xref: /illumos-gate/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision 6a074c93c5dee390d8ca2377f42e55418f0a9eb3)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  *	Copyright 1983,1984,1985,1986,1987,1988,1989 AT&T.
28  *	All Rights Reserved
29  */
30 
31 #pragma ident	"%Z%%M%	%I%	%E% SMI"
32 
33 #include <sys/param.h>
34 #include <sys/types.h>
35 #include <sys/systm.h>
36 #include <sys/cred.h>
37 #include <sys/time.h>
38 #include <sys/vnode.h>
39 #include <sys/vfs.h>
40 #include <sys/vfs_opreg.h>
41 #include <sys/file.h>
42 #include <sys/filio.h>
43 #include <sys/uio.h>
44 #include <sys/buf.h>
45 #include <sys/mman.h>
46 #include <sys/pathname.h>
47 #include <sys/dirent.h>
48 #include <sys/debug.h>
49 #include <sys/vmsystm.h>
50 #include <sys/fcntl.h>
51 #include <sys/flock.h>
52 #include <sys/swap.h>
53 #include <sys/errno.h>
54 #include <sys/strsubr.h>
55 #include <sys/sysmacros.h>
56 #include <sys/kmem.h>
57 #include <sys/cmn_err.h>
58 #include <sys/pathconf.h>
59 #include <sys/utsname.h>
60 #include <sys/dnlc.h>
61 #include <sys/acl.h>
62 #include <sys/systeminfo.h>
63 #include <sys/policy.h>
64 #include <sys/sdt.h>
65 #include <sys/list.h>
66 #include <sys/stat.h>
67 
68 #include <rpc/types.h>
69 #include <rpc/auth.h>
70 #include <rpc/clnt.h>
71 
72 #include <nfs/nfs.h>
73 #include <nfs/nfs_clnt.h>
74 #include <nfs/nfs_acl.h>
75 #include <nfs/lm.h>
76 #include <nfs/nfs4.h>
77 #include <nfs/nfs4_kprot.h>
78 #include <nfs/rnode4.h>
79 #include <nfs/nfs4_clnt.h>
80 
81 #include <vm/hat.h>
82 #include <vm/as.h>
83 #include <vm/page.h>
84 #include <vm/pvn.h>
85 #include <vm/seg.h>
86 #include <vm/seg_map.h>
87 #include <vm/seg_kpm.h>
88 #include <vm/seg_vn.h>
89 
90 #include <fs/fs_subr.h>
91 
92 #include <sys/ddi.h>
93 #include <sys/int_fmtio.h>
94 
95 typedef struct {
96 	nfs4_ga_res_t	*di_garp;
97 	cred_t		*di_cred;
98 	hrtime_t	di_time_call;
99 } dirattr_info_t;
100 
101 typedef enum nfs4_acl_op {
102 	NFS4_ACL_GET,
103 	NFS4_ACL_SET
104 } nfs4_acl_op_t;
105 
106 static void	nfs4_update_dircaches(change_info4 *, vnode_t *, vnode_t *,
107 			char *, dirattr_info_t *);
108 
109 static void	nfs4close_otw(rnode4_t *, cred_t *, nfs4_open_owner_t *,
110 		    nfs4_open_stream_t *, int *, int *, nfs4_close_type_t,
111 		    nfs4_error_t *, int *);
112 static int	nfs4_rdwrlbn(vnode_t *, page_t *, u_offset_t, size_t, int,
113 			cred_t *);
114 static int	nfs4write(vnode_t *, caddr_t, u_offset_t, int, cred_t *,
115 			stable_how4 *);
116 static int	nfs4read(vnode_t *, caddr_t, offset_t, int, size_t *,
117 			cred_t *, bool_t, struct uio *);
118 static int	nfs4setattr(vnode_t *, struct vattr *, int, cred_t *,
119 			vsecattr_t *);
120 static int	nfs4openattr(vnode_t *, vnode_t **, int, cred_t *);
121 static int	nfs4lookup(vnode_t *, char *, vnode_t **, cred_t *, int);
122 static int	nfs4lookup_xattr(vnode_t *, char *, vnode_t **, int, cred_t *);
123 static int	nfs4lookupvalidate_otw(vnode_t *, char *, vnode_t **, cred_t *);
124 static int	nfs4lookupnew_otw(vnode_t *, char *, vnode_t **, cred_t *);
125 static int	nfs4mknod(vnode_t *, char *, struct vattr *, enum vcexcl,
126 			int, vnode_t **, cred_t *);
127 static int	nfs4open_otw(vnode_t *, char *, struct vattr *, vnode_t **,
128 			cred_t *, int, int, enum createmode4, int);
129 static int	nfs4rename(vnode_t *, char *, vnode_t *, char *, cred_t *);
130 static int	nfs4rename_persistent_fh(vnode_t *, char *, vnode_t *,
131 			vnode_t *, char *, cred_t *, nfsstat4 *);
132 static int	nfs4rename_volatile_fh(vnode_t *, char *, vnode_t *,
133 			vnode_t *, char *, cred_t *, nfsstat4 *);
134 static int	do_nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
135 static void	nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
136 static int	nfs4_bio(struct buf *, stable_how4 *, cred_t *, bool_t);
137 static int	nfs4_getapage(vnode_t *, u_offset_t, size_t, uint_t *,
138 			page_t *[], size_t, struct seg *, caddr_t,
139 			enum seg_rw, cred_t *);
140 static void	nfs4_readahead(vnode_t *, u_offset_t, caddr_t, struct seg *,
141 			cred_t *);
142 static int	nfs4_sync_putapage(vnode_t *, page_t *, u_offset_t, size_t,
143 			int, cred_t *);
144 static int	nfs4_sync_pageio(vnode_t *, page_t *, u_offset_t, size_t,
145 			int, cred_t *);
146 static int	nfs4_commit(vnode_t *, offset4, count4, cred_t *);
147 static void	nfs4_set_mod(vnode_t *);
148 static void	nfs4_get_commit(vnode_t *);
149 static void	nfs4_get_commit_range(vnode_t *, u_offset_t, size_t);
150 static int	nfs4_putpage_commit(vnode_t *, offset_t, size_t, cred_t *);
151 static int	nfs4_commit_vp(vnode_t *, u_offset_t, size_t, cred_t *, int);
152 static int	nfs4_sync_commit(vnode_t *, page_t *, offset3, count3,
153 			cred_t *);
154 static void	do_nfs4_async_commit(vnode_t *, page_t *, offset3, count3,
155 			cred_t *);
156 static int	nfs4_update_attrcache(nfsstat4, nfs4_ga_res_t *,
157 			hrtime_t, vnode_t *, cred_t *);
158 static int	nfs4_open_non_reg_file(vnode_t **, int, cred_t *);
159 static int	nfs4_safelock(vnode_t *, const struct flock64 *, cred_t *);
160 static void	nfs4_register_lock_locally(vnode_t *, struct flock64 *, int,
161 			u_offset_t);
162 static int 	nfs4_lockrelease(vnode_t *, int, offset_t, cred_t *);
163 static int	nfs4_block_and_wait(clock_t *, rnode4_t *);
164 static cred_t  *state_to_cred(nfs4_open_stream_t *);
165 static int	vtoname(vnode_t *, char *, ssize_t);
166 static void	denied_to_flk(LOCK4denied *, flock64_t *, LOCKT4args *);
167 static pid_t	lo_to_pid(lock_owner4 *);
168 static void	nfs4_reinstitute_local_lock_state(vnode_t *, flock64_t *,
169 			cred_t *, nfs4_lock_owner_t *);
170 static void	push_reinstate(vnode_t *, int, flock64_t *, cred_t *,
171 			nfs4_lock_owner_t *);
172 static int 	open_and_get_osp(vnode_t *, cred_t *, nfs4_open_stream_t **);
173 static void	nfs4_delmap_callback(struct as *, void *, uint_t);
174 static void	nfs4_free_delmapcall(nfs4_delmapcall_t *);
175 static nfs4_delmapcall_t	*nfs4_init_delmapcall();
176 static int	nfs4_find_and_delete_delmapcall(rnode4_t *, int *);
177 static int	nfs4_is_acl_mask_valid(uint_t, nfs4_acl_op_t);
178 static int	nfs4_create_getsecattr_return(vsecattr_t *, vsecattr_t *,
179 			uid_t, gid_t, int);
180 
181 /*
182  * Routines that implement the setting of v4 args for the misc. ops
183  */
184 static void	nfs4args_lock_free(nfs_argop4 *);
185 static void	nfs4args_lockt_free(nfs_argop4 *);
186 static void	nfs4args_setattr(nfs_argop4 *, vattr_t *, vsecattr_t *,
187 			int, rnode4_t *, cred_t *, bitmap4, int *,
188 			nfs4_stateid_types_t *);
189 static void	nfs4args_setattr_free(nfs_argop4 *);
190 static int	nfs4args_verify(nfs_argop4 *, vattr_t *, enum nfs_opnum4,
191 			bitmap4);
192 static void	nfs4args_verify_free(nfs_argop4 *);
193 static void	nfs4args_write(nfs_argop4 *, stable_how4, rnode4_t *, cred_t *,
194 			WRITE4args **, nfs4_stateid_types_t *);
195 
196 /*
197  * These are the vnode ops functions that implement the vnode interface to
198  * the networked file system.  See more comments below at nfs4_vnodeops.
199  */
200 static int	nfs4_open(vnode_t **, int, cred_t *);
201 static int	nfs4_close(vnode_t *, int, int, offset_t, cred_t *);
202 static int	nfs4_read(vnode_t *, struct uio *, int, cred_t *,
203 			caller_context_t *);
204 static int	nfs4_write(vnode_t *, struct uio *, int, cred_t *,
205 			caller_context_t *);
206 static int	nfs4_ioctl(vnode_t *, int, intptr_t, int, cred_t *, int *);
207 static int	nfs4_getattr(vnode_t *, struct vattr *, int, cred_t *);
208 static int	nfs4_setattr(vnode_t *, struct vattr *, int, cred_t *,
209 			caller_context_t *);
210 static int	nfs4_access(vnode_t *, int, int, cred_t *);
211 static int	nfs4_readlink(vnode_t *, struct uio *, cred_t *);
212 static int	nfs4_fsync(vnode_t *, int, cred_t *);
213 static void	nfs4_inactive(vnode_t *, cred_t *);
214 static int	nfs4_lookup(vnode_t *, char *, vnode_t **,
215 			struct pathname *, int, vnode_t *, cred_t *);
216 static int	nfs4_create(vnode_t *, char *, struct vattr *, enum vcexcl,
217 			int, vnode_t **, cred_t *, int);
218 static int	nfs4_remove(vnode_t *, char *, cred_t *);
219 static int	nfs4_link(vnode_t *, vnode_t *, char *, cred_t *);
220 static int	nfs4_rename(vnode_t *, char *, vnode_t *, char *, cred_t *);
221 static int	nfs4_mkdir(vnode_t *, char *, struct vattr *,
222 			vnode_t **, cred_t *);
223 static int	nfs4_rmdir(vnode_t *, char *, vnode_t *, cred_t *);
224 static int	nfs4_symlink(vnode_t *, char *, struct vattr *, char *,
225 			cred_t *);
226 static int	nfs4_readdir(vnode_t *, struct uio *, cred_t *, int *);
227 static int	nfs4_fid(vnode_t *, fid_t *);
228 static int	nfs4_rwlock(vnode_t *, int, caller_context_t *);
229 static void	nfs4_rwunlock(vnode_t *, int, caller_context_t *);
230 static int	nfs4_seek(vnode_t *, offset_t, offset_t *);
231 static int	nfs4_getpage(vnode_t *, offset_t, size_t, uint_t *,
232 			page_t *[], size_t, struct seg *, caddr_t,
233 			enum seg_rw, cred_t *);
234 static int	nfs4_putpage(vnode_t *, offset_t, size_t, int, cred_t *);
235 static int	nfs4_map(vnode_t *, offset_t, struct as *, caddr_t *,
236 			size_t, uchar_t, uchar_t, uint_t, cred_t *);
237 static int	nfs4_addmap(vnode_t *, offset_t, struct as *, caddr_t,
238 			size_t, uchar_t, uchar_t, uint_t, cred_t *);
239 static int	nfs4_cmp(vnode_t *, vnode_t *);
240 static int	nfs4_frlock(vnode_t *, int, struct flock64 *, int, offset_t,
241 			struct flk_callback *, cred_t *);
242 static int	nfs4_space(vnode_t *, int, struct flock64 *, int, offset_t,
243 			cred_t *, caller_context_t *);
244 static int	nfs4_realvp(vnode_t *, vnode_t **);
245 static int	nfs4_delmap(vnode_t *, offset_t, struct as *, caddr_t,
246 			size_t, uint_t, uint_t, uint_t, cred_t *);
247 static int	nfs4_pathconf(vnode_t *, int, ulong_t *, cred_t *);
248 static int	nfs4_pageio(vnode_t *, page_t *, u_offset_t, size_t, int,
249 			cred_t *);
250 static void	nfs4_dispose(vnode_t *, page_t *, int, int, cred_t *);
251 static int	nfs4_setsecattr(vnode_t *, vsecattr_t *, int, cred_t *);
252 static int	nfs4_getsecattr(vnode_t *, vsecattr_t *, int, cred_t *);
253 static int	nfs4_shrlock(vnode_t *, int, struct shrlock *, int, cred_t *);
254 
255 /*
256  * Used for nfs4_commit_vp() to indicate if we should
257  * wait on pending writes.
258  */
259 #define	NFS4_WRITE_NOWAIT	0
260 #define	NFS4_WRITE_WAIT		1
261 
262 #define	NFS4_BASE_WAIT_TIME 1	/* 1 second */
263 
264 /*
265  * Error flags used to pass information about certain special errors
266  * which need to be handled specially.
267  */
268 #define	NFS_EOF			-98
269 #define	NFS_VERF_MISMATCH	-97
270 
271 /*
272  * Flags used to differentiate between which operation drove the
273  * potential CLOSE OTW. (see nfs4_close_otw_if_necessary)
274  */
275 #define	NFS4_CLOSE_OP		0x1
276 #define	NFS4_DELMAP_OP		0x2
277 #define	NFS4_INACTIVE_OP	0x3
278 
279 #define	ISVDEV(t) ((t == VBLK) || (t == VCHR) || (t == VFIFO))
280 
281 /* ALIGN64 aligns the given buffer and adjust buffer size to 64 bit */
282 #define	ALIGN64(x, ptr, sz)						\
283 	x = ((uintptr_t)(ptr)) & (sizeof (uint64_t) - 1);		\
284 	if (x) {							\
285 		x = sizeof (uint64_t) - (x);				\
286 		sz -= (x);						\
287 		ptr += (x);						\
288 	}
289 
290 #ifdef DEBUG
291 int nfs4_client_attr_debug = 0;
292 int nfs4_client_state_debug = 0;
293 int nfs4_client_shadow_debug = 0;
294 int nfs4_client_lock_debug = 0;
295 int nfs4_seqid_sync = 0;
296 int nfs4_client_map_debug = 0;
297 static int nfs4_pageio_debug = 0;
298 int nfs4_client_inactive_debug = 0;
299 int nfs4_client_recov_debug = 0;
300 int nfs4_client_recov_stub_debug = 0;
301 int nfs4_client_failover_debug = 0;
302 int nfs4_client_call_debug = 0;
303 int nfs4_client_lookup_debug = 0;
304 int nfs4_client_zone_debug = 0;
305 int nfs4_lost_rqst_debug = 0;
306 int nfs4_rdattrerr_debug = 0;
307 int nfs4_open_stream_debug = 0;
308 
309 int nfs4read_error_inject;
310 
311 static int nfs4_create_misses = 0;
312 
313 static int nfs4_readdir_cache_shorts = 0;
314 static int nfs4_readdir_readahead = 0;
315 
316 static int nfs4_bio_do_stop = 0;
317 
318 static int nfs4_lostpage = 0;	/* number of times we lost original page */
319 
320 int nfs4_mmap_debug = 0;
321 
322 static int nfs4_pathconf_cache_hits = 0;
323 static int nfs4_pathconf_cache_misses = 0;
324 
325 int nfs4close_all_cnt;
326 int nfs4close_one_debug = 0;
327 int nfs4close_notw_debug = 0;
328 
329 int denied_to_flk_debug = 0;
330 void *lockt_denied_debug;
331 
332 #endif
333 
334 /*
335  * How long to wait before trying again if OPEN_CONFIRM gets ETIMEDOUT
336  * or NFS4ERR_RESOURCE.
337  */
338 static int confirm_retry_sec = 30;
339 
340 static int nfs4_lookup_neg_cache = 1;
341 
342 /*
343  * number of pages to read ahead
344  * optimized for 100 base-T.
345  */
346 static int nfs4_nra = 4;
347 
348 static int nfs4_do_symlink_cache = 1;
349 
350 static int nfs4_pathconf_disable_cache = 0;
351 
352 /*
353  * These are the vnode ops routines which implement the vnode interface to
354  * the networked file system.  These routines just take their parameters,
355  * make them look networkish by putting the right info into interface structs,
356  * and then calling the appropriate remote routine(s) to do the work.
357  *
358  * Note on directory name lookup cacheing:  If we detect a stale fhandle,
359  * we purge the directory cache relative to that vnode.  This way, the
360  * user won't get burned by the cache repeatedly.  See <nfs/rnode4.h> for
361  * more details on rnode locking.
362  */
363 
364 struct vnodeops *nfs4_vnodeops;
365 
366 const fs_operation_def_t nfs4_vnodeops_template[] = {
367 	VOPNAME_OPEN,		{ .vop_open = nfs4_open },
368 	VOPNAME_CLOSE,		{ .vop_close = nfs4_close },
369 	VOPNAME_READ,		{ .vop_read = nfs4_read },
370 	VOPNAME_WRITE,		{ .vop_write = nfs4_write },
371 	VOPNAME_IOCTL,		{ .vop_ioctl = nfs4_ioctl },
372 	VOPNAME_GETATTR,	{ .vop_getattr = nfs4_getattr },
373 	VOPNAME_SETATTR,	{ .vop_setattr = nfs4_setattr },
374 	VOPNAME_ACCESS,		{ .vop_access = nfs4_access },
375 	VOPNAME_LOOKUP,		{ .vop_lookup = nfs4_lookup },
376 	VOPNAME_CREATE,		{ .vop_create = nfs4_create },
377 	VOPNAME_REMOVE,		{ .vop_remove = nfs4_remove },
378 	VOPNAME_LINK,		{ .vop_link = nfs4_link },
379 	VOPNAME_RENAME,		{ .vop_rename = nfs4_rename },
380 	VOPNAME_MKDIR,		{ .vop_mkdir = nfs4_mkdir },
381 	VOPNAME_RMDIR,		{ .vop_rmdir = nfs4_rmdir },
382 	VOPNAME_READDIR,	{ .vop_readdir = nfs4_readdir },
383 	VOPNAME_SYMLINK,	{ .vop_symlink = nfs4_symlink },
384 	VOPNAME_READLINK,	{ .vop_readlink = nfs4_readlink },
385 	VOPNAME_FSYNC,		{ .vop_fsync = nfs4_fsync },
386 	VOPNAME_INACTIVE,	{ .vop_inactive = nfs4_inactive },
387 	VOPNAME_FID,		{ .vop_fid = nfs4_fid },
388 	VOPNAME_RWLOCK,		{ .vop_rwlock = nfs4_rwlock },
389 	VOPNAME_RWUNLOCK,	{ .vop_rwunlock = nfs4_rwunlock },
390 	VOPNAME_SEEK,		{ .vop_seek = nfs4_seek },
391 	VOPNAME_FRLOCK,		{ .vop_frlock = nfs4_frlock },
392 	VOPNAME_SPACE,		{ .vop_space = nfs4_space },
393 	VOPNAME_REALVP,		{ .vop_realvp = nfs4_realvp },
394 	VOPNAME_GETPAGE,	{ .vop_getpage = nfs4_getpage },
395 	VOPNAME_PUTPAGE,	{ .vop_putpage = nfs4_putpage },
396 	VOPNAME_MAP,		{ .vop_map = nfs4_map },
397 	VOPNAME_ADDMAP,		{ .vop_addmap = nfs4_addmap },
398 	VOPNAME_DELMAP,		{ .vop_delmap = nfs4_delmap },
399 	/* no separate nfs4_dump */
400 	VOPNAME_DUMP,		{ .vop_dump = nfs_dump },
401 	VOPNAME_PATHCONF,	{ .vop_pathconf = nfs4_pathconf },
402 	VOPNAME_PAGEIO,		{ .vop_pageio = nfs4_pageio },
403 	VOPNAME_DISPOSE,	{ .vop_dispose = nfs4_dispose },
404 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = nfs4_setsecattr },
405 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = nfs4_getsecattr },
406 	VOPNAME_SHRLOCK,	{ .vop_shrlock = nfs4_shrlock },
407 	VOPNAME_VNEVENT, 	{ .vop_vnevent = fs_vnevent_support },
408 	NULL,			NULL
409 };
410 
411 /*
412  * The following are subroutines and definitions to set args or get res
413  * for the different nfsv4 ops
414  */
415 
416 void
417 nfs4args_lookup_free(nfs_argop4 *argop, int arglen)
418 {
419 	int i;
420 
421 	for (i = 0; i < arglen; i++) {
422 	    if (argop[i].argop == OP_LOOKUP)
423 		kmem_free(
424 			argop[i].nfs_argop4_u.oplookup.objname.utf8string_val,
425 			argop[i].nfs_argop4_u.oplookup.objname.utf8string_len);
426 	}
427 }
428 
429 static void
430 nfs4args_lock_free(nfs_argop4 *argop)
431 {
432 	locker4 *locker = &argop->nfs_argop4_u.oplock.locker;
433 
434 	if (locker->new_lock_owner == TRUE) {
435 		open_to_lock_owner4 *open_owner;
436 
437 		open_owner = &locker->locker4_u.open_owner;
438 		if (open_owner->lock_owner.owner_val != NULL) {
439 			kmem_free(open_owner->lock_owner.owner_val,
440 				open_owner->lock_owner.owner_len);
441 		}
442 	}
443 }
444 
445 static void
446 nfs4args_lockt_free(nfs_argop4 *argop)
447 {
448 	lock_owner4 *lowner = &argop->nfs_argop4_u.oplockt.owner;
449 
450 	if (lowner->owner_val != NULL) {
451 		kmem_free(lowner->owner_val, lowner->owner_len);
452 	}
453 }
454 
455 static void
456 nfs4args_setattr(nfs_argop4 *argop, vattr_t *vap, vsecattr_t *vsap, int flags,
457 		rnode4_t *rp, cred_t *cr, bitmap4 supp, int *error,
458 		nfs4_stateid_types_t *sid_types)
459 {
460 	fattr4		*attr = &argop->nfs_argop4_u.opsetattr.obj_attributes;
461 	mntinfo4_t	*mi;
462 
463 	argop->argop = OP_SETATTR;
464 	/*
465 	 * The stateid is set to 0 if client is not modifying the size
466 	 * and otherwise to whatever nfs4_get_stateid() returns.
467 	 *
468 	 * XXX Note: nfs4_get_stateid() returns 0 if no lockowner and/or no
469 	 * state struct could be found for the process/file pair.  We may
470 	 * want to change this in the future (by OPENing the file).  See
471 	 * bug # 4474852.
472 	 */
473 	if (vap->va_mask & AT_SIZE) {
474 
475 		ASSERT(rp != NULL);
476 		mi = VTOMI4(RTOV4(rp));
477 
478 		argop->nfs_argop4_u.opsetattr.stateid =
479 			nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
480 				OP_SETATTR, sid_types, FALSE);
481 	} else {
482 		bzero(&argop->nfs_argop4_u.opsetattr.stateid,
483 		    sizeof (stateid4));
484 	}
485 
486 	*error = vattr_to_fattr4(vap, vsap, attr, flags, OP_SETATTR, supp);
487 	if (*error)
488 		bzero(attr, sizeof (*attr));
489 }
490 
491 static void
492 nfs4args_setattr_free(nfs_argop4 *argop)
493 {
494 	nfs4_fattr4_free(&argop->nfs_argop4_u.opsetattr.obj_attributes);
495 }
496 
497 static int
498 nfs4args_verify(nfs_argop4 *argop, vattr_t *vap, enum nfs_opnum4 op,
499 		bitmap4 supp)
500 {
501 	fattr4 *attr;
502 	int error = 0;
503 
504 	argop->argop = op;
505 	switch (op) {
506 	case OP_VERIFY:
507 		attr = &argop->nfs_argop4_u.opverify.obj_attributes;
508 		break;
509 	case OP_NVERIFY:
510 		attr = &argop->nfs_argop4_u.opnverify.obj_attributes;
511 		break;
512 	default:
513 		return (EINVAL);
514 	}
515 	if (!error)
516 		error = vattr_to_fattr4(vap, NULL, attr, 0, op, supp);
517 	if (error)
518 		bzero(attr, sizeof (*attr));
519 	return (error);
520 }
521 
522 static void
523 nfs4args_verify_free(nfs_argop4 *argop)
524 {
525 	switch (argop->argop) {
526 	case OP_VERIFY:
527 		nfs4_fattr4_free(&argop->nfs_argop4_u.opverify.obj_attributes);
528 		break;
529 	case OP_NVERIFY:
530 		nfs4_fattr4_free(&argop->nfs_argop4_u.opnverify.obj_attributes);
531 		break;
532 	default:
533 		break;
534 	}
535 }
536 
537 static void
538 nfs4args_write(nfs_argop4 *argop, stable_how4 stable, rnode4_t *rp, cred_t *cr,
539 	WRITE4args **wargs_pp, nfs4_stateid_types_t *sid_tp)
540 {
541 	WRITE4args *wargs = &argop->nfs_argop4_u.opwrite;
542 	mntinfo4_t *mi = VTOMI4(RTOV4(rp));
543 
544 	argop->argop = OP_WRITE;
545 	wargs->stable = stable;
546 	wargs->stateid = nfs4_get_w_stateid(cr, rp, curproc->p_pidp->pid_id,
547 				mi, OP_WRITE, sid_tp);
548 	wargs->mblk = NULL;
549 	*wargs_pp = wargs;
550 }
551 
552 void
553 nfs4args_copen_free(OPEN4cargs *open_args)
554 {
555 	if (open_args->owner.owner_val) {
556 		kmem_free(open_args->owner.owner_val,
557 					open_args->owner.owner_len);
558 	}
559 	if ((open_args->opentype == OPEN4_CREATE) &&
560 	    (open_args->mode != EXCLUSIVE4)) {
561 		nfs4_fattr4_free(&open_args->createhow4_u.createattrs);
562 	}
563 }
564 
565 /*
566  * XXX:  This is referenced in modstubs.s
567  */
568 struct vnodeops *
569 nfs4_getvnodeops(void)
570 {
571 	return (nfs4_vnodeops);
572 }
573 
574 /*
575  * The OPEN operation opens a regular file.
576  *
577  * ARGSUSED
578  */
579 static int
580 nfs4_open(vnode_t **vpp, int flag, cred_t *cr)
581 {
582 	vnode_t *dvp = NULL;
583 	rnode4_t *rp, *drp;
584 	int error;
585 	int just_been_created;
586 	char fn[MAXNAMELEN];
587 
588 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4_open: "));
589 	if (nfs_zone() != VTOMI4(*vpp)->mi_zone)
590 		return (EIO);
591 	rp = VTOR4(*vpp);
592 
593 	/*
594 	 * Check to see if opening something besides a regular file;
595 	 * if so skip the OTW call
596 	 */
597 	if ((*vpp)->v_type != VREG) {
598 		error = nfs4_open_non_reg_file(vpp, flag, cr);
599 		return (error);
600 	}
601 
602 	/*
603 	 * XXX - would like a check right here to know if the file is
604 	 * executable or not, so as to skip OTW
605 	 */
606 
607 	if ((error = vtodv(*vpp, &dvp, cr, TRUE)) != 0)
608 		return (error);
609 
610 	drp = VTOR4(dvp);
611 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
612 		return (EINTR);
613 
614 	if ((error = vtoname(*vpp, fn, MAXNAMELEN)) != 0) {
615 		nfs_rw_exit(&drp->r_rwlock);
616 		return (error);
617 	}
618 
619 	/*
620 	 * See if this file has just been CREATEd.
621 	 * If so, clear the flag and update the dnlc, which was previously
622 	 * skipped in nfs4_create.
623 	 * XXX need better serilization on this.
624 	 * XXX move this into the nf4open_otw call, after we have
625 	 * XXX acquired the open owner seqid sync.
626 	 */
627 	mutex_enter(&rp->r_statev4_lock);
628 	if (rp->created_v4) {
629 		rp->created_v4 = 0;
630 		mutex_exit(&rp->r_statev4_lock);
631 
632 		dnlc_update(dvp, fn, *vpp);
633 		/* This is needed so we don't bump the open ref count */
634 		just_been_created = 1;
635 	} else {
636 		mutex_exit(&rp->r_statev4_lock);
637 		just_been_created = 0;
638 	}
639 
640 	/*
641 	 * If caller specified O_TRUNC/FTRUNC, then be sure to set
642 	 * FWRITE (to drive successful setattr(size=0) after open)
643 	 */
644 	if (flag & FTRUNC)
645 		flag |= FWRITE;
646 
647 	error = nfs4open_otw(dvp, fn, NULL, vpp, cr, 0, flag, 0,
648 			just_been_created);
649 
650 	if (!error && !((*vpp)->v_flag & VROOT))
651 		dnlc_update(dvp, fn, *vpp);
652 
653 	nfs_rw_exit(&drp->r_rwlock);
654 
655 	/* release the hold from vtodv */
656 	VN_RELE(dvp);
657 
658 	/* exchange the shadow for the master vnode, if needed */
659 
660 	if (error == 0 && IS_SHADOW(*vpp, rp))
661 		sv_exchange(vpp);
662 
663 	return (error);
664 }
665 
666 /*
667  * See if there's a "lost open" request to be saved and recovered.
668  */
669 static void
670 nfs4open_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
671 	nfs4_open_owner_t *oop, cred_t *cr, vnode_t *vp,
672 	vnode_t *dvp, OPEN4cargs *open_args)
673 {
674 	vfs_t *vfsp;
675 	char *srccfp;
676 
677 	vfsp = (dvp ? dvp->v_vfsp : vp->v_vfsp);
678 
679 	if (error != ETIMEDOUT && error != EINTR &&
680 			!NFS4_FRC_UNMT_ERR(error, vfsp)) {
681 		lost_rqstp->lr_op = 0;
682 		return;
683 	}
684 
685 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
686 		    "nfs4open_save_lost_rqst: error %d", error));
687 
688 	lost_rqstp->lr_op = OP_OPEN;
689 	/*
690 	 * The vp (if it is not NULL) and dvp are held and rele'd via
691 	 * the recovery code.  See nfs4_save_lost_rqst.
692 	 */
693 	lost_rqstp->lr_vp = vp;
694 	lost_rqstp->lr_dvp = dvp;
695 	lost_rqstp->lr_oop = oop;
696 	lost_rqstp->lr_osp = NULL;
697 	lost_rqstp->lr_lop = NULL;
698 	lost_rqstp->lr_cr = cr;
699 	lost_rqstp->lr_flk = NULL;
700 	lost_rqstp->lr_oacc = open_args->share_access;
701 	lost_rqstp->lr_odeny = open_args->share_deny;
702 	lost_rqstp->lr_oclaim = open_args->claim;
703 	if (open_args->claim == CLAIM_DELEGATE_CUR) {
704 		lost_rqstp->lr_ostateid =
705 		    open_args->open_claim4_u.delegate_cur_info.delegate_stateid;
706 		srccfp = open_args->open_claim4_u.delegate_cur_info.cfile;
707 	} else {
708 		srccfp = open_args->open_claim4_u.cfile;
709 	}
710 	lost_rqstp->lr_ofile.utf8string_len = 0;
711 	lost_rqstp->lr_ofile.utf8string_val = NULL;
712 	(void) str_to_utf8(srccfp, &lost_rqstp->lr_ofile);
713 	lost_rqstp->lr_putfirst = FALSE;
714 }
715 
716 struct nfs4_excl_time {
717 	uint32 seconds;
718 	uint32 nseconds;
719 };
720 
721 /*
722  * The OPEN operation creates and/or opens a regular file
723  *
724  * ARGSUSED
725  */
726 static int
727 nfs4open_otw(vnode_t *dvp, char *file_name, struct vattr *in_va,
728 	vnode_t **vpp, cred_t *cr, int create_flag, int open_flag,
729 	enum createmode4 createmode, int file_just_been_created)
730 {
731 	rnode4_t *rp;
732 	rnode4_t *drp = VTOR4(dvp);
733 	vnode_t *vp = NULL;
734 	vnode_t *vpi = *vpp;
735 	bool_t needrecov = FALSE;
736 
737 	int doqueue = 1;
738 
739 	COMPOUND4args_clnt args;
740 	COMPOUND4res_clnt res;
741 	nfs_argop4 *argop;
742 	nfs_resop4 *resop;
743 	int argoplist_size;
744 	int idx_open, idx_fattr;
745 
746 	GETFH4res *gf_res = NULL;
747 	OPEN4res *op_res = NULL;
748 	nfs4_ga_res_t *garp;
749 	fattr4 *attr = NULL;
750 	struct nfs4_excl_time verf;
751 	bool_t did_excl_setup = FALSE;
752 	int created_osp;
753 
754 	OPEN4cargs *open_args;
755 	nfs4_open_owner_t	*oop = NULL;
756 	nfs4_open_stream_t	*osp = NULL;
757 	seqid4 seqid = 0;
758 	bool_t retry_open = FALSE;
759 	nfs4_recov_state_t recov_state;
760 	nfs4_lost_rqst_t lost_rqst;
761 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
762 	hrtime_t t;
763 	int acc = 0;
764 	cred_t *cred_otw = NULL;	/* cred used to do the RPC call */
765 	cred_t *ncr = NULL;
766 
767 	nfs4_sharedfh_t *otw_sfh;
768 	nfs4_sharedfh_t *orig_sfh;
769 	int fh_differs = 0;
770 	int numops, setgid_flag;
771 	int num_bseqid_retry = NFS4_NUM_RETRY_BAD_SEQID + 1;
772 
773 	/*
774 	 * Make sure we properly deal with setting the right gid on
775 	 * a newly created file to reflect the parent's setgid bit
776 	 */
777 	setgid_flag = 0;
778 	if (create_flag && in_va) {
779 
780 		/*
781 		 * If the parent's directory has the setgid bit set
782 		 * _and_ the client was able to get a valid mapping
783 		 * for the parent dir's owner_group, we want to
784 		 * append NVERIFY(owner_group == dva.va_gid) and
785 		 * SETATTR to the CREATE compound.
786 		 */
787 		mutex_enter(&drp->r_statelock);
788 		if (drp->r_attr.va_mode & VSGID &&
789 		    drp->r_attr.va_gid != GID_NOBODY) {
790 			in_va->va_gid = drp->r_attr.va_gid;
791 			setgid_flag = 1;
792 		}
793 		mutex_exit(&drp->r_statelock);
794 	}
795 
796 	/*
797 	 * Normal/non-create compound:
798 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new)
799 	 *
800 	 * Open(create) compound no setgid:
801 	 * PUTFH(dfh) + SAVEFH + OPEN(create) + GETFH + GETATTR(new) +
802 	 * RESTOREFH + GETATTR
803 	 *
804 	 * Open(create) setgid:
805 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new) +
806 	 * SAVEFH + PUTFH(dfh) + GETATTR(dvp) + RESTOREFH +
807 	 * NVERIFY(grp) + SETATTR
808 	 */
809 	if (setgid_flag) {
810 		numops = 10;
811 		idx_open = 1;
812 		idx_fattr = 3;
813 	} else if (create_flag) {
814 		numops = 7;
815 		idx_open = 2;
816 		idx_fattr = 4;
817 	} else {
818 		numops = 4;
819 		idx_open = 1;
820 		idx_fattr = 3;
821 	}
822 
823 	args.array_len = numops;
824 	argoplist_size = numops * sizeof (nfs_argop4);
825 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
826 
827 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw: "
828 		"open %s open flag 0x%x cred %p", file_name, open_flag,
829 		(void *)cr));
830 
831 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
832 	if (create_flag) {
833 		/*
834 		 * We are to create a file.  Initialize the passed in vnode
835 		 * pointer.
836 		 */
837 		vpi = NULL;
838 	} else {
839 		/*
840 		 * Check to see if the client owns a read delegation and is
841 		 * trying to open for write.  If so, then return the delegation
842 		 * to avoid the server doing a cb_recall and returning DELAY.
843 		 * NB - we don't use the statev4_lock here because we'd have
844 		 * to drop the lock anyway and the result would be stale.
845 		 */
846 		if ((open_flag & FWRITE) &&
847 		    VTOR4(vpi)->r_deleg_type == OPEN_DELEGATE_READ)
848 			(void) nfs4delegreturn(VTOR4(vpi), NFS4_DR_REOPEN);
849 
850 		/*
851 		 * If the file has a delegation, then do an access check up
852 		 * front.  This avoids having to an access check later after
853 		 * we've already done start_op, which could deadlock.
854 		 */
855 		if (VTOR4(vpi)->r_deleg_type != OPEN_DELEGATE_NONE) {
856 			if (open_flag & FREAD &&
857 			    nfs4_access(vpi, VREAD, 0, cr) == 0)
858 				acc |= VREAD;
859 			if (open_flag & FWRITE &&
860 			    nfs4_access(vpi, VWRITE, 0, cr) == 0)
861 				acc |= VWRITE;
862 		}
863 	}
864 
865 	drp = VTOR4(dvp);
866 
867 	recov_state.rs_flags = 0;
868 	recov_state.rs_num_retry_despite_err = 0;
869 	cred_otw = cr;
870 
871 recov_retry:
872 	fh_differs = 0;
873 	nfs4_error_zinit(&e);
874 
875 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, vpi, &recov_state);
876 	if (e.error) {
877 		if (ncr != NULL)
878 			crfree(ncr);
879 		kmem_free(argop, argoplist_size);
880 		return (e.error);
881 	}
882 
883 	args.ctag = TAG_OPEN;
884 	args.array_len = numops;
885 	args.array = argop;
886 
887 	/* putfh directory fh */
888 	argop[0].argop = OP_CPUTFH;
889 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
890 
891 	/* OPEN: either op 1 or op 2 depending upon create/setgid flags */
892 	argop[idx_open].argop = OP_COPEN;
893 	open_args = &argop[idx_open].nfs_argop4_u.opcopen;
894 	open_args->claim = CLAIM_NULL;
895 
896 	/* name of file */
897 	open_args->open_claim4_u.cfile = file_name;
898 	open_args->owner.owner_len = 0;
899 	open_args->owner.owner_val = NULL;
900 
901 	if (create_flag) {
902 		/* CREATE a file */
903 		open_args->opentype = OPEN4_CREATE;
904 		open_args->mode = createmode;
905 		if (createmode == EXCLUSIVE4) {
906 			if (did_excl_setup == FALSE) {
907 				verf.seconds = nfs_atoi(hw_serial);
908 				if (verf.seconds != 0)
909 					verf.nseconds = newnum();
910 				else {
911 					timestruc_t now;
912 
913 					gethrestime(&now);
914 					verf.seconds = now.tv_sec;
915 					verf.nseconds = now.tv_nsec;
916 				}
917 				/*
918 				 * Since the server will use this value for the
919 				 * mtime, make sure that it can't overflow. Zero
920 				 * out the MSB. The actual value does not matter
921 				 * here, only its uniqeness.
922 				 */
923 				verf.seconds &= INT32_MAX;
924 				did_excl_setup = TRUE;
925 			}
926 
927 			/* Now copy over verifier to OPEN4args. */
928 			open_args->createhow4_u.createverf = *(uint64_t *)&verf;
929 		} else {
930 			int v_error;
931 			bitmap4 supp_attrs;
932 			servinfo4_t *svp;
933 
934 			attr = &open_args->createhow4_u.createattrs;
935 
936 			svp = drp->r_server;
937 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
938 			supp_attrs = svp->sv_supp_attrs;
939 			nfs_rw_exit(&svp->sv_lock);
940 
941 			/* GUARDED4 or UNCHECKED4 */
942 			v_error = vattr_to_fattr4(in_va, NULL, attr, 0, OP_OPEN,
943 					supp_attrs);
944 			if (v_error) {
945 				bzero(attr, sizeof (*attr));
946 				nfs4args_copen_free(open_args);
947 				nfs4_end_op(VTOMI4(dvp), dvp, vpi,
948 					&recov_state, FALSE);
949 				if (ncr != NULL)
950 					crfree(ncr);
951 				kmem_free(argop, argoplist_size);
952 				return (v_error);
953 			}
954 		}
955 	} else {
956 		/* NO CREATE */
957 		open_args->opentype = OPEN4_NOCREATE;
958 	}
959 
960 	if (recov_state.rs_sp != NULL) {
961 		mutex_enter(&recov_state.rs_sp->s_lock);
962 		open_args->owner.clientid = recov_state.rs_sp->clientid;
963 		mutex_exit(&recov_state.rs_sp->s_lock);
964 	} else {
965 		/* XXX should we just fail here? */
966 		open_args->owner.clientid = 0;
967 	}
968 
969 	/*
970 	 * This increments oop's ref count or creates a temporary 'just_created'
971 	 * open owner that will become valid when this OPEN/OPEN_CONFIRM call
972 	 * completes.
973 	 */
974 	mutex_enter(&VTOMI4(dvp)->mi_lock);
975 
976 	/* See if a permanent or just created open owner exists */
977 	oop = find_open_owner_nolock(cr, NFS4_JUST_CREATED, VTOMI4(dvp));
978 	if (!oop) {
979 		/*
980 		 * This open owner does not exist so create a temporary
981 		 * just created one.
982 		 */
983 		oop = create_open_owner(cr, VTOMI4(dvp));
984 		ASSERT(oop != NULL);
985 	}
986 	mutex_exit(&VTOMI4(dvp)->mi_lock);
987 
988 	/* this length never changes, do alloc before seqid sync */
989 	open_args->owner.owner_len = sizeof (oop->oo_name);
990 	open_args->owner.owner_val =
991 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
992 
993 	e.error = nfs4_start_open_seqid_sync(oop, VTOMI4(dvp));
994 	if (e.error == EAGAIN) {
995 		open_owner_rele(oop);
996 		nfs4args_copen_free(open_args);
997 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
998 		if (ncr != NULL) {
999 			crfree(ncr);
1000 			ncr = NULL;
1001 		}
1002 		goto recov_retry;
1003 	}
1004 
1005 	/* Check to see if we need to do the OTW call */
1006 	if (!create_flag) {
1007 		if (!nfs4_is_otw_open_necessary(oop, open_flag, vpi,
1008 			file_just_been_created, &e.error, acc, &recov_state)) {
1009 
1010 			/*
1011 			 * The OTW open is not necessary.  Either
1012 			 * the open can succeed without it (eg.
1013 			 * delegation, error == 0) or the open
1014 			 * must fail due to an access failure
1015 			 * (error != 0).  In either case, tidy
1016 			 * up and return.
1017 			 */
1018 
1019 			nfs4_end_open_seqid_sync(oop);
1020 			open_owner_rele(oop);
1021 			nfs4args_copen_free(open_args);
1022 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, FALSE);
1023 			if (ncr != NULL)
1024 				crfree(ncr);
1025 			kmem_free(argop, argoplist_size);
1026 			return (e.error);
1027 		}
1028 	}
1029 
1030 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1031 	    open_args->owner.owner_len);
1032 
1033 	seqid = nfs4_get_open_seqid(oop) + 1;
1034 	open_args->seqid = seqid;
1035 	open_args->share_access = 0;
1036 	if (open_flag & FREAD)
1037 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1038 	if (open_flag & FWRITE)
1039 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1040 	open_args->share_deny = OPEN4_SHARE_DENY_NONE;
1041 
1042 
1043 
1044 	/*
1045 	 * getfh w/sanity check for idx_open/idx_fattr
1046 	 */
1047 	ASSERT((idx_open + 1) == (idx_fattr - 1));
1048 	argop[idx_open + 1].argop = OP_GETFH;
1049 
1050 	/* getattr */
1051 	argop[idx_fattr].argop = OP_GETATTR;
1052 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1053 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1054 
1055 	if (setgid_flag) {
1056 		vattr_t	_v;
1057 		servinfo4_t *svp;
1058 		bitmap4	supp_attrs;
1059 
1060 		svp = drp->r_server;
1061 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1062 		supp_attrs = svp->sv_supp_attrs;
1063 		nfs_rw_exit(&svp->sv_lock);
1064 
1065 		/*
1066 		 * For setgid case, we need to:
1067 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1068 		 */
1069 		argop[4].argop = OP_SAVEFH;
1070 
1071 		argop[5].argop = OP_CPUTFH;
1072 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
1073 
1074 		argop[6].argop = OP_GETATTR;
1075 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1076 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1077 
1078 		argop[7].argop = OP_RESTOREFH;
1079 
1080 		/*
1081 		 * nverify
1082 		 */
1083 		_v.va_mask = AT_GID;
1084 		_v.va_gid = in_va->va_gid;
1085 		if (!(e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
1086 		    supp_attrs))) {
1087 
1088 			/*
1089 			 * setattr
1090 			 *
1091 			 * We _know_ we're not messing with AT_SIZE or
1092 			 * AT_XTIME, so no need for stateid or flags.
1093 			 * Also we specify NULL rp since we're only
1094 			 * interested in setting owner_group attributes.
1095 			 */
1096 			nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr,
1097 			    supp_attrs, &e.error, 0);
1098 			if (e.error)
1099 				nfs4args_verify_free(&argop[8]);
1100 		}
1101 
1102 		if (e.error) {
1103 			/*
1104 			 * XXX - Revisit the last argument to nfs4_end_op()
1105 			 *	 once 5020486 is fixed.
1106 			 */
1107 			nfs4_end_open_seqid_sync(oop);
1108 			open_owner_rele(oop);
1109 			nfs4args_copen_free(open_args);
1110 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1111 			if (ncr != NULL)
1112 				crfree(ncr);
1113 			kmem_free(argop, argoplist_size);
1114 			return (e.error);
1115 		}
1116 	} else if (create_flag) {
1117 		/*
1118 		 * For setgid case, we need to:
1119 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1120 		 */
1121 		argop[1].argop = OP_SAVEFH;
1122 
1123 		argop[5].argop = OP_RESTOREFH;
1124 
1125 		argop[6].argop = OP_GETATTR;
1126 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1127 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1128 	}
1129 
1130 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1131 	    "nfs4open_otw: %s call, nm %s, rp %s",
1132 	    needrecov ? "recov" : "first", file_name,
1133 	    rnode4info(VTOR4(dvp))));
1134 
1135 	t = gethrtime();
1136 
1137 	rfs4call(VTOMI4(dvp), &args, &res, cred_otw, &doqueue, 0, &e);
1138 
1139 	if (!e.error && nfs4_need_to_bump_seqid(&res))
1140 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1141 
1142 	needrecov = nfs4_needs_recovery(&e, TRUE, dvp->v_vfsp);
1143 
1144 	if (e.error || needrecov) {
1145 		bool_t abort = FALSE;
1146 
1147 		if (needrecov) {
1148 			nfs4_bseqid_entry_t *bsep = NULL;
1149 
1150 			nfs4open_save_lost_rqst(e.error, &lost_rqst, oop,
1151 			    cred_otw, vpi, dvp, open_args);
1152 
1153 			if (!e.error && res.status == NFS4ERR_BAD_SEQID) {
1154 				bsep = nfs4_create_bseqid_entry(oop, NULL,
1155 					vpi, 0, args.ctag, open_args->seqid);
1156 				num_bseqid_retry--;
1157 			}
1158 
1159 			abort = nfs4_start_recovery(&e, VTOMI4(dvp), dvp, vpi,
1160 				    NULL, lost_rqst.lr_op == OP_OPEN ?
1161 				    &lost_rqst : NULL, OP_OPEN, bsep);
1162 
1163 			if (bsep)
1164 				kmem_free(bsep, sizeof (*bsep));
1165 			/* give up if we keep getting BAD_SEQID */
1166 			if (num_bseqid_retry == 0)
1167 				abort = TRUE;
1168 			if (abort == TRUE && e.error == 0)
1169 				e.error = geterrno4(res.status);
1170 		}
1171 		nfs4_end_open_seqid_sync(oop);
1172 		open_owner_rele(oop);
1173 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1174 		nfs4args_copen_free(open_args);
1175 		if (setgid_flag) {
1176 			nfs4args_verify_free(&argop[8]);
1177 			nfs4args_setattr_free(&argop[9]);
1178 		}
1179 		if (!e.error)
1180 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1181 		if (ncr != NULL) {
1182 			crfree(ncr);
1183 			ncr = NULL;
1184 		}
1185 		if (!needrecov || abort == TRUE || e.error == EINTR ||
1186 		    NFS4_FRC_UNMT_ERR(e.error, dvp->v_vfsp)) {
1187 			kmem_free(argop, argoplist_size);
1188 			return (e.error);
1189 		}
1190 		goto recov_retry;
1191 	}
1192 
1193 	/*
1194 	 * Will check and update lease after checking the rflag for
1195 	 * OPEN_CONFIRM in the successful OPEN call.
1196 	 */
1197 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
1198 
1199 		/*
1200 		 * XXX what if we're crossing mount points from server1:/drp
1201 		 * to server2:/drp/rp.
1202 		 */
1203 
1204 		/* Signal our end of use of the open seqid */
1205 		nfs4_end_open_seqid_sync(oop);
1206 
1207 		/*
1208 		 * This will destroy the open owner if it was just created,
1209 		 * and no one else has put a reference on it.
1210 		 */
1211 		open_owner_rele(oop);
1212 		if (create_flag && (createmode != EXCLUSIVE4) &&
1213 		    res.status == NFS4ERR_BADOWNER)
1214 			nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1215 
1216 		e.error = geterrno4(res.status);
1217 		nfs4args_copen_free(open_args);
1218 		if (setgid_flag) {
1219 			nfs4args_verify_free(&argop[8]);
1220 			nfs4args_setattr_free(&argop[9]);
1221 		}
1222 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1223 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1224 		/*
1225 		 * If the reply is NFS4ERR_ACCESS, it may be because
1226 		 * we are root (no root net access).  If the real uid
1227 		 * is not root, then retry with the real uid instead.
1228 		 */
1229 		if (ncr != NULL) {
1230 			crfree(ncr);
1231 			ncr = NULL;
1232 		}
1233 		if (res.status == NFS4ERR_ACCESS &&
1234 		    (ncr = crnetadjust(cred_otw)) != NULL) {
1235 			cred_otw = ncr;
1236 			goto recov_retry;
1237 		}
1238 		kmem_free(argop, argoplist_size);
1239 		return (e.error);
1240 	}
1241 
1242 	resop = &res.array[idx_open];  /* open res */
1243 	op_res = &resop->nfs_resop4_u.opopen;
1244 
1245 #ifdef DEBUG
1246 	/*
1247 	 * verify attrset bitmap
1248 	 */
1249 	if (create_flag &&
1250 	    (createmode == UNCHECKED4 || createmode == GUARDED4)) {
1251 		/* make sure attrset returned is what we asked for */
1252 		/* XXX Ignore this 'error' for now */
1253 		if (attr->attrmask != op_res->attrset)
1254 			/* EMPTY */;
1255 	}
1256 #endif
1257 
1258 	if (op_res->rflags & OPEN4_RESULT_LOCKTYPE_POSIX) {
1259 		mutex_enter(&VTOMI4(dvp)->mi_lock);
1260 		VTOMI4(dvp)->mi_flags |= MI4_POSIX_LOCK;
1261 		mutex_exit(&VTOMI4(dvp)->mi_lock);
1262 	}
1263 
1264 	resop = &res.array[idx_open + 1];  /* getfh res */
1265 	gf_res = &resop->nfs_resop4_u.opgetfh;
1266 
1267 	otw_sfh = sfh4_get(&gf_res->object, VTOMI4(dvp));
1268 
1269 	/*
1270 	 * The open stateid has been updated on the server but not
1271 	 * on the client yet.  There is a path: makenfs4node->nfs4_attr_cache->
1272 	 * flush_pages->VOP_PUTPAGE->...->nfs4write where we will issue an OTW
1273 	 * WRITE call.  That, however, will use the old stateid, so go ahead
1274 	 * and upate the open stateid now, before any call to makenfs4node.
1275 	 */
1276 	if (vpi) {
1277 		nfs4_open_stream_t	*tmp_osp;
1278 		rnode4_t		*tmp_rp = VTOR4(vpi);
1279 
1280 		tmp_osp = find_open_stream(oop, tmp_rp);
1281 		if (tmp_osp) {
1282 			tmp_osp->open_stateid = op_res->stateid;
1283 			mutex_exit(&tmp_osp->os_sync_lock);
1284 			open_stream_rele(tmp_osp, tmp_rp);
1285 		}
1286 
1287 		/*
1288 		 * We must determine if the file handle given by the otw open
1289 		 * is the same as the file handle which was passed in with
1290 		 * *vpp.  This case can be reached if the file we are trying
1291 		 * to open has been removed and another file has been created
1292 		 * having the same file name.  The passed in vnode is released
1293 		 * later.
1294 		 */
1295 		orig_sfh = VTOR4(vpi)->r_fh;
1296 		fh_differs = nfs4cmpfh(&orig_sfh->sfh_fh, &otw_sfh->sfh_fh);
1297 	}
1298 
1299 	garp = &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res;
1300 
1301 	if (create_flag || fh_differs) {
1302 		int rnode_err = 0;
1303 
1304 		vp = makenfs4node(otw_sfh, garp, dvp->v_vfsp, t, cr,
1305 		    dvp, fn_get(VTOSV(dvp)->sv_name, file_name));
1306 
1307 		if (e.error)
1308 			PURGE_ATTRCACHE4(vp);
1309 		/*
1310 		 * For the newly created vp case, make sure the rnode
1311 		 * isn't bad before using it.
1312 		 */
1313 		mutex_enter(&(VTOR4(vp))->r_statelock);
1314 		if (VTOR4(vp)->r_flags & R4RECOVERR)
1315 			rnode_err = EIO;
1316 		mutex_exit(&(VTOR4(vp))->r_statelock);
1317 
1318 		if (rnode_err) {
1319 			nfs4_end_open_seqid_sync(oop);
1320 			nfs4args_copen_free(open_args);
1321 			if (setgid_flag) {
1322 				nfs4args_verify_free(&argop[8]);
1323 				nfs4args_setattr_free(&argop[9]);
1324 			}
1325 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1326 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1327 				    needrecov);
1328 			open_owner_rele(oop);
1329 			VN_RELE(vp);
1330 			if (ncr != NULL)
1331 				crfree(ncr);
1332 			sfh4_rele(&otw_sfh);
1333 			kmem_free(argop, argoplist_size);
1334 			return (EIO);
1335 		}
1336 	} else {
1337 		vp = vpi;
1338 	}
1339 	sfh4_rele(&otw_sfh);
1340 
1341 	/*
1342 	 * It seems odd to get a full set of attrs and then not update
1343 	 * the object's attrcache in the non-create case.  Create case uses
1344 	 * the attrs since makenfs4node checks to see if the attrs need to
1345 	 * be updated (and then updates them).  The non-create case should
1346 	 * update attrs also.
1347 	 */
1348 	if (! create_flag && ! fh_differs && !e.error) {
1349 		nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
1350 	}
1351 
1352 	nfs4_error_zinit(&e);
1353 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
1354 		/* This does not do recovery for vp explicitly. */
1355 		nfs4open_confirm(vp, &seqid, &op_res->stateid, cred_otw, FALSE,
1356 		    &retry_open, oop, FALSE, &e, &num_bseqid_retry);
1357 
1358 		if (e.error || e.stat) {
1359 			nfs4_end_open_seqid_sync(oop);
1360 			nfs4args_copen_free(open_args);
1361 			if (setgid_flag) {
1362 				nfs4args_verify_free(&argop[8]);
1363 				nfs4args_setattr_free(&argop[9]);
1364 			}
1365 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1366 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1367 				needrecov);
1368 			open_owner_rele(oop);
1369 			if (create_flag || fh_differs) {
1370 				/* rele the makenfs4node */
1371 				VN_RELE(vp);
1372 			}
1373 			if (ncr != NULL) {
1374 				crfree(ncr);
1375 				ncr = NULL;
1376 			}
1377 			if (retry_open == TRUE) {
1378 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1379 				    "nfs4open_otw: retry the open since OPEN "
1380 				    "CONFIRM failed with error %d stat %d",
1381 				    e.error, e.stat));
1382 				if (create_flag && createmode == GUARDED4) {
1383 					NFS4_DEBUG(nfs4_client_recov_debug,
1384 					    (CE_NOTE, "nfs4open_otw: switch "
1385 					    "createmode from GUARDED4 to "
1386 					    "UNCHECKED4"));
1387 					createmode = UNCHECKED4;
1388 				}
1389 				goto recov_retry;
1390 			}
1391 			if (!e.error) {
1392 				if (create_flag && (createmode != EXCLUSIVE4) &&
1393 				    e.stat == NFS4ERR_BADOWNER)
1394 					nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1395 
1396 				e.error = geterrno4(e.stat);
1397 			}
1398 			kmem_free(argop, argoplist_size);
1399 			return (e.error);
1400 		}
1401 	}
1402 
1403 	rp = VTOR4(vp);
1404 
1405 	mutex_enter(&rp->r_statev4_lock);
1406 	if (create_flag)
1407 		rp->created_v4 = 1;
1408 	mutex_exit(&rp->r_statev4_lock);
1409 
1410 	mutex_enter(&oop->oo_lock);
1411 	/* Doesn't matter if 'oo_just_created' already was set as this */
1412 	oop->oo_just_created = NFS4_PERM_CREATED;
1413 	if (oop->oo_cred_otw)
1414 		crfree(oop->oo_cred_otw);
1415 	oop->oo_cred_otw = cred_otw;
1416 	crhold(oop->oo_cred_otw);
1417 	mutex_exit(&oop->oo_lock);
1418 
1419 	/* returns with 'os_sync_lock' held */
1420 	osp = find_or_create_open_stream(oop, rp, &created_osp);
1421 	if (!osp) {
1422 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1423 		    "nfs4open_otw: failed to create an open stream"));
1424 		NFS4_DEBUG(nfs4_seqid_sync, (CE_NOTE, "nfs4open_otw: "
1425 		    "signal our end of use of the open seqid"));
1426 
1427 		nfs4_end_open_seqid_sync(oop);
1428 		open_owner_rele(oop);
1429 		nfs4args_copen_free(open_args);
1430 		if (setgid_flag) {
1431 			nfs4args_verify_free(&argop[8]);
1432 			nfs4args_setattr_free(&argop[9]);
1433 		}
1434 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1435 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1436 		if (create_flag || fh_differs)
1437 			VN_RELE(vp);
1438 		if (ncr != NULL)
1439 			crfree(ncr);
1440 
1441 		kmem_free(argop, argoplist_size);
1442 		return (EINVAL);
1443 
1444 	}
1445 
1446 	osp->open_stateid = op_res->stateid;
1447 
1448 	if (open_flag & FREAD)
1449 		osp->os_share_acc_read++;
1450 	if (open_flag & FWRITE)
1451 		osp->os_share_acc_write++;
1452 	osp->os_share_deny_none++;
1453 
1454 	/*
1455 	 * Need to reset this bitfield for the possible case where we were
1456 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
1457 	 * we could retry the CLOSE, OPENed the file again.
1458 	 */
1459 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
1460 	osp->os_final_close = 0;
1461 	osp->os_force_close = 0;
1462 #ifdef DEBUG
1463 	if (osp->os_failed_reopen)
1464 		NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE, "nfs4open_otw:"
1465 		    " clearing os_failed_reopen for osp %p, cr %p, rp %s",
1466 		    (void *)osp, (void *)cr, rnode4info(rp)));
1467 #endif
1468 	osp->os_failed_reopen = 0;
1469 
1470 	mutex_exit(&osp->os_sync_lock);
1471 
1472 	nfs4_end_open_seqid_sync(oop);
1473 
1474 	if (created_osp && recov_state.rs_sp != NULL) {
1475 		mutex_enter(&recov_state.rs_sp->s_lock);
1476 		nfs4_inc_state_ref_count_nolock(recov_state.rs_sp, VTOMI4(dvp));
1477 		mutex_exit(&recov_state.rs_sp->s_lock);
1478 	}
1479 
1480 	/* get rid of our reference to find oop */
1481 	open_owner_rele(oop);
1482 
1483 	open_stream_rele(osp, rp);
1484 
1485 	/* accept delegation, if any */
1486 	nfs4_delegation_accept(rp, CLAIM_NULL, op_res, garp, cred_otw);
1487 
1488 	nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1489 
1490 	if (createmode == EXCLUSIVE4 &&
1491 		(in_va->va_mask & ~(AT_GID | AT_SIZE))) {
1492 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw:"
1493 			" EXCLUSIVE4: sending a SETATTR"));
1494 		/*
1495 		 * If doing an exclusive create, then generate
1496 		 * a SETATTR to set the initial attributes.
1497 		 * Try to set the mtime and the atime to the
1498 		 * server's current time.  It is somewhat
1499 		 * expected that these fields will be used to
1500 		 * store the exclusive create cookie.  If not,
1501 		 * server implementors will need to know that
1502 		 * a SETATTR will follow an exclusive create
1503 		 * and the cookie should be destroyed if
1504 		 * appropriate.
1505 		 *
1506 		 * The AT_GID and AT_SIZE bits are turned off
1507 		 * so that the SETATTR request will not attempt
1508 		 * to process these.  The gid will be set
1509 		 * separately if appropriate.  The size is turned
1510 		 * off because it is assumed that a new file will
1511 		 * be created empty and if the file wasn't empty,
1512 		 * then the exclusive create will have failed
1513 		 * because the file must have existed already.
1514 		 * Therefore, no truncate operation is needed.
1515 		 */
1516 		in_va->va_mask &= ~(AT_GID | AT_SIZE);
1517 		in_va->va_mask |= (AT_MTIME | AT_ATIME);
1518 
1519 		e.error = nfs4setattr(vp, in_va, 0, cr, NULL);
1520 		if (e.error) {
1521 			/*
1522 			 * Couldn't correct the attributes of
1523 			 * the newly created file and the
1524 			 * attributes are wrong.  Remove the
1525 			 * file and return an error to the
1526 			 * application.
1527 			 */
1528 			/* XXX will this take care of client state ? */
1529 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1530 				"nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1531 				" remove file", e.error));
1532 			VN_RELE(vp);
1533 			(void) nfs4_remove(dvp, file_name, cr);
1534 			/*
1535 			 * Since we've reled the vnode and removed
1536 			 * the file we now need to return the error.
1537 			 * At this point we don't want to update the
1538 			 * dircaches, call nfs4_waitfor_purge_complete
1539 			 * or set vpp to vp so we need to skip these
1540 			 * as well.
1541 			 */
1542 			goto skip_update_dircaches;
1543 		}
1544 	}
1545 
1546 	/*
1547 	 * If we created or found the correct vnode, due to create_flag or
1548 	 * fh_differs being set, then update directory cache attribute, readdir
1549 	 * and dnlc caches.
1550 	 */
1551 	if (create_flag || fh_differs) {
1552 		dirattr_info_t dinfo, *dinfop;
1553 
1554 		/*
1555 		 * Make sure getattr succeeded before using results.
1556 		 * note: op 7 is getattr(dir) for both flavors of
1557 		 * open(create).
1558 		 */
1559 		if (create_flag && res.status == NFS4_OK) {
1560 			dinfo.di_time_call = t;
1561 			dinfo.di_cred = cr;
1562 			dinfo.di_garp =
1563 				&res.array[6].nfs_resop4_u.opgetattr.ga_res;
1564 			dinfop = &dinfo;
1565 		} else {
1566 			dinfop = NULL;
1567 		}
1568 
1569 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1570 					dinfop);
1571 	}
1572 
1573 	/*
1574 	 * If the page cache for this file was flushed from actions
1575 	 * above, it was done asynchronously and if that is true,
1576 	 * there is a need to wait here for it to complete.  This must
1577 	 * be done outside of start_fop/end_fop.
1578 	 */
1579 	(void) nfs4_waitfor_purge_complete(vp);
1580 
1581 	/*
1582 	 * It is implicit that we are in the open case (create_flag == 0) since
1583 	 * fh_differs can only be set to a non-zero value in the open case.
1584 	 */
1585 	if (fh_differs != 0 && vpi != NULL)
1586 		VN_RELE(vpi);
1587 
1588 	/*
1589 	 * Be sure to set *vpp to the correct value before returning.
1590 	 */
1591 	*vpp = vp;
1592 
1593 skip_update_dircaches:
1594 
1595 	nfs4args_copen_free(open_args);
1596 	if (setgid_flag) {
1597 		nfs4args_verify_free(&argop[8]);
1598 		nfs4args_setattr_free(&argop[9]);
1599 	}
1600 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1601 
1602 	if (ncr)
1603 		crfree(ncr);
1604 	kmem_free(argop, argoplist_size);
1605 	return (e.error);
1606 }
1607 
1608 /*
1609  * Reopen an open instance.  cf. nfs4open_otw().
1610  *
1611  * Errors are returned by the nfs4_error_t parameter.
1612  * - ep->error contains an errno value or zero.
1613  * - if it is zero, ep->stat is set to an NFS status code, if any.
1614  *   If the file could not be reopened, but the caller should continue, the
1615  *   file is marked dead and no error values are returned.  If the caller
1616  *   should stop recovering open files and start over, either the ep->error
1617  *   value or ep->stat will indicate an error (either something that requires
1618  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1619  *   filehandles) may be handled silently by this routine.
1620  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1621  *   will be started, so the caller should not do it.
1622  *
1623  * Gotos:
1624  * - kill_file : reopen failed in such a fashion to constitute marking the
1625  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1626  *   is for cases where recovery is not possible.
1627  * - failed_reopen : same as above, except that the file has already been
1628  *   marked dead, so no need to do it again.
1629  * - bailout : reopen failed but we are able to recover and retry the reopen -
1630  *   either within this function immediatley or via the calling function.
1631  */
1632 
1633 void
1634 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1635 	    open_claim_type4 claim, bool_t frc_use_claim_previous,
1636 	    bool_t is_recov)
1637 {
1638 	COMPOUND4args_clnt args;
1639 	COMPOUND4res_clnt res;
1640 	nfs_argop4 argop[4];
1641 	nfs_resop4 *resop;
1642 	OPEN4res *op_res = NULL;
1643 	OPEN4cargs *open_args;
1644 	GETFH4res *gf_res;
1645 	rnode4_t *rp = VTOR4(vp);
1646 	int doqueue = 1;
1647 	cred_t *cr = NULL, *cred_otw = NULL;
1648 	nfs4_open_owner_t *oop = NULL;
1649 	seqid4 seqid;
1650 	nfs4_ga_res_t *garp;
1651 	char fn[MAXNAMELEN];
1652 	nfs4_recov_state_t recov = {NULL, 0};
1653 	nfs4_lost_rqst_t lost_rqst;
1654 	mntinfo4_t *mi = VTOMI4(vp);
1655 	bool_t abort;
1656 	char *failed_msg = "";
1657 	int fh_different;
1658 	hrtime_t t;
1659 	nfs4_bseqid_entry_t *bsep = NULL;
1660 
1661 	ASSERT(nfs4_consistent_type(vp));
1662 	ASSERT(nfs_zone() == mi->mi_zone);
1663 
1664 	nfs4_error_zinit(ep);
1665 
1666 	/* this is the cred used to find the open owner */
1667 	cr = state_to_cred(osp);
1668 	if (cr == NULL) {
1669 		failed_msg = "Couldn't reopen: no cred";
1670 		goto kill_file;
1671 	}
1672 	/* use this cred for OTW operations */
1673 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1674 
1675 top:
1676 	nfs4_error_zinit(ep);
1677 
1678 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1679 		/* File system has been unmounted, quit */
1680 		ep->error = EIO;
1681 		failed_msg = "Couldn't reopen: file system has been unmounted";
1682 		goto kill_file;
1683 	}
1684 
1685 	oop = osp->os_open_owner;
1686 
1687 	ASSERT(oop != NULL);
1688 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1689 		failed_msg = "can't reopen: no open owner";
1690 		goto kill_file;
1691 	}
1692 	open_owner_hold(oop);
1693 
1694 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1695 	if (ep->error) {
1696 		open_owner_rele(oop);
1697 		oop = NULL;
1698 		goto bailout;
1699 	}
1700 
1701 	/*
1702 	 * If the rnode has a delegation and the delegation has been
1703 	 * recovered and the server didn't request a recall and the caller
1704 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1705 	 * recovery) and the rnode hasn't been marked dead, then install
1706 	 * the delegation stateid in the open stream.  Otherwise, proceed
1707 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1708 	 */
1709 	mutex_enter(&rp->r_statev4_lock);
1710 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1711 	    !rp->r_deleg_return_pending &&
1712 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1713 	    !rp->r_deleg_needs_recall &&
1714 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1715 	    !(rp->r_flags & R4RECOVERR)) {
1716 		mutex_enter(&osp->os_sync_lock);
1717 		osp->os_delegation = 1;
1718 		osp->open_stateid = rp->r_deleg_stateid;
1719 		mutex_exit(&osp->os_sync_lock);
1720 		mutex_exit(&rp->r_statev4_lock);
1721 		goto bailout;
1722 	}
1723 	mutex_exit(&rp->r_statev4_lock);
1724 
1725 	/*
1726 	 * If the file failed recovery, just quit.  This failure need not
1727 	 * affect other reopens, so don't return an error.
1728 	 */
1729 	mutex_enter(&rp->r_statelock);
1730 	if (rp->r_flags & R4RECOVERR) {
1731 		mutex_exit(&rp->r_statelock);
1732 		ep->error = 0;
1733 		goto failed_reopen;
1734 	}
1735 	mutex_exit(&rp->r_statelock);
1736 
1737 	/*
1738 	 * argop is empty here
1739 	 *
1740 	 * PUTFH, OPEN, GETATTR
1741 	 */
1742 	args.ctag = TAG_REOPEN;
1743 	args.array_len = 4;
1744 	args.array = argop;
1745 
1746 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1747 	    "nfs4_reopen: file is type %d, id %s",
1748 	    vp->v_type, rnode4info(VTOR4(vp))));
1749 
1750 	argop[0].argop = OP_CPUTFH;
1751 
1752 	if (claim != CLAIM_PREVIOUS) {
1753 		/*
1754 		 * if this is a file mount then
1755 		 * use the mntinfo parentfh
1756 		 */
1757 		argop[0].nfs_argop4_u.opcputfh.sfh =
1758 			(vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1759 						VTOSV(vp)->sv_dfh;
1760 	} else {
1761 		/* putfh fh to reopen */
1762 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1763 	}
1764 
1765 	argop[1].argop = OP_COPEN;
1766 	open_args = &argop[1].nfs_argop4_u.opcopen;
1767 	open_args->claim = claim;
1768 
1769 	if (claim == CLAIM_NULL) {
1770 
1771 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1772 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1773 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1774 			    (void *)vp);
1775 			failed_msg = "Couldn't reopen: vtoname failed for "
1776 			    "CLAIM_NULL";
1777 			/* nothing allocated yet */
1778 			goto kill_file;
1779 		}
1780 
1781 		open_args->open_claim4_u.cfile = fn;
1782 	} else if (claim == CLAIM_PREVIOUS) {
1783 
1784 		/*
1785 		 * We have two cases to deal with here:
1786 		 * 1) We're being called to reopen files in order to satisfy
1787 		 *    a lock operation request which requires us to explicitly
1788 		 *    reopen files which were opened under a delegation.  If
1789 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1790 		 *    that case, frc_use_claim_previous is TRUE and we must
1791 		 *    use the rnode's current delegation type (r_deleg_type).
1792 		 * 2) We're reopening files during some form of recovery.
1793 		 *    In this case, frc_use_claim_previous is FALSE and we
1794 		 *    use the delegation type appropriate for recovery
1795 		 *    (r_deleg_needs_recovery).
1796 		 */
1797 		mutex_enter(&rp->r_statev4_lock);
1798 		open_args->open_claim4_u.delegate_type =
1799 			frc_use_claim_previous ?
1800 				rp->r_deleg_type :
1801 				rp->r_deleg_needs_recovery;
1802 		mutex_exit(&rp->r_statev4_lock);
1803 
1804 	} else if (claim == CLAIM_DELEGATE_CUR) {
1805 
1806 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1807 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1808 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1809 			    "with %m", (void *)vp);
1810 			failed_msg = "Couldn't reopen: vtoname failed for "
1811 			    "CLAIM_DELEGATE_CUR";
1812 			/* nothing allocated yet */
1813 			goto kill_file;
1814 		}
1815 
1816 		mutex_enter(&rp->r_statev4_lock);
1817 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1818 							rp->r_deleg_stateid;
1819 		mutex_exit(&rp->r_statev4_lock);
1820 
1821 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1822 	}
1823 	open_args->opentype = OPEN4_NOCREATE;
1824 	open_args->owner.clientid = mi2clientid(mi);
1825 	open_args->owner.owner_len = sizeof (oop->oo_name);
1826 	open_args->owner.owner_val =
1827 			kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1828 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1829 			open_args->owner.owner_len);
1830 	open_args->share_access = 0;
1831 	open_args->share_deny = 0;
1832 
1833 	mutex_enter(&osp->os_sync_lock);
1834 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1835 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1836 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1837 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1838 	    osp->os_share_acc_write, osp->os_open_ref_count,
1839 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1840 
1841 	if (osp->os_share_acc_read || osp->os_mmap_read)
1842 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1843 	if (osp->os_share_acc_write || osp->os_mmap_write)
1844 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1845 	if (osp->os_share_deny_read)
1846 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1847 	if (osp->os_share_deny_write)
1848 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1849 	mutex_exit(&osp->os_sync_lock);
1850 
1851 	seqid = nfs4_get_open_seqid(oop) + 1;
1852 	open_args->seqid = seqid;
1853 
1854 	/* Construct the getfh part of the compound */
1855 	argop[2].argop = OP_GETFH;
1856 
1857 	/* Construct the getattr part of the compound */
1858 	argop[3].argop = OP_GETATTR;
1859 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1860 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1861 
1862 	t = gethrtime();
1863 
1864 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1865 
1866 	if (ep->error) {
1867 		if (!is_recov && !frc_use_claim_previous &&
1868 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1869 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1870 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1871 				cred_otw, vp, NULL, open_args);
1872 			abort = nfs4_start_recovery(ep,
1873 				    VTOMI4(vp), vp, NULL, NULL,
1874 				    lost_rqst.lr_op == OP_OPEN ?
1875 				    &lost_rqst : NULL, OP_OPEN, NULL);
1876 			nfs4args_copen_free(open_args);
1877 			goto bailout;
1878 		}
1879 
1880 		nfs4args_copen_free(open_args);
1881 
1882 		if (ep->error == EACCES && cred_otw != cr) {
1883 			crfree(cred_otw);
1884 			cred_otw = cr;
1885 			crhold(cred_otw);
1886 			nfs4_end_open_seqid_sync(oop);
1887 			open_owner_rele(oop);
1888 			oop = NULL;
1889 			goto top;
1890 		}
1891 		if (ep->error == ETIMEDOUT)
1892 			goto bailout;
1893 		failed_msg = "Couldn't reopen: rpc error";
1894 		goto kill_file;
1895 	}
1896 
1897 	if (nfs4_need_to_bump_seqid(&res))
1898 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1899 
1900 	switch (res.status) {
1901 	case NFS4_OK:
1902 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1903 			mutex_enter(&rp->r_statelock);
1904 			rp->r_delay_interval = 0;
1905 			mutex_exit(&rp->r_statelock);
1906 		}
1907 		break;
1908 	case NFS4ERR_BAD_SEQID:
1909 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1910 			args.ctag, open_args->seqid);
1911 
1912 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1913 			    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1914 			    NULL, OP_OPEN, bsep);
1915 
1916 		nfs4args_copen_free(open_args);
1917 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1918 		nfs4_end_open_seqid_sync(oop);
1919 		open_owner_rele(oop);
1920 		oop = NULL;
1921 		kmem_free(bsep, sizeof (*bsep));
1922 
1923 		goto kill_file;
1924 	case NFS4ERR_NO_GRACE:
1925 		nfs4args_copen_free(open_args);
1926 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1927 		nfs4_end_open_seqid_sync(oop);
1928 		open_owner_rele(oop);
1929 		oop = NULL;
1930 		if (claim == CLAIM_PREVIOUS) {
1931 			/*
1932 			 * Retry as a plain open. We don't need to worry about
1933 			 * checking the changeinfo: it is acceptable for a
1934 			 * client to re-open a file and continue processing
1935 			 * (in the absence of locks).
1936 			 */
1937 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1938 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1939 			    "will retry as CLAIM_NULL"));
1940 			claim = CLAIM_NULL;
1941 			nfs4_mi_kstat_inc_no_grace(mi);
1942 			goto top;
1943 		}
1944 		failed_msg =
1945 		    "Couldn't reopen: tried reclaim outside grace period. ";
1946 		goto kill_file;
1947 	case NFS4ERR_GRACE:
1948 		nfs4_set_grace_wait(mi);
1949 		nfs4args_copen_free(open_args);
1950 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1951 		nfs4_end_open_seqid_sync(oop);
1952 		open_owner_rele(oop);
1953 		oop = NULL;
1954 		ep->error = nfs4_wait_for_grace(mi, &recov);
1955 		if (ep->error != 0)
1956 			goto bailout;
1957 		goto top;
1958 	case NFS4ERR_DELAY:
1959 		nfs4_set_delay_wait(vp);
1960 		nfs4args_copen_free(open_args);
1961 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1962 		nfs4_end_open_seqid_sync(oop);
1963 		open_owner_rele(oop);
1964 		oop = NULL;
1965 		ep->error = nfs4_wait_for_delay(vp, &recov);
1966 		nfs4_mi_kstat_inc_delay(mi);
1967 		if (ep->error != 0)
1968 			goto bailout;
1969 		goto top;
1970 	case NFS4ERR_FHEXPIRED:
1971 		/* recover filehandle and retry */
1972 		abort = nfs4_start_recovery(ep,
1973 				mi, vp, NULL, NULL, NULL, OP_OPEN, NULL);
1974 		nfs4args_copen_free(open_args);
1975 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1976 		nfs4_end_open_seqid_sync(oop);
1977 		open_owner_rele(oop);
1978 		oop = NULL;
1979 		if (abort == FALSE)
1980 			goto top;
1981 		failed_msg = "Couldn't reopen: recovery aborted";
1982 		goto kill_file;
1983 	case NFS4ERR_RESOURCE:
1984 	case NFS4ERR_STALE_CLIENTID:
1985 	case NFS4ERR_WRONGSEC:
1986 	case NFS4ERR_EXPIRED:
1987 		/*
1988 		 * Do not mark the file dead and let the calling
1989 		 * function initiate recovery.
1990 		 */
1991 		nfs4args_copen_free(open_args);
1992 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1993 		nfs4_end_open_seqid_sync(oop);
1994 		open_owner_rele(oop);
1995 		oop = NULL;
1996 		goto bailout;
1997 	case NFS4ERR_ACCESS:
1998 		if (cred_otw != cr) {
1999 			crfree(cred_otw);
2000 			cred_otw = cr;
2001 			crhold(cred_otw);
2002 			nfs4args_copen_free(open_args);
2003 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2004 			nfs4_end_open_seqid_sync(oop);
2005 			open_owner_rele(oop);
2006 			oop = NULL;
2007 			goto top;
2008 		}
2009 		/* fall through */
2010 	default:
2011 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2012 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2013 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2014 		    rnode4info(VTOR4(vp))));
2015 		failed_msg = "Couldn't reopen: NFSv4 error";
2016 		nfs4args_copen_free(open_args);
2017 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2018 		goto kill_file;
2019 	}
2020 
2021 	resop = &res.array[1];  /* open res */
2022 	op_res = &resop->nfs_resop4_u.opopen;
2023 
2024 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2025 
2026 	/*
2027 	 * Check if the path we reopened really is the same
2028 	 * file. We could end up in a situation where the file
2029 	 * was removed and a new file created with the same name.
2030 	 */
2031 	resop = &res.array[2];
2032 	gf_res = &resop->nfs_resop4_u.opgetfh;
2033 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2034 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2035 	if (fh_different) {
2036 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2037 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2038 			/* Oops, we don't have the same file */
2039 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2040 				failed_msg = "Couldn't reopen: Persistent "
2041 				    "file handle changed";
2042 			else
2043 				failed_msg = "Couldn't reopen: Volatile "
2044 				    "(no expire on open) file handle changed";
2045 
2046 			nfs4args_copen_free(open_args);
2047 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2048 			nfs_rw_exit(&mi->mi_fh_lock);
2049 			goto kill_file;
2050 
2051 		} else {
2052 			/*
2053 			 * We have volatile file handles that don't compare.
2054 			 * If the fids are the same then we assume that the
2055 			 * file handle expired but the rnode still refers to
2056 			 * the same file object.
2057 			 *
2058 			 * First check that we have fids or not.
2059 			 * If we don't we have a dumb server so we will
2060 			 * just assume every thing is ok for now.
2061 			 */
2062 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2063 			    rp->r_attr.va_mask & AT_NODEID &&
2064 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2065 				/*
2066 				 * We have fids, but they don't
2067 				 * compare. So kill the file.
2068 				 */
2069 				failed_msg =
2070 					"Couldn't reopen: file handle changed"
2071 				    " due to mismatched fids";
2072 				nfs4args_copen_free(open_args);
2073 				(void) xdr_free(xdr_COMPOUND4res_clnt,
2074 						(caddr_t)&res);
2075 				nfs_rw_exit(&mi->mi_fh_lock);
2076 				goto kill_file;
2077 			} else {
2078 				/*
2079 				 * We have volatile file handles that refers
2080 				 * to the same file (at least they have the
2081 				 * same fid) or we don't have fids so we
2082 				 * can't tell. :(. We'll be a kind and accepting
2083 				 * client so we'll update the rnode's file
2084 				 * handle with the otw handle.
2085 				 *
2086 				 * We need to drop mi->mi_fh_lock since
2087 				 * sh4_update acquires it. Since there is
2088 				 * only one recovery thread there is no
2089 				 * race.
2090 				 */
2091 				nfs_rw_exit(&mi->mi_fh_lock);
2092 				sfh4_update(rp->r_fh, &gf_res->object);
2093 			}
2094 		}
2095 	} else {
2096 		nfs_rw_exit(&mi->mi_fh_lock);
2097 	}
2098 
2099 	ASSERT(nfs4_consistent_type(vp));
2100 
2101 	/*
2102 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2103 	 * over.  Presumably if there is a persistent error it will show up
2104 	 * when we resend the OPEN.
2105 	 */
2106 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2107 		bool_t retry_open = FALSE;
2108 
2109 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2110 					cred_otw, is_recov, &retry_open,
2111 					oop, FALSE, ep, NULL);
2112 		if (ep->error || ep->stat) {
2113 			nfs4args_copen_free(open_args);
2114 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2115 			nfs4_end_open_seqid_sync(oop);
2116 			open_owner_rele(oop);
2117 			oop = NULL;
2118 			goto top;
2119 		}
2120 	}
2121 
2122 	mutex_enter(&osp->os_sync_lock);
2123 	osp->open_stateid = op_res->stateid;
2124 	osp->os_delegation = 0;
2125 	/*
2126 	 * Need to reset this bitfield for the possible case where we were
2127 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2128 	 * we could retry the CLOSE, OPENed the file again.
2129 	 */
2130 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2131 	osp->os_final_close = 0;
2132 	osp->os_force_close = 0;
2133 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2134 		osp->os_dc_openacc = open_args->share_access;
2135 	mutex_exit(&osp->os_sync_lock);
2136 
2137 	nfs4_end_open_seqid_sync(oop);
2138 
2139 	/* accept delegation, if any */
2140 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2141 
2142 	nfs4args_copen_free(open_args);
2143 
2144 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2145 
2146 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2147 
2148 	ASSERT(nfs4_consistent_type(vp));
2149 
2150 	open_owner_rele(oop);
2151 	crfree(cr);
2152 	crfree(cred_otw);
2153 	return;
2154 
2155 kill_file:
2156 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2157 failed_reopen:
2158 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2159 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2160 	    (void *)osp, (void *)cr, rnode4info(rp)));
2161 	mutex_enter(&osp->os_sync_lock);
2162 	osp->os_failed_reopen = 1;
2163 	mutex_exit(&osp->os_sync_lock);
2164 bailout:
2165 	if (oop != NULL) {
2166 		nfs4_end_open_seqid_sync(oop);
2167 		open_owner_rele(oop);
2168 	}
2169 	if (cr != NULL)
2170 		crfree(cr);
2171 	if (cred_otw != NULL)
2172 		crfree(cred_otw);
2173 }
2174 
2175 /* for . and .. OPENs */
2176 /* ARGSUSED */
2177 static int
2178 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2179 {
2180 	rnode4_t *rp;
2181 	nfs4_ga_res_t gar;
2182 
2183 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2184 
2185 	/*
2186 	 * If close-to-open consistency checking is turned off or
2187 	 * if there is no cached data, we can avoid
2188 	 * the over the wire getattr.  Otherwise, force a
2189 	 * call to the server to get fresh attributes and to
2190 	 * check caches. This is required for close-to-open
2191 	 * consistency.
2192 	 */
2193 	rp = VTOR4(*vpp);
2194 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2195 			(rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2196 		return (0);
2197 
2198 	gar.n4g_va.va_mask = AT_ALL;
2199 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2200 }
2201 
2202 /*
2203  * CLOSE a file
2204  */
2205 static int
2206 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr)
2207 {
2208 	rnode4_t	*rp;
2209 	int		 error = 0;
2210 	int		 r_error = 0;
2211 	int		 n4error = 0;
2212 	nfs4_error_t	 e = { 0, NFS4_OK, RPC_SUCCESS };
2213 
2214 	/*
2215 	 * Remove client state for this (lockowner, file) pair.
2216 	 * Issue otw v4 call to have the server do the same.
2217 	 */
2218 
2219 	rp = VTOR4(vp);
2220 
2221 	/*
2222 	 * zone_enter(2) prevents processes from changing zones with NFS files
2223 	 * open; if we happen to get here from the wrong zone we can't do
2224 	 * anything over the wire.
2225 	 */
2226 	if (VTOMI4(vp)->mi_zone != nfs_zone()) {
2227 		/*
2228 		 * We could attempt to clean up locks, except we're sure
2229 		 * that the current process didn't acquire any locks on
2230 		 * the file: any attempt to lock a file belong to another zone
2231 		 * will fail, and one can't lock an NFS file and then change
2232 		 * zones, as that fails too.
2233 		 *
2234 		 * Returning an error here is the sane thing to do.  A
2235 		 * subsequent call to VN_RELE() which translates to a
2236 		 * nfs4_inactive() will clean up state: if the zone of the
2237 		 * vnode's origin is still alive and kicking, the inactive
2238 		 * thread will handle the request (from the correct zone), and
2239 		 * everything (minus the OTW close call) should be OK.  If the
2240 		 * zone is going away nfs4_async_inactive() will throw away
2241 		 * delegations, open streams and cached pages inline.
2242 		 */
2243 		return (EIO);
2244 	}
2245 
2246 	/*
2247 	 * If we are using local locking for this filesystem, then
2248 	 * release all of the SYSV style record locks.  Otherwise,
2249 	 * we are doing network locking and we need to release all
2250 	 * of the network locks.  All of the locks held by this
2251 	 * process on this file are released no matter what the
2252 	 * incoming reference count is.
2253 	 */
2254 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK) {
2255 		cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
2256 		cleanshares(vp, ttoproc(curthread)->p_pid);
2257 	} else
2258 		e.error = nfs4_lockrelease(vp, flag, offset, cr);
2259 
2260 	if (e.error)
2261 		return (e.error);
2262 
2263 	if (count > 1)
2264 		return (0);
2265 
2266 	/*
2267 	 * If the file has been `unlinked', then purge the
2268 	 * DNLC so that this vnode will get reycled quicker
2269 	 * and the .nfs* file on the server will get removed.
2270 	 */
2271 	if (rp->r_unldvp != NULL)
2272 		dnlc_purge_vp(vp);
2273 
2274 	/*
2275 	 * If the file was open for write and there are pages,
2276 	 * do a synchronous flush and commit of all of the
2277 	 * dirty and uncommitted pages.
2278 	 */
2279 	ASSERT(!e.error);
2280 	if ((flag & FWRITE) && nfs4_has_pages(vp))
2281 		error = nfs4_putpage_commit(vp, 0, 0, cr);
2282 
2283 	mutex_enter(&rp->r_statelock);
2284 	r_error = rp->r_error;
2285 	rp->r_error = 0;
2286 	mutex_exit(&rp->r_statelock);
2287 
2288 	/*
2289 	 * If this file type is one for which no explicit 'open' was
2290 	 * done, then bail now (ie. no need for protocol 'close'). If
2291 	 * there was an error w/the vm subsystem, return _that_ error,
2292 	 * otherwise, return any errors that may've been reported via
2293 	 * the rnode.
2294 	 */
2295 	if (vp->v_type != VREG)
2296 		return (error ? error : r_error);
2297 
2298 	/*
2299 	 * The sync putpage commit may have failed above, but since
2300 	 * we're working w/a regular file, we need to do the protocol
2301 	 * 'close' (nfs4close_one will figure out if an otw close is
2302 	 * needed or not). Report any errors _after_ doing the protocol
2303 	 * 'close'.
2304 	 */
2305 	nfs4close_one(vp, NULL, cr, flag, NULL, &e, CLOSE_NORM, 0, 0, 0);
2306 	n4error = e.error ? e.error : geterrno4(e.stat);
2307 
2308 	/*
2309 	 * Error reporting prio (Hi -> Lo)
2310 	 *
2311 	 *   i) nfs4_putpage_commit (error)
2312 	 *  ii) rnode's (r_error)
2313 	 * iii) nfs4close_one (n4error)
2314 	 */
2315 	return (error ? error : (r_error ? r_error : n4error));
2316 }
2317 
2318 /*
2319  * Initialize *lost_rqstp.
2320  */
2321 
2322 static void
2323 nfs4close_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
2324 	nfs4_open_owner_t *oop, nfs4_open_stream_t *osp, cred_t *cr,
2325 	vnode_t *vp)
2326 {
2327 	if (error != ETIMEDOUT && error != EINTR &&
2328 	    !NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
2329 		lost_rqstp->lr_op = 0;
2330 		return;
2331 	}
2332 
2333 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
2334 			"nfs4close_save_lost_rqst: error %d", error));
2335 
2336 	lost_rqstp->lr_op = OP_CLOSE;
2337 	/*
2338 	 * The vp is held and rele'd via the recovery code.
2339 	 * See nfs4_save_lost_rqst.
2340 	 */
2341 	lost_rqstp->lr_vp = vp;
2342 	lost_rqstp->lr_dvp = NULL;
2343 	lost_rqstp->lr_oop = oop;
2344 	lost_rqstp->lr_osp = osp;
2345 	ASSERT(osp != NULL);
2346 	ASSERT(mutex_owned(&osp->os_sync_lock));
2347 	osp->os_pending_close = 1;
2348 	lost_rqstp->lr_lop = NULL;
2349 	lost_rqstp->lr_cr = cr;
2350 	lost_rqstp->lr_flk = NULL;
2351 	lost_rqstp->lr_putfirst = FALSE;
2352 }
2353 
2354 /*
2355  * Assumes you already have the open seqid sync grabbed as well as the
2356  * 'os_sync_lock'.  Note: this will release the open seqid sync and
2357  * 'os_sync_lock' if client recovery starts.  Calling functions have to
2358  * be prepared to handle this.
2359  *
2360  * 'recov' is returned as 1 if the CLOSE operation detected client recovery
2361  * was needed and was started, and that the calling function should retry
2362  * this function; otherwise it is returned as 0.
2363  *
2364  * Errors are returned via the nfs4_error_t parameter.
2365  */
2366 static void
2367 nfs4close_otw(rnode4_t *rp, cred_t *cred_otw, nfs4_open_owner_t *oop,
2368 	nfs4_open_stream_t *osp, int *recov, int *did_start_seqid_syncp,
2369 	nfs4_close_type_t close_type, nfs4_error_t *ep, int *have_sync_lockp)
2370 {
2371 	COMPOUND4args_clnt args;
2372 	COMPOUND4res_clnt res;
2373 	CLOSE4args *close_args;
2374 	nfs_resop4 *resop;
2375 	nfs_argop4 argop[3];
2376 	int doqueue = 1;
2377 	mntinfo4_t *mi;
2378 	seqid4 seqid;
2379 	vnode_t *vp;
2380 	bool_t needrecov = FALSE;
2381 	nfs4_lost_rqst_t lost_rqst;
2382 	hrtime_t t;
2383 
2384 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
2385 
2386 	ASSERT(MUTEX_HELD(&osp->os_sync_lock));
2387 
2388 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw"));
2389 
2390 	/* Only set this to 1 if recovery is started */
2391 	*recov = 0;
2392 
2393 	/* do the OTW call to close the file */
2394 
2395 	if (close_type == CLOSE_RESEND)
2396 		args.ctag = TAG_CLOSE_LOST;
2397 	else if (close_type == CLOSE_AFTER_RESEND)
2398 		args.ctag = TAG_CLOSE_UNDO;
2399 	else
2400 		args.ctag = TAG_CLOSE;
2401 
2402 	args.array_len = 3;
2403 	args.array = argop;
2404 
2405 	vp = RTOV4(rp);
2406 
2407 	mi = VTOMI4(vp);
2408 
2409 	/* putfh target fh */
2410 	argop[0].argop = OP_CPUTFH;
2411 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
2412 
2413 	argop[1].argop = OP_GETATTR;
2414 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
2415 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
2416 
2417 	argop[2].argop = OP_CLOSE;
2418 	close_args = &argop[2].nfs_argop4_u.opclose;
2419 
2420 	seqid = nfs4_get_open_seqid(oop) + 1;
2421 
2422 	close_args->seqid = seqid;
2423 	close_args->open_stateid = osp->open_stateid;
2424 
2425 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
2426 	    "nfs4close_otw: %s call, rp %s", needrecov ? "recov" : "first",
2427 	    rnode4info(rp)));
2428 
2429 	t = gethrtime();
2430 
2431 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
2432 
2433 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
2434 		nfs4_set_open_seqid(seqid, oop, args.ctag);
2435 	}
2436 
2437 	needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
2438 	if (ep->error && !needrecov) {
2439 		/*
2440 		 * if there was an error and no recovery is to be done
2441 		 * then then set up the file to flush its cache if
2442 		 * needed for the next caller.
2443 		 */
2444 		mutex_enter(&rp->r_statelock);
2445 		PURGE_ATTRCACHE4_LOCKED(rp);
2446 		rp->r_flags &= ~R4WRITEMODIFIED;
2447 		mutex_exit(&rp->r_statelock);
2448 		return;
2449 	}
2450 
2451 	if (needrecov) {
2452 		bool_t abort;
2453 		nfs4_bseqid_entry_t *bsep = NULL;
2454 
2455 		if (close_type != CLOSE_RESEND)
2456 			nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
2457 				osp, cred_otw, vp);
2458 
2459 		if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
2460 			bsep = nfs4_create_bseqid_entry(oop, NULL, vp,
2461 				0, args.ctag, close_args->seqid);
2462 
2463 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
2464 			"nfs4close_otw: initiating recovery. error %d "
2465 			"res.status %d", ep->error, res.status));
2466 
2467 		/*
2468 		 * Drop the 'os_sync_lock' here so we don't hit
2469 		 * a potential recursive mutex_enter via an
2470 		 * 'open_stream_hold()'.
2471 		 */
2472 		mutex_exit(&osp->os_sync_lock);
2473 		*have_sync_lockp = 0;
2474 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
2475 			    (close_type != CLOSE_RESEND &&
2476 			    lost_rqst.lr_op == OP_CLOSE) ? &lost_rqst : NULL,
2477 			    OP_CLOSE, bsep);
2478 
2479 		/* drop open seq sync, and let the calling function regrab it */
2480 		nfs4_end_open_seqid_sync(oop);
2481 		*did_start_seqid_syncp = 0;
2482 
2483 		if (bsep)
2484 			kmem_free(bsep, sizeof (*bsep));
2485 		/*
2486 		 * For signals, the caller wants to quit, so don't say to
2487 		 * retry.  For forced unmount, if it's a user thread, it
2488 		 * wants to quit.  If it's a recovery thread, the retry
2489 		 * will happen higher-up on the call stack.  Either way,
2490 		 * don't say to retry.
2491 		 */
2492 		if (abort == FALSE && ep->error != EINTR &&
2493 		    !NFS4_FRC_UNMT_ERR(ep->error, mi->mi_vfsp) &&
2494 		    close_type != CLOSE_RESEND &&
2495 		    close_type != CLOSE_AFTER_RESEND)
2496 			*recov = 1;
2497 		else
2498 			*recov = 0;
2499 
2500 		if (!ep->error)
2501 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2502 		return;
2503 	}
2504 
2505 	if (res.status) {
2506 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2507 		return;
2508 	}
2509 
2510 	mutex_enter(&rp->r_statev4_lock);
2511 	rp->created_v4 = 0;
2512 	mutex_exit(&rp->r_statev4_lock);
2513 
2514 	resop = &res.array[2];
2515 	osp->open_stateid = resop->nfs_resop4_u.opclose.open_stateid;
2516 	osp->os_valid = 0;
2517 
2518 	/*
2519 	 * This removes the reference obtained at OPEN; ie, when the
2520 	 * open stream structure was created.
2521 	 *
2522 	 * We don't have to worry about calling 'open_stream_rele'
2523 	 * since we our currently holding a reference to the open
2524 	 * stream which means the count cannot go to 0 with this
2525 	 * decrement.
2526 	 */
2527 	ASSERT(osp->os_ref_count >= 2);
2528 	osp->os_ref_count--;
2529 
2530 	if (!ep->error)
2531 		nfs4_attr_cache(vp,
2532 				&res.array[1].nfs_resop4_u.opgetattr.ga_res,
2533 				t, cred_otw, TRUE, NULL);
2534 
2535 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw:"
2536 		" returning %d", ep->error));
2537 
2538 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2539 }
2540 
2541 /* ARGSUSED */
2542 static int
2543 nfs4_read(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2544 	caller_context_t *ct)
2545 {
2546 	rnode4_t *rp;
2547 	u_offset_t off;
2548 	offset_t diff;
2549 	uint_t on;
2550 	uint_t n;
2551 	caddr_t base;
2552 	uint_t flags;
2553 	int error;
2554 	mntinfo4_t *mi;
2555 
2556 	rp = VTOR4(vp);
2557 
2558 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2559 
2560 	if (IS_SHADOW(vp, rp))
2561 		vp = RTOV4(rp);
2562 
2563 	if (vp->v_type != VREG)
2564 		return (EISDIR);
2565 
2566 	mi = VTOMI4(vp);
2567 
2568 	if (nfs_zone() != mi->mi_zone)
2569 		return (EIO);
2570 
2571 	if (uiop->uio_resid == 0)
2572 		return (0);
2573 
2574 	if (uiop->uio_loffset < 0 || uiop->uio_loffset + uiop->uio_resid < 0)
2575 		return (EINVAL);
2576 
2577 	mutex_enter(&rp->r_statelock);
2578 	if (rp->r_flags & R4RECOVERRP)
2579 		error = (rp->r_error ? rp->r_error : EIO);
2580 	else
2581 		error = 0;
2582 	mutex_exit(&rp->r_statelock);
2583 	if (error)
2584 		return (error);
2585 
2586 	/*
2587 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2588 	 * using client-side direct I/O and the file is not mmap'd and
2589 	 * there are no cached pages.
2590 	 */
2591 	if ((vp->v_flag & VNOCACHE) ||
2592 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2593 	    rp->r_mapcnt == 0 && !nfs4_has_pages(vp))) {
2594 		size_t resid = 0;
2595 
2596 		return (nfs4read(vp, NULL, uiop->uio_loffset,
2597 				uiop->uio_resid, &resid, cr, FALSE, uiop));
2598 	}
2599 
2600 	error = 0;
2601 
2602 	do {
2603 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2604 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2605 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2606 
2607 		if (error = nfs4_validate_caches(vp, cr))
2608 			break;
2609 
2610 		mutex_enter(&rp->r_statelock);
2611 		diff = rp->r_size - uiop->uio_loffset;
2612 		mutex_exit(&rp->r_statelock);
2613 		if (diff <= 0)
2614 			break;
2615 		if (diff < n)
2616 			n = (uint_t)diff;
2617 
2618 		if (vpm_enable) {
2619 			/*
2620 			 * Copy data.
2621 			 */
2622 			error = vpm_data_copy(vp, off + on, n, uiop,
2623 						1, NULL, 0, S_READ);
2624 
2625 		} else {
2626 			base = segmap_getmapflt(segkmap, vp, off + on, n, 1,
2627 							S_READ);
2628 
2629 			error = uiomove(base + on, n, UIO_READ, uiop);
2630 		}
2631 
2632 		if (!error) {
2633 			/*
2634 			 * If read a whole block or read to eof,
2635 			 * won't need this buffer again soon.
2636 			 */
2637 			mutex_enter(&rp->r_statelock);
2638 			if (n + on == MAXBSIZE ||
2639 			    uiop->uio_loffset == rp->r_size)
2640 				flags = SM_DONTNEED;
2641 			else
2642 				flags = 0;
2643 			mutex_exit(&rp->r_statelock);
2644 			if (vpm_enable) {
2645 				error = vpm_sync_pages(vp, off, n, flags);
2646 			} else {
2647 				error = segmap_release(segkmap, base, flags);
2648 			}
2649 		} else {
2650 			if (vpm_enable) {
2651 				(void) vpm_sync_pages(vp, off, n, 0);
2652 			} else {
2653 				(void) segmap_release(segkmap, base, 0);
2654 			}
2655 		}
2656 	} while (!error && uiop->uio_resid > 0);
2657 
2658 	return (error);
2659 }
2660 
2661 /* ARGSUSED */
2662 static int
2663 nfs4_write(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2664 		caller_context_t *ct)
2665 {
2666 	rlim64_t limit = uiop->uio_llimit;
2667 	rnode4_t *rp;
2668 	u_offset_t off;
2669 	caddr_t base;
2670 	uint_t flags;
2671 	int remainder;
2672 	size_t n;
2673 	int on;
2674 	int error;
2675 	int resid;
2676 	u_offset_t offset;
2677 	mntinfo4_t *mi;
2678 	uint_t bsize;
2679 
2680 	rp = VTOR4(vp);
2681 
2682 	if (IS_SHADOW(vp, rp))
2683 		vp = RTOV4(rp);
2684 
2685 	if (vp->v_type != VREG)
2686 		return (EISDIR);
2687 
2688 	mi = VTOMI4(vp);
2689 
2690 	if (nfs_zone() != mi->mi_zone)
2691 		return (EIO);
2692 
2693 	if (uiop->uio_resid == 0)
2694 		return (0);
2695 
2696 	mutex_enter(&rp->r_statelock);
2697 	if (rp->r_flags & R4RECOVERRP)
2698 		error = (rp->r_error ? rp->r_error : EIO);
2699 	else
2700 		error = 0;
2701 	mutex_exit(&rp->r_statelock);
2702 	if (error)
2703 		return (error);
2704 
2705 	if (ioflag & FAPPEND) {
2706 		struct vattr va;
2707 
2708 		/*
2709 		 * Must serialize if appending.
2710 		 */
2711 		if (nfs_rw_lock_held(&rp->r_rwlock, RW_READER)) {
2712 			nfs_rw_exit(&rp->r_rwlock);
2713 			if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER,
2714 			    INTR(vp)))
2715 				return (EINTR);
2716 		}
2717 
2718 		va.va_mask = AT_SIZE;
2719 		error = nfs4getattr(vp, &va, cr);
2720 		if (error)
2721 			return (error);
2722 		uiop->uio_loffset = va.va_size;
2723 	}
2724 
2725 	offset = uiop->uio_loffset + uiop->uio_resid;
2726 
2727 	if (uiop->uio_loffset < (offset_t)0 || offset < 0)
2728 		return (EINVAL);
2729 
2730 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
2731 		limit = MAXOFFSET_T;
2732 
2733 	/*
2734 	 * Check to make sure that the process will not exceed
2735 	 * its limit on file size.  It is okay to write up to
2736 	 * the limit, but not beyond.  Thus, the write which
2737 	 * reaches the limit will be short and the next write
2738 	 * will return an error.
2739 	 */
2740 	remainder = 0;
2741 	if (offset > uiop->uio_llimit) {
2742 		remainder = offset - uiop->uio_llimit;
2743 		uiop->uio_resid = uiop->uio_llimit - uiop->uio_loffset;
2744 		if (uiop->uio_resid <= 0) {
2745 			proc_t *p = ttoproc(curthread);
2746 
2747 			uiop->uio_resid += remainder;
2748 			mutex_enter(&p->p_lock);
2749 			(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE],
2750 			    p->p_rctls, p, RCA_UNSAFE_SIGINFO);
2751 			mutex_exit(&p->p_lock);
2752 			return (EFBIG);
2753 		}
2754 	}
2755 
2756 	/* update the change attribute, if we have a write delegation */
2757 
2758 	mutex_enter(&rp->r_statev4_lock);
2759 	if (rp->r_deleg_type == OPEN_DELEGATE_WRITE)
2760 		rp->r_deleg_change++;
2761 
2762 	mutex_exit(&rp->r_statev4_lock);
2763 
2764 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
2765 		return (EINTR);
2766 
2767 	/*
2768 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2769 	 * using client-side direct I/O and the file is not mmap'd and
2770 	 * there are no cached pages.
2771 	 */
2772 	if ((vp->v_flag & VNOCACHE) ||
2773 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2774 	    rp->r_mapcnt == 0 && !nfs4_has_pages(vp))) {
2775 		size_t bufsize;
2776 		int count;
2777 		u_offset_t org_offset;
2778 		stable_how4 stab_comm;
2779 nfs4_fwrite:
2780 		if (rp->r_flags & R4STALE) {
2781 			resid = uiop->uio_resid;
2782 			offset = uiop->uio_loffset;
2783 			error = rp->r_error;
2784 			goto bottom;
2785 		}
2786 
2787 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2788 		base = kmem_alloc(bufsize, KM_SLEEP);
2789 		do {
2790 			if (ioflag & FDSYNC)
2791 				stab_comm = DATA_SYNC4;
2792 			else
2793 				stab_comm = FILE_SYNC4;
2794 			resid = uiop->uio_resid;
2795 			offset = uiop->uio_loffset;
2796 			count = MIN(uiop->uio_resid, bufsize);
2797 			org_offset = uiop->uio_loffset;
2798 			error = uiomove(base, count, UIO_WRITE, uiop);
2799 			if (!error) {
2800 				error = nfs4write(vp, base, org_offset,
2801 						count, cr, &stab_comm);
2802 				if (!error) {
2803 					mutex_enter(&rp->r_statelock);
2804 					if (rp->r_size < uiop->uio_loffset)
2805 						rp->r_size = uiop->uio_loffset;
2806 					mutex_exit(&rp->r_statelock);
2807 				}
2808 			}
2809 		} while (!error && uiop->uio_resid > 0);
2810 		kmem_free(base, bufsize);
2811 		goto bottom;
2812 	}
2813 
2814 	bsize = vp->v_vfsp->vfs_bsize;
2815 
2816 	do {
2817 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2818 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2819 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2820 
2821 		resid = uiop->uio_resid;
2822 		offset = uiop->uio_loffset;
2823 
2824 		if (rp->r_flags & R4STALE) {
2825 			error = rp->r_error;
2826 			break;
2827 		}
2828 
2829 		/*
2830 		 * Don't create dirty pages faster than they
2831 		 * can be cleaned so that the system doesn't
2832 		 * get imbalanced.  If the async queue is
2833 		 * maxed out, then wait for it to drain before
2834 		 * creating more dirty pages.  Also, wait for
2835 		 * any threads doing pagewalks in the vop_getattr
2836 		 * entry points so that they don't block for
2837 		 * long periods.
2838 		 */
2839 		mutex_enter(&rp->r_statelock);
2840 		while ((mi->mi_max_threads != 0 &&
2841 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2842 		    rp->r_gcount > 0)
2843 			cv_wait(&rp->r_cv, &rp->r_statelock);
2844 		mutex_exit(&rp->r_statelock);
2845 
2846 		if (vpm_enable) {
2847 			/*
2848 			 * It will use kpm mappings, so no need to
2849 			 * pass an address.
2850 			 */
2851 			error = writerp4(rp, NULL, n, uiop, 0);
2852 		} else  {
2853 			if (segmap_kpm) {
2854 				int pon = uiop->uio_loffset & PAGEOFFSET;
2855 				size_t pn = MIN(PAGESIZE - pon,
2856 							uiop->uio_resid);
2857 				int pagecreate;
2858 
2859 				mutex_enter(&rp->r_statelock);
2860 				pagecreate = (pon == 0) && (pn == PAGESIZE ||
2861 					uiop->uio_loffset + pn >= rp->r_size);
2862 				mutex_exit(&rp->r_statelock);
2863 
2864 				base = segmap_getmapflt(segkmap, vp, off + on,
2865 						pn, !pagecreate, S_WRITE);
2866 
2867 				error = writerp4(rp, base + pon, n, uiop,
2868 								pagecreate);
2869 
2870 			} else {
2871 				base = segmap_getmapflt(segkmap, vp, off + on,
2872 							n, 0, S_READ);
2873 				error = writerp4(rp, base + on, n, uiop, 0);
2874 			}
2875 		}
2876 
2877 		if (!error) {
2878 			if (mi->mi_flags & MI4_NOAC)
2879 				flags = SM_WRITE;
2880 			else if ((uiop->uio_loffset % bsize) == 0 ||
2881 			    IS_SWAPVP(vp)) {
2882 				/*
2883 				 * Have written a whole block.
2884 				 * Start an asynchronous write
2885 				 * and mark the buffer to
2886 				 * indicate that it won't be
2887 				 * needed again soon.
2888 				 */
2889 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
2890 			} else
2891 				flags = 0;
2892 			if ((ioflag & (FSYNC|FDSYNC)) ||
2893 			    (rp->r_flags & R4OUTOFSPACE)) {
2894 				flags &= ~SM_ASYNC;
2895 				flags |= SM_WRITE;
2896 			}
2897 			if (vpm_enable) {
2898 				error = vpm_sync_pages(vp, off, n, flags);
2899 			} else {
2900 				error = segmap_release(segkmap, base, flags);
2901 			}
2902 		} else {
2903 			if (vpm_enable) {
2904 				(void) vpm_sync_pages(vp, off, n, 0);
2905 			} else {
2906 				(void) segmap_release(segkmap, base, 0);
2907 			}
2908 			/*
2909 			 * In the event that we got an access error while
2910 			 * faulting in a page for a write-only file just
2911 			 * force a write.
2912 			 */
2913 			if (error == EACCES)
2914 				goto nfs4_fwrite;
2915 		}
2916 	} while (!error && uiop->uio_resid > 0);
2917 
2918 bottom:
2919 	if (error) {
2920 		uiop->uio_resid = resid + remainder;
2921 		uiop->uio_loffset = offset;
2922 	} else {
2923 		uiop->uio_resid += remainder;
2924 
2925 		mutex_enter(&rp->r_statev4_lock);
2926 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
2927 			gethrestime(&rp->r_attr.va_mtime);
2928 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
2929 		}
2930 		mutex_exit(&rp->r_statev4_lock);
2931 	}
2932 
2933 	nfs_rw_exit(&rp->r_lkserlock);
2934 
2935 	return (error);
2936 }
2937 
2938 /*
2939  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
2940  */
2941 static int
2942 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
2943 	int flags, cred_t *cr)
2944 {
2945 	struct buf *bp;
2946 	int error;
2947 	page_t *savepp;
2948 	uchar_t fsdata;
2949 	stable_how4 stab_comm;
2950 
2951 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
2952 	bp = pageio_setup(pp, len, vp, flags);
2953 	ASSERT(bp != NULL);
2954 
2955 	/*
2956 	 * pageio_setup should have set b_addr to 0.  This
2957 	 * is correct since we want to do I/O on a page
2958 	 * boundary.  bp_mapin will use this addr to calculate
2959 	 * an offset, and then set b_addr to the kernel virtual
2960 	 * address it allocated for us.
2961 	 */
2962 	ASSERT(bp->b_un.b_addr == 0);
2963 
2964 	bp->b_edev = 0;
2965 	bp->b_dev = 0;
2966 	bp->b_lblkno = lbtodb(off);
2967 	bp->b_file = vp;
2968 	bp->b_offset = (offset_t)off;
2969 	bp_mapin(bp);
2970 
2971 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
2972 	    freemem > desfree)
2973 		stab_comm = UNSTABLE4;
2974 	else
2975 		stab_comm = FILE_SYNC4;
2976 
2977 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
2978 
2979 	bp_mapout(bp);
2980 	pageio_done(bp);
2981 
2982 	if (stab_comm == UNSTABLE4)
2983 		fsdata = C_DELAYCOMMIT;
2984 	else
2985 		fsdata = C_NOCOMMIT;
2986 
2987 	savepp = pp;
2988 	do {
2989 		pp->p_fsdata = fsdata;
2990 	} while ((pp = pp->p_next) != savepp);
2991 
2992 	return (error);
2993 }
2994 
2995 /*
2996  */
2997 static int
2998 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
2999 {
3000 	nfs4_open_owner_t	*oop;
3001 	nfs4_open_stream_t	*osp;
3002 	rnode4_t		*rp = VTOR4(vp);
3003 	mntinfo4_t 		*mi = VTOMI4(vp);
3004 	int 			reopen_needed;
3005 
3006 	ASSERT(nfs_zone() == mi->mi_zone);
3007 
3008 
3009 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
3010 	if (!oop)
3011 		return (EIO);
3012 
3013 	/* returns with 'os_sync_lock' held */
3014 	osp = find_open_stream(oop, rp);
3015 	if (!osp) {
3016 		open_owner_rele(oop);
3017 		return (EIO);
3018 	}
3019 
3020 	if (osp->os_failed_reopen) {
3021 		mutex_exit(&osp->os_sync_lock);
3022 		open_stream_rele(osp, rp);
3023 		open_owner_rele(oop);
3024 		return (EIO);
3025 	}
3026 
3027 	/*
3028 	 * Determine whether a reopen is needed.  If this
3029 	 * is a delegation open stream, then the os_delegation bit
3030 	 * should be set.
3031 	 */
3032 
3033 	reopen_needed = osp->os_delegation;
3034 
3035 	mutex_exit(&osp->os_sync_lock);
3036 	open_owner_rele(oop);
3037 
3038 	if (reopen_needed) {
3039 		nfs4_error_zinit(ep);
3040 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
3041 		mutex_enter(&osp->os_sync_lock);
3042 		if (ep->error || ep->stat || osp->os_failed_reopen) {
3043 			mutex_exit(&osp->os_sync_lock);
3044 			open_stream_rele(osp, rp);
3045 			return (EIO);
3046 		}
3047 		mutex_exit(&osp->os_sync_lock);
3048 	}
3049 	open_stream_rele(osp, rp);
3050 
3051 	return (0);
3052 }
3053 
3054 /*
3055  * Write to file.  Writes to remote server in largest size
3056  * chunks that the server can handle.  Write is synchronous.
3057  */
3058 static int
3059 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3060 	stable_how4 *stab_comm)
3061 {
3062 	mntinfo4_t *mi;
3063 	COMPOUND4args_clnt args;
3064 	COMPOUND4res_clnt res;
3065 	WRITE4args *wargs;
3066 	WRITE4res *wres;
3067 	nfs_argop4 argop[2];
3068 	nfs_resop4 *resop;
3069 	int tsize;
3070 	stable_how4 stable;
3071 	rnode4_t *rp;
3072 	int doqueue = 1;
3073 	bool_t needrecov;
3074 	nfs4_recov_state_t recov_state;
3075 	nfs4_stateid_types_t sid_types;
3076 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3077 
3078 	rp = VTOR4(vp);
3079 	mi = VTOMI4(vp);
3080 
3081 	ASSERT(nfs_zone() == mi->mi_zone);
3082 
3083 	stable = *stab_comm;
3084 	*stab_comm = FILE_SYNC4;
3085 
3086 	needrecov = FALSE;
3087 	recov_state.rs_flags = 0;
3088 	recov_state.rs_num_retry_despite_err = 0;
3089 	nfs4_init_stateid_types(&sid_types);
3090 
3091 recov_retry:
3092 	args.ctag = TAG_WRITE;
3093 	args.array_len = 2;
3094 	args.array = argop;
3095 
3096 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3097 			    &recov_state, NULL);
3098 	if (e.error)
3099 		return (e.error);
3100 
3101 	/* 0. putfh target fh */
3102 	argop[0].argop = OP_CPUTFH;
3103 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3104 
3105 	/* 1. write */
3106 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3107 
3108 	do {
3109 
3110 		wargs->offset = (offset4)offset;
3111 		wargs->data_val = base;
3112 
3113 		if (mi->mi_io_kstats) {
3114 			mutex_enter(&mi->mi_lock);
3115 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3116 			mutex_exit(&mi->mi_lock);
3117 		}
3118 
3119 		if ((vp->v_flag & VNOCACHE) ||
3120 		    (rp->r_flags & R4DIRECTIO) ||
3121 		    (mi->mi_flags & MI4_DIRECTIO))
3122 			tsize = MIN(mi->mi_stsize, count);
3123 		else
3124 			tsize = MIN(mi->mi_curwrite, count);
3125 		wargs->data_len = (uint_t)tsize;
3126 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3127 
3128 		if (mi->mi_io_kstats) {
3129 			mutex_enter(&mi->mi_lock);
3130 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3131 			mutex_exit(&mi->mi_lock);
3132 		}
3133 
3134 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3135 		if (e.error && !needrecov) {
3136 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3137 				&recov_state, needrecov);
3138 			return (e.error);
3139 		}
3140 
3141 
3142 		/*
3143 		 * Do handling of OLD_STATEID outside
3144 		 * of the normal recovery framework.
3145 		 *
3146 		 * If write receives a BAD stateid error while using a
3147 		 * delegation stateid, retry using the open stateid (if it
3148 		 * exists).  If it doesn't have an open stateid, reopen the
3149 		 * file first, then retry.
3150 		 */
3151 		if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3152 		    sid_types.cur_sid_type != SPEC_SID) {
3153 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3154 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3155 				&recov_state, needrecov);
3156 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3157 			goto recov_retry;
3158 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3159 			    sid_types.cur_sid_type == DEL_SID) {
3160 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3161 			mutex_enter(&rp->r_statev4_lock);
3162 			rp->r_deleg_return_pending = TRUE;
3163 			mutex_exit(&rp->r_statev4_lock);
3164 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3165 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3166 					&recov_state, needrecov);
3167 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3168 								(caddr_t)&res);
3169 				return (EIO);
3170 			}
3171 			nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3172 				&recov_state, needrecov);
3173 			/* hold needed for nfs4delegreturn_thread */
3174 			VN_HOLD(vp);
3175 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3176 				NFS4_DR_DISCARD), FALSE);
3177 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3178 			goto recov_retry;
3179 		}
3180 
3181 		if (needrecov) {
3182 			bool_t abort;
3183 
3184 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3185 				"nfs4write: client got error %d, res.status %d"
3186 				", so start recovery", e.error, res.status));
3187 
3188 			abort = nfs4_start_recovery(&e,
3189 				    VTOMI4(vp), vp, NULL, &wargs->stateid,
3190 				    NULL, OP_WRITE, NULL);
3191 			if (!e.error) {
3192 				e.error = geterrno4(res.status);
3193 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3194 								(caddr_t)&res);
3195 			}
3196 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3197 				&recov_state, needrecov);
3198 			if (abort == FALSE)
3199 				goto recov_retry;
3200 			return (e.error);
3201 		}
3202 
3203 		if (res.status) {
3204 			e.error = geterrno4(res.status);
3205 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3206 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3207 				&recov_state, needrecov);
3208 			return (e.error);
3209 		}
3210 
3211 		resop = &res.array[1];	/* write res */
3212 		wres = &resop->nfs_resop4_u.opwrite;
3213 
3214 		if ((int)wres->count > tsize) {
3215 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3216 
3217 			zcmn_err(getzoneid(), CE_WARN,
3218 			"nfs4write: server wrote %u, requested was %u",
3219 			    (int)wres->count, tsize);
3220 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3221 				&recov_state, needrecov);
3222 			return (EIO);
3223 		}
3224 		if (wres->committed == UNSTABLE4) {
3225 			*stab_comm = UNSTABLE4;
3226 			if (wargs->stable == DATA_SYNC4 ||
3227 			    wargs->stable == FILE_SYNC4) {
3228 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3229 								(caddr_t)&res);
3230 				zcmn_err(getzoneid(), CE_WARN,
3231 					"nfs4write: server %s did not commit "
3232 					"to stable storage",
3233 					rp->r_server->sv_hostname);
3234 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3235 						&recov_state, needrecov);
3236 				return (EIO);
3237 			}
3238 		}
3239 
3240 		tsize = (int)wres->count;
3241 		count -= tsize;
3242 		base += tsize;
3243 		offset += tsize;
3244 		if (mi->mi_io_kstats) {
3245 			mutex_enter(&mi->mi_lock);
3246 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3247 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3248 			    tsize;
3249 			mutex_exit(&mi->mi_lock);
3250 		}
3251 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3252 		mutex_enter(&rp->r_statelock);
3253 		if (rp->r_flags & R4HAVEVERF) {
3254 			if (rp->r_writeverf != wres->writeverf) {
3255 				nfs4_set_mod(vp);
3256 				rp->r_writeverf = wres->writeverf;
3257 			}
3258 		} else {
3259 			rp->r_writeverf = wres->writeverf;
3260 			rp->r_flags |= R4HAVEVERF;
3261 		}
3262 		PURGE_ATTRCACHE4_LOCKED(rp);
3263 		rp->r_flags |= R4WRITEMODIFIED;
3264 		gethrestime(&rp->r_attr.va_mtime);
3265 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3266 		mutex_exit(&rp->r_statelock);
3267 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3268 	} while (count);
3269 
3270 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state, needrecov);
3271 
3272 	return (e.error);
3273 }
3274 
3275 /*
3276  * Read from a file.  Reads data in largest chunks our interface can handle.
3277  */
3278 static int
3279 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3280 	size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3281 {
3282 	mntinfo4_t *mi;
3283 	COMPOUND4args_clnt args;
3284 	COMPOUND4res_clnt res;
3285 	READ4args *rargs;
3286 	nfs_argop4 argop[2];
3287 	int tsize;
3288 	int doqueue;
3289 	rnode4_t *rp;
3290 	int data_len;
3291 	bool_t is_eof;
3292 	bool_t needrecov = FALSE;
3293 	nfs4_recov_state_t recov_state;
3294 	nfs4_stateid_types_t sid_types;
3295 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3296 
3297 	rp = VTOR4(vp);
3298 	mi = VTOMI4(vp);
3299 	doqueue = 1;
3300 
3301 	ASSERT(nfs_zone() == mi->mi_zone);
3302 
3303 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3304 
3305 	args.array_len = 2;
3306 	args.array = argop;
3307 
3308 	nfs4_init_stateid_types(&sid_types);
3309 
3310 	recov_state.rs_flags = 0;
3311 	recov_state.rs_num_retry_despite_err = 0;
3312 
3313 recov_retry:
3314 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3315 			    &recov_state, NULL);
3316 	if (e.error)
3317 		return (e.error);
3318 
3319 	/* putfh target fh */
3320 	argop[0].argop = OP_CPUTFH;
3321 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3322 
3323 	/* read */
3324 	argop[1].argop = OP_READ;
3325 	rargs = &argop[1].nfs_argop4_u.opread;
3326 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3327 				OP_READ, &sid_types, async);
3328 
3329 	do {
3330 		if (mi->mi_io_kstats) {
3331 			mutex_enter(&mi->mi_lock);
3332 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3333 			mutex_exit(&mi->mi_lock);
3334 		}
3335 
3336 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3337 		    "nfs4read: %s call, rp %s",
3338 		    needrecov ? "recov" : "first",
3339 		    rnode4info(rp)));
3340 
3341 		if ((vp->v_flag & VNOCACHE) ||
3342 		    (rp->r_flags & R4DIRECTIO) ||
3343 		    (mi->mi_flags & MI4_DIRECTIO))
3344 			tsize = MIN(mi->mi_tsize, count);
3345 		else
3346 			tsize = MIN(mi->mi_curread, count);
3347 		rargs->offset = (offset4)offset;
3348 		rargs->count = (count4)tsize;
3349 		rargs->res_data_val_alt = NULL;
3350 		rargs->res_mblk = NULL;
3351 		rargs->res_uiop = NULL;
3352 		rargs->res_maxsize = 0;
3353 		if (uiop)
3354 			rargs->res_uiop = uiop;
3355 		else
3356 			rargs->res_data_val_alt = base;
3357 		rargs->res_maxsize = tsize;
3358 
3359 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3360 #ifdef	DEBUG
3361 		if (nfs4read_error_inject) {
3362 			res.status = nfs4read_error_inject;
3363 			nfs4read_error_inject = 0;
3364 		}
3365 #endif
3366 
3367 		if (mi->mi_io_kstats) {
3368 			mutex_enter(&mi->mi_lock);
3369 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3370 			mutex_exit(&mi->mi_lock);
3371 		}
3372 
3373 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3374 		if (e.error != 0 && !needrecov) {
3375 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3376 				&recov_state, needrecov);
3377 			return (e.error);
3378 		}
3379 
3380 		/*
3381 		 * Do proper retry for OLD and BAD stateid errors outside
3382 		 * of the normal recovery framework.  There are two differences
3383 		 * between async and sync reads.  The first is that we allow
3384 		 * retry on BAD_STATEID for async reads, but not sync reads.
3385 		 * The second is that we mark the file dead for a failed
3386 		 * attempt with a special stateid for sync reads, but just
3387 		 * return EIO for async reads.
3388 		 *
3389 		 * If a sync read receives a BAD stateid error while using a
3390 		 * delegation stateid, retry using the open stateid (if it
3391 		 * exists).  If it doesn't have an open stateid, reopen the
3392 		 * file first, then retry.
3393 		 */
3394 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3395 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3396 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3397 				&recov_state, needrecov);
3398 			if (sid_types.cur_sid_type == SPEC_SID) {
3399 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3400 						(caddr_t)&res);
3401 				return (EIO);
3402 			}
3403 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3404 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3405 			goto recov_retry;
3406 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3407 			    !async && sid_types.cur_sid_type != SPEC_SID) {
3408 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3409 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3410 				&recov_state, needrecov);
3411 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3412 			goto recov_retry;
3413 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3414 			    sid_types.cur_sid_type == DEL_SID) {
3415 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3416 			mutex_enter(&rp->r_statev4_lock);
3417 			rp->r_deleg_return_pending = TRUE;
3418 			mutex_exit(&rp->r_statev4_lock);
3419 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3420 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3421 					&recov_state, needrecov);
3422 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3423 				    (caddr_t)&res);
3424 				return (EIO);
3425 			}
3426 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3427 				&recov_state, needrecov);
3428 			/* hold needed for nfs4delegreturn_thread */
3429 			VN_HOLD(vp);
3430 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3431 				NFS4_DR_DISCARD), FALSE);
3432 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3433 			goto recov_retry;
3434 		}
3435 		if (needrecov) {
3436 			bool_t abort;
3437 
3438 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3439 			    "nfs4read: initiating recovery\n"));
3440 
3441 			abort = nfs4_start_recovery(&e,
3442 				    mi, vp, NULL, &rargs->stateid,
3443 				    NULL, OP_READ, NULL);
3444 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3445 				&recov_state, needrecov);
3446 			/*
3447 			 * Do not retry if we got OLD_STATEID using a special
3448 			 * stateid.  This avoids looping with a broken server.
3449 			 */
3450 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3451 			    sid_types.cur_sid_type == SPEC_SID)
3452 				abort = TRUE;
3453 
3454 			if (abort == FALSE) {
3455 				/*
3456 				 * Need to retry all possible stateids in
3457 				 * case the recovery error wasn't stateid
3458 				 * related or the stateids have become
3459 				 * stale (server reboot).
3460 				 */
3461 				nfs4_init_stateid_types(&sid_types);
3462 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3463 						(caddr_t)&res);
3464 				goto recov_retry;
3465 			}
3466 
3467 			if (!e.error) {
3468 				e.error = geterrno4(res.status);
3469 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3470 						(caddr_t)&res);
3471 			}
3472 			return (e.error);
3473 		}
3474 
3475 		if (res.status) {
3476 			e.error = geterrno4(res.status);
3477 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3478 				&recov_state, needrecov);
3479 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3480 			return (e.error);
3481 		}
3482 
3483 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3484 		count -= data_len;
3485 		if (base)
3486 			base += data_len;
3487 		offset += data_len;
3488 		if (mi->mi_io_kstats) {
3489 			mutex_enter(&mi->mi_lock);
3490 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3491 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3492 			mutex_exit(&mi->mi_lock);
3493 		}
3494 		lwp_stat_update(LWP_STAT_INBLK, 1);
3495 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3496 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3497 
3498 	} while (count && !is_eof);
3499 
3500 	*residp = count;
3501 
3502 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3503 
3504 	return (e.error);
3505 }
3506 
3507 /* ARGSUSED */
3508 static int
3509 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp)
3510 {
3511 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3512 		return (EIO);
3513 	switch (cmd) {
3514 		case _FIODIRECTIO:
3515 			return (nfs4_directio(vp, (int)arg, cr));
3516 		default:
3517 			return (ENOTTY);
3518 	}
3519 }
3520 
3521 static int
3522 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr)
3523 {
3524 	int error;
3525 	rnode4_t *rp = VTOR4(vp);
3526 
3527 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3528 		return (EIO);
3529 	/*
3530 	 * If it has been specified that the return value will
3531 	 * just be used as a hint, and we are only being asked
3532 	 * for size, fsid or rdevid, then return the client's
3533 	 * notion of these values without checking to make sure
3534 	 * that the attribute cache is up to date.
3535 	 * The whole point is to avoid an over the wire GETATTR
3536 	 * call.
3537 	 */
3538 	if (flags & ATTR_HINT) {
3539 		if (vap->va_mask ==
3540 		    (vap->va_mask & (AT_SIZE | AT_FSID | AT_RDEV))) {
3541 			mutex_enter(&rp->r_statelock);
3542 			if (vap->va_mask | AT_SIZE)
3543 				vap->va_size = rp->r_size;
3544 			if (vap->va_mask | AT_FSID)
3545 				vap->va_fsid = rp->r_attr.va_fsid;
3546 			if (vap->va_mask | AT_RDEV)
3547 				vap->va_rdev = rp->r_attr.va_rdev;
3548 			mutex_exit(&rp->r_statelock);
3549 			return (0);
3550 		}
3551 	}
3552 
3553 	/*
3554 	 * Only need to flush pages if asking for the mtime
3555 	 * and if there any dirty pages or any outstanding
3556 	 * asynchronous (write) requests for this file.
3557 	 */
3558 	if (vap->va_mask & AT_MTIME) {
3559 		rp = VTOR4(vp);
3560 		if (nfs4_has_pages(vp)) {
3561 			mutex_enter(&rp->r_statev4_lock);
3562 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3563 				mutex_exit(&rp->r_statev4_lock);
3564 				if (rp->r_flags & R4DIRTY ||
3565 				    rp->r_awcount > 0) {
3566 					mutex_enter(&rp->r_statelock);
3567 					rp->r_gcount++;
3568 					mutex_exit(&rp->r_statelock);
3569 					error =
3570 						nfs4_putpage(vp, (u_offset_t)0,
3571 								0, 0, cr);
3572 					mutex_enter(&rp->r_statelock);
3573 					if (error && (error == ENOSPC ||
3574 							error == EDQUOT)) {
3575 						if (!rp->r_error)
3576 							rp->r_error = error;
3577 					}
3578 					if (--rp->r_gcount == 0)
3579 						cv_broadcast(&rp->r_cv);
3580 					mutex_exit(&rp->r_statelock);
3581 				}
3582 			} else {
3583 				mutex_exit(&rp->r_statev4_lock);
3584 			}
3585 		}
3586 	}
3587 	return (nfs4getattr(vp, vap, cr));
3588 }
3589 
3590 int
3591 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3592 {
3593 	/*
3594 	 * If these are the only two bits cleared
3595 	 * on the server then return 0 (OK) else
3596 	 * return 1 (BAD).
3597 	 */
3598 	on_client &= ~(S_ISUID|S_ISGID);
3599 	if (on_client == from_server)
3600 		return (0);
3601 	else
3602 		return (1);
3603 }
3604 
3605 /*ARGSUSED4*/
3606 static int
3607 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3608 		caller_context_t *ct)
3609 {
3610 	if (vap->va_mask & AT_NOSET)
3611 		return (EINVAL);
3612 
3613 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3614 		return (EIO);
3615 
3616 	/*
3617 	 * Don't call secpolicy_vnode_setattr, the client cannot
3618 	 * use its cached attributes to make security decisions
3619 	 * as the server may be faking mode bits or mapping uid/gid.
3620 	 * Always just let the server to the checking.
3621 	 * If we provide the ability to remove basic priviledges
3622 	 * to setattr (e.g. basic without chmod) then we will
3623 	 * need to add a check here before calling the server.
3624 	 */
3625 
3626 	return (nfs4setattr(vp, vap, flags, cr, NULL));
3627 }
3628 
3629 /*
3630  * To replace the "guarded" version 3 setattr, we use two types of compound
3631  * setattr requests:
3632  * 1. The "normal" setattr, used when the size of the file isn't being
3633  *    changed - { Putfh <fh>; Setattr; Getattr }/
3634  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3635  *    with only ctime as the argument. If the server ctime differs from
3636  *    what is cached on the client, the verify will fail, but we would
3637  *    already have the ctime from the preceding getattr, so just set it
3638  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3639  *	Setattr; Getattr }.
3640  *
3641  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3642  * this setattr and NULL if they are not.
3643  */
3644 static int
3645 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3646 		vsecattr_t *vsap)
3647 {
3648 	COMPOUND4args_clnt args;
3649 	COMPOUND4res_clnt res, *resp = NULL;
3650 	nfs4_ga_res_t *garp = NULL;
3651 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3652 	nfs_argop4 argop[5];
3653 	int verify_argop = -1;
3654 	int setattr_argop = 1;
3655 	nfs_resop4 *resop;
3656 	vattr_t va;
3657 	rnode4_t *rp;
3658 	int doqueue = 1;
3659 	uint_t mask = vap->va_mask;
3660 	mode_t omode;
3661 	vsecattr_t *vsp;
3662 	timestruc_t ctime;
3663 	bool_t needrecov = FALSE;
3664 	nfs4_recov_state_t recov_state;
3665 	nfs4_stateid_types_t sid_types;
3666 	stateid4 stateid;
3667 	hrtime_t t;
3668 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3669 	servinfo4_t *svp;
3670 	bitmap4 supp_attrs;
3671 
3672 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3673 	rp = VTOR4(vp);
3674 	nfs4_init_stateid_types(&sid_types);
3675 
3676 	/*
3677 	 * Only need to flush pages if there are any pages and
3678 	 * if the file is marked as dirty in some fashion.  The
3679 	 * file must be flushed so that we can accurately
3680 	 * determine the size of the file and the cached data
3681 	 * after the SETATTR returns.  A file is considered to
3682 	 * be dirty if it is either marked with R4DIRTY, has
3683 	 * outstanding i/o's active, or is mmap'd.  In this
3684 	 * last case, we can't tell whether there are dirty
3685 	 * pages, so we flush just to be sure.
3686 	 */
3687 	if (nfs4_has_pages(vp) &&
3688 	    ((rp->r_flags & R4DIRTY) ||
3689 	    rp->r_count > 0 ||
3690 	    rp->r_mapcnt > 0)) {
3691 		ASSERT(vp->v_type != VCHR);
3692 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr);
3693 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3694 			mutex_enter(&rp->r_statelock);
3695 			if (!rp->r_error)
3696 				rp->r_error = e.error;
3697 			mutex_exit(&rp->r_statelock);
3698 		}
3699 	}
3700 
3701 	if (mask & AT_SIZE) {
3702 		/*
3703 		 * Verification setattr compound for non-deleg AT_SIZE:
3704 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3705 		 * Set ctime local here (outside the do_again label)
3706 		 * so that subsequent retries (after failed VERIFY)
3707 		 * will use ctime from GETATTR results (from failed
3708 		 * verify compound) as VERIFY arg.
3709 		 * If file has delegation, then VERIFY(time_metadata)
3710 		 * is of little added value, so don't bother.
3711 		 */
3712 		mutex_enter(&rp->r_statev4_lock);
3713 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3714 						rp->r_deleg_return_pending) {
3715 			numops = 5;
3716 			ctime = rp->r_attr.va_ctime;
3717 		}
3718 		mutex_exit(&rp->r_statev4_lock);
3719 	}
3720 
3721 	recov_state.rs_flags = 0;
3722 	recov_state.rs_num_retry_despite_err = 0;
3723 
3724 	args.ctag = TAG_SETATTR;
3725 do_again:
3726 recov_retry:
3727 	setattr_argop = numops - 2;
3728 
3729 	args.array = argop;
3730 	args.array_len = numops;
3731 
3732 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3733 	if (e.error)
3734 		return (e.error);
3735 
3736 
3737 	/* putfh target fh */
3738 	argop[0].argop = OP_CPUTFH;
3739 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3740 
3741 	if (numops == 5) {
3742 		/*
3743 		 * We only care about the ctime, but need to get mtime
3744 		 * and size for proper cache update.
3745 		 */
3746 		/* getattr */
3747 		argop[1].argop = OP_GETATTR;
3748 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3749 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3750 
3751 		/* verify - set later in loop */
3752 		verify_argop = 2;
3753 	}
3754 
3755 	/* setattr */
3756 	svp = rp->r_server;
3757 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3758 	supp_attrs = svp->sv_supp_attrs;
3759 	nfs_rw_exit(&svp->sv_lock);
3760 
3761 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3762 		supp_attrs, &e.error, &sid_types);
3763 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3764 	if (e.error) {
3765 		/* req time field(s) overflow - return immediately */
3766 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3767 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3768 						opsetattr.obj_attributes);
3769 		return (e.error);
3770 	}
3771 	omode = rp->r_attr.va_mode;
3772 
3773 	/* getattr */
3774 	argop[numops-1].argop = OP_GETATTR;
3775 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3776 	/*
3777 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3778 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3779 	 * used in updating the ACL cache.
3780 	 */
3781 	if (vsap != NULL)
3782 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3783 		    FATTR4_ACL_MASK;
3784 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3785 
3786 	/*
3787 	 * setattr iterates if the object size is set and the cached ctime
3788 	 * does not match the file ctime. In that case, verify the ctime first.
3789 	 */
3790 
3791 	do {
3792 		if (verify_argop != -1) {
3793 			/*
3794 			 * Verify that the ctime match before doing setattr.
3795 			 */
3796 			va.va_mask = AT_CTIME;
3797 			va.va_ctime = ctime;
3798 			svp = rp->r_server;
3799 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3800 			supp_attrs = svp->sv_supp_attrs;
3801 			nfs_rw_exit(&svp->sv_lock);
3802 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3803 					OP_VERIFY, supp_attrs);
3804 			if (e.error) {
3805 				/* req time field(s) overflow - return */
3806 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3807 					needrecov);
3808 				break;
3809 			}
3810 		}
3811 
3812 		doqueue = 1;
3813 
3814 		t = gethrtime();
3815 
3816 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3817 
3818 		/*
3819 		 * Purge the access cache and ACL cache if changing either the
3820 		 * owner of the file, the group owner, or the mode.  These may
3821 		 * change the access permissions of the file, so purge old
3822 		 * information and start over again.
3823 		 */
3824 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3825 			(void) nfs4_access_purge_rp(rp);
3826 			if (rp->r_secattr != NULL) {
3827 				mutex_enter(&rp->r_statelock);
3828 				vsp = rp->r_secattr;
3829 				rp->r_secattr = NULL;
3830 				mutex_exit(&rp->r_statelock);
3831 				if (vsp != NULL)
3832 					nfs4_acl_free_cache(vsp);
3833 			}
3834 		}
3835 
3836 		/*
3837 		 * If res.array_len == numops, then everything succeeded,
3838 		 * except for possibly the final getattr.  If only the
3839 		 * last getattr failed, give up, and don't try recovery.
3840 		 */
3841 		if (res.array_len == numops) {
3842 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3843 			    needrecov);
3844 			if (! e.error)
3845 				resp = &res;
3846 			break;
3847 		}
3848 
3849 		/*
3850 		 * if either rpc call failed or completely succeeded - done
3851 		 */
3852 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
3853 		if (e.error) {
3854 			PURGE_ATTRCACHE4(vp);
3855 			if (!needrecov) {
3856 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3857 				    needrecov);
3858 				break;
3859 			}
3860 		}
3861 
3862 		/*
3863 		 * Do proper retry for OLD_STATEID outside of the normal
3864 		 * recovery framework.
3865 		 */
3866 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3867 		    sid_types.cur_sid_type != SPEC_SID &&
3868 		    sid_types.cur_sid_type != NO_SID) {
3869 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3870 				    needrecov);
3871 			nfs4_save_stateid(&stateid, &sid_types);
3872 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3873 						opsetattr.obj_attributes);
3874 			if (verify_argop != -1) {
3875 				nfs4args_verify_free(&argop[verify_argop]);
3876 				verify_argop = -1;
3877 			}
3878 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3879 			goto recov_retry;
3880 		}
3881 
3882 		if (needrecov) {
3883 			bool_t abort;
3884 
3885 			abort = nfs4_start_recovery(&e,
3886 				    VTOMI4(vp), vp, NULL, NULL, NULL,
3887 				    OP_SETATTR, NULL);
3888 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3889 				    needrecov);
3890 			/*
3891 			 * Do not retry if we failed with OLD_STATEID using
3892 			 * a special stateid.  This is done to avoid looping
3893 			 * with a broken server.
3894 			 */
3895 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3896 			    (sid_types.cur_sid_type == SPEC_SID ||
3897 			    sid_types.cur_sid_type == NO_SID))
3898 				abort = TRUE;
3899 			if (!e.error) {
3900 				if (res.status == NFS4ERR_BADOWNER)
3901 					nfs4_log_badowner(VTOMI4(vp),
3902 					    OP_SETATTR);
3903 
3904 				e.error = geterrno4(res.status);
3905 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3906 								(caddr_t)&res);
3907 			}
3908 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3909 						opsetattr.obj_attributes);
3910 			if (verify_argop != -1) {
3911 				nfs4args_verify_free(&argop[verify_argop]);
3912 				verify_argop = -1;
3913 			}
3914 			if (abort == FALSE) {
3915 				/*
3916 				 * Need to retry all possible stateids in
3917 				 * case the recovery error wasn't stateid
3918 				 * related or the stateids have become
3919 				 * stale (server reboot).
3920 				 */
3921 				nfs4_init_stateid_types(&sid_types);
3922 				goto recov_retry;
3923 			}
3924 			return (e.error);
3925 		}
3926 
3927 		/*
3928 		 * Need to call nfs4_end_op before nfs4getattr to
3929 		 * avoid potential nfs4_start_op deadlock. See RFE
3930 		 * 4777612.  Calls to nfs4_invalidate_pages() and
3931 		 * nfs4_purge_stale_fh() might also generate over the
3932 		 * wire calls which my cause nfs4_start_op() deadlock.
3933 		 */
3934 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3935 
3936 		/*
3937 		 * Check to update lease.
3938 		 */
3939 		resp = &res;
3940 		if (res.status == NFS4_OK) {
3941 			break;
3942 		}
3943 
3944 		/*
3945 		 * Check if verify failed to see if try again
3946 		 */
3947 		if ((verify_argop == -1) || (res.array_len != 3)) {
3948 			/*
3949 			 * can't continue...
3950 			 */
3951 			if (res.status == NFS4ERR_BADOWNER)
3952 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
3953 
3954 			e.error = geterrno4(res.status);
3955 		} else {
3956 			/*
3957 			 * When the verify request fails, the client ctime is
3958 			 * not in sync with the server. This is the same as
3959 			 * the version 3 "not synchronized" error, and we
3960 			 * handle it in a similar manner (XXX do we need to???).
3961 			 * Use the ctime returned in the first getattr for
3962 			 * the input to the next verify.
3963 			 * If we couldn't get the attributes, then we give up
3964 			 * because we can't complete the operation as required.
3965 			 */
3966 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
3967 		}
3968 		if (e.error) {
3969 			PURGE_ATTRCACHE4(vp);
3970 			nfs4_purge_stale_fh(e.error, vp, cr);
3971 		} else {
3972 			/*
3973 			 * retry with a new verify value
3974 			 */
3975 			ctime = garp->n4g_va.va_ctime;
3976 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3977 			resp = NULL;
3978 		}
3979 		if (!e.error) {
3980 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3981 						opsetattr.obj_attributes);
3982 			if (verify_argop != -1) {
3983 				nfs4args_verify_free(&argop[verify_argop]);
3984 				verify_argop = -1;
3985 			}
3986 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3987 			goto do_again;
3988 		}
3989 	} while (!e.error);
3990 
3991 	if (e.error) {
3992 		/*
3993 		 * If we are here, rfs4call has an irrecoverable error - return
3994 		 */
3995 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3996 						opsetattr.obj_attributes);
3997 		if (verify_argop != -1) {
3998 			nfs4args_verify_free(&argop[verify_argop]);
3999 			verify_argop = -1;
4000 		}
4001 		if (resp)
4002 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4003 		return (e.error);
4004 	}
4005 
4006 
4007 
4008 	/*
4009 	 * If changing the size of the file, invalidate
4010 	 * any local cached data which is no longer part
4011 	 * of the file.  We also possibly invalidate the
4012 	 * last page in the file.  We could use
4013 	 * pvn_vpzero(), but this would mark the page as
4014 	 * modified and require it to be written back to
4015 	 * the server for no particularly good reason.
4016 	 * This way, if we access it, then we bring it
4017 	 * back in.  A read should be cheaper than a
4018 	 * write.
4019 	 */
4020 	if (mask & AT_SIZE) {
4021 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
4022 	}
4023 
4024 	/* either no error or one of the postop getattr failed */
4025 
4026 	/*
4027 	 * XXX Perform a simplified version of wcc checking. Instead of
4028 	 * have another getattr to get pre-op, just purge cache if
4029 	 * any of the ops prior to and including the getattr failed.
4030 	 * If the getattr succeeded then update the attrcache accordingly.
4031 	 */
4032 
4033 	garp = NULL;
4034 	if (res.status == NFS4_OK) {
4035 		/*
4036 		 * Last getattr
4037 		 */
4038 		resop = &res.array[numops - 1];
4039 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4040 	}
4041 	/*
4042 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
4043 	 * rather than filling it.  See the function itself for details.
4044 	 */
4045 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4046 	if (garp != NULL) {
4047 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
4048 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
4049 			vs_ace4_destroy(&garp->n4g_vsa);
4050 		} else {
4051 			if (vsap != NULL) {
4052 				/*
4053 				 * The ACL was supposed to be set and to be
4054 				 * returned in the last getattr of this
4055 				 * compound, but for some reason the getattr
4056 				 * result doesn't contain the ACL.  In this
4057 				 * case, purge the ACL cache.
4058 				 */
4059 				if (rp->r_secattr != NULL) {
4060 					mutex_enter(&rp->r_statelock);
4061 					vsp = rp->r_secattr;
4062 					rp->r_secattr = NULL;
4063 					mutex_exit(&rp->r_statelock);
4064 					if (vsp != NULL)
4065 						nfs4_acl_free_cache(vsp);
4066 				}
4067 			}
4068 		}
4069 	}
4070 
4071 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4072 		/*
4073 		 * Set the size, rather than relying on getting it updated
4074 		 * via a GETATTR.  With delegations the client tries to
4075 		 * suppress GETATTR calls.
4076 		 */
4077 		mutex_enter(&rp->r_statelock);
4078 		rp->r_size = vap->va_size;
4079 		mutex_exit(&rp->r_statelock);
4080 	}
4081 
4082 	/*
4083 	 * Can free up request args and res
4084 	 */
4085 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4086 						opsetattr.obj_attributes);
4087 	if (verify_argop != -1) {
4088 		nfs4args_verify_free(&argop[verify_argop]);
4089 		verify_argop = -1;
4090 	}
4091 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4092 
4093 	/*
4094 	 * Some servers will change the mode to clear the setuid
4095 	 * and setgid bits when changing the uid or gid.  The
4096 	 * client needs to compensate appropriately.
4097 	 */
4098 	if (mask & (AT_UID | AT_GID)) {
4099 		int terror, do_setattr;
4100 
4101 		do_setattr = 0;
4102 		va.va_mask = AT_MODE;
4103 		terror = nfs4getattr(vp, &va, cr);
4104 		if (!terror &&
4105 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4106 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4107 			va.va_mask = AT_MODE;
4108 			if (mask & AT_MODE) {
4109 				/*
4110 				 * We asked the mode to be changed and what
4111 				 * we just got from the server in getattr is
4112 				 * not what we wanted it to be, so set it now.
4113 				 */
4114 				va.va_mode = vap->va_mode;
4115 				do_setattr = 1;
4116 			} else {
4117 				/*
4118 				 * We did not ask the mode to be changed,
4119 				 * Check to see that the server just cleared
4120 				 * I_SUID and I_GUID from it. If not then
4121 				 * set mode to omode with UID/GID cleared.
4122 				 */
4123 				if (nfs4_compare_modes(va.va_mode, omode)) {
4124 					omode &= ~(S_ISUID|S_ISGID);
4125 					va.va_mode = omode;
4126 					do_setattr = 1;
4127 				}
4128 			}
4129 
4130 			if (do_setattr)
4131 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4132 		}
4133 	}
4134 
4135 	return (e.error);
4136 }
4137 
4138 /* ARGSUSED */
4139 static int
4140 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr)
4141 {
4142 	COMPOUND4args_clnt args;
4143 	COMPOUND4res_clnt res;
4144 	int doqueue;
4145 	uint32_t acc, resacc, argacc;
4146 	rnode4_t *rp;
4147 	cred_t *cred, *ncr, *ncrfree = NULL;
4148 	nfs4_access_type_t cacc;
4149 	int num_ops;
4150 	nfs_argop4 argop[3];
4151 	nfs_resop4 *resop;
4152 	bool_t needrecov = FALSE, do_getattr;
4153 	nfs4_recov_state_t recov_state;
4154 	int rpc_error;
4155 	hrtime_t t;
4156 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4157 	mntinfo4_t *mi = VTOMI4(vp);
4158 
4159 	if (nfs_zone() != mi->mi_zone)
4160 		return (EIO);
4161 
4162 	acc = 0;
4163 	if (mode & VREAD)
4164 		acc |= ACCESS4_READ;
4165 	if (mode & VWRITE) {
4166 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4167 			return (EROFS);
4168 		if (vp->v_type == VDIR)
4169 			acc |= ACCESS4_DELETE;
4170 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4171 	}
4172 	if (mode & VEXEC) {
4173 		if (vp->v_type == VDIR)
4174 			acc |= ACCESS4_LOOKUP;
4175 		else
4176 			acc |= ACCESS4_EXECUTE;
4177 	}
4178 
4179 	if (VTOR4(vp)->r_acache != NULL) {
4180 		e.error = nfs4_validate_caches(vp, cr);
4181 		if (e.error)
4182 			return (e.error);
4183 	}
4184 
4185 	rp = VTOR4(vp);
4186 	if (vp->v_type == VDIR) {
4187 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4188 			ACCESS4_EXTEND | ACCESS4_LOOKUP;
4189 	} else {
4190 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4191 			ACCESS4_EXECUTE;
4192 	}
4193 	recov_state.rs_flags = 0;
4194 	recov_state.rs_num_retry_despite_err = 0;
4195 
4196 	cred = cr;
4197 	/*
4198 	 * ncr and ncrfree both initially
4199 	 * point to the memory area returned
4200 	 * by crnetadjust();
4201 	 * ncrfree not NULL when exiting means
4202 	 * that we need to release it
4203 	 */
4204 	ncr = crnetadjust(cred);
4205 	ncrfree = ncr;
4206 
4207 tryagain:
4208 	cacc = nfs4_access_check(rp, acc, cred);
4209 	if (cacc == NFS4_ACCESS_ALLOWED) {
4210 		if (ncrfree != NULL)
4211 			crfree(ncrfree);
4212 		return (0);
4213 	}
4214 	if (cacc == NFS4_ACCESS_DENIED) {
4215 		/*
4216 		 * If the cred can be adjusted, try again
4217 		 * with the new cred.
4218 		 */
4219 		if (ncr != NULL) {
4220 			cred = ncr;
4221 			ncr = NULL;
4222 			goto tryagain;
4223 		}
4224 		if (ncrfree != NULL)
4225 			crfree(ncrfree);
4226 		return (EACCES);
4227 	}
4228 
4229 recov_retry:
4230 	/*
4231 	 * Don't take with r_statev4_lock here. r_deleg_type could
4232 	 * change as soon as lock is released.  Since it is an int,
4233 	 * there is no atomicity issue.
4234 	 */
4235 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4236 	num_ops = do_getattr ? 3 : 2;
4237 
4238 	args.ctag = TAG_ACCESS;
4239 
4240 	args.array_len = num_ops;
4241 	args.array = argop;
4242 
4243 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4244 					&recov_state, NULL)) {
4245 		if (ncrfree != NULL)
4246 			crfree(ncrfree);
4247 		return (e.error);
4248 	}
4249 
4250 	/* putfh target fh */
4251 	argop[0].argop = OP_CPUTFH;
4252 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4253 
4254 	/* access */
4255 	argop[1].argop = OP_ACCESS;
4256 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4257 
4258 	/* getattr */
4259 	if (do_getattr) {
4260 		argop[2].argop = OP_GETATTR;
4261 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4262 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4263 	}
4264 
4265 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4266 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4267 	    rnode4info(VTOR4(vp))));
4268 
4269 	doqueue = 1;
4270 	t = gethrtime();
4271 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4272 	rpc_error = e.error;
4273 
4274 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4275 	if (needrecov) {
4276 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4277 		    "nfs4_access: initiating recovery\n"));
4278 
4279 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4280 		    NULL, OP_ACCESS, NULL) == FALSE) {
4281 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4282 			    &recov_state, needrecov);
4283 			if (!e.error)
4284 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4285 						(caddr_t)&res);
4286 			goto recov_retry;
4287 		}
4288 	}
4289 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4290 
4291 	if (e.error)
4292 		goto out;
4293 
4294 	if (res.status) {
4295 		e.error = geterrno4(res.status);
4296 		/*
4297 		 * This might generate over the wire calls throught
4298 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4299 		 * here to avoid a deadlock.
4300 		 */
4301 		nfs4_purge_stale_fh(e.error, vp, cr);
4302 		goto out;
4303 	}
4304 	resop = &res.array[1];	/* access res */
4305 
4306 	resacc = resop->nfs_resop4_u.opaccess.access;
4307 
4308 	if (do_getattr) {
4309 		resop++;	/* getattr res */
4310 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4311 				t, cr, FALSE, NULL);
4312 	}
4313 
4314 	if (!e.error) {
4315 		nfs4_access_cache(rp, argacc, resacc, cred);
4316 		/*
4317 		 * we just cached results with cred; if cred is the
4318 		 * adjusted credentials from crnetadjust, we do not want
4319 		 * to release them before exiting: hence setting ncrfree
4320 		 * to NULL
4321 		 */
4322 		if (cred != cr)
4323 			ncrfree = NULL;
4324 		/* XXX check the supported bits too? */
4325 		if ((acc & resacc) != acc) {
4326 			/*
4327 			 * The following code implements the semantic
4328 			 * that a setuid root program has *at least* the
4329 			 * permissions of the user that is running the
4330 			 * program.  See rfs3call() for more portions
4331 			 * of the implementation of this functionality.
4332 			 */
4333 			/* XXX-LP */
4334 			if (ncr != NULL) {
4335 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4336 						(caddr_t)&res);
4337 				cred = ncr;
4338 				ncr = NULL;
4339 				goto tryagain;
4340 			}
4341 			e.error = EACCES;
4342 		}
4343 	}
4344 
4345 out:
4346 	if (!rpc_error)
4347 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4348 
4349 	if (ncrfree != NULL)
4350 		crfree(ncrfree);
4351 
4352 	return (e.error);
4353 }
4354 
4355 static int
4356 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr)
4357 {
4358 	COMPOUND4args_clnt args;
4359 	COMPOUND4res_clnt res;
4360 	int doqueue;
4361 	rnode4_t *rp;
4362 	nfs_argop4 argop[3];
4363 	nfs_resop4 *resop;
4364 	READLINK4res *lr_res;
4365 	nfs4_ga_res_t *garp;
4366 	uint_t len;
4367 	char *linkdata;
4368 	bool_t needrecov = FALSE;
4369 	nfs4_recov_state_t recov_state;
4370 	hrtime_t t;
4371 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4372 
4373 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4374 		return (EIO);
4375 	/*
4376 	 * Can't readlink anything other than a symbolic link.
4377 	 */
4378 	if (vp->v_type != VLNK)
4379 		return (EINVAL);
4380 
4381 	rp = VTOR4(vp);
4382 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4383 		e.error = nfs4_validate_caches(vp, cr);
4384 		if (e.error)
4385 			return (e.error);
4386 		mutex_enter(&rp->r_statelock);
4387 		if (rp->r_symlink.contents != NULL) {
4388 			e.error = uiomove(rp->r_symlink.contents,
4389 			    rp->r_symlink.len, UIO_READ, uiop);
4390 			mutex_exit(&rp->r_statelock);
4391 			return (e.error);
4392 		}
4393 		mutex_exit(&rp->r_statelock);
4394 	}
4395 	recov_state.rs_flags = 0;
4396 	recov_state.rs_num_retry_despite_err = 0;
4397 
4398 recov_retry:
4399 	args.array_len = 3;
4400 	args.array = argop;
4401 	args.ctag = TAG_READLINK;
4402 
4403 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4404 	if (e.error) {
4405 		return (e.error);
4406 	}
4407 
4408 	/* 0. putfh symlink fh */
4409 	argop[0].argop = OP_CPUTFH;
4410 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4411 
4412 	/* 1. readlink */
4413 	argop[1].argop = OP_READLINK;
4414 
4415 	/* 2. getattr */
4416 	argop[2].argop = OP_GETATTR;
4417 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4418 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4419 
4420 	doqueue = 1;
4421 
4422 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4423 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4424 	    rnode4info(VTOR4(vp))));
4425 
4426 	t = gethrtime();
4427 
4428 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4429 
4430 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4431 	if (needrecov) {
4432 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4433 		    "nfs4_readlink: initiating recovery\n"));
4434 
4435 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4436 		    NULL, OP_READLINK, NULL) == FALSE) {
4437 			if (!e.error)
4438 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4439 								(caddr_t)&res);
4440 
4441 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4442 			    needrecov);
4443 			goto recov_retry;
4444 		}
4445 	}
4446 
4447 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4448 
4449 	if (e.error)
4450 		return (e.error);
4451 
4452 	/*
4453 	 * There is an path in the code below which calls
4454 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4455 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4456 	 * here to avoid nfs4_start_op() deadlock.
4457 	 */
4458 
4459 	if (res.status && (res.array_len < args.array_len)) {
4460 		/*
4461 		 * either Putfh or Link failed
4462 		 */
4463 		e.error = geterrno4(res.status);
4464 		nfs4_purge_stale_fh(e.error, vp, cr);
4465 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4466 		return (e.error);
4467 	}
4468 
4469 	resop = &res.array[1];	/* readlink res */
4470 	lr_res = &resop->nfs_resop4_u.opreadlink;
4471 
4472 	/*
4473 	 * treat symlink names as data
4474 	 */
4475 	linkdata = utf8_to_str(&lr_res->link, &len, NULL);
4476 	if (linkdata != NULL) {
4477 		int uio_len = len - 1;
4478 		/* len includes null byte, which we won't uiomove */
4479 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4480 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4481 			mutex_enter(&rp->r_statelock);
4482 			if (rp->r_symlink.contents == NULL) {
4483 				rp->r_symlink.contents = linkdata;
4484 				rp->r_symlink.len = uio_len;
4485 				rp->r_symlink.size = len;
4486 				mutex_exit(&rp->r_statelock);
4487 			} else {
4488 				mutex_exit(&rp->r_statelock);
4489 				kmem_free(linkdata, len);
4490 			}
4491 		} else {
4492 			kmem_free(linkdata, len);
4493 		}
4494 	}
4495 	if (res.status == NFS4_OK) {
4496 		resop++;	/* getattr res */
4497 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4498 	}
4499 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4500 
4501 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4502 
4503 	/*
4504 	 * The over the wire error for attempting to readlink something
4505 	 * other than a symbolic link is ENXIO.  However, we need to
4506 	 * return EINVAL instead of ENXIO, so we map it here.
4507 	 */
4508 	return (e.error == ENXIO ? EINVAL : e.error);
4509 }
4510 
4511 /*
4512  * Flush local dirty pages to stable storage on the server.
4513  *
4514  * If FNODSYNC is specified, then there is nothing to do because
4515  * metadata changes are not cached on the client before being
4516  * sent to the server.
4517  */
4518 static int
4519 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr)
4520 {
4521 	int error;
4522 
4523 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4524 		return (0);
4525 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4526 		return (EIO);
4527 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4528 	if (!error)
4529 		error = VTOR4(vp)->r_error;
4530 	return (error);
4531 }
4532 
4533 /*
4534  * Weirdness: if the file was removed or the target of a rename
4535  * operation while it was open, it got renamed instead.  Here we
4536  * remove the renamed file.
4537  */
4538 static void
4539 nfs4_inactive(vnode_t *vp, cred_t *cr)
4540 {
4541 	rnode4_t *rp;
4542 
4543 	ASSERT(vp != DNLC_NO_VNODE);
4544 
4545 	rp = VTOR4(vp);
4546 
4547 	if (IS_SHADOW(vp, rp)) {
4548 		sv_inactive(vp);
4549 		return;
4550 	}
4551 
4552 	/*
4553 	 * If this is coming from the wrong zone, we let someone in the right
4554 	 * zone take care of it asynchronously.  We can get here due to
4555 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4556 	 * potentially turn into an expensive no-op if, for instance, v_count
4557 	 * gets incremented in the meantime, but it's still correct.
4558 	 */
4559 	if (nfs_zone() != VTOMI4(vp)->mi_zone) {
4560 		nfs4_async_inactive(vp, cr);
4561 		return;
4562 	}
4563 
4564 	/*
4565 	 * Some of the cleanup steps might require over-the-wire
4566 	 * operations.  Since VOP_INACTIVE can get called as a result of
4567 	 * other over-the-wire operations (e.g., an attribute cache update
4568 	 * can lead to a DNLC purge), doing those steps now would lead to a
4569 	 * nested call to the recovery framework, which can deadlock.  So
4570 	 * do any over-the-wire cleanups asynchronously, in a separate
4571 	 * thread.
4572 	 */
4573 
4574 	mutex_enter(&rp->r_os_lock);
4575 	mutex_enter(&rp->r_statelock);
4576 	mutex_enter(&rp->r_statev4_lock);
4577 
4578 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4579 		mutex_exit(&rp->r_statev4_lock);
4580 		mutex_exit(&rp->r_statelock);
4581 		mutex_exit(&rp->r_os_lock);
4582 		nfs4_async_inactive(vp, cr);
4583 		return;
4584 	}
4585 
4586 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4587 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4588 		mutex_exit(&rp->r_statev4_lock);
4589 		mutex_exit(&rp->r_statelock);
4590 		mutex_exit(&rp->r_os_lock);
4591 		nfs4_async_inactive(vp, cr);
4592 		return;
4593 	}
4594 
4595 	if (rp->r_unldvp != NULL) {
4596 		mutex_exit(&rp->r_statev4_lock);
4597 		mutex_exit(&rp->r_statelock);
4598 		mutex_exit(&rp->r_os_lock);
4599 		nfs4_async_inactive(vp, cr);
4600 		return;
4601 	}
4602 	mutex_exit(&rp->r_statev4_lock);
4603 	mutex_exit(&rp->r_statelock);
4604 	mutex_exit(&rp->r_os_lock);
4605 
4606 	rp4_addfree(rp, cr);
4607 }
4608 
4609 /*
4610  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4611  * various bits of state.  The caller must not refer to vp after this call.
4612  */
4613 
4614 void
4615 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4616 {
4617 	rnode4_t *rp = VTOR4(vp);
4618 	nfs4_recov_state_t recov_state;
4619 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4620 	vnode_t *unldvp;
4621 	char *unlname;
4622 	cred_t *unlcred;
4623 	COMPOUND4args_clnt args;
4624 	COMPOUND4res_clnt res, *resp;
4625 	nfs_argop4 argop[2];
4626 	int doqueue;
4627 #ifdef DEBUG
4628 	char *name;
4629 #endif
4630 
4631 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
4632 	ASSERT(!IS_SHADOW(vp, rp));
4633 
4634 #ifdef DEBUG
4635 	name = fn_name(VTOSV(vp)->sv_name);
4636 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4637 		"release vnode %s", name));
4638 	kmem_free(name, MAXNAMELEN);
4639 #endif
4640 
4641 	if (vp->v_type == VREG) {
4642 		bool_t recov_failed = FALSE;
4643 
4644 		e.error = nfs4close_all(vp, cr);
4645 		if (e.error) {
4646 			/* Check to see if recovery failed */
4647 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4648 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4649 				recov_failed = TRUE;
4650 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4651 			if (!recov_failed) {
4652 				mutex_enter(&rp->r_statelock);
4653 				if (rp->r_flags & R4RECOVERR)
4654 					recov_failed = TRUE;
4655 				mutex_exit(&rp->r_statelock);
4656 			}
4657 			if (recov_failed) {
4658 				NFS4_DEBUG(nfs4_client_recov_debug,
4659 					    (CE_NOTE, "nfs4_inactive_otw: "
4660 					    "close failed (recovery failure)"));
4661 			}
4662 		}
4663 	}
4664 
4665 redo:
4666 	if (rp->r_unldvp == NULL) {
4667 		rp4_addfree(rp, cr);
4668 		return;
4669 	}
4670 
4671 	/*
4672 	 * Save the vnode pointer for the directory where the
4673 	 * unlinked-open file got renamed, then set it to NULL
4674 	 * to prevent another thread from getting here before
4675 	 * we're done with the remove.  While we have the
4676 	 * statelock, make local copies of the pertinent rnode
4677 	 * fields.  If we weren't to do this in an atomic way, the
4678 	 * the unl* fields could become inconsistent with respect
4679 	 * to each other due to a race condition between this
4680 	 * code and nfs_remove().  See bug report 1034328.
4681 	 */
4682 	mutex_enter(&rp->r_statelock);
4683 	if (rp->r_unldvp == NULL) {
4684 		mutex_exit(&rp->r_statelock);
4685 		rp4_addfree(rp, cr);
4686 		return;
4687 	}
4688 
4689 	unldvp = rp->r_unldvp;
4690 	rp->r_unldvp = NULL;
4691 	unlname = rp->r_unlname;
4692 	rp->r_unlname = NULL;
4693 	unlcred = rp->r_unlcred;
4694 	rp->r_unlcred = NULL;
4695 	mutex_exit(&rp->r_statelock);
4696 
4697 	/*
4698 	 * If there are any dirty pages left, then flush
4699 	 * them.  This is unfortunate because they just
4700 	 * may get thrown away during the remove operation,
4701 	 * but we have to do this for correctness.
4702 	 */
4703 	if (nfs4_has_pages(vp) &&
4704 			    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4705 		ASSERT(vp->v_type != VCHR);
4706 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr);
4707 		if (e.error) {
4708 			mutex_enter(&rp->r_statelock);
4709 			if (!rp->r_error)
4710 				rp->r_error = e.error;
4711 			mutex_exit(&rp->r_statelock);
4712 		}
4713 	}
4714 
4715 	recov_state.rs_flags = 0;
4716 	recov_state.rs_num_retry_despite_err = 0;
4717 recov_retry_remove:
4718 	/*
4719 	 * Do the remove operation on the renamed file
4720 	 */
4721 	args.ctag = TAG_INACTIVE;
4722 
4723 	/*
4724 	 * Remove ops: putfh dir; remove
4725 	 */
4726 	args.array_len = 2;
4727 	args.array = argop;
4728 
4729 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4730 	if (e.error) {
4731 		kmem_free(unlname, MAXNAMELEN);
4732 		crfree(unlcred);
4733 		VN_RELE(unldvp);
4734 		/*
4735 		 * Try again; this time around r_unldvp will be NULL, so we'll
4736 		 * just call rp4_addfree() and return.
4737 		 */
4738 		goto redo;
4739 	}
4740 
4741 	/* putfh directory */
4742 	argop[0].argop = OP_CPUTFH;
4743 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4744 
4745 	/* remove */
4746 	argop[1].argop = OP_CREMOVE;
4747 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4748 
4749 	doqueue = 1;
4750 	resp = &res;
4751 
4752 #if 0 /* notyet */
4753 	/*
4754 	 * Can't do this yet.  We may be being called from
4755 	 * dnlc_purge_XXX while that routine is holding a
4756 	 * mutex lock to the nc_rele list.  The calls to
4757 	 * nfs3_cache_wcc_data may result in calls to
4758 	 * dnlc_purge_XXX.  This will result in a deadlock.
4759 	 */
4760 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4761 	if (e.error) {
4762 		PURGE_ATTRCACHE4(unldvp);
4763 		resp = NULL;
4764 	} else if (res.status) {
4765 		e.error = geterrno4(res.status);
4766 		PURGE_ATTRCACHE4(unldvp);
4767 		/*
4768 		 * This code is inactive right now
4769 		 * but if made active there should
4770 		 * be a nfs4_end_op() call before
4771 		 * nfs4_purge_stale_fh to avoid start_op()
4772 		 * deadlock. See BugId: 4948726
4773 		 */
4774 		nfs4_purge_stale_fh(error, unldvp, cr);
4775 	} else {
4776 		nfs_resop4 *resop;
4777 		REMOVE4res *rm_res;
4778 
4779 		resop = &res.array[1];
4780 		rm_res = &resop->nfs_resop4_u.opremove;
4781 		/*
4782 		 * Update directory cache attribute,
4783 		 * readdir and dnlc caches.
4784 		 */
4785 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4786 	}
4787 #else
4788 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4789 
4790 	PURGE_ATTRCACHE4(unldvp);
4791 #endif
4792 
4793 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4794 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4795 		    NULL, NULL, OP_REMOVE, NULL) == FALSE) {
4796 			if (!e.error)
4797 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4798 								(caddr_t)&res);
4799 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4800 							&recov_state, TRUE);
4801 			goto recov_retry_remove;
4802 		}
4803 	}
4804 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4805 
4806 	/*
4807 	 * Release stuff held for the remove
4808 	 */
4809 	VN_RELE(unldvp);
4810 	if (!e.error && resp)
4811 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4812 
4813 	kmem_free(unlname, MAXNAMELEN);
4814 	crfree(unlcred);
4815 	goto redo;
4816 }
4817 
4818 /*
4819  * Remote file system operations having to do with directory manipulation.
4820  */
4821 /* ARGSUSED3 */
4822 static int
4823 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4824 	int flags, vnode_t *rdir, cred_t *cr)
4825 {
4826 	int error;
4827 	vnode_t *vp, *avp = NULL;
4828 	rnode4_t *drp;
4829 
4830 	*vpp = NULL;
4831 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4832 		return (EPERM);
4833 	/*
4834 	 * if LOOKUP_XATTR, must replace dvp (object) with
4835 	 * object's attrdir before continuing with lookup
4836 	 */
4837 	if (flags & LOOKUP_XATTR) {
4838 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4839 		if (error)
4840 			return (error);
4841 
4842 		dvp = avp;
4843 
4844 		/*
4845 		 * If lookup is for "", just return dvp now.  The attrdir
4846 		 * has already been activated (from nfs4lookup_xattr), and
4847 		 * the caller will RELE the original dvp -- not
4848 		 * the attrdir.  So, set vpp and return.
4849 		 * Currently, when the LOOKUP_XATTR flag is
4850 		 * passed to VOP_LOOKUP, the name is always empty, and
4851 		 * shortcircuiting here avoids 3 unneeded lock/unlock
4852 		 * pairs.
4853 		 *
4854 		 * If a non-empty name was provided, then it is the
4855 		 * attribute name, and it will be looked up below.
4856 		 */
4857 		if (*nm == '\0') {
4858 			*vpp = dvp;
4859 			return (0);
4860 		}
4861 
4862 		/*
4863 		 * The vfs layer never sends a name when asking for the
4864 		 * attrdir, so we should never get here (unless of course
4865 		 * name is passed at some time in future -- at which time
4866 		 * we'll blow up here).
4867 		 */
4868 		ASSERT(0);
4869 	}
4870 
4871 	drp = VTOR4(dvp);
4872 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4873 		return (EINTR);
4874 
4875 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
4876 	nfs_rw_exit(&drp->r_rwlock);
4877 
4878 	/*
4879 	 * If vnode is a device, create special vnode.
4880 	 */
4881 	if (!error && ISVDEV((*vpp)->v_type)) {
4882 		vp = *vpp;
4883 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
4884 		VN_RELE(vp);
4885 	}
4886 
4887 	return (error);
4888 }
4889 
4890 /* ARGSUSED */
4891 static int
4892 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
4893 {
4894 	int error;
4895 	rnode4_t *drp;
4896 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
4897 	mntinfo4_t *mi;
4898 
4899 	mi = VTOMI4(dvp);
4900 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR))
4901 		return (EINVAL);
4902 
4903 	drp = VTOR4(dvp);
4904 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4905 		return (EINTR);
4906 
4907 	mutex_enter(&drp->r_statelock);
4908 	/*
4909 	 * If the server doesn't support xattrs just return EINVAL
4910 	 */
4911 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
4912 		mutex_exit(&drp->r_statelock);
4913 		nfs_rw_exit(&drp->r_rwlock);
4914 		return (EINVAL);
4915 	}
4916 
4917 	/*
4918 	 * If there is a cached xattr directory entry,
4919 	 * use it as long as the attributes are valid. If the
4920 	 * attributes are not valid, take the simple approach and
4921 	 * free the cached value and re-fetch a new value.
4922 	 *
4923 	 * We don't negative entry cache for now, if we did we
4924 	 * would need to check if the file has changed on every
4925 	 * lookup. But xattrs don't exist very often and failing
4926 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
4927 	 * so do an openattr over the wire for now.
4928 	 */
4929 	if (drp->r_xattr_dir != NULL) {
4930 		if (ATTRCACHE4_VALID(dvp)) {
4931 			VN_HOLD(drp->r_xattr_dir);
4932 			*vpp = drp->r_xattr_dir;
4933 			mutex_exit(&drp->r_statelock);
4934 			nfs_rw_exit(&drp->r_rwlock);
4935 			return (0);
4936 		}
4937 		VN_RELE(drp->r_xattr_dir);
4938 		drp->r_xattr_dir = NULL;
4939 	}
4940 	mutex_exit(&drp->r_statelock);
4941 
4942 	error = nfs4openattr(dvp, vpp, cflag, cr);
4943 
4944 	nfs_rw_exit(&drp->r_rwlock);
4945 
4946 	return (error);
4947 }
4948 
4949 static int
4950 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
4951 {
4952 	int error;
4953 	rnode4_t *drp;
4954 
4955 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
4956 
4957 	/*
4958 	 * If lookup is for "", just return dvp.  Don't need
4959 	 * to send it over the wire, look it up in the dnlc,
4960 	 * or perform any access checks.
4961 	 */
4962 	if (*nm == '\0') {
4963 		VN_HOLD(dvp);
4964 		*vpp = dvp;
4965 		return (0);
4966 	}
4967 
4968 	/*
4969 	 * Can't do lookups in non-directories.
4970 	 */
4971 	if (dvp->v_type != VDIR)
4972 		return (ENOTDIR);
4973 
4974 	/*
4975 	 * If lookup is for ".", just return dvp.  Don't need
4976 	 * to send it over the wire or look it up in the dnlc,
4977 	 * just need to check access.
4978 	 */
4979 	if (nm[0] == '.' && nm[1] == '\0') {
4980 		error = nfs4_access(dvp, VEXEC, 0, cr);
4981 		if (error)
4982 			return (error);
4983 		VN_HOLD(dvp);
4984 		*vpp = dvp;
4985 		return (0);
4986 	}
4987 
4988 	drp = VTOR4(dvp);
4989 	if (!(drp->r_flags & R4LOOKUP)) {
4990 		mutex_enter(&drp->r_statelock);
4991 		drp->r_flags |= R4LOOKUP;
4992 		mutex_exit(&drp->r_statelock);
4993 	}
4994 
4995 	*vpp = NULL;
4996 	/*
4997 	 * Lookup this name in the DNLC.  If there is no entry
4998 	 * lookup over the wire.
4999 	 */
5000 	if (!skipdnlc)
5001 		*vpp = dnlc_lookup(dvp, nm);
5002 	if (*vpp == NULL) {
5003 		/*
5004 		 * We need to go over the wire to lookup the name.
5005 		 */
5006 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
5007 	}
5008 
5009 	/*
5010 	 * We hit on the dnlc
5011 	 */
5012 	if (*vpp != DNLC_NO_VNODE ||
5013 			    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
5014 		/*
5015 		 * But our attrs may not be valid.
5016 		 */
5017 		if (ATTRCACHE4_VALID(dvp)) {
5018 			error = nfs4_waitfor_purge_complete(dvp);
5019 			if (error) {
5020 				VN_RELE(*vpp);
5021 				*vpp = NULL;
5022 				return (error);
5023 			}
5024 
5025 			/*
5026 			 * If after the purge completes, check to make sure
5027 			 * our attrs are still valid.
5028 			 */
5029 			if (ATTRCACHE4_VALID(dvp)) {
5030 				/*
5031 				 * If we waited for a purge we may have
5032 				 * lost our vnode so look it up again.
5033 				 */
5034 				VN_RELE(*vpp);
5035 				*vpp = dnlc_lookup(dvp, nm);
5036 				if (*vpp == NULL)
5037 					return (nfs4lookupnew_otw(dvp,
5038 						nm, vpp, cr));
5039 
5040 				/*
5041 				 * The access cache should almost always hit
5042 				 */
5043 				error = nfs4_access(dvp, VEXEC, 0, cr);
5044 
5045 				if (error) {
5046 					VN_RELE(*vpp);
5047 					*vpp = NULL;
5048 					return (error);
5049 				}
5050 				if (*vpp == DNLC_NO_VNODE) {
5051 					VN_RELE(*vpp);
5052 					*vpp = NULL;
5053 					return (ENOENT);
5054 				}
5055 				return (0);
5056 			}
5057 		}
5058 	}
5059 
5060 	ASSERT(*vpp != NULL);
5061 
5062 	/*
5063 	 * We may have gotten here we have one of the following cases:
5064 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5065 	 *		need to validate them.
5066 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5067 	 *		must validate.
5068 	 *
5069 	 * Go to the server and check if the directory has changed, if
5070 	 * it hasn't we are done and can use the dnlc entry.
5071 	 */
5072 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5073 }
5074 
5075 /*
5076  * Go to the server and check if the directory has changed, if
5077  * it hasn't we are done and can use the dnlc entry.  If it
5078  * has changed we get a new copy of its attributes and check
5079  * the access for VEXEC, then relookup the filename and
5080  * get its filehandle and attributes.
5081  *
5082  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5083  *	if the NVERIFY failed we must
5084  *		purge the caches
5085  *		cache new attributes (will set r_time_attr_inval)
5086  *		cache new access
5087  *		recheck VEXEC access
5088  *		add name to dnlc, possibly negative
5089  *		if LOOKUP succeeded
5090  *			cache new attributes
5091  *	else
5092  *		set a new r_time_attr_inval for dvp
5093  *		check to make sure we have access
5094  *
5095  * The vpp returned is the vnode passed in if the directory is valid,
5096  * a new vnode if successful lookup, or NULL on error.
5097  */
5098 static int
5099 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5100 {
5101 	COMPOUND4args_clnt args;
5102 	COMPOUND4res_clnt res;
5103 	fattr4 *ver_fattr;
5104 	fattr4_change dchange;
5105 	int32_t *ptr;
5106 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5107 	nfs_argop4 *argop;
5108 	int doqueue;
5109 	mntinfo4_t *mi;
5110 	nfs4_recov_state_t recov_state;
5111 	hrtime_t t;
5112 	int isdotdot;
5113 	vnode_t *nvp;
5114 	nfs_fh4 *fhp;
5115 	nfs4_sharedfh_t *sfhp;
5116 	nfs4_access_type_t cacc;
5117 	rnode4_t *nrp;
5118 	rnode4_t *drp = VTOR4(dvp);
5119 	nfs4_ga_res_t *garp = NULL;
5120 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5121 
5122 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5123 	ASSERT(nm != NULL);
5124 	ASSERT(nm[0] != '\0');
5125 	ASSERT(dvp->v_type == VDIR);
5126 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5127 	ASSERT(*vpp != NULL);
5128 
5129 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5130 		isdotdot = 1;
5131 		args.ctag = TAG_LOOKUP_VPARENT;
5132 	} else {
5133 		/*
5134 		 * Do not allow crossing of server mount points.  The
5135 		 * only visible entries in a SRVSTUB dir are . and ..
5136 		 * This code handles the non-.. case.  We can't even get
5137 		 * this far if looking up ".".
5138 		 */
5139 		if (VTOR4(dvp)->r_flags & R4SRVSTUB) {
5140 			VN_RELE(*vpp);
5141 			*vpp = NULL;
5142 			return (ENOENT);
5143 		}
5144 		isdotdot = 0;
5145 		args.ctag = TAG_LOOKUP_VALID;
5146 	}
5147 
5148 	mi = VTOMI4(dvp);
5149 	recov_state.rs_flags = 0;
5150 	recov_state.rs_num_retry_despite_err = 0;
5151 
5152 	nvp = NULL;
5153 
5154 	/* Save the original mount point security information */
5155 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5156 
5157 recov_retry:
5158 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5159 			    &recov_state, NULL);
5160 	if (e.error) {
5161 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5162 		VN_RELE(*vpp);
5163 		*vpp = NULL;
5164 		return (e.error);
5165 	}
5166 
5167 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5168 
5169 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5170 	args.array_len = 7;
5171 	args.array = argop;
5172 
5173 	/* 0. putfh file */
5174 	argop[0].argop = OP_CPUTFH;
5175 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5176 
5177 	/* 1. nverify the change info */
5178 	argop[1].argop = OP_NVERIFY;
5179 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5180 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5181 	ver_fattr->attrlist4 = (char *)&dchange;
5182 	ptr = (int32_t *)&dchange;
5183 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5184 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5185 
5186 	/* 2. getattr directory */
5187 	argop[2].argop = OP_GETATTR;
5188 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5189 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5190 
5191 	/* 3. access directory */
5192 	argop[3].argop = OP_ACCESS;
5193 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5194 			ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5195 
5196 	/* 4. lookup name */
5197 	if (isdotdot) {
5198 		argop[4].argop = OP_LOOKUPP;
5199 	} else {
5200 		argop[4].argop = OP_CLOOKUP;
5201 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5202 	}
5203 
5204 	/* 5. resulting file handle */
5205 	argop[5].argop = OP_GETFH;
5206 
5207 	/* 6. resulting file attributes */
5208 	argop[6].argop = OP_GETATTR;
5209 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5210 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5211 
5212 	doqueue = 1;
5213 	t = gethrtime();
5214 
5215 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5216 
5217 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5218 		/*
5219 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5220 		 * from this thread, do not go thru the recovery thread since
5221 		 * we need the nm information.
5222 		 *
5223 		 * Not doing dotdot case because there is no specification
5224 		 * for (PUTFH, SECINFO "..") yet.
5225 		 */
5226 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5227 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr))) {
5228 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5229 					&recov_state, FALSE);
5230 			} else {
5231 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5232 					&recov_state, TRUE);
5233 			}
5234 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5235 			kmem_free(argop, argoplist_size);
5236 			if (!e.error)
5237 				goto recov_retry;
5238 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5239 			VN_RELE(*vpp);
5240 			*vpp = NULL;
5241 			return (e.error);
5242 		}
5243 
5244 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5245 		    OP_LOOKUP, NULL) == FALSE) {
5246 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5247 				&recov_state, TRUE);
5248 
5249 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5250 			kmem_free(argop, argoplist_size);
5251 			goto recov_retry;
5252 		}
5253 	}
5254 
5255 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5256 
5257 	if (e.error || res.array_len == 0) {
5258 		/*
5259 		 * If e.error isn't set, then reply has no ops (or we couldn't
5260 		 * be here).  The only legal way to reply without an op array
5261 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5262 		 * be in the reply for all other status values.
5263 		 *
5264 		 * For valid replies without an ops array, return ENOTSUP
5265 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5266 		 * return EIO -- don't trust status.
5267 		 */
5268 		if (e.error == 0)
5269 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5270 				ENOTSUP : EIO;
5271 		VN_RELE(*vpp);
5272 		*vpp = NULL;
5273 		kmem_free(argop, argoplist_size);
5274 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5275 		return (e.error);
5276 	}
5277 
5278 	if (res.status != NFS4ERR_SAME) {
5279 		e.error = geterrno4(res.status);
5280 
5281 		/*
5282 		 * The NVERIFY "failed" so the directory has changed
5283 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5284 		 * cleanly.
5285 		 */
5286 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5287 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5288 			nfs4_purge_stale_fh(e.error, dvp, cr);
5289 			VN_RELE(*vpp);
5290 			*vpp = NULL;
5291 			goto exit;
5292 		}
5293 
5294 		/*
5295 		 * We know the NVERIFY "failed" so we must:
5296 		 *	purge the caches (access and indirectly dnlc if needed)
5297 		 */
5298 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5299 
5300 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5301 			nfs4_purge_stale_fh(e.error, dvp, cr);
5302 			VN_RELE(*vpp);
5303 			*vpp = NULL;
5304 			goto exit;
5305 		}
5306 
5307 		/*
5308 		 * Install new cached attributes for the directory
5309 		 */
5310 		nfs4_attr_cache(dvp,
5311 				&res.array[2].nfs_resop4_u.opgetattr.ga_res,
5312 				t, cr, FALSE, NULL);
5313 
5314 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5315 			nfs4_purge_stale_fh(e.error, dvp, cr);
5316 			VN_RELE(*vpp);
5317 			*vpp = NULL;
5318 			e.error = geterrno4(res.status);
5319 			goto exit;
5320 		}
5321 
5322 		/*
5323 		 * Now we know the directory is valid,
5324 		 * cache new directory access
5325 		 */
5326 		nfs4_access_cache(drp,
5327 			args.array[3].nfs_argop4_u.opaccess.access,
5328 			res.array[3].nfs_resop4_u.opaccess.access, cr);
5329 
5330 		/*
5331 		 * recheck VEXEC access
5332 		 */
5333 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5334 		if (cacc != NFS4_ACCESS_ALLOWED) {
5335 			/*
5336 			 * Directory permissions might have been revoked
5337 			 */
5338 			if (cacc == NFS4_ACCESS_DENIED) {
5339 				e.error = EACCES;
5340 				VN_RELE(*vpp);
5341 				*vpp = NULL;
5342 				goto exit;
5343 			}
5344 
5345 			/*
5346 			 * Somehow we must not have asked for enough
5347 			 * so try a singleton ACCESS, should never happen.
5348 			 */
5349 			e.error = nfs4_access(dvp, VEXEC, 0, cr);
5350 			if (e.error) {
5351 				VN_RELE(*vpp);
5352 				*vpp = NULL;
5353 				goto exit;
5354 			}
5355 		}
5356 
5357 		e.error = geterrno4(res.status);
5358 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5359 			/*
5360 			 * The lookup failed, probably no entry
5361 			 */
5362 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5363 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5364 			} else {
5365 				/*
5366 				 * Might be some other error, so remove
5367 				 * the dnlc entry to make sure we start all
5368 				 * over again, next time.
5369 				 */
5370 				dnlc_remove(dvp, nm);
5371 			}
5372 			VN_RELE(*vpp);
5373 			*vpp = NULL;
5374 			goto exit;
5375 		}
5376 
5377 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5378 			/*
5379 			 * The file exists but we can't get its fh for
5380 			 * some unknown reason.  Remove it from the dnlc
5381 			 * and error out to be safe.
5382 			 */
5383 			dnlc_remove(dvp, nm);
5384 			VN_RELE(*vpp);
5385 			*vpp = NULL;
5386 			goto exit;
5387 		}
5388 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5389 		if (fhp->nfs_fh4_len == 0) {
5390 			/*
5391 			 * The file exists but a bogus fh
5392 			 * some unknown reason.  Remove it from the dnlc
5393 			 * and error out to be safe.
5394 			 */
5395 			e.error = ENOENT;
5396 			dnlc_remove(dvp, nm);
5397 			VN_RELE(*vpp);
5398 			*vpp = NULL;
5399 			goto exit;
5400 		}
5401 		sfhp = sfh4_get(fhp, mi);
5402 
5403 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5404 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5405 
5406 		/*
5407 		 * Make the new rnode
5408 		 */
5409 		if (isdotdot) {
5410 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5411 			if (e.error) {
5412 				sfh4_rele(&sfhp);
5413 				VN_RELE(*vpp);
5414 				*vpp = NULL;
5415 				goto exit;
5416 			}
5417 			/*
5418 			 * XXX if nfs4_make_dotdot uses an existing rnode
5419 			 * XXX it doesn't update the attributes.
5420 			 * XXX for now just save them again to save an OTW
5421 			 */
5422 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5423 		} else {
5424 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5425 				dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5426 			/*
5427 			 * If v_type == VNON, then garp was NULL because
5428 			 * the last op in the compound failed and makenfs4node
5429 			 * could not find the vnode for sfhp. It created
5430 			 * a new vnode, so we have nothing to purge here.
5431 			 */
5432 			if (nvp->v_type == VNON) {
5433 				vattr_t vattr;
5434 
5435 				vattr.va_mask = AT_TYPE;
5436 				/*
5437 				 * N.B. We've already called nfs4_end_fop above.
5438 				 */
5439 				e.error = nfs4getattr(nvp, &vattr, cr);
5440 				if (e.error) {
5441 					sfh4_rele(&sfhp);
5442 					VN_RELE(*vpp);
5443 					*vpp = NULL;
5444 					VN_RELE(nvp);
5445 					goto exit;
5446 				}
5447 				nvp->v_type = vattr.va_type;
5448 			}
5449 		}
5450 		sfh4_rele(&sfhp);
5451 
5452 		nrp = VTOR4(nvp);
5453 		mutex_enter(&nrp->r_statev4_lock);
5454 		if (!nrp->created_v4) {
5455 			mutex_exit(&nrp->r_statev4_lock);
5456 			dnlc_update(dvp, nm, nvp);
5457 		} else
5458 			mutex_exit(&nrp->r_statev4_lock);
5459 
5460 		VN_RELE(*vpp);
5461 		*vpp = nvp;
5462 	} else {
5463 		hrtime_t now;
5464 		hrtime_t delta = 0;
5465 
5466 		e.error = 0;
5467 
5468 		/*
5469 		 * Because the NVERIFY "succeeded" we know that the
5470 		 * directory attributes are still valid
5471 		 * so update r_time_attr_inval
5472 		 */
5473 		now = gethrtime();
5474 		mutex_enter(&drp->r_statelock);
5475 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5476 			delta = now - drp->r_time_attr_saved;
5477 			if (delta < mi->mi_acdirmin)
5478 				delta = mi->mi_acdirmin;
5479 			else if (delta > mi->mi_acdirmax)
5480 				delta = mi->mi_acdirmax;
5481 		}
5482 		drp->r_time_attr_inval = now + delta;
5483 		mutex_exit(&drp->r_statelock);
5484 		dnlc_update(dvp, nm, *vpp);
5485 
5486 		/*
5487 		 * Even though we have a valid directory attr cache
5488 		 * and dnlc entry, we may not have access.
5489 		 * This should almost always hit the cache.
5490 		 */
5491 		e.error = nfs4_access(dvp, VEXEC, 0, cr);
5492 		if (e.error) {
5493 			VN_RELE(*vpp);
5494 			*vpp = NULL;
5495 		}
5496 
5497 		if (*vpp == DNLC_NO_VNODE) {
5498 			VN_RELE(*vpp);
5499 			*vpp = NULL;
5500 			e.error = ENOENT;
5501 		}
5502 	}
5503 
5504 exit:
5505 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5506 	kmem_free(argop, argoplist_size);
5507 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5508 	return (e.error);
5509 }
5510 
5511 /*
5512  * We need to go over the wire to lookup the name, but
5513  * while we are there verify the directory has not
5514  * changed but if it has, get new attributes and check access
5515  *
5516  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5517  *					NVERIFY GETATTR ACCESS
5518  *
5519  * With the results:
5520  *	if the NVERIFY failed we must purge the caches, add new attributes,
5521  *		and cache new access.
5522  *	set a new r_time_attr_inval
5523  *	add name to dnlc, possibly negative
5524  *	if LOOKUP succeeded
5525  *		cache new attributes
5526  */
5527 static int
5528 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5529 {
5530 	COMPOUND4args_clnt args;
5531 	COMPOUND4res_clnt res;
5532 	fattr4 *ver_fattr;
5533 	fattr4_change dchange;
5534 	int32_t *ptr;
5535 	nfs4_ga_res_t *garp = NULL;
5536 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5537 	nfs_argop4 *argop;
5538 	int doqueue;
5539 	mntinfo4_t *mi;
5540 	nfs4_recov_state_t recov_state;
5541 	hrtime_t t;
5542 	int isdotdot;
5543 	vnode_t *nvp;
5544 	nfs_fh4 *fhp;
5545 	nfs4_sharedfh_t *sfhp;
5546 	nfs4_access_type_t cacc;
5547 	rnode4_t *nrp;
5548 	rnode4_t *drp = VTOR4(dvp);
5549 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5550 
5551 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5552 	ASSERT(nm != NULL);
5553 	ASSERT(nm[0] != '\0');
5554 	ASSERT(dvp->v_type == VDIR);
5555 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5556 	ASSERT(*vpp == NULL);
5557 
5558 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5559 		isdotdot = 1;
5560 		args.ctag = TAG_LOOKUP_PARENT;
5561 	} else {
5562 		/*
5563 		 * Do not allow crossing of server mount points.  The
5564 		 * only visible entries in a SRVSTUB dir are . and ..
5565 		 * This code handles the non-.. case.  We can't even get
5566 		 * this far if looking up ".".
5567 		 */
5568 		if (VTOR4(dvp)->r_flags & R4SRVSTUB)
5569 			return (ENOENT);
5570 
5571 		isdotdot = 0;
5572 		args.ctag = TAG_LOOKUP;
5573 	}
5574 
5575 	mi = VTOMI4(dvp);
5576 	recov_state.rs_flags = 0;
5577 	recov_state.rs_num_retry_despite_err = 0;
5578 
5579 	nvp = NULL;
5580 
5581 	/* Save the original mount point security information */
5582 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5583 
5584 recov_retry:
5585 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5586 			    &recov_state, NULL);
5587 	if (e.error) {
5588 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5589 		return (e.error);
5590 	}
5591 
5592 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5593 
5594 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5595 	args.array_len = 9;
5596 	args.array = argop;
5597 
5598 	/* 0. putfh file */
5599 	argop[0].argop = OP_CPUTFH;
5600 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5601 
5602 	/* 1. savefh for the nverify */
5603 	argop[1].argop = OP_SAVEFH;
5604 
5605 	/* 2. lookup name */
5606 	if (isdotdot) {
5607 		argop[2].argop = OP_LOOKUPP;
5608 	} else {
5609 		argop[2].argop = OP_CLOOKUP;
5610 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5611 	}
5612 
5613 	/* 3. resulting file handle */
5614 	argop[3].argop = OP_GETFH;
5615 
5616 	/* 4. resulting file attributes */
5617 	argop[4].argop = OP_GETATTR;
5618 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5619 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5620 
5621 	/* 5. restorefh back the directory for the nverify */
5622 	argop[5].argop = OP_RESTOREFH;
5623 
5624 	/* 6. nverify the change info */
5625 	argop[6].argop = OP_NVERIFY;
5626 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5627 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5628 	ver_fattr->attrlist4 = (char *)&dchange;
5629 	ptr = (int32_t *)&dchange;
5630 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5631 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5632 
5633 	/* 7. getattr directory */
5634 	argop[7].argop = OP_GETATTR;
5635 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5636 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5637 
5638 	/* 8. access directory */
5639 	argop[8].argop = OP_ACCESS;
5640 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5641 			ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5642 
5643 	doqueue = 1;
5644 	t = gethrtime();
5645 
5646 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5647 
5648 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5649 		/*
5650 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5651 		 * from this thread, do not go thru the recovery thread since
5652 		 * we need the nm information.
5653 		 *
5654 		 * Not doing dotdot case because there is no specification
5655 		 * for (PUTFH, SECINFO "..") yet.
5656 		 */
5657 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5658 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr))) {
5659 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5660 					&recov_state, FALSE);
5661 			} else {
5662 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5663 					&recov_state, TRUE);
5664 			}
5665 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5666 			kmem_free(argop, argoplist_size);
5667 			if (!e.error)
5668 				goto recov_retry;
5669 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5670 			return (e.error);
5671 		}
5672 
5673 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5674 		    OP_LOOKUP, NULL) == FALSE) {
5675 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5676 				&recov_state, TRUE);
5677 
5678 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5679 			kmem_free(argop, argoplist_size);
5680 			goto recov_retry;
5681 		}
5682 	}
5683 
5684 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5685 
5686 	if (e.error || res.array_len == 0) {
5687 		/*
5688 		 * If e.error isn't set, then reply has no ops (or we couldn't
5689 		 * be here).  The only legal way to reply without an op array
5690 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5691 		 * be in the reply for all other status values.
5692 		 *
5693 		 * For valid replies without an ops array, return ENOTSUP
5694 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5695 		 * return EIO -- don't trust status.
5696 		 */
5697 		if (e.error == 0)
5698 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5699 				ENOTSUP : EIO;
5700 
5701 		kmem_free(argop, argoplist_size);
5702 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5703 		return (e.error);
5704 	}
5705 
5706 	e.error = geterrno4(res.status);
5707 
5708 	/*
5709 	 * The PUTFH and SAVEFH may have failed.
5710 	 */
5711 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5712 		    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5713 		nfs4_purge_stale_fh(e.error, dvp, cr);
5714 		goto exit;
5715 	}
5716 
5717 	/*
5718 	 * Check if the file exists, if it does delay entering
5719 	 * into the dnlc until after we update the directory
5720 	 * attributes so we don't cause it to get purged immediately.
5721 	 */
5722 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5723 		/*
5724 		 * The lookup failed, probably no entry
5725 		 */
5726 		if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5727 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5728 		}
5729 		goto exit;
5730 	}
5731 
5732 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5733 		/*
5734 		 * The file exists but we can't get its fh for
5735 		 * some unknown reason. Error out to be safe.
5736 		 */
5737 		goto exit;
5738 	}
5739 
5740 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5741 	if (fhp->nfs_fh4_len == 0) {
5742 		/*
5743 		 * The file exists but a bogus fh
5744 		 * some unknown reason.  Error out to be safe.
5745 		 */
5746 		e.error = EIO;
5747 		goto exit;
5748 	}
5749 	sfhp = sfh4_get(fhp, mi);
5750 
5751 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5752 		sfh4_rele(&sfhp);
5753 		e.error = EIO;
5754 		goto exit;
5755 	}
5756 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5757 
5758 	/*
5759 	 * The RESTOREFH may have failed
5760 	 */
5761 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5762 		sfh4_rele(&sfhp);
5763 		e.error = EIO;
5764 		goto exit;
5765 	}
5766 
5767 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5768 		/*
5769 		 * First make sure the NVERIFY failed as we expected,
5770 		 * if it didn't then be conservative and error out
5771 		 * as we can't trust the directory.
5772 		 */
5773 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5774 			sfh4_rele(&sfhp);
5775 			e.error = EIO;
5776 			goto exit;
5777 		}
5778 
5779 		/*
5780 		 * We know the NVERIFY "failed" so the directory has changed,
5781 		 * so we must:
5782 		 *	purge the caches (access and indirectly dnlc if needed)
5783 		 */
5784 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5785 
5786 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5787 			sfh4_rele(&sfhp);
5788 			goto exit;
5789 		}
5790 		nfs4_attr_cache(dvp,
5791 				&res.array[7].nfs_resop4_u.opgetattr.ga_res,
5792 				t, cr, FALSE, NULL);
5793 
5794 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5795 			nfs4_purge_stale_fh(e.error, dvp, cr);
5796 			sfh4_rele(&sfhp);
5797 			e.error = geterrno4(res.status);
5798 			goto exit;
5799 		}
5800 
5801 		/*
5802 		 * Now we know the directory is valid,
5803 		 * cache new directory access
5804 		 */
5805 		nfs4_access_cache(drp,
5806 			args.array[8].nfs_argop4_u.opaccess.access,
5807 			res.array[8].nfs_resop4_u.opaccess.access, cr);
5808 
5809 		/*
5810 		 * recheck VEXEC access
5811 		 */
5812 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5813 		if (cacc != NFS4_ACCESS_ALLOWED) {
5814 			/*
5815 			 * Directory permissions might have been revoked
5816 			 */
5817 			if (cacc == NFS4_ACCESS_DENIED) {
5818 				sfh4_rele(&sfhp);
5819 				e.error = EACCES;
5820 				goto exit;
5821 			}
5822 
5823 			/*
5824 			 * Somehow we must not have asked for enough
5825 			 * so try a singleton ACCESS should never happen
5826 			 */
5827 			e.error = nfs4_access(dvp, VEXEC, 0, cr);
5828 			if (e.error) {
5829 				sfh4_rele(&sfhp);
5830 				goto exit;
5831 			}
5832 		}
5833 
5834 		e.error = geterrno4(res.status);
5835 	} else {
5836 		hrtime_t now;
5837 		hrtime_t delta = 0;
5838 
5839 		e.error = 0;
5840 
5841 		/*
5842 		 * Because the NVERIFY "succeeded" we know that the
5843 		 * directory attributes are still valid
5844 		 * so update r_time_attr_inval
5845 		 */
5846 		now = gethrtime();
5847 		mutex_enter(&drp->r_statelock);
5848 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5849 			delta = now - drp->r_time_attr_saved;
5850 			if (delta < mi->mi_acdirmin)
5851 				delta = mi->mi_acdirmin;
5852 			else if (delta > mi->mi_acdirmax)
5853 				delta = mi->mi_acdirmax;
5854 		}
5855 		drp->r_time_attr_inval = now + delta;
5856 		mutex_exit(&drp->r_statelock);
5857 
5858 		/*
5859 		 * Even though we have a valid directory attr cache,
5860 		 * we may not have access.
5861 		 * This should almost always hit the cache.
5862 		 */
5863 		e.error = nfs4_access(dvp, VEXEC, 0, cr);
5864 		if (e.error) {
5865 			sfh4_rele(&sfhp);
5866 			goto exit;
5867 		}
5868 	}
5869 
5870 	/*
5871 	 * Now we have successfully completed the lookup, if the
5872 	 * directory has changed we now have the valid attributes.
5873 	 * We also know we have directory access.
5874 	 * Create the new rnode and insert it in the dnlc.
5875 	 */
5876 	if (isdotdot) {
5877 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5878 		if (e.error) {
5879 			sfh4_rele(&sfhp);
5880 			goto exit;
5881 		}
5882 		/*
5883 		 * XXX if nfs4_make_dotdot uses an existing rnode
5884 		 * XXX it doesn't update the attributes.
5885 		 * XXX for now just save them again to save an OTW
5886 		 */
5887 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5888 	} else {
5889 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5890 			dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5891 	}
5892 	sfh4_rele(&sfhp);
5893 
5894 	nrp = VTOR4(nvp);
5895 	mutex_enter(&nrp->r_statev4_lock);
5896 	if (!nrp->created_v4) {
5897 		mutex_exit(&nrp->r_statev4_lock);
5898 		dnlc_update(dvp, nm, nvp);
5899 	} else
5900 		mutex_exit(&nrp->r_statev4_lock);
5901 
5902 	*vpp = nvp;
5903 
5904 exit:
5905 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5906 	kmem_free(argop, argoplist_size);
5907 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5908 	return (e.error);
5909 }
5910 
5911 #ifdef DEBUG
5912 void
5913 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
5914 {
5915 	uint_t i, len;
5916 	zoneid_t zoneid = getzoneid();
5917 	char *s;
5918 
5919 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
5920 	for (i = 0; i < argcnt; i++) {
5921 		nfs_argop4 *op = &argbase[i];
5922 		switch (op->argop) {
5923 		case OP_CPUTFH:
5924 		case OP_PUTFH:
5925 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
5926 			break;
5927 		case OP_PUTROOTFH:
5928 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
5929 			break;
5930 		case OP_CLOOKUP:
5931 			s = op->nfs_argop4_u.opclookup.cname;
5932 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5933 			break;
5934 		case OP_LOOKUP:
5935 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
5936 			    &len, NULL);
5937 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5938 			kmem_free(s, len);
5939 			break;
5940 		case OP_LOOKUPP:
5941 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
5942 			break;
5943 		case OP_GETFH:
5944 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
5945 			break;
5946 		case OP_GETATTR:
5947 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
5948 			break;
5949 		case OP_OPENATTR:
5950 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
5951 			break;
5952 		default:
5953 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
5954 			    op->argop);
5955 			break;
5956 		}
5957 	}
5958 }
5959 #endif
5960 
5961 /*
5962  * nfs4lookup_setup - constructs a multi-lookup compound request.
5963  *
5964  * Given the path "nm1/nm2/.../nmn", the following compound requests
5965  * may be created:
5966  *
5967  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
5968  * is faster, for now.
5969  *
5970  * l4_getattrs indicates the type of compound requested.
5971  *
5972  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
5973  *
5974  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
5975  *
5976  *   total number of ops is n + 1.
5977  *
5978  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
5979  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
5980  *      before the last component, and only get attributes
5981  *      for the last component.  Note that the second-to-last
5982  *	pathname component is XATTR_RPATH, which does NOT go
5983  *	over-the-wire as a lookup.
5984  *
5985  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
5986  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
5987  *
5988  *   and total number of ops is n + 5.
5989  *
5990  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
5991  *      attribute directory: create lookups plus an OPENATTR
5992  *	replacing the last lookup.  Note that the last pathname
5993  *	component is XATTR_RPATH, which does NOT go over-the-wire
5994  *	as a lookup.
5995  *
5996  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
5997  *		Openattr; Getfh; Getattr }
5998  *
5999  *   and total number of ops is n + 5.
6000  *
6001  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6002  *	nodes too.
6003  *
6004  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6005  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6006  *
6007  *   and total number of ops is 3*n + 1.
6008  *
6009  * All cases: returns the index in the arg array of the final LOOKUP op, or
6010  * -1 if no LOOKUPs were used.
6011  */
6012 int
6013 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6014 {
6015 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6016 	nfs_argop4 *argbase, *argop;
6017 	int arglen, argcnt;
6018 	int n = 1;	/* number of components */
6019 	int nga = 1;	/* number of Getattr's in request */
6020 	char c = '\0', *s, *p;
6021 	int lookup_idx = -1;
6022 	int argoplist_size;
6023 
6024 	/* set lookuparg response result to 0 */
6025 	lookupargp->resp->status = NFS4_OK;
6026 
6027 	/* skip leading "/" or "." e.g. ".//./" if there is */
6028 	for (; ; nm++) {
6029 		if (*nm != '/' && *nm != '.')
6030 			break;
6031 
6032 		/* ".." is counted as 1 component */
6033 		if (*nm == '.' && *(nm + 1) == '.')
6034 			break;
6035 	}
6036 
6037 	/*
6038 	 * Find n = number of components - nm must be null terminated
6039 	 * Skip "." components.
6040 	 */
6041 	if (*nm != '\0') {
6042 		for (n = 1, s = nm; *s != '\0'; s++) {
6043 			if ((*s == '/') && (*(s + 1) != '/') &&
6044 				    (*(s + 1) != '\0') &&
6045 				    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6046 					*(s + 2) == '\0')))
6047 				n++;
6048 		}
6049 	} else
6050 		n = 0;
6051 
6052 	/*
6053 	 * nga is number of components that need Getfh+Getattr
6054 	 */
6055 	switch (l4_getattrs) {
6056 	case LKP4_NO_ATTRIBUTES:
6057 		nga = 0;
6058 		break;
6059 	case LKP4_ALL_ATTRIBUTES:
6060 		nga = n;
6061 		/*
6062 		 * Always have at least 1 getfh, getattr pair
6063 		 */
6064 		if (nga == 0)
6065 			nga++;
6066 		break;
6067 	case LKP4_LAST_ATTRDIR:
6068 	case LKP4_LAST_NAMED_ATTR:
6069 		nga = n+1;
6070 		break;
6071 	}
6072 
6073 	/*
6074 	 * If change to use the filehandle attr instead of getfh
6075 	 * the following line can be deleted.
6076 	 */
6077 	nga *= 2;
6078 
6079 	/*
6080 	 * calculate number of ops in request as
6081 	 * header + trailer + lookups + getattrs
6082 	 */
6083 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6084 
6085 	argoplist_size = arglen * sizeof (nfs_argop4);
6086 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6087 	lookupargp->argsp->array = argop;
6088 
6089 	argcnt = lookupargp->header_len;
6090 	argop += argcnt;
6091 
6092 	/*
6093 	 * loop and create a lookup op and possibly getattr/getfh for
6094 	 * each component. Skip "." components.
6095 	 */
6096 	for (s = nm; *s != '\0'; s = p) {
6097 		/*
6098 		 * Set up a pathname struct for each component if needed
6099 		 */
6100 		while (*s == '/')
6101 			s++;
6102 		if (*s == '\0')
6103 			break;
6104 		for (p = s; (*p != '/') && (*p != '\0'); p++);
6105 		c = *p;
6106 		*p = '\0';
6107 
6108 		if (s[0] == '.' && s[1] == '\0') {
6109 			*p = c;
6110 			continue;
6111 		}
6112 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6113 		    strcmp(s, XATTR_RPATH) == 0) {
6114 			/* getfh XXX may not be needed in future */
6115 			argop->argop = OP_GETFH;
6116 			argop++;
6117 			argcnt++;
6118 
6119 			/* getattr */
6120 			argop->argop = OP_GETATTR;
6121 			argop->nfs_argop4_u.opgetattr.attr_request =
6122 							lookupargp->ga_bits;
6123 			argop->nfs_argop4_u.opgetattr.mi =
6124 				lookupargp->mi;
6125 			argop++;
6126 			argcnt++;
6127 
6128 			/* openattr */
6129 			argop->argop = OP_OPENATTR;
6130 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6131 		    strcmp(s, XATTR_RPATH) == 0) {
6132 			/* openattr */
6133 			argop->argop = OP_OPENATTR;
6134 			argop++;
6135 			argcnt++;
6136 
6137 			/* getfh XXX may not be needed in future */
6138 			argop->argop = OP_GETFH;
6139 			argop++;
6140 			argcnt++;
6141 
6142 			/* getattr */
6143 			argop->argop = OP_GETATTR;
6144 			argop->nfs_argop4_u.opgetattr.attr_request =
6145 							lookupargp->ga_bits;
6146 			argop->nfs_argop4_u.opgetattr.mi =
6147 							lookupargp->mi;
6148 			argop++;
6149 			argcnt++;
6150 			*p = c;
6151 			continue;
6152 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6153 			/* lookupp */
6154 			argop->argop = OP_LOOKUPP;
6155 		} else {
6156 			/* lookup */
6157 			argop->argop = OP_LOOKUP;
6158 			(void) str_to_utf8(s,
6159 				&argop->nfs_argop4_u.oplookup.objname);
6160 		}
6161 		lookup_idx = argcnt;
6162 		argop++;
6163 		argcnt++;
6164 
6165 		*p = c;
6166 
6167 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6168 			/* getfh XXX may not be needed in future */
6169 			argop->argop = OP_GETFH;
6170 			argop++;
6171 			argcnt++;
6172 
6173 			/* getattr */
6174 			argop->argop = OP_GETATTR;
6175 			argop->nfs_argop4_u.opgetattr.attr_request =
6176 							lookupargp->ga_bits;
6177 			argop->nfs_argop4_u.opgetattr.mi =
6178 							lookupargp->mi;
6179 			argop++;
6180 			argcnt++;
6181 		}
6182 	}
6183 
6184 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6185 		((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6186 		if (needgetfh) {
6187 			/* stick in a post-lookup getfh */
6188 			argop->argop = OP_GETFH;
6189 			argcnt++;
6190 			argop++;
6191 		}
6192 		/* post-lookup getattr */
6193 		argop->argop = OP_GETATTR;
6194 		argop->nfs_argop4_u.opgetattr.attr_request =
6195 						lookupargp->ga_bits;
6196 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6197 		argcnt++;
6198 	}
6199 	argcnt += lookupargp->trailer_len;	/* actual op count */
6200 	lookupargp->argsp->array_len = argcnt;
6201 	lookupargp->arglen = arglen;
6202 
6203 #ifdef DEBUG
6204 	if (nfs4_client_lookup_debug)
6205 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6206 #endif
6207 
6208 	return (lookup_idx);
6209 }
6210 
6211 static int
6212 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6213 {
6214 	COMPOUND4args_clnt	args;
6215 	COMPOUND4res_clnt	res;
6216 	GETFH4res	*gf_res = NULL;
6217 	nfs_argop4	argop[4];
6218 	nfs_resop4	*resop = NULL;
6219 	nfs4_sharedfh_t *sfhp;
6220 	hrtime_t t;
6221 	nfs4_error_t	e;
6222 
6223 	rnode4_t	*drp;
6224 	int		doqueue = 1;
6225 	vnode_t		*vp;
6226 	int		needrecov = 0;
6227 	nfs4_recov_state_t recov_state;
6228 
6229 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6230 
6231 	*avp = NULL;
6232 	recov_state.rs_flags = 0;
6233 	recov_state.rs_num_retry_despite_err = 0;
6234 
6235 recov_retry:
6236 	/* COMPOUND: putfh, openattr, getfh, getattr */
6237 	args.array_len = 4;
6238 	args.array = argop;
6239 	args.ctag = TAG_OPENATTR;
6240 
6241 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6242 	if (e.error)
6243 		return (e.error);
6244 
6245 	drp = VTOR4(dvp);
6246 
6247 	/* putfh */
6248 	argop[0].argop = OP_CPUTFH;
6249 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6250 
6251 	/* openattr */
6252 	argop[1].argop = OP_OPENATTR;
6253 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6254 
6255 	/* getfh */
6256 	argop[2].argop = OP_GETFH;
6257 
6258 	/* getattr */
6259 	argop[3].argop = OP_GETATTR;
6260 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6261 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6262 
6263 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6264 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6265 	    rnode4info(drp)));
6266 
6267 	t = gethrtime();
6268 
6269 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6270 
6271 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6272 	if (needrecov) {
6273 		bool_t abort;
6274 
6275 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6276 		    "nfs4openattr: initiating recovery\n"));
6277 
6278 		abort = nfs4_start_recovery(&e,
6279 				VTOMI4(dvp), dvp, NULL, NULL, NULL,
6280 				OP_OPENATTR, NULL);
6281 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6282 		if (!e.error) {
6283 			e.error = geterrno4(res.status);
6284 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6285 		}
6286 		if (abort == FALSE)
6287 			goto recov_retry;
6288 		return (e.error);
6289 	}
6290 
6291 	if (e.error) {
6292 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6293 		return (e.error);
6294 	}
6295 
6296 	if (res.status) {
6297 		/*
6298 		 * If OTW errro is NOTSUPP, then it should be
6299 		 * translated to EINVAL.  All Solaris file system
6300 		 * implementations return EINVAL to the syscall layer
6301 		 * when the attrdir cannot be created due to an
6302 		 * implementation restriction or noxattr mount option.
6303 		 */
6304 		if (res.status == NFS4ERR_NOTSUPP) {
6305 			mutex_enter(&drp->r_statelock);
6306 			if (drp->r_xattr_dir)
6307 				VN_RELE(drp->r_xattr_dir);
6308 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6309 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6310 			mutex_exit(&drp->r_statelock);
6311 
6312 			e.error = EINVAL;
6313 		} else {
6314 			e.error = geterrno4(res.status);
6315 		}
6316 
6317 		if (e.error) {
6318 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6319 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6320 				    needrecov);
6321 			return (e.error);
6322 		}
6323 	}
6324 
6325 	resop = &res.array[0];  /* putfh res */
6326 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6327 
6328 	resop = &res.array[1];  /* openattr res */
6329 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6330 
6331 	resop = &res.array[2];  /* getfh res */
6332 	gf_res = &resop->nfs_resop4_u.opgetfh;
6333 	if (gf_res->object.nfs_fh4_len == 0) {
6334 		*avp = NULL;
6335 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6336 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6337 		return (ENOENT);
6338 	}
6339 
6340 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6341 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6342 				dvp->v_vfsp, t, cr, dvp,
6343 				fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH));
6344 	sfh4_rele(&sfhp);
6345 
6346 	if (e.error)
6347 		PURGE_ATTRCACHE4(vp);
6348 
6349 	mutex_enter(&vp->v_lock);
6350 	vp->v_flag |= V_XATTRDIR;
6351 	mutex_exit(&vp->v_lock);
6352 
6353 	*avp = vp;
6354 
6355 	mutex_enter(&drp->r_statelock);
6356 	if (drp->r_xattr_dir)
6357 		VN_RELE(drp->r_xattr_dir);
6358 	VN_HOLD(vp);
6359 	drp->r_xattr_dir = vp;
6360 
6361 	/*
6362 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6363 	 * NULL.  xattrs could be created at any time, and we have no
6364 	 * way to update pc4_xattr_exists in the base object if/when
6365 	 * it happens.
6366 	 */
6367 	drp->r_pathconf.pc4_xattr_valid = 0;
6368 
6369 	mutex_exit(&drp->r_statelock);
6370 
6371 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6372 
6373 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6374 
6375 	return (0);
6376 }
6377 
6378 /* ARGSUSED */
6379 static int
6380 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6381 	int mode, vnode_t **vpp, cred_t *cr, int flags)
6382 {
6383 	int error;
6384 	vnode_t *vp = NULL;
6385 	rnode4_t *rp;
6386 	struct vattr vattr;
6387 	rnode4_t *drp;
6388 	vnode_t *tempvp;
6389 	enum createmode4 createmode;
6390 	bool_t must_trunc = FALSE;
6391 	int	truncating = 0;
6392 
6393 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6394 		return (EPERM);
6395 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6396 		return (EINVAL);
6397 	}
6398 
6399 	/* . and .. have special meaning in the protocol, reject them. */
6400 
6401 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6402 		return (EISDIR);
6403 
6404 	drp = VTOR4(dvp);
6405 
6406 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6407 		return (EINTR);
6408 
6409 top:
6410 	/*
6411 	 * We make a copy of the attributes because the caller does not
6412 	 * expect us to change what va points to.
6413 	 */
6414 	vattr = *va;
6415 
6416 	/*
6417 	 * If the pathname is "", then dvp is the root vnode of
6418 	 * a remote file mounted over a local directory.
6419 	 * All that needs to be done is access
6420 	 * checking and truncation.  Note that we avoid doing
6421 	 * open w/ create because the parent directory might
6422 	 * be in pseudo-fs and the open would fail.
6423 	 */
6424 	if (*nm == '\0') {
6425 		error = 0;
6426 		VN_HOLD(dvp);
6427 		vp = dvp;
6428 		must_trunc = TRUE;
6429 	} else {
6430 		/*
6431 		 * We need to go over the wire, just to be sure whether the
6432 		 * file exists or not.  Using the DNLC can be dangerous in
6433 		 * this case when making a decision regarding existence.
6434 		 */
6435 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6436 	}
6437 
6438 	if (exclusive)
6439 		createmode = EXCLUSIVE4;
6440 	else
6441 		createmode = GUARDED4;
6442 
6443 	/*
6444 	 * error would be set if the file does not exist on the
6445 	 * server, so lets go create it.
6446 	 */
6447 	if (error) {
6448 		goto create_otw;
6449 	}
6450 
6451 	/*
6452 	 * File does exist on the server
6453 	 */
6454 	if (exclusive == EXCL)
6455 		error = EEXIST;
6456 	else if (vp->v_type == VDIR && (mode & VWRITE))
6457 		error = EISDIR;
6458 	else {
6459 		/*
6460 		 * If vnode is a device, create special vnode.
6461 		 */
6462 		if (ISVDEV(vp->v_type)) {
6463 			tempvp = vp;
6464 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6465 			VN_RELE(tempvp);
6466 		}
6467 		if (!(error = VOP_ACCESS(vp, mode, 0, cr))) {
6468 			if ((vattr.va_mask & AT_SIZE) &&
6469 			    vp->v_type == VREG) {
6470 				rp = VTOR4(vp);
6471 				/*
6472 				 * Check here for large file handled
6473 				 * by LF-unaware process (as
6474 				 * ufs_create() does)
6475 				 */
6476 				if (!(flags & FOFFMAX)) {
6477 					mutex_enter(&rp->r_statelock);
6478 					if (rp->r_size > MAXOFF32_T)
6479 						error = EOVERFLOW;
6480 					mutex_exit(&rp->r_statelock);
6481 				}
6482 
6483 				/* if error is set then we need to return */
6484 				if (error) {
6485 					nfs_rw_exit(&drp->r_rwlock);
6486 					VN_RELE(vp);
6487 					return (error);
6488 				}
6489 
6490 				if (must_trunc) {
6491 					vattr.va_mask = AT_SIZE;
6492 					error = nfs4setattr(vp, &vattr, 0, cr,
6493 						NULL);
6494 				} else {
6495 				/*
6496 				 * we know we have a regular file that already
6497 				 * exists and we may end up truncating the file
6498 				 * as a result of the open_otw, so flush out
6499 				 * any dirty pages for this file first.
6500 				 */
6501 					if (nfs4_has_pages(vp) &&
6502 					    ((rp->r_flags & R4DIRTY) ||
6503 					    rp->r_count > 0 ||
6504 					    rp->r_mapcnt > 0)) {
6505 						error = nfs4_putpage(vp,
6506 							(offset_t)0, 0, 0, cr);
6507 						if (error && (error == ENOSPC ||
6508 						    error == EDQUOT)) {
6509 							mutex_enter(
6510 							    &rp->r_statelock);
6511 							if (!rp->r_error)
6512 								rp->r_error =
6513 								    error;
6514 							mutex_exit(
6515 							    &rp->r_statelock);
6516 						}
6517 					}
6518 					vattr.va_mask = (AT_SIZE |
6519 							AT_TYPE | AT_MODE);
6520 					vattr.va_type = VREG;
6521 					createmode = UNCHECKED4;
6522 					truncating = 1;
6523 					goto create_otw;
6524 				}
6525 			}
6526 		}
6527 	}
6528 	nfs_rw_exit(&drp->r_rwlock);
6529 	if (error) {
6530 		VN_RELE(vp);
6531 	} else {
6532 		vnode_t *tvp;
6533 		rnode4_t *trp;
6534 		/*
6535 		 * existing file got truncated, notify.
6536 		 */
6537 		tvp = vp;
6538 		if (vp->v_type == VREG) {
6539 			trp = VTOR4(vp);
6540 			if (IS_SHADOW(vp, trp))
6541 				tvp = RTOV4(trp);
6542 		}
6543 		vnevent_create(tvp);
6544 		*vpp = vp;
6545 	}
6546 	return (error);
6547 
6548 create_otw:
6549 	dnlc_remove(dvp, nm);
6550 
6551 	ASSERT(vattr.va_mask & AT_TYPE);
6552 
6553 	/*
6554 	 * If not a regular file let nfs4mknod() handle it.
6555 	 */
6556 	if (vattr.va_type != VREG) {
6557 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6558 		nfs_rw_exit(&drp->r_rwlock);
6559 		return (error);
6560 	}
6561 
6562 	/*
6563 	 * It _is_ a regular file.
6564 	 */
6565 	ASSERT(vattr.va_mask & AT_MODE);
6566 	if (MANDMODE(vattr.va_mode)) {
6567 		nfs_rw_exit(&drp->r_rwlock);
6568 		return (EACCES);
6569 	}
6570 
6571 	/*
6572 	 * If this happens to be a mknod of a regular file, then flags will
6573 	 * have neither FREAD or FWRITE.  However, we must set at least one
6574 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6575 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6576 	 * set (based on openmode specified by app).
6577 	 */
6578 	if ((flags & (FREAD|FWRITE)) == 0)
6579 		flags |= (FREAD|FWRITE);
6580 
6581 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6582 
6583 	if (vp != NULL) {
6584 		/* if create was successful, throw away the file's pages */
6585 		if (!error && (vattr.va_mask & AT_SIZE))
6586 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6587 				cr);
6588 		/* release the lookup hold */
6589 		VN_RELE(vp);
6590 		vp = NULL;
6591 	}
6592 
6593 	/*
6594 	 * validate that we opened a regular file. This handles a misbehaving
6595 	 * server that returns an incorrect FH.
6596 	 */
6597 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6598 		error = EISDIR;
6599 		VN_RELE(*vpp);
6600 	}
6601 
6602 	/*
6603 	 * If this is not an exclusive create, then the CREATE
6604 	 * request will be made with the GUARDED mode set.  This
6605 	 * means that the server will return EEXIST if the file
6606 	 * exists.  The file could exist because of a retransmitted
6607 	 * request.  In this case, we recover by starting over and
6608 	 * checking to see whether the file exists.  This second
6609 	 * time through it should and a CREATE request will not be
6610 	 * sent.
6611 	 *
6612 	 * This handles the problem of a dangling CREATE request
6613 	 * which contains attributes which indicate that the file
6614 	 * should be truncated.  This retransmitted request could
6615 	 * possibly truncate valid data in the file if not caught
6616 	 * by the duplicate request mechanism on the server or if
6617 	 * not caught by other means.  The scenario is:
6618 	 *
6619 	 * Client transmits CREATE request with size = 0
6620 	 * Client times out, retransmits request.
6621 	 * Response to the first request arrives from the server
6622 	 *  and the client proceeds on.
6623 	 * Client writes data to the file.
6624 	 * The server now processes retransmitted CREATE request
6625 	 *  and truncates file.
6626 	 *
6627 	 * The use of the GUARDED CREATE request prevents this from
6628 	 * happening because the retransmitted CREATE would fail
6629 	 * with EEXIST and would not truncate the file.
6630 	 */
6631 	if (error == EEXIST && exclusive == NONEXCL) {
6632 #ifdef DEBUG
6633 		nfs4_create_misses++;
6634 #endif
6635 		goto top;
6636 	}
6637 	nfs_rw_exit(&drp->r_rwlock);
6638 	if (truncating && !error && *vpp) {
6639 		vnode_t *tvp;
6640 		rnode4_t *trp;
6641 		/*
6642 		 * existing file got truncated, notify.
6643 		 */
6644 		tvp = *vpp;
6645 		trp = VTOR4(tvp);
6646 		if (IS_SHADOW(tvp, trp))
6647 			tvp = RTOV4(trp);
6648 		vnevent_create(tvp);
6649 	}
6650 	return (error);
6651 }
6652 
6653 /*
6654  * Create compound (for mkdir, mknod, symlink):
6655  * { Putfh <dfh>; Create; Getfh; Getattr }
6656  * It's okay if setattr failed to set gid - this is not considered
6657  * an error, but purge attrs in that case.
6658  */
6659 static int
6660 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6661 	vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6662 {
6663 	int need_end_op = FALSE;
6664 	COMPOUND4args_clnt args;
6665 	COMPOUND4res_clnt res, *resp = NULL;
6666 	nfs_argop4 *argop;
6667 	nfs_resop4 *resop;
6668 	int doqueue;
6669 	mntinfo4_t *mi;
6670 	rnode4_t *drp = VTOR4(dvp);
6671 	change_info4 *cinfo;
6672 	GETFH4res *gf_res;
6673 	struct vattr vattr;
6674 	vnode_t *vp;
6675 	fattr4 *crattr;
6676 	bool_t needrecov = FALSE;
6677 	nfs4_recov_state_t recov_state;
6678 	nfs4_sharedfh_t *sfhp = NULL;
6679 	hrtime_t t;
6680 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6681 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6682 	dirattr_info_t dinfo, *dinfop;
6683 	servinfo4_t *svp;
6684 	bitmap4 supp_attrs;
6685 
6686 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6687 		type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6688 
6689 	mi = VTOMI4(dvp);
6690 
6691 	/*
6692 	 * Make sure we properly deal with setting the right gid
6693 	 * on a new directory to reflect the parent's setgid bit
6694 	 */
6695 	setgid_flag = 0;
6696 	if (type == NF4DIR) {
6697 		struct vattr dva;
6698 
6699 		va->va_mode &= ~VSGID;
6700 		dva.va_mask = AT_MODE | AT_GID;
6701 		if (VOP_GETATTR(dvp, &dva, 0, cr) == 0) {
6702 
6703 			/*
6704 			 * If the parent's directory has the setgid bit set
6705 			 * _and_ the client was able to get a valid mapping
6706 			 * for the parent dir's owner_group, we want to
6707 			 * append NVERIFY(owner_group == dva.va_gid) and
6708 			 * SETTATTR to the CREATE compound.
6709 			 */
6710 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6711 				setgid_flag = 1;
6712 				va->va_mode |= VSGID;
6713 				if (dva.va_gid != GID_NOBODY) {
6714 					va->va_mask |= AT_GID;
6715 					va->va_gid = dva.va_gid;
6716 				}
6717 			}
6718 		}
6719 	}
6720 
6721 	/*
6722 	 * Create ops:
6723 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6724 	 *	5:restorefh(dir) 6:getattr(dir)
6725 	 *
6726 	 * if (setgid)
6727 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6728 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6729 	 *	8:nverify 9:setattr
6730 	 */
6731 	if (setgid_flag) {
6732 		numops = 10;
6733 		idx_create = 1;
6734 		idx_fattr = 3;
6735 	} else {
6736 		numops = 7;
6737 		idx_create = 2;
6738 		idx_fattr = 4;
6739 	}
6740 
6741 	ASSERT(nfs_zone() == mi->mi_zone);
6742 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6743 		return (EINTR);
6744 	}
6745 	recov_state.rs_flags = 0;
6746 	recov_state.rs_num_retry_despite_err = 0;
6747 
6748 	argoplist_size = numops * sizeof (nfs_argop4);
6749 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6750 
6751 recov_retry:
6752 	if (type == NF4LNK)
6753 		args.ctag = TAG_SYMLINK;
6754 	else if (type == NF4DIR)
6755 		args.ctag = TAG_MKDIR;
6756 	else
6757 		args.ctag = TAG_MKNOD;
6758 
6759 	args.array_len = numops;
6760 	args.array = argop;
6761 
6762 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6763 		nfs_rw_exit(&drp->r_rwlock);
6764 		kmem_free(argop, argoplist_size);
6765 		return (e.error);
6766 	}
6767 	need_end_op = TRUE;
6768 
6769 
6770 	/* 0: putfh directory */
6771 	argop[0].argop = OP_CPUTFH;
6772 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6773 
6774 	/* 1/2: Create object */
6775 	argop[idx_create].argop = OP_CCREATE;
6776 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6777 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6778 	if (type == NF4LNK) {
6779 		/*
6780 		 * symlink, treat name as data
6781 		 */
6782 		ASSERT(data != NULL);
6783 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6784 							(char *)data;
6785 	}
6786 	if (type == NF4BLK || type == NF4CHR) {
6787 		ASSERT(data != NULL);
6788 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6789 							*((specdata4 *)data);
6790 	}
6791 
6792 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6793 
6794 	svp = drp->r_server;
6795 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6796 	supp_attrs = svp->sv_supp_attrs;
6797 	nfs_rw_exit(&svp->sv_lock);
6798 
6799 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6800 		nfs_rw_exit(&drp->r_rwlock);
6801 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6802 		e.error = EINVAL;
6803 		kmem_free(argop, argoplist_size);
6804 		return (e.error);
6805 	}
6806 
6807 	/* 2/3: getfh fh of created object */
6808 	ASSERT(idx_create + 1 == idx_fattr - 1);
6809 	argop[idx_create + 1].argop = OP_GETFH;
6810 
6811 	/* 3/4: getattr of new object */
6812 	argop[idx_fattr].argop = OP_GETATTR;
6813 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6814 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6815 
6816 	if (setgid_flag) {
6817 		vattr_t	_v;
6818 
6819 		argop[4].argop = OP_SAVEFH;
6820 
6821 		argop[5].argop = OP_CPUTFH;
6822 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6823 
6824 		argop[6].argop = OP_GETATTR;
6825 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6826 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6827 
6828 		argop[7].argop = OP_RESTOREFH;
6829 
6830 		/*
6831 		 * nverify
6832 		 *
6833 		 * XXX - Revisit the last argument to nfs4_end_op()
6834 		 *	 once 5020486 is fixed.
6835 		 */
6836 		_v.va_mask = AT_GID;
6837 		_v.va_gid = va->va_gid;
6838 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6839 		    supp_attrs)) {
6840 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6841 			nfs_rw_exit(&drp->r_rwlock);
6842 			nfs4_fattr4_free(crattr);
6843 			kmem_free(argop, argoplist_size);
6844 			return (e.error);
6845 		}
6846 
6847 		/*
6848 		 * setattr
6849 		 *
6850 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
6851 		 * so no need for stateid or flags. Also we specify NULL
6852 		 * rp since we're only interested in setting owner_group
6853 		 * attributes.
6854 		 */
6855 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
6856 		    &e.error, 0);
6857 
6858 		if (e.error) {
6859 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6860 			nfs_rw_exit(&drp->r_rwlock);
6861 			nfs4_fattr4_free(crattr);
6862 			nfs4args_verify_free(&argop[8]);
6863 			kmem_free(argop, argoplist_size);
6864 			return (e.error);
6865 		}
6866 	} else {
6867 		argop[1].argop = OP_SAVEFH;
6868 
6869 		argop[5].argop = OP_RESTOREFH;
6870 
6871 		argop[6].argop = OP_GETATTR;
6872 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6873 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6874 	}
6875 
6876 	dnlc_remove(dvp, nm);
6877 
6878 	doqueue = 1;
6879 	t = gethrtime();
6880 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
6881 
6882 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
6883 	if (e.error) {
6884 		PURGE_ATTRCACHE4(dvp);
6885 		if (!needrecov)
6886 			goto out;
6887 	}
6888 
6889 	if (needrecov) {
6890 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
6891 		    OP_CREATE, NULL) == FALSE) {
6892 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6893 				    needrecov);
6894 			need_end_op = FALSE;
6895 			nfs4_fattr4_free(crattr);
6896 			if (setgid_flag) {
6897 				nfs4args_verify_free(&argop[8]);
6898 				nfs4args_setattr_free(&argop[9]);
6899 			}
6900 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6901 			goto recov_retry;
6902 		}
6903 	}
6904 
6905 	resp = &res;
6906 
6907 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
6908 
6909 		if (res.status == NFS4ERR_BADOWNER)
6910 			nfs4_log_badowner(mi, OP_CREATE);
6911 
6912 		e.error = geterrno4(res.status);
6913 
6914 		/*
6915 		 * This check is left over from when create was implemented
6916 		 * using a setattr op (instead of createattrs).  If the
6917 		 * putfh/create/getfh failed, the error was returned.  If
6918 		 * setattr/getattr failed, we keep going.
6919 		 *
6920 		 * It might be better to get rid of the GETFH also, and just
6921 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
6922 		 * Then if any of the operations failed, we could return the
6923 		 * error now, and remove much of the error code below.
6924 		 */
6925 		if (res.array_len <= idx_fattr) {
6926 			/*
6927 			 * Either Putfh, Create or Getfh failed.
6928 			 */
6929 			PURGE_ATTRCACHE4(dvp);
6930 			/*
6931 			 * nfs4_purge_stale_fh() may generate otw calls through
6932 			 * nfs4_invalidate_pages. Hence the need to call
6933 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
6934 			 */
6935 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6936 			    needrecov);
6937 			need_end_op = FALSE;
6938 			nfs4_purge_stale_fh(e.error, dvp, cr);
6939 			goto out;
6940 		}
6941 	}
6942 
6943 	resop = &res.array[idx_create];	/* create res */
6944 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
6945 
6946 	resop = &res.array[idx_create + 1]; /* getfh res */
6947 	gf_res = &resop->nfs_resop4_u.opgetfh;
6948 
6949 	sfhp = sfh4_get(&gf_res->object, mi);
6950 	if (e.error) {
6951 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
6952 		    fn_get(VTOSV(dvp)->sv_name, nm));
6953 		if (vp->v_type == VNON) {
6954 			vattr.va_mask = AT_TYPE;
6955 			/*
6956 			 * Need to call nfs4_end_op before nfs4getattr to avoid
6957 			 * potential nfs4_start_op deadlock. See RFE 4777612.
6958 			 */
6959 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6960 				needrecov);
6961 			need_end_op = FALSE;
6962 			e.error = nfs4getattr(vp, &vattr, cr);
6963 			if (e.error) {
6964 				VN_RELE(vp);
6965 				*vpp = NULL;
6966 				goto out;
6967 			}
6968 			vp->v_type = vattr.va_type;
6969 		}
6970 		e.error = 0;
6971 	} else {
6972 		*vpp = vp = makenfs4node(sfhp,
6973 			&res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
6974 			dvp->v_vfsp, t, cr,
6975 			dvp, fn_get(VTOSV(dvp)->sv_name, nm));
6976 	}
6977 
6978 	/*
6979 	 * If compound succeeded, then update dir attrs
6980 	 */
6981 	if (res.status == NFS4_OK) {
6982 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
6983 		dinfo.di_cred = cr;
6984 		dinfo.di_time_call = t;
6985 		dinfop = &dinfo;
6986 	} else
6987 		dinfop = NULL;
6988 
6989 	/* Update directory cache attribute, readdir and dnlc caches */
6990 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
6991 
6992 out:
6993 	if (sfhp != NULL)
6994 		sfh4_rele(&sfhp);
6995 	nfs_rw_exit(&drp->r_rwlock);
6996 	nfs4_fattr4_free(crattr);
6997 	if (setgid_flag) {
6998 		nfs4args_verify_free(&argop[8]);
6999 		nfs4args_setattr_free(&argop[9]);
7000 	}
7001 	if (resp)
7002 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7003 	if (need_end_op)
7004 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7005 
7006 	kmem_free(argop, argoplist_size);
7007 	return (e.error);
7008 }
7009 
7010 /* ARGSUSED */
7011 static int
7012 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7013 	int mode, vnode_t **vpp, cred_t *cr)
7014 {
7015 	int error;
7016 	vnode_t *vp;
7017 	nfs_ftype4 type;
7018 	specdata4 spec, *specp = NULL;
7019 
7020 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7021 
7022 	switch (va->va_type) {
7023 	case VCHR:
7024 	case VBLK:
7025 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7026 		spec.specdata1 = getmajor(va->va_rdev);
7027 		spec.specdata2 = getminor(va->va_rdev);
7028 		specp = &spec;
7029 		break;
7030 
7031 	case VFIFO:
7032 		type = NF4FIFO;
7033 		break;
7034 	case VSOCK:
7035 		type = NF4SOCK;
7036 		break;
7037 
7038 	default:
7039 		return (EINVAL);
7040 	}
7041 
7042 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7043 	if (error) {
7044 		return (error);
7045 	}
7046 
7047 	/*
7048 	 * This might not be needed any more; special case to deal
7049 	 * with problematic v2/v3 servers.  Since create was unable
7050 	 * to set group correctly, not sure what hope setattr has.
7051 	 */
7052 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7053 		va->va_mask = AT_GID;
7054 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7055 	}
7056 
7057 	/*
7058 	 * If vnode is a device create special vnode
7059 	 */
7060 	if (ISVDEV(vp->v_type)) {
7061 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7062 		VN_RELE(vp);
7063 	} else {
7064 		*vpp = vp;
7065 	}
7066 	return (error);
7067 }
7068 
7069 /*
7070  * Remove requires that the current fh be the target directory.
7071  * After the operation, the current fh is unchanged.
7072  * The compound op structure is:
7073  *      PUTFH(targetdir), REMOVE
7074  *
7075  * Weirdness: if the vnode to be removed is open
7076  * we rename it instead of removing it and nfs_inactive
7077  * will remove the new name.
7078  */
7079 static int
7080 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr)
7081 {
7082 	COMPOUND4args_clnt args;
7083 	COMPOUND4res_clnt res, *resp = NULL;
7084 	REMOVE4res *rm_res;
7085 	nfs_argop4 argop[3];
7086 	nfs_resop4 *resop;
7087 	vnode_t *vp;
7088 	char *tmpname;
7089 	int doqueue;
7090 	mntinfo4_t *mi;
7091 	rnode4_t *rp;
7092 	rnode4_t *drp;
7093 	int needrecov = 0;
7094 	nfs4_recov_state_t recov_state;
7095 	int isopen;
7096 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7097 	dirattr_info_t dinfo;
7098 
7099 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7100 		return (EPERM);
7101 	drp = VTOR4(dvp);
7102 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7103 		return (EINTR);
7104 
7105 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7106 	if (e.error) {
7107 		nfs_rw_exit(&drp->r_rwlock);
7108 		return (e.error);
7109 	}
7110 
7111 	if (vp->v_type == VDIR) {
7112 		VN_RELE(vp);
7113 		nfs_rw_exit(&drp->r_rwlock);
7114 		return (EISDIR);
7115 	}
7116 
7117 	/*
7118 	 * First just remove the entry from the name cache, as it
7119 	 * is most likely the only entry for this vp.
7120 	 */
7121 	dnlc_remove(dvp, nm);
7122 
7123 	rp = VTOR4(vp);
7124 
7125 	/*
7126 	 * For regular file types, check to see if the file is open by looking
7127 	 * at the open streams.
7128 	 * For all other types, check the reference count on the vnode.  Since
7129 	 * they are not opened OTW they never have an open stream.
7130 	 *
7131 	 * If the file is open, rename it to .nfsXXXX.
7132 	 */
7133 	if (vp->v_type != VREG) {
7134 		/*
7135 		 * If the file has a v_count > 1 then there may be more than one
7136 		 * entry in the name cache due multiple links or an open file,
7137 		 * but we don't have the real reference count so flush all
7138 		 * possible entries.
7139 		 */
7140 		if (vp->v_count > 1)
7141 			dnlc_purge_vp(vp);
7142 
7143 		/*
7144 		 * Now we have the real reference count.
7145 		 */
7146 		isopen = vp->v_count > 1;
7147 	} else {
7148 		mutex_enter(&rp->r_os_lock);
7149 		isopen = list_head(&rp->r_open_streams) != NULL;
7150 		mutex_exit(&rp->r_os_lock);
7151 	}
7152 
7153 	mutex_enter(&rp->r_statelock);
7154 	if (isopen &&
7155 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7156 		mutex_exit(&rp->r_statelock);
7157 		tmpname = newname();
7158 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr);
7159 		if (e.error)
7160 			kmem_free(tmpname, MAXNAMELEN);
7161 		else {
7162 			mutex_enter(&rp->r_statelock);
7163 			if (rp->r_unldvp == NULL) {
7164 				VN_HOLD(dvp);
7165 				rp->r_unldvp = dvp;
7166 				if (rp->r_unlcred != NULL)
7167 					crfree(rp->r_unlcred);
7168 				crhold(cr);
7169 				rp->r_unlcred = cr;
7170 				rp->r_unlname = tmpname;
7171 			} else {
7172 				kmem_free(rp->r_unlname, MAXNAMELEN);
7173 				rp->r_unlname = tmpname;
7174 			}
7175 			mutex_exit(&rp->r_statelock);
7176 		}
7177 		VN_RELE(vp);
7178 		nfs_rw_exit(&drp->r_rwlock);
7179 		return (e.error);
7180 	}
7181 	/*
7182 	 * Actually remove the file/dir
7183 	 */
7184 	mutex_exit(&rp->r_statelock);
7185 
7186 	/*
7187 	 * We need to flush any dirty pages which happen to
7188 	 * be hanging around before removing the file.
7189 	 * This shouldn't happen very often since in NFSv4
7190 	 * we should be close to open consistent.
7191 	 */
7192 	if (nfs4_has_pages(vp) &&
7193 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7194 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr);
7195 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7196 			mutex_enter(&rp->r_statelock);
7197 			if (!rp->r_error)
7198 				rp->r_error = e.error;
7199 			mutex_exit(&rp->r_statelock);
7200 		}
7201 	}
7202 
7203 	mi = VTOMI4(dvp);
7204 
7205 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7206 	recov_state.rs_flags = 0;
7207 	recov_state.rs_num_retry_despite_err = 0;
7208 
7209 recov_retry:
7210 	/*
7211 	 * Remove ops: putfh dir; remove
7212 	 */
7213 	args.ctag = TAG_REMOVE;
7214 	args.array_len = 3;
7215 	args.array = argop;
7216 
7217 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7218 	if (e.error) {
7219 		nfs_rw_exit(&drp->r_rwlock);
7220 		VN_RELE(vp);
7221 		return (e.error);
7222 	}
7223 
7224 	/* putfh directory */
7225 	argop[0].argop = OP_CPUTFH;
7226 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7227 
7228 	/* remove */
7229 	argop[1].argop = OP_CREMOVE;
7230 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7231 
7232 	/* getattr dir */
7233 	argop[2].argop = OP_GETATTR;
7234 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7235 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7236 
7237 	doqueue = 1;
7238 	dinfo.di_time_call = gethrtime();
7239 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7240 
7241 	PURGE_ATTRCACHE4(vp);
7242 
7243 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7244 	if (e.error)
7245 		PURGE_ATTRCACHE4(dvp);
7246 
7247 	if (needrecov) {
7248 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7249 		    NULL, NULL, NULL, OP_REMOVE, NULL) == FALSE) {
7250 			if (!e.error)
7251 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7252 								(caddr_t)&res);
7253 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7254 					needrecov);
7255 			goto recov_retry;
7256 		}
7257 	}
7258 
7259 	/*
7260 	 * Matching nfs4_end_op() for start_op() above.
7261 	 * There is a path in the code below which calls
7262 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7263 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7264 	 * here to avoid nfs4_start_op() deadlock.
7265 	 */
7266 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7267 
7268 	if (!e.error) {
7269 		resp = &res;
7270 
7271 		if (res.status) {
7272 			e.error = geterrno4(res.status);
7273 			PURGE_ATTRCACHE4(dvp);
7274 			nfs4_purge_stale_fh(e.error, dvp, cr);
7275 		} else {
7276 			resop = &res.array[1];	/* remove res */
7277 			rm_res = &resop->nfs_resop4_u.opremove;
7278 
7279 			dinfo.di_garp =
7280 				&res.array[2].nfs_resop4_u.opgetattr.ga_res;
7281 			dinfo.di_cred = cr;
7282 
7283 			/* Update directory attr, readdir and dnlc caches */
7284 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7285 				&dinfo);
7286 		}
7287 	}
7288 	nfs_rw_exit(&drp->r_rwlock);
7289 	if (resp)
7290 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7291 
7292 	if (e.error == 0) {
7293 		vnode_t *tvp;
7294 		rnode4_t *trp;
7295 		trp = VTOR4(vp);
7296 		tvp = vp;
7297 		if (IS_SHADOW(vp, trp))
7298 			tvp = RTOV4(trp);
7299 		vnevent_remove(tvp, dvp, nm);
7300 	}
7301 	VN_RELE(vp);
7302 	return (e.error);
7303 }
7304 
7305 /*
7306  * Link requires that the current fh be the target directory and the
7307  * saved fh be the source fh. After the operation, the current fh is unchanged.
7308  * Thus the compound op structure is:
7309  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7310  *	GETATTR(file)
7311  */
7312 static int
7313 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr)
7314 {
7315 	COMPOUND4args_clnt args;
7316 	COMPOUND4res_clnt res, *resp = NULL;
7317 	LINK4res *ln_res;
7318 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7319 	nfs_argop4 *argop;
7320 	nfs_resop4 *resop;
7321 	vnode_t *realvp, *nvp;
7322 	int doqueue;
7323 	mntinfo4_t *mi;
7324 	rnode4_t *tdrp;
7325 	bool_t needrecov = FALSE;
7326 	nfs4_recov_state_t recov_state;
7327 	hrtime_t t;
7328 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7329 	dirattr_info_t dinfo;
7330 
7331 	ASSERT(*tnm != '\0');
7332 	ASSERT(tdvp->v_type == VDIR);
7333 	ASSERT(nfs4_consistent_type(tdvp));
7334 	ASSERT(nfs4_consistent_type(svp));
7335 
7336 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7337 		return (EPERM);
7338 	if (VOP_REALVP(svp, &realvp) == 0) {
7339 		svp = realvp;
7340 		ASSERT(nfs4_consistent_type(svp));
7341 	}
7342 
7343 	tdrp = VTOR4(tdvp);
7344 	mi = VTOMI4(svp);
7345 
7346 	if (!(mi->mi_flags & MI4_LINK)) {
7347 		return (EOPNOTSUPP);
7348 	}
7349 	recov_state.rs_flags = 0;
7350 	recov_state.rs_num_retry_despite_err = 0;
7351 
7352 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7353 		return (EINTR);
7354 
7355 recov_retry:
7356 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7357 
7358 	args.ctag = TAG_LINK;
7359 
7360 	/*
7361 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7362 	 * restorefh; getattr(fl)
7363 	 */
7364 	args.array_len = 7;
7365 	args.array = argop;
7366 
7367 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7368 	if (e.error) {
7369 		kmem_free(argop, argoplist_size);
7370 		nfs_rw_exit(&tdrp->r_rwlock);
7371 		return (e.error);
7372 	}
7373 
7374 	/* 0. putfh file */
7375 	argop[0].argop = OP_CPUTFH;
7376 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7377 
7378 	/* 1. save current fh to free up the space for the dir */
7379 	argop[1].argop = OP_SAVEFH;
7380 
7381 	/* 2. putfh targetdir */
7382 	argop[2].argop = OP_CPUTFH;
7383 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7384 
7385 	/* 3. link: current_fh is targetdir, saved_fh is source */
7386 	argop[3].argop = OP_CLINK;
7387 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7388 
7389 	/* 4. Get attributes of dir */
7390 	argop[4].argop = OP_GETATTR;
7391 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7392 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7393 
7394 	/* 5. If link was successful, restore current vp to file */
7395 	argop[5].argop = OP_RESTOREFH;
7396 
7397 	/* 6. Get attributes of linked object */
7398 	argop[6].argop = OP_GETATTR;
7399 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7400 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7401 
7402 	dnlc_remove(tdvp, tnm);
7403 
7404 	doqueue = 1;
7405 	t = gethrtime();
7406 
7407 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7408 
7409 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7410 	if (e.error != 0 && !needrecov) {
7411 		PURGE_ATTRCACHE4(tdvp);
7412 		PURGE_ATTRCACHE4(svp);
7413 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7414 		goto out;
7415 	}
7416 
7417 	if (needrecov) {
7418 		bool_t abort;
7419 
7420 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7421 			    NULL, NULL, OP_LINK, NULL);
7422 		if (abort == FALSE) {
7423 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7424 				    needrecov);
7425 			kmem_free(argop, argoplist_size);
7426 			if (!e.error)
7427 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7428 								(caddr_t)&res);
7429 			goto recov_retry;
7430 		} else {
7431 			if (e.error != 0) {
7432 				PURGE_ATTRCACHE4(tdvp);
7433 				PURGE_ATTRCACHE4(svp);
7434 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7435 					    &recov_state, needrecov);
7436 				goto out;
7437 			}
7438 			/* fall through for res.status case */
7439 		}
7440 	}
7441 
7442 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7443 
7444 	resp = &res;
7445 	if (res.status) {
7446 		/* If link succeeded, then don't return error */
7447 		e.error = geterrno4(res.status);
7448 		if (res.array_len <= 4) {
7449 			/*
7450 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7451 			 */
7452 			PURGE_ATTRCACHE4(svp);
7453 			PURGE_ATTRCACHE4(tdvp);
7454 			if (e.error == EOPNOTSUPP) {
7455 				mutex_enter(&mi->mi_lock);
7456 				mi->mi_flags &= ~MI4_LINK;
7457 				mutex_exit(&mi->mi_lock);
7458 			}
7459 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7460 			/* XXX-LP */
7461 			if (e.error == EISDIR && crgetuid(cr) != 0)
7462 				e.error = EPERM;
7463 			goto out;
7464 		}
7465 	}
7466 
7467 	/* either no error or one of the postop getattr failed */
7468 
7469 	/*
7470 	 * XXX - if LINK succeeded, but no attrs were returned for link
7471 	 * file, purge its cache.
7472 	 *
7473 	 * XXX Perform a simplified version of wcc checking. Instead of
7474 	 * have another getattr to get pre-op, just purge cache if
7475 	 * any of the ops prior to and including the getattr failed.
7476 	 * If the getattr succeeded then update the attrcache accordingly.
7477 	 */
7478 
7479 	/*
7480 	 * update cache with link file postattrs.
7481 	 * Note: at this point resop points to link res.
7482 	 */
7483 	resop = &res.array[3];	/* link res */
7484 	ln_res = &resop->nfs_resop4_u.oplink;
7485 	if (res.status == NFS4_OK) {
7486 		e.error = nfs4_update_attrcache(res.status,
7487 				&res.array[6].nfs_resop4_u.opgetattr.ga_res,
7488 				t, svp, cr);
7489 	}
7490 
7491 	/*
7492 	 * Call makenfs4node to create the new shadow vp for tnm.
7493 	 * We pass NULL attrs because we just cached attrs for
7494 	 * the src object.  All we're trying to accomplish is to
7495 	 * to create the new shadow vnode.
7496 	 */
7497 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7498 			tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm));
7499 
7500 	/* Update target cache attribute, readdir and dnlc caches */
7501 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7502 	dinfo.di_time_call = t;
7503 	dinfo.di_cred = cr;
7504 
7505 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7506 	ASSERT(nfs4_consistent_type(tdvp));
7507 	ASSERT(nfs4_consistent_type(svp));
7508 	ASSERT(nfs4_consistent_type(nvp));
7509 	VN_RELE(nvp);
7510 
7511 	if (!e.error) {
7512 		vnode_t *tvp;
7513 		rnode4_t *trp;
7514 		/*
7515 		 * Notify the source file of this link operation.
7516 		 */
7517 		trp = VTOR4(svp);
7518 		tvp = svp;
7519 		if (IS_SHADOW(svp, trp))
7520 			tvp = RTOV4(trp);
7521 		vnevent_link(tvp);
7522 	}
7523 out:
7524 	kmem_free(argop, argoplist_size);
7525 	if (resp)
7526 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7527 
7528 	nfs_rw_exit(&tdrp->r_rwlock);
7529 
7530 	return (e.error);
7531 }
7532 
7533 static int
7534 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr)
7535 {
7536 	vnode_t *realvp;
7537 
7538 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7539 		return (EPERM);
7540 	if (VOP_REALVP(ndvp, &realvp) == 0)
7541 		ndvp = realvp;
7542 
7543 	return (nfs4rename(odvp, onm, ndvp, nnm, cr));
7544 }
7545 
7546 /*
7547  * nfs4rename does the real work of renaming in NFS Version 4.
7548  *
7549  * A file handle is considered volatile for renaming purposes if either
7550  * of the volatile bits are turned on. However, the compound may differ
7551  * based on the likelihood of the filehandle to change during rename.
7552  */
7553 static int
7554 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr)
7555 {
7556 	int error;
7557 	mntinfo4_t *mi;
7558 	vnode_t *nvp = NULL;
7559 	vnode_t *ovp = NULL;
7560 	char *tmpname = NULL;
7561 	rnode4_t *rp;
7562 	rnode4_t *odrp;
7563 	rnode4_t *ndrp;
7564 	int did_link = 0;
7565 	int do_link = 1;
7566 	nfsstat4 stat = NFS4_OK;
7567 
7568 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7569 	ASSERT(nfs4_consistent_type(odvp));
7570 	ASSERT(nfs4_consistent_type(ndvp));
7571 
7572 	if (onm[0] == '.' && (onm[1] == '\0' ||
7573 			(onm[1] == '.' && onm[2] == '\0')))
7574 		return (EINVAL);
7575 
7576 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7577 			(nnm[1] == '.' && nnm[2] == '\0')))
7578 		return (EINVAL);
7579 
7580 	odrp = VTOR4(odvp);
7581 	ndrp = VTOR4(ndvp);
7582 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7583 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7584 			return (EINTR);
7585 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7586 			nfs_rw_exit(&odrp->r_rwlock);
7587 			return (EINTR);
7588 		}
7589 	} else {
7590 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7591 			return (EINTR);
7592 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7593 			nfs_rw_exit(&ndrp->r_rwlock);
7594 			return (EINTR);
7595 		}
7596 	}
7597 
7598 	/*
7599 	 * Lookup the target file.  If it exists, it needs to be
7600 	 * checked to see whether it is a mount point and whether
7601 	 * it is active (open).
7602 	 */
7603 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7604 	if (!error) {
7605 		int	isactive;
7606 
7607 		ASSERT(nfs4_consistent_type(nvp));
7608 		/*
7609 		 * If this file has been mounted on, then just
7610 		 * return busy because renaming to it would remove
7611 		 * the mounted file system from the name space.
7612 		 */
7613 		if (vn_ismntpt(nvp)) {
7614 			VN_RELE(nvp);
7615 			nfs_rw_exit(&odrp->r_rwlock);
7616 			nfs_rw_exit(&ndrp->r_rwlock);
7617 			return (EBUSY);
7618 		}
7619 
7620 		/*
7621 		 * First just remove the entry from the name cache, as it
7622 		 * is most likely the only entry for this vp.
7623 		 */
7624 		dnlc_remove(ndvp, nnm);
7625 
7626 		rp = VTOR4(nvp);
7627 
7628 		if (nvp->v_type != VREG) {
7629 			/*
7630 			 * Purge the name cache of all references to this vnode
7631 			 * so that we can check the reference count to infer
7632 			 * whether it is active or not.
7633 			 */
7634 			if (nvp->v_count > 1)
7635 				dnlc_purge_vp(nvp);
7636 
7637 			isactive = nvp->v_count > 1;
7638 		} else {
7639 			mutex_enter(&rp->r_os_lock);
7640 			isactive = list_head(&rp->r_open_streams) != NULL;
7641 			mutex_exit(&rp->r_os_lock);
7642 		}
7643 
7644 		/*
7645 		 * If the vnode is active and is not a directory,
7646 		 * arrange to rename it to a
7647 		 * temporary file so that it will continue to be
7648 		 * accessible.  This implements the "unlink-open-file"
7649 		 * semantics for the target of a rename operation.
7650 		 * Before doing this though, make sure that the
7651 		 * source and target files are not already the same.
7652 		 */
7653 		if (isactive && nvp->v_type != VDIR) {
7654 			/*
7655 			 * Lookup the source name.
7656 			 */
7657 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7658 
7659 			/*
7660 			 * The source name *should* already exist.
7661 			 */
7662 			if (error) {
7663 				VN_RELE(nvp);
7664 				nfs_rw_exit(&odrp->r_rwlock);
7665 				nfs_rw_exit(&ndrp->r_rwlock);
7666 				return (error);
7667 			}
7668 
7669 			ASSERT(nfs4_consistent_type(ovp));
7670 
7671 			/*
7672 			 * Compare the two vnodes.  If they are the same,
7673 			 * just release all held vnodes and return success.
7674 			 */
7675 			if (VN_CMP(ovp, nvp)) {
7676 				VN_RELE(ovp);
7677 				VN_RELE(nvp);
7678 				nfs_rw_exit(&odrp->r_rwlock);
7679 				nfs_rw_exit(&ndrp->r_rwlock);
7680 				return (0);
7681 			}
7682 
7683 			/*
7684 			 * Can't mix and match directories and non-
7685 			 * directories in rename operations.  We already
7686 			 * know that the target is not a directory.  If
7687 			 * the source is a directory, return an error.
7688 			 */
7689 			if (ovp->v_type == VDIR) {
7690 				VN_RELE(ovp);
7691 				VN_RELE(nvp);
7692 				nfs_rw_exit(&odrp->r_rwlock);
7693 				nfs_rw_exit(&ndrp->r_rwlock);
7694 				return (ENOTDIR);
7695 			}
7696 link_call:
7697 			/*
7698 			 * The target file exists, is not the same as
7699 			 * the source file, and is active.  We first
7700 			 * try to Link it to a temporary filename to
7701 			 * avoid having the server removing the file
7702 			 * completely (which could cause data loss to
7703 			 * the user's POV in the event the Rename fails
7704 			 * -- see bug 1165874).
7705 			 */
7706 			/*
7707 			 * The do_link and did_link booleans are
7708 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7709 			 * returned for the Rename.  Some servers can
7710 			 * not Rename over an Open file, so they return
7711 			 * this error.  The client needs to Remove the
7712 			 * newly created Link and do two Renames, just
7713 			 * as if the server didn't support LINK.
7714 			 */
7715 			tmpname = newname();
7716 			error = 0;
7717 
7718 			if (do_link) {
7719 				error = nfs4_link(ndvp, nvp, tmpname, cr);
7720 			}
7721 			if (error == EOPNOTSUPP || !do_link) {
7722 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7723 				    cr);
7724 				did_link = 0;
7725 			} else {
7726 				did_link = 1;
7727 			}
7728 			if (error) {
7729 				kmem_free(tmpname, MAXNAMELEN);
7730 				VN_RELE(ovp);
7731 				VN_RELE(nvp);
7732 				nfs_rw_exit(&odrp->r_rwlock);
7733 				nfs_rw_exit(&ndrp->r_rwlock);
7734 				return (error);
7735 			}
7736 
7737 			mutex_enter(&rp->r_statelock);
7738 			if (rp->r_unldvp == NULL) {
7739 				VN_HOLD(ndvp);
7740 				rp->r_unldvp = ndvp;
7741 				if (rp->r_unlcred != NULL)
7742 					crfree(rp->r_unlcred);
7743 				crhold(cr);
7744 				rp->r_unlcred = cr;
7745 				rp->r_unlname = tmpname;
7746 			} else {
7747 				if (rp->r_unlname)
7748 					kmem_free(rp->r_unlname, MAXNAMELEN);
7749 				rp->r_unlname = tmpname;
7750 			}
7751 			mutex_exit(&rp->r_statelock);
7752 		}
7753 
7754 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7755 
7756 		ASSERT(nfs4_consistent_type(nvp));
7757 	}
7758 
7759 	if (ovp == NULL) {
7760 		/*
7761 		 * When renaming directories to be a subdirectory of a
7762 		 * different parent, the dnlc entry for ".." will no
7763 		 * longer be valid, so it must be removed.
7764 		 *
7765 		 * We do a lookup here to determine whether we are renaming
7766 		 * a directory and we need to check if we are renaming
7767 		 * an unlinked file.  This might have already been done
7768 		 * in previous code, so we check ovp == NULL to avoid
7769 		 * doing it twice.
7770 		 */
7771 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7772 		/*
7773 		 * The source name *should* already exist.
7774 		 */
7775 		if (error) {
7776 			nfs_rw_exit(&odrp->r_rwlock);
7777 			nfs_rw_exit(&ndrp->r_rwlock);
7778 			if (nvp) {
7779 				VN_RELE(nvp);
7780 			}
7781 			return (error);
7782 		}
7783 		ASSERT(ovp != NULL);
7784 		ASSERT(nfs4_consistent_type(ovp));
7785 	}
7786 
7787 	/*
7788 	 * Is the object being renamed a dir, and if so, is
7789 	 * it being renamed to a child of itself?  The underlying
7790 	 * fs should ultimately return EINVAL for this case;
7791 	 * however, buggy beta non-Solaris NFSv4 servers at
7792 	 * interop testing events have allowed this behavior,
7793 	 * and it caused our client to panic due to a recursive
7794 	 * mutex_enter in fn_move.
7795 	 *
7796 	 * The tedious locking in fn_move could be changed to
7797 	 * deal with this case, and the client could avoid the
7798 	 * panic; however, the client would just confuse itself
7799 	 * later and misbehave.  A better way to handle the broken
7800 	 * server is to detect this condition and return EINVAL
7801 	 * without ever sending the the bogus rename to the server.
7802 	 * We know the rename is invalid -- just fail it now.
7803 	 */
7804 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7805 		VN_RELE(ovp);
7806 		nfs_rw_exit(&odrp->r_rwlock);
7807 		nfs_rw_exit(&ndrp->r_rwlock);
7808 		if (nvp) {
7809 			VN_RELE(nvp);
7810 		}
7811 		return (EINVAL);
7812 	}
7813 
7814 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7815 
7816 	/*
7817 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7818 	 * possible for the filehandle to change due to the rename.
7819 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7820 	 * the fh will not change because of the rename, but we still need
7821 	 * to update its rnode entry with the new name for
7822 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7823 	 * has no effect on these for now, but for future improvements,
7824 	 * we might want to use it too to simplify handling of files
7825 	 * that are open with that flag on. (XXX)
7826 	 */
7827 	mi = VTOMI4(odvp);
7828 	if (NFS4_VOLATILE_FH(mi)) {
7829 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7830 				&stat);
7831 	} else {
7832 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7833 				&stat);
7834 	}
7835 	ASSERT(nfs4_consistent_type(odvp));
7836 	ASSERT(nfs4_consistent_type(ndvp));
7837 	ASSERT(nfs4_consistent_type(ovp));
7838 
7839 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
7840 		do_link = 0;
7841 		/*
7842 		 * Before the 'link_call' code, we did a nfs4_lookup
7843 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
7844 		 * call we call VN_RELE to match that hold.  We need
7845 		 * to place an additional VN_HOLD here since we will
7846 		 * be hitting that VN_RELE again.
7847 		 */
7848 		VN_HOLD(nvp);
7849 
7850 		(void) nfs4_remove(ndvp, tmpname, cr);
7851 
7852 		/* Undo the unlinked file naming stuff we just did */
7853 		mutex_enter(&rp->r_statelock);
7854 		if (rp->r_unldvp) {
7855 			VN_RELE(ndvp);
7856 			rp->r_unldvp = NULL;
7857 			if (rp->r_unlcred != NULL)
7858 				crfree(rp->r_unlcred);
7859 			rp->r_unlcred = NULL;
7860 			/* rp->r_unlanme points to tmpname */
7861 			if (rp->r_unlname)
7862 				kmem_free(rp->r_unlname, MAXNAMELEN);
7863 			rp->r_unlname = NULL;
7864 		}
7865 		mutex_exit(&rp->r_statelock);
7866 
7867 		if (nvp) {
7868 			VN_RELE(nvp);
7869 		}
7870 		goto link_call;
7871 	}
7872 
7873 	if (error) {
7874 		VN_RELE(ovp);
7875 		nfs_rw_exit(&odrp->r_rwlock);
7876 		nfs_rw_exit(&ndrp->r_rwlock);
7877 		if (nvp) {
7878 			VN_RELE(nvp);
7879 		}
7880 		return (error);
7881 	}
7882 
7883 	/*
7884 	 * when renaming directories to be a subdirectory of a
7885 	 * different parent, the dnlc entry for ".." will no
7886 	 * longer be valid, so it must be removed
7887 	 */
7888 	rp = VTOR4(ovp);
7889 	if (ndvp != odvp) {
7890 		if (ovp->v_type == VDIR) {
7891 			dnlc_remove(ovp, "..");
7892 			if (rp->r_dir != NULL)
7893 				nfs4_purge_rddir_cache(ovp);
7894 		}
7895 	}
7896 
7897 	/*
7898 	 * If we are renaming the unlinked file, update the
7899 	 * r_unldvp and r_unlname as needed.
7900 	 */
7901 	mutex_enter(&rp->r_statelock);
7902 	if (rp->r_unldvp != NULL) {
7903 		if (strcmp(rp->r_unlname, onm) == 0) {
7904 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
7905 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
7906 			if (ndvp != rp->r_unldvp) {
7907 				VN_RELE(rp->r_unldvp);
7908 				rp->r_unldvp = ndvp;
7909 				VN_HOLD(ndvp);
7910 			}
7911 		}
7912 	}
7913 	mutex_exit(&rp->r_statelock);
7914 
7915 	/*
7916 	 * Notify the rename vnevents to source vnode, and to the target
7917 	 * vnode if it already existed.
7918 	 */
7919 	if (error == 0) {
7920 		vnode_t *tvp;
7921 		rnode4_t *trp;
7922 		/*
7923 		 * Notify the vnode. Each links is represented by
7924 		 * a different vnode, in nfsv4.
7925 		 */
7926 		if (nvp) {
7927 			trp = VTOR4(nvp);
7928 			tvp = nvp;
7929 			if (IS_SHADOW(nvp, trp))
7930 				tvp = RTOV4(trp);
7931 			vnevent_rename_dest(tvp, ndvp, nnm);
7932 		}
7933 
7934 		/*
7935 		 * if the source and destination directory are not the
7936 		 * same notify the destination directory.
7937 		 */
7938 		if (VTOR4(odvp) != VTOR4(ndvp)) {
7939 			trp = VTOR4(ndvp);
7940 			tvp = ndvp;
7941 			if (IS_SHADOW(ndvp, trp))
7942 				tvp = RTOV4(trp);
7943 			vnevent_rename_dest_dir(tvp);
7944 		}
7945 
7946 		trp = VTOR4(ovp);
7947 		tvp = ovp;
7948 		if (IS_SHADOW(ovp, trp))
7949 			tvp = RTOV4(trp);
7950 		vnevent_rename_src(tvp, odvp, onm);
7951 	}
7952 
7953 	if (nvp) {
7954 		VN_RELE(nvp);
7955 	}
7956 	VN_RELE(ovp);
7957 
7958 	nfs_rw_exit(&odrp->r_rwlock);
7959 	nfs_rw_exit(&ndrp->r_rwlock);
7960 
7961 	return (error);
7962 }
7963 
7964 /*
7965  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
7966  * when it is known that the filehandle is persistent through rename.
7967  *
7968  * Rename requires that the current fh be the target directory and the
7969  * saved fh be the source directory. After the operation, the current fh
7970  * is unchanged.
7971  * The compound op structure for persistent fh rename is:
7972  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
7973  * Rather than bother with the directory postop args, we'll simply
7974  * update that a change occured in the cache, so no post-op getattrs.
7975  */
7976 static int
7977 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
7978 	vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
7979 {
7980 	COMPOUND4args_clnt args;
7981 	COMPOUND4res_clnt res, *resp = NULL;
7982 	nfs_argop4 *argop;
7983 	nfs_resop4 *resop;
7984 	int doqueue, argoplist_size;
7985 	mntinfo4_t *mi;
7986 	rnode4_t *odrp = VTOR4(odvp);
7987 	rnode4_t *ndrp = VTOR4(ndvp);
7988 	RENAME4res *rn_res;
7989 	bool_t needrecov;
7990 	nfs4_recov_state_t recov_state;
7991 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7992 	dirattr_info_t dinfo, *dinfop;
7993 
7994 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7995 
7996 	recov_state.rs_flags = 0;
7997 	recov_state.rs_num_retry_despite_err = 0;
7998 
7999 	/*
8000 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
8001 	 *
8002 	 * If source/target are different dirs, then append putfh(src); getattr
8003 	 */
8004 	args.array_len = (odvp == ndvp) ? 5 : 7;
8005 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8006 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8007 
8008 recov_retry:
8009 	*statp = NFS4_OK;
8010 
8011 	/* No need to Lookup the file, persistent fh */
8012 	args.ctag = TAG_RENAME;
8013 
8014 	mi = VTOMI4(odvp);
8015 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8016 	if (e.error) {
8017 		kmem_free(argop, argoplist_size);
8018 		return (e.error);
8019 	}
8020 
8021 	/* 0: putfh source directory */
8022 	argop[0].argop = OP_CPUTFH;
8023 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8024 
8025 	/* 1: Save source fh to free up current for target */
8026 	argop[1].argop = OP_SAVEFH;
8027 
8028 	/* 2: putfh targetdir */
8029 	argop[2].argop = OP_CPUTFH;
8030 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8031 
8032 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8033 	argop[3].argop = OP_CRENAME;
8034 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8035 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8036 
8037 	/* 4: getattr (targetdir) */
8038 	argop[4].argop = OP_GETATTR;
8039 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8040 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8041 
8042 	if (ndvp != odvp) {
8043 
8044 		/* 5: putfh (sourcedir) */
8045 		argop[5].argop = OP_CPUTFH;
8046 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8047 
8048 		/* 6: getattr (sourcedir) */
8049 		argop[6].argop = OP_GETATTR;
8050 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8051 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8052 	}
8053 
8054 	dnlc_remove(odvp, onm);
8055 	dnlc_remove(ndvp, nnm);
8056 
8057 	doqueue = 1;
8058 	dinfo.di_time_call = gethrtime();
8059 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8060 
8061 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8062 	if (e.error) {
8063 		PURGE_ATTRCACHE4(odvp);
8064 		PURGE_ATTRCACHE4(ndvp);
8065 	} else {
8066 		*statp = res.status;
8067 	}
8068 
8069 	if (needrecov) {
8070 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8071 		    OP_RENAME, NULL) == FALSE) {
8072 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8073 			if (!e.error)
8074 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8075 								(caddr_t)&res);
8076 			goto recov_retry;
8077 		}
8078 	}
8079 
8080 	if (!e.error) {
8081 		resp = &res;
8082 		/*
8083 		 * as long as OP_RENAME
8084 		 */
8085 		if (res.status != NFS4_OK && res.array_len <= 4) {
8086 			e.error = geterrno4(res.status);
8087 			PURGE_ATTRCACHE4(odvp);
8088 			PURGE_ATTRCACHE4(ndvp);
8089 			/*
8090 			 * System V defines rename to return EEXIST, not
8091 			 * ENOTEMPTY if the target directory is not empty.
8092 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8093 			 * which geterrno4 maps to ENOTEMPTY.
8094 			 */
8095 			if (e.error == ENOTEMPTY)
8096 				e.error = EEXIST;
8097 		} else {
8098 
8099 			resop = &res.array[3];	/* rename res */
8100 			rn_res = &resop->nfs_resop4_u.oprename;
8101 
8102 			if (res.status == NFS4_OK) {
8103 				/*
8104 				 * Update target attribute, readdir and dnlc
8105 				 * caches.
8106 				 */
8107 				dinfo.di_garp =
8108 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8109 				dinfo.di_cred = cr;
8110 				dinfop = &dinfo;
8111 			} else
8112 				dinfop = NULL;
8113 
8114 			nfs4_update_dircaches(&rn_res->target_cinfo,
8115 						ndvp, NULL, NULL, dinfop);
8116 
8117 			/*
8118 			 * Update source attribute, readdir and dnlc caches
8119 			 *
8120 			 */
8121 			if (ndvp != odvp) {
8122 				if (dinfop)
8123 					dinfo.di_garp =
8124 					    &(res.array[6].nfs_resop4_u.
8125 					    opgetattr.ga_res);
8126 
8127 				nfs4_update_dircaches(&rn_res->source_cinfo,
8128 						odvp, NULL, NULL, dinfop);
8129 			}
8130 
8131 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8132 									nnm);
8133 		}
8134 	}
8135 
8136 	if (resp)
8137 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8138 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8139 	kmem_free(argop, argoplist_size);
8140 
8141 	return (e.error);
8142 }
8143 
8144 /*
8145  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8146  * it is possible for the filehandle to change due to the rename.
8147  *
8148  * The compound req in this case includes a post-rename lookup and getattr
8149  * to ensure that we have the correct fh and attributes for the object.
8150  *
8151  * Rename requires that the current fh be the target directory and the
8152  * saved fh be the source directory. After the operation, the current fh
8153  * is unchanged.
8154  *
8155  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8156  * update the filehandle for the renamed object.  We also get the old
8157  * filehandle for historical reasons; this should be taken out sometime.
8158  * This results in a rather cumbersome compound...
8159  *
8160  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8161  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8162  *
8163  */
8164 static int
8165 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8166 	vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8167 {
8168 	COMPOUND4args_clnt args;
8169 	COMPOUND4res_clnt res, *resp = NULL;
8170 	int argoplist_size;
8171 	nfs_argop4 *argop;
8172 	nfs_resop4 *resop;
8173 	int doqueue;
8174 	mntinfo4_t *mi;
8175 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8176 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8177 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8178 	RENAME4res *rn_res;
8179 	GETFH4res *ngf_res;
8180 	bool_t needrecov;
8181 	nfs4_recov_state_t recov_state;
8182 	hrtime_t t;
8183 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8184 	dirattr_info_t dinfo, *dinfop = &dinfo;
8185 
8186 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8187 
8188 	recov_state.rs_flags = 0;
8189 	recov_state.rs_num_retry_despite_err = 0;
8190 
8191 recov_retry:
8192 	*statp = NFS4_OK;
8193 
8194 	/*
8195 	 * There is a window between the RPC and updating the path and
8196 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8197 	 * code, so that it doesn't try to use the old path during that
8198 	 * window.
8199 	 */
8200 	mutex_enter(&orp->r_statelock);
8201 	while (orp->r_flags & R4RECEXPFH) {
8202 		klwp_t *lwp = ttolwp(curthread);
8203 
8204 		if (lwp != NULL)
8205 			lwp->lwp_nostop++;
8206 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8207 			mutex_exit(&orp->r_statelock);
8208 			if (lwp != NULL)
8209 				lwp->lwp_nostop--;
8210 			return (EINTR);
8211 		}
8212 		if (lwp != NULL)
8213 			lwp->lwp_nostop--;
8214 	}
8215 	orp->r_flags |= R4RECEXPFH;
8216 	mutex_exit(&orp->r_statelock);
8217 
8218 	mi = VTOMI4(odvp);
8219 
8220 	args.ctag = TAG_RENAME_VFH;
8221 	args.array_len = (odvp == ndvp) ? 10 : 12;
8222 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8223 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8224 
8225 	/*
8226 	 * Rename ops:
8227 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8228 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8229 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8230 	 *
8231 	 *    if (odvp != ndvp)
8232 	 *	add putfh(sourcedir), getattr(sourcedir) }
8233 	 */
8234 	args.array = argop;
8235 
8236 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8237 			    &recov_state, NULL);
8238 	if (e.error) {
8239 		kmem_free(argop, argoplist_size);
8240 		mutex_enter(&orp->r_statelock);
8241 		orp->r_flags &= ~R4RECEXPFH;
8242 		cv_broadcast(&orp->r_cv);
8243 		mutex_exit(&orp->r_statelock);
8244 		return (e.error);
8245 	}
8246 
8247 	/* 0: putfh source directory */
8248 	argop[0].argop = OP_CPUTFH;
8249 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8250 
8251 	/* 1: Save source fh to free up current for target */
8252 	argop[1].argop = OP_SAVEFH;
8253 
8254 	/* 2: Lookup pre-rename fh of renamed object */
8255 	argop[2].argop = OP_CLOOKUP;
8256 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8257 
8258 	/* 3: getfh fh of renamed object (before rename) */
8259 	argop[3].argop = OP_GETFH;
8260 
8261 	/* 4: putfh targetdir */
8262 	argop[4].argop = OP_CPUTFH;
8263 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8264 
8265 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8266 	argop[5].argop = OP_CRENAME;
8267 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8268 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8269 
8270 	/* 6: getattr of target dir (post op attrs) */
8271 	argop[6].argop = OP_GETATTR;
8272 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8273 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8274 
8275 	/* 7: Lookup post-rename fh of renamed object */
8276 	argop[7].argop = OP_CLOOKUP;
8277 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8278 
8279 	/* 8: getfh fh of renamed object (after rename) */
8280 	argop[8].argop = OP_GETFH;
8281 
8282 	/* 9: getattr of renamed object */
8283 	argop[9].argop = OP_GETATTR;
8284 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8285 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8286 
8287 	/*
8288 	 * If source/target dirs are different, then get new post-op
8289 	 * attrs for source dir also.
8290 	 */
8291 	if (ndvp != odvp) {
8292 		/* 10: putfh (sourcedir) */
8293 		argop[10].argop = OP_CPUTFH;
8294 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8295 
8296 		/* 11: getattr (sourcedir) */
8297 		argop[11].argop = OP_GETATTR;
8298 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8299 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8300 	}
8301 
8302 	dnlc_remove(odvp, onm);
8303 	dnlc_remove(ndvp, nnm);
8304 
8305 	doqueue = 1;
8306 	t = gethrtime();
8307 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8308 
8309 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8310 	if (e.error) {
8311 		PURGE_ATTRCACHE4(odvp);
8312 		PURGE_ATTRCACHE4(ndvp);
8313 		if (!needrecov) {
8314 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8315 					&recov_state, needrecov);
8316 			goto out;
8317 		}
8318 	} else {
8319 		*statp = res.status;
8320 	}
8321 
8322 	if (needrecov) {
8323 		bool_t abort;
8324 
8325 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8326 			    OP_RENAME, NULL);
8327 		if (abort == FALSE) {
8328 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8329 					&recov_state, needrecov);
8330 			kmem_free(argop, argoplist_size);
8331 			if (!e.error)
8332 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8333 								(caddr_t)&res);
8334 			mutex_enter(&orp->r_statelock);
8335 			orp->r_flags &= ~R4RECEXPFH;
8336 			cv_broadcast(&orp->r_cv);
8337 			mutex_exit(&orp->r_statelock);
8338 			goto recov_retry;
8339 		} else {
8340 			if (e.error != 0) {
8341 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8342 						&recov_state, needrecov);
8343 				goto out;
8344 			}
8345 			/* fall through for res.status case */
8346 		}
8347 	}
8348 
8349 	resp = &res;
8350 	/*
8351 	 * If OP_RENAME (or any prev op) failed, then return an error.
8352 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8353 	 */
8354 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8355 		/*
8356 		 * Error in an op other than last Getattr
8357 		 */
8358 		e.error = geterrno4(res.status);
8359 		PURGE_ATTRCACHE4(odvp);
8360 		PURGE_ATTRCACHE4(ndvp);
8361 		/*
8362 		 * System V defines rename to return EEXIST, not
8363 		 * ENOTEMPTY if the target directory is not empty.
8364 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8365 		 * which geterrno4 maps to ENOTEMPTY.
8366 		 */
8367 		if (e.error == ENOTEMPTY)
8368 			e.error = EEXIST;
8369 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8370 				needrecov);
8371 		goto out;
8372 	}
8373 
8374 	/* rename results */
8375 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8376 
8377 	if (res.status == NFS4_OK) {
8378 		/* Update target attribute, readdir and dnlc caches */
8379 		dinfo.di_garp =
8380 			&res.array[6].nfs_resop4_u.opgetattr.ga_res;
8381 		dinfo.di_cred = cr;
8382 		dinfo.di_time_call = t;
8383 	} else
8384 		dinfop = NULL;
8385 
8386 	/* Update source cache attribute, readdir and dnlc caches */
8387 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8388 
8389 	/* Update source cache attribute, readdir and dnlc caches */
8390 	if (ndvp != odvp) {
8391 
8392 		/*
8393 		 * If dinfop is non-NULL, then compound succeded, so
8394 		 * set di_garp to attrs for source dir.  dinfop is only
8395 		 * set to NULL when compound fails.
8396 		 */
8397 		if (dinfop)
8398 			dinfo.di_garp =
8399 				&res.array[11].nfs_resop4_u.opgetattr.ga_res;
8400 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8401 				dinfop);
8402 	}
8403 
8404 	/*
8405 	 * Update the rnode with the new component name and args,
8406 	 * and if the file handle changed, also update it with the new fh.
8407 	 * This is only necessary if the target object has an rnode
8408 	 * entry and there is no need to create one for it.
8409 	 */
8410 	resop = &res.array[8];	/* getfh new res */
8411 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8412 
8413 	/*
8414 	 * Update the path and filehandle for the renamed object.
8415 	 */
8416 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8417 
8418 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8419 
8420 	if (res.status == NFS4_OK) {
8421 		resop++;	/* getattr res */
8422 		e.error = nfs4_update_attrcache(res.status,
8423 				&resop->nfs_resop4_u.opgetattr.ga_res,
8424 				t, ovp, cr);
8425 	}
8426 
8427 out:
8428 	kmem_free(argop, argoplist_size);
8429 	if (resp)
8430 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8431 	mutex_enter(&orp->r_statelock);
8432 	orp->r_flags &= ~R4RECEXPFH;
8433 	cv_broadcast(&orp->r_cv);
8434 	mutex_exit(&orp->r_statelock);
8435 
8436 	return (e.error);
8437 }
8438 
8439 static int
8440 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr)
8441 {
8442 	int error;
8443 	vnode_t *vp;
8444 
8445 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8446 		return (EPERM);
8447 	/*
8448 	 * As ".." has special meaning and rather than send a mkdir
8449 	 * over the wire to just let the server freak out, we just
8450 	 * short circuit it here and return EEXIST
8451 	 */
8452 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8453 		return (EEXIST);
8454 
8455 	/*
8456 	 * Decision to get the right gid and setgid bit of the
8457 	 * new directory is now made in call_nfs4_create_req.
8458 	 */
8459 	va->va_mask |= AT_MODE;
8460 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8461 	if (error)
8462 		return (error);
8463 
8464 	*vpp = vp;
8465 	return (0);
8466 }
8467 
8468 
8469 /*
8470  * rmdir is using the same remove v4 op as does remove.
8471  * Remove requires that the current fh be the target directory.
8472  * After the operation, the current fh is unchanged.
8473  * The compound op structure is:
8474  *      PUTFH(targetdir), REMOVE
8475  */
8476 static int
8477 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr)
8478 {
8479 	int need_end_op = FALSE;
8480 	COMPOUND4args_clnt args;
8481 	COMPOUND4res_clnt res, *resp = NULL;
8482 	REMOVE4res *rm_res;
8483 	nfs_argop4 argop[3];
8484 	nfs_resop4 *resop;
8485 	vnode_t *vp;
8486 	int doqueue;
8487 	mntinfo4_t *mi;
8488 	rnode4_t *drp;
8489 	bool_t needrecov = FALSE;
8490 	nfs4_recov_state_t recov_state;
8491 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8492 	dirattr_info_t dinfo, *dinfop;
8493 
8494 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8495 		return (EPERM);
8496 	/*
8497 	 * As ".." has special meaning and rather than send a rmdir
8498 	 * over the wire to just let the server freak out, we just
8499 	 * short circuit it here and return EEXIST
8500 	 */
8501 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8502 		return (EEXIST);
8503 
8504 	drp = VTOR4(dvp);
8505 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8506 		return (EINTR);
8507 
8508 	/*
8509 	 * Attempt to prevent a rmdir(".") from succeeding.
8510 	 */
8511 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8512 	if (e.error) {
8513 		nfs_rw_exit(&drp->r_rwlock);
8514 		return (e.error);
8515 	}
8516 	if (vp == cdir) {
8517 		VN_RELE(vp);
8518 		nfs_rw_exit(&drp->r_rwlock);
8519 		return (EINVAL);
8520 	}
8521 
8522 	/*
8523 	 * Since nfsv4 remove op works on both files and directories,
8524 	 * check that the removed object is indeed a directory.
8525 	 */
8526 	if (vp->v_type != VDIR) {
8527 		VN_RELE(vp);
8528 		nfs_rw_exit(&drp->r_rwlock);
8529 		return (ENOTDIR);
8530 	}
8531 
8532 	/*
8533 	 * First just remove the entry from the name cache, as it
8534 	 * is most likely an entry for this vp.
8535 	 */
8536 	dnlc_remove(dvp, nm);
8537 
8538 	/*
8539 	 * If there vnode reference count is greater than one, then
8540 	 * there may be additional references in the DNLC which will
8541 	 * need to be purged.  First, trying removing the entry for
8542 	 * the parent directory and see if that removes the additional
8543 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8544 	 * to completely remove any references to the directory which
8545 	 * might still exist in the DNLC.
8546 	 */
8547 	if (vp->v_count > 1) {
8548 		dnlc_remove(vp, "..");
8549 		if (vp->v_count > 1)
8550 			dnlc_purge_vp(vp);
8551 	}
8552 
8553 	mi = VTOMI4(dvp);
8554 	recov_state.rs_flags = 0;
8555 	recov_state.rs_num_retry_despite_err = 0;
8556 
8557 recov_retry:
8558 	args.ctag = TAG_RMDIR;
8559 
8560 	/*
8561 	 * Rmdir ops: putfh dir; remove
8562 	 */
8563 	args.array_len = 3;
8564 	args.array = argop;
8565 
8566 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8567 	if (e.error) {
8568 		nfs_rw_exit(&drp->r_rwlock);
8569 		return (e.error);
8570 	}
8571 	need_end_op = TRUE;
8572 
8573 	/* putfh directory */
8574 	argop[0].argop = OP_CPUTFH;
8575 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8576 
8577 	/* remove */
8578 	argop[1].argop = OP_CREMOVE;
8579 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8580 
8581 	/* getattr (postop attrs for dir that contained removed dir) */
8582 	argop[2].argop = OP_GETATTR;
8583 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8584 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8585 
8586 	dinfo.di_time_call = gethrtime();
8587 	doqueue = 1;
8588 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8589 
8590 	PURGE_ATTRCACHE4(vp);
8591 
8592 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8593 	if (e.error) {
8594 		PURGE_ATTRCACHE4(dvp);
8595 	}
8596 
8597 	if (needrecov) {
8598 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8599 		    NULL, OP_REMOVE, NULL) == FALSE) {
8600 			if (!e.error)
8601 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8602 								(caddr_t)&res);
8603 
8604 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8605 			    needrecov);
8606 			need_end_op = FALSE;
8607 			goto recov_retry;
8608 		}
8609 	}
8610 
8611 	if (!e.error) {
8612 		resp = &res;
8613 
8614 		/*
8615 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8616 		 * failed.
8617 		 */
8618 		if (res.status != NFS4_OK && res.array_len <= 2) {
8619 			e.error = geterrno4(res.status);
8620 			PURGE_ATTRCACHE4(dvp);
8621 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8622 						&recov_state, needrecov);
8623 			need_end_op = FALSE;
8624 			nfs4_purge_stale_fh(e.error, dvp, cr);
8625 			/*
8626 			 * System V defines rmdir to return EEXIST, not
8627 			 * ENOTEMPTY if the directory is not empty.  Over
8628 			 * the wire, the error is NFSERR_ENOTEMPTY which
8629 			 * geterrno4 maps to ENOTEMPTY.
8630 			 */
8631 			if (e.error == ENOTEMPTY)
8632 				e.error = EEXIST;
8633 		} else {
8634 			resop = &res.array[1];	/* remove res */
8635 			rm_res = &resop->nfs_resop4_u.opremove;
8636 
8637 			if (res.status == NFS4_OK) {
8638 				resop = &res.array[2];	/* dir attrs */
8639 				dinfo.di_garp =
8640 					&resop->nfs_resop4_u.opgetattr.ga_res;
8641 				dinfo.di_cred = cr;
8642 				dinfop = &dinfo;
8643 			} else
8644 				dinfop = NULL;
8645 
8646 			/* Update dir attribute, readdir and dnlc caches */
8647 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8648 				dinfop);
8649 
8650 			/* destroy rddir cache for dir that was removed */
8651 			if (VTOR4(vp)->r_dir != NULL)
8652 				nfs4_purge_rddir_cache(vp);
8653 		}
8654 	}
8655 
8656 	if (need_end_op)
8657 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8658 
8659 	nfs_rw_exit(&drp->r_rwlock);
8660 
8661 	if (resp)
8662 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8663 
8664 	if (e.error == 0) {
8665 		vnode_t *tvp;
8666 		rnode4_t *trp;
8667 		trp = VTOR4(vp);
8668 		tvp = vp;
8669 		if (IS_SHADOW(vp, trp))
8670 			tvp = RTOV4(trp);
8671 		vnevent_rmdir(tvp, dvp, nm);
8672 	}
8673 
8674 	VN_RELE(vp);
8675 
8676 	return (e.error);
8677 }
8678 
8679 static int
8680 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr)
8681 {
8682 	int error;
8683 	vnode_t *vp;
8684 	rnode4_t *rp;
8685 	char *contents;
8686 	mntinfo4_t *mi = VTOMI4(dvp);
8687 
8688 	if (nfs_zone() != mi->mi_zone)
8689 		return (EPERM);
8690 	if (!(mi->mi_flags & MI4_SYMLINK))
8691 		return (EOPNOTSUPP);
8692 
8693 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8694 	if (error) {
8695 		return (error);
8696 	}
8697 
8698 	ASSERT(nfs4_consistent_type(vp));
8699 	rp = VTOR4(vp);
8700 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8701 
8702 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8703 
8704 		if (contents != NULL) {
8705 			mutex_enter(&rp->r_statelock);
8706 			if (rp->r_symlink.contents == NULL) {
8707 				rp->r_symlink.len = strlen(tnm);
8708 				bcopy(tnm, contents, rp->r_symlink.len);
8709 				rp->r_symlink.contents = contents;
8710 				rp->r_symlink.size = MAXPATHLEN;
8711 				mutex_exit(&rp->r_statelock);
8712 			} else {
8713 				mutex_exit(&rp->r_statelock);
8714 				kmem_free((void *)contents, MAXPATHLEN);
8715 			}
8716 		}
8717 	}
8718 	VN_RELE(vp);
8719 
8720 	return (error);
8721 }
8722 
8723 
8724 /*
8725  * Read directory entries.
8726  * There are some weird things to look out for here.  The uio_loffset
8727  * field is either 0 or it is the offset returned from a previous
8728  * readdir.  It is an opaque value used by the server to find the
8729  * correct directory block to read. The count field is the number
8730  * of blocks to read on the server.  This is advisory only, the server
8731  * may return only one block's worth of entries.  Entries may be compressed
8732  * on the server.
8733  */
8734 static int
8735 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp)
8736 {
8737 	int error;
8738 	uint_t count;
8739 	rnode4_t *rp;
8740 	rddir4_cache *rdc;
8741 	rddir4_cache *rrdc;
8742 
8743 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8744 		return (EIO);
8745 	rp = VTOR4(vp);
8746 
8747 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8748 
8749 	/*
8750 	 * Make sure that the directory cache is valid.
8751 	 */
8752 	if (rp->r_dir != NULL) {
8753 		if (nfs_disable_rddir_cache != 0) {
8754 			/*
8755 			 * Setting nfs_disable_rddir_cache in /etc/system
8756 			 * allows interoperability with servers that do not
8757 			 * properly update the attributes of directories.
8758 			 * Any cached information gets purged before an
8759 			 * access is made to it.
8760 			 */
8761 			nfs4_purge_rddir_cache(vp);
8762 		}
8763 
8764 		error = nfs4_validate_caches(vp, cr);
8765 		if (error)
8766 			return (error);
8767 	}
8768 
8769 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8770 
8771 	/*
8772 	 * Short circuit last readdir which always returns 0 bytes.
8773 	 * This can be done after the directory has been read through
8774 	 * completely at least once.  This will set r_direof which
8775 	 * can be used to find the value of the last cookie.
8776 	 */
8777 	mutex_enter(&rp->r_statelock);
8778 	if (rp->r_direof != NULL &&
8779 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8780 		mutex_exit(&rp->r_statelock);
8781 #ifdef DEBUG
8782 		nfs4_readdir_cache_shorts++;
8783 #endif
8784 		if (eofp)
8785 			*eofp = 1;
8786 		return (0);
8787 	}
8788 
8789 	/*
8790 	 * Look for a cache entry.  Cache entries are identified
8791 	 * by the NFS cookie value and the byte count requested.
8792 	 */
8793 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8794 
8795 	/*
8796 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8797 	 */
8798 	if (rdc == NULL) {
8799 		mutex_exit(&rp->r_statelock);
8800 		return (EINTR);
8801 	}
8802 
8803 	/*
8804 	 * Check to see if we need to fill this entry in.
8805 	 */
8806 	if (rdc->flags & RDDIRREQ) {
8807 		rdc->flags &= ~RDDIRREQ;
8808 		rdc->flags |= RDDIR;
8809 		mutex_exit(&rp->r_statelock);
8810 
8811 		/*
8812 		 * Do the readdir.
8813 		 */
8814 		nfs4readdir(vp, rdc, cr);
8815 
8816 		/*
8817 		 * Reaquire the lock, so that we can continue
8818 		 */
8819 		mutex_enter(&rp->r_statelock);
8820 		/*
8821 		 * The entry is now complete
8822 		 */
8823 		rdc->flags &= ~RDDIR;
8824 	}
8825 
8826 	ASSERT(!(rdc->flags & RDDIR));
8827 
8828 	/*
8829 	 * If an error occurred while attempting
8830 	 * to fill the cache entry, mark the entry invalid and
8831 	 * just return the error.
8832 	 */
8833 	if (rdc->error) {
8834 		error = rdc->error;
8835 		rdc->flags |= RDDIRREQ;
8836 		rddir4_cache_rele(rp, rdc);
8837 		mutex_exit(&rp->r_statelock);
8838 		return (error);
8839 	}
8840 
8841 	/*
8842 	 * The cache entry is complete and good,
8843 	 * copyout the dirent structs to the calling
8844 	 * thread.
8845 	 */
8846 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
8847 
8848 	/*
8849 	 * If no error occurred during the copyout,
8850 	 * update the offset in the uio struct to
8851 	 * contain the value of the next NFS 4 cookie
8852 	 * and set the eof value appropriately.
8853 	 */
8854 	if (!error) {
8855 		uiop->uio_loffset = rdc->nfs4_ncookie;
8856 		if (eofp)
8857 			*eofp = rdc->eof;
8858 	}
8859 
8860 	/*
8861 	 * Decide whether to do readahead.  Don't if we
8862 	 * have already read to the end of directory.
8863 	 */
8864 	if (rdc->eof) {
8865 		/*
8866 		 * Make the entry the direof only if it is cached
8867 		 */
8868 		if (rdc->flags & RDDIRCACHED)
8869 			rp->r_direof = rdc;
8870 		rddir4_cache_rele(rp, rdc);
8871 		mutex_exit(&rp->r_statelock);
8872 		return (error);
8873 	}
8874 
8875 	/* Determine if a readdir readahead should be done */
8876 	if (!(rp->r_flags & R4LOOKUP)) {
8877 		rddir4_cache_rele(rp, rdc);
8878 		mutex_exit(&rp->r_statelock);
8879 		return (error);
8880 	}
8881 
8882 	/*
8883 	 * Now look for a readahead entry.
8884 	 *
8885 	 * Check to see whether we found an entry for the readahead.
8886 	 * If so, we don't need to do anything further, so free the new
8887 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
8888 	 * it to the cache, and then initiate an asynchronous readdir
8889 	 * operation to fill it.
8890 	 */
8891 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
8892 
8893 	/*
8894 	 * A readdir cache entry could not be obtained for the readahead.  In
8895 	 * this case we skip the readahead and return.
8896 	 */
8897 	if (rrdc == NULL) {
8898 		rddir4_cache_rele(rp, rdc);
8899 		mutex_exit(&rp->r_statelock);
8900 		return (error);
8901 	}
8902 
8903 	/*
8904 	 * Check to see if we need to fill this entry in.
8905 	 */
8906 	if (rrdc->flags & RDDIRREQ) {
8907 		rrdc->flags &= ~RDDIRREQ;
8908 		rrdc->flags |= RDDIR;
8909 		rddir4_cache_rele(rp, rdc);
8910 		mutex_exit(&rp->r_statelock);
8911 #ifdef DEBUG
8912 		nfs4_readdir_readahead++;
8913 #endif
8914 		/*
8915 		 * Do the readdir.
8916 		 */
8917 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
8918 		return (error);
8919 	}
8920 
8921 	rddir4_cache_rele(rp, rrdc);
8922 	rddir4_cache_rele(rp, rdc);
8923 	mutex_exit(&rp->r_statelock);
8924 	return (error);
8925 }
8926 
8927 static int
8928 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
8929 {
8930 	int error;
8931 	rnode4_t *rp;
8932 
8933 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
8934 
8935 	rp = VTOR4(vp);
8936 
8937 	/*
8938 	 * Obtain the readdir results for the caller.
8939 	 */
8940 	nfs4readdir(vp, rdc, cr);
8941 
8942 	mutex_enter(&rp->r_statelock);
8943 	/*
8944 	 * The entry is now complete
8945 	 */
8946 	rdc->flags &= ~RDDIR;
8947 
8948 	error = rdc->error;
8949 	if (error)
8950 		rdc->flags |= RDDIRREQ;
8951 	rddir4_cache_rele(rp, rdc);
8952 	mutex_exit(&rp->r_statelock);
8953 
8954 	return (error);
8955 }
8956 
8957 static void
8958 nfs4readdir_stub(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
8959 {
8960 	int stublength;
8961 	dirent64_t *dp;
8962 	u_longlong_t nodeid, pnodeid;
8963 	vnode_t *dotdotvp = NULL;
8964 	rnode4_t *rp = VTOR4(vp);
8965 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
8966 
8967 	rdc->error = 0;
8968 	rdc->entries = 0;
8969 	rdc->actlen = rdc->entlen = 0;
8970 	rdc->eof = TRUE;
8971 
8972 	/* Check for EOF case for readdir of stub */
8973 	if (cookie != 0 && cookie != 1)
8974 		return;
8975 
8976 	nodeid = rp->r_attr.va_nodeid;
8977 	if (vp->v_flag & VROOT) {
8978 		pnodeid = nodeid;	/* root of mount point */
8979 	} else {
8980 		if (rdc->error = nfs4_lookup(vp, "..", &dotdotvp, 0, 0, 0, cr))
8981 			return;
8982 		pnodeid = VTOR4(dotdotvp)->r_attr.va_nodeid;
8983 		VN_RELE(dotdotvp);
8984 	}
8985 
8986 	stublength = DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2);
8987 	rdc->entries = kmem_alloc(stublength, KM_SLEEP);
8988 	rdc->entlen = rdc->buflen = stublength;
8989 	rdc->eof = TRUE;
8990 
8991 	dp = (dirent64_t *)rdc->entries;
8992 
8993 	if (rdc->nfs4_cookie == (nfs_cookie4)0) {
8994 		bcopy(nfs4_dot_entries, rdc->entries,
8995 			DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2));
8996 		dp->d_ino = nodeid;
8997 		dp = (struct dirent64 *)(((char *)dp) + DIRENT64_RECLEN(1));
8998 		dp->d_ino = pnodeid;
8999 		rdc->actlen = DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2);
9000 	} else	{	/* for ".." entry */
9001 		bcopy(nfs4_dot_dot_entry, rdc->entries, DIRENT64_RECLEN(2));
9002 		dp->d_ino = pnodeid;
9003 		rdc->actlen = DIRENT64_RECLEN(2);
9004 	}
9005 	rdc->nfs4_ncookie = rdc->actlen;
9006 }
9007 
9008 /*
9009  * Read directory entries.
9010  * There are some weird things to look out for here.  The uio_loffset
9011  * field is either 0 or it is the offset returned from a previous
9012  * readdir.  It is an opaque value used by the server to find the
9013  * correct directory block to read. The count field is the number
9014  * of blocks to read on the server.  This is advisory only, the server
9015  * may return only one block's worth of entries.  Entries may be compressed
9016  * on the server.
9017  *
9018  * Generates the following compound request:
9019  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9020  *    must include a Lookupp as well. In this case, send:
9021  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9022  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9023  *
9024  * Get complete attributes and filehandles for entries if this is the
9025  * first read of the directory. Otherwise, just get fileid's.
9026  */
9027 static void
9028 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9029 {
9030 	COMPOUND4args_clnt args;
9031 	COMPOUND4res_clnt res;
9032 	READDIR4args *rargs;
9033 	READDIR4res_clnt *rd_res;
9034 	bitmap4 rd_bitsval;
9035 	nfs_argop4 argop[5];
9036 	nfs_resop4 *resop;
9037 	rnode4_t *rp = VTOR4(vp);
9038 	mntinfo4_t *mi = VTOMI4(vp);
9039 	int doqueue;
9040 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9041 	vnode_t *dvp;
9042 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9043 	int num_ops, res_opcnt;
9044 	bool_t needrecov = FALSE;
9045 	nfs4_recov_state_t recov_state;
9046 	hrtime_t t;
9047 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9048 
9049 	ASSERT(nfs_zone() == mi->mi_zone);
9050 	ASSERT(rdc->flags & RDDIR);
9051 	ASSERT(rdc->entries == NULL);
9052 
9053 	if (rp->r_flags & R4SRVSTUB) {
9054 		nfs4readdir_stub(vp, rdc, cr);
9055 		return;
9056 	}
9057 
9058 	num_ops = 2;
9059 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9060 		/*
9061 		 * Since nfsv4 readdir may not return entries for "." and "..",
9062 		 * the client must recreate them:
9063 		 * To find the correct nodeid, do the following:
9064 		 * For current node, get nodeid from dnlc.
9065 		 * - if current node is rootvp, set pnodeid to nodeid.
9066 		 * - else if parent is in the dnlc, get its nodeid from there.
9067 		 * - else add LOOKUPP+GETATTR to compound.
9068 		 */
9069 		nodeid = rp->r_attr.va_nodeid;
9070 		if (vp->v_flag & VROOT) {
9071 			pnodeid = nodeid;	/* root of mount point */
9072 		} else {
9073 			dvp = dnlc_lookup(vp, "..");
9074 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9075 				/* parent in dnlc cache - no need for otw */
9076 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9077 			} else {
9078 				/*
9079 				 * parent not in dnlc cache,
9080 				 * do lookupp to get its id
9081 				 */
9082 				num_ops = 5;
9083 				pnodeid = 0; /* set later by getattr parent */
9084 			}
9085 			if (dvp)
9086 				VN_RELE(dvp);
9087 		}
9088 	}
9089 	recov_state.rs_flags = 0;
9090 	recov_state.rs_num_retry_despite_err = 0;
9091 
9092 	/* Save the original mount point security flavor */
9093 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9094 
9095 recov_retry:
9096 	args.ctag = TAG_READDIR;
9097 
9098 	args.array = argop;
9099 	args.array_len = num_ops;
9100 
9101 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9102 					&recov_state, NULL)) {
9103 		/*
9104 		 * If readdir a node that is a stub for a crossed mount point,
9105 		 * keep the original secinfo flavor for the current file
9106 		 * system, not the crossed one.
9107 		 */
9108 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9109 		rdc->error = e.error;
9110 		return;
9111 	}
9112 
9113 	/*
9114 	 * Determine which attrs to request for dirents.  This code
9115 	 * must be protected by nfs4_start/end_fop because of r_server
9116 	 * (which will change during failover recovery).
9117 	 *
9118 	 */
9119 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9120 		/*
9121 		 * Get all vattr attrs plus filehandle and rdattr_error
9122 		 */
9123 		rd_bitsval = NFS4_VATTR_MASK |
9124 			FATTR4_RDATTR_ERROR_MASK |
9125 			FATTR4_FILEHANDLE_MASK;
9126 
9127 		if (rp->r_flags & R4READDIRWATTR) {
9128 			mutex_enter(&rp->r_statelock);
9129 			rp->r_flags &= ~R4READDIRWATTR;
9130 			mutex_exit(&rp->r_statelock);
9131 		}
9132 	} else {
9133 		servinfo4_t *svp = rp->r_server;
9134 
9135 		/*
9136 		 * Already read directory. Use readdir with
9137 		 * no attrs (except for mounted_on_fileid) for updates.
9138 		 */
9139 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9140 
9141 		/*
9142 		 * request mounted on fileid if supported, else request
9143 		 * fileid.  maybe we should verify that fileid is supported
9144 		 * and request something else if not.
9145 		 */
9146 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9147 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9148 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9149 		nfs_rw_exit(&svp->sv_lock);
9150 	}
9151 
9152 	/* putfh directory fh */
9153 	argop[0].argop = OP_CPUTFH;
9154 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9155 
9156 	argop[1].argop = OP_READDIR;
9157 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9158 	/*
9159 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9160 	 * cookie 0 should be used over-the-wire to start reading at
9161 	 * the beginning of the directory excluding "." and "..".
9162 	 */
9163 	if (rdc->nfs4_cookie == 0 ||
9164 	    rdc->nfs4_cookie == 1 ||
9165 	    rdc->nfs4_cookie == 2) {
9166 		rargs->cookie = (nfs_cookie4)0;
9167 		rargs->cookieverf = 0;
9168 	} else {
9169 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9170 		mutex_enter(&rp->r_statelock);
9171 		rargs->cookieverf = rp->r_cookieverf4;
9172 		mutex_exit(&rp->r_statelock);
9173 	}
9174 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9175 	rargs->maxcount = mi->mi_tsize;
9176 	rargs->attr_request = rd_bitsval;
9177 	rargs->rdc = rdc;
9178 	rargs->dvp = vp;
9179 	rargs->mi = mi;
9180 	rargs->cr = cr;
9181 
9182 
9183 	/*
9184 	 * If count < than the minimum required, we return no entries
9185 	 * and fail with EINVAL
9186 	 */
9187 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9188 		rdc->error = EINVAL;
9189 		goto out;
9190 	}
9191 
9192 	if (args.array_len == 5) {
9193 		/*
9194 		 * Add lookupp and getattr for parent nodeid.
9195 		 */
9196 		argop[2].argop = OP_LOOKUPP;
9197 
9198 		argop[3].argop = OP_GETFH;
9199 
9200 		/* getattr parent */
9201 		argop[4].argop = OP_GETATTR;
9202 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9203 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9204 	}
9205 
9206 	doqueue = 1;
9207 
9208 	if (mi->mi_io_kstats) {
9209 		mutex_enter(&mi->mi_lock);
9210 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9211 		mutex_exit(&mi->mi_lock);
9212 	}
9213 
9214 	/* capture the time of this call */
9215 	rargs->t = t = gethrtime();
9216 
9217 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9218 
9219 	if (mi->mi_io_kstats) {
9220 		mutex_enter(&mi->mi_lock);
9221 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9222 		mutex_exit(&mi->mi_lock);
9223 	}
9224 
9225 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9226 
9227 	/*
9228 	 * If RPC error occurred and it isn't an error that
9229 	 * triggers recovery, then go ahead and fail now.
9230 	 */
9231 	if (e.error != 0 && !needrecov) {
9232 		rdc->error = e.error;
9233 		goto out;
9234 	}
9235 
9236 	if (needrecov) {
9237 		bool_t abort;
9238 
9239 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9240 		    "nfs4readdir: initiating recovery.\n"));
9241 
9242 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9243 			    NULL, OP_READDIR, NULL);
9244 		if (abort == FALSE) {
9245 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9246 				    &recov_state, needrecov);
9247 			if (!e.error)
9248 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9249 						(caddr_t)&res);
9250 			if (rdc->entries != NULL) {
9251 				kmem_free(rdc->entries, rdc->entlen);
9252 				rdc->entries = NULL;
9253 			}
9254 			goto recov_retry;
9255 		}
9256 
9257 		if (e.error != 0) {
9258 			rdc->error = e.error;
9259 			goto out;
9260 		}
9261 
9262 		/* fall through for res.status case */
9263 	}
9264 
9265 	res_opcnt = res.array_len;
9266 
9267 	/*
9268 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9269 	 * failure here.  Subsequent ops are for filling out dot-dot
9270 	 * dirent, and if they fail, we still want to give the caller
9271 	 * the dirents returned by (the successful) READDIR op, so we need
9272 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9273 	 *
9274 	 * One example where PUTFH+READDIR ops would succeed but
9275 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9276 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9277 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9278 	 * x perm.  We need to come up with a non-vendor-specific way
9279 	 * for a POSIX server to return d_ino from dotdot's dirent if
9280 	 * client only requests mounted_on_fileid, and just say the
9281 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9282 	 * client requested any mandatory attrs, server would be required
9283 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9284 	 * for dotdot.
9285 	 */
9286 
9287 	if (res.status) {
9288 		if (res_opcnt <= 2) {
9289 			e.error = geterrno4(res.status);
9290 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9291 			    &recov_state, needrecov);
9292 			nfs4_purge_stale_fh(e.error, vp, cr);
9293 			rdc->error = e.error;
9294 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9295 			if (rdc->entries != NULL) {
9296 				kmem_free(rdc->entries, rdc->entlen);
9297 				rdc->entries = NULL;
9298 			}
9299 			/*
9300 			 * If readdir a node that is a stub for a
9301 			 * crossed mount point, keep the original
9302 			 * secinfo flavor for the current file system,
9303 			 * not the crossed one.
9304 			 */
9305 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9306 			return;
9307 		}
9308 	}
9309 
9310 	resop = &res.array[1];	/* readdir res */
9311 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9312 
9313 	mutex_enter(&rp->r_statelock);
9314 	rp->r_cookieverf4 = rd_res->cookieverf;
9315 	mutex_exit(&rp->r_statelock);
9316 
9317 	/*
9318 	 * For "." and ".." entries
9319 	 * e.g.
9320 	 *	seek(cookie=0) -> "." entry with d_off = 1
9321 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9322 	 */
9323 	if (cookie == (nfs_cookie4) 0) {
9324 		if (rd_res->dotp)
9325 			rd_res->dotp->d_ino = nodeid;
9326 		if (rd_res->dotdotp)
9327 			rd_res->dotdotp->d_ino = pnodeid;
9328 	}
9329 	if (cookie == (nfs_cookie4) 1) {
9330 		if (rd_res->dotdotp)
9331 			rd_res->dotdotp->d_ino = pnodeid;
9332 	}
9333 
9334 
9335 	/* LOOKUPP+GETATTR attemped */
9336 	if (args.array_len == 5 && rd_res->dotdotp) {
9337 		if (res.status == NFS4_OK && res_opcnt == 5) {
9338 			nfs_fh4 *fhp;
9339 			nfs4_sharedfh_t *sfhp;
9340 			vnode_t *pvp;
9341 			nfs4_ga_res_t *garp;
9342 
9343 			resop++;	/* lookupp */
9344 			resop++;	/* getfh   */
9345 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9346 
9347 			resop++;	/* getattr of parent */
9348 
9349 			/*
9350 			 * First, take care of finishing the
9351 			 * readdir results.
9352 			 */
9353 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9354 			/*
9355 			 * The d_ino of .. must be the inode number
9356 			 * of the mounted filesystem.
9357 			 */
9358 			if (garp->n4g_va.va_mask & AT_NODEID)
9359 				rd_res->dotdotp->d_ino =
9360 					garp->n4g_va.va_nodeid;
9361 
9362 
9363 			/*
9364 			 * Next, create the ".." dnlc entry
9365 			 */
9366 			sfhp = sfh4_get(fhp, mi);
9367 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9368 				dnlc_update(vp, "..", pvp);
9369 				VN_RELE(pvp);
9370 			}
9371 			sfh4_rele(&sfhp);
9372 		}
9373 	}
9374 
9375 	if (mi->mi_io_kstats) {
9376 		mutex_enter(&mi->mi_lock);
9377 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9378 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9379 		mutex_exit(&mi->mi_lock);
9380 	}
9381 
9382 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9383 
9384 out:
9385 	/*
9386 	 * If readdir a node that is a stub for a crossed mount point,
9387 	 * keep the original secinfo flavor for the current file system,
9388 	 * not the crossed one.
9389 	 */
9390 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9391 
9392 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9393 }
9394 
9395 
9396 static int
9397 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9398 {
9399 	rnode4_t *rp = VTOR4(bp->b_vp);
9400 	int count;
9401 	int error;
9402 	cred_t *cred_otw = NULL;
9403 	offset_t offset;
9404 	nfs4_open_stream_t *osp = NULL;
9405 	bool_t first_time = TRUE;	/* first time getting otw cred */
9406 	bool_t last_time = FALSE;	/* last time getting otw cred */
9407 
9408 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9409 
9410 	DTRACE_IO1(start, struct buf *, bp);
9411 	offset = ldbtob(bp->b_lblkno);
9412 
9413 	if (bp->b_flags & B_READ) {
9414 	read_again:
9415 		/*
9416 		 * Releases the osp, if it is provided.
9417 		 * Puts a hold on the cred_otw and the new osp (if found).
9418 		 */
9419 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9420 			&first_time, &last_time);
9421 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9422 						offset, bp->b_bcount,
9423 						&bp->b_resid, cred_otw,
9424 						readahead, NULL);
9425 		crfree(cred_otw);
9426 		if (!error) {
9427 			if (bp->b_resid) {
9428 				/*
9429 				 * Didn't get it all because we hit EOF,
9430 				 * zero all the memory beyond the EOF.
9431 				 */
9432 				/* bzero(rdaddr + */
9433 				bzero(bp->b_un.b_addr +
9434 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9435 			}
9436 			mutex_enter(&rp->r_statelock);
9437 			if (bp->b_resid == bp->b_bcount &&
9438 			    offset >= rp->r_size) {
9439 				/*
9440 				 * We didn't read anything at all as we are
9441 				 * past EOF.  Return an error indicator back
9442 				 * but don't destroy the pages (yet).
9443 				 */
9444 				error = NFS_EOF;
9445 			}
9446 			mutex_exit(&rp->r_statelock);
9447 		} else if (error == EACCES && last_time == FALSE) {
9448 				goto read_again;
9449 		}
9450 	} else {
9451 		if (!(rp->r_flags & R4STALE)) {
9452 		write_again:
9453 			/*
9454 			 * Releases the osp, if it is provided.
9455 			 * Puts a hold on the cred_otw and the new
9456 			 * osp (if found).
9457 			 */
9458 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9459 				&first_time, &last_time);
9460 			mutex_enter(&rp->r_statelock);
9461 			count = MIN(bp->b_bcount, rp->r_size - offset);
9462 			mutex_exit(&rp->r_statelock);
9463 			if (count < 0)
9464 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9465 #ifdef DEBUG
9466 			if (count == 0) {
9467 				zoneid_t zoneid = getzoneid();
9468 
9469 				zcmn_err(zoneid, CE_WARN,
9470 				    "nfs4_bio: zero length write at %lld",
9471 				    offset);
9472 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9473 				    "b_bcount=%ld, file size=%lld",
9474 				    rp->r_flags, (long)bp->b_bcount,
9475 				    rp->r_size);
9476 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9477 				if (nfs4_bio_do_stop)
9478 					debug_enter("nfs4_bio");
9479 			}
9480 #endif
9481 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9482 			    count, cred_otw, stab_comm);
9483 			if (error == EACCES && last_time == FALSE) {
9484 				crfree(cred_otw);
9485 				goto write_again;
9486 			}
9487 			bp->b_error = error;
9488 			if (error && error != EINTR &&
9489 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9490 				/*
9491 				 * Don't print EDQUOT errors on the console.
9492 				 * Don't print asynchronous EACCES errors.
9493 				 * Don't print EFBIG errors.
9494 				 * Print all other write errors.
9495 				 */
9496 				if (error != EDQUOT && error != EFBIG &&
9497 				    (error != EACCES ||
9498 				    !(bp->b_flags & B_ASYNC)))
9499 					nfs4_write_error(bp->b_vp,
9500 					    error, cred_otw);
9501 				/*
9502 				 * Update r_error and r_flags as appropriate.
9503 				 * If the error was ESTALE, then mark the
9504 				 * rnode as not being writeable and save
9505 				 * the error status.  Otherwise, save any
9506 				 * errors which occur from asynchronous
9507 				 * page invalidations.  Any errors occurring
9508 				 * from other operations should be saved
9509 				 * by the caller.
9510 				 */
9511 				mutex_enter(&rp->r_statelock);
9512 				if (error == ESTALE) {
9513 					rp->r_flags |= R4STALE;
9514 					if (!rp->r_error)
9515 						rp->r_error = error;
9516 				} else if (!rp->r_error &&
9517 				    (bp->b_flags &
9518 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9519 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9520 					rp->r_error = error;
9521 				}
9522 				mutex_exit(&rp->r_statelock);
9523 			}
9524 			crfree(cred_otw);
9525 		} else
9526 			error = rp->r_error;
9527 	}
9528 
9529 	if (error != 0 && error != NFS_EOF)
9530 		bp->b_flags |= B_ERROR;
9531 
9532 	if (osp)
9533 		open_stream_rele(osp, rp);
9534 
9535 	DTRACE_IO1(done, struct buf *, bp);
9536 
9537 	return (error);
9538 }
9539 
9540 /* ARGSUSED */
9541 static int
9542 nfs4_fid(vnode_t *vp, fid_t *fidp)
9543 {
9544 	return (EREMOTE);
9545 }
9546 
9547 /* ARGSUSED2 */
9548 static int
9549 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9550 {
9551 	rnode4_t *rp = VTOR4(vp);
9552 
9553 	if (!write_lock) {
9554 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9555 		return (V_WRITELOCK_FALSE);
9556 	}
9557 
9558 	if ((rp->r_flags & R4DIRECTIO) ||
9559 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9560 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9561 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9562 			return (V_WRITELOCK_FALSE);
9563 		nfs_rw_exit(&rp->r_rwlock);
9564 	}
9565 
9566 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9567 	return (V_WRITELOCK_TRUE);
9568 }
9569 
9570 /* ARGSUSED */
9571 static void
9572 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9573 {
9574 	rnode4_t *rp = VTOR4(vp);
9575 
9576 	nfs_rw_exit(&rp->r_rwlock);
9577 }
9578 
9579 /* ARGSUSED */
9580 static int
9581 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp)
9582 {
9583 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9584 		return (EIO);
9585 
9586 	/*
9587 	 * Because we stuff the readdir cookie into the offset field
9588 	 * someone may attempt to do an lseek with the cookie which
9589 	 * we want to succeed.
9590 	 */
9591 	if (vp->v_type == VDIR)
9592 		return (0);
9593 	if (*noffp < 0)
9594 		return (EINVAL);
9595 	return (0);
9596 }
9597 
9598 
9599 /*
9600  * Return all the pages from [off..off+len) in file
9601  */
9602 static int
9603 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9604 	page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9605 	enum seg_rw rw, cred_t *cr)
9606 {
9607 	rnode4_t *rp;
9608 	int error;
9609 	mntinfo4_t *mi;
9610 
9611 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9612 		return (EIO);
9613 	rp = VTOR4(vp);
9614 	if (IS_SHADOW(vp, rp))
9615 		vp = RTOV4(rp);
9616 
9617 	if (vp->v_flag & VNOMAP)
9618 		return (ENOSYS);
9619 
9620 	if (protp != NULL)
9621 		*protp = PROT_ALL;
9622 
9623 	/*
9624 	 * Now validate that the caches are up to date.
9625 	 */
9626 	if (error = nfs4_validate_caches(vp, cr))
9627 		return (error);
9628 
9629 	mi = VTOMI4(vp);
9630 retry:
9631 	mutex_enter(&rp->r_statelock);
9632 
9633 	/*
9634 	 * Don't create dirty pages faster than they
9635 	 * can be cleaned so that the system doesn't
9636 	 * get imbalanced.  If the async queue is
9637 	 * maxed out, then wait for it to drain before
9638 	 * creating more dirty pages.  Also, wait for
9639 	 * any threads doing pagewalks in the vop_getattr
9640 	 * entry points so that they don't block for
9641 	 * long periods.
9642 	 */
9643 	if (rw == S_CREATE) {
9644 		while ((mi->mi_max_threads != 0 &&
9645 			rp->r_awcount > 2 * mi->mi_max_threads) ||
9646 			rp->r_gcount > 0)
9647 			cv_wait(&rp->r_cv, &rp->r_statelock);
9648 	}
9649 
9650 	/*
9651 	 * If we are getting called as a side effect of an nfs_write()
9652 	 * operation the local file size might not be extended yet.
9653 	 * In this case we want to be able to return pages of zeroes.
9654 	 */
9655 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9656 		NFS4_DEBUG(nfs4_pageio_debug,
9657 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9658 		    "len=%llu, size=%llu, attrsize =%llu", off,
9659 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9660 		mutex_exit(&rp->r_statelock);
9661 		return (EFAULT);		/* beyond EOF */
9662 	}
9663 
9664 	mutex_exit(&rp->r_statelock);
9665 
9666 	if (len <= PAGESIZE) {
9667 		error = nfs4_getapage(vp, off, len, protp, pl, plsz,
9668 		    seg, addr, rw, cr);
9669 		NFS4_DEBUG(nfs4_pageio_debug && error,
9670 			(CE_NOTE, "getpage error %d; off=%lld, "
9671 			"len=%lld", error, off, (u_longlong_t)len));
9672 	} else {
9673 		error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9674 		    pl, plsz, seg, addr, rw, cr);
9675 		NFS4_DEBUG(nfs4_pageio_debug && error,
9676 			(CE_NOTE, "getpages error %d; off=%lld, "
9677 			"len=%lld", error, off, (u_longlong_t)len));
9678 	}
9679 
9680 	switch (error) {
9681 	case NFS_EOF:
9682 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9683 		goto retry;
9684 	case ESTALE:
9685 		nfs4_purge_stale_fh(error, vp, cr);
9686 	}
9687 
9688 	return (error);
9689 }
9690 
9691 /*
9692  * Called from pvn_getpages or nfs4_getpage to get a particular page.
9693  */
9694 /* ARGSUSED */
9695 static int
9696 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9697 	page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9698 	enum seg_rw rw, cred_t *cr)
9699 {
9700 	rnode4_t *rp;
9701 	uint_t bsize;
9702 	struct buf *bp;
9703 	page_t *pp;
9704 	u_offset_t lbn;
9705 	u_offset_t io_off;
9706 	u_offset_t blkoff;
9707 	u_offset_t rablkoff;
9708 	size_t io_len;
9709 	uint_t blksize;
9710 	int error;
9711 	int readahead;
9712 	int readahead_issued = 0;
9713 	int ra_window; /* readahead window */
9714 	page_t *pagefound;
9715 	page_t *savepp;
9716 
9717 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9718 		return (EIO);
9719 
9720 	rp = VTOR4(vp);
9721 	ASSERT(!IS_SHADOW(vp, rp));
9722 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9723 
9724 reread:
9725 	bp = NULL;
9726 	pp = NULL;
9727 	pagefound = NULL;
9728 
9729 	if (pl != NULL)
9730 		pl[0] = NULL;
9731 
9732 	error = 0;
9733 	lbn = off / bsize;
9734 	blkoff = lbn * bsize;
9735 
9736 	/*
9737 	 * Queueing up the readahead before doing the synchronous read
9738 	 * results in a significant increase in read throughput because
9739 	 * of the increased parallelism between the async threads and
9740 	 * the process context.
9741 	 */
9742 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9743 	    rw != S_CREATE &&
9744 	    !(vp->v_flag & VNOCACHE)) {
9745 		mutex_enter(&rp->r_statelock);
9746 
9747 		/*
9748 		 * Calculate the number of readaheads to do.
9749 		 * a) No readaheads at offset = 0.
9750 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9751 		 *    window is closed.
9752 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9753 		 *    upon how far the readahead window is open or close.
9754 		 * d) No readaheads if rp->r_nextr is not within the scope
9755 		 *    of the readahead window (random i/o).
9756 		 */
9757 
9758 		if (off == 0)
9759 			readahead = 0;
9760 		else if (blkoff == rp->r_nextr)
9761 			readahead = nfs4_nra;
9762 		else if (rp->r_nextr > blkoff &&
9763 			((ra_window = (rp->r_nextr - blkoff) / bsize)
9764 					<= (nfs4_nra - 1)))
9765 			readahead = nfs4_nra - ra_window;
9766 		else
9767 			readahead = 0;
9768 
9769 		rablkoff = rp->r_nextr;
9770 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9771 			mutex_exit(&rp->r_statelock);
9772 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9773 			    addr + (rablkoff + bsize - off),
9774 			    seg, cr, nfs4_readahead) < 0) {
9775 				mutex_enter(&rp->r_statelock);
9776 				break;
9777 			}
9778 			readahead--;
9779 			rablkoff += bsize;
9780 			/*
9781 			 * Indicate that we did a readahead so
9782 			 * readahead offset is not updated
9783 			 * by the synchronous read below.
9784 			 */
9785 			readahead_issued = 1;
9786 			mutex_enter(&rp->r_statelock);
9787 			/*
9788 			 * set readahead offset to
9789 			 * offset of last async readahead
9790 			 * request.
9791 			 */
9792 			rp->r_nextr = rablkoff;
9793 		}
9794 		mutex_exit(&rp->r_statelock);
9795 	}
9796 
9797 again:
9798 	if ((pagefound = page_exists(vp, off)) == NULL) {
9799 		if (pl == NULL) {
9800 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9801 			    nfs4_readahead);
9802 		} else if (rw == S_CREATE) {
9803 			/*
9804 			 * Block for this page is not allocated, or the offset
9805 			 * is beyond the current allocation size, or we're
9806 			 * allocating a swap slot and the page was not found,
9807 			 * so allocate it and return a zero page.
9808 			 */
9809 			if ((pp = page_create_va(vp, off,
9810 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9811 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9812 			io_len = PAGESIZE;
9813 			mutex_enter(&rp->r_statelock);
9814 			rp->r_nextr = off + PAGESIZE;
9815 			mutex_exit(&rp->r_statelock);
9816 		} else {
9817 			/*
9818 			 * Need to go to server to get a block
9819 			 */
9820 			mutex_enter(&rp->r_statelock);
9821 			if (blkoff < rp->r_size &&
9822 			    blkoff + bsize > rp->r_size) {
9823 				/*
9824 				 * If less than a block left in
9825 				 * file read less than a block.
9826 				 */
9827 				if (rp->r_size <= off) {
9828 					/*
9829 					 * Trying to access beyond EOF,
9830 					 * set up to get at least one page.
9831 					 */
9832 					blksize = off + PAGESIZE - blkoff;
9833 				} else
9834 					blksize = rp->r_size - blkoff;
9835 			} else if ((off == 0) ||
9836 				(off != rp->r_nextr && !readahead_issued)) {
9837 				blksize = PAGESIZE;
9838 				blkoff = off; /* block = page here */
9839 			} else
9840 				blksize = bsize;
9841 			mutex_exit(&rp->r_statelock);
9842 
9843 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9844 			    &io_len, blkoff, blksize, 0);
9845 
9846 			/*
9847 			 * Some other thread has entered the page,
9848 			 * so just use it.
9849 			 */
9850 			if (pp == NULL)
9851 				goto again;
9852 
9853 			/*
9854 			 * Now round the request size up to page boundaries.
9855 			 * This ensures that the entire page will be
9856 			 * initialized to zeroes if EOF is encountered.
9857 			 */
9858 			io_len = ptob(btopr(io_len));
9859 
9860 			bp = pageio_setup(pp, io_len, vp, B_READ);
9861 			ASSERT(bp != NULL);
9862 
9863 			/*
9864 			 * pageio_setup should have set b_addr to 0.  This
9865 			 * is correct since we want to do I/O on a page
9866 			 * boundary.  bp_mapin will use this addr to calculate
9867 			 * an offset, and then set b_addr to the kernel virtual
9868 			 * address it allocated for us.
9869 			 */
9870 			ASSERT(bp->b_un.b_addr == 0);
9871 
9872 			bp->b_edev = 0;
9873 			bp->b_dev = 0;
9874 			bp->b_lblkno = lbtodb(io_off);
9875 			bp->b_file = vp;
9876 			bp->b_offset = (offset_t)off;
9877 			bp_mapin(bp);
9878 
9879 			/*
9880 			 * If doing a write beyond what we believe is EOF,
9881 			 * don't bother trying to read the pages from the
9882 			 * server, we'll just zero the pages here.  We
9883 			 * don't check that the rw flag is S_WRITE here
9884 			 * because some implementations may attempt a
9885 			 * read access to the buffer before copying data.
9886 			 */
9887 			mutex_enter(&rp->r_statelock);
9888 			if (io_off >= rp->r_size && seg == segkmap) {
9889 				mutex_exit(&rp->r_statelock);
9890 				bzero(bp->b_un.b_addr, io_len);
9891 			} else {
9892 				mutex_exit(&rp->r_statelock);
9893 				error = nfs4_bio(bp, NULL, cr, FALSE);
9894 			}
9895 
9896 			/*
9897 			 * Unmap the buffer before freeing it.
9898 			 */
9899 			bp_mapout(bp);
9900 			pageio_done(bp);
9901 
9902 			savepp = pp;
9903 			do {
9904 				pp->p_fsdata = C_NOCOMMIT;
9905 			} while ((pp = pp->p_next) != savepp);
9906 
9907 			if (error == NFS_EOF) {
9908 				/*
9909 				 * If doing a write system call just return
9910 				 * zeroed pages, else user tried to get pages
9911 				 * beyond EOF, return error.  We don't check
9912 				 * that the rw flag is S_WRITE here because
9913 				 * some implementations may attempt a read
9914 				 * access to the buffer before copying data.
9915 				 */
9916 				if (seg == segkmap)
9917 					error = 0;
9918 				else
9919 					error = EFAULT;
9920 			}
9921 
9922 			if (!readahead_issued && !error) {
9923 				mutex_enter(&rp->r_statelock);
9924 				rp->r_nextr = io_off + io_len;
9925 				mutex_exit(&rp->r_statelock);
9926 			}
9927 		}
9928 	}
9929 
9930 out:
9931 	if (pl == NULL)
9932 		return (error);
9933 
9934 	if (error) {
9935 		if (pp != NULL)
9936 			pvn_read_done(pp, B_ERROR);
9937 		return (error);
9938 	}
9939 
9940 	if (pagefound) {
9941 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
9942 
9943 		/*
9944 		 * Page exists in the cache, acquire the appropriate lock.
9945 		 * If this fails, start all over again.
9946 		 */
9947 		if ((pp = page_lookup(vp, off, se)) == NULL) {
9948 #ifdef DEBUG
9949 			nfs4_lostpage++;
9950 #endif
9951 			goto reread;
9952 		}
9953 		pl[0] = pp;
9954 		pl[1] = NULL;
9955 		return (0);
9956 	}
9957 
9958 	if (pp != NULL)
9959 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
9960 
9961 	return (error);
9962 }
9963 
9964 static void
9965 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
9966 	cred_t *cr)
9967 {
9968 	int error;
9969 	page_t *pp;
9970 	u_offset_t io_off;
9971 	size_t io_len;
9972 	struct buf *bp;
9973 	uint_t bsize, blksize;
9974 	rnode4_t *rp = VTOR4(vp);
9975 	page_t *savepp;
9976 
9977 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9978 
9979 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9980 
9981 	mutex_enter(&rp->r_statelock);
9982 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
9983 		/*
9984 		 * If less than a block left in file read less
9985 		 * than a block.
9986 		 */
9987 		blksize = rp->r_size - blkoff;
9988 	} else
9989 		blksize = bsize;
9990 	mutex_exit(&rp->r_statelock);
9991 
9992 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
9993 	    &io_off, &io_len, blkoff, blksize, 1);
9994 	/*
9995 	 * The isra flag passed to the kluster function is 1, we may have
9996 	 * gotten a return value of NULL for a variety of reasons (# of free
9997 	 * pages < minfree, someone entered the page on the vnode etc). In all
9998 	 * cases, we want to punt on the readahead.
9999 	 */
10000 	if (pp == NULL)
10001 		return;
10002 
10003 	/*
10004 	 * Now round the request size up to page boundaries.
10005 	 * This ensures that the entire page will be
10006 	 * initialized to zeroes if EOF is encountered.
10007 	 */
10008 	io_len = ptob(btopr(io_len));
10009 
10010 	bp = pageio_setup(pp, io_len, vp, B_READ);
10011 	ASSERT(bp != NULL);
10012 
10013 	/*
10014 	 * pageio_setup should have set b_addr to 0.  This is correct since
10015 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10016 	 * to calculate an offset, and then set b_addr to the kernel virtual
10017 	 * address it allocated for us.
10018 	 */
10019 	ASSERT(bp->b_un.b_addr == 0);
10020 
10021 	bp->b_edev = 0;
10022 	bp->b_dev = 0;
10023 	bp->b_lblkno = lbtodb(io_off);
10024 	bp->b_file = vp;
10025 	bp->b_offset = (offset_t)blkoff;
10026 	bp_mapin(bp);
10027 
10028 	/*
10029 	 * If doing a write beyond what we believe is EOF, don't bother trying
10030 	 * to read the pages from the server, we'll just zero the pages here.
10031 	 * We don't check that the rw flag is S_WRITE here because some
10032 	 * implementations may attempt a read access to the buffer before
10033 	 * copying data.
10034 	 */
10035 	mutex_enter(&rp->r_statelock);
10036 	if (io_off >= rp->r_size && seg == segkmap) {
10037 		mutex_exit(&rp->r_statelock);
10038 		bzero(bp->b_un.b_addr, io_len);
10039 		error = 0;
10040 	} else {
10041 		mutex_exit(&rp->r_statelock);
10042 		error = nfs4_bio(bp, NULL, cr, TRUE);
10043 		if (error == NFS_EOF)
10044 			error = 0;
10045 	}
10046 
10047 	/*
10048 	 * Unmap the buffer before freeing it.
10049 	 */
10050 	bp_mapout(bp);
10051 	pageio_done(bp);
10052 
10053 	savepp = pp;
10054 	do {
10055 		pp->p_fsdata = C_NOCOMMIT;
10056 	} while ((pp = pp->p_next) != savepp);
10057 
10058 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10059 
10060 	/*
10061 	 * In case of error set readahead offset
10062 	 * to the lowest offset.
10063 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10064 	 */
10065 	if (error && rp->r_nextr > io_off) {
10066 		mutex_enter(&rp->r_statelock);
10067 		if (rp->r_nextr > io_off)
10068 			rp->r_nextr = io_off;
10069 		mutex_exit(&rp->r_statelock);
10070 	}
10071 }
10072 
10073 /*
10074  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10075  * If len == 0, do from off to EOF.
10076  *
10077  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10078  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10079  * (from pageout).
10080  */
10081 static int
10082 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr)
10083 {
10084 	int error;
10085 	rnode4_t *rp;
10086 
10087 	ASSERT(cr != NULL);
10088 
10089 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10090 		return (EIO);
10091 
10092 	rp = VTOR4(vp);
10093 	if (IS_SHADOW(vp, rp))
10094 		vp = RTOV4(rp);
10095 
10096 	/*
10097 	 * XXX - Why should this check be made here?
10098 	 */
10099 	if (vp->v_flag & VNOMAP)
10100 		return (ENOSYS);
10101 
10102 	if (len == 0 && !(flags & B_INVAL) &&
10103 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10104 		return (0);
10105 
10106 	mutex_enter(&rp->r_statelock);
10107 	rp->r_count++;
10108 	mutex_exit(&rp->r_statelock);
10109 	error = nfs4_putpages(vp, off, len, flags, cr);
10110 	mutex_enter(&rp->r_statelock);
10111 	rp->r_count--;
10112 	cv_broadcast(&rp->r_cv);
10113 	mutex_exit(&rp->r_statelock);
10114 
10115 	return (error);
10116 }
10117 
10118 /*
10119  * Write out a single page, possibly klustering adjacent dirty pages.
10120  */
10121 int
10122 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10123 	int flags, cred_t *cr)
10124 {
10125 	u_offset_t io_off;
10126 	u_offset_t lbn_off;
10127 	u_offset_t lbn;
10128 	size_t io_len;
10129 	uint_t bsize;
10130 	int error;
10131 	rnode4_t *rp;
10132 
10133 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10134 	ASSERT(pp != NULL);
10135 	ASSERT(cr != NULL);
10136 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10137 
10138 	rp = VTOR4(vp);
10139 	ASSERT(rp->r_count > 0);
10140 	ASSERT(!IS_SHADOW(vp, rp));
10141 
10142 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10143 	lbn = pp->p_offset / bsize;
10144 	lbn_off = lbn * bsize;
10145 
10146 	/*
10147 	 * Find a kluster that fits in one block, or in
10148 	 * one page if pages are bigger than blocks.  If
10149 	 * there is less file space allocated than a whole
10150 	 * page, we'll shorten the i/o request below.
10151 	 */
10152 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10153 	    roundup(bsize, PAGESIZE), flags);
10154 
10155 	/*
10156 	 * pvn_write_kluster shouldn't have returned a page with offset
10157 	 * behind the original page we were given.  Verify that.
10158 	 */
10159 	ASSERT((pp->p_offset / bsize) >= lbn);
10160 
10161 	/*
10162 	 * Now pp will have the list of kept dirty pages marked for
10163 	 * write back.  It will also handle invalidation and freeing
10164 	 * of pages that are not dirty.  Check for page length rounding
10165 	 * problems.
10166 	 */
10167 	if (io_off + io_len > lbn_off + bsize) {
10168 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10169 		io_len = lbn_off + bsize - io_off;
10170 	}
10171 	/*
10172 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10173 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10174 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10175 	 * progress and the r_size has not been made consistent with the
10176 	 * new size of the file. When the uiomove() completes the r_size is
10177 	 * updated and the R4MODINPROGRESS flag is cleared.
10178 	 *
10179 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10180 	 * consistent value of r_size. Without this handshaking, it is
10181 	 * possible that nfs4_bio() picks  up the old value of r_size
10182 	 * before the uiomove() in writerp4() completes. This will result
10183 	 * in the write through nfs4_bio() being dropped.
10184 	 *
10185 	 * More precisely, there is a window between the time the uiomove()
10186 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10187 	 * operation intervenes in this window, the page will be picked up,
10188 	 * because it is dirty (it will be unlocked, unless it was
10189 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10190 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10191 	 * checked. This will still be the old size. Therefore the page will
10192 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10193 	 * the page will be found to be clean and the write will be dropped.
10194 	 */
10195 	if (rp->r_flags & R4MODINPROGRESS) {
10196 		mutex_enter(&rp->r_statelock);
10197 		if ((rp->r_flags & R4MODINPROGRESS) &&
10198 		    rp->r_modaddr + MAXBSIZE > io_off &&
10199 		    rp->r_modaddr < io_off + io_len) {
10200 			page_t *plist;
10201 			/*
10202 			 * A write is in progress for this region of the file.
10203 			 * If we did not detect R4MODINPROGRESS here then this
10204 			 * path through nfs_putapage() would eventually go to
10205 			 * nfs4_bio() and may not write out all of the data
10206 			 * in the pages. We end up losing data. So we decide
10207 			 * to set the modified bit on each page in the page
10208 			 * list and mark the rnode with R4DIRTY. This write
10209 			 * will be restarted at some later time.
10210 			 */
10211 			plist = pp;
10212 			while (plist != NULL) {
10213 				pp = plist;
10214 				page_sub(&plist, pp);
10215 				hat_setmod(pp);
10216 				page_io_unlock(pp);
10217 				page_unlock(pp);
10218 			}
10219 			rp->r_flags |= R4DIRTY;
10220 			mutex_exit(&rp->r_statelock);
10221 			if (offp)
10222 				*offp = io_off;
10223 			if (lenp)
10224 				*lenp = io_len;
10225 			return (0);
10226 		}
10227 		mutex_exit(&rp->r_statelock);
10228 	}
10229 
10230 	if (flags & B_ASYNC) {
10231 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10232 		    nfs4_sync_putapage);
10233 	} else
10234 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10235 
10236 	if (offp)
10237 		*offp = io_off;
10238 	if (lenp)
10239 		*lenp = io_len;
10240 	return (error);
10241 }
10242 
10243 static int
10244 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10245 	int flags, cred_t *cr)
10246 {
10247 	int error;
10248 	rnode4_t *rp;
10249 
10250 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10251 
10252 	flags |= B_WRITE;
10253 
10254 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10255 
10256 	rp = VTOR4(vp);
10257 
10258 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10259 	    error == EACCES) &&
10260 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10261 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10262 			mutex_enter(&rp->r_statelock);
10263 			rp->r_flags |= R4OUTOFSPACE;
10264 			mutex_exit(&rp->r_statelock);
10265 		}
10266 		flags |= B_ERROR;
10267 		pvn_write_done(pp, flags);
10268 		/*
10269 		 * If this was not an async thread, then try again to
10270 		 * write out the pages, but this time, also destroy
10271 		 * them whether or not the write is successful.  This
10272 		 * will prevent memory from filling up with these
10273 		 * pages and destroying them is the only alternative
10274 		 * if they can't be written out.
10275 		 *
10276 		 * Don't do this if this is an async thread because
10277 		 * when the pages are unlocked in pvn_write_done,
10278 		 * some other thread could have come along, locked
10279 		 * them, and queued for an async thread.  It would be
10280 		 * possible for all of the async threads to be tied
10281 		 * up waiting to lock the pages again and they would
10282 		 * all already be locked and waiting for an async
10283 		 * thread to handle them.  Deadlock.
10284 		 */
10285 		if (!(flags & B_ASYNC)) {
10286 			error = nfs4_putpage(vp, io_off, io_len,
10287 			    B_INVAL | B_FORCE, cr);
10288 		}
10289 	} else {
10290 		if (error)
10291 			flags |= B_ERROR;
10292 		else if (rp->r_flags & R4OUTOFSPACE) {
10293 			mutex_enter(&rp->r_statelock);
10294 			rp->r_flags &= ~R4OUTOFSPACE;
10295 			mutex_exit(&rp->r_statelock);
10296 		}
10297 		pvn_write_done(pp, flags);
10298 		if (freemem < desfree)
10299 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10300 					NFS4_WRITE_NOWAIT);
10301 	}
10302 
10303 	return (error);
10304 }
10305 
10306 #ifdef DEBUG
10307 int nfs4_force_open_before_mmap = 0;
10308 #endif
10309 
10310 static int
10311 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10312 	size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr)
10313 {
10314 	struct segvn_crargs vn_a;
10315 	int error = 0;
10316 	rnode4_t *rp = VTOR4(vp);
10317 	mntinfo4_t *mi = VTOMI4(vp);
10318 
10319 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10320 		return (EIO);
10321 
10322 	if (vp->v_flag & VNOMAP)
10323 		return (ENOSYS);
10324 
10325 	if (off < 0 || (off + len) < 0)
10326 		return (ENXIO);
10327 
10328 	if (vp->v_type != VREG)
10329 		return (ENODEV);
10330 
10331 	/*
10332 	 * If the file is delegated to the client don't do anything.
10333 	 * If the file is not delegated, then validate the data cache.
10334 	 */
10335 	mutex_enter(&rp->r_statev4_lock);
10336 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10337 		mutex_exit(&rp->r_statev4_lock);
10338 		error = nfs4_validate_caches(vp, cr);
10339 		if (error)
10340 			return (error);
10341 	} else {
10342 		mutex_exit(&rp->r_statev4_lock);
10343 	}
10344 
10345 	/*
10346 	 * Check to see if the vnode is currently marked as not cachable.
10347 	 * This means portions of the file are locked (through VOP_FRLOCK).
10348 	 * In this case the map request must be refused.  We use
10349 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10350 	 */
10351 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
10352 		return (EINTR);
10353 
10354 	if (vp->v_flag & VNOCACHE) {
10355 		error = EAGAIN;
10356 		goto done;
10357 	}
10358 
10359 	/*
10360 	 * Don't allow concurrent locks and mapping if mandatory locking is
10361 	 * enabled.
10362 	 */
10363 	if (flk_has_remote_locks(vp)) {
10364 		struct vattr va;
10365 		va.va_mask = AT_MODE;
10366 		error = nfs4getattr(vp, &va, cr);
10367 		if (error != 0)
10368 			goto done;
10369 		if (MANDLOCK(vp, va.va_mode)) {
10370 			error = EAGAIN;
10371 			goto done;
10372 		}
10373 	}
10374 
10375 	/*
10376 	 * It is possible that the rnode has a lost lock request that we
10377 	 * are still trying to recover, and that the request conflicts with
10378 	 * this map request.
10379 	 *
10380 	 * An alternative approach would be for nfs4_safemap() to consider
10381 	 * queued lock requests when deciding whether to set or clear
10382 	 * VNOCACHE.  This would require the frlock code path to call
10383 	 * nfs4_safemap() after enqueing a lost request.
10384 	 */
10385 	if (nfs4_map_lost_lock_conflict(vp)) {
10386 		error = EAGAIN;
10387 		goto done;
10388 	}
10389 
10390 	as_rangelock(as);
10391 	if (!(flags & MAP_FIXED)) {
10392 		map_addr(addrp, len, off, 1, flags);
10393 		if (*addrp == NULL) {
10394 			as_rangeunlock(as);
10395 			error = ENOMEM;
10396 			goto done;
10397 		}
10398 	} else {
10399 		/*
10400 		 * User specified address - blow away any previous mappings
10401 		 */
10402 		(void) as_unmap(as, *addrp, len);
10403 	}
10404 
10405 	if (vp->v_type == VREG) {
10406 		/*
10407 		 * We need to retrieve the open stream
10408 		 */
10409 		nfs4_open_stream_t	*osp = NULL;
10410 		nfs4_open_owner_t	*oop = NULL;
10411 
10412 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10413 		if (oop != NULL) {
10414 			/* returns with 'os_sync_lock' held */
10415 			osp = find_open_stream(oop, rp);
10416 			open_owner_rele(oop);
10417 		}
10418 		if (osp == NULL) {
10419 #ifdef DEBUG
10420 			if (nfs4_force_open_before_mmap) {
10421 				error = EIO;
10422 				goto done;
10423 			}
10424 #endif
10425 			/* returns with 'os_sync_lock' held */
10426 			error = open_and_get_osp(vp, cr, &osp);
10427 			if (osp == NULL) {
10428 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10429 				    "nfs4_map: we tried to OPEN the file "
10430 				    "but again no osp, so fail with EIO"));
10431 				goto done;
10432 			}
10433 		}
10434 
10435 		if (osp->os_failed_reopen) {
10436 			mutex_exit(&osp->os_sync_lock);
10437 			open_stream_rele(osp, rp);
10438 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10439 			    "nfs4_map: os_failed_reopen set on "
10440 			    "osp %p, cr %p, rp %s", (void *)osp,
10441 			    (void *)cr, rnode4info(rp)));
10442 			error = EIO;
10443 			goto done;
10444 		}
10445 		mutex_exit(&osp->os_sync_lock);
10446 		open_stream_rele(osp, rp);
10447 	}
10448 
10449 	vn_a.vp = vp;
10450 	vn_a.offset = off;
10451 	vn_a.type = (flags & MAP_TYPE);
10452 	vn_a.prot = (uchar_t)prot;
10453 	vn_a.maxprot = (uchar_t)maxprot;
10454 	vn_a.flags = (flags & ~MAP_TYPE);
10455 	vn_a.cred = cr;
10456 	vn_a.amp = NULL;
10457 	vn_a.szc = 0;
10458 	vn_a.lgrp_mem_policy_flags = 0;
10459 
10460 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10461 	as_rangeunlock(as);
10462 
10463 done:
10464 	nfs_rw_exit(&rp->r_lkserlock);
10465 	return (error);
10466 }
10467 
10468 /*
10469  * We're most likely dealing with a kernel module that likes to READ
10470  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10471  * officially OPEN the file to create the necessary client state
10472  * for bookkeeping of os_mmap_read/write counts.
10473  *
10474  * Since VOP_MAP only passes in a pointer to the vnode rather than
10475  * a double pointer, we can't handle the case where nfs4open_otw()
10476  * returns a different vnode than the one passed into VOP_MAP (since
10477  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10478  * we return NULL and let nfs4_map() fail.  Note: the only case where
10479  * this should happen is if the file got removed and replaced with the
10480  * same name on the server (in addition to the fact that we're trying
10481  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10482  */
10483 static int
10484 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10485 {
10486 	rnode4_t		*rp, *drp;
10487 	vnode_t			*dvp, *open_vp;
10488 	char			file_name[MAXNAMELEN];
10489 	int			just_created;
10490 	nfs4_open_stream_t	*osp;
10491 	nfs4_open_owner_t	*oop;
10492 	int			error;
10493 
10494 	*ospp = NULL;
10495 	open_vp = map_vp;
10496 
10497 	rp = VTOR4(open_vp);
10498 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10499 		return (error);
10500 	drp = VTOR4(dvp);
10501 
10502 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10503 		VN_RELE(dvp);
10504 		return (EINTR);
10505 	}
10506 
10507 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10508 		nfs_rw_exit(&drp->r_rwlock);
10509 		VN_RELE(dvp);
10510 		return (error);
10511 	}
10512 
10513 	mutex_enter(&rp->r_statev4_lock);
10514 	if (rp->created_v4) {
10515 		rp->created_v4 = 0;
10516 		mutex_exit(&rp->r_statev4_lock);
10517 
10518 		dnlc_update(dvp, file_name, open_vp);
10519 		/* This is needed so we don't bump the open ref count */
10520 		just_created = 1;
10521 	} else {
10522 		mutex_exit(&rp->r_statev4_lock);
10523 		just_created = 0;
10524 	}
10525 
10526 	VN_HOLD(map_vp);
10527 
10528 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10529 		just_created);
10530 	if (error) {
10531 		nfs_rw_exit(&drp->r_rwlock);
10532 		VN_RELE(dvp);
10533 		VN_RELE(map_vp);
10534 		return (error);
10535 	}
10536 
10537 	nfs_rw_exit(&drp->r_rwlock);
10538 	VN_RELE(dvp);
10539 
10540 	/*
10541 	 * If nfs4open_otw() returned a different vnode then "undo"
10542 	 * the open and return failure to the caller.
10543 	 */
10544 	if (!VN_CMP(open_vp, map_vp)) {
10545 		nfs4_error_t e;
10546 
10547 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10548 		    "open returned a different vnode"));
10549 		/*
10550 		 * If there's an error, ignore it,
10551 		 * and let VOP_INACTIVE handle it.
10552 		 */
10553 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10554 				CLOSE_NORM, 0, 0, 0);
10555 		VN_RELE(map_vp);
10556 		return (EIO);
10557 	}
10558 
10559 	VN_RELE(map_vp);
10560 
10561 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10562 	if (!oop) {
10563 		nfs4_error_t e;
10564 
10565 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10566 		    "no open owner"));
10567 		/*
10568 		 * If there's an error, ignore it,
10569 		 * and let VOP_INACTIVE handle it.
10570 		 */
10571 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10572 				CLOSE_NORM, 0, 0, 0);
10573 		return (EIO);
10574 	}
10575 	osp = find_open_stream(oop, rp);
10576 	open_owner_rele(oop);
10577 	*ospp = osp;
10578 	return (0);
10579 }
10580 
10581 /*
10582  * Please be aware that when this function is called, the address space write
10583  * a_lock is held.  Do not put over the wire calls in this function.
10584  */
10585 /* ARGSUSED */
10586 static int
10587 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10588 	size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr)
10589 {
10590 	rnode4_t		*rp;
10591 	int			error = 0;
10592 	mntinfo4_t		*mi;
10593 
10594 	mi = VTOMI4(vp);
10595 	rp = VTOR4(vp);
10596 
10597 	if (nfs_zone() != mi->mi_zone)
10598 		return (EIO);
10599 	if (vp->v_flag & VNOMAP)
10600 		return (ENOSYS);
10601 
10602 	/*
10603 	 * Need to hold rwlock while incrementing the mapcnt so that
10604 	 * mmap'ing can be serialized with writes so that the caching
10605 	 * can be handled correctly.
10606 	 *
10607 	 * Don't need to update the open stream first, since this
10608 	 * mmap can't add any additional share access that isn't
10609 	 * already contained in the open stream (for the case where we
10610 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10611 	 * take into account os_mmap_read[write] counts).
10612 	 */
10613 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR(vp)))
10614 		return (EINTR);
10615 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10616 	nfs_rw_exit(&rp->r_rwlock);
10617 
10618 	if (vp->v_type == VREG) {
10619 		/*
10620 		 * We need to retrieve the open stream and update the counts.
10621 		 * If there is no open stream here, something is wrong.
10622 		 */
10623 		nfs4_open_stream_t	*osp = NULL;
10624 		nfs4_open_owner_t	*oop = NULL;
10625 
10626 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10627 		if (oop != NULL) {
10628 			/* returns with 'os_sync_lock' held */
10629 			osp = find_open_stream(oop, rp);
10630 			open_owner_rele(oop);
10631 		}
10632 		if (osp == NULL) {
10633 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10634 			    "nfs4_addmap: we should have an osp"
10635 			    "but we don't, so fail with EIO"));
10636 			error = EIO;
10637 			goto out;
10638 		}
10639 
10640 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10641 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10642 
10643 		/*
10644 		 * Update the map count in the open stream.
10645 		 * This is necessary in the case where we
10646 		 * open/mmap/close/, then the server reboots, and we
10647 		 * attempt to reopen.  If the mmap doesn't add share
10648 		 * access then we send an invalid reopen with
10649 		 * access = NONE.
10650 		 *
10651 		 * We need to specifically check each PROT_* so a mmap
10652 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10653 		 * read and write access.  A simple comparison of prot
10654 		 * to ~PROT_WRITE to determine read access is insufficient
10655 		 * since prot can be |= with PROT_USER, etc.
10656 		 */
10657 
10658 		/*
10659 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10660 		 */
10661 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10662 			osp->os_mmap_write += btopr(len);
10663 		if (maxprot & PROT_READ)
10664 			osp->os_mmap_read += btopr(len);
10665 		if (maxprot & PROT_EXEC)
10666 			osp->os_mmap_read += btopr(len);
10667 		/*
10668 		 * Ensure that os_mmap_read gets incremented, even if
10669 		 * maxprot were to look like PROT_NONE.
10670 		 */
10671 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10672 		    !(maxprot & PROT_EXEC))
10673 			osp->os_mmap_read += btopr(len);
10674 		osp->os_mapcnt += btopr(len);
10675 		mutex_exit(&osp->os_sync_lock);
10676 		open_stream_rele(osp, rp);
10677 	}
10678 
10679 out:
10680 	/*
10681 	 * If we got an error, then undo our
10682 	 * incrementing of 'r_mapcnt'.
10683 	 */
10684 
10685 	if (error) {
10686 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10687 		ASSERT(rp->r_mapcnt >= 0);
10688 	}
10689 	return (error);
10690 }
10691 
10692 static int
10693 nfs4_cmp(vnode_t *vp1, vnode_t *vp2)
10694 {
10695 
10696 	return (VTOR4(vp1) == VTOR4(vp2));
10697 }
10698 
10699 static int
10700 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10701 	offset_t offset, struct flk_callback *flk_cbp, cred_t *cr)
10702 {
10703 	int rc;
10704 	u_offset_t start, end;
10705 	rnode4_t *rp;
10706 	int error = 0, intr = INTR4(vp);
10707 	nfs4_error_t e;
10708 
10709 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10710 		return (EIO);
10711 
10712 	/* check for valid cmd parameter */
10713 	if (cmd != F_GETLK && cmd != F_SETLK && cmd != F_SETLKW)
10714 		return (EINVAL);
10715 
10716 	/* Verify l_type. */
10717 	switch (bfp->l_type) {
10718 	case F_RDLCK:
10719 		if (cmd != F_GETLK && !(flag & FREAD))
10720 			return (EBADF);
10721 		break;
10722 	case F_WRLCK:
10723 		if (cmd != F_GETLK && !(flag & FWRITE))
10724 			return (EBADF);
10725 		break;
10726 	case F_UNLCK:
10727 		intr = 0;
10728 		break;
10729 
10730 	default:
10731 		return (EINVAL);
10732 	}
10733 
10734 	/* check the validity of the lock range */
10735 	if (rc = flk_convert_lock_data(vp, bfp, &start, &end, offset))
10736 		return (rc);
10737 	if (rc = flk_check_lock_data(start, end, MAXEND))
10738 		return (rc);
10739 
10740 	/*
10741 	 * If the filesystem is mounted using local locking, pass the
10742 	 * request off to the local locking code.
10743 	 */
10744 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10745 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10746 			/*
10747 			 * For complete safety, we should be holding
10748 			 * r_lkserlock.  However, we can't call
10749 			 * nfs4_safelock and then fs_frlock while
10750 			 * holding r_lkserlock, so just invoke
10751 			 * nfs4_safelock and expect that this will
10752 			 * catch enough of the cases.
10753 			 */
10754 			if (!nfs4_safelock(vp, bfp, cr))
10755 				return (EAGAIN);
10756 		}
10757 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr));
10758 	}
10759 
10760 	rp = VTOR4(vp);
10761 
10762 	/*
10763 	 * Check whether the given lock request can proceed, given the
10764 	 * current file mappings.
10765 	 */
10766 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr))
10767 		return (EINTR);
10768 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10769 		if (!nfs4_safelock(vp, bfp, cr)) {
10770 			rc = EAGAIN;
10771 			goto done;
10772 		}
10773 	}
10774 
10775 	/*
10776 	 * Flush the cache after waiting for async I/O to finish.  For new
10777 	 * locks, this is so that the process gets the latest bits from the
10778 	 * server.  For unlocks, this is so that other clients see the
10779 	 * latest bits once the file has been unlocked.  If currently dirty
10780 	 * pages can't be flushed, then don't allow a lock to be set.  But
10781 	 * allow unlocks to succeed, to avoid having orphan locks on the
10782 	 * server.
10783 	 */
10784 	if (cmd != F_GETLK) {
10785 		mutex_enter(&rp->r_statelock);
10786 		while (rp->r_count > 0) {
10787 		    if (intr) {
10788 			klwp_t *lwp = ttolwp(curthread);
10789 
10790 			if (lwp != NULL)
10791 				lwp->lwp_nostop++;
10792 			if (cv_wait_sig(&rp->r_cv, &rp->r_statelock) == 0) {
10793 				if (lwp != NULL)
10794 					lwp->lwp_nostop--;
10795 				rc = EINTR;
10796 				break;
10797 			}
10798 			if (lwp != NULL)
10799 				lwp->lwp_nostop--;
10800 		    } else
10801 			cv_wait(&rp->r_cv, &rp->r_statelock);
10802 		}
10803 		mutex_exit(&rp->r_statelock);
10804 		if (rc != 0)
10805 			goto done;
10806 		error = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr);
10807 		if (error) {
10808 			if (error == ENOSPC || error == EDQUOT) {
10809 				mutex_enter(&rp->r_statelock);
10810 				if (!rp->r_error)
10811 					rp->r_error = error;
10812 				mutex_exit(&rp->r_statelock);
10813 			}
10814 			if (bfp->l_type != F_UNLCK) {
10815 				rc = ENOLCK;
10816 				goto done;
10817 			}
10818 		}
10819 	}
10820 
10821 	/*
10822 	 * Call the lock manager to do the real work of contacting
10823 	 * the server and obtaining the lock.
10824 	 */
10825 
10826 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, flag, offset,
10827 		cr, &e, NULL, NULL);
10828 	rc = e.error;
10829 
10830 	if (rc == 0)
10831 		nfs4_lockcompletion(vp, cmd);
10832 
10833 done:
10834 	nfs_rw_exit(&rp->r_lkserlock);
10835 
10836 	return (rc);
10837 }
10838 
10839 /*
10840  * Free storage space associated with the specified vnode.  The portion
10841  * to be freed is specified by bfp->l_start and bfp->l_len (already
10842  * normalized to a "whence" of 0).
10843  *
10844  * This is an experimental facility whose continued existence is not
10845  * guaranteed.  Currently, we only support the special case
10846  * of l_len == 0, meaning free to end of file.
10847  */
10848 /* ARGSUSED */
10849 static int
10850 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10851 	offset_t offset, cred_t *cr, caller_context_t *ct)
10852 {
10853 	int error;
10854 
10855 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10856 		return (EIO);
10857 	ASSERT(vp->v_type == VREG);
10858 	if (cmd != F_FREESP)
10859 		return (EINVAL);
10860 
10861 	error = convoff(vp, bfp, 0, offset);
10862 	if (!error) {
10863 		ASSERT(bfp->l_start >= 0);
10864 		if (bfp->l_len == 0) {
10865 			struct vattr va;
10866 
10867 			va.va_mask = AT_SIZE;
10868 			va.va_size = bfp->l_start;
10869 			error = nfs4setattr(vp, &va, 0, cr, NULL);
10870 		} else
10871 			error = EINVAL;
10872 	}
10873 
10874 	return (error);
10875 }
10876 
10877 /* ARGSUSED */
10878 static int
10879 nfs4_realvp(vnode_t *vp, vnode_t **vpp)
10880 {
10881 	rnode4_t *rp;
10882 	rp = VTOR4(vp);
10883 
10884 	if (vp->v_type == VREG && IS_SHADOW(vp, rp)) {
10885 		vp = RTOV4(rp);
10886 	}
10887 	*vpp = vp;
10888 	return (0);
10889 }
10890 
10891 /*
10892  * Setup and add an address space callback to do the work of the delmap call.
10893  * The callback will (and must be) deleted in the actual callback function.
10894  *
10895  * This is done in order to take care of the problem that we have with holding
10896  * the address space's a_lock for a long period of time (e.g. if the NFS server
10897  * is down).  Callbacks will be executed in the address space code while the
10898  * a_lock is not held.  Holding the address space's a_lock causes things such
10899  * as ps and fork to hang because they are trying to acquire this lock as well.
10900  */
10901 /* ARGSUSED */
10902 static int
10903 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10904 	size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr)
10905 {
10906 	int			caller_found;
10907 	int			error;
10908 	rnode4_t		*rp;
10909 	nfs4_delmap_args_t	*dmapp;
10910 	nfs4_delmapcall_t	*delmap_call;
10911 
10912 	if (vp->v_flag & VNOMAP)
10913 		return (ENOSYS);
10914 
10915 	/*
10916 	 * A process may not change zones if it has NFS pages mmap'ed
10917 	 * in, so we can't legitimately get here from the wrong zone.
10918 	 */
10919 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10920 
10921 	rp = VTOR4(vp);
10922 
10923 	/*
10924 	 * The way that the address space of this process deletes its mapping
10925 	 * of this file is via the following call chains:
10926 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10927 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10928 	 *
10929 	 * With the use of address space callbacks we are allowed to drop the
10930 	 * address space lock, a_lock, while executing the NFS operations that
10931 	 * need to go over the wire.  Returning EAGAIN to the caller of this
10932 	 * function is what drives the execution of the callback that we add
10933 	 * below.  The callback will be executed by the address space code
10934 	 * after dropping the a_lock.  When the callback is finished, since
10935 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
10936 	 * is called again on the same segment to finish the rest of the work
10937 	 * that needs to happen during unmapping.
10938 	 *
10939 	 * This action of calling back into the segment driver causes
10940 	 * nfs4_delmap() to get called again, but since the callback was
10941 	 * already executed at this point, it already did the work and there
10942 	 * is nothing left for us to do.
10943 	 *
10944 	 * To Summarize:
10945 	 * - The first time nfs4_delmap is called by the current thread is when
10946 	 * we add the caller associated with this delmap to the delmap caller
10947 	 * list, add the callback, and return EAGAIN.
10948 	 * - The second time in this call chain when nfs4_delmap is called we
10949 	 * will find this caller in the delmap caller list and realize there
10950 	 * is no more work to do thus removing this caller from the list and
10951 	 * returning the error that was set in the callback execution.
10952 	 */
10953 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
10954 	if (caller_found) {
10955 		/*
10956 		 * 'error' is from the actual delmap operations.  To avoid
10957 		 * hangs, we need to handle the return of EAGAIN differently
10958 		 * since this is what drives the callback execution.
10959 		 * In this case, we don't want to return EAGAIN and do the
10960 		 * callback execution because there are none to execute.
10961 		 */
10962 		if (error == EAGAIN)
10963 			return (0);
10964 		else
10965 			return (error);
10966 	}
10967 
10968 	/* current caller was not in the list */
10969 	delmap_call = nfs4_init_delmapcall();
10970 
10971 	mutex_enter(&rp->r_statelock);
10972 	list_insert_tail(&rp->r_indelmap, delmap_call);
10973 	mutex_exit(&rp->r_statelock);
10974 
10975 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
10976 
10977 	dmapp->vp = vp;
10978 	dmapp->off = off;
10979 	dmapp->addr = addr;
10980 	dmapp->len = len;
10981 	dmapp->prot = prot;
10982 	dmapp->maxprot = maxprot;
10983 	dmapp->flags = flags;
10984 	dmapp->cr = cr;
10985 	dmapp->caller = delmap_call;
10986 
10987 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
10988 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
10989 
10990 	return (error ? error : EAGAIN);
10991 }
10992 
10993 static nfs4_delmapcall_t *
10994 nfs4_init_delmapcall()
10995 {
10996 	nfs4_delmapcall_t	*delmap_call;
10997 
10998 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
10999 	delmap_call->call_id = curthread;
11000 	delmap_call->error = 0;
11001 
11002 	return (delmap_call);
11003 }
11004 
11005 static void
11006 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11007 {
11008 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11009 }
11010 
11011 /*
11012  * Searches for the current delmap caller (based on curthread) in the list of
11013  * callers.  If it is found, we remove it and free the delmap caller.
11014  * Returns:
11015  *      0 if the caller wasn't found
11016  *      1 if the caller was found, removed and freed.  *errp will be set
11017  *	to what the result of the delmap was.
11018  */
11019 static int
11020 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11021 {
11022 	nfs4_delmapcall_t	*delmap_call;
11023 
11024 	/*
11025 	 * If the list doesn't exist yet, we create it and return
11026 	 * that the caller wasn't found.  No list = no callers.
11027 	 */
11028 	mutex_enter(&rp->r_statelock);
11029 	if (!(rp->r_flags & R4DELMAPLIST)) {
11030 		/* The list does not exist */
11031 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11032 		    offsetof(nfs4_delmapcall_t, call_node));
11033 		rp->r_flags |= R4DELMAPLIST;
11034 		mutex_exit(&rp->r_statelock);
11035 		return (0);
11036 	} else {
11037 		/* The list exists so search it */
11038 		for (delmap_call = list_head(&rp->r_indelmap);
11039 		    delmap_call != NULL;
11040 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11041 			if (delmap_call->call_id == curthread) {
11042 				/* current caller is in the list */
11043 				*errp = delmap_call->error;
11044 				list_remove(&rp->r_indelmap, delmap_call);
11045 				mutex_exit(&rp->r_statelock);
11046 				nfs4_free_delmapcall(delmap_call);
11047 				return (1);
11048 			}
11049 		}
11050 	}
11051 	mutex_exit(&rp->r_statelock);
11052 	return (0);
11053 }
11054 
11055 /*
11056  * Remove some pages from an mmap'd vnode.  Just update the
11057  * count of pages.  If doing close-to-open, then flush and
11058  * commit all of the pages associated with this file.
11059  * Otherwise, start an asynchronous page flush to write out
11060  * any dirty pages.  This will also associate a credential
11061  * with the rnode which can be used to write the pages.
11062  */
11063 /* ARGSUSED */
11064 static void
11065 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11066 {
11067 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11068 	rnode4_t		*rp;
11069 	mntinfo4_t		*mi;
11070 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11071 
11072 	rp = VTOR4(dmapp->vp);
11073 	mi = VTOMI4(dmapp->vp);
11074 
11075 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11076 	ASSERT(rp->r_mapcnt >= 0);
11077 
11078 	/*
11079 	 * Initiate a page flush and potential commit if there are
11080 	 * pages, the file system was not mounted readonly, the segment
11081 	 * was mapped shared, and the pages themselves were writeable.
11082 	 */
11083 	if (nfs4_has_pages(dmapp->vp) &&
11084 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11085 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11086 		mutex_enter(&rp->r_statelock);
11087 		rp->r_flags |= R4DIRTY;
11088 		mutex_exit(&rp->r_statelock);
11089 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11090 		    dmapp->len, dmapp->cr);
11091 		if (!e.error) {
11092 			mutex_enter(&rp->r_statelock);
11093 			e.error = rp->r_error;
11094 			rp->r_error = 0;
11095 			mutex_exit(&rp->r_statelock);
11096 		}
11097 	} else
11098 		e.error = 0;
11099 
11100 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11101 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11102 		    B_INVAL, dmapp->cr);
11103 
11104 	if (e.error) {
11105 		e.stat = puterrno4(e.error);
11106 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11107 			OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11108 		dmapp->caller->error = e.error;
11109 	}
11110 
11111 	/* Check to see if we need to close the file */
11112 
11113 	if (dmapp->vp->v_type == VREG) {
11114 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11115 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11116 
11117 		if (e.error != 0 || e.stat != NFS4_OK) {
11118 			/*
11119 			 * Since it is possible that e.error == 0 and
11120 			 * e.stat != NFS4_OK (and vice versa),
11121 			 * we do the proper checking in order to get both
11122 			 * e.error and e.stat reporting the correct info.
11123 			 */
11124 			if (e.stat == NFS4_OK)
11125 				e.stat = puterrno4(e.error);
11126 			if (e.error == 0)
11127 				e.error = geterrno4(e.stat);
11128 
11129 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11130 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11131 			dmapp->caller->error = e.error;
11132 		}
11133 	}
11134 
11135 	(void) as_delete_callback(as, arg);
11136 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11137 }
11138 
11139 
11140 static uint_t
11141 fattr4_maxfilesize_to_bits(uint64_t ll)
11142 {
11143 	uint_t l = 1;
11144 
11145 	if (ll == 0) {
11146 		return (0);
11147 	}
11148 
11149 	if (ll & 0xffffffff00000000) {
11150 		l += 32; ll >>= 32;
11151 	}
11152 	if (ll & 0xffff0000) {
11153 		l += 16; ll >>= 16;
11154 	}
11155 	if (ll & 0xff00) {
11156 		l += 8; ll >>= 8;
11157 	}
11158 	if (ll & 0xf0) {
11159 		l += 4; ll >>= 4;
11160 	}
11161 	if (ll & 0xc) {
11162 		l += 2; ll >>= 2;
11163 	}
11164 	if (ll & 0x2) {
11165 		l += 1;
11166 	}
11167 	return (l);
11168 }
11169 
11170 static int
11171 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr)
11172 {
11173 	int error;
11174 	hrtime_t t;
11175 	rnode4_t *rp;
11176 	nfs4_ga_res_t gar;
11177 	nfs4_ga_ext_res_t ger;
11178 
11179 	gar.n4g_ext_res = &ger;
11180 
11181 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11182 		return (EIO);
11183 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11184 		*valp = MAXPATHLEN;
11185 		return (0);
11186 	}
11187 	if (cmd == _PC_ACL_ENABLED) {
11188 		*valp = _ACL_ACE_ENABLED;
11189 		return (0);
11190 	}
11191 
11192 	rp = VTOR4(vp);
11193 	if (cmd == _PC_XATTR_EXISTS) {
11194 		/*
11195 		 * Eventually should attempt small client readdir before
11196 		 * going otw with GETATTR(FATTR4_NAMED_ATTR).  For now
11197 		 * just drive the OTW getattr.  This is required because
11198 		 * _PC_XATTR_EXISTS can only return true if attributes
11199 		 * exist -- simply checking for existance of the attrdir
11200 		 * is not sufficient.
11201 		 *
11202 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11203 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11204 		 * and we don't have any way to update the "base" object's
11205 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11206 		 * could help out.
11207 		 */
11208 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11209 		    rp->r_xattr_dir == NULL) {
11210 			*valp = rp->r_pathconf.pc4_xattr_exists;
11211 			return (0);
11212 		}
11213 	} else {  /* OLD CODE */
11214 		if (ATTRCACHE4_VALID(vp)) {
11215 			mutex_enter(&rp->r_statelock);
11216 			if (rp->r_pathconf.pc4_cache_valid) {
11217 				error = 0;
11218 				switch (cmd) {
11219 				case _PC_FILESIZEBITS:
11220 					*valp =
11221 					rp->r_pathconf.pc4_filesizebits;
11222 					break;
11223 				case _PC_LINK_MAX:
11224 					*valp =
11225 					rp->r_pathconf.pc4_link_max;
11226 					break;
11227 				case _PC_NAME_MAX:
11228 					*valp =
11229 					rp->r_pathconf.pc4_name_max;
11230 					break;
11231 				case _PC_CHOWN_RESTRICTED:
11232 					*valp =
11233 					rp->r_pathconf.pc4_chown_restricted;
11234 					break;
11235 				case _PC_NO_TRUNC:
11236 					*valp =
11237 					rp->r_pathconf.pc4_no_trunc;
11238 					break;
11239 				default:
11240 					error = EINVAL;
11241 					break;
11242 				}
11243 				mutex_exit(&rp->r_statelock);
11244 #ifdef DEBUG
11245 				nfs4_pathconf_cache_hits++;
11246 #endif
11247 				return (error);
11248 			}
11249 			mutex_exit(&rp->r_statelock);
11250 		}
11251 	}
11252 #ifdef DEBUG
11253 	nfs4_pathconf_cache_misses++;
11254 #endif
11255 
11256 	t = gethrtime();
11257 
11258 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11259 
11260 	if (error) {
11261 		mutex_enter(&rp->r_statelock);
11262 		rp->r_pathconf.pc4_cache_valid = FALSE;
11263 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11264 		mutex_exit(&rp->r_statelock);
11265 		return (error);
11266 	}
11267 
11268 	/* interpret the max filesize */
11269 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11270 		fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11271 
11272 	/* Store the attributes we just received */
11273 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11274 
11275 	switch (cmd) {
11276 	case _PC_FILESIZEBITS:
11277 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11278 		break;
11279 	case _PC_LINK_MAX:
11280 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11281 		break;
11282 	case _PC_NAME_MAX:
11283 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11284 		break;
11285 	case _PC_CHOWN_RESTRICTED:
11286 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11287 		break;
11288 	case _PC_NO_TRUNC:
11289 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11290 		break;
11291 	case _PC_XATTR_EXISTS:
11292 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists;
11293 		break;
11294 	default:
11295 		return (EINVAL);
11296 	}
11297 
11298 	return (0);
11299 }
11300 
11301 /*
11302  * Called by async thread to do synchronous pageio. Do the i/o, wait
11303  * for it to complete, and cleanup the page list when done.
11304  */
11305 static int
11306 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11307 	int flags, cred_t *cr)
11308 {
11309 	int error;
11310 
11311 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11312 
11313 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11314 	if (flags & B_READ)
11315 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11316 	else
11317 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11318 	return (error);
11319 }
11320 
11321 static int
11322 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11323 	int flags, cred_t *cr)
11324 {
11325 	int error;
11326 	rnode4_t *rp;
11327 
11328 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11329 		return (EIO);
11330 
11331 	if (pp == NULL)
11332 		return (EINVAL);
11333 
11334 	rp = VTOR4(vp);
11335 	mutex_enter(&rp->r_statelock);
11336 	rp->r_count++;
11337 	mutex_exit(&rp->r_statelock);
11338 
11339 	if (flags & B_ASYNC) {
11340 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11341 		    nfs4_sync_pageio);
11342 	} else
11343 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11344 	mutex_enter(&rp->r_statelock);
11345 	rp->r_count--;
11346 	cv_broadcast(&rp->r_cv);
11347 	mutex_exit(&rp->r_statelock);
11348 	return (error);
11349 }
11350 
11351 static void
11352 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr)
11353 {
11354 	int error;
11355 	rnode4_t *rp;
11356 	page_t *plist;
11357 	page_t *pptr;
11358 	offset3 offset;
11359 	count3 len;
11360 	k_sigset_t smask;
11361 
11362 	/*
11363 	 * We should get called with fl equal to either B_FREE or
11364 	 * B_INVAL.  Any other value is illegal.
11365 	 *
11366 	 * The page that we are either supposed to free or destroy
11367 	 * should be exclusive locked and its io lock should not
11368 	 * be held.
11369 	 */
11370 	ASSERT(fl == B_FREE || fl == B_INVAL);
11371 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11372 
11373 	rp = VTOR4(vp);
11374 
11375 	/*
11376 	 * If the page doesn't need to be committed or we shouldn't
11377 	 * even bother attempting to commit it, then just make sure
11378 	 * that the p_fsdata byte is clear and then either free or
11379 	 * destroy the page as appropriate.
11380 	 */
11381 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11382 		pp->p_fsdata = C_NOCOMMIT;
11383 		if (fl == B_FREE)
11384 			page_free(pp, dn);
11385 		else
11386 			page_destroy(pp, dn);
11387 		return;
11388 	}
11389 
11390 	/*
11391 	 * If there is a page invalidation operation going on, then
11392 	 * if this is one of the pages being destroyed, then just
11393 	 * clear the p_fsdata byte and then either free or destroy
11394 	 * the page as appropriate.
11395 	 */
11396 	mutex_enter(&rp->r_statelock);
11397 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11398 		mutex_exit(&rp->r_statelock);
11399 		pp->p_fsdata = C_NOCOMMIT;
11400 		if (fl == B_FREE)
11401 			page_free(pp, dn);
11402 		else
11403 			page_destroy(pp, dn);
11404 		return;
11405 	}
11406 
11407 	/*
11408 	 * If we are freeing this page and someone else is already
11409 	 * waiting to do a commit, then just unlock the page and
11410 	 * return.  That other thread will take care of commiting
11411 	 * this page.  The page can be freed sometime after the
11412 	 * commit has finished.  Otherwise, if the page is marked
11413 	 * as delay commit, then we may be getting called from
11414 	 * pvn_write_done, one page at a time.   This could result
11415 	 * in one commit per page, so we end up doing lots of small
11416 	 * commits instead of fewer larger commits.  This is bad,
11417 	 * we want do as few commits as possible.
11418 	 */
11419 	if (fl == B_FREE) {
11420 		if (rp->r_flags & R4COMMITWAIT) {
11421 			page_unlock(pp);
11422 			mutex_exit(&rp->r_statelock);
11423 			return;
11424 		}
11425 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11426 			pp->p_fsdata = C_COMMIT;
11427 			page_unlock(pp);
11428 			mutex_exit(&rp->r_statelock);
11429 			return;
11430 		}
11431 	}
11432 
11433 	/*
11434 	 * Check to see if there is a signal which would prevent an
11435 	 * attempt to commit the pages from being successful.  If so,
11436 	 * then don't bother with all of the work to gather pages and
11437 	 * generate the unsuccessful RPC.  Just return from here and
11438 	 * let the page be committed at some later time.
11439 	 */
11440 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11441 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11442 		sigunintr(&smask);
11443 		page_unlock(pp);
11444 		mutex_exit(&rp->r_statelock);
11445 		return;
11446 	}
11447 	sigunintr(&smask);
11448 
11449 	/*
11450 	 * We are starting to need to commit pages, so let's try
11451 	 * to commit as many as possible at once to reduce the
11452 	 * overhead.
11453 	 *
11454 	 * Set the `commit inprogress' state bit.  We must
11455 	 * first wait until any current one finishes.  Then
11456 	 * we initialize the c_pages list with this page.
11457 	 */
11458 	while (rp->r_flags & R4COMMIT) {
11459 		rp->r_flags |= R4COMMITWAIT;
11460 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11461 		rp->r_flags &= ~R4COMMITWAIT;
11462 	}
11463 	rp->r_flags |= R4COMMIT;
11464 	mutex_exit(&rp->r_statelock);
11465 	ASSERT(rp->r_commit.c_pages == NULL);
11466 	rp->r_commit.c_pages = pp;
11467 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11468 	rp->r_commit.c_commlen = PAGESIZE;
11469 
11470 	/*
11471 	 * Gather together all other pages which can be committed.
11472 	 * They will all be chained off r_commit.c_pages.
11473 	 */
11474 	nfs4_get_commit(vp);
11475 
11476 	/*
11477 	 * Clear the `commit inprogress' status and disconnect
11478 	 * the list of pages to be committed from the rnode.
11479 	 * At this same time, we also save the starting offset
11480 	 * and length of data to be committed on the server.
11481 	 */
11482 	plist = rp->r_commit.c_pages;
11483 	rp->r_commit.c_pages = NULL;
11484 	offset = rp->r_commit.c_commbase;
11485 	len = rp->r_commit.c_commlen;
11486 	mutex_enter(&rp->r_statelock);
11487 	rp->r_flags &= ~R4COMMIT;
11488 	cv_broadcast(&rp->r_commit.c_cv);
11489 	mutex_exit(&rp->r_statelock);
11490 
11491 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11492 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11493 		nfs4_async_commit(vp, plist, offset, len,
11494 		    cr, do_nfs4_async_commit);
11495 		return;
11496 	}
11497 
11498 	/*
11499 	 * Actually generate the COMMIT op over the wire operation.
11500 	 */
11501 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11502 
11503 	/*
11504 	 * If we got an error during the commit, just unlock all
11505 	 * of the pages.  The pages will get retransmitted to the
11506 	 * server during a putpage operation.
11507 	 */
11508 	if (error) {
11509 		while (plist != NULL) {
11510 			pptr = plist;
11511 			page_sub(&plist, pptr);
11512 			page_unlock(pptr);
11513 		}
11514 		return;
11515 	}
11516 
11517 	/*
11518 	 * We've tried as hard as we can to commit the data to stable
11519 	 * storage on the server.  We just unlock the rest of the pages
11520 	 * and clear the commit required state.  They will be put
11521 	 * onto the tail of the cachelist if they are nolonger
11522 	 * mapped.
11523 	 */
11524 	while (plist != pp) {
11525 		pptr = plist;
11526 		page_sub(&plist, pptr);
11527 		pptr->p_fsdata = C_NOCOMMIT;
11528 		page_unlock(pptr);
11529 	}
11530 
11531 	/*
11532 	 * It is possible that nfs4_commit didn't return error but
11533 	 * some other thread has modified the page we are going
11534 	 * to free/destroy.
11535 	 *    In this case we need to rewrite the page. Do an explicit check
11536 	 * before attempting to free/destroy the page. If modified, needs to
11537 	 * be rewritten so unlock the page and return.
11538 	 */
11539 	if (hat_ismod(pp)) {
11540 		pp->p_fsdata = C_NOCOMMIT;
11541 		page_unlock(pp);
11542 		return;
11543 	}
11544 
11545 	/*
11546 	 * Now, as appropriate, either free or destroy the page
11547 	 * that we were called with.
11548 	 */
11549 	pp->p_fsdata = C_NOCOMMIT;
11550 	if (fl == B_FREE)
11551 		page_free(pp, dn);
11552 	else
11553 		page_destroy(pp, dn);
11554 }
11555 
11556 /*
11557  * Commit requires that the current fh be the file written to.
11558  * The compound op structure is:
11559  *      PUTFH(file), COMMIT
11560  */
11561 static int
11562 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11563 {
11564 	COMPOUND4args_clnt args;
11565 	COMPOUND4res_clnt res;
11566 	COMMIT4res *cm_res;
11567 	nfs_argop4 argop[2];
11568 	nfs_resop4 *resop;
11569 	int doqueue;
11570 	mntinfo4_t *mi;
11571 	rnode4_t *rp;
11572 	cred_t *cred_otw = NULL;
11573 	bool_t needrecov = FALSE;
11574 	nfs4_recov_state_t recov_state;
11575 	nfs4_open_stream_t *osp = NULL;
11576 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11577 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11578 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11579 
11580 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11581 
11582 	rp = VTOR4(vp);
11583 
11584 	mi = VTOMI4(vp);
11585 	recov_state.rs_flags = 0;
11586 	recov_state.rs_num_retry_despite_err = 0;
11587 get_commit_cred:
11588 	/*
11589 	 * Releases the osp, if a valid open stream is provided.
11590 	 * Puts a hold on the cred_otw and the new osp (if found).
11591 	 */
11592 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11593 			&first_time, &last_time);
11594 	args.ctag = TAG_COMMIT;
11595 recov_retry:
11596 	/*
11597 	 * Commit ops: putfh file; commit
11598 	 */
11599 	args.array_len = 2;
11600 	args.array = argop;
11601 
11602 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11603 			    &recov_state, NULL);
11604 	if (e.error) {
11605 		crfree(cred_otw);
11606 		if (osp != NULL)
11607 			open_stream_rele(osp, rp);
11608 		return (e.error);
11609 	}
11610 
11611 	/* putfh directory */
11612 	argop[0].argop = OP_CPUTFH;
11613 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11614 
11615 	/* commit */
11616 	argop[1].argop = OP_COMMIT;
11617 	argop[1].nfs_argop4_u.opcommit.offset = offset;
11618 	argop[1].nfs_argop4_u.opcommit.count = count;
11619 
11620 	doqueue = 1;
11621 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
11622 
11623 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
11624 	if (!needrecov && e.error) {
11625 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
11626 			needrecov);
11627 		crfree(cred_otw);
11628 		if (e.error == EACCES && last_time == FALSE)
11629 			goto get_commit_cred;
11630 		if (osp != NULL)
11631 			open_stream_rele(osp, rp);
11632 		return (e.error);
11633 	}
11634 
11635 	if (needrecov) {
11636 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
11637 		    NULL, OP_COMMIT, NULL) == FALSE) {
11638 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11639 				&recov_state, needrecov);
11640 			if (!e.error)
11641 				(void) xdr_free(xdr_COMPOUND4res_clnt,
11642 								(caddr_t)&res);
11643 			goto recov_retry;
11644 		}
11645 		if (e.error) {
11646 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11647 				&recov_state, needrecov);
11648 			crfree(cred_otw);
11649 			if (osp != NULL)
11650 				open_stream_rele(osp, rp);
11651 			return (e.error);
11652 		}
11653 		/* fall through for res.status case */
11654 	}
11655 
11656 	if (res.status) {
11657 		e.error = geterrno4(res.status);
11658 		if (e.error == EACCES && last_time == FALSE) {
11659 			crfree(cred_otw);
11660 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11661 				&recov_state, needrecov);
11662 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11663 			goto get_commit_cred;
11664 		}
11665 		/*
11666 		 * Can't do a nfs4_purge_stale_fh here because this
11667 		 * can cause a deadlock.  nfs4_commit can
11668 		 * be called from nfs4_dispose which can be called
11669 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
11670 		 * can call back to pvn_vplist_dirty.
11671 		 */
11672 		if (e.error == ESTALE) {
11673 			mutex_enter(&rp->r_statelock);
11674 			rp->r_flags |= R4STALE;
11675 			if (!rp->r_error)
11676 				rp->r_error = e.error;
11677 			mutex_exit(&rp->r_statelock);
11678 			PURGE_ATTRCACHE4(vp);
11679 		} else {
11680 			mutex_enter(&rp->r_statelock);
11681 			if (!rp->r_error)
11682 				rp->r_error = e.error;
11683 			mutex_exit(&rp->r_statelock);
11684 		}
11685 	} else {
11686 		ASSERT(rp->r_flags & R4HAVEVERF);
11687 		resop = &res.array[1];	/* commit res */
11688 		cm_res = &resop->nfs_resop4_u.opcommit;
11689 		mutex_enter(&rp->r_statelock);
11690 		if (cm_res->writeverf == rp->r_writeverf) {
11691 			mutex_exit(&rp->r_statelock);
11692 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11693 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11694 				&recov_state, needrecov);
11695 			crfree(cred_otw);
11696 			if (osp != NULL)
11697 				open_stream_rele(osp, rp);
11698 			return (0);
11699 		}
11700 		nfs4_set_mod(vp);
11701 		rp->r_writeverf = cm_res->writeverf;
11702 		mutex_exit(&rp->r_statelock);
11703 		e.error = NFS_VERF_MISMATCH;
11704 	}
11705 
11706 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11707 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
11708 	crfree(cred_otw);
11709 	if (osp != NULL)
11710 		open_stream_rele(osp, rp);
11711 
11712 	return (e.error);
11713 }
11714 
11715 static void
11716 nfs4_set_mod(vnode_t *vp)
11717 {
11718 	page_t *pp;
11719 	kmutex_t *vphm;
11720 	rnode4_t *rp;
11721 
11722 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11723 
11724 	/* make sure we're looking at the master vnode, not a shadow */
11725 
11726 	rp = VTOR4(vp);
11727 	if (IS_SHADOW(vp, rp))
11728 		vp = RTOV4(rp);
11729 
11730 	vphm = page_vnode_mutex(vp);
11731 	mutex_enter(vphm);
11732 	/*
11733 	 * If there are no pages associated with this vnode, then
11734 	 * just return.
11735 	 */
11736 	if ((pp = vp->v_pages) == NULL) {
11737 		mutex_exit(vphm);
11738 		return;
11739 	}
11740 
11741 	do {
11742 		if (pp->p_fsdata != C_NOCOMMIT) {
11743 			hat_setmod(pp);
11744 			pp->p_fsdata = C_NOCOMMIT;
11745 		}
11746 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11747 	mutex_exit(vphm);
11748 }
11749 
11750 /*
11751  * This function is used to gather a page list of the pages which
11752  * can be committed on the server.
11753  *
11754  * The calling thread must have set R4COMMIT.  This bit is used to
11755  * serialize access to the commit structure in the rnode.  As long
11756  * as the thread has set R4COMMIT, then it can manipulate the commit
11757  * structure without requiring any other locks.
11758  *
11759  * When this function is called from nfs4_dispose() the page passed
11760  * into nfs4_dispose() will be SE_EXCL locked, and so this function
11761  * will skip it. This is not a problem since we initially add the
11762  * page to the r_commit page list.
11763  *
11764  */
11765 static void
11766 nfs4_get_commit(vnode_t *vp)
11767 {
11768 	rnode4_t *rp;
11769 	page_t *pp;
11770 	kmutex_t *vphm;
11771 
11772 	rp = VTOR4(vp);
11773 
11774 	ASSERT(rp->r_flags & R4COMMIT);
11775 
11776 	/* make sure we're looking at the master vnode, not a shadow */
11777 
11778 	if (IS_SHADOW(vp, rp))
11779 		vp = RTOV4(rp);
11780 
11781 	vphm = page_vnode_mutex(vp);
11782 	mutex_enter(vphm);
11783 
11784 	/*
11785 	 * If there are no pages associated with this vnode, then
11786 	 * just return.
11787 	 */
11788 	if ((pp = vp->v_pages) == NULL) {
11789 		mutex_exit(vphm);
11790 		return;
11791 	}
11792 
11793 	/*
11794 	 * Step through all of the pages associated with this vnode
11795 	 * looking for pages which need to be committed.
11796 	 */
11797 	do {
11798 		/*
11799 		 * First short-cut everything (without the page_lock)
11800 		 * and see if this page does not need to be committed
11801 		 * or is modified if so then we'll just skip it.
11802 		 */
11803 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
11804 			continue;
11805 
11806 		/*
11807 		 * Attempt to lock the page.  If we can't, then
11808 		 * someone else is messing with it or we have been
11809 		 * called from nfs4_dispose and this is the page that
11810 		 * nfs4_dispose was called with.. anyway just skip it.
11811 		 */
11812 		if (!page_trylock(pp, SE_EXCL))
11813 			continue;
11814 
11815 		/*
11816 		 * Lets check again now that we have the page lock.
11817 		 */
11818 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11819 			page_unlock(pp);
11820 			continue;
11821 		}
11822 
11823 		/* this had better not be a free page */
11824 		ASSERT(PP_ISFREE(pp) == 0);
11825 
11826 		/*
11827 		 * The page needs to be committed and we locked it.
11828 		 * Update the base and length parameters and add it
11829 		 * to r_pages.
11830 		 */
11831 		if (rp->r_commit.c_pages == NULL) {
11832 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11833 			rp->r_commit.c_commlen = PAGESIZE;
11834 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
11835 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
11836 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
11837 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11838 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
11839 			    <= pp->p_offset) {
11840 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11841 			    rp->r_commit.c_commbase + PAGESIZE;
11842 		}
11843 		page_add(&rp->r_commit.c_pages, pp);
11844 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11845 
11846 	mutex_exit(vphm);
11847 }
11848 
11849 /*
11850  * This routine is used to gather together a page list of the pages
11851  * which are to be committed on the server.  This routine must not
11852  * be called if the calling thread holds any locked pages.
11853  *
11854  * The calling thread must have set R4COMMIT.  This bit is used to
11855  * serialize access to the commit structure in the rnode.  As long
11856  * as the thread has set R4COMMIT, then it can manipulate the commit
11857  * structure without requiring any other locks.
11858  */
11859 static void
11860 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
11861 {
11862 
11863 	rnode4_t *rp;
11864 	page_t *pp;
11865 	u_offset_t end;
11866 	u_offset_t off;
11867 	ASSERT(len != 0);
11868 	rp = VTOR4(vp);
11869 	ASSERT(rp->r_flags & R4COMMIT);
11870 
11871 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11872 
11873 	/* make sure we're looking at the master vnode, not a shadow */
11874 
11875 	if (IS_SHADOW(vp, rp))
11876 		vp = RTOV4(rp);
11877 
11878 	/*
11879 	 * If there are no pages associated with this vnode, then
11880 	 * just return.
11881 	 */
11882 	if ((pp = vp->v_pages) == NULL)
11883 		return;
11884 	/*
11885 	 * Calculate the ending offset.
11886 	 */
11887 	end = soff + len;
11888 	for (off = soff; off < end; off += PAGESIZE) {
11889 		/*
11890 		 * Lookup each page by vp, offset.
11891 		 */
11892 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
11893 			continue;
11894 		/*
11895 		 * If this page does not need to be committed or is
11896 		 * modified, then just skip it.
11897 		 */
11898 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11899 			page_unlock(pp);
11900 			continue;
11901 		}
11902 
11903 		ASSERT(PP_ISFREE(pp) == 0);
11904 		/*
11905 		 * The page needs to be committed and we locked it.
11906 		 * Update the base and length parameters and add it
11907 		 * to r_pages.
11908 		 */
11909 		if (rp->r_commit.c_pages == NULL) {
11910 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11911 			rp->r_commit.c_commlen = PAGESIZE;
11912 		} else {
11913 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11914 			rp->r_commit.c_commbase + PAGESIZE;
11915 		}
11916 		page_add(&rp->r_commit.c_pages, pp);
11917 	}
11918 }
11919 
11920 /*
11921  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
11922  * Flushes and commits data to the server.
11923  */
11924 static int
11925 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
11926 {
11927 	int error;
11928 	verifier4 write_verf;
11929 	rnode4_t *rp = VTOR4(vp);
11930 
11931 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11932 
11933 	/*
11934 	 * Flush the data portion of the file and then commit any
11935 	 * portions which need to be committed.  This may need to
11936 	 * be done twice if the server has changed state since
11937 	 * data was last written.  The data will need to be
11938 	 * rewritten to the server and then a new commit done.
11939 	 *
11940 	 * In fact, this may need to be done several times if the
11941 	 * server is having problems and crashing while we are
11942 	 * attempting to do this.
11943 	 */
11944 
11945 top:
11946 	/*
11947 	 * Do a flush based on the poff and plen arguments.  This
11948 	 * will synchronously write out any modified pages in the
11949 	 * range specified by (poff, plen). This starts all of the
11950 	 * i/o operations which will be waited for in the next
11951 	 * call to nfs4_putpage
11952 	 */
11953 
11954 	mutex_enter(&rp->r_statelock);
11955 	write_verf = rp->r_writeverf;
11956 	mutex_exit(&rp->r_statelock);
11957 
11958 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr);
11959 	if (error == EAGAIN)
11960 		error = 0;
11961 
11962 	/*
11963 	 * Do a flush based on the poff and plen arguments.  This
11964 	 * will synchronously write out any modified pages in the
11965 	 * range specified by (poff, plen) and wait until all of
11966 	 * the asynchronous i/o's in that range are done as well.
11967 	 */
11968 	if (!error)
11969 		error = nfs4_putpage(vp, poff, plen, 0, cr);
11970 
11971 	if (error)
11972 		return (error);
11973 
11974 	mutex_enter(&rp->r_statelock);
11975 	if (rp->r_writeverf != write_verf) {
11976 		mutex_exit(&rp->r_statelock);
11977 		goto top;
11978 	}
11979 	mutex_exit(&rp->r_statelock);
11980 
11981 	/*
11982 	 * Now commit any pages which might need to be committed.
11983 	 * If the error, NFS_VERF_MISMATCH, is returned, then
11984 	 * start over with the flush operation.
11985 	 */
11986 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
11987 
11988 	if (error == NFS_VERF_MISMATCH)
11989 		goto top;
11990 
11991 	return (error);
11992 }
11993 
11994 /*
11995  * nfs4_commit_vp()  will wait for other pending commits and
11996  * will either commit the whole file or a range, plen dictates
11997  * if we commit whole file. a value of zero indicates the whole
11998  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
11999  */
12000 static int
12001 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12002 		cred_t *cr, int wait_on_writes)
12003 {
12004 	rnode4_t *rp;
12005 	page_t *plist;
12006 	offset3 offset;
12007 	count3 len;
12008 
12009 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12010 
12011 	rp = VTOR4(vp);
12012 
12013 	/*
12014 	 *  before we gather commitable pages make
12015 	 *  sure there are no outstanding async writes
12016 	 */
12017 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12018 		mutex_enter(&rp->r_statelock);
12019 		while (rp->r_count > 0) {
12020 			cv_wait(&rp->r_cv, &rp->r_statelock);
12021 		}
12022 		mutex_exit(&rp->r_statelock);
12023 	}
12024 
12025 	/*
12026 	 * Set the `commit inprogress' state bit.  We must
12027 	 * first wait until any current one finishes.
12028 	 */
12029 	mutex_enter(&rp->r_statelock);
12030 	while (rp->r_flags & R4COMMIT) {
12031 		rp->r_flags |= R4COMMITWAIT;
12032 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12033 		rp->r_flags &= ~R4COMMITWAIT;
12034 	}
12035 	rp->r_flags |= R4COMMIT;
12036 	mutex_exit(&rp->r_statelock);
12037 
12038 	/*
12039 	 * Gather all of the pages which need to be
12040 	 * committed.
12041 	 */
12042 	if (plen == 0)
12043 		nfs4_get_commit(vp);
12044 	else
12045 		nfs4_get_commit_range(vp, poff, plen);
12046 
12047 	/*
12048 	 * Clear the `commit inprogress' bit and disconnect the
12049 	 * page list which was gathered by nfs4_get_commit.
12050 	 */
12051 	plist = rp->r_commit.c_pages;
12052 	rp->r_commit.c_pages = NULL;
12053 	offset = rp->r_commit.c_commbase;
12054 	len = rp->r_commit.c_commlen;
12055 	mutex_enter(&rp->r_statelock);
12056 	rp->r_flags &= ~R4COMMIT;
12057 	cv_broadcast(&rp->r_commit.c_cv);
12058 	mutex_exit(&rp->r_statelock);
12059 
12060 	/*
12061 	 * If any pages need to be committed, commit them and
12062 	 * then unlock them so that they can be freed some
12063 	 * time later.
12064 	 */
12065 	if (plist == NULL)
12066 		return (0);
12067 
12068 	/*
12069 	 * No error occurred during the flush portion
12070 	 * of this operation, so now attempt to commit
12071 	 * the data to stable storage on the server.
12072 	 *
12073 	 * This will unlock all of the pages on the list.
12074 	 */
12075 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12076 }
12077 
12078 static int
12079 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12080 	cred_t *cr)
12081 {
12082 	int error;
12083 	page_t *pp;
12084 
12085 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12086 
12087 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12088 
12089 	/*
12090 	 * If we got an error, then just unlock all of the pages
12091 	 * on the list.
12092 	 */
12093 	if (error) {
12094 		while (plist != NULL) {
12095 			pp = plist;
12096 			page_sub(&plist, pp);
12097 			page_unlock(pp);
12098 		}
12099 		return (error);
12100 	}
12101 	/*
12102 	 * We've tried as hard as we can to commit the data to stable
12103 	 * storage on the server.  We just unlock the pages and clear
12104 	 * the commit required state.  They will get freed later.
12105 	 */
12106 	while (plist != NULL) {
12107 		pp = plist;
12108 		page_sub(&plist, pp);
12109 		pp->p_fsdata = C_NOCOMMIT;
12110 		page_unlock(pp);
12111 	}
12112 
12113 	return (error);
12114 }
12115 
12116 static void
12117 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12118 	cred_t *cr)
12119 {
12120 
12121 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12122 }
12123 
12124 /*ARGSUSED*/
12125 static int
12126 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr)
12127 {
12128 	int		error = 0;
12129 	mntinfo4_t	*mi;
12130 	vattr_t		va;
12131 	vsecattr_t	nfsace4_vsap;
12132 
12133 	mi = VTOMI4(vp);
12134 	if (nfs_zone() != mi->mi_zone)
12135 		return (EIO);
12136 	if (mi->mi_flags & MI4_ACL) {
12137 		/* if we have a delegation, return it */
12138 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12139 			(void) nfs4delegreturn(VTOR4(vp),
12140 					NFS4_DR_REOPEN|NFS4_DR_PUSH);
12141 
12142 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12143 			NFS4_ACL_SET);
12144 		if (error) /* EINVAL */
12145 			return (error);
12146 
12147 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12148 			/*
12149 			 * These are aclent_t type entries.
12150 			 */
12151 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12152 			    vp->v_type == VDIR, FALSE);
12153 			if (error)
12154 				return (error);
12155 		} else {
12156 			/*
12157 			 * These are ace_t type entries.
12158 			 */
12159 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12160 			    FALSE);
12161 			if (error)
12162 				return (error);
12163 		}
12164 		bzero(&va, sizeof (va));
12165 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12166 		vs_ace4_destroy(&nfsace4_vsap);
12167 		return (error);
12168 	}
12169 	return (ENOSYS);
12170 }
12171 
12172 static int
12173 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr)
12174 {
12175 	int		error;
12176 	mntinfo4_t	*mi;
12177 	nfs4_ga_res_t	gar;
12178 	rnode4_t	*rp = VTOR4(vp);
12179 
12180 	mi = VTOMI4(vp);
12181 	if (nfs_zone() != mi->mi_zone)
12182 		return (EIO);
12183 
12184 	bzero(&gar, sizeof (gar));
12185 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12186 
12187 	/*
12188 	 * vsecattr->vsa_mask holds the original acl request mask.
12189 	 * This is needed when determining what to return.
12190 	 * (See: nfs4_create_getsecattr_return())
12191 	 */
12192 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12193 	if (error) /* EINVAL */
12194 		return (error);
12195 
12196 	if (mi->mi_flags & MI4_ACL) {
12197 		/*
12198 		 * Check if the data is cached and the cache is valid.  If it
12199 		 * is we don't go over the wire.
12200 		 */
12201 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12202 			mutex_enter(&rp->r_statelock);
12203 			if (rp->r_secattr != NULL) {
12204 				error = nfs4_create_getsecattr_return(
12205 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12206 				    rp->r_attr.va_gid,
12207 				    vp->v_type == VDIR);
12208 				if (!error) { /* error == 0 - Success! */
12209 					mutex_exit(&rp->r_statelock);
12210 					return (error);
12211 				}
12212 			}
12213 			mutex_exit(&rp->r_statelock);
12214 		}
12215 
12216 		/*
12217 		 * The getattr otw call will always get both the acl, in
12218 		 * the form of a list of nfsace4's, and the number of acl
12219 		 * entries; independent of the value of gar.n4g_vsa.vsa_mask.
12220 		 */
12221 		gar.n4g_va.va_mask = AT_ALL;
12222 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12223 		if (error) {
12224 			vs_ace4_destroy(&gar.n4g_vsa);
12225 			if (error == ENOTSUP || error == EOPNOTSUPP)
12226 				error = fs_fab_acl(vp, vsecattr, flag, cr);
12227 			return (error);
12228 		}
12229 
12230 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12231 			/*
12232 			 * No error was returned, but according to the response
12233 			 * bitmap, neither was an acl.
12234 			 */
12235 			vs_ace4_destroy(&gar.n4g_vsa);
12236 			error = fs_fab_acl(vp, vsecattr, flag, cr);
12237 			return (error);
12238 		}
12239 
12240 		/*
12241 		 * Update the cache with the ACL.
12242 		 */
12243 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12244 
12245 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12246 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12247 		    vp->v_type == VDIR);
12248 		vs_ace4_destroy(&gar.n4g_vsa);
12249 		if ((error) && (vsecattr->vsa_mask &
12250 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12251 		    (error != EACCES)) {
12252 			error = fs_fab_acl(vp, vsecattr, flag, cr);
12253 		}
12254 		return (error);
12255 	}
12256 	error = fs_fab_acl(vp, vsecattr, flag, cr);
12257 	return (error);
12258 }
12259 
12260 /*
12261  * The function returns:
12262  * 	- 0 (zero) if the passed in "acl_mask" is a valid request.
12263  * 	- EINVAL if the passed in "acl_mask" is an invalid request.
12264  *
12265  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12266  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12267  *
12268  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12269  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12270  * - We have a count field set without the corresponding acl field set. (e.g. -
12271  * VSA_ACECNT is set, but VSA_ACE is not)
12272  */
12273 static int
12274 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12275 {
12276 	/* Shortcut the masks that are always valid. */
12277 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12278 		return (0);
12279 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12280 		return (0);
12281 
12282 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12283 		/*
12284 		 * We can't have any VSA_ACL type stuff in the mask now.
12285 		 */
12286 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12287 		    VSA_DFACLCNT))
12288 			return (EINVAL);
12289 
12290 		if (op == NFS4_ACL_SET) {
12291 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12292 				return (EINVAL);
12293 		}
12294 	}
12295 
12296 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12297 		/*
12298 		 * We can't have any VSA_ACE type stuff in the mask now.
12299 		 */
12300 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12301 			return (EINVAL);
12302 
12303 		if (op == NFS4_ACL_SET) {
12304 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12305 				return (EINVAL);
12306 
12307 			if ((acl_mask & VSA_DFACLCNT) &&
12308 			    !(acl_mask & VSA_DFACL))
12309 				return (EINVAL);
12310 		}
12311 	}
12312 	return (0);
12313 }
12314 
12315 /*
12316  * The theory behind creating the correct getsecattr return is simply this:
12317  * "Don't return anything that the caller is not expecting to have to free."
12318  */
12319 static int
12320 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12321 	uid_t uid, gid_t gid, int isdir)
12322 {
12323 	int error = 0;
12324 	/* Save the mask since the translators modify it. */
12325 	uint_t	orig_mask = vsap->vsa_mask;
12326 
12327 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12328 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid,
12329 		    FALSE, ((orig_mask & VSA_ACE) ? FALSE : TRUE));
12330 
12331 		if (error)
12332 			return (error);
12333 
12334 		/*
12335 		 * If the caller only asked for the ace count (VSA_ACECNT)
12336 		 * don't give them the full acl (VSA_ACE), free it.
12337 		 */
12338 		if (!orig_mask & VSA_ACE) {
12339 			if (vsap->vsa_aclentp != NULL) {
12340 				kmem_free(vsap->vsa_aclentp,
12341 				    vsap->vsa_aclcnt * sizeof (ace_t));
12342 				vsap->vsa_aclentp = NULL;
12343 			}
12344 		}
12345 		vsap->vsa_mask = orig_mask;
12346 
12347 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12348 	    VSA_DFACLCNT)) {
12349 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12350 		    isdir, FALSE,
12351 		    ((orig_mask & (VSA_ACL | VSA_DFACL)) ? FALSE : TRUE));
12352 
12353 		if (error)
12354 			return (error);
12355 
12356 		/*
12357 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12358 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12359 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12360 		 */
12361 		if (!orig_mask & VSA_ACL) {
12362 			if (vsap->vsa_aclentp != NULL) {
12363 				kmem_free(vsap->vsa_aclentp,
12364 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12365 				vsap->vsa_aclentp = NULL;
12366 			}
12367 		}
12368 
12369 		if (!orig_mask & VSA_DFACL) {
12370 			if (vsap->vsa_dfaclentp != NULL) {
12371 				kmem_free(vsap->vsa_dfaclentp,
12372 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12373 				vsap->vsa_dfaclentp = NULL;
12374 			}
12375 		}
12376 		vsap->vsa_mask = orig_mask;
12377 	}
12378 	return (0);
12379 }
12380 
12381 static int
12382 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr)
12383 {
12384 	int error;
12385 
12386 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12387 		return (EIO);
12388 	/*
12389 	 * check for valid cmd parameter
12390 	 */
12391 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12392 		return (EINVAL);
12393 
12394 	/*
12395 	 * Check access permissions
12396 	 */
12397 	if ((cmd & F_SHARE) &&
12398 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12399 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12400 		return (EBADF);
12401 
12402 	/*
12403 	 * If the filesystem is mounted using local locking, pass the
12404 	 * request off to the local share code.
12405 	 */
12406 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12407 		return (fs_shrlock(vp, cmd, shr, flag, cr));
12408 
12409 	switch (cmd) {
12410 	case F_SHARE:
12411 	case F_UNSHARE:
12412 		/*
12413 		 * This will be properly implemented later,
12414 		 * see RFE: 4823948 .
12415 		 */
12416 		error = EAGAIN;
12417 		break;
12418 
12419 	case F_HASREMOTELOCKS:
12420 		/*
12421 		 * NFS client can't store remote locks itself
12422 		 */
12423 		shr->s_access = 0;
12424 		error = 0;
12425 		break;
12426 
12427 	default:
12428 		error = EINVAL;
12429 		break;
12430 	}
12431 
12432 	return (error);
12433 }
12434 
12435 /*
12436  * Common code called by directory ops to update the attrcache
12437  */
12438 static int
12439 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12440 	hrtime_t t, vnode_t *vp, cred_t *cr)
12441 {
12442 	int error = 0;
12443 
12444 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12445 
12446 	if (status != NFS4_OK) {
12447 		/* getattr not done or failed */
12448 		PURGE_ATTRCACHE4(vp);
12449 		return (error);
12450 	}
12451 
12452 	if (garp) {
12453 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12454 	} else {
12455 		PURGE_ATTRCACHE4(vp);
12456 	}
12457 	return (error);
12458 }
12459 
12460 /*
12461  * Update directory caches for directory modification ops (link, rename, etc.)
12462  * When dinfo is NULL, manage dircaches in the old way.
12463  */
12464 static void
12465 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12466 		dirattr_info_t *dinfo)
12467 {
12468 	rnode4_t	*drp = VTOR4(dvp);
12469 
12470 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12471 
12472 	/* Purge rddir cache for dir since it changed */
12473 	if (drp->r_dir != NULL)
12474 		nfs4_purge_rddir_cache(dvp);
12475 
12476 	/*
12477 	 * If caller provided dinfo, then use it to manage dir caches.
12478 	 */
12479 	if (dinfo != NULL) {
12480 		if (vp != NULL) {
12481 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12482 			if (!VTOR4(vp)->created_v4) {
12483 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12484 				dnlc_update(dvp, nm, vp);
12485 			} else {
12486 				/*
12487 				 * XXX don't update if the created_v4 flag is
12488 				 * set
12489 				 */
12490 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12491 				NFS4_DEBUG(nfs4_client_state_debug,
12492 					(CE_NOTE, "nfs4_update_dircaches: "
12493 					"don't update dnlc: created_v4 flag"));
12494 			}
12495 		}
12496 
12497 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12498 				dinfo->di_cred, FALSE, cinfo);
12499 
12500 		return;
12501 	}
12502 
12503 	/*
12504 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12505 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12506 	 * attrs, the dir's attrs must be purged.
12507 	 *
12508 	 * XXX this check and dnlc update/purge should really be atomic,
12509 	 * XXX but can't use rnode statelock because it'll deadlock in
12510 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12511 	 * XXX does occur.
12512 	 *
12513 	 * XXX We also may want to check that atomic is true in the
12514 	 * XXX change_info struct. If it is not, the change_info may
12515 	 * XXX reflect changes by more than one clients which means that
12516 	 * XXX our cache may not be valid.
12517 	 */
12518 	PURGE_ATTRCACHE4(dvp);
12519 	if (drp->r_change == cinfo->before) {
12520 		/* no changes took place in the directory prior to our link */
12521 		if (vp != NULL) {
12522 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12523 			if (!VTOR4(vp)->created_v4) {
12524 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12525 				dnlc_update(dvp, nm, vp);
12526 			} else {
12527 				/*
12528 				 * XXX dont' update if the created_v4 flag
12529 				 * is set
12530 				 */
12531 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12532 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12533 					"nfs4_update_dircaches: don't"
12534 					" update dnlc: created_v4 flag"));
12535 			}
12536 		}
12537 	} else {
12538 		/* Another client modified directory - purge its dnlc cache */
12539 		dnlc_purge_vp(dvp);
12540 	}
12541 }
12542 
12543 /*
12544  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12545  * file.
12546  *
12547  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12548  * file (ie: client recovery) and otherwise set to FALSE.
12549  *
12550  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12551  * initiated) calling functions.
12552  *
12553  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12554  * of resending a 'lost' open request.
12555  *
12556  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12557  * server that hands out BAD_SEQID on open confirm.
12558  *
12559  * Errors are returned via the nfs4_error_t parameter.
12560  */
12561 void
12562 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12563 	bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12564 	bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12565 {
12566 	COMPOUND4args_clnt args;
12567 	COMPOUND4res_clnt res;
12568 	nfs_argop4 argop[2];
12569 	nfs_resop4 *resop;
12570 	int doqueue = 1;
12571 	mntinfo4_t *mi;
12572 	OPEN_CONFIRM4args *open_confirm_args;
12573 	int needrecov;
12574 
12575 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12576 #if DEBUG
12577 	mutex_enter(&oop->oo_lock);
12578 	ASSERT(oop->oo_seqid_inuse);
12579 	mutex_exit(&oop->oo_lock);
12580 #endif
12581 
12582 recov_retry_confirm:
12583 	nfs4_error_zinit(ep);
12584 	*retry_open = FALSE;
12585 
12586 	if (resend)
12587 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12588 	else
12589 		args.ctag = TAG_OPEN_CONFIRM;
12590 
12591 	args.array_len = 2;
12592 	args.array = argop;
12593 
12594 	/* putfh target fh */
12595 	argop[0].argop = OP_CPUTFH;
12596 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12597 
12598 	argop[1].argop = OP_OPEN_CONFIRM;
12599 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12600 
12601 	(*seqid) += 1;
12602 	open_confirm_args->seqid = *seqid;
12603 	open_confirm_args->open_stateid = *stateid;
12604 
12605 	mi = VTOMI4(vp);
12606 
12607 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12608 
12609 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12610 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12611 	}
12612 
12613 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12614 	if (!needrecov && ep->error)
12615 		return;
12616 
12617 	if (needrecov) {
12618 		bool_t abort = FALSE;
12619 
12620 		if (reopening_file == FALSE) {
12621 			nfs4_bseqid_entry_t *bsep = NULL;
12622 
12623 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12624 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12625 					vp, 0, args.ctag,
12626 					open_confirm_args->seqid);
12627 
12628 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp,
12629 				    NULL, NULL, NULL, OP_OPEN_CONFIRM, bsep);
12630 			if (bsep) {
12631 				kmem_free(bsep, sizeof (*bsep));
12632 				if (num_bseqid_retryp &&
12633 				    --(*num_bseqid_retryp) == 0)
12634 					abort = TRUE;
12635 			}
12636 		}
12637 		if ((ep->error == ETIMEDOUT ||
12638 					res.status == NFS4ERR_RESOURCE) &&
12639 					abort == FALSE && resend == FALSE) {
12640 			if (!ep->error)
12641 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12642 								(caddr_t)&res);
12643 
12644 			delay(SEC_TO_TICK(confirm_retry_sec));
12645 			goto recov_retry_confirm;
12646 		}
12647 		/* State may have changed so retry the entire OPEN op */
12648 		if (abort == FALSE)
12649 			*retry_open = TRUE;
12650 		else
12651 			*retry_open = FALSE;
12652 		if (!ep->error)
12653 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12654 		return;
12655 	}
12656 
12657 	if (res.status) {
12658 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12659 		return;
12660 	}
12661 
12662 	resop = &res.array[1];  /* open confirm res */
12663 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
12664 				stateid, sizeof (*stateid));
12665 
12666 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12667 }
12668 
12669 /*
12670  * Return the credentials associated with a client state object.  The
12671  * caller is responsible for freeing the credentials.
12672  */
12673 
12674 static cred_t *
12675 state_to_cred(nfs4_open_stream_t *osp)
12676 {
12677 	cred_t *cr;
12678 
12679 	/*
12680 	 * It's ok to not lock the open stream and open owner to get
12681 	 * the oo_cred since this is only written once (upon creation)
12682 	 * and will not change.
12683 	 */
12684 	cr = osp->os_open_owner->oo_cred;
12685 	crhold(cr);
12686 
12687 	return (cr);
12688 }
12689 
12690 /*
12691  * nfs4_find_sysid
12692  *
12693  * Find the sysid for the knetconfig associated with the given mi.
12694  */
12695 static struct lm_sysid *
12696 nfs4_find_sysid(mntinfo4_t *mi)
12697 {
12698 	ASSERT(nfs_zone() == mi->mi_zone);
12699 
12700 	/*
12701 	 * Switch from RDMA knconf to original mount knconf
12702 	 */
12703 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
12704 		    mi->mi_curr_serv->sv_hostname, NULL));
12705 }
12706 
12707 #ifdef DEBUG
12708 /*
12709  * Return a string version of the call type for easy reading.
12710  */
12711 static char *
12712 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
12713 {
12714 	switch (ctype) {
12715 	case NFS4_LCK_CTYPE_NORM:
12716 		return ("NORMAL");
12717 	case NFS4_LCK_CTYPE_RECLAIM:
12718 		return ("RECLAIM");
12719 	case NFS4_LCK_CTYPE_RESEND:
12720 		return ("RESEND");
12721 	case NFS4_LCK_CTYPE_REINSTATE:
12722 		return ("REINSTATE");
12723 	default:
12724 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
12725 			"type %d", ctype);
12726 		return ("");
12727 	}
12728 }
12729 #endif
12730 
12731 /*
12732  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
12733  * Unlock requests don't have an over-the-wire locktype, so we just return
12734  * something non-threatening.
12735  */
12736 
12737 static nfs_lock_type4
12738 flk_to_locktype(int cmd, int l_type)
12739 {
12740 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
12741 
12742 	switch (l_type) {
12743 	case F_UNLCK:
12744 		return (READ_LT);
12745 	case F_RDLCK:
12746 		if (cmd == F_SETLK)
12747 			return (READ_LT);
12748 		else
12749 			return (READW_LT);
12750 	case F_WRLCK:
12751 		if (cmd == F_SETLK)
12752 			return (WRITE_LT);
12753 		else
12754 			return (WRITEW_LT);
12755 	}
12756 	panic("flk_to_locktype");
12757 	/*NOTREACHED*/
12758 }
12759 
12760 /*
12761  * Do some preliminary checks for nfs4frlock.
12762  */
12763 static int
12764 nfs4frlock_validate_args(int cmd, flock64_t *flk, int flag, vnode_t *vp,
12765 	u_offset_t offset)
12766 {
12767 	int error = 0;
12768 
12769 	/*
12770 	 * If we are setting a lock, check that the file is opened
12771 	 * with the correct mode.
12772 	 */
12773 	if (cmd == F_SETLK || cmd == F_SETLKW) {
12774 		if ((flk->l_type == F_RDLCK && (flag & FREAD) == 0) ||
12775 		    (flk->l_type == F_WRLCK && (flag & FWRITE) == 0)) {
12776 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12777 			    "nfs4frlock_validate_args: file was opened with "
12778 			    "incorrect mode"));
12779 			return (EBADF);
12780 		}
12781 	}
12782 
12783 	/* Convert the offset. It may need to be restored before returning. */
12784 	if (error = convoff(vp, flk, 0, offset)) {
12785 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12786 		    "nfs4frlock_validate_args: convoff  =>  error= %d\n",
12787 		    error));
12788 		return (error);
12789 	}
12790 
12791 	return (error);
12792 }
12793 
12794 /*
12795  * Set the flock64's lm_sysid for nfs4frlock.
12796  */
12797 static int
12798 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
12799 {
12800 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12801 
12802 	/* Find the lm_sysid */
12803 	*lspp = nfs4_find_sysid(VTOMI4(vp));
12804 
12805 	if (*lspp == NULL) {
12806 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12807 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
12808 		return (ENOLCK);
12809 	}
12810 
12811 	flk->l_sysid = lm_sysidt(*lspp);
12812 
12813 	return (0);
12814 }
12815 
12816 /*
12817  * Do the remaining preliminary setup for nfs4frlock.
12818  */
12819 static void
12820 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
12821 	flock64_t *flk, short *whencep, vnode_t *vp, cred_t *search_cr,
12822 	cred_t **cred_otw)
12823 {
12824 	/*
12825 	 * set tick_delay to the base delay time.
12826 	 * (NFS4_BASE_WAIT_TIME is in secs)
12827 	 */
12828 
12829 	*tick_delayp = drv_usectohz(NFS4_BASE_WAIT_TIME * 1000 * 1000);
12830 
12831 	/*
12832 	 * If lock is relative to EOF, we need the newest length of the
12833 	 * file. Therefore invalidate the ATTR_CACHE.
12834 	 */
12835 
12836 	*whencep = flk->l_whence;
12837 
12838 	if (*whencep == 2)		/* SEEK_END */
12839 		PURGE_ATTRCACHE4(vp);
12840 
12841 	recov_statep->rs_flags = 0;
12842 	recov_statep->rs_num_retry_despite_err = 0;
12843 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
12844 }
12845 
12846 /*
12847  * Initialize and allocate the data structures necessary for
12848  * the nfs4frlock call.
12849  * Allocates argsp's op array, frees up the saved_rqstpp if there is one.
12850  */
12851 static void
12852 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
12853 	nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
12854 	bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
12855 	bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
12856 {
12857 	int		argoplist_size;
12858 	int		num_ops = 2;
12859 
12860 	*retry = FALSE;
12861 	*did_start_fop = FALSE;
12862 	*skip_get_err = FALSE;
12863 	lost_rqstp->lr_op = 0;
12864 	argoplist_size  = num_ops * sizeof (nfs_argop4);
12865 	/* fill array with zero */
12866 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
12867 
12868 	*argspp = argsp;
12869 	*respp = NULL;
12870 
12871 	argsp->array_len = num_ops;
12872 	argsp->array = *argopp;
12873 
12874 	/* initialize in case of error; will get real value down below */
12875 	argsp->ctag = TAG_NONE;
12876 
12877 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
12878 		*op_hintp = OH_LOCKU;
12879 	else
12880 		*op_hintp = OH_OTHER;
12881 }
12882 
12883 /*
12884  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
12885  * the proper nfs4_server_t for this instance of nfs4frlock.
12886  * Returns 0 (success) or an errno value.
12887  */
12888 static int
12889 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
12890 	nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
12891 	bool_t *did_start_fop, bool_t *startrecovp)
12892 {
12893 	int error = 0;
12894 	rnode4_t *rp;
12895 
12896 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12897 
12898 	if (ctype == NFS4_LCK_CTYPE_NORM) {
12899 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
12900 				recov_statep, startrecovp);
12901 		if (error)
12902 			return (error);
12903 		*did_start_fop = TRUE;
12904 	} else {
12905 		*did_start_fop = FALSE;
12906 		*startrecovp = FALSE;
12907 	}
12908 
12909 	if (!error) {
12910 		rp = VTOR4(vp);
12911 
12912 		/* If the file failed recovery, just quit. */
12913 		mutex_enter(&rp->r_statelock);
12914 		if (rp->r_flags & R4RECOVERR) {
12915 			error = EIO;
12916 		}
12917 		mutex_exit(&rp->r_statelock);
12918 	}
12919 
12920 	return (error);
12921 }
12922 
12923 /*
12924  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
12925  * resend nfs4frlock call is initiated by the recovery framework.
12926  * Acquires the lop and oop seqid synchronization.
12927  */
12928 static void
12929 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
12930 	COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
12931 	nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
12932 	LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
12933 {
12934 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
12935 	int error;
12936 
12937 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
12938 		(CE_NOTE,
12939 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
12940 	ASSERT(resend_rqstp != NULL);
12941 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
12942 	    resend_rqstp->lr_op == OP_LOCKU);
12943 
12944 	*oopp = resend_rqstp->lr_oop;
12945 	if (resend_rqstp->lr_oop) {
12946 		open_owner_hold(resend_rqstp->lr_oop);
12947 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
12948 		ASSERT(error == 0);	/* recov thread always succeeds */
12949 	}
12950 
12951 	/* Must resend this lost lock/locku request. */
12952 	ASSERT(resend_rqstp->lr_lop != NULL);
12953 	*lopp = resend_rqstp->lr_lop;
12954 	lock_owner_hold(resend_rqstp->lr_lop);
12955 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
12956 	ASSERT(error == 0);	/* recov thread always succeeds */
12957 
12958 	*ospp = resend_rqstp->lr_osp;
12959 	if (*ospp)
12960 		open_stream_hold(resend_rqstp->lr_osp);
12961 
12962 	if (resend_rqstp->lr_op == OP_LOCK) {
12963 		LOCK4args *lock_args;
12964 
12965 		argop->argop = OP_LOCK;
12966 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
12967 		lock_args->locktype = resend_rqstp->lr_locktype;
12968 		lock_args->reclaim =
12969 			(resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
12970 		lock_args->offset = resend_rqstp->lr_flk->l_start;
12971 		lock_args->length = resend_rqstp->lr_flk->l_len;
12972 		if (lock_args->length == 0)
12973 			lock_args->length = ~lock_args->length;
12974 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
12975 				mi2clientid(mi), &lock_args->locker);
12976 
12977 		switch (resend_rqstp->lr_ctype) {
12978 		case NFS4_LCK_CTYPE_RESEND:
12979 			argsp->ctag = TAG_LOCK_RESEND;
12980 			break;
12981 		case NFS4_LCK_CTYPE_REINSTATE:
12982 			argsp->ctag = TAG_LOCK_REINSTATE;
12983 			break;
12984 		case NFS4_LCK_CTYPE_RECLAIM:
12985 			argsp->ctag = TAG_LOCK_RECLAIM;
12986 			break;
12987 		default:
12988 			argsp->ctag = TAG_LOCK_UNKNOWN;
12989 			break;
12990 		}
12991 	} else {
12992 		LOCKU4args *locku_args;
12993 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
12994 
12995 		argop->argop = OP_LOCKU;
12996 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
12997 		locku_args->locktype = READ_LT;
12998 		locku_args->seqid = lop->lock_seqid + 1;
12999 		mutex_enter(&lop->lo_lock);
13000 		locku_args->lock_stateid = lop->lock_stateid;
13001 		mutex_exit(&lop->lo_lock);
13002 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13003 		locku_args->length = resend_rqstp->lr_flk->l_len;
13004 		if (locku_args->length == 0)
13005 			locku_args->length = ~locku_args->length;
13006 
13007 		switch (resend_rqstp->lr_ctype) {
13008 		case NFS4_LCK_CTYPE_RESEND:
13009 			argsp->ctag = TAG_LOCKU_RESEND;
13010 			break;
13011 		case NFS4_LCK_CTYPE_REINSTATE:
13012 			argsp->ctag = TAG_LOCKU_REINSTATE;
13013 			break;
13014 		default:
13015 			argsp->ctag = TAG_LOCK_UNKNOWN;
13016 			break;
13017 		}
13018 	}
13019 }
13020 
13021 /*
13022  * Setup the LOCKT4 arguments.
13023  */
13024 static void
13025 nfs4frlock_setup_lockt_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13026 	LOCKT4args **lockt_argsp, COMPOUND4args_clnt *argsp, flock64_t *flk,
13027 	rnode4_t *rp)
13028 {
13029 	LOCKT4args *lockt_args;
13030 
13031 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13032 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13033 	argop->argop = OP_LOCKT;
13034 	argsp->ctag = TAG_LOCKT;
13035 	lockt_args = &argop->nfs_argop4_u.oplockt;
13036 
13037 	/*
13038 	 * The locktype will be READ_LT unless it's
13039 	 * a write lock. We do this because the Solaris
13040 	 * system call allows the combination of
13041 	 * F_UNLCK and F_GETLK* and so in that case the
13042 	 * unlock is mapped to a read.
13043 	 */
13044 	if (flk->l_type == F_WRLCK)
13045 		lockt_args->locktype = WRITE_LT;
13046 	else
13047 		lockt_args->locktype = READ_LT;
13048 
13049 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13050 	/* set the lock owner4 args */
13051 	nfs4_setlockowner_args(&lockt_args->owner, rp,
13052 	    ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13053 	    flk->l_pid);
13054 	lockt_args->offset = flk->l_start;
13055 	lockt_args->length = flk->l_len;
13056 	if (flk->l_len == 0)
13057 		lockt_args->length = ~lockt_args->length;
13058 
13059 	*lockt_argsp = lockt_args;
13060 }
13061 
13062 /*
13063  * If the client is holding a delegation, and the open stream to be used
13064  * with this lock request is a delegation open stream, then re-open the stream.
13065  * Sets the nfs4_error_t to all zeros unless the open stream has already
13066  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13067  * means the caller should retry (like a recovery retry).
13068  */
13069 static void
13070 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13071 {
13072 	open_delegation_type4	dt;
13073 	bool_t			reopen_needed, force;
13074 	nfs4_open_stream_t	*osp;
13075 	open_claim_type4 	oclaim;
13076 	rnode4_t		*rp = VTOR4(vp);
13077 	mntinfo4_t		*mi = VTOMI4(vp);
13078 
13079 	ASSERT(nfs_zone() == mi->mi_zone);
13080 
13081 	nfs4_error_zinit(ep);
13082 
13083 	mutex_enter(&rp->r_statev4_lock);
13084 	dt = rp->r_deleg_type;
13085 	mutex_exit(&rp->r_statev4_lock);
13086 
13087 	if (dt != OPEN_DELEGATE_NONE) {
13088 		nfs4_open_owner_t	*oop;
13089 
13090 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13091 		if (!oop) {
13092 			ep->stat = NFS4ERR_IO;
13093 			return;
13094 		}
13095 		/* returns with 'os_sync_lock' held */
13096 		osp = find_open_stream(oop, rp);
13097 		if (!osp) {
13098 			open_owner_rele(oop);
13099 			ep->stat = NFS4ERR_IO;
13100 			return;
13101 		}
13102 
13103 		if (osp->os_failed_reopen) {
13104 			NFS4_DEBUG((nfs4_open_stream_debug ||
13105 				    nfs4_client_lock_debug), (CE_NOTE,
13106 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13107 			    "for osp %p, cr %p, rp %s", (void *)osp,
13108 			    (void *)cr, rnode4info(rp)));
13109 			mutex_exit(&osp->os_sync_lock);
13110 			open_stream_rele(osp, rp);
13111 			open_owner_rele(oop);
13112 			ep->stat = NFS4ERR_IO;
13113 			return;
13114 		}
13115 
13116 		/*
13117 		 * Determine whether a reopen is needed.  If this
13118 		 * is a delegation open stream, then send the open
13119 		 * to the server to give visibility to the open owner.
13120 		 * Even if it isn't a delegation open stream, we need
13121 		 * to check if the previous open CLAIM_DELEGATE_CUR
13122 		 * was sufficient.
13123 		 */
13124 
13125 		reopen_needed = osp->os_delegation ||
13126 		    ((lt == F_RDLCK &&
13127 			!(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13128 		    (lt == F_WRLCK &&
13129 			!(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13130 
13131 		mutex_exit(&osp->os_sync_lock);
13132 		open_owner_rele(oop);
13133 
13134 		if (reopen_needed) {
13135 			/*
13136 			 * Always use CLAIM_PREVIOUS after server reboot.
13137 			 * The server will reject CLAIM_DELEGATE_CUR if
13138 			 * it is used during the grace period.
13139 			 */
13140 			mutex_enter(&mi->mi_lock);
13141 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13142 				oclaim = CLAIM_PREVIOUS;
13143 				force = TRUE;
13144 			} else {
13145 				oclaim = CLAIM_DELEGATE_CUR;
13146 				force = FALSE;
13147 			}
13148 			mutex_exit(&mi->mi_lock);
13149 
13150 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13151 			if (ep->error == EAGAIN) {
13152 				nfs4_error_zinit(ep);
13153 				ep->stat = NFS4ERR_DELAY;
13154 			}
13155 		}
13156 		open_stream_rele(osp, rp);
13157 		osp = NULL;
13158 	}
13159 }
13160 
13161 /*
13162  * Setup the LOCKU4 arguments.
13163  * Returns errors via the nfs4_error_t.
13164  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13165  *			over-the-wire.  The caller must release the
13166  *			reference on *lopp.
13167  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13168  * (other)		unrecoverable error.
13169  */
13170 static void
13171 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13172 	LOCKU4args **locku_argsp, flock64_t *flk,
13173 	nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13174 	vnode_t *vp, int flag, u_offset_t offset, cred_t *cr,
13175 	bool_t *skip_get_err, bool_t *go_otwp)
13176 {
13177 	nfs4_lock_owner_t	*lop = NULL;
13178 	LOCKU4args		*locku_args;
13179 	pid_t			pid;
13180 	bool_t			is_spec = FALSE;
13181 	rnode4_t		*rp = VTOR4(vp);
13182 
13183 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13184 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13185 
13186 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13187 	if (ep->error || ep->stat)
13188 		return;
13189 
13190 	argop->argop = OP_LOCKU;
13191 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13192 		argsp->ctag = TAG_LOCKU_REINSTATE;
13193 	else
13194 		argsp->ctag = TAG_LOCKU;
13195 	locku_args = &argop->nfs_argop4_u.oplocku;
13196 	*locku_argsp = locku_args;
13197 
13198 	/*
13199 	 * XXX what should locku_args->locktype be?
13200 	 * setting to ALWAYS be READ_LT so at least
13201 	 * it is a valid locktype.
13202 	 */
13203 
13204 	locku_args->locktype = READ_LT;
13205 
13206 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13207 		flk->l_pid;
13208 
13209 	/*
13210 	 * Get the lock owner stateid.  If no lock owner
13211 	 * exists, return success.
13212 	 */
13213 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13214 	*lopp = lop;
13215 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13216 		is_spec = TRUE;
13217 	if (!lop || is_spec) {
13218 		/*
13219 		 * No lock owner so no locks to unlock.
13220 		 * Return success.  If there was a failed
13221 		 * reclaim earlier, the lock might still be
13222 		 * registered with the local locking code,
13223 		 * so notify it of the unlock.
13224 		 *
13225 		 * If the lockowner is using a special stateid,
13226 		 * then the original lock request (that created
13227 		 * this lockowner) was never successful, so we
13228 		 * have no lock to undo OTW.
13229 		 */
13230 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13231 			"nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13232 			"(%ld) so return success", (long)pid));
13233 
13234 		if (ctype == NFS4_LCK_CTYPE_NORM)
13235 			flk->l_pid = curproc->p_pid;
13236 		nfs4_register_lock_locally(vp, flk, flag, offset);
13237 		/*
13238 		 * Release our hold and NULL out so final_cleanup
13239 		 * doesn't try to end a lock seqid sync we
13240 		 * never started.
13241 		 */
13242 		if (is_spec) {
13243 			lock_owner_rele(lop);
13244 			*lopp = NULL;
13245 		}
13246 		*skip_get_err = TRUE;
13247 		*go_otwp = FALSE;
13248 		return;
13249 	}
13250 
13251 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13252 	if (ep->error == EAGAIN) {
13253 		lock_owner_rele(lop);
13254 		*lopp = NULL;
13255 		return;
13256 	}
13257 
13258 	mutex_enter(&lop->lo_lock);
13259 	locku_args->lock_stateid = lop->lock_stateid;
13260 	mutex_exit(&lop->lo_lock);
13261 	locku_args->seqid = lop->lock_seqid + 1;
13262 
13263 	/* leave the ref count on lop, rele after RPC call */
13264 
13265 	locku_args->offset = flk->l_start;
13266 	locku_args->length = flk->l_len;
13267 	if (flk->l_len == 0)
13268 		locku_args->length = ~locku_args->length;
13269 
13270 	*go_otwp = TRUE;
13271 }
13272 
13273 /*
13274  * Setup the LOCK4 arguments.
13275  *
13276  * Returns errors via the nfs4_error_t.
13277  * NFS4_OK		no problems
13278  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13279  * (other)		unrecoverable error
13280  */
13281 static void
13282 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13283 	nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13284 	nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13285 	flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13286 {
13287 	LOCK4args		*lock_args;
13288 	nfs4_open_owner_t	*oop = NULL;
13289 	nfs4_open_stream_t	*osp = NULL;
13290 	nfs4_lock_owner_t	*lop = NULL;
13291 	pid_t			pid;
13292 	rnode4_t		*rp = VTOR4(vp);
13293 
13294 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13295 
13296 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13297 	if (ep->error || ep->stat != NFS4_OK)
13298 		return;
13299 
13300 	argop->argop = OP_LOCK;
13301 	if (ctype == NFS4_LCK_CTYPE_NORM)
13302 		argsp->ctag = TAG_LOCK;
13303 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13304 		argsp->ctag = TAG_RELOCK;
13305 	else
13306 		argsp->ctag = TAG_LOCK_REINSTATE;
13307 	lock_args = &argop->nfs_argop4_u.oplock;
13308 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13309 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13310 	/*
13311 	 * Get the lock owner.  If no lock owner exists,
13312 	 * create a 'temporary' one and grab the open seqid
13313 	 * synchronization (which puts a hold on the open
13314 	 * owner and open stream).
13315 	 * This also grabs the lock seqid synchronization.
13316 	 */
13317 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid : flk->l_pid;
13318 	ep->stat =
13319 		nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13320 
13321 	if (ep->stat != NFS4_OK)
13322 		goto out;
13323 
13324 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13325 			&lock_args->locker);
13326 
13327 	lock_args->offset = flk->l_start;
13328 	lock_args->length = flk->l_len;
13329 	if (flk->l_len == 0)
13330 		lock_args->length = ~lock_args->length;
13331 	*lock_argsp = lock_args;
13332 out:
13333 	*oopp = oop;
13334 	*ospp = osp;
13335 	*lopp = lop;
13336 }
13337 
13338 /*
13339  * After we get the reply from the server, record the proper information
13340  * for possible resend lock requests.
13341  *
13342  * Allocates memory for the saved_rqstp if we have a lost lock to save.
13343  */
13344 static void
13345 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13346 	nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13347 	nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13348 	nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13349 {
13350 	bool_t unlock = (flk->l_type == F_UNLCK);
13351 
13352 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13353 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13354 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13355 
13356 	if (error != 0 && !unlock) {
13357 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13358 			    nfs4_client_lock_debug), (CE_NOTE,
13359 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13360 		    " for lop %p", (void *)lop));
13361 		ASSERT(lop != NULL);
13362 		mutex_enter(&lop->lo_lock);
13363 		lop->lo_pending_rqsts = 1;
13364 		mutex_exit(&lop->lo_lock);
13365 	}
13366 
13367 	lost_rqstp->lr_putfirst = FALSE;
13368 	lost_rqstp->lr_op = 0;
13369 
13370 	/*
13371 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13372 	 * recovery purposes so that the lock request that was sent
13373 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13374 	 * unmount.  This is done to have the client's local locking state
13375 	 * match the v4 server's state; that is, the request was
13376 	 * potentially received and accepted by the server but the client
13377 	 * thinks it was not.
13378 	 */
13379 	if (error == ETIMEDOUT || error == EINTR ||
13380 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13381 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13382 			    nfs4_client_lock_debug), (CE_NOTE,
13383 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13384 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13385 		    (void *)lop, (void *)oop, (void *)osp));
13386 		if (unlock)
13387 			lost_rqstp->lr_op = OP_LOCKU;
13388 		else {
13389 			lost_rqstp->lr_op = OP_LOCK;
13390 			lost_rqstp->lr_locktype = locktype;
13391 		}
13392 		/*
13393 		 * Objects are held and rele'd via the recovery code.
13394 		 * See nfs4_save_lost_rqst.
13395 		 */
13396 		lost_rqstp->lr_vp = vp;
13397 		lost_rqstp->lr_dvp = NULL;
13398 		lost_rqstp->lr_oop = oop;
13399 		lost_rqstp->lr_osp = osp;
13400 		lost_rqstp->lr_lop = lop;
13401 		lost_rqstp->lr_cr = cr;
13402 		switch (ctype) {
13403 		case NFS4_LCK_CTYPE_NORM:
13404 			flk->l_pid = ttoproc(curthread)->p_pid;
13405 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13406 			break;
13407 		case NFS4_LCK_CTYPE_REINSTATE:
13408 			lost_rqstp->lr_putfirst = TRUE;
13409 			lost_rqstp->lr_ctype = ctype;
13410 			break;
13411 		default:
13412 			break;
13413 		}
13414 		lost_rqstp->lr_flk = flk;
13415 	}
13416 }
13417 
13418 /*
13419  * Update lop's seqid.  Also update the seqid stored in a resend request,
13420  * if any.  (Some recovery errors increment the seqid, and we may have to
13421  * send the resend request again.)
13422  */
13423 
13424 static void
13425 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13426     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13427 {
13428 	if (lock_args) {
13429 		if (lock_args->locker.new_lock_owner == TRUE)
13430 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13431 		else {
13432 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13433 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13434 		}
13435 	} else if (locku_args) {
13436 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13437 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13438 	}
13439 }
13440 
13441 /*
13442  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13443  * COMPOUND4 args/res for calls that need to retry.
13444  * Switches the *cred_otwp to base_cr.
13445  */
13446 static void
13447 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13448     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13449     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13450     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13451     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13452 {
13453 	nfs4_open_owner_t	*oop = *oopp;
13454 	nfs4_open_stream_t	*osp = *ospp;
13455 	nfs4_lock_owner_t	*lop = *lopp;
13456 	nfs_argop4		*argop = (*argspp)->array;
13457 
13458 	if (*did_start_fop) {
13459 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13460 			    needrecov);
13461 		*did_start_fop = FALSE;
13462 	}
13463 	ASSERT((*argspp)->array_len == 2);
13464 	if (argop[1].argop == OP_LOCK)
13465 		nfs4args_lock_free(&argop[1]);
13466 	else if (argop[1].argop == OP_LOCKT)
13467 		nfs4args_lockt_free(&argop[1]);
13468 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13469 	if (!error)
13470 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13471 	*argspp = NULL;
13472 	*respp = NULL;
13473 
13474 	if (lop) {
13475 		nfs4_end_lock_seqid_sync(lop);
13476 		lock_owner_rele(lop);
13477 		*lopp = NULL;
13478 	}
13479 
13480 	/* need to free up the reference on osp for lock args */
13481 	if (osp != NULL) {
13482 		open_stream_rele(osp, VTOR4(vp));
13483 		*ospp = NULL;
13484 	}
13485 
13486 	/* need to free up the reference on oop for lock args */
13487 	if (oop != NULL) {
13488 		nfs4_end_open_seqid_sync(oop);
13489 		open_owner_rele(oop);
13490 		*oopp = NULL;
13491 	}
13492 
13493 	crfree(*cred_otwp);
13494 	*cred_otwp = base_cr;
13495 	crhold(*cred_otwp);
13496 }
13497 
13498 /*
13499  * Function to process the client's recovery for nfs4frlock.
13500  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13501  *
13502  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13503  * COMPOUND4 args/res for calls that need to retry.
13504  *
13505  * Note: the rp's r_lkserlock is *not* dropped during this path.
13506  */
13507 static bool_t
13508 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13509 	COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13510 	LOCK4args *lock_args, LOCKU4args *locku_args,
13511 	nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13512 	nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13513 	nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13514 	bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13515 {
13516 	nfs4_open_owner_t	*oop = *oopp;
13517 	nfs4_open_stream_t	*osp = *ospp;
13518 	nfs4_lock_owner_t	*lop = *lopp;
13519 
13520 	bool_t abort, retry;
13521 
13522 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13523 	ASSERT((*argspp) != NULL);
13524 	ASSERT((*respp) != NULL);
13525 	if (lock_args || locku_args)
13526 		ASSERT(lop != NULL);
13527 
13528 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13529 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13530 
13531 	retry = TRUE;
13532 	abort = FALSE;
13533 	if (needrecov) {
13534 		nfs4_bseqid_entry_t *bsep = NULL;
13535 		nfs_opnum4 op;
13536 
13537 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13538 
13539 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13540 			seqid4 seqid;
13541 
13542 			if (lock_args) {
13543 				if (lock_args->locker.new_lock_owner == TRUE)
13544 					seqid = lock_args->locker.locker4_u.
13545 						    open_owner.open_seqid;
13546 				else
13547 					seqid = lock_args->locker.locker4_u.
13548 						    lock_owner.lock_seqid;
13549 			} else if (locku_args) {
13550 				seqid = locku_args->seqid;
13551 			} else {
13552 				seqid = 0;
13553 			}
13554 
13555 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13556 				flk->l_pid, (*argspp)->ctag, seqid);
13557 		}
13558 
13559 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13560 			    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13561 			    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13562 			    NULL, op, bsep);
13563 
13564 		if (bsep)
13565 			kmem_free(bsep, sizeof (*bsep));
13566 	}
13567 
13568 	/*
13569 	 * Return that we do not want to retry the request for 3 cases:
13570 	 * 1. If we received EINTR or are bailing out because of a forced
13571 	 *    unmount, we came into this code path just for the sake of
13572 	 *    initiating recovery, we now need to return the error.
13573 	 * 2. If we have aborted recovery.
13574 	 * 3. We received NFS4ERR_BAD_SEQID.
13575 	 */
13576 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13577 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13578 		retry = FALSE;
13579 
13580 	if (*did_start_fop == TRUE) {
13581 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13582 		    needrecov);
13583 		*did_start_fop = FALSE;
13584 	}
13585 
13586 	if (retry == TRUE) {
13587 		nfs_argop4	*argop;
13588 
13589 		argop = (*argspp)->array;
13590 		ASSERT((*argspp)->array_len == 2);
13591 
13592 		if (argop[1].argop == OP_LOCK)
13593 			nfs4args_lock_free(&argop[1]);
13594 		else if (argop[1].argop == OP_LOCKT)
13595 			nfs4args_lockt_free(&argop[1]);
13596 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13597 		if (!ep->error)
13598 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13599 		*respp = NULL;
13600 		*argspp = NULL;
13601 	}
13602 
13603 	if (lop != NULL) {
13604 		nfs4_end_lock_seqid_sync(lop);
13605 		lock_owner_rele(lop);
13606 	}
13607 
13608 	*lopp = NULL;
13609 
13610 	/* need to free up the reference on osp for lock args */
13611 	if (osp != NULL) {
13612 		open_stream_rele(osp, rp);
13613 		*ospp = NULL;
13614 	}
13615 
13616 	/* need to free up the reference on oop for lock args */
13617 	if (oop != NULL) {
13618 		nfs4_end_open_seqid_sync(oop);
13619 		open_owner_rele(oop);
13620 		*oopp = NULL;
13621 	}
13622 
13623 	return (retry);
13624 }
13625 
13626 /*
13627  * Handles the succesful reply from the server for nfs4frlock.
13628  */
13629 static void
13630 nfs4frlock_results_ok(nfs4_lock_call_type_t ctype, int cmd, flock64_t *flk,
13631 	vnode_t *vp, int flag, u_offset_t offset,
13632 	nfs4_lost_rqst_t *resend_rqstp)
13633 {
13634 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13635 	if ((cmd == F_SETLK || cmd == F_SETLKW) &&
13636 	    (flk->l_type == F_RDLCK || flk->l_type == F_WRLCK)) {
13637 		if (ctype == NFS4_LCK_CTYPE_NORM) {
13638 			flk->l_pid = ttoproc(curthread)->p_pid;
13639 			/*
13640 			 * We do not register lost locks locally in
13641 			 * the 'resend' case since the user/application
13642 			 * doesn't think we have the lock.
13643 			 */
13644 			ASSERT(!resend_rqstp);
13645 			nfs4_register_lock_locally(vp, flk, flag, offset);
13646 		}
13647 	}
13648 }
13649 
13650 /*
13651  * Handle the DENIED reply from the server for nfs4frlock.
13652  * Returns TRUE if we should retry the request; FALSE otherwise.
13653  *
13654  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13655  * COMPOUND4 args/res for calls that need to retry.  Can also
13656  * drop and regrab the r_lkserlock.
13657  */
13658 static bool_t
13659 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13660 	LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13661 	nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13662 	vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13663 	nfs4_recov_state_t *recov_statep, int needrecov,
13664 	COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13665 	clock_t *tick_delayp, short *whencep, int *errorp,
13666 	nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13667 	bool_t *skip_get_err)
13668 {
13669 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13670 
13671 	if (lock_args) {
13672 		nfs4_open_owner_t	*oop = *oopp;
13673 		nfs4_open_stream_t	*osp = *ospp;
13674 		nfs4_lock_owner_t	*lop = *lopp;
13675 		int			intr;
13676 
13677 		/*
13678 		 * Blocking lock needs to sleep and retry from the request.
13679 		 *
13680 		 * Do not block and wait for 'resend' or 'reinstate'
13681 		 * lock requests, just return the error.
13682 		 *
13683 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13684 		 */
13685 		if (cmd == F_SETLKW) {
13686 			rnode4_t *rp = VTOR4(vp);
13687 			nfs_argop4 *argop = (*argspp)->array;
13688 
13689 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13690 
13691 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13692 				recov_statep, needrecov);
13693 			*did_start_fop = FALSE;
13694 			ASSERT((*argspp)->array_len == 2);
13695 			if (argop[1].argop == OP_LOCK)
13696 				nfs4args_lock_free(&argop[1]);
13697 			else if (argop[1].argop == OP_LOCKT)
13698 				nfs4args_lockt_free(&argop[1]);
13699 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13700 			if (*respp)
13701 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13702 							(caddr_t)*respp);
13703 			*argspp = NULL;
13704 			*respp = NULL;
13705 			nfs4_end_lock_seqid_sync(lop);
13706 			lock_owner_rele(lop);
13707 			*lopp = NULL;
13708 			if (osp != NULL) {
13709 				open_stream_rele(osp, rp);
13710 				*ospp = NULL;
13711 			}
13712 			if (oop != NULL) {
13713 				nfs4_end_open_seqid_sync(oop);
13714 				open_owner_rele(oop);
13715 				*oopp = NULL;
13716 			}
13717 
13718 			nfs_rw_exit(&rp->r_lkserlock);
13719 
13720 			intr = nfs4_block_and_wait(tick_delayp, rp);
13721 
13722 			if (intr) {
13723 				(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13724 						RW_WRITER, FALSE);
13725 				*errorp = EINTR;
13726 				return (FALSE);
13727 			}
13728 
13729 			(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13730 					RW_WRITER, FALSE);
13731 
13732 			/*
13733 			 * Make sure we are still safe to lock with
13734 			 * regards to mmapping.
13735 			 */
13736 			if (!nfs4_safelock(vp, flk, cr)) {
13737 				*errorp = EAGAIN;
13738 				return (FALSE);
13739 			}
13740 
13741 			return (TRUE);
13742 		}
13743 		if (ctype == NFS4_LCK_CTYPE_NORM)
13744 			*errorp = EAGAIN;
13745 		*skip_get_err = TRUE;
13746 		flk->l_whence = 0;
13747 		*whencep = 0;
13748 		return (FALSE);
13749 	} else if (lockt_args) {
13750 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13751 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
13752 
13753 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
13754 			flk, lockt_args);
13755 
13756 		/* according to NLM code */
13757 		*errorp = 0;
13758 		*whencep = 0;
13759 		*skip_get_err = TRUE;
13760 		return (FALSE);
13761 	}
13762 	return (FALSE);
13763 }
13764 
13765 /*
13766  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
13767  */
13768 static void
13769 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
13770 {
13771 	switch (resp->status) {
13772 	case NFS4ERR_ACCESS:
13773 	case NFS4ERR_ADMIN_REVOKED:
13774 	case NFS4ERR_BADHANDLE:
13775 	case NFS4ERR_BAD_RANGE:
13776 	case NFS4ERR_BAD_SEQID:
13777 	case NFS4ERR_BAD_STATEID:
13778 	case NFS4ERR_BADXDR:
13779 	case NFS4ERR_DEADLOCK:
13780 	case NFS4ERR_DELAY:
13781 	case NFS4ERR_EXPIRED:
13782 	case NFS4ERR_FHEXPIRED:
13783 	case NFS4ERR_GRACE:
13784 	case NFS4ERR_INVAL:
13785 	case NFS4ERR_ISDIR:
13786 	case NFS4ERR_LEASE_MOVED:
13787 	case NFS4ERR_LOCK_NOTSUPP:
13788 	case NFS4ERR_LOCK_RANGE:
13789 	case NFS4ERR_MOVED:
13790 	case NFS4ERR_NOFILEHANDLE:
13791 	case NFS4ERR_NO_GRACE:
13792 	case NFS4ERR_OLD_STATEID:
13793 	case NFS4ERR_OPENMODE:
13794 	case NFS4ERR_RECLAIM_BAD:
13795 	case NFS4ERR_RECLAIM_CONFLICT:
13796 	case NFS4ERR_RESOURCE:
13797 	case NFS4ERR_SERVERFAULT:
13798 	case NFS4ERR_STALE:
13799 	case NFS4ERR_STALE_CLIENTID:
13800 	case NFS4ERR_STALE_STATEID:
13801 		return;
13802 	default:
13803 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13804 		    "nfs4frlock_results_default: got unrecognizable "
13805 		    "res.status %d", resp->status));
13806 		*errorp = NFS4ERR_INVAL;
13807 	}
13808 }
13809 
13810 /*
13811  * The lock request was successful, so update the client's state.
13812  */
13813 static void
13814 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
13815 	LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
13816 	vnode_t *vp, flock64_t *flk, cred_t *cr,
13817 	nfs4_lost_rqst_t *resend_rqstp)
13818 {
13819 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13820 
13821 	if (lock_args) {
13822 		LOCK4res *lock_res;
13823 
13824 		lock_res = &resop->nfs_resop4_u.oplock;
13825 		/* update the stateid with server's response */
13826 
13827 		if (lock_args->locker.new_lock_owner == TRUE) {
13828 			mutex_enter(&lop->lo_lock);
13829 			lop->lo_just_created = NFS4_PERM_CREATED;
13830 			mutex_exit(&lop->lo_lock);
13831 		}
13832 
13833 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
13834 
13835 		/*
13836 		 * If the lock was the result of a resending a lost
13837 		 * request, we've synched up the stateid and seqid
13838 		 * with the server, but now the server might be out of sync
13839 		 * with what the application thinks it has for locks.
13840 		 * Clean that up here.  It's unclear whether we should do
13841 		 * this even if the filesystem has been forcibly unmounted.
13842 		 * For most servers, it's probably wasted effort, but
13843 		 * RFC3530 lets servers require that unlocks exactly match
13844 		 * the locks that are held.
13845 		 */
13846 		if (resend_rqstp != NULL &&
13847 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
13848 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
13849 		} else {
13850 			flk->l_whence = 0;
13851 		}
13852 	} else if (locku_args) {
13853 		LOCKU4res *locku_res;
13854 
13855 		locku_res = &resop->nfs_resop4_u.oplocku;
13856 
13857 		/* Update the stateid with the server's response */
13858 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
13859 	} else if (lockt_args) {
13860 		/* Switch the lock type to express success, see fcntl */
13861 		flk->l_type = F_UNLCK;
13862 		flk->l_whence = 0;
13863 	}
13864 }
13865 
13866 /*
13867  * Do final cleanup before exiting nfs4frlock.
13868  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13869  * COMPOUND4 args/res for calls that haven't already.
13870  */
13871 static void
13872 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
13873 	COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
13874 	nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
13875 	nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13876 	short whence, u_offset_t offset, struct lm_sysid *ls,
13877 	int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
13878 	bool_t did_start_fop, bool_t skip_get_err,
13879 	cred_t *cred_otw, cred_t *cred)
13880 {
13881 	mntinfo4_t	*mi = VTOMI4(vp);
13882 	rnode4_t	*rp = VTOR4(vp);
13883 	int		error = *errorp;
13884 	nfs_argop4	*argop;
13885 
13886 	ASSERT(nfs_zone() == mi->mi_zone);
13887 	/*
13888 	 * The client recovery code wants the raw status information,
13889 	 * so don't map the NFS status code to an errno value for
13890 	 * non-normal call types.
13891 	 */
13892 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13893 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
13894 			*errorp = geterrno4(resp->status);
13895 		if (did_start_fop == TRUE)
13896 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
13897 				needrecov);
13898 
13899 		if (!error && resp && resp->status == NFS4_OK) {
13900 		/*
13901 		 * We've established a new lock on the server, so invalidate
13902 		 * the pages associated with the vnode to get the most up to
13903 		 * date pages from the server after acquiring the lock. We
13904 		 * want to be sure that the read operation gets the newest data.
13905 		 * N.B.
13906 		 * We used to do this in nfs4frlock_results_ok but that doesn't
13907 		 * work since VOP_PUTPAGE can call nfs4_commit which calls
13908 		 * nfs4_start_fop. We flush the pages below after calling
13909 		 * nfs4_end_fop above
13910 		 */
13911 			int error;
13912 
13913 			error = VOP_PUTPAGE(vp, (u_offset_t)0,
13914 						0, B_INVAL, cred);
13915 
13916 			if (error && (error == ENOSPC || error == EDQUOT)) {
13917 				rnode4_t *rp = VTOR4(vp);
13918 
13919 				mutex_enter(&rp->r_statelock);
13920 				if (!rp->r_error)
13921 					rp->r_error = error;
13922 				mutex_exit(&rp->r_statelock);
13923 			}
13924 		}
13925 	}
13926 	if (argsp) {
13927 		ASSERT(argsp->array_len == 2);
13928 		argop = argsp->array;
13929 		if (argop[1].argop == OP_LOCK)
13930 			nfs4args_lock_free(&argop[1]);
13931 		else if (argop[1].argop == OP_LOCKT)
13932 			nfs4args_lockt_free(&argop[1]);
13933 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13934 		if (resp)
13935 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
13936 	}
13937 
13938 	/* free the reference on the lock owner */
13939 	if (lop != NULL) {
13940 		nfs4_end_lock_seqid_sync(lop);
13941 		lock_owner_rele(lop);
13942 	}
13943 
13944 	/* need to free up the reference on osp for lock args */
13945 	if (osp != NULL)
13946 		open_stream_rele(osp, rp);
13947 
13948 	/* need to free up the reference on oop for lock args */
13949 	if (oop != NULL) {
13950 		nfs4_end_open_seqid_sync(oop);
13951 		open_owner_rele(oop);
13952 	}
13953 
13954 	(void) convoff(vp, flk, whence, offset);
13955 
13956 	lm_rel_sysid(ls);
13957 
13958 	/*
13959 	 * Record debug information in the event we get EINVAL.
13960 	 */
13961 	mutex_enter(&mi->mi_lock);
13962 	if (*errorp == EINVAL && (lock_args || locku_args) &&
13963 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
13964 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
13965 			zcmn_err(getzoneid(), CE_NOTE,
13966 			    "%s operation failed with "
13967 			    "EINVAL probably since the server, %s,"
13968 			    " doesn't support POSIX style locking",
13969 			    lock_args ? "LOCK" : "LOCKU",
13970 			    mi->mi_curr_serv->sv_hostname);
13971 			mi->mi_flags |= MI4_LOCK_DEBUG;
13972 		}
13973 	}
13974 	mutex_exit(&mi->mi_lock);
13975 
13976 	if (cred_otw)
13977 		crfree(cred_otw);
13978 }
13979 
13980 /*
13981  * This calls the server and the local locking code.
13982  *
13983  * Client locks are registerred locally by oring the sysid with
13984  * LM_SYSID_CLIENT. The server registers locks locally using just the sysid.
13985  * We need to distinguish between the two to avoid collision in case one
13986  * machine is used as both client and server.
13987  *
13988  * Blocking lock requests will continually retry to acquire the lock
13989  * forever.
13990  *
13991  * The ctype is defined as follows:
13992  * NFS4_LCK_CTYPE_NORM: normal lock request.
13993  *
13994  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
13995  * recovery, get the pid from flk instead of curproc, and don't reregister
13996  * the lock locally.
13997  *
13998  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
13999  * that we will use the information passed in via resend_rqstp to setup the
14000  * lock/locku request.  This resend is the exact same request as the 'lost
14001  * lock', and is initiated by the recovery framework. A successful resend
14002  * request can initiate one or more reinstate requests.
14003  *
14004  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14005  * does not trigger additional reinstate requests.  This lock call type is
14006  * set for setting the v4 server's locking state back to match what the
14007  * client's local locking state is in the event of a received 'lost lock'.
14008  *
14009  * Errors are returned via the nfs4_error_t parameter.
14010  */
14011 void
14012 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14013 		int flag, u_offset_t offset, cred_t *cr, nfs4_error_t *ep,
14014 		nfs4_lost_rqst_t *resend_rqstp, int *did_reclaimp)
14015 {
14016 	COMPOUND4args_clnt	args, *argsp = NULL;
14017 	COMPOUND4res_clnt	res, *resp = NULL;
14018 	nfs_argop4	*argop;
14019 	nfs_resop4	*resop;
14020 	rnode4_t	*rp;
14021 	int		doqueue = 1;
14022 	clock_t		tick_delay;  /* delay in clock ticks */
14023 	struct lm_sysid	*ls;
14024 	LOCK4args	*lock_args = NULL;
14025 	LOCKU4args	*locku_args = NULL;
14026 	LOCKT4args	*lockt_args = NULL;
14027 	nfs4_open_owner_t *oop = NULL;
14028 	nfs4_open_stream_t *osp = NULL;
14029 	nfs4_lock_owner_t *lop = NULL;
14030 	bool_t		needrecov = FALSE;
14031 	nfs4_recov_state_t recov_state;
14032 	short		whence;
14033 	nfs4_op_hint_t	op_hint;
14034 	nfs4_lost_rqst_t lost_rqst;
14035 	bool_t		retry = FALSE;
14036 	bool_t		did_start_fop = FALSE;
14037 	bool_t		skip_get_err = FALSE;
14038 	cred_t		*cred_otw = NULL;
14039 	bool_t		recovonly;	/* just queue request */
14040 	int		frc_no_reclaim = 0;
14041 #ifdef DEBUG
14042 	char *name;
14043 #endif
14044 
14045 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14046 
14047 #ifdef DEBUG
14048 	name = fn_name(VTOSV(vp)->sv_name);
14049 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14050 	    "%s: cmd %d, type %d, offset %llu, start %"PRIx64", "
14051 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14052 	    "resend request %s", name, cmd, flk->l_type, offset, flk->l_start,
14053 	    flk->l_len, ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid :
14054 	    flk->l_pid, flk->l_sysid, nfs4frlock_get_call_type(ctype),
14055 	    resend_rqstp ? "TRUE" : "FALSE"));
14056 	kmem_free(name, MAXNAMELEN);
14057 #endif
14058 
14059 	nfs4_error_zinit(ep);
14060 	ep->error = nfs4frlock_validate_args(cmd, flk, flag, vp, offset);
14061 	if (ep->error)
14062 		return;
14063 	ep->error = nfs4frlock_get_sysid(&ls, vp, flk);
14064 	if (ep->error)
14065 		return;
14066 	nfs4frlock_pre_setup(&tick_delay, &recov_state, flk, &whence,
14067 	    vp, cr, &cred_otw);
14068 
14069 recov_retry:
14070 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14071 		&retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14072 	rp = VTOR4(vp);
14073 
14074 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14075 			    &did_start_fop, &recovonly);
14076 
14077 	if (ep->error)
14078 		goto out;
14079 
14080 	if (recovonly) {
14081 		/*
14082 		 * Leave the request for the recovery system to deal with.
14083 		 */
14084 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14085 		ASSERT(cmd != F_GETLK);
14086 		ASSERT(flk->l_type == F_UNLCK);
14087 
14088 		nfs4_error_init(ep, EINTR);
14089 		needrecov = TRUE;
14090 		lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14091 		if (lop != NULL) {
14092 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14093 				NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14094 			(void) nfs4_start_recovery(ep,
14095 				VTOMI4(vp), vp, NULL, NULL,
14096 				(lost_rqst.lr_op == OP_LOCK ||
14097 				lost_rqst.lr_op == OP_LOCKU) ?
14098 				&lost_rqst : NULL, OP_LOCKU, NULL);
14099 			lock_owner_rele(lop);
14100 			lop = NULL;
14101 		}
14102 		flk->l_pid = curproc->p_pid;
14103 		nfs4_register_lock_locally(vp, flk, flag, offset);
14104 		goto out;
14105 	}
14106 
14107 	/* putfh directory fh */
14108 	argop[0].argop = OP_CPUTFH;
14109 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14110 
14111 	/*
14112 	 * Set up the over-the-wire arguments and get references to the
14113 	 * open owner, etc.
14114 	 */
14115 
14116 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14117 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14118 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14119 			&argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14120 	} else {
14121 		bool_t go_otw = TRUE;
14122 
14123 		ASSERT(resend_rqstp == NULL);
14124 
14125 		switch (cmd) {
14126 		case F_GETLK:
14127 		case F_O_GETLK:
14128 			nfs4frlock_setup_lockt_args(ctype, &argop[1],
14129 					&lockt_args, argsp, flk, rp);
14130 			break;
14131 		case F_SETLKW:
14132 		case F_SETLK:
14133 			if (flk->l_type == F_UNLCK)
14134 				nfs4frlock_setup_locku_args(ctype,
14135 						&argop[1], &locku_args, flk,
14136 						&lop, ep, argsp,
14137 						vp, flag, offset, cr,
14138 						&skip_get_err, &go_otw);
14139 			else
14140 				nfs4frlock_setup_lock_args(ctype,
14141 					&lock_args, &oop, &osp, &lop, &argop[1],
14142 					argsp, flk, cmd, vp, cr, ep);
14143 
14144 			if (ep->error)
14145 				goto out;
14146 
14147 			switch (ep->stat) {
14148 			case NFS4_OK:
14149 				break;
14150 			case NFS4ERR_DELAY:
14151 				/* recov thread never gets this error */
14152 				ASSERT(resend_rqstp == NULL);
14153 				ASSERT(did_start_fop);
14154 
14155 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14156 				    &recov_state, TRUE);
14157 				did_start_fop = FALSE;
14158 				if (argop[1].argop == OP_LOCK)
14159 					nfs4args_lock_free(&argop[1]);
14160 				else if (argop[1].argop == OP_LOCKT)
14161 					nfs4args_lockt_free(&argop[1]);
14162 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14163 				argsp = NULL;
14164 				goto recov_retry;
14165 			default:
14166 				ep->error = EIO;
14167 				goto out;
14168 			}
14169 			break;
14170 		default:
14171 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14172 				"nfs4_frlock: invalid cmd %d", cmd));
14173 			ep->error = EINVAL;
14174 			goto out;
14175 		}
14176 
14177 		if (!go_otw)
14178 			goto out;
14179 	}
14180 
14181 	/* XXX should we use the local reclock as a cache ? */
14182 	/*
14183 	 * Unregister the lock with the local locking code before
14184 	 * contacting the server.  This avoids a potential race where
14185 	 * another process gets notified that it has been granted a lock
14186 	 * before we can unregister ourselves locally.
14187 	 */
14188 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK) {
14189 		if (ctype == NFS4_LCK_CTYPE_NORM)
14190 			flk->l_pid = ttoproc(curthread)->p_pid;
14191 		nfs4_register_lock_locally(vp, flk, flag, offset);
14192 	}
14193 
14194 	/*
14195 	 * Send the server the lock request.  Continually loop with a delay
14196 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14197 	 */
14198 	resp = &res;
14199 
14200 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14201 	    (CE_NOTE,
14202 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14203 	    rnode4info(rp)));
14204 
14205 	if (lock_args && frc_no_reclaim) {
14206 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14207 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14208 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14209 		lock_args->reclaim = FALSE;
14210 		if (did_reclaimp)
14211 			*did_reclaimp = 0;
14212 	}
14213 
14214 	/*
14215 	 * Do the OTW call.
14216 	 */
14217 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14218 
14219 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14220 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14221 
14222 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14223 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14224 	    "nfs4frlock: needrecov %d", needrecov));
14225 
14226 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14227 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14228 		    args.ctag);
14229 
14230 	/*
14231 	 * Check if one of these mutually exclusive error cases has
14232 	 * happened:
14233 	 *   need to swap credentials due to access error
14234 	 *   recovery is needed
14235 	 *   different error (only known case is missing Kerberos ticket)
14236 	 */
14237 
14238 	if ((ep->error == EACCES ||
14239 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14240 	    cred_otw != cr) {
14241 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14242 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14243 		    cr, &cred_otw);
14244 		goto recov_retry;
14245 	}
14246 
14247 	if (needrecov) {
14248 		/*
14249 		 * LOCKT requests don't need to recover from lost
14250 		 * requests since they don't create/modify state.
14251 		 */
14252 		if ((ep->error == EINTR ||
14253 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14254 		    lockt_args)
14255 			goto out;
14256 		/*
14257 		 * Do not attempt recovery for requests initiated by
14258 		 * the recovery framework.  Let the framework redrive them.
14259 		 */
14260 		if (ctype != NFS4_LCK_CTYPE_NORM)
14261 			goto out;
14262 		else {
14263 			ASSERT(resend_rqstp == NULL);
14264 		}
14265 
14266 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14267 			flk_to_locktype(cmd, flk->l_type),
14268 			oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14269 
14270 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14271 			    &resp, lock_args, locku_args, &oop, &osp, &lop,
14272 			    rp, vp, &recov_state, op_hint, &did_start_fop,
14273 			    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14274 
14275 		if (retry) {
14276 			ASSERT(oop == NULL);
14277 			ASSERT(osp == NULL);
14278 			ASSERT(lop == NULL);
14279 			goto recov_retry;
14280 		}
14281 		goto out;
14282 	}
14283 
14284 	/*
14285 	 * Bail out if have reached this point with ep->error set. Can
14286 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14287 	 * This happens if Kerberos ticket has expired or has been
14288 	 * destroyed.
14289 	 */
14290 	if (ep->error != 0)
14291 		goto out;
14292 
14293 	/*
14294 	 * Process the reply.
14295 	 */
14296 	switch (resp->status) {
14297 	case NFS4_OK:
14298 		resop = &resp->array[1];
14299 		nfs4frlock_results_ok(ctype, cmd, flk, vp, flag, offset,
14300 			resend_rqstp);
14301 		/*
14302 		 * Have a successful lock operation, now update state.
14303 		 */
14304 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14305 			resop, lop, vp, flk, cr, resend_rqstp);
14306 		break;
14307 
14308 	case NFS4ERR_DENIED:
14309 		resop = &resp->array[1];
14310 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14311 				&oop, &osp, &lop, cmd, vp, flk, op_hint,
14312 				&recov_state, needrecov, &argsp, &resp,
14313 				&tick_delay, &whence, &ep->error, resop, cr,
14314 				&did_start_fop, &skip_get_err);
14315 
14316 		if (retry) {
14317 			ASSERT(oop == NULL);
14318 			ASSERT(osp == NULL);
14319 			ASSERT(lop == NULL);
14320 			goto recov_retry;
14321 		}
14322 		break;
14323 	/*
14324 	 * If the server won't let us reclaim, fall-back to trying to lock
14325 	 * the file from scratch. Code elsewhere will check the changeinfo
14326 	 * to ensure the file hasn't been changed.
14327 	 */
14328 	case NFS4ERR_NO_GRACE:
14329 		if (lock_args && lock_args->reclaim == TRUE) {
14330 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14331 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14332 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14333 			frc_no_reclaim = 1;
14334 			/* clean up before retrying */
14335 			needrecov = 0;
14336 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14337 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14338 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14339 			goto recov_retry;
14340 		}
14341 		/* FALLTHROUGH */
14342 
14343 	default:
14344 		nfs4frlock_results_default(resp, &ep->error);
14345 		break;
14346 	}
14347 out:
14348 	/*
14349 	 * Process and cleanup from error.  Make interrupted unlock
14350 	 * requests look successful, since they will be handled by the
14351 	 * client recovery code.
14352 	 */
14353 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14354 		needrecov, oop, osp, lop, flk, whence, offset, ls, &ep->error,
14355 		lock_args, locku_args, did_start_fop,
14356 		skip_get_err, cred_otw, cr);
14357 
14358 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14359 	    (cmd == F_SETLK || cmd == F_SETLKW))
14360 		ep->error = 0;
14361 }
14362 
14363 /*
14364  * nfs4_safelock:
14365  *
14366  * Return non-zero if the given lock request can be handled without
14367  * violating the constraints on concurrent mapping and locking.
14368  */
14369 
14370 static int
14371 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14372 {
14373 	rnode4_t *rp = VTOR4(vp);
14374 	struct vattr va;
14375 	int error;
14376 
14377 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14378 	ASSERT(rp->r_mapcnt >= 0);
14379 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14380 		"(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14381 		"write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14382 		bfp->l_start, bfp->l_len, rp->r_mapcnt));
14383 
14384 	if (rp->r_mapcnt == 0)
14385 		return (1);		/* always safe if not mapped */
14386 
14387 	/*
14388 	 * If the file is already mapped and there are locks, then they
14389 	 * should be all safe locks.  So adding or removing a lock is safe
14390 	 * as long as the new request is safe (i.e., whole-file, meaning
14391 	 * length and starting offset are both zero).
14392 	 */
14393 
14394 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14395 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14396 			"cannot lock a memory mapped file unless locking the "
14397 			"entire file: start %"PRIx64", len %"PRIx64,
14398 			bfp->l_start, bfp->l_len));
14399 		return (0);
14400 	}
14401 
14402 	/* mandatory locking and mapping don't mix */
14403 	va.va_mask = AT_MODE;
14404 	error = VOP_GETATTR(vp, &va, 0, cr);
14405 	if (error != 0) {
14406 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14407 		"getattr error %d", error));
14408 		return (0);		/* treat errors conservatively */
14409 	}
14410 	if (MANDLOCK(vp, va.va_mode)) {
14411 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14412 			"cannot mandatory lock and mmap a file"));
14413 		return (0);
14414 	}
14415 
14416 	return (1);
14417 }
14418 
14419 
14420 /*
14421  * Register the lock locally within Solaris.
14422  * As the client, we "or" the sysid with LM_SYSID_CLIENT when
14423  * recording locks locally.
14424  *
14425  * This should handle conflicts/cooperation with NFS v2/v3 since all locks
14426  * are registered locally.
14427  */
14428 void
14429 nfs4_register_lock_locally(vnode_t *vp, struct flock64 *flk, int flag,
14430 	u_offset_t offset)
14431 {
14432 	int oldsysid;
14433 	int error;
14434 #ifdef DEBUG
14435 	char *name;
14436 #endif
14437 
14438 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14439 
14440 #ifdef DEBUG
14441 	name = fn_name(VTOSV(vp)->sv_name);
14442 	NFS4_DEBUG(nfs4_client_lock_debug,
14443 	    (CE_NOTE, "nfs4_register_lock_locally: %s: type %d, "
14444 	    "start %"PRIx64", length %"PRIx64", pid %ld, sysid %d",
14445 	    name, flk->l_type, flk->l_start, flk->l_len, (long)flk->l_pid,
14446 	    flk->l_sysid));
14447 	kmem_free(name, MAXNAMELEN);
14448 #endif
14449 
14450 	/* register the lock with local locking */
14451 	oldsysid = flk->l_sysid;
14452 	flk->l_sysid |= LM_SYSID_CLIENT;
14453 	error = reclock(vp, flk, SETFLCK, flag, offset, NULL);
14454 #ifdef DEBUG
14455 	if (error != 0) {
14456 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14457 			"nfs4_register_lock_locally: could not register with"
14458 			" local locking"));
14459 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14460 			"error %d, vp 0x%p, pid %d, sysid 0x%x",
14461 			error, (void *)vp, flk->l_pid, flk->l_sysid));
14462 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14463 			"type %d off 0x%" PRIx64 " len 0x%" PRIx64,
14464 			flk->l_type, flk->l_start, flk->l_len));
14465 		(void) reclock(vp, flk, 0, flag, offset, NULL);
14466 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14467 			"blocked by pid %d sysid 0x%x type %d "
14468 			"off 0x%" PRIx64 " len 0x%" PRIx64,
14469 			flk->l_pid, flk->l_sysid, flk->l_type, flk->l_start,
14470 			flk->l_len));
14471 	}
14472 #endif
14473 	flk->l_sysid = oldsysid;
14474 }
14475 
14476 /*
14477  * nfs4_lockrelease:
14478  *
14479  * Release any locks on the given vnode that are held by the current
14480  * process.  Also removes the lock owner (if one exists) from the rnode's
14481  * list.
14482  */
14483 static int
14484 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14485 {
14486 	flock64_t ld;
14487 	int ret, error;
14488 	rnode4_t *rp;
14489 	nfs4_lock_owner_t *lop;
14490 	nfs4_recov_state_t recov_state;
14491 	mntinfo4_t *mi;
14492 	bool_t possible_orphan = FALSE;
14493 	bool_t recovonly;
14494 
14495 	ASSERT((uintptr_t)vp > KERNELBASE);
14496 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14497 
14498 	rp = VTOR4(vp);
14499 	mi = VTOMI4(vp);
14500 
14501 	/*
14502 	 * If we have not locked anything then we can
14503 	 * just return since we have no work to do.
14504 	 */
14505 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14506 		return (0);
14507 	}
14508 
14509 	/*
14510 	 * We need to comprehend that another thread may
14511 	 * kick off recovery and the lock_owner we have stashed
14512 	 * in lop might be invalid so we should NOT cache it
14513 	 * locally!
14514 	 */
14515 	recov_state.rs_flags = 0;
14516 	recov_state.rs_num_retry_despite_err = 0;
14517 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14518 			    &recovonly);
14519 	if (error) {
14520 		mutex_enter(&rp->r_statelock);
14521 		rp->r_flags |= R4LODANGLERS;
14522 		mutex_exit(&rp->r_statelock);
14523 		return (error);
14524 	}
14525 
14526 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14527 
14528 	/*
14529 	 * Check if the lock owner might have a lock (request was sent but
14530 	 * no response was received).  Also check if there are any remote
14531 	 * locks on the file.  (In theory we shouldn't have to make this
14532 	 * second check if there's no lock owner, but for now we'll be
14533 	 * conservative and do it anyway.)  If either condition is true,
14534 	 * send an unlock for the entire file to the server.
14535 	 *
14536 	 * Note that no explicit synchronization is needed here.  At worst,
14537 	 * flk_has_remote_locks() will return a false positive, in which case
14538 	 * the unlock call wastes time but doesn't harm correctness.
14539 	 */
14540 
14541 	if (lop) {
14542 		mutex_enter(&lop->lo_lock);
14543 		possible_orphan = lop->lo_pending_rqsts;
14544 		mutex_exit(&lop->lo_lock);
14545 		lock_owner_rele(lop);
14546 	}
14547 
14548 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14549 
14550 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14551 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14552 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14553 	    (void *)lop));
14554 
14555 	if (possible_orphan || flk_has_remote_locks(vp)) {
14556 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14557 		ld.l_whence = 0;	/* unlock from start of file */
14558 		ld.l_start = 0;
14559 		ld.l_len = 0;		/* do entire file */
14560 
14561 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL, cr);
14562 
14563 		if (ret != 0) {
14564 			/*
14565 			 * If VOP_FRLOCK fails, make sure we unregister
14566 			 * local locks before we continue.
14567 			 */
14568 			ld.l_pid = ttoproc(curthread)->p_pid;
14569 			nfs4_register_lock_locally(vp, &ld, flag, offset);
14570 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14571 				"nfs4_lockrelease: lock release error on vp"
14572 				" %p: error %d.\n", (void *)vp, ret));
14573 		}
14574 	}
14575 
14576 	recov_state.rs_flags = 0;
14577 	recov_state.rs_num_retry_despite_err = 0;
14578 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14579 			    &recovonly);
14580 	if (error) {
14581 		mutex_enter(&rp->r_statelock);
14582 		rp->r_flags |= R4LODANGLERS;
14583 		mutex_exit(&rp->r_statelock);
14584 		return (error);
14585 	}
14586 
14587 	/*
14588 	 * So, here we're going to need to retrieve the lock-owner
14589 	 * again (in case recovery has done a switch-a-roo) and
14590 	 * remove it because we can.
14591 	 */
14592 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14593 
14594 	if (lop) {
14595 		nfs4_rnode_remove_lock_owner(rp, lop);
14596 		lock_owner_rele(lop);
14597 	}
14598 
14599 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14600 	return (0);
14601 }
14602 
14603 /*
14604  * Wait for 'tick_delay' clock ticks.
14605  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14606  * NOTE: lock_lease_time is in seconds.
14607  *
14608  * XXX For future improvements, should implement a waiting queue scheme.
14609  */
14610 static int
14611 nfs4_block_and_wait(clock_t *tick_delay, rnode4_t *rp)
14612 {
14613 	long milliseconds_delay;
14614 	time_t lock_lease_time;
14615 
14616 	/* wait tick_delay clock ticks or siginteruptus */
14617 	if (delay_sig(*tick_delay)) {
14618 		return (EINTR);
14619 	}
14620 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14621 		"reissue the lock request: blocked for %ld clock ticks: %ld "
14622 		"milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14623 
14624 	/* get the lease time */
14625 	lock_lease_time = r2lease_time(rp);
14626 
14627 	/* drv_hztousec converts ticks to microseconds */
14628 	milliseconds_delay = drv_hztousec(*tick_delay) / 1000;
14629 	if (milliseconds_delay < lock_lease_time * 1000) {
14630 		*tick_delay = 2 * *tick_delay;
14631 		if (drv_hztousec(*tick_delay) > lock_lease_time * 1000 * 1000)
14632 			*tick_delay = drv_usectohz(lock_lease_time*1000*1000);
14633 	}
14634 	return (0);
14635 }
14636 
14637 
14638 void
14639 nfs4_vnops_init(void)
14640 {
14641 }
14642 
14643 void
14644 nfs4_vnops_fini(void)
14645 {
14646 }
14647 
14648 /*
14649  * Return a reference to the directory (parent) vnode for a given vnode,
14650  * using the saved pathname information and the directory file handle.  The
14651  * caller is responsible for disposing of the reference.
14652  * Returns zero or an errno value.
14653  *
14654  * Caller should set need_start_op to FALSE if it is the recovery
14655  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14656  */
14657 int
14658 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14659 {
14660 	svnode_t *svnp;
14661 	vnode_t *dvp = NULL;
14662 	servinfo4_t *svp;
14663 	nfs4_fname_t *mfname;
14664 	int error;
14665 
14666 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14667 
14668 	if (vp->v_flag & VROOT) {
14669 		nfs4_sharedfh_t *sfh;
14670 		nfs_fh4 fh;
14671 		mntinfo4_t *mi;
14672 
14673 		ASSERT(vp->v_type == VREG);
14674 
14675 		mi = VTOMI4(vp);
14676 		svp = mi->mi_curr_serv;
14677 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14678 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14679 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14680 		sfh = sfh4_get(&fh, VTOMI4(vp));
14681 		nfs_rw_exit(&svp->sv_lock);
14682 		mfname = mi->mi_fname;
14683 		fn_hold(mfname);
14684 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14685 		sfh4_rele(&sfh);
14686 
14687 		if (dvp->v_type == VNON)
14688 			dvp->v_type = VDIR;
14689 		*dvpp = dvp;
14690 		return (0);
14691 	}
14692 
14693 	svnp = VTOSV(vp);
14694 
14695 	if (svnp == NULL) {
14696 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14697 			"shadow node is NULL"));
14698 		return (EINVAL);
14699 	}
14700 
14701 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14702 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14703 			"shadow node name or dfh val == NULL"));
14704 		return (EINVAL);
14705 	}
14706 
14707 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14708 							(int)need_start_op);
14709 	if (error != 0) {
14710 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14711 			"nfs4_make_dotdot returned %d", error));
14712 		return (error);
14713 	}
14714 	if (!dvp) {
14715 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14716 			"nfs4_make_dotdot returned a NULL dvp"));
14717 		return (EIO);
14718 	}
14719 	if (dvp->v_type == VNON)
14720 		dvp->v_type = VDIR;
14721 	ASSERT(dvp->v_type == VDIR);
14722 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14723 		mutex_enter(&dvp->v_lock);
14724 		dvp->v_flag |= V_XATTRDIR;
14725 		mutex_exit(&dvp->v_lock);
14726 	}
14727 	*dvpp = dvp;
14728 	return (0);
14729 }
14730 
14731 /*
14732  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14733  * length that fnamep can accept, including the trailing null.
14734  * Returns 0 if okay, returns an errno value if there was a problem.
14735  */
14736 
14737 int
14738 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14739 {
14740 	char *fn;
14741 	int err = 0;
14742 	servinfo4_t *svp;
14743 	svnode_t *shvp;
14744 
14745 	/*
14746 	 * If the file being opened has VROOT set, then this is
14747 	 * a "file" mount.  sv_name will not be interesting, so
14748 	 * go back to the servinfo4 to get the original mount
14749 	 * path and strip off all but the final edge.  Otherwise
14750 	 * just return the name from the shadow vnode.
14751 	 */
14752 
14753 	if (vp->v_flag & VROOT) {
14754 
14755 		svp = VTOMI4(vp)->mi_curr_serv;
14756 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14757 
14758 		fn = strrchr(svp->sv_path, '/');
14759 		if (fn == NULL)
14760 			err = EINVAL;
14761 		else
14762 			fn++;
14763 	} else {
14764 		shvp = VTOSV(vp);
14765 		fn = fn_name(shvp->sv_name);
14766 	}
14767 
14768 	if (err == 0)
14769 		if (strlen(fn) < maxlen)
14770 			(void) strcpy(fnamep, fn);
14771 		else
14772 			err = ENAMETOOLONG;
14773 
14774 	if (vp->v_flag & VROOT)
14775 		nfs_rw_exit(&svp->sv_lock);
14776 	else
14777 		kmem_free(fn, MAXNAMELEN);
14778 
14779 	return (err);
14780 }
14781 
14782 /*
14783  * Bookkeeping for a close that doesn't need to go over the wire.
14784  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14785  * it is left at 1.
14786  */
14787 void
14788 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14789 {
14790 	rnode4_t		*rp;
14791 	mntinfo4_t		*mi;
14792 
14793 	mi = VTOMI4(vp);
14794 	rp = VTOR4(vp);
14795 
14796 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14797 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14798 	ASSERT(nfs_zone() == mi->mi_zone);
14799 	ASSERT(mutex_owned(&osp->os_sync_lock));
14800 	ASSERT(*have_lockp);
14801 
14802 	if (!osp->os_valid ||
14803 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14804 		return;
14805 	}
14806 
14807 	/*
14808 	 * This removes the reference obtained at OPEN; ie,
14809 	 * when the open stream structure was created.
14810 	 *
14811 	 * We don't have to worry about calling 'open_stream_rele'
14812 	 * since we our currently holding a reference to this
14813 	 * open stream which means the count can not go to 0 with
14814 	 * this decrement.
14815 	 */
14816 	ASSERT(osp->os_ref_count >= 2);
14817 	osp->os_ref_count--;
14818 	osp->os_valid = 0;
14819 	mutex_exit(&osp->os_sync_lock);
14820 	*have_lockp = 0;
14821 
14822 	nfs4_dec_state_ref_count(mi);
14823 }
14824 
14825 /*
14826  * Close all remaining open streams on the rnode.  These open streams
14827  * could be here because:
14828  * - The close attempted at either close or delmap failed
14829  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
14830  * - Someone did mknod on a regular file but never opened it
14831  */
14832 int
14833 nfs4close_all(vnode_t *vp, cred_t *cr)
14834 {
14835 	nfs4_open_stream_t *osp;
14836 	int error;
14837 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
14838 	rnode4_t *rp;
14839 
14840 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14841 
14842 	error = 0;
14843 	rp = VTOR4(vp);
14844 
14845 	/*
14846 	 * At this point, all we know is that the last time
14847 	 * someone called vn_rele, the count was 1.  Since then,
14848 	 * the vnode could have been re-activated.  We want to
14849 	 * loop through the open streams and close each one, but
14850 	 * we have to be careful since once we release the rnode
14851 	 * hash bucket lock, someone else is free to come in and
14852 	 * re-activate the rnode and add new open streams.  The
14853 	 * strategy is take the rnode hash bucket lock, verify that
14854 	 * the count is still 1, grab the open stream off the
14855 	 * head of the list and mark it invalid, then release the
14856 	 * rnode hash bucket lock and proceed with that open stream.
14857 	 * This is ok because nfs4close_one() will acquire the proper
14858 	 * open/create to close/destroy synchronization for open
14859 	 * streams, and will ensure that if someone has reopened
14860 	 * the open stream after we've dropped the hash bucket lock
14861 	 * then we'll just simply return without destroying the
14862 	 * open stream.
14863 	 * Repeat until the list is empty.
14864 	 */
14865 
14866 	for (;;) {
14867 
14868 		/* make sure vnode hasn't been reactivated */
14869 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
14870 		mutex_enter(&vp->v_lock);
14871 		if (vp->v_count > 1) {
14872 			mutex_exit(&vp->v_lock);
14873 			rw_exit(&rp->r_hashq->r_lock);
14874 			break;
14875 		}
14876 		/*
14877 		 * Grabbing r_os_lock before releasing v_lock prevents
14878 		 * a window where the rnode/open stream could get
14879 		 * reactivated (and os_force_close set to 0) before we
14880 		 * had a chance to set os_force_close to 1.
14881 		 */
14882 		mutex_enter(&rp->r_os_lock);
14883 		mutex_exit(&vp->v_lock);
14884 
14885 		osp = list_head(&rp->r_open_streams);
14886 		if (!osp) {
14887 			/* nothing left to CLOSE OTW, so return */
14888 			mutex_exit(&rp->r_os_lock);
14889 			rw_exit(&rp->r_hashq->r_lock);
14890 			break;
14891 		}
14892 
14893 		mutex_enter(&rp->r_statev4_lock);
14894 		/* the file can't still be mem mapped */
14895 		ASSERT(rp->r_mapcnt == 0);
14896 		if (rp->created_v4)
14897 			rp->created_v4 = 0;
14898 		mutex_exit(&rp->r_statev4_lock);
14899 
14900 		/*
14901 		 * Grab a ref on this open stream; nfs4close_one
14902 		 * will mark it as invalid
14903 		 */
14904 		mutex_enter(&osp->os_sync_lock);
14905 		osp->os_ref_count++;
14906 		osp->os_force_close = 1;
14907 		mutex_exit(&osp->os_sync_lock);
14908 		mutex_exit(&rp->r_os_lock);
14909 		rw_exit(&rp->r_hashq->r_lock);
14910 
14911 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
14912 
14913 		/* Update error if it isn't already non-zero */
14914 		if (error == 0) {
14915 			if (e.error)
14916 				error = e.error;
14917 			else if (e.stat)
14918 				error = geterrno4(e.stat);
14919 		}
14920 
14921 #ifdef	DEBUG
14922 		nfs4close_all_cnt++;
14923 #endif
14924 		/* Release the ref on osp acquired above. */
14925 		open_stream_rele(osp, rp);
14926 
14927 		/* Proceed to the next open stream, if any */
14928 	}
14929 	return (error);
14930 }
14931 
14932 /*
14933  * nfs4close_one - close one open stream for a file if needed.
14934  *
14935  * "close_type" indicates which close path this is:
14936  * CLOSE_NORM: close initiated via VOP_CLOSE.
14937  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
14938  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
14939  *	the close and release of client state for this open stream
14940  *	(unless someone else has the open stream open).
14941  * CLOSE_RESEND: indicates the request is a replay of an earlier request
14942  *	(e.g., due to abort because of a signal).
14943  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
14944  *
14945  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
14946  * recovery.  Instead, the caller is expected to deal with retries.
14947  *
14948  * The caller can either pass in the osp ('provided_osp') or not.
14949  *
14950  * 'access_bits' represents the access we are closing/downgrading.
14951  *
14952  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
14953  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
14954  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
14955  *
14956  * Errors are returned via the nfs4_error_t.
14957  */
14958 void
14959 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
14960 	int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
14961 	nfs4_close_type_t close_type, size_t len, uint_t maxprot,
14962 	uint_t mmap_flags)
14963 {
14964 	nfs4_open_owner_t *oop;
14965 	nfs4_open_stream_t *osp = NULL;
14966 	int retry = 0;
14967 	int num_retries = NFS4_NUM_RECOV_RETRIES;
14968 	rnode4_t *rp;
14969 	mntinfo4_t *mi;
14970 	nfs4_recov_state_t recov_state;
14971 	cred_t *cred_otw = NULL;
14972 	bool_t recovonly = FALSE;
14973 	int isrecov;
14974 	int force_close;
14975 	int close_failed = 0;
14976 	int did_dec_count = 0;
14977 	int did_start_op = 0;
14978 	int did_force_recovlock = 0;
14979 	int did_start_seqid_sync = 0;
14980 	int have_sync_lock = 0;
14981 
14982 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14983 
14984 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
14985 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
14986 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
14987 	    len, maxprot, mmap_flags, access_bits));
14988 
14989 	nfs4_error_zinit(ep);
14990 	rp = VTOR4(vp);
14991 	mi = VTOMI4(vp);
14992 	isrecov = (close_type == CLOSE_RESEND ||
14993 			close_type == CLOSE_AFTER_RESEND);
14994 
14995 	/*
14996 	 * First get the open owner.
14997 	 */
14998 	if (!provided_osp) {
14999 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
15000 	} else {
15001 		oop = provided_osp->os_open_owner;
15002 		ASSERT(oop != NULL);
15003 		open_owner_hold(oop);
15004 	}
15005 
15006 	if (!oop) {
15007 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15008 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15009 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15010 		    (void *)provided_osp, close_type));
15011 		ep->error = EIO;
15012 		goto out;
15013 	}
15014 
15015 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15016 recov_retry:
15017 	osp = NULL;
15018 	close_failed = 0;
15019 	force_close = (close_type == CLOSE_FORCE);
15020 	retry = 0;
15021 	did_start_op = 0;
15022 	did_force_recovlock = 0;
15023 	did_start_seqid_sync = 0;
15024 	have_sync_lock = 0;
15025 	recovonly = FALSE;
15026 	recov_state.rs_flags = 0;
15027 	recov_state.rs_num_retry_despite_err = 0;
15028 
15029 	/*
15030 	 * Second synchronize with recovery.
15031 	 */
15032 	if (!isrecov) {
15033 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15034 				&recov_state, &recovonly);
15035 		if (!ep->error) {
15036 			did_start_op = 1;
15037 		} else {
15038 			close_failed = 1;
15039 			/*
15040 			 * If we couldn't get start_fop, but have to
15041 			 * cleanup state, then at least acquire the
15042 			 * mi_recovlock so we can synchronize with
15043 			 * recovery.
15044 			 */
15045 			if (close_type == CLOSE_FORCE) {
15046 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15047 					RW_READER, FALSE);
15048 				did_force_recovlock = 1;
15049 			} else
15050 				goto out;
15051 		}
15052 	}
15053 
15054 	/*
15055 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15056 	 * set 'recovonly' to TRUE since most likely this is due to
15057 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15058 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15059 	 * to retry, causing us to loop until recovery finishes.  Plus we
15060 	 * don't need protection over the open seqid since we're not going
15061 	 * OTW, hence don't need to use the seqid.
15062 	 */
15063 	if (recovonly == FALSE) {
15064 		/* need to grab the open owner sync before 'os_sync_lock' */
15065 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15066 		if (ep->error == EAGAIN) {
15067 			ASSERT(!isrecov);
15068 			if (did_start_op)
15069 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15070 					&recov_state, TRUE);
15071 			if (did_force_recovlock)
15072 				nfs_rw_exit(&mi->mi_recovlock);
15073 			goto recov_retry;
15074 		}
15075 		did_start_seqid_sync = 1;
15076 	}
15077 
15078 	/*
15079 	 * Third get an open stream and acquire 'os_sync_lock' to
15080 	 * sychronize the opening/creating of an open stream with the
15081 	 * closing/destroying of an open stream.
15082 	 */
15083 	if (!provided_osp) {
15084 		/* returns with 'os_sync_lock' held */
15085 		osp = find_open_stream(oop, rp);
15086 		if (!osp) {
15087 			ep->error = EIO;
15088 			goto out;
15089 		}
15090 	} else {
15091 		osp = provided_osp;
15092 		open_stream_hold(osp);
15093 		mutex_enter(&osp->os_sync_lock);
15094 	}
15095 	have_sync_lock = 1;
15096 
15097 	ASSERT(oop == osp->os_open_owner);
15098 
15099 	/*
15100 	 * Fourth, do any special pre-OTW CLOSE processing
15101 	 * based on the specific close type.
15102 	 */
15103 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15104 	    !did_dec_count) {
15105 		ASSERT(osp->os_open_ref_count > 0);
15106 		osp->os_open_ref_count--;
15107 		did_dec_count = 1;
15108 		if (osp->os_open_ref_count == 0)
15109 			osp->os_final_close = 1;
15110 	}
15111 
15112 	if (close_type == CLOSE_FORCE) {
15113 		/* see if somebody reopened the open stream. */
15114 		if (!osp->os_force_close) {
15115 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15116 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15117 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15118 			ep->error = 0;
15119 			ep->stat = NFS4_OK;
15120 			goto out;
15121 		}
15122 
15123 		if (!osp->os_final_close && !did_dec_count) {
15124 			osp->os_open_ref_count--;
15125 			did_dec_count = 1;
15126 		}
15127 
15128 		/*
15129 		 * We can't depend on os_open_ref_count being 0 due to the
15130 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15131 		 */
15132 #ifdef	NOTYET
15133 		ASSERT(osp->os_open_ref_count == 0);
15134 #endif
15135 		if (osp->os_open_ref_count != 0) {
15136 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15137 			    "nfs4close_one: should panic here on an "
15138 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15139 			    "since this is probably the exec problem."));
15140 
15141 			osp->os_open_ref_count = 0;
15142 		}
15143 
15144 		/*
15145 		 * There is the possibility that nfs4close_one()
15146 		 * for close_type == CLOSE_DELMAP couldn't find the
15147 		 * open stream, thus couldn't decrement its os_mapcnt;
15148 		 * therefore we can't use this ASSERT yet.
15149 		 */
15150 #ifdef	NOTYET
15151 		ASSERT(osp->os_mapcnt == 0);
15152 #endif
15153 		osp->os_mapcnt = 0;
15154 	}
15155 
15156 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15157 		ASSERT(osp->os_mapcnt >= btopr(len));
15158 
15159 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15160 			osp->os_mmap_write -= btopr(len);
15161 		if (maxprot & PROT_READ)
15162 			osp->os_mmap_read -= btopr(len);
15163 		if (maxprot & PROT_EXEC)
15164 			osp->os_mmap_read -= btopr(len);
15165 		/* mirror the PROT_NONE check in nfs4_addmap() */
15166 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15167 		    !(maxprot & PROT_EXEC))
15168 			osp->os_mmap_read -= btopr(len);
15169 		osp->os_mapcnt -= btopr(len);
15170 		did_dec_count = 1;
15171 	}
15172 
15173 	if (recovonly) {
15174 		nfs4_lost_rqst_t lost_rqst;
15175 
15176 		/* request should not already be in recovery queue */
15177 		ASSERT(lrp == NULL);
15178 		nfs4_error_init(ep, EINTR);
15179 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15180 			osp, cred_otw, vp);
15181 		mutex_exit(&osp->os_sync_lock);
15182 		have_sync_lock = 0;
15183 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15184 				lost_rqst.lr_op == OP_CLOSE ?
15185 				&lost_rqst : NULL, OP_CLOSE, NULL);
15186 		close_failed = 1;
15187 		force_close = 0;
15188 		goto close_cleanup;
15189 	}
15190 
15191 	/*
15192 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15193 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15194 	 * space, which means we stopped operating on the open stream
15195 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15196 	 * stateid could be stale, potentially triggering a false
15197 	 * setclientid), and just clean up the client's internal state.
15198 	 */
15199 	if (osp->os_orig_oo_name != oop->oo_name) {
15200 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15201 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15202 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15203 		    "oo_name %" PRIx64")",
15204 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15205 		    oop->oo_name));
15206 		close_failed = 1;
15207 	}
15208 
15209 	/* If the file failed recovery, just quit. */
15210 	mutex_enter(&rp->r_statelock);
15211 	if (rp->r_flags & R4RECOVERR) {
15212 		close_failed = 1;
15213 	}
15214 	mutex_exit(&rp->r_statelock);
15215 
15216 	/*
15217 	 * If the force close path failed to obtain start_fop
15218 	 * then skip the OTW close and just remove the state.
15219 	 */
15220 	if (close_failed)
15221 		goto close_cleanup;
15222 
15223 	/*
15224 	 * Fifth, check to see if there are still mapped pages or other
15225 	 * opens using this open stream.  If there are then we can't
15226 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15227 	 */
15228 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15229 		nfs4_lost_rqst_t	new_lost_rqst;
15230 		bool_t			needrecov = FALSE;
15231 		cred_t			*odg_cred_otw = NULL;
15232 		seqid4			open_dg_seqid = 0;
15233 
15234 		if (osp->os_delegation) {
15235 			/*
15236 			 * If this open stream was never OPENed OTW then we
15237 			 * surely can't DOWNGRADE it (especially since the
15238 			 * osp->open_stateid is really a delegation stateid
15239 			 * when os_delegation is 1).
15240 			 */
15241 			if (access_bits & FREAD)
15242 				osp->os_share_acc_read--;
15243 			if (access_bits & FWRITE)
15244 				osp->os_share_acc_write--;
15245 			osp->os_share_deny_none--;
15246 			nfs4_error_zinit(ep);
15247 			goto out;
15248 		}
15249 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15250 				lrp, ep, &odg_cred_otw, &open_dg_seqid);
15251 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15252 		if (needrecov && !isrecov) {
15253 			bool_t abort;
15254 			nfs4_bseqid_entry_t *bsep = NULL;
15255 
15256 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15257 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15258 					vp, 0,
15259 					lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15260 					open_dg_seqid);
15261 
15262 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15263 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15264 			mutex_exit(&osp->os_sync_lock);
15265 			have_sync_lock = 0;
15266 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15267 				    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15268 				    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15269 				    bsep);
15270 			if (odg_cred_otw)
15271 				crfree(odg_cred_otw);
15272 			if (bsep)
15273 				kmem_free(bsep, sizeof (*bsep));
15274 
15275 			if (abort == TRUE)
15276 				goto out;
15277 
15278 			if (did_start_seqid_sync) {
15279 				nfs4_end_open_seqid_sync(oop);
15280 				did_start_seqid_sync = 0;
15281 			}
15282 			open_stream_rele(osp, rp);
15283 
15284 			if (did_start_op)
15285 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15286 					&recov_state, FALSE);
15287 			if (did_force_recovlock)
15288 				nfs_rw_exit(&mi->mi_recovlock);
15289 
15290 			goto recov_retry;
15291 		} else {
15292 			if (odg_cred_otw)
15293 				crfree(odg_cred_otw);
15294 		}
15295 		goto out;
15296 	}
15297 
15298 	/*
15299 	 * If this open stream was created as the results of an open
15300 	 * while holding a delegation, then just release it; no need
15301 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15302 	 */
15303 	if (osp->os_delegation) {
15304 		nfs4close_notw(vp, osp, &have_sync_lock);
15305 		nfs4_error_zinit(ep);
15306 		goto out;
15307 	}
15308 
15309 	/*
15310 	 * If this stream is not valid, we're done.
15311 	 */
15312 	if (!osp->os_valid) {
15313 		nfs4_error_zinit(ep);
15314 		goto out;
15315 	}
15316 
15317 	/*
15318 	 * Last open or mmap ref has vanished, need to do an OTW close.
15319 	 * First check to see if a close is still necessary.
15320 	 */
15321 	if (osp->os_failed_reopen) {
15322 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15323 		    "don't close OTW osp %p since reopen failed.",
15324 		    (void *)osp));
15325 		/*
15326 		 * Reopen of the open stream failed, hence the
15327 		 * stateid of the open stream is invalid/stale, and
15328 		 * sending this OTW would incorrectly cause another
15329 		 * round of recovery.  In this case, we need to set
15330 		 * the 'os_valid' bit to 0 so another thread doesn't
15331 		 * come in and re-open this open stream before
15332 		 * this "closing" thread cleans up state (decrementing
15333 		 * the nfs4_server_t's state_ref_count and decrementing
15334 		 * the os_ref_count).
15335 		 */
15336 		osp->os_valid = 0;
15337 		/*
15338 		 * This removes the reference obtained at OPEN; ie,
15339 		 * when the open stream structure was created.
15340 		 *
15341 		 * We don't have to worry about calling 'open_stream_rele'
15342 		 * since we our currently holding a reference to this
15343 		 * open stream which means the count can not go to 0 with
15344 		 * this decrement.
15345 		 */
15346 		ASSERT(osp->os_ref_count >= 2);
15347 		osp->os_ref_count--;
15348 		nfs4_error_zinit(ep);
15349 		close_failed = 0;
15350 		goto close_cleanup;
15351 	}
15352 
15353 	ASSERT(osp->os_ref_count > 1);
15354 
15355 	/*
15356 	 * Sixth, try the CLOSE OTW.
15357 	 */
15358 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15359 	    close_type, ep, &have_sync_lock);
15360 
15361 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15362 		/*
15363 		 * Let the recovery thread be responsible for
15364 		 * removing the state for CLOSE.
15365 		 */
15366 		close_failed = 1;
15367 		force_close = 0;
15368 		retry = 0;
15369 	}
15370 
15371 	/* See if we need to retry with a different cred */
15372 	if ((ep->error == EACCES ||
15373 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15374 	    cred_otw != cr) {
15375 		crfree(cred_otw);
15376 		cred_otw = cr;
15377 		crhold(cred_otw);
15378 		retry = 1;
15379 	}
15380 
15381 	if (ep->error || ep->stat)
15382 		close_failed = 1;
15383 
15384 	if (retry && !isrecov && num_retries-- > 0) {
15385 		if (have_sync_lock) {
15386 			mutex_exit(&osp->os_sync_lock);
15387 			have_sync_lock = 0;
15388 		}
15389 		if (did_start_seqid_sync) {
15390 			nfs4_end_open_seqid_sync(oop);
15391 			did_start_seqid_sync = 0;
15392 		}
15393 		open_stream_rele(osp, rp);
15394 
15395 		if (did_start_op)
15396 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15397 				&recov_state, FALSE);
15398 		if (did_force_recovlock)
15399 			nfs_rw_exit(&mi->mi_recovlock);
15400 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15401 			"nfs4close_one: need to retry the close "
15402 			"operation"));
15403 		goto recov_retry;
15404 	}
15405 close_cleanup:
15406 	/*
15407 	 * Seventh and lastly, process our results.
15408 	 */
15409 	if (close_failed && force_close) {
15410 		/*
15411 		 * It's ok to drop and regrab the 'os_sync_lock' since
15412 		 * nfs4close_notw() will recheck to make sure the
15413 		 * "close"/removal of state should happen.
15414 		 */
15415 		if (!have_sync_lock) {
15416 			mutex_enter(&osp->os_sync_lock);
15417 			have_sync_lock = 1;
15418 		}
15419 		/*
15420 		 * This is last call, remove the ref on the open
15421 		 * stream created by open and clean everything up.
15422 		 */
15423 		osp->os_pending_close = 0;
15424 		nfs4close_notw(vp, osp, &have_sync_lock);
15425 		nfs4_error_zinit(ep);
15426 	}
15427 
15428 	if (!close_failed) {
15429 		if (have_sync_lock) {
15430 			osp->os_pending_close = 0;
15431 			mutex_exit(&osp->os_sync_lock);
15432 			have_sync_lock = 0;
15433 		} else {
15434 			mutex_enter(&osp->os_sync_lock);
15435 			osp->os_pending_close = 0;
15436 			mutex_exit(&osp->os_sync_lock);
15437 		}
15438 		if (did_start_op && recov_state.rs_sp != NULL) {
15439 			mutex_enter(&recov_state.rs_sp->s_lock);
15440 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15441 			mutex_exit(&recov_state.rs_sp->s_lock);
15442 		} else {
15443 			nfs4_dec_state_ref_count(mi);
15444 		}
15445 		nfs4_error_zinit(ep);
15446 	}
15447 
15448 out:
15449 	if (have_sync_lock)
15450 		mutex_exit(&osp->os_sync_lock);
15451 	if (did_start_op)
15452 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15453 		    recovonly ? TRUE : FALSE);
15454 	if (did_force_recovlock)
15455 		nfs_rw_exit(&mi->mi_recovlock);
15456 	if (cred_otw)
15457 		crfree(cred_otw);
15458 	if (osp)
15459 		open_stream_rele(osp, rp);
15460 	if (oop) {
15461 		if (did_start_seqid_sync)
15462 			nfs4_end_open_seqid_sync(oop);
15463 		open_owner_rele(oop);
15464 	}
15465 }
15466 
15467 /*
15468  * Convert information returned by the server in the LOCK4denied
15469  * structure to the form required by fcntl.
15470  */
15471 static void
15472 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15473 {
15474 	nfs4_lo_name_t *lo;
15475 
15476 #ifdef	DEBUG
15477 	if (denied_to_flk_debug) {
15478 		lockt_denied_debug = lockt_denied;
15479 		debug_enter("lockt_denied");
15480 	}
15481 #endif
15482 
15483 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15484 	flk->l_whence = 0;	/* aka SEEK_SET */
15485 	flk->l_start = lockt_denied->offset;
15486 	flk->l_len = lockt_denied->length;
15487 
15488 	/*
15489 	 * If the blocking clientid matches our client id, then we can
15490 	 * interpret the lockowner (since we built it).  If not, then
15491 	 * fabricate a sysid and pid.  Note that the l_sysid field
15492 	 * in *flk already has the local sysid.
15493 	 */
15494 
15495 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15496 
15497 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15498 			lo = (nfs4_lo_name_t *)
15499 				lockt_denied->owner.owner_val;
15500 
15501 			flk->l_pid = lo->ln_pid;
15502 		} else {
15503 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15504 			"denied_to_flk: bad lock owner length\n"));
15505 
15506 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15507 		}
15508 	} else {
15509 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15510 		"denied_to_flk: foreign clientid\n"));
15511 
15512 		/*
15513 		 * Construct a new sysid which should be different from
15514 		 * sysids of other systems.
15515 		 */
15516 
15517 		flk->l_sysid++;
15518 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15519 	}
15520 }
15521 
15522 static pid_t
15523 lo_to_pid(lock_owner4 *lop)
15524 {
15525 	pid_t pid = 0;
15526 	uchar_t *cp;
15527 	int i;
15528 
15529 	cp = (uchar_t *)&lop->clientid;
15530 
15531 	for (i = 0; i < sizeof (lop->clientid); i++)
15532 		pid += (pid_t)*cp++;
15533 
15534 	cp = (uchar_t *)lop->owner_val;
15535 
15536 	for (i = 0; i < lop->owner_len; i++)
15537 		pid += (pid_t)*cp++;
15538 
15539 	return (pid);
15540 }
15541 
15542 /*
15543  * Given a lock pointer, returns the length of that lock.
15544  * "end" is the last locked offset the "l_len" covers from
15545  * the start of the lock.
15546  */
15547 static off64_t
15548 lock_to_end(flock64_t *lock)
15549 {
15550 	off64_t lock_end;
15551 
15552 	if (lock->l_len == 0)
15553 		lock_end = (off64_t)MAXEND;
15554 	else
15555 		lock_end = lock->l_start + lock->l_len - 1;
15556 
15557 	return (lock_end);
15558 }
15559 
15560 /*
15561  * Given the end of a lock, it will return you the length "l_len" for that lock.
15562  */
15563 static off64_t
15564 end_to_len(off64_t start, off64_t end)
15565 {
15566 	off64_t lock_len;
15567 
15568 	ASSERT(end >= start);
15569 	if (end == MAXEND)
15570 		lock_len = 0;
15571 	else
15572 		lock_len = end - start + 1;
15573 
15574 	return (lock_len);
15575 }
15576 
15577 /*
15578  * On given end for a lock it determines if it is the last locked offset
15579  * or not, if so keeps it as is, else adds one to return the length for
15580  * valid start.
15581  */
15582 static off64_t
15583 start_check(off64_t x)
15584 {
15585 	if (x == MAXEND)
15586 		return (x);
15587 	else
15588 		return (x + 1);
15589 }
15590 
15591 /*
15592  * See if these two locks overlap, and if so return 1;
15593  * otherwise, return 0.
15594  */
15595 static int
15596 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15597 {
15598 	off64_t llfp_end, curfp_end;
15599 
15600 	llfp_end = lock_to_end(llfp);
15601 	curfp_end = lock_to_end(curfp);
15602 
15603 	if (((llfp_end >= curfp->l_start) &&
15604 		(llfp->l_start <= curfp->l_start)) ||
15605 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15606 		return (1);
15607 	return (0);
15608 }
15609 
15610 /*
15611  * Determine what the interseting lock region is, and add that to the
15612  * 'nl_llpp' locklist in increasing order (by l_start).
15613  */
15614 static void
15615 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15616 	locklist_t **nl_llpp, vnode_t *vp)
15617 {
15618 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15619 	off64_t lost_flp_end, local_flp_end, len, start;
15620 
15621 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15622 
15623 	if (!locks_intersect(lost_flp, local_flp))
15624 		return;
15625 
15626 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15627 	    "locks intersect"));
15628 
15629 	lost_flp_end = lock_to_end(lost_flp);
15630 	local_flp_end = lock_to_end(local_flp);
15631 
15632 	/* Find the starting point of the intersecting region */
15633 	if (local_flp->l_start > lost_flp->l_start)
15634 		start = local_flp->l_start;
15635 	else
15636 		start = lost_flp->l_start;
15637 
15638 	/* Find the lenght of the intersecting region */
15639 	if (lost_flp_end < local_flp_end)
15640 		len = end_to_len(start, lost_flp_end);
15641 	else
15642 		len = end_to_len(start, local_flp_end);
15643 
15644 	/*
15645 	 * Prepare the flock structure for the intersection found and insert
15646 	 * it into the new list in increasing l_start order. This list contains
15647 	 * intersections of locks registered by the client with the local host
15648 	 * and the lost lock.
15649 	 * The lock type of this lock is the same as that of the local_flp.
15650 	 */
15651 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15652 	intersect_llp->ll_flock.l_start = start;
15653 	intersect_llp->ll_flock.l_len = len;
15654 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15655 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15656 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15657 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15658 	intersect_llp->ll_vp = vp;
15659 
15660 	tmp_fllp = *nl_llpp;
15661 	cur_fllp = NULL;
15662 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15663 		intersect_llp->ll_flock.l_start) {
15664 			cur_fllp = tmp_fllp;
15665 			tmp_fllp = tmp_fllp->ll_next;
15666 	}
15667 	if (cur_fllp == NULL) {
15668 		/* first on the list */
15669 		intersect_llp->ll_next = *nl_llpp;
15670 		*nl_llpp = intersect_llp;
15671 	} else {
15672 		intersect_llp->ll_next = cur_fllp->ll_next;
15673 		cur_fllp->ll_next = intersect_llp;
15674 	}
15675 
15676 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15677 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15678 	    intersect_llp->ll_flock.l_start,
15679 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15680 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15681 }
15682 
15683 /*
15684  * Our local locking current state is potentially different than
15685  * what the NFSv4 server thinks we have due to a lost lock that was
15686  * resent and then received.  We need to reset our "NFSv4" locking
15687  * state to match the current local locking state for this pid since
15688  * that is what the user/application sees as what the world is.
15689  *
15690  * We cannot afford to drop the open/lock seqid sync since then we can
15691  * get confused about what the current local locking state "is" versus
15692  * "was".
15693  *
15694  * If we are unable to fix up the locks, we send SIGLOST to the affected
15695  * process.  This is not done if the filesystem has been forcibly
15696  * unmounted, in case the process has already exited and a new process
15697  * exists with the same pid.
15698  */
15699 static void
15700 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15701 		nfs4_lock_owner_t *lop)
15702 {
15703 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15704 	mntinfo4_t *mi = VTOMI4(vp);
15705 	const int cmd = F_SETLK;
15706 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15707 	flock64_t ul_fl;
15708 
15709 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15710 		"nfs4_reinstitute_local_lock_state"));
15711 
15712 	/*
15713 	 * Find active locks for this vp from the local locking code.
15714 	 * Scan through this list and find out the locks that intersect with
15715 	 * the lost lock. Once we find the lock that intersects, add the
15716 	 * intersection area as a new lock to a new list "ri_llp". The lock
15717 	 * type of the intersection region lock added to ri_llp is the same
15718 	 * as that found in the active lock list, "list". The intersecting
15719 	 * region locks are added to ri_llp in increasing l_start order.
15720 	 */
15721 	ASSERT(nfs_zone() == mi->mi_zone);
15722 
15723 	locks = flk_active_locks_for_vp(vp);
15724 	ri_llp = NULL;
15725 
15726 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15727 		ASSERT(llp->ll_vp == vp);
15728 		/*
15729 		 * Pick locks that belong to this pid/lockowner
15730 		 */
15731 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15732 			continue;
15733 
15734 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15735 	}
15736 
15737 	/*
15738 	 * Now we have the list of intersections with the lost lock. These are
15739 	 * the locks that were/are active before the server replied to the
15740 	 * last/lost lock. Issue these locks to the server here. Playing these
15741 	 * locks to the server will re-establish aur current local locking state
15742 	 * with the v4 server.
15743 	 * If we get an error, send SIGLOST to the application for that lock.
15744 	 */
15745 
15746 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15747 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15748 		    "nfs4_reinstitute_local_lock_state: need to issue "
15749 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15750 		    llp->ll_flock.l_start,
15751 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15752 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15753 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15754 		/*
15755 		 * No need to relock what we already have
15756 		 */
15757 		if (llp->ll_flock.l_type == lost_flp->l_type)
15758 			continue;
15759 
15760 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15761 	}
15762 
15763 	/*
15764 	 * Now keeping the start of the lost lock as our reference parse the
15765 	 * newly created ri_llp locklist to find the ranges that we have locked
15766 	 * with the v4 server but not in the current local locking. We need
15767 	 * to unlock these ranges.
15768 	 * These ranges can also be reffered to as those ranges, where the lost
15769 	 * lock does not overlap with the locks in the ri_llp but are locked
15770 	 * since the server replied to the lost lock.
15771 	 */
15772 	cur_start = lost_flp->l_start;
15773 	lost_flp_end = lock_to_end(lost_flp);
15774 
15775 	ul_fl.l_type = F_UNLCK;
15776 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15777 	ul_fl.l_sysid = lost_flp->l_sysid;
15778 	ul_fl.l_pid = lost_flp->l_pid;
15779 
15780 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15781 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15782 
15783 		if (llp->ll_flock.l_start <= cur_start) {
15784 			cur_start = start_check(llp_ll_flock_end);
15785 			continue;
15786 		}
15787 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15788 			"nfs4_reinstitute_local_lock_state: "
15789 			"UNLOCK [%"PRIx64" - %"PRIx64"]",
15790 			cur_start, llp->ll_flock.l_start));
15791 
15792 		ul_fl.l_start = cur_start;
15793 		ul_fl.l_len = end_to_len(cur_start,
15794 		    (llp->ll_flock.l_start - 1));
15795 
15796 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15797 		cur_start = start_check(llp_ll_flock_end);
15798 	}
15799 
15800 	/*
15801 	 * In the case where the lost lock ends after all intersecting locks,
15802 	 * unlock the last part of the lost lock range.
15803 	 */
15804 	if (cur_start != start_check(lost_flp_end)) {
15805 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15806 			"nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15807 			"lost lock region [%"PRIx64" - %"PRIx64"]",
15808 			cur_start, lost_flp->l_start + lost_flp->l_len));
15809 
15810 		ul_fl.l_start = cur_start;
15811 		/*
15812 		 * Is it an to-EOF lock? if so unlock till the end
15813 		 */
15814 		if (lost_flp->l_len == 0)
15815 			ul_fl.l_len = 0;
15816 		else
15817 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15818 
15819 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15820 	}
15821 
15822 	if (locks != NULL)
15823 		flk_free_locklist(locks);
15824 
15825 	/* Free up our newly created locklist */
15826 	for (llp = ri_llp; llp != NULL; ) {
15827 		tmp_llp = llp->ll_next;
15828 		kmem_free(llp, sizeof (locklist_t));
15829 		llp = tmp_llp;
15830 	}
15831 
15832 	/*
15833 	 * Now return back to the original calling nfs4frlock()
15834 	 * and let us naturally drop our seqid syncs.
15835 	 */
15836 }
15837 
15838 /*
15839  * Create a lost state record for the given lock reinstantiation request
15840  * and push it onto the lost state queue.
15841  */
15842 static void
15843 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
15844 	nfs4_lock_owner_t *lop)
15845 {
15846 	nfs4_lost_rqst_t req;
15847 	nfs_lock_type4 locktype;
15848 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
15849 
15850 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15851 
15852 	locktype = flk_to_locktype(cmd, flk->l_type);
15853 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
15854 				NULL, NULL, lop, flk, &req, cr, vp);
15855 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
15856 		    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
15857 		    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
15858 		    NULL);
15859 }
15860