xref: /titanic_52/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision 8d96d5b3a759119baa5937624b8716c8abb4d572)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  *	Copyright 1983,1984,1985,1986,1987,1988,1989 AT&T.
29  *	All Rights Reserved
30  */
31 
32 #pragma ident	"%Z%%M%	%I%	%E% SMI"
33 
34 #include <sys/param.h>
35 #include <sys/types.h>
36 #include <sys/systm.h>
37 #include <sys/cred.h>
38 #include <sys/time.h>
39 #include <sys/vnode.h>
40 #include <sys/vfs.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 nfs4_open_stream_t *open_and_get_osp(vnode_t *, cred_t *, mntinfo4_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, nfs4_open,
368 	VOPNAME_CLOSE, nfs4_close,
369 	VOPNAME_READ, nfs4_read,
370 	VOPNAME_WRITE, nfs4_write,
371 	VOPNAME_IOCTL, nfs4_ioctl,
372 	VOPNAME_GETATTR, nfs4_getattr,
373 	VOPNAME_SETATTR, nfs4_setattr,
374 	VOPNAME_ACCESS, nfs4_access,
375 	VOPNAME_LOOKUP, nfs4_lookup,
376 	VOPNAME_CREATE, nfs4_create,
377 	VOPNAME_REMOVE, nfs4_remove,
378 	VOPNAME_LINK, nfs4_link,
379 	VOPNAME_RENAME, nfs4_rename,
380 	VOPNAME_MKDIR, nfs4_mkdir,
381 	VOPNAME_RMDIR, nfs4_rmdir,
382 	VOPNAME_READDIR, nfs4_readdir,
383 	VOPNAME_SYMLINK, nfs4_symlink,
384 	VOPNAME_READLINK, nfs4_readlink,
385 	VOPNAME_FSYNC, nfs4_fsync,
386 	VOPNAME_INACTIVE, (fs_generic_func_p) nfs4_inactive,
387 	VOPNAME_FID, nfs4_fid,
388 	VOPNAME_RWLOCK, nfs4_rwlock,
389 	VOPNAME_RWUNLOCK, (fs_generic_func_p) nfs4_rwunlock,
390 	VOPNAME_SEEK, nfs4_seek,
391 	VOPNAME_FRLOCK, nfs4_frlock,
392 	VOPNAME_SPACE, nfs4_space,
393 	VOPNAME_REALVP, nfs4_realvp,
394 	VOPNAME_GETPAGE, nfs4_getpage,
395 	VOPNAME_PUTPAGE, nfs4_putpage,
396 	VOPNAME_MAP, (fs_generic_func_p) nfs4_map,
397 	VOPNAME_ADDMAP, (fs_generic_func_p) nfs4_addmap,
398 	VOPNAME_DELMAP, nfs4_delmap,
399 	VOPNAME_DUMP, nfs_dump,		/* there is no separate nfs4_dump */
400 	VOPNAME_PATHCONF, nfs4_pathconf,
401 	VOPNAME_PAGEIO, nfs4_pageio,
402 	VOPNAME_DISPOSE, (fs_generic_func_p) nfs4_dispose,
403 	VOPNAME_SETSECATTR, nfs4_setsecattr,
404 	VOPNAME_GETSECATTR, nfs4_getsecattr,
405 	VOPNAME_SHRLOCK, nfs4_shrlock,
406 	NULL, NULL
407 };
408 
409 /*
410  * The following are subroutines and definitions to set args or get res
411  * for the different nfsv4 ops
412  */
413 
414 void
415 nfs4args_lookup_free(nfs_argop4 *argop, int arglen)
416 {
417 	int i;
418 
419 	for (i = 0; i < arglen; i++) {
420 	    if (argop[i].argop == OP_LOOKUP)
421 		kmem_free(
422 			argop[i].nfs_argop4_u.oplookup.objname.utf8string_val,
423 			argop[i].nfs_argop4_u.oplookup.objname.utf8string_len);
424 	}
425 }
426 
427 static void
428 nfs4args_lock_free(nfs_argop4 *argop)
429 {
430 	locker4 *locker = &argop->nfs_argop4_u.oplock.locker;
431 
432 	if (locker->new_lock_owner == TRUE) {
433 		open_to_lock_owner4 *open_owner;
434 
435 		open_owner = &locker->locker4_u.open_owner;
436 		if (open_owner->lock_owner.owner_val != NULL) {
437 			kmem_free(open_owner->lock_owner.owner_val,
438 				open_owner->lock_owner.owner_len);
439 		}
440 	}
441 }
442 
443 static void
444 nfs4args_lockt_free(nfs_argop4 *argop)
445 {
446 	lock_owner4 *lowner = &argop->nfs_argop4_u.oplockt.owner;
447 
448 	if (lowner->owner_val != NULL) {
449 		kmem_free(lowner->owner_val, lowner->owner_len);
450 	}
451 }
452 
453 static void
454 nfs4args_setattr(nfs_argop4 *argop, vattr_t *vap, vsecattr_t *vsap, int flags,
455 		rnode4_t *rp, cred_t *cr, bitmap4 supp, int *error,
456 		nfs4_stateid_types_t *sid_types)
457 {
458 	fattr4		*attr = &argop->nfs_argop4_u.opsetattr.obj_attributes;
459 	mntinfo4_t	*mi;
460 
461 	argop->argop = OP_SETATTR;
462 	/*
463 	 * The stateid is set to 0 if client is not modifying the size
464 	 * and otherwise to whatever nfs4_get_stateid() returns.
465 	 *
466 	 * XXX Note: nfs4_get_stateid() returns 0 if no lockowner and/or no
467 	 * state struct could be found for the process/file pair.  We may
468 	 * want to change this in the future (by OPENing the file).  See
469 	 * bug # 4474852.
470 	 */
471 	if (vap->va_mask & AT_SIZE) {
472 
473 		ASSERT(rp != NULL);
474 		mi = VTOMI4(RTOV4(rp));
475 
476 		argop->nfs_argop4_u.opsetattr.stateid =
477 			nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
478 				OP_SETATTR, sid_types, FALSE);
479 	} else {
480 		bzero(&argop->nfs_argop4_u.opsetattr.stateid,
481 		    sizeof (stateid4));
482 	}
483 
484 	*error = vattr_to_fattr4(vap, vsap, attr, flags, OP_SETATTR, supp);
485 	if (*error)
486 		bzero(attr, sizeof (*attr));
487 }
488 
489 static void
490 nfs4args_setattr_free(nfs_argop4 *argop)
491 {
492 	nfs4_fattr4_free(&argop->nfs_argop4_u.opsetattr.obj_attributes);
493 }
494 
495 static int
496 nfs4args_verify(nfs_argop4 *argop, vattr_t *vap, enum nfs_opnum4 op,
497 		bitmap4 supp)
498 {
499 	fattr4 *attr;
500 	int error = 0;
501 
502 	argop->argop = op;
503 	switch (op) {
504 	case OP_VERIFY:
505 		attr = &argop->nfs_argop4_u.opverify.obj_attributes;
506 		break;
507 	case OP_NVERIFY:
508 		attr = &argop->nfs_argop4_u.opnverify.obj_attributes;
509 		break;
510 	default:
511 		return (EINVAL);
512 	}
513 	if (!error)
514 		error = vattr_to_fattr4(vap, NULL, attr, 0, op, supp);
515 	if (error)
516 		bzero(attr, sizeof (*attr));
517 	return (error);
518 }
519 
520 static void
521 nfs4args_verify_free(nfs_argop4 *argop)
522 {
523 	switch (argop->argop) {
524 	case OP_VERIFY:
525 		nfs4_fattr4_free(&argop->nfs_argop4_u.opverify.obj_attributes);
526 		break;
527 	case OP_NVERIFY:
528 		nfs4_fattr4_free(&argop->nfs_argop4_u.opnverify.obj_attributes);
529 		break;
530 	default:
531 		break;
532 	}
533 }
534 
535 static void
536 nfs4args_write(nfs_argop4 *argop, stable_how4 stable, rnode4_t *rp, cred_t *cr,
537 	WRITE4args **wargs_pp, nfs4_stateid_types_t *sid_tp)
538 {
539 	WRITE4args *wargs = &argop->nfs_argop4_u.opwrite;
540 	mntinfo4_t *mi = VTOMI4(RTOV4(rp));
541 
542 	argop->argop = OP_WRITE;
543 	wargs->stable = stable;
544 	wargs->stateid = nfs4_get_w_stateid(cr, rp, curproc->p_pidp->pid_id,
545 				mi, OP_WRITE, sid_tp);
546 	wargs->mblk = NULL;
547 	*wargs_pp = wargs;
548 }
549 
550 void
551 nfs4args_copen_free(OPEN4cargs *open_args)
552 {
553 	if (open_args->owner.owner_val) {
554 		kmem_free(open_args->owner.owner_val,
555 					open_args->owner.owner_len);
556 	}
557 	if ((open_args->opentype == OPEN4_CREATE) &&
558 	    (open_args->mode != EXCLUSIVE4)) {
559 		nfs4_fattr4_free(&open_args->createhow4_u.createattrs);
560 	}
561 }
562 
563 /*
564  * XXX:  This is referenced in modstubs.s
565  */
566 struct vnodeops *
567 nfs4_getvnodeops(void)
568 {
569 	return (nfs4_vnodeops);
570 }
571 
572 /*
573  * The OPEN operation opens a regular file.
574  *
575  * ARGSUSED
576  */
577 static int
578 nfs4_open(vnode_t **vpp, int flag, cred_t *cr)
579 {
580 	vnode_t *dvp = NULL;
581 	rnode4_t *rp;
582 	int error;
583 	int just_been_created;
584 	char fn[MAXNAMELEN];
585 
586 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4_open: "));
587 	if (nfs_zone() != VTOMI4(*vpp)->mi_zone)
588 		return (EIO);
589 	rp = VTOR4(*vpp);
590 
591 	/*
592 	 * Check to see if opening something besides a regular file;
593 	 * if so skip the OTW call
594 	 */
595 	if ((*vpp)->v_type != VREG) {
596 		error = nfs4_open_non_reg_file(vpp, flag, cr);
597 		return (error);
598 	}
599 
600 	/*
601 	 * XXX - would like a check right here to know if the file is
602 	 * executable or not, so as to skip OTW
603 	 */
604 
605 	if ((error = vtoname(*vpp, fn, MAXNAMELEN)) != 0)
606 		return (error);
607 
608 	if ((error = vtodv(*vpp, &dvp, cr, TRUE)) != 0)
609 		return (error);
610 
611 	/*
612 	 * See if this file has just been CREATEd.
613 	 * If so, clear the flag and update the dnlc, which was previously
614 	 * skipped in nfs4_create.
615 	 * XXX need better serilization on this.
616 	 * XXX move this into the nf4open_otw call, after we have
617 	 * XXX acquired the open owner seqid sync.
618 	 */
619 	mutex_enter(&rp->r_statev4_lock);
620 	if (rp->created_v4) {
621 		rp->created_v4 = 0;
622 		mutex_exit(&rp->r_statev4_lock);
623 
624 		dnlc_update(dvp, fn, *vpp);
625 		/* This is needed so we don't bump the open ref count */
626 		just_been_created = 1;
627 	} else {
628 		mutex_exit(&rp->r_statev4_lock);
629 		just_been_created = 0;
630 	}
631 
632 	/*
633 	 * If caller specified O_TRUNC/FTRUNC, then be sure to set
634 	 * FWRITE (to drive successful setattr(size=0) after open)
635 	 */
636 	if (flag & FTRUNC)
637 		flag |= FWRITE;
638 
639 	error = nfs4open_otw(dvp, fn, NULL, vpp, cr, 0, flag, 0,
640 			just_been_created);
641 
642 	if (!error && !((*vpp)->v_flag & VROOT))
643 		dnlc_update(dvp, fn, *vpp);
644 
645 	/* release the hold from vtodv */
646 	VN_RELE(dvp);
647 
648 	/* exchange the shadow for the master vnode, if needed */
649 
650 	if (error == 0 && IS_SHADOW(*vpp, rp))
651 		sv_exchange(vpp);
652 
653 	return (error);
654 }
655 
656 /*
657  * See if there's a "lost open" request to be saved and recovered.
658  */
659 static void
660 nfs4open_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
661 	nfs4_open_owner_t *oop, cred_t *cr, vnode_t *vp,
662 	vnode_t *dvp, OPEN4cargs *open_args)
663 {
664 	vfs_t *vfsp;
665 	char *srccfp;
666 
667 	vfsp = (dvp ? dvp->v_vfsp : vp->v_vfsp);
668 
669 	if (error != ETIMEDOUT && error != EINTR &&
670 			!NFS4_FRC_UNMT_ERR(error, vfsp)) {
671 		lost_rqstp->lr_op = 0;
672 		return;
673 	}
674 
675 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
676 		    "nfs4open_save_lost_rqst: error %d", error));
677 
678 	lost_rqstp->lr_op = OP_OPEN;
679 	/*
680 	 * The vp (if it is not NULL) and dvp are held and rele'd via
681 	 * the recovery code.  See nfs4_save_lost_rqst.
682 	 */
683 	lost_rqstp->lr_vp = vp;
684 	lost_rqstp->lr_dvp = dvp;
685 	lost_rqstp->lr_oop = oop;
686 	lost_rqstp->lr_osp = NULL;
687 	lost_rqstp->lr_lop = NULL;
688 	lost_rqstp->lr_cr = cr;
689 	lost_rqstp->lr_flk = NULL;
690 	lost_rqstp->lr_oacc = open_args->share_access;
691 	lost_rqstp->lr_odeny = open_args->share_deny;
692 	lost_rqstp->lr_oclaim = open_args->claim;
693 	if (open_args->claim == CLAIM_DELEGATE_CUR) {
694 		lost_rqstp->lr_ostateid =
695 		    open_args->open_claim4_u.delegate_cur_info.delegate_stateid;
696 		srccfp = open_args->open_claim4_u.delegate_cur_info.cfile;
697 	} else {
698 		srccfp = open_args->open_claim4_u.cfile;
699 	}
700 	lost_rqstp->lr_ofile.utf8string_len = 0;
701 	lost_rqstp->lr_ofile.utf8string_val = NULL;
702 	(void) str_to_utf8(srccfp, &lost_rqstp->lr_ofile);
703 	lost_rqstp->lr_putfirst = FALSE;
704 }
705 
706 struct nfs4_excl_time {
707 	uint32 seconds;
708 	uint32 nseconds;
709 };
710 
711 /*
712  * The OPEN operation creates and/or opens a regular file
713  *
714  * ARGSUSED
715  */
716 static int
717 nfs4open_otw(vnode_t *dvp, char *file_name, struct vattr *in_va,
718 	vnode_t **vpp, cred_t *cr, int create_flag, int open_flag,
719 	enum createmode4 createmode, int file_just_been_created)
720 {
721 	rnode4_t *rp;
722 	rnode4_t *drp = VTOR4(dvp);
723 	vnode_t *vp = NULL;
724 	vnode_t *vpi = *vpp;
725 	bool_t needrecov = FALSE;
726 
727 	int doqueue = 1;
728 
729 	COMPOUND4args_clnt args;
730 	COMPOUND4res_clnt res;
731 	nfs_argop4 *argop;
732 	nfs_resop4 *resop;
733 	int argoplist_size;
734 	int idx_open, idx_fattr;
735 
736 	GETFH4res *gf_res = NULL;
737 	OPEN4res *op_res = NULL;
738 	nfs4_ga_res_t *garp;
739 	fattr4 *attr = NULL;
740 	struct nfs4_excl_time verf;
741 	bool_t did_excl_setup = FALSE;
742 	int created_osp;
743 
744 	OPEN4cargs *open_args;
745 	nfs4_open_owner_t	*oop = NULL;
746 	nfs4_open_stream_t	*osp = NULL;
747 	seqid4 seqid = 0;
748 	bool_t retry_open = FALSE;
749 	nfs4_recov_state_t recov_state;
750 	nfs4_lost_rqst_t lost_rqst;
751 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
752 	hrtime_t t;
753 	int acc = 0;
754 	cred_t *cred_otw = NULL;	/* cred used to do the RPC call */
755 	cred_t *ncr = NULL;
756 
757 	nfs4_sharedfh_t *otw_sfh;
758 	nfs4_sharedfh_t *orig_sfh;
759 	int fh_differs = 0;
760 	int numops, setgid_flag;
761 	int num_bseqid_retry = NFS4_NUM_RETRY_BAD_SEQID + 1;
762 
763 	/*
764 	 * Make sure we properly deal with setting the right gid on
765 	 * a newly created file to reflect the parent's setgid bit
766 	 */
767 	setgid_flag = 0;
768 	if (create_flag && in_va) {
769 
770 		/*
771 		 * If the parent's directory has the setgid bit set
772 		 * _and_ the client was able to get a valid mapping
773 		 * for the parent dir's owner_group, we want to
774 		 * append NVERIFY(owner_group == dva.va_gid) and
775 		 * SETATTR to the CREATE compound.
776 		 */
777 		mutex_enter(&drp->r_statelock);
778 		if (drp->r_attr.va_mode & VSGID &&
779 		    drp->r_attr.va_gid != GID_NOBODY) {
780 			in_va->va_gid = drp->r_attr.va_gid;
781 			setgid_flag = 1;
782 		}
783 		mutex_exit(&drp->r_statelock);
784 	}
785 
786 	/*
787 	 * Normal/non-create compound:
788 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new)
789 	 *
790 	 * Open(create) compound no setgid:
791 	 * PUTFH(dfh) + SAVEFH + OPEN(create) + GETFH + GETATTR(new) +
792 	 * RESTOREFH + GETATTR
793 	 *
794 	 * Open(create) setgid:
795 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new) +
796 	 * SAVEFH + PUTFH(dfh) + GETATTR(dvp) + RESTOREFH +
797 	 * NVERIFY(grp) + SETATTR
798 	 */
799 	if (setgid_flag) {
800 		numops = 10;
801 		idx_open = 1;
802 		idx_fattr = 3;
803 	} else if (create_flag) {
804 		numops = 7;
805 		idx_open = 2;
806 		idx_fattr = 4;
807 	} else {
808 		numops = 4;
809 		idx_open = 1;
810 		idx_fattr = 3;
811 	}
812 
813 	args.array_len = numops;
814 	argoplist_size = numops * sizeof (nfs_argop4);
815 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
816 
817 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw: "
818 		"open %s open flag 0x%x cred %p", file_name, open_flag,
819 		(void *)cr));
820 
821 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
822 	if (create_flag) {
823 		/*
824 		 * We are to create a file.  Initialize the passed in vnode
825 		 * pointer.
826 		 */
827 		vpi = NULL;
828 	} else {
829 		/*
830 		 * Check to see if the client owns a read delegation and is
831 		 * trying to open for write.  If so, then return the delegation
832 		 * to avoid the server doing a cb_recall and returning DELAY.
833 		 * NB - we don't use the statev4_lock here because we'd have
834 		 * to drop the lock anyway and the result would be stale.
835 		 */
836 		if ((open_flag & FWRITE) &&
837 		    VTOR4(vpi)->r_deleg_type == OPEN_DELEGATE_READ)
838 			(void) nfs4delegreturn(VTOR4(vpi), NFS4_DR_REOPEN);
839 
840 		/*
841 		 * If the file has a delegation, then do an access check up
842 		 * front.  This avoids having to an access check later after
843 		 * we've already done start_op, which could deadlock.
844 		 */
845 		if (VTOR4(vpi)->r_deleg_type != OPEN_DELEGATE_NONE) {
846 			if (open_flag & FREAD &&
847 			    nfs4_access(vpi, VREAD, 0, cr) == 0)
848 				acc |= VREAD;
849 			if (open_flag & FWRITE &&
850 			    nfs4_access(vpi, VWRITE, 0, cr) == 0)
851 				acc |= VWRITE;
852 		}
853 	}
854 
855 	drp = VTOR4(dvp);
856 
857 	recov_state.rs_flags = 0;
858 	recov_state.rs_num_retry_despite_err = 0;
859 	cred_otw = cr;
860 
861 recov_retry:
862 	fh_differs = 0;
863 	nfs4_error_zinit(&e);
864 
865 	/* argop is empty here */
866 
867 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
868 		if (ncr != NULL)
869 			crfree(ncr);
870 		kmem_free(argop, argoplist_size);
871 		return (EINTR);
872 	}
873 
874 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, vpi, &recov_state);
875 	if (e.error) {
876 		nfs_rw_exit(&drp->r_rwlock);
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 				nfs_rw_exit(&drp->r_rwlock);
948 				nfs4_end_op(VTOMI4(dvp), dvp, vpi,
949 					&recov_state, FALSE);
950 				if (ncr != NULL)
951 					crfree(ncr);
952 				kmem_free(argop, argoplist_size);
953 				return (v_error);
954 			}
955 		}
956 	} else {
957 		/* NO CREATE */
958 		open_args->opentype = OPEN4_NOCREATE;
959 	}
960 
961 	if (recov_state.rs_sp != NULL) {
962 		mutex_enter(&recov_state.rs_sp->s_lock);
963 		open_args->owner.clientid = recov_state.rs_sp->clientid;
964 		mutex_exit(&recov_state.rs_sp->s_lock);
965 	} else {
966 		/* XXX should we just fail here? */
967 		open_args->owner.clientid = 0;
968 	}
969 
970 	/*
971 	 * This increments oop's ref count or creates a temporary 'just_created'
972 	 * open owner that will become valid when this OPEN/OPEN_CONFIRM call
973 	 * completes.
974 	 */
975 	mutex_enter(&VTOMI4(dvp)->mi_lock);
976 
977 	/* See if a permanent or just created open owner exists */
978 	oop = find_open_owner_nolock(cr, NFS4_JUST_CREATED, VTOMI4(dvp));
979 	if (!oop) {
980 		/*
981 		 * This open owner does not exist so create a temporary
982 		 * just created one.
983 		 */
984 		oop = create_open_owner(cr, VTOMI4(dvp));
985 		ASSERT(oop != NULL);
986 	}
987 	mutex_exit(&VTOMI4(dvp)->mi_lock);
988 
989 	/* this length never changes, do alloc before seqid sync */
990 	open_args->owner.owner_len = sizeof (oop->oo_name);
991 	open_args->owner.owner_val =
992 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
993 
994 	e.error = nfs4_start_open_seqid_sync(oop, VTOMI4(dvp));
995 	if (e.error == EAGAIN) {
996 		open_owner_rele(oop);
997 		nfs4args_copen_free(open_args);
998 		nfs_rw_exit(&drp->r_rwlock);
999 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1000 		if (ncr != NULL) {
1001 			crfree(ncr);
1002 			ncr = NULL;
1003 		}
1004 		goto recov_retry;
1005 	}
1006 
1007 	/* Check to see if we need to do the OTW call */
1008 	if (!create_flag) {
1009 		if (!nfs4_is_otw_open_necessary(oop, open_flag, vpi,
1010 			file_just_been_created, &e.error, acc, &recov_state)) {
1011 
1012 			/*
1013 			 * The OTW open is not necessary.  Either
1014 			 * the open can succeed without it (eg.
1015 			 * delegation, error == 0) or the open
1016 			 * must fail due to an access failure
1017 			 * (error != 0).  In either case, tidy
1018 			 * up and return.
1019 			 */
1020 
1021 			nfs4_end_open_seqid_sync(oop);
1022 			open_owner_rele(oop);
1023 			nfs4args_copen_free(open_args);
1024 			nfs_rw_exit(&drp->r_rwlock);
1025 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, FALSE);
1026 			if (ncr != NULL)
1027 				crfree(ncr);
1028 			kmem_free(argop, argoplist_size);
1029 			return (e.error);
1030 		}
1031 	}
1032 
1033 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1034 	    open_args->owner.owner_len);
1035 
1036 	seqid = nfs4_get_open_seqid(oop) + 1;
1037 	open_args->seqid = seqid;
1038 	open_args->share_access = 0;
1039 	if (open_flag & FREAD)
1040 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1041 	if (open_flag & FWRITE)
1042 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1043 	open_args->share_deny = OPEN4_SHARE_DENY_NONE;
1044 
1045 
1046 
1047 	/*
1048 	 * getfh w/sanity check for idx_open/idx_fattr
1049 	 */
1050 	ASSERT((idx_open + 1) == (idx_fattr - 1));
1051 	argop[idx_open + 1].argop = OP_GETFH;
1052 
1053 	/* getattr */
1054 	argop[idx_fattr].argop = OP_GETATTR;
1055 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1056 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1057 
1058 	if (setgid_flag) {
1059 		vattr_t	_v;
1060 		servinfo4_t *svp;
1061 		bitmap4	supp_attrs;
1062 
1063 		svp = drp->r_server;
1064 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1065 		supp_attrs = svp->sv_supp_attrs;
1066 		nfs_rw_exit(&svp->sv_lock);
1067 
1068 		/*
1069 		 * For setgid case, we need to:
1070 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1071 		 */
1072 		argop[4].argop = OP_SAVEFH;
1073 
1074 		argop[5].argop = OP_CPUTFH;
1075 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
1076 
1077 		argop[6].argop = OP_GETATTR;
1078 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1079 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1080 
1081 		argop[7].argop = OP_RESTOREFH;
1082 
1083 		/*
1084 		 * nverify
1085 		 */
1086 		_v.va_mask = AT_GID;
1087 		_v.va_gid = in_va->va_gid;
1088 		if (!(e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
1089 		    supp_attrs))) {
1090 
1091 			/*
1092 			 * setattr
1093 			 *
1094 			 * We _know_ we're not messing with AT_SIZE or
1095 			 * AT_XTIME, so no need for stateid or flags.
1096 			 * Also we specify NULL rp since we're only
1097 			 * interested in setting owner_group attributes.
1098 			 */
1099 			nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr,
1100 			    supp_attrs, &e.error, 0);
1101 			if (e.error)
1102 				nfs4args_verify_free(&argop[8]);
1103 		}
1104 
1105 		if (e.error) {
1106 			/*
1107 			 * XXX - Revisit the last argument to nfs4_end_op()
1108 			 *	 once 5020486 is fixed.
1109 			 */
1110 			nfs4_end_open_seqid_sync(oop);
1111 			open_owner_rele(oop);
1112 			nfs4args_copen_free(open_args);
1113 			nfs_rw_exit(&drp->r_rwlock);
1114 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1115 			if (ncr != NULL)
1116 				crfree(ncr);
1117 			kmem_free(argop, argoplist_size);
1118 			return (e.error);
1119 		}
1120 	} else if (create_flag) {
1121 		/*
1122 		 * For setgid case, we need to:
1123 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1124 		 */
1125 		argop[1].argop = OP_SAVEFH;
1126 
1127 		argop[5].argop = OP_RESTOREFH;
1128 
1129 		argop[6].argop = OP_GETATTR;
1130 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1131 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1132 	}
1133 
1134 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1135 	    "nfs4open_otw: %s call, nm %s, rp %s",
1136 	    needrecov ? "recov" : "first", file_name,
1137 	    rnode4info(VTOR4(dvp))));
1138 
1139 	t = gethrtime();
1140 
1141 	rfs4call(VTOMI4(dvp), &args, &res, cred_otw, &doqueue, 0, &e);
1142 
1143 	if (!e.error && nfs4_need_to_bump_seqid(&res))
1144 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1145 
1146 	needrecov = nfs4_needs_recovery(&e, TRUE, dvp->v_vfsp);
1147 
1148 	if (e.error || needrecov) {
1149 		bool_t abort = FALSE;
1150 
1151 		if (needrecov) {
1152 			nfs4_bseqid_entry_t *bsep = NULL;
1153 
1154 			nfs4open_save_lost_rqst(e.error, &lost_rqst, oop,
1155 			    cred_otw, vpi, dvp, open_args);
1156 
1157 			if (!e.error && res.status == NFS4ERR_BAD_SEQID) {
1158 				bsep = nfs4_create_bseqid_entry(oop, NULL,
1159 					vpi, 0, args.ctag, open_args->seqid);
1160 				num_bseqid_retry--;
1161 			}
1162 
1163 			abort = nfs4_start_recovery(&e, VTOMI4(dvp), dvp, vpi,
1164 				    NULL, lost_rqst.lr_op == OP_OPEN ?
1165 				    &lost_rqst : NULL, OP_OPEN, bsep);
1166 
1167 			if (bsep)
1168 				kmem_free(bsep, sizeof (*bsep));
1169 			/* give up if we keep getting BAD_SEQID */
1170 			if (num_bseqid_retry == 0)
1171 				abort = TRUE;
1172 			if (abort == TRUE && e.error == 0)
1173 				e.error = geterrno4(res.status);
1174 		}
1175 		nfs4_end_open_seqid_sync(oop);
1176 		open_owner_rele(oop);
1177 		nfs_rw_exit(&drp->r_rwlock);
1178 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1179 		nfs4args_copen_free(open_args);
1180 		if (setgid_flag) {
1181 			nfs4args_verify_free(&argop[8]);
1182 			nfs4args_setattr_free(&argop[9]);
1183 		}
1184 		if (!e.error)
1185 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1186 		if (ncr != NULL) {
1187 			crfree(ncr);
1188 			ncr = NULL;
1189 		}
1190 		if (!needrecov || abort == TRUE || e.error == EINTR ||
1191 		    NFS4_FRC_UNMT_ERR(e.error, dvp->v_vfsp)) {
1192 			kmem_free(argop, argoplist_size);
1193 			return (e.error);
1194 		}
1195 		goto recov_retry;
1196 	}
1197 
1198 	/*
1199 	 * Will check and update lease after checking the rflag for
1200 	 * OPEN_CONFIRM in the successful OPEN call.
1201 	 */
1202 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
1203 
1204 		/*
1205 		 * XXX what if we're crossing mount points from server1:/drp
1206 		 * to server2:/drp/rp.
1207 		 */
1208 
1209 		/* Signal our end of use of the open seqid */
1210 		nfs4_end_open_seqid_sync(oop);
1211 
1212 		/*
1213 		 * This will destroy the open owner if it was just created,
1214 		 * and no one else has put a reference on it.
1215 		 */
1216 		open_owner_rele(oop);
1217 		if (create_flag && (createmode != EXCLUSIVE4) &&
1218 		    res.status == NFS4ERR_BADOWNER)
1219 			nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1220 
1221 		e.error = geterrno4(res.status);
1222 		nfs4args_copen_free(open_args);
1223 		if (setgid_flag) {
1224 			nfs4args_verify_free(&argop[8]);
1225 			nfs4args_setattr_free(&argop[9]);
1226 		}
1227 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1228 		nfs_rw_exit(&drp->r_rwlock);
1229 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1230 		/*
1231 		 * If the reply is NFS4ERR_ACCESS, it may be because
1232 		 * we are root (no root net access).  If the real uid
1233 		 * is not root, then retry with the real uid instead.
1234 		 */
1235 		if (ncr != NULL) {
1236 			crfree(ncr);
1237 			ncr = NULL;
1238 		}
1239 		if (res.status == NFS4ERR_ACCESS &&
1240 		    (ncr = crnetadjust(cred_otw)) != NULL) {
1241 			cred_otw = ncr;
1242 			goto recov_retry;
1243 		}
1244 		kmem_free(argop, argoplist_size);
1245 		return (e.error);
1246 	}
1247 
1248 	resop = &res.array[idx_open];  /* open res */
1249 	op_res = &resop->nfs_resop4_u.opopen;
1250 
1251 #ifdef DEBUG
1252 	/*
1253 	 * verify attrset bitmap
1254 	 */
1255 	if (create_flag &&
1256 	    (createmode == UNCHECKED4 || createmode == GUARDED4)) {
1257 		/* make sure attrset returned is what we asked for */
1258 		/* XXX Ignore this 'error' for now */
1259 		if (attr->attrmask != op_res->attrset)
1260 			/* EMPTY */;
1261 	}
1262 #endif
1263 
1264 	if (op_res->rflags & OPEN4_RESULT_LOCKTYPE_POSIX) {
1265 		mutex_enter(&VTOMI4(dvp)->mi_lock);
1266 		VTOMI4(dvp)->mi_flags |= MI4_POSIX_LOCK;
1267 		mutex_exit(&VTOMI4(dvp)->mi_lock);
1268 	}
1269 
1270 	resop = &res.array[idx_open + 1];  /* getfh res */
1271 	gf_res = &resop->nfs_resop4_u.opgetfh;
1272 
1273 	otw_sfh = sfh4_get(&gf_res->object, VTOMI4(dvp));
1274 
1275 	/*
1276 	 * The open stateid has been updated on the server but not
1277 	 * on the client yet.  There is a path: makenfs4node->nfs4_attr_cache->
1278 	 * flush_pages->VOP_PUTPAGE->...->nfs4write where we will issue an OTW
1279 	 * WRITE call.  That, however, will use the old stateid, so go ahead
1280 	 * and upate the open stateid now, before any call to makenfs4node.
1281 	 */
1282 	if (vpi) {
1283 		nfs4_open_stream_t	*tmp_osp;
1284 		rnode4_t		*tmp_rp = VTOR4(vpi);
1285 
1286 		tmp_osp = find_open_stream(oop, tmp_rp);
1287 		if (tmp_osp) {
1288 			tmp_osp->open_stateid = op_res->stateid;
1289 			mutex_exit(&tmp_osp->os_sync_lock);
1290 			open_stream_rele(tmp_osp, tmp_rp);
1291 		}
1292 
1293 		/*
1294 		 * We must determine if the file handle given by the otw open
1295 		 * is the same as the file handle which was passed in with
1296 		 * *vpp.  This case can be reached if the file we are trying
1297 		 * to open has been removed and another file has been created
1298 		 * having the same file name.  The passed in vnode is released
1299 		 * later.
1300 		 */
1301 		orig_sfh = VTOR4(vpi)->r_fh;
1302 		fh_differs = nfs4cmpfh(&orig_sfh->sfh_fh, &otw_sfh->sfh_fh);
1303 	}
1304 
1305 	garp = &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res;
1306 
1307 	if (create_flag || fh_differs) {
1308 		int rnode_err = 0;
1309 
1310 		vp = makenfs4node(otw_sfh, garp, dvp->v_vfsp, t, cr,
1311 		    dvp, fn_get(VTOSV(dvp)->sv_name, file_name));
1312 
1313 		if (e.error)
1314 			PURGE_ATTRCACHE4(vp);
1315 		/*
1316 		 * For the newly created vp case, make sure the rnode
1317 		 * isn't bad before using it.
1318 		 */
1319 		mutex_enter(&(VTOR4(vp))->r_statelock);
1320 		if (VTOR4(vp)->r_flags & R4RECOVERR)
1321 			rnode_err = EIO;
1322 		mutex_exit(&(VTOR4(vp))->r_statelock);
1323 
1324 		if (rnode_err) {
1325 			nfs4_end_open_seqid_sync(oop);
1326 			nfs4args_copen_free(open_args);
1327 			if (setgid_flag) {
1328 				nfs4args_verify_free(&argop[8]);
1329 				nfs4args_setattr_free(&argop[9]);
1330 			}
1331 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1332 			nfs_rw_exit(&drp->r_rwlock);
1333 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1334 				    needrecov);
1335 			open_owner_rele(oop);
1336 			VN_RELE(vp);
1337 			if (ncr != NULL)
1338 				crfree(ncr);
1339 			sfh4_rele(&otw_sfh);
1340 			kmem_free(argop, argoplist_size);
1341 			return (EIO);
1342 		}
1343 	} else {
1344 		vp = vpi;
1345 	}
1346 	sfh4_rele(&otw_sfh);
1347 
1348 	/*
1349 	 * It seems odd to get a full set of attrs and then not update
1350 	 * the object's attrcache in the non-create case.  Create case uses
1351 	 * the attrs since makenfs4node checks to see if the attrs need to
1352 	 * be updated (and then updates them).  The non-create case should
1353 	 * update attrs also.
1354 	 */
1355 	if (! create_flag && ! fh_differs && !e.error) {
1356 		nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
1357 	}
1358 
1359 	nfs4_error_zinit(&e);
1360 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
1361 		/* This does not do recovery for vp explicitly. */
1362 		nfs4open_confirm(vp, &seqid, &op_res->stateid, cred_otw, FALSE,
1363 		    &retry_open, oop, FALSE, &e, &num_bseqid_retry);
1364 
1365 		if (e.error || e.stat) {
1366 			nfs4_end_open_seqid_sync(oop);
1367 			nfs4args_copen_free(open_args);
1368 			if (setgid_flag) {
1369 				nfs4args_verify_free(&argop[8]);
1370 				nfs4args_setattr_free(&argop[9]);
1371 			}
1372 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1373 			nfs_rw_exit(&drp->r_rwlock);
1374 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1375 				needrecov);
1376 			open_owner_rele(oop);
1377 			if (create_flag || fh_differs) {
1378 				/* rele the makenfs4node */
1379 				VN_RELE(vp);
1380 			}
1381 			if (ncr != NULL) {
1382 				crfree(ncr);
1383 				ncr = NULL;
1384 			}
1385 			if (retry_open == TRUE) {
1386 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1387 				    "nfs4open_otw: retry the open since OPEN "
1388 				    "CONFIRM failed with error %d stat %d",
1389 				    e.error, e.stat));
1390 				if (create_flag && createmode == GUARDED4) {
1391 					NFS4_DEBUG(nfs4_client_recov_debug,
1392 					    (CE_NOTE, "nfs4open_otw: switch "
1393 					    "createmode from GUARDED4 to "
1394 					    "UNCHECKED4"));
1395 					createmode = UNCHECKED4;
1396 				}
1397 				goto recov_retry;
1398 			}
1399 			if (!e.error) {
1400 				if (create_flag && (createmode != EXCLUSIVE4) &&
1401 				    e.stat == NFS4ERR_BADOWNER)
1402 					nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1403 
1404 				e.error = geterrno4(e.stat);
1405 			}
1406 			kmem_free(argop, argoplist_size);
1407 			return (e.error);
1408 		}
1409 	}
1410 
1411 	rp = VTOR4(vp);
1412 
1413 	mutex_enter(&rp->r_statev4_lock);
1414 	if (create_flag)
1415 		rp->created_v4 = 1;
1416 	mutex_exit(&rp->r_statev4_lock);
1417 
1418 	mutex_enter(&oop->oo_lock);
1419 	/* Doesn't matter if 'oo_just_created' already was set as this */
1420 	oop->oo_just_created = NFS4_PERM_CREATED;
1421 	if (oop->oo_cred_otw)
1422 		crfree(oop->oo_cred_otw);
1423 	oop->oo_cred_otw = cred_otw;
1424 	crhold(oop->oo_cred_otw);
1425 	mutex_exit(&oop->oo_lock);
1426 
1427 	/* returns with 'os_sync_lock' held */
1428 	osp = find_or_create_open_stream(oop, rp, &created_osp);
1429 	if (!osp) {
1430 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1431 		    "nfs4open_otw: failed to create an open stream"));
1432 		NFS4_DEBUG(nfs4_seqid_sync, (CE_NOTE, "nfs4open_otw: "
1433 		    "signal our end of use of the open seqid"));
1434 
1435 		nfs4_end_open_seqid_sync(oop);
1436 		open_owner_rele(oop);
1437 		nfs4args_copen_free(open_args);
1438 		if (setgid_flag) {
1439 			nfs4args_verify_free(&argop[8]);
1440 			nfs4args_setattr_free(&argop[9]);
1441 		}
1442 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1443 		nfs_rw_exit(&drp->r_rwlock);
1444 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1445 		if (create_flag || fh_differs)
1446 			VN_RELE(vp);
1447 		if (ncr != NULL)
1448 			crfree(ncr);
1449 
1450 		kmem_free(argop, argoplist_size);
1451 		return (EINVAL);
1452 
1453 	}
1454 
1455 	osp->open_stateid = op_res->stateid;
1456 
1457 	if (open_flag & FREAD)
1458 		osp->os_share_acc_read++;
1459 	if (open_flag & FWRITE)
1460 		osp->os_share_acc_write++;
1461 	osp->os_share_deny_none++;
1462 
1463 	/*
1464 	 * Need to reset this bitfield for the possible case where we were
1465 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
1466 	 * we could retry the CLOSE, OPENed the file again.
1467 	 */
1468 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
1469 	osp->os_final_close = 0;
1470 	osp->os_force_close = 0;
1471 #ifdef DEBUG
1472 	if (osp->os_failed_reopen)
1473 		NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE, "nfs4open_otw:"
1474 		    " clearing os_failed_reopen for osp %p, cr %p, rp %s",
1475 		    (void *)osp, (void *)cr, rnode4info(rp)));
1476 #endif
1477 	osp->os_failed_reopen = 0;
1478 
1479 	mutex_exit(&osp->os_sync_lock);
1480 
1481 	nfs4_end_open_seqid_sync(oop);
1482 
1483 	if (created_osp && recov_state.rs_sp != NULL) {
1484 		mutex_enter(&recov_state.rs_sp->s_lock);
1485 		nfs4_inc_state_ref_count_nolock(recov_state.rs_sp, VTOMI4(dvp));
1486 		mutex_exit(&recov_state.rs_sp->s_lock);
1487 	}
1488 
1489 	/* get rid of our reference to find oop */
1490 	open_owner_rele(oop);
1491 
1492 	open_stream_rele(osp, rp);
1493 
1494 	/* accept delegation, if any */
1495 	nfs4_delegation_accept(rp, CLAIM_NULL, op_res, garp, cred_otw);
1496 
1497 	nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1498 
1499 	if (createmode == EXCLUSIVE4 &&
1500 		(in_va->va_mask & ~(AT_GID | AT_SIZE))) {
1501 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw:"
1502 			" EXCLUSIVE4: sending a SETATTR"));
1503 		/*
1504 		 * If doing an exclusive create, then generate
1505 		 * a SETATTR to set the initial attributes.
1506 		 * Try to set the mtime and the atime to the
1507 		 * server's current time.  It is somewhat
1508 		 * expected that these fields will be used to
1509 		 * store the exclusive create cookie.  If not,
1510 		 * server implementors will need to know that
1511 		 * a SETATTR will follow an exclusive create
1512 		 * and the cookie should be destroyed if
1513 		 * appropriate.
1514 		 *
1515 		 * The AT_GID and AT_SIZE bits are turned off
1516 		 * so that the SETATTR request will not attempt
1517 		 * to process these.  The gid will be set
1518 		 * separately if appropriate.  The size is turned
1519 		 * off because it is assumed that a new file will
1520 		 * be created empty and if the file wasn't empty,
1521 		 * then the exclusive create will have failed
1522 		 * because the file must have existed already.
1523 		 * Therefore, no truncate operation is needed.
1524 		 */
1525 		in_va->va_mask &= ~(AT_GID | AT_SIZE);
1526 		in_va->va_mask |= (AT_MTIME | AT_ATIME);
1527 
1528 		e.error = nfs4setattr(vp, in_va, 0, cr, NULL);
1529 		if (e.error) {
1530 			/*
1531 			 * Couldn't correct the attributes of
1532 			 * the newly created file and the
1533 			 * attributes are wrong.  Remove the
1534 			 * file and return an error to the
1535 			 * application.
1536 			 */
1537 			/* XXX will this take care of client state ? */
1538 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1539 				"nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1540 				" remove file", e.error));
1541 			VN_RELE(vp);
1542 			(void) nfs4_remove(dvp, file_name, cr);
1543 			nfs_rw_exit(&drp->r_rwlock);
1544 			goto skip_rwlock_exit;
1545 		}
1546 	}
1547 
1548 	/*
1549 	 * If we created or found the correct vnode, due to create_flag or
1550 	 * fh_differs being set, then update directory cache attribute, readdir
1551 	 * and dnlc caches.
1552 	 */
1553 	if (create_flag || fh_differs) {
1554 		dirattr_info_t dinfo, *dinfop;
1555 
1556 		/*
1557 		 * Make sure getattr succeeded before using results.
1558 		 * note: op 7 is getattr(dir) for both flavors of
1559 		 * open(create).
1560 		 */
1561 		if (create_flag && res.status == NFS4_OK) {
1562 			dinfo.di_time_call = t;
1563 			dinfo.di_cred = cr;
1564 			dinfo.di_garp =
1565 				&res.array[6].nfs_resop4_u.opgetattr.ga_res;
1566 			dinfop = &dinfo;
1567 		} else {
1568 			dinfop = NULL;
1569 		}
1570 
1571 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1572 					dinfop);
1573 	}
1574 	nfs_rw_exit(&drp->r_rwlock);
1575 skip_rwlock_exit:
1576 
1577 	/*
1578 	 * If the page cache for this file was flushed from actions
1579 	 * above, it was done asynchronously and if that is true,
1580 	 * there is a need to wait here for it to complete.  This must
1581 	 * be done outside of start_fop/end_fop.
1582 	 */
1583 	(void) nfs4_waitfor_purge_complete(vp);
1584 
1585 	/*
1586 	 * It is implicit that we are in the open case (create_flag == 0) since
1587 	 * fh_differs can only be set to a non-zero value in the open case.
1588 	 */
1589 	if (fh_differs != 0 && vpi != NULL)
1590 		VN_RELE(vpi);
1591 
1592 	/*
1593 	 * Be sure to set *vpp to the correct value before returning.
1594 	 */
1595 	*vpp = vp;
1596 
1597 	nfs4args_copen_free(open_args);
1598 	if (setgid_flag) {
1599 		nfs4args_verify_free(&argop[8]);
1600 		nfs4args_setattr_free(&argop[9]);
1601 	}
1602 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1603 
1604 	if (ncr)
1605 		crfree(ncr);
1606 	kmem_free(argop, argoplist_size);
1607 	return (e.error);
1608 }
1609 
1610 /*
1611  * Reopen an open instance.  cf. nfs4open_otw().
1612  *
1613  * Errors are returned by the nfs4_error_t parameter.
1614  * - ep->error contains an errno value or zero.
1615  * - if it is zero, ep->stat is set to an NFS status code, if any.
1616  *   If the file could not be reopened, but the caller should continue, the
1617  *   file is marked dead and no error values are returned.  If the caller
1618  *   should stop recovering open files and start over, either the ep->error
1619  *   value or ep->stat will indicate an error (either something that requires
1620  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1621  *   filehandles) may be handled silently by this routine.
1622  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1623  *   will be started, so the caller should not do it.
1624  *
1625  * Gotos:
1626  * - kill_file : reopen failed in such a fashion to constitute marking the
1627  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1628  *   is for cases where recovery is not possible.
1629  * - failed_reopen : same as above, except that the file has already been
1630  *   marked dead, so no need to do it again.
1631  * - bailout : reopen failed but we are able to recover and retry the reopen -
1632  *   either within this function immediatley or via the calling function.
1633  */
1634 
1635 void
1636 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1637 	    open_claim_type4 claim, bool_t frc_use_claim_previous,
1638 	    bool_t is_recov)
1639 {
1640 	COMPOUND4args_clnt args;
1641 	COMPOUND4res_clnt res;
1642 	nfs_argop4 argop[4];
1643 	nfs_resop4 *resop;
1644 	OPEN4res *op_res = NULL;
1645 	OPEN4cargs *open_args;
1646 	GETFH4res *gf_res;
1647 	rnode4_t *rp = VTOR4(vp);
1648 	int doqueue = 1;
1649 	cred_t *cr = NULL, *cred_otw = NULL;
1650 	nfs4_open_owner_t *oop = NULL;
1651 	seqid4 seqid;
1652 	nfs4_ga_res_t *garp;
1653 	char fn[MAXNAMELEN];
1654 	nfs4_recov_state_t recov = {NULL, 0};
1655 	nfs4_lost_rqst_t lost_rqst;
1656 	mntinfo4_t *mi = VTOMI4(vp);
1657 	bool_t abort;
1658 	char *failed_msg = "";
1659 	int fh_different;
1660 	hrtime_t t;
1661 	nfs4_bseqid_entry_t *bsep = NULL;
1662 
1663 	ASSERT(nfs4_consistent_type(vp));
1664 	ASSERT(nfs_zone() == mi->mi_zone);
1665 
1666 	nfs4_error_zinit(ep);
1667 
1668 	/* this is the cred used to find the open owner */
1669 	cr = state_to_cred(osp);
1670 	if (cr == NULL) {
1671 		failed_msg = "Couldn't reopen: no cred";
1672 		goto kill_file;
1673 	}
1674 	/* use this cred for OTW operations */
1675 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1676 
1677 top:
1678 	nfs4_error_zinit(ep);
1679 
1680 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1681 		/* File system has been unmounted, quit */
1682 		ep->error = EIO;
1683 		failed_msg = "Couldn't reopen: file system has been unmounted";
1684 		goto kill_file;
1685 	}
1686 
1687 	oop = osp->os_open_owner;
1688 
1689 	ASSERT(oop != NULL);
1690 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1691 		failed_msg = "can't reopen: no open owner";
1692 		goto kill_file;
1693 	}
1694 	open_owner_hold(oop);
1695 
1696 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1697 	if (ep->error) {
1698 		open_owner_rele(oop);
1699 		oop = NULL;
1700 		goto bailout;
1701 	}
1702 
1703 	/*
1704 	 * If the rnode has a delegation and the delegation has been
1705 	 * recovered and the server didn't request a recall and the caller
1706 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1707 	 * recovery) and the rnode hasn't been marked dead, then install
1708 	 * the delegation stateid in the open stream.  Otherwise, proceed
1709 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1710 	 */
1711 	mutex_enter(&rp->r_statev4_lock);
1712 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1713 	    !rp->r_deleg_return_pending &&
1714 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1715 	    !rp->r_deleg_needs_recall &&
1716 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1717 	    !(rp->r_flags & R4RECOVERR)) {
1718 		mutex_enter(&osp->os_sync_lock);
1719 		osp->os_delegation = 1;
1720 		osp->open_stateid = rp->r_deleg_stateid;
1721 		mutex_exit(&osp->os_sync_lock);
1722 		mutex_exit(&rp->r_statev4_lock);
1723 		goto bailout;
1724 	}
1725 	mutex_exit(&rp->r_statev4_lock);
1726 
1727 	/*
1728 	 * If the file failed recovery, just quit.  This failure need not
1729 	 * affect other reopens, so don't return an error.
1730 	 */
1731 	mutex_enter(&rp->r_statelock);
1732 	if (rp->r_flags & R4RECOVERR) {
1733 		mutex_exit(&rp->r_statelock);
1734 		ep->error = 0;
1735 		goto failed_reopen;
1736 	}
1737 	mutex_exit(&rp->r_statelock);
1738 
1739 	/*
1740 	 * argop is empty here
1741 	 *
1742 	 * PUTFH, OPEN, GETATTR
1743 	 */
1744 	args.ctag = TAG_REOPEN;
1745 	args.array_len = 4;
1746 	args.array = argop;
1747 
1748 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1749 	    "nfs4_reopen: file is type %d, id %s",
1750 	    vp->v_type, rnode4info(VTOR4(vp))));
1751 
1752 	argop[0].argop = OP_CPUTFH;
1753 
1754 	if (claim != CLAIM_PREVIOUS) {
1755 		/*
1756 		 * if this is a file mount then
1757 		 * use the mntinfo parentfh
1758 		 */
1759 		argop[0].nfs_argop4_u.opcputfh.sfh =
1760 			(vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1761 						VTOSV(vp)->sv_dfh;
1762 	} else {
1763 		/* putfh fh to reopen */
1764 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1765 	}
1766 
1767 	argop[1].argop = OP_COPEN;
1768 	open_args = &argop[1].nfs_argop4_u.opcopen;
1769 	open_args->claim = claim;
1770 
1771 	if (claim == CLAIM_NULL) {
1772 
1773 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1774 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1775 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1776 			    (void *)vp);
1777 			failed_msg = "Couldn't reopen: vtoname failed for "
1778 			    "CLAIM_NULL";
1779 			/* nothing allocated yet */
1780 			goto kill_file;
1781 		}
1782 
1783 		open_args->open_claim4_u.cfile = fn;
1784 	} else if (claim == CLAIM_PREVIOUS) {
1785 
1786 		/*
1787 		 * We have two cases to deal with here:
1788 		 * 1) We're being called to reopen files in order to satisfy
1789 		 *    a lock operation request which requires us to explicitly
1790 		 *    reopen files which were opened under a delegation.  If
1791 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1792 		 *    that case, frc_use_claim_previous is TRUE and we must
1793 		 *    use the rnode's current delegation type (r_deleg_type).
1794 		 * 2) We're reopening files during some form of recovery.
1795 		 *    In this case, frc_use_claim_previous is FALSE and we
1796 		 *    use the delegation type appropriate for recovery
1797 		 *    (r_deleg_needs_recovery).
1798 		 */
1799 		mutex_enter(&rp->r_statev4_lock);
1800 		open_args->open_claim4_u.delegate_type =
1801 			frc_use_claim_previous ?
1802 				rp->r_deleg_type :
1803 				rp->r_deleg_needs_recovery;
1804 		mutex_exit(&rp->r_statev4_lock);
1805 
1806 	} else if (claim == CLAIM_DELEGATE_CUR) {
1807 
1808 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1809 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1810 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1811 			    "with %m", (void *)vp);
1812 			failed_msg = "Couldn't reopen: vtoname failed for "
1813 			    "CLAIM_DELEGATE_CUR";
1814 			/* nothing allocated yet */
1815 			goto kill_file;
1816 		}
1817 
1818 		mutex_enter(&rp->r_statev4_lock);
1819 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1820 							rp->r_deleg_stateid;
1821 		mutex_exit(&rp->r_statev4_lock);
1822 
1823 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1824 	}
1825 	open_args->opentype = OPEN4_NOCREATE;
1826 	open_args->owner.clientid = mi2clientid(mi);
1827 	open_args->owner.owner_len = sizeof (oop->oo_name);
1828 	open_args->owner.owner_val =
1829 			kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1830 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1831 			open_args->owner.owner_len);
1832 	open_args->share_access = 0;
1833 	open_args->share_deny = 0;
1834 
1835 	mutex_enter(&osp->os_sync_lock);
1836 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1837 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1838 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1839 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1840 	    osp->os_share_acc_write, osp->os_open_ref_count,
1841 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1842 
1843 	if (osp->os_share_acc_read || osp->os_mmap_read)
1844 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1845 	if (osp->os_share_acc_write || osp->os_mmap_write)
1846 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1847 	if (osp->os_share_deny_read)
1848 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1849 	if (osp->os_share_deny_write)
1850 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1851 	mutex_exit(&osp->os_sync_lock);
1852 
1853 	seqid = nfs4_get_open_seqid(oop) + 1;
1854 	open_args->seqid = seqid;
1855 
1856 	/* Construct the getfh part of the compound */
1857 	argop[2].argop = OP_GETFH;
1858 
1859 	/* Construct the getattr part of the compound */
1860 	argop[3].argop = OP_GETATTR;
1861 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1862 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1863 
1864 	t = gethrtime();
1865 
1866 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1867 
1868 	if (ep->error) {
1869 		if (!is_recov && !frc_use_claim_previous &&
1870 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1871 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1872 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1873 				cred_otw, vp, NULL, open_args);
1874 			abort = nfs4_start_recovery(ep,
1875 				    VTOMI4(vp), vp, NULL, NULL,
1876 				    lost_rqst.lr_op == OP_OPEN ?
1877 				    &lost_rqst : NULL, OP_OPEN, NULL);
1878 			nfs4args_copen_free(open_args);
1879 			goto bailout;
1880 		}
1881 
1882 		nfs4args_copen_free(open_args);
1883 
1884 		if (ep->error == EACCES && cred_otw != cr) {
1885 			crfree(cred_otw);
1886 			cred_otw = cr;
1887 			crhold(cred_otw);
1888 			nfs4_end_open_seqid_sync(oop);
1889 			open_owner_rele(oop);
1890 			oop = NULL;
1891 			goto top;
1892 		}
1893 		if (ep->error == ETIMEDOUT)
1894 			goto bailout;
1895 		failed_msg = "Couldn't reopen: rpc error";
1896 		goto kill_file;
1897 	}
1898 
1899 	if (nfs4_need_to_bump_seqid(&res))
1900 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1901 
1902 	switch (res.status) {
1903 	case NFS4_OK:
1904 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1905 			mutex_enter(&rp->r_statelock);
1906 			rp->r_delay_interval = 0;
1907 			mutex_exit(&rp->r_statelock);
1908 		}
1909 		break;
1910 	case NFS4ERR_BAD_SEQID:
1911 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1912 			args.ctag, open_args->seqid);
1913 
1914 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1915 			    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1916 			    NULL, OP_OPEN, bsep);
1917 
1918 		nfs4args_copen_free(open_args);
1919 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1920 		nfs4_end_open_seqid_sync(oop);
1921 		open_owner_rele(oop);
1922 		oop = NULL;
1923 		kmem_free(bsep, sizeof (*bsep));
1924 
1925 		goto kill_file;
1926 	case NFS4ERR_NO_GRACE:
1927 		nfs4args_copen_free(open_args);
1928 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1929 		nfs4_end_open_seqid_sync(oop);
1930 		open_owner_rele(oop);
1931 		oop = NULL;
1932 		if (claim == CLAIM_PREVIOUS) {
1933 			/*
1934 			 * Retry as a plain open. We don't need to worry about
1935 			 * checking the changeinfo: it is acceptable for a
1936 			 * client to re-open a file and continue processing
1937 			 * (in the absence of locks).
1938 			 */
1939 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1940 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1941 			    "will retry as CLAIM_NULL"));
1942 			claim = CLAIM_NULL;
1943 			nfs4_mi_kstat_inc_no_grace(mi);
1944 			goto top;
1945 		}
1946 		failed_msg =
1947 		    "Couldn't reopen: tried reclaim outside grace period. ";
1948 		goto kill_file;
1949 	case NFS4ERR_GRACE:
1950 		nfs4_set_grace_wait(mi);
1951 		nfs4args_copen_free(open_args);
1952 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1953 		nfs4_end_open_seqid_sync(oop);
1954 		open_owner_rele(oop);
1955 		oop = NULL;
1956 		ep->error = nfs4_wait_for_grace(mi, &recov);
1957 		if (ep->error != 0)
1958 			goto bailout;
1959 		goto top;
1960 	case NFS4ERR_DELAY:
1961 		nfs4_set_delay_wait(vp);
1962 		nfs4args_copen_free(open_args);
1963 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1964 		nfs4_end_open_seqid_sync(oop);
1965 		open_owner_rele(oop);
1966 		oop = NULL;
1967 		ep->error = nfs4_wait_for_delay(vp, &recov);
1968 		nfs4_mi_kstat_inc_delay(mi);
1969 		if (ep->error != 0)
1970 			goto bailout;
1971 		goto top;
1972 	case NFS4ERR_FHEXPIRED:
1973 		/* recover filehandle and retry */
1974 		abort = nfs4_start_recovery(ep,
1975 				mi, vp, NULL, NULL, NULL, OP_OPEN, NULL);
1976 		nfs4args_copen_free(open_args);
1977 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1978 		nfs4_end_open_seqid_sync(oop);
1979 		open_owner_rele(oop);
1980 		oop = NULL;
1981 		if (abort == FALSE)
1982 			goto top;
1983 		failed_msg = "Couldn't reopen: recovery aborted";
1984 		goto kill_file;
1985 	case NFS4ERR_RESOURCE:
1986 	case NFS4ERR_STALE_CLIENTID:
1987 	case NFS4ERR_WRONGSEC:
1988 	case NFS4ERR_EXPIRED:
1989 		/*
1990 		 * Do not mark the file dead and let the calling
1991 		 * function initiate recovery.
1992 		 */
1993 		nfs4args_copen_free(open_args);
1994 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1995 		nfs4_end_open_seqid_sync(oop);
1996 		open_owner_rele(oop);
1997 		oop = NULL;
1998 		goto bailout;
1999 	case NFS4ERR_ACCESS:
2000 		if (cred_otw != cr) {
2001 			crfree(cred_otw);
2002 			cred_otw = cr;
2003 			crhold(cred_otw);
2004 			nfs4args_copen_free(open_args);
2005 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2006 			nfs4_end_open_seqid_sync(oop);
2007 			open_owner_rele(oop);
2008 			oop = NULL;
2009 			goto top;
2010 		}
2011 		/* fall through */
2012 	default:
2013 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2014 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2015 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2016 		    rnode4info(VTOR4(vp))));
2017 		failed_msg = "Couldn't reopen: NFSv4 error";
2018 		nfs4args_copen_free(open_args);
2019 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2020 		goto kill_file;
2021 	}
2022 
2023 	resop = &res.array[1];  /* open res */
2024 	op_res = &resop->nfs_resop4_u.opopen;
2025 
2026 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2027 
2028 	/*
2029 	 * Check if the path we reopened really is the same
2030 	 * file. We could end up in a situation where the file
2031 	 * was removed and a new file created with the same name.
2032 	 */
2033 	resop = &res.array[2];
2034 	gf_res = &resop->nfs_resop4_u.opgetfh;
2035 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2036 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2037 	if (fh_different) {
2038 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2039 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2040 			/* Oops, we don't have the same file */
2041 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2042 				failed_msg = "Couldn't reopen: Persistent "
2043 				    "file handle changed";
2044 			else
2045 				failed_msg = "Couldn't reopen: Volatile "
2046 				    "(no expire on open) file handle changed";
2047 
2048 			nfs4args_copen_free(open_args);
2049 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2050 			nfs_rw_exit(&mi->mi_fh_lock);
2051 			goto kill_file;
2052 
2053 		} else {
2054 			/*
2055 			 * We have volatile file handles that don't compare.
2056 			 * If the fids are the same then we assume that the
2057 			 * file handle expired but the rnode still refers to
2058 			 * the same file object.
2059 			 *
2060 			 * First check that we have fids or not.
2061 			 * If we don't we have a dumb server so we will
2062 			 * just assume every thing is ok for now.
2063 			 */
2064 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2065 			    rp->r_attr.va_mask & AT_NODEID &&
2066 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2067 				/*
2068 				 * We have fids, but they don't
2069 				 * compare. So kill the file.
2070 				 */
2071 				failed_msg =
2072 					"Couldn't reopen: file handle changed"
2073 				    " due to mismatched fids";
2074 				nfs4args_copen_free(open_args);
2075 				(void) xdr_free(xdr_COMPOUND4res_clnt,
2076 						(caddr_t)&res);
2077 				nfs_rw_exit(&mi->mi_fh_lock);
2078 				goto kill_file;
2079 			} else {
2080 				/*
2081 				 * We have volatile file handles that refers
2082 				 * to the same file (at least they have the
2083 				 * same fid) or we don't have fids so we
2084 				 * can't tell. :(. We'll be a kind and accepting
2085 				 * client so we'll update the rnode's file
2086 				 * handle with the otw handle.
2087 				 *
2088 				 * We need to drop mi->mi_fh_lock since
2089 				 * sh4_update acquires it. Since there is
2090 				 * only one recovery thread there is no
2091 				 * race.
2092 				 */
2093 				nfs_rw_exit(&mi->mi_fh_lock);
2094 				sfh4_update(rp->r_fh, &gf_res->object);
2095 			}
2096 		}
2097 	} else {
2098 		nfs_rw_exit(&mi->mi_fh_lock);
2099 	}
2100 
2101 	ASSERT(nfs4_consistent_type(vp));
2102 
2103 	/*
2104 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2105 	 * over.  Presumably if there is a persistent error it will show up
2106 	 * when we resend the OPEN.
2107 	 */
2108 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2109 		bool_t retry_open = FALSE;
2110 
2111 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2112 					cred_otw, is_recov, &retry_open,
2113 					oop, FALSE, ep, NULL);
2114 		if (ep->error || ep->stat) {
2115 			nfs4args_copen_free(open_args);
2116 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2117 			nfs4_end_open_seqid_sync(oop);
2118 			open_owner_rele(oop);
2119 			oop = NULL;
2120 			goto top;
2121 		}
2122 	}
2123 
2124 	mutex_enter(&osp->os_sync_lock);
2125 	osp->open_stateid = op_res->stateid;
2126 	osp->os_delegation = 0;
2127 	/*
2128 	 * Need to reset this bitfield for the possible case where we were
2129 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2130 	 * we could retry the CLOSE, OPENed the file again.
2131 	 */
2132 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2133 	osp->os_final_close = 0;
2134 	osp->os_force_close = 0;
2135 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2136 		osp->os_dc_openacc = open_args->share_access;
2137 	mutex_exit(&osp->os_sync_lock);
2138 
2139 	nfs4_end_open_seqid_sync(oop);
2140 
2141 	/* accept delegation, if any */
2142 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2143 
2144 	nfs4args_copen_free(open_args);
2145 
2146 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2147 
2148 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2149 
2150 	ASSERT(nfs4_consistent_type(vp));
2151 
2152 	open_owner_rele(oop);
2153 	crfree(cr);
2154 	crfree(cred_otw);
2155 	return;
2156 
2157 kill_file:
2158 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2159 failed_reopen:
2160 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2161 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2162 	    (void *)osp, (void *)cr, rnode4info(rp)));
2163 	mutex_enter(&osp->os_sync_lock);
2164 	osp->os_failed_reopen = 1;
2165 	mutex_exit(&osp->os_sync_lock);
2166 bailout:
2167 	if (oop != NULL) {
2168 		nfs4_end_open_seqid_sync(oop);
2169 		open_owner_rele(oop);
2170 	}
2171 	if (cr != NULL)
2172 		crfree(cr);
2173 	if (cred_otw != NULL)
2174 		crfree(cred_otw);
2175 }
2176 
2177 /* for . and .. OPENs */
2178 /* ARGSUSED */
2179 static int
2180 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2181 {
2182 	rnode4_t *rp;
2183 	nfs4_ga_res_t gar;
2184 
2185 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2186 
2187 	/*
2188 	 * If close-to-open consistency checking is turned off or
2189 	 * if there is no cached data, we can avoid
2190 	 * the over the wire getattr.  Otherwise, force a
2191 	 * call to the server to get fresh attributes and to
2192 	 * check caches. This is required for close-to-open
2193 	 * consistency.
2194 	 */
2195 	rp = VTOR4(*vpp);
2196 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2197 			(rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2198 		return (0);
2199 
2200 	gar.n4g_va.va_mask = AT_ALL;
2201 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2202 }
2203 
2204 /*
2205  * CLOSE a file
2206  */
2207 static int
2208 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr)
2209 {
2210 	rnode4_t *rp;
2211 	int pc_err = 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 		pc_err = nfs4_putpage_commit(vp, 0, 0, cr);
2282 	}
2283 
2284 	mutex_enter(&rp->r_statelock);
2285 	e.error = rp->r_error;
2286 	rp->r_error = 0;
2287 	mutex_exit(&rp->r_statelock);
2288 
2289 	/* Check to see if we need to close the file */
2290 
2291 	if (vp->v_type != VREG)
2292 		return (pc_err ? pc_err : e.error);
2293 
2294 	/* Let nfs4close_one figure out if an OTW close is needed. */
2295 	nfs4close_one(vp, NULL, cr, flag, NULL, &e, CLOSE_NORM, 0, 0, 0);
2296 
2297 	if (pc_err)
2298 		return (pc_err);
2299 
2300 	return (e.error ? e.error : geterrno4(e.stat));
2301 }
2302 
2303 /*
2304  * Initialize *lost_rqstp.
2305  */
2306 
2307 static void
2308 nfs4close_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
2309 	nfs4_open_owner_t *oop, nfs4_open_stream_t *osp, cred_t *cr,
2310 	vnode_t *vp)
2311 {
2312 	if (error != ETIMEDOUT && error != EINTR &&
2313 	    !NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
2314 		lost_rqstp->lr_op = 0;
2315 		return;
2316 	}
2317 
2318 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
2319 			"nfs4close_save_lost_rqst: error %d", error));
2320 
2321 	lost_rqstp->lr_op = OP_CLOSE;
2322 	/*
2323 	 * The vp is held and rele'd via the recovery code.
2324 	 * See nfs4_save_lost_rqst.
2325 	 */
2326 	lost_rqstp->lr_vp = vp;
2327 	lost_rqstp->lr_dvp = NULL;
2328 	lost_rqstp->lr_oop = oop;
2329 	lost_rqstp->lr_osp = osp;
2330 	ASSERT(osp != NULL);
2331 	ASSERT(mutex_owned(&osp->os_sync_lock));
2332 	osp->os_pending_close = 1;
2333 	lost_rqstp->lr_lop = NULL;
2334 	lost_rqstp->lr_cr = cr;
2335 	lost_rqstp->lr_flk = NULL;
2336 	lost_rqstp->lr_putfirst = FALSE;
2337 }
2338 
2339 /*
2340  * Assumes you already have the open seqid sync grabbed as well as the
2341  * 'os_sync_lock'.  Note: this will release the open seqid sync and
2342  * 'os_sync_lock' if client recovery starts.  Calling functions have to
2343  * be prepared to handle this.
2344  *
2345  * 'recov' is returned as 1 if the CLOSE operation detected client recovery
2346  * was needed and was started, and that the calling function should retry
2347  * this function; otherwise it is returned as 0.
2348  *
2349  * Errors are returned via the nfs4_error_t parameter.
2350  */
2351 static void
2352 nfs4close_otw(rnode4_t *rp, cred_t *cred_otw, nfs4_open_owner_t *oop,
2353 	nfs4_open_stream_t *osp, int *recov, int *did_start_seqid_syncp,
2354 	nfs4_close_type_t close_type, nfs4_error_t *ep, int *have_sync_lockp)
2355 {
2356 	COMPOUND4args_clnt args;
2357 	COMPOUND4res_clnt res;
2358 	CLOSE4args *close_args;
2359 	nfs_resop4 *resop;
2360 	nfs_argop4 argop[3];
2361 	int doqueue = 1;
2362 	mntinfo4_t *mi;
2363 	seqid4 seqid;
2364 	vnode_t *vp;
2365 	bool_t needrecov = FALSE;
2366 	nfs4_lost_rqst_t lost_rqst;
2367 	hrtime_t t;
2368 
2369 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
2370 
2371 	ASSERT(MUTEX_HELD(&osp->os_sync_lock));
2372 
2373 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw"));
2374 
2375 	/* Only set this to 1 if recovery is started */
2376 	*recov = 0;
2377 
2378 	/* do the OTW call to close the file */
2379 
2380 	if (close_type == CLOSE_RESEND)
2381 		args.ctag = TAG_CLOSE_LOST;
2382 	else if (close_type == CLOSE_AFTER_RESEND)
2383 		args.ctag = TAG_CLOSE_UNDO;
2384 	else
2385 		args.ctag = TAG_CLOSE;
2386 
2387 	args.array_len = 3;
2388 	args.array = argop;
2389 
2390 	vp = RTOV4(rp);
2391 
2392 	mi = VTOMI4(vp);
2393 
2394 	/* putfh target fh */
2395 	argop[0].argop = OP_CPUTFH;
2396 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
2397 
2398 	argop[1].argop = OP_GETATTR;
2399 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
2400 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
2401 
2402 	argop[2].argop = OP_CLOSE;
2403 	close_args = &argop[2].nfs_argop4_u.opclose;
2404 
2405 	seqid = nfs4_get_open_seqid(oop) + 1;
2406 
2407 	close_args->seqid = seqid;
2408 	close_args->open_stateid = osp->open_stateid;
2409 
2410 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
2411 	    "nfs4close_otw: %s call, rp %s", needrecov ? "recov" : "first",
2412 	    rnode4info(rp)));
2413 
2414 	t = gethrtime();
2415 
2416 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
2417 
2418 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
2419 		nfs4_set_open_seqid(seqid, oop, args.ctag);
2420 	}
2421 
2422 	needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
2423 	if (ep->error && !needrecov) {
2424 		/*
2425 		 * if there was an error and no recovery is to be done
2426 		 * then then set up the file to flush its cache if
2427 		 * needed for the next caller.
2428 		 */
2429 		mutex_enter(&rp->r_statelock);
2430 		PURGE_ATTRCACHE4_LOCKED(rp);
2431 		rp->r_flags &= ~R4WRITEMODIFIED;
2432 		mutex_exit(&rp->r_statelock);
2433 		return;
2434 	}
2435 
2436 	if (needrecov) {
2437 		bool_t abort;
2438 		nfs4_bseqid_entry_t *bsep = NULL;
2439 
2440 		if (close_type != CLOSE_RESEND)
2441 			nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
2442 				osp, cred_otw, vp);
2443 
2444 		if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
2445 			bsep = nfs4_create_bseqid_entry(oop, NULL, vp,
2446 				0, args.ctag, close_args->seqid);
2447 
2448 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
2449 			"nfs4close_otw: initiating recovery. error %d "
2450 			"res.status %d", ep->error, res.status));
2451 
2452 		/*
2453 		 * Drop the 'os_sync_lock' here so we don't hit
2454 		 * a potential recursive mutex_enter via an
2455 		 * 'open_stream_hold()'.
2456 		 */
2457 		mutex_exit(&osp->os_sync_lock);
2458 		*have_sync_lockp = 0;
2459 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
2460 			    (close_type != CLOSE_RESEND &&
2461 			    lost_rqst.lr_op == OP_CLOSE) ? &lost_rqst : NULL,
2462 			    OP_CLOSE, bsep);
2463 
2464 		/* drop open seq sync, and let the calling function regrab it */
2465 		nfs4_end_open_seqid_sync(oop);
2466 		*did_start_seqid_syncp = 0;
2467 
2468 		if (bsep)
2469 			kmem_free(bsep, sizeof (*bsep));
2470 		/*
2471 		 * For signals, the caller wants to quit, so don't say to
2472 		 * retry.  For forced unmount, if it's a user thread, it
2473 		 * wants to quit.  If it's a recovery thread, the retry
2474 		 * will happen higher-up on the call stack.  Either way,
2475 		 * don't say to retry.
2476 		 */
2477 		if (abort == FALSE && ep->error != EINTR &&
2478 		    !NFS4_FRC_UNMT_ERR(ep->error, mi->mi_vfsp) &&
2479 		    close_type != CLOSE_RESEND &&
2480 		    close_type != CLOSE_AFTER_RESEND)
2481 			*recov = 1;
2482 		else
2483 			*recov = 0;
2484 
2485 		if (!ep->error)
2486 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2487 		return;
2488 	}
2489 
2490 	if (res.status) {
2491 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2492 		return;
2493 	}
2494 
2495 	mutex_enter(&rp->r_statev4_lock);
2496 	rp->created_v4 = 0;
2497 	mutex_exit(&rp->r_statev4_lock);
2498 
2499 	resop = &res.array[2];
2500 	osp->open_stateid = resop->nfs_resop4_u.opclose.open_stateid;
2501 	osp->os_valid = 0;
2502 
2503 	/*
2504 	 * This removes the reference obtained at OPEN; ie, when the
2505 	 * open stream structure was created.
2506 	 *
2507 	 * We don't have to worry about calling 'open_stream_rele'
2508 	 * since we our currently holding a reference to the open
2509 	 * stream which means the count cannot go to 0 with this
2510 	 * decrement.
2511 	 */
2512 	ASSERT(osp->os_ref_count >= 2);
2513 	osp->os_ref_count--;
2514 
2515 	if (!ep->error)
2516 		nfs4_attr_cache(vp,
2517 				&res.array[1].nfs_resop4_u.opgetattr.ga_res,
2518 				t, cred_otw, TRUE, NULL);
2519 
2520 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw:"
2521 		" returning %d", ep->error));
2522 
2523 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2524 }
2525 
2526 /* ARGSUSED */
2527 static int
2528 nfs4_read(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2529 	caller_context_t *ct)
2530 {
2531 	rnode4_t *rp;
2532 	u_offset_t off;
2533 	offset_t diff;
2534 	uint_t on;
2535 	uint_t n;
2536 	caddr_t base;
2537 	uint_t flags;
2538 	int error;
2539 	mntinfo4_t *mi;
2540 
2541 	rp = VTOR4(vp);
2542 
2543 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2544 
2545 	if (IS_SHADOW(vp, rp))
2546 		vp = RTOV4(rp);
2547 
2548 	if (vp->v_type != VREG)
2549 		return (EISDIR);
2550 
2551 	mi = VTOMI4(vp);
2552 
2553 	if (nfs_zone() != mi->mi_zone)
2554 		return (EIO);
2555 
2556 	if (uiop->uio_resid == 0)
2557 		return (0);
2558 
2559 	if (uiop->uio_loffset < 0 || uiop->uio_loffset + uiop->uio_resid < 0)
2560 		return (EINVAL);
2561 
2562 	mutex_enter(&rp->r_statelock);
2563 	if (rp->r_flags & R4RECOVERRP)
2564 		error = (rp->r_error ? rp->r_error : EIO);
2565 	else
2566 		error = 0;
2567 	mutex_exit(&rp->r_statelock);
2568 	if (error)
2569 		return (error);
2570 
2571 	/*
2572 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2573 	 * using client-side direct I/O and the file is not mmap'd and
2574 	 * there are no cached pages.
2575 	 */
2576 	if ((vp->v_flag & VNOCACHE) ||
2577 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2578 	    rp->r_mapcnt == 0 && !nfs4_has_pages(vp))) {
2579 		size_t resid = 0;
2580 
2581 		return (nfs4read(vp, NULL, uiop->uio_loffset,
2582 				uiop->uio_resid, &resid, cr, FALSE, uiop));
2583 	}
2584 
2585 	error = 0;
2586 
2587 	do {
2588 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2589 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2590 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2591 
2592 		if (error = nfs4_validate_caches(vp, cr))
2593 			break;
2594 
2595 		mutex_enter(&rp->r_statelock);
2596 		diff = rp->r_size - uiop->uio_loffset;
2597 		mutex_exit(&rp->r_statelock);
2598 		if (diff <= 0)
2599 			break;
2600 		if (diff < n)
2601 			n = (uint_t)diff;
2602 
2603 		base = segmap_getmapflt(segkmap, vp, off + on, n, 1, S_READ);
2604 
2605 		error = uiomove(base + on, n, UIO_READ, uiop);
2606 
2607 		if (!error) {
2608 			/*
2609 			 * If read a whole block or read to eof,
2610 			 * won't need this buffer again soon.
2611 			 */
2612 			mutex_enter(&rp->r_statelock);
2613 			if (n + on == MAXBSIZE ||
2614 			    uiop->uio_loffset == rp->r_size)
2615 				flags = SM_DONTNEED;
2616 			else
2617 				flags = 0;
2618 			mutex_exit(&rp->r_statelock);
2619 			error = segmap_release(segkmap, base, flags);
2620 		} else
2621 			(void) segmap_release(segkmap, base, 0);
2622 	} while (!error && uiop->uio_resid > 0);
2623 
2624 	return (error);
2625 }
2626 
2627 /* ARGSUSED */
2628 static int
2629 nfs4_write(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2630 		caller_context_t *ct)
2631 {
2632 	rlim64_t limit = uiop->uio_llimit;
2633 	rnode4_t *rp;
2634 	u_offset_t off;
2635 	caddr_t base;
2636 	uint_t flags;
2637 	int remainder;
2638 	size_t n;
2639 	int on;
2640 	int error;
2641 	int resid;
2642 	u_offset_t offset;
2643 	mntinfo4_t *mi;
2644 	uint_t bsize;
2645 
2646 	rp = VTOR4(vp);
2647 
2648 	if (IS_SHADOW(vp, rp))
2649 		vp = RTOV4(rp);
2650 
2651 	if (vp->v_type != VREG)
2652 		return (EISDIR);
2653 
2654 	mi = VTOMI4(vp);
2655 
2656 	if (nfs_zone() != mi->mi_zone)
2657 		return (EIO);
2658 
2659 	if (uiop->uio_resid == 0)
2660 		return (0);
2661 
2662 	mutex_enter(&rp->r_statelock);
2663 	if (rp->r_flags & R4RECOVERRP)
2664 		error = (rp->r_error ? rp->r_error : EIO);
2665 	else
2666 		error = 0;
2667 	mutex_exit(&rp->r_statelock);
2668 	if (error)
2669 		return (error);
2670 
2671 	if (ioflag & FAPPEND) {
2672 		struct vattr va;
2673 
2674 		/*
2675 		 * Must serialize if appending.
2676 		 */
2677 		if (nfs_rw_lock_held(&rp->r_rwlock, RW_READER)) {
2678 			nfs_rw_exit(&rp->r_rwlock);
2679 			if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER,
2680 			    INTR(vp)))
2681 				return (EINTR);
2682 		}
2683 
2684 		va.va_mask = AT_SIZE;
2685 		error = nfs4getattr(vp, &va, cr);
2686 		if (error)
2687 			return (error);
2688 		uiop->uio_loffset = va.va_size;
2689 	}
2690 
2691 	offset = uiop->uio_loffset + uiop->uio_resid;
2692 
2693 	if (uiop->uio_loffset < (offset_t)0 || offset < 0)
2694 		return (EINVAL);
2695 
2696 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
2697 		limit = MAXOFFSET_T;
2698 
2699 	/*
2700 	 * Check to make sure that the process will not exceed
2701 	 * its limit on file size.  It is okay to write up to
2702 	 * the limit, but not beyond.  Thus, the write which
2703 	 * reaches the limit will be short and the next write
2704 	 * will return an error.
2705 	 */
2706 	remainder = 0;
2707 	if (offset > uiop->uio_llimit) {
2708 		remainder = offset - uiop->uio_llimit;
2709 		uiop->uio_resid = uiop->uio_llimit - uiop->uio_loffset;
2710 		if (uiop->uio_resid <= 0) {
2711 			proc_t *p = ttoproc(curthread);
2712 
2713 			uiop->uio_resid += remainder;
2714 			mutex_enter(&p->p_lock);
2715 			(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE],
2716 			    p->p_rctls, p, RCA_UNSAFE_SIGINFO);
2717 			mutex_exit(&p->p_lock);
2718 			return (EFBIG);
2719 		}
2720 	}
2721 
2722 	/* update the change attribute, if we have a write delegation */
2723 
2724 	mutex_enter(&rp->r_statev4_lock);
2725 	if (rp->r_deleg_type == OPEN_DELEGATE_WRITE)
2726 		rp->r_deleg_change++;
2727 
2728 	mutex_exit(&rp->r_statev4_lock);
2729 
2730 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
2731 		return (EINTR);
2732 
2733 	/*
2734 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2735 	 * using client-side direct I/O and the file is not mmap'd and
2736 	 * there are no cached pages.
2737 	 */
2738 	if ((vp->v_flag & VNOCACHE) ||
2739 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2740 	    rp->r_mapcnt == 0 && !nfs4_has_pages(vp))) {
2741 		size_t bufsize;
2742 		int count;
2743 		u_offset_t org_offset;
2744 		stable_how4 stab_comm;
2745 nfs4_fwrite:
2746 		if (rp->r_flags & R4STALE) {
2747 			resid = uiop->uio_resid;
2748 			offset = uiop->uio_loffset;
2749 			error = rp->r_error;
2750 			goto bottom;
2751 		}
2752 
2753 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2754 		base = kmem_alloc(bufsize, KM_SLEEP);
2755 		do {
2756 			if (ioflag & FDSYNC)
2757 				stab_comm = DATA_SYNC4;
2758 			else
2759 				stab_comm = FILE_SYNC4;
2760 			resid = uiop->uio_resid;
2761 			offset = uiop->uio_loffset;
2762 			count = MIN(uiop->uio_resid, bufsize);
2763 			org_offset = uiop->uio_loffset;
2764 			error = uiomove(base, count, UIO_WRITE, uiop);
2765 			if (!error) {
2766 				error = nfs4write(vp, base, org_offset,
2767 						count, cr, &stab_comm);
2768 				if (!error) {
2769 					mutex_enter(&rp->r_statelock);
2770 					if (rp->r_size < uiop->uio_loffset)
2771 						rp->r_size = uiop->uio_loffset;
2772 					mutex_exit(&rp->r_statelock);
2773 				}
2774 			}
2775 		} while (!error && uiop->uio_resid > 0);
2776 		kmem_free(base, bufsize);
2777 		goto bottom;
2778 	}
2779 
2780 	bsize = vp->v_vfsp->vfs_bsize;
2781 
2782 	do {
2783 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2784 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2785 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2786 
2787 		resid = uiop->uio_resid;
2788 		offset = uiop->uio_loffset;
2789 
2790 		if (rp->r_flags & R4STALE) {
2791 			error = rp->r_error;
2792 			break;
2793 		}
2794 
2795 		/*
2796 		 * Don't create dirty pages faster than they
2797 		 * can be cleaned so that the system doesn't
2798 		 * get imbalanced.  If the async queue is
2799 		 * maxed out, then wait for it to drain before
2800 		 * creating more dirty pages.  Also, wait for
2801 		 * any threads doing pagewalks in the vop_getattr
2802 		 * entry points so that they don't block for
2803 		 * long periods.
2804 		 */
2805 		mutex_enter(&rp->r_statelock);
2806 		while ((mi->mi_max_threads != 0 &&
2807 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2808 		    rp->r_gcount > 0)
2809 			cv_wait(&rp->r_cv, &rp->r_statelock);
2810 		mutex_exit(&rp->r_statelock);
2811 
2812 		if (segmap_kpm) {
2813 			int pon = uiop->uio_loffset & PAGEOFFSET;
2814 			size_t pn = MIN(PAGESIZE - pon, uiop->uio_resid);
2815 			int pagecreate;
2816 
2817 			mutex_enter(&rp->r_statelock);
2818 			pagecreate = (pon == 0) && (pn == PAGESIZE ||
2819 				uiop->uio_loffset + pn >= rp->r_size);
2820 			mutex_exit(&rp->r_statelock);
2821 
2822 			base = segmap_getmapflt(segkmap, vp, off + on,
2823 						pn, !pagecreate, S_WRITE);
2824 
2825 			error = writerp4(rp, base + pon, n, uiop, pagecreate);
2826 
2827 		} else {
2828 			base = segmap_getmapflt(segkmap, vp, off + on,
2829 						n, 0, S_READ);
2830 			error = writerp4(rp, base + on, n, uiop, 0);
2831 		}
2832 
2833 		if (!error) {
2834 			if (mi->mi_flags & MI4_NOAC)
2835 				flags = SM_WRITE;
2836 			else if ((uiop->uio_loffset % bsize) == 0 ||
2837 			    IS_SWAPVP(vp)) {
2838 				/*
2839 				 * Have written a whole block.
2840 				 * Start an asynchronous write
2841 				 * and mark the buffer to
2842 				 * indicate that it won't be
2843 				 * needed again soon.
2844 				 */
2845 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
2846 			} else
2847 				flags = 0;
2848 			if ((ioflag & (FSYNC|FDSYNC)) ||
2849 			    (rp->r_flags & R4OUTOFSPACE)) {
2850 				flags &= ~SM_ASYNC;
2851 				flags |= SM_WRITE;
2852 			}
2853 			error = segmap_release(segkmap, base, flags);
2854 		} else {
2855 			(void) segmap_release(segkmap, base, 0);
2856 			/*
2857 			 * In the event that we got an access error while
2858 			 * faulting in a page for a write-only file just
2859 			 * force a write.
2860 			 */
2861 			if (error == EACCES)
2862 				goto nfs4_fwrite;
2863 		}
2864 	} while (!error && uiop->uio_resid > 0);
2865 
2866 bottom:
2867 	if (error) {
2868 		uiop->uio_resid = resid + remainder;
2869 		uiop->uio_loffset = offset;
2870 	} else {
2871 		uiop->uio_resid += remainder;
2872 
2873 		mutex_enter(&rp->r_statev4_lock);
2874 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
2875 			gethrestime(&rp->r_attr.va_mtime);
2876 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
2877 		}
2878 		mutex_exit(&rp->r_statev4_lock);
2879 	}
2880 
2881 	nfs_rw_exit(&rp->r_lkserlock);
2882 
2883 	return (error);
2884 }
2885 
2886 /*
2887  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
2888  */
2889 static int
2890 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
2891 	int flags, cred_t *cr)
2892 {
2893 	struct buf *bp;
2894 	int error;
2895 	page_t *savepp;
2896 	uchar_t fsdata;
2897 	stable_how4 stab_comm;
2898 
2899 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
2900 	bp = pageio_setup(pp, len, vp, flags);
2901 	ASSERT(bp != NULL);
2902 
2903 	/*
2904 	 * pageio_setup should have set b_addr to 0.  This
2905 	 * is correct since we want to do I/O on a page
2906 	 * boundary.  bp_mapin will use this addr to calculate
2907 	 * an offset, and then set b_addr to the kernel virtual
2908 	 * address it allocated for us.
2909 	 */
2910 	ASSERT(bp->b_un.b_addr == 0);
2911 
2912 	bp->b_edev = 0;
2913 	bp->b_dev = 0;
2914 	bp->b_lblkno = lbtodb(off);
2915 	bp->b_file = vp;
2916 	bp->b_offset = (offset_t)off;
2917 	bp_mapin(bp);
2918 
2919 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
2920 	    freemem > desfree)
2921 		stab_comm = UNSTABLE4;
2922 	else
2923 		stab_comm = FILE_SYNC4;
2924 
2925 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
2926 
2927 	bp_mapout(bp);
2928 	pageio_done(bp);
2929 
2930 	if (stab_comm == UNSTABLE4)
2931 		fsdata = C_DELAYCOMMIT;
2932 	else
2933 		fsdata = C_NOCOMMIT;
2934 
2935 	savepp = pp;
2936 	do {
2937 		pp->p_fsdata = fsdata;
2938 	} while ((pp = pp->p_next) != savepp);
2939 
2940 	return (error);
2941 }
2942 
2943 /*
2944  */
2945 static int
2946 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
2947 {
2948 	nfs4_open_owner_t	*oop;
2949 	nfs4_open_stream_t	*osp;
2950 	rnode4_t		*rp = VTOR4(vp);
2951 	mntinfo4_t 		*mi = VTOMI4(vp);
2952 	int 			reopen_needed;
2953 
2954 	ASSERT(nfs_zone() == mi->mi_zone);
2955 
2956 
2957 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
2958 	if (!oop)
2959 		return (EIO);
2960 
2961 	/* returns with 'os_sync_lock' held */
2962 	osp = find_open_stream(oop, rp);
2963 	if (!osp) {
2964 		open_owner_rele(oop);
2965 		return (EIO);
2966 	}
2967 
2968 	if (osp->os_failed_reopen) {
2969 		mutex_exit(&osp->os_sync_lock);
2970 		open_stream_rele(osp, rp);
2971 		open_owner_rele(oop);
2972 		return (EIO);
2973 	}
2974 
2975 	/*
2976 	 * Determine whether a reopen is needed.  If this
2977 	 * is a delegation open stream, then the os_delegation bit
2978 	 * should be set.
2979 	 */
2980 
2981 	reopen_needed = osp->os_delegation;
2982 
2983 	mutex_exit(&osp->os_sync_lock);
2984 	open_owner_rele(oop);
2985 
2986 	if (reopen_needed) {
2987 		nfs4_error_zinit(ep);
2988 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
2989 		mutex_enter(&osp->os_sync_lock);
2990 		if (ep->error || ep->stat || osp->os_failed_reopen) {
2991 			mutex_exit(&osp->os_sync_lock);
2992 			open_stream_rele(osp, rp);
2993 			return (EIO);
2994 		}
2995 		mutex_exit(&osp->os_sync_lock);
2996 	}
2997 	open_stream_rele(osp, rp);
2998 
2999 	return (0);
3000 }
3001 
3002 /*
3003  * Write to file.  Writes to remote server in largest size
3004  * chunks that the server can handle.  Write is synchronous.
3005  */
3006 static int
3007 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3008 	stable_how4 *stab_comm)
3009 {
3010 	mntinfo4_t *mi;
3011 	COMPOUND4args_clnt args;
3012 	COMPOUND4res_clnt res;
3013 	WRITE4args *wargs;
3014 	WRITE4res *wres;
3015 	nfs_argop4 argop[2];
3016 	nfs_resop4 *resop;
3017 	int tsize;
3018 	stable_how4 stable;
3019 	rnode4_t *rp;
3020 	int doqueue = 1;
3021 	bool_t needrecov;
3022 	nfs4_recov_state_t recov_state;
3023 	nfs4_stateid_types_t sid_types;
3024 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3025 
3026 	rp = VTOR4(vp);
3027 	mi = VTOMI4(vp);
3028 
3029 	ASSERT(nfs_zone() == mi->mi_zone);
3030 
3031 	stable = *stab_comm;
3032 	*stab_comm = FILE_SYNC4;
3033 
3034 	needrecov = FALSE;
3035 	recov_state.rs_flags = 0;
3036 	recov_state.rs_num_retry_despite_err = 0;
3037 	nfs4_init_stateid_types(&sid_types);
3038 
3039 recov_retry:
3040 	args.ctag = TAG_WRITE;
3041 	args.array_len = 2;
3042 	args.array = argop;
3043 
3044 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3045 			    &recov_state, NULL);
3046 	if (e.error)
3047 		return (e.error);
3048 
3049 	/* 0. putfh target fh */
3050 	argop[0].argop = OP_CPUTFH;
3051 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3052 
3053 	/* 1. write */
3054 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3055 
3056 	do {
3057 
3058 		wargs->offset = (offset4)offset;
3059 		wargs->data_val = base;
3060 
3061 		if (mi->mi_io_kstats) {
3062 			mutex_enter(&mi->mi_lock);
3063 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3064 			mutex_exit(&mi->mi_lock);
3065 		}
3066 
3067 		if ((vp->v_flag & VNOCACHE) ||
3068 		    (rp->r_flags & R4DIRECTIO) ||
3069 		    (mi->mi_flags & MI4_DIRECTIO))
3070 			tsize = MIN(mi->mi_stsize, count);
3071 		else
3072 			tsize = MIN(mi->mi_curwrite, count);
3073 		wargs->data_len = (uint_t)tsize;
3074 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3075 
3076 		if (mi->mi_io_kstats) {
3077 			mutex_enter(&mi->mi_lock);
3078 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3079 			mutex_exit(&mi->mi_lock);
3080 		}
3081 
3082 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3083 		if (e.error && !needrecov) {
3084 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3085 				&recov_state, needrecov);
3086 			return (e.error);
3087 		}
3088 
3089 
3090 		/*
3091 		 * Do handling of OLD_STATEID outside
3092 		 * of the normal recovery framework.
3093 		 *
3094 		 * If write receives a BAD stateid error while using a
3095 		 * delegation stateid, retry using the open stateid (if it
3096 		 * exists).  If it doesn't have an open stateid, reopen the
3097 		 * file first, then retry.
3098 		 */
3099 		if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3100 		    sid_types.cur_sid_type != SPEC_SID) {
3101 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3102 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3103 				&recov_state, needrecov);
3104 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3105 			goto recov_retry;
3106 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3107 			    sid_types.cur_sid_type == DEL_SID) {
3108 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3109 			mutex_enter(&rp->r_statev4_lock);
3110 			rp->r_deleg_return_pending = TRUE;
3111 			mutex_exit(&rp->r_statev4_lock);
3112 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3113 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3114 					&recov_state, needrecov);
3115 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3116 								(caddr_t)&res);
3117 				return (EIO);
3118 			}
3119 			nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3120 				&recov_state, needrecov);
3121 			/* hold needed for nfs4delegreturn_thread */
3122 			VN_HOLD(vp);
3123 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3124 				NFS4_DR_DISCARD), FALSE);
3125 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3126 			goto recov_retry;
3127 		}
3128 
3129 		if (needrecov) {
3130 			bool_t abort;
3131 
3132 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3133 				"nfs4write: client got error %d, res.status %d"
3134 				", so start recovery", e.error, res.status));
3135 
3136 			abort = nfs4_start_recovery(&e,
3137 				    VTOMI4(vp), vp, NULL, &wargs->stateid,
3138 				    NULL, OP_WRITE, NULL);
3139 			if (!e.error) {
3140 				e.error = geterrno4(res.status);
3141 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3142 								(caddr_t)&res);
3143 			}
3144 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3145 				&recov_state, needrecov);
3146 			if (abort == FALSE)
3147 				goto recov_retry;
3148 			return (e.error);
3149 		}
3150 
3151 		if (res.status) {
3152 			e.error = geterrno4(res.status);
3153 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3154 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3155 				&recov_state, needrecov);
3156 			return (e.error);
3157 		}
3158 
3159 		resop = &res.array[1];	/* write res */
3160 		wres = &resop->nfs_resop4_u.opwrite;
3161 
3162 		if ((int)wres->count > tsize) {
3163 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3164 
3165 			zcmn_err(getzoneid(), CE_WARN,
3166 			"nfs4write: server wrote %u, requested was %u",
3167 			    (int)wres->count, tsize);
3168 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3169 				&recov_state, needrecov);
3170 			return (EIO);
3171 		}
3172 		if (wres->committed == UNSTABLE4) {
3173 			*stab_comm = UNSTABLE4;
3174 			if (wargs->stable == DATA_SYNC4 ||
3175 			    wargs->stable == FILE_SYNC4) {
3176 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3177 								(caddr_t)&res);
3178 				zcmn_err(getzoneid(), CE_WARN,
3179 					"nfs4write: server %s did not commit "
3180 					"to stable storage",
3181 					rp->r_server->sv_hostname);
3182 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3183 						&recov_state, needrecov);
3184 				return (EIO);
3185 			}
3186 		}
3187 
3188 		tsize = (int)wres->count;
3189 		count -= tsize;
3190 		base += tsize;
3191 		offset += tsize;
3192 		if (mi->mi_io_kstats) {
3193 			mutex_enter(&mi->mi_lock);
3194 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3195 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3196 			    tsize;
3197 			mutex_exit(&mi->mi_lock);
3198 		}
3199 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3200 		mutex_enter(&rp->r_statelock);
3201 		if (rp->r_flags & R4HAVEVERF) {
3202 			if (rp->r_writeverf != wres->writeverf) {
3203 				nfs4_set_mod(vp);
3204 				rp->r_writeverf = wres->writeverf;
3205 			}
3206 		} else {
3207 			rp->r_writeverf = wres->writeverf;
3208 			rp->r_flags |= R4HAVEVERF;
3209 		}
3210 		PURGE_ATTRCACHE4_LOCKED(rp);
3211 		rp->r_flags |= R4WRITEMODIFIED;
3212 		gethrestime(&rp->r_attr.va_mtime);
3213 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3214 		mutex_exit(&rp->r_statelock);
3215 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3216 	} while (count);
3217 
3218 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state, needrecov);
3219 
3220 	return (e.error);
3221 }
3222 
3223 /*
3224  * Read from a file.  Reads data in largest chunks our interface can handle.
3225  */
3226 static int
3227 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3228 	size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3229 {
3230 	mntinfo4_t *mi;
3231 	COMPOUND4args_clnt args;
3232 	COMPOUND4res_clnt res;
3233 	READ4args *rargs;
3234 	nfs_argop4 argop[2];
3235 	int tsize;
3236 	int doqueue;
3237 	rnode4_t *rp;
3238 	int data_len;
3239 	bool_t is_eof;
3240 	bool_t needrecov = FALSE;
3241 	nfs4_recov_state_t recov_state;
3242 	nfs4_stateid_types_t sid_types;
3243 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3244 
3245 	rp = VTOR4(vp);
3246 	mi = VTOMI4(vp);
3247 	doqueue = 1;
3248 
3249 	ASSERT(nfs_zone() == mi->mi_zone);
3250 
3251 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3252 
3253 	args.array_len = 2;
3254 	args.array = argop;
3255 
3256 	nfs4_init_stateid_types(&sid_types);
3257 
3258 	recov_state.rs_flags = 0;
3259 	recov_state.rs_num_retry_despite_err = 0;
3260 
3261 recov_retry:
3262 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3263 			    &recov_state, NULL);
3264 	if (e.error)
3265 		return (e.error);
3266 
3267 	/* putfh target fh */
3268 	argop[0].argop = OP_CPUTFH;
3269 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3270 
3271 	/* read */
3272 	argop[1].argop = OP_READ;
3273 	rargs = &argop[1].nfs_argop4_u.opread;
3274 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3275 				OP_READ, &sid_types, async);
3276 
3277 	do {
3278 		if (mi->mi_io_kstats) {
3279 			mutex_enter(&mi->mi_lock);
3280 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3281 			mutex_exit(&mi->mi_lock);
3282 		}
3283 
3284 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3285 		    "nfs4read: %s call, rp %s",
3286 		    needrecov ? "recov" : "first",
3287 		    rnode4info(rp)));
3288 
3289 		if ((vp->v_flag & VNOCACHE) ||
3290 		    (rp->r_flags & R4DIRECTIO) ||
3291 		    (mi->mi_flags & MI4_DIRECTIO))
3292 			tsize = MIN(mi->mi_tsize, count);
3293 		else
3294 			tsize = MIN(mi->mi_curread, count);
3295 		rargs->offset = (offset4)offset;
3296 		rargs->count = (count4)tsize;
3297 		rargs->res_data_val_alt = NULL;
3298 		rargs->res_mblk = NULL;
3299 		rargs->res_uiop = NULL;
3300 		rargs->res_maxsize = 0;
3301 		if (uiop)
3302 			rargs->res_uiop = uiop;
3303 		else
3304 			rargs->res_data_val_alt = base;
3305 		rargs->res_maxsize = tsize;
3306 
3307 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3308 #ifdef	DEBUG
3309 		if (nfs4read_error_inject) {
3310 			res.status = nfs4read_error_inject;
3311 			nfs4read_error_inject = 0;
3312 		}
3313 #endif
3314 
3315 		if (mi->mi_io_kstats) {
3316 			mutex_enter(&mi->mi_lock);
3317 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3318 			mutex_exit(&mi->mi_lock);
3319 		}
3320 
3321 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3322 		if (e.error != 0 && !needrecov) {
3323 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3324 				&recov_state, needrecov);
3325 			return (e.error);
3326 		}
3327 
3328 		/*
3329 		 * Do proper retry for OLD and BAD stateid errors outside
3330 		 * of the normal recovery framework.  There are two differences
3331 		 * between async and sync reads.  The first is that we allow
3332 		 * retry on BAD_STATEID for async reads, but not sync reads.
3333 		 * The second is that we mark the file dead for a failed
3334 		 * attempt with a special stateid for sync reads, but just
3335 		 * return EIO for async reads.
3336 		 *
3337 		 * If a sync read receives a BAD stateid error while using a
3338 		 * delegation stateid, retry using the open stateid (if it
3339 		 * exists).  If it doesn't have an open stateid, reopen the
3340 		 * file first, then retry.
3341 		 */
3342 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3343 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3344 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3345 				&recov_state, needrecov);
3346 			if (sid_types.cur_sid_type == SPEC_SID) {
3347 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3348 						(caddr_t)&res);
3349 				return (EIO);
3350 			}
3351 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3352 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3353 			goto recov_retry;
3354 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3355 			    !async && sid_types.cur_sid_type != SPEC_SID) {
3356 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3357 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3358 				&recov_state, needrecov);
3359 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3360 			goto recov_retry;
3361 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3362 			    sid_types.cur_sid_type == DEL_SID) {
3363 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3364 			mutex_enter(&rp->r_statev4_lock);
3365 			rp->r_deleg_return_pending = TRUE;
3366 			mutex_exit(&rp->r_statev4_lock);
3367 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3368 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3369 					&recov_state, needrecov);
3370 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3371 				    (caddr_t)&res);
3372 				return (EIO);
3373 			}
3374 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3375 				&recov_state, needrecov);
3376 			/* hold needed for nfs4delegreturn_thread */
3377 			VN_HOLD(vp);
3378 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3379 				NFS4_DR_DISCARD), FALSE);
3380 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3381 			goto recov_retry;
3382 		}
3383 		if (needrecov) {
3384 			bool_t abort;
3385 
3386 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3387 			    "nfs4read: initiating recovery\n"));
3388 
3389 			abort = nfs4_start_recovery(&e,
3390 				    mi, vp, NULL, &rargs->stateid,
3391 				    NULL, OP_READ, NULL);
3392 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3393 				&recov_state, needrecov);
3394 			/*
3395 			 * Do not retry if we got OLD_STATEID using a special
3396 			 * stateid.  This avoids looping with a broken server.
3397 			 */
3398 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3399 			    sid_types.cur_sid_type == SPEC_SID)
3400 				abort = TRUE;
3401 
3402 			if (abort == FALSE) {
3403 				/*
3404 				 * Need to retry all possible stateids in
3405 				 * case the recovery error wasn't stateid
3406 				 * related or the stateids have become
3407 				 * stale (server reboot).
3408 				 */
3409 				nfs4_init_stateid_types(&sid_types);
3410 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3411 						(caddr_t)&res);
3412 				goto recov_retry;
3413 			}
3414 
3415 			if (!e.error) {
3416 				e.error = geterrno4(res.status);
3417 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3418 						(caddr_t)&res);
3419 			}
3420 			return (e.error);
3421 		}
3422 
3423 		if (res.status) {
3424 			e.error = geterrno4(res.status);
3425 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3426 				&recov_state, needrecov);
3427 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3428 			return (e.error);
3429 		}
3430 
3431 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3432 		count -= data_len;
3433 		if (base)
3434 			base += data_len;
3435 		offset += data_len;
3436 		if (mi->mi_io_kstats) {
3437 			mutex_enter(&mi->mi_lock);
3438 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3439 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3440 			mutex_exit(&mi->mi_lock);
3441 		}
3442 		lwp_stat_update(LWP_STAT_INBLK, 1);
3443 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3444 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3445 
3446 	} while (count && !is_eof);
3447 
3448 	*residp = count;
3449 
3450 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3451 
3452 	return (e.error);
3453 }
3454 
3455 /* ARGSUSED */
3456 static int
3457 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp)
3458 {
3459 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3460 		return (EIO);
3461 	switch (cmd) {
3462 		case _FIODIRECTIO:
3463 			return (nfs4_directio(vp, (int)arg, cr));
3464 		default:
3465 			return (ENOTTY);
3466 	}
3467 }
3468 
3469 static int
3470 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr)
3471 {
3472 	int error;
3473 	rnode4_t *rp = VTOR4(vp);
3474 
3475 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3476 		return (EIO);
3477 	/*
3478 	 * If it has been specified that the return value will
3479 	 * just be used as a hint, and we are only being asked
3480 	 * for size, fsid or rdevid, then return the client's
3481 	 * notion of these values without checking to make sure
3482 	 * that the attribute cache is up to date.
3483 	 * The whole point is to avoid an over the wire GETATTR
3484 	 * call.
3485 	 */
3486 	if (flags & ATTR_HINT) {
3487 		if (vap->va_mask ==
3488 		    (vap->va_mask & (AT_SIZE | AT_FSID | AT_RDEV))) {
3489 			mutex_enter(&rp->r_statelock);
3490 			if (vap->va_mask | AT_SIZE)
3491 				vap->va_size = rp->r_size;
3492 			if (vap->va_mask | AT_FSID)
3493 				vap->va_fsid = rp->r_attr.va_fsid;
3494 			if (vap->va_mask | AT_RDEV)
3495 				vap->va_rdev = rp->r_attr.va_rdev;
3496 			mutex_exit(&rp->r_statelock);
3497 			return (0);
3498 		}
3499 	}
3500 
3501 	/*
3502 	 * Only need to flush pages if asking for the mtime
3503 	 * and if there any dirty pages or any outstanding
3504 	 * asynchronous (write) requests for this file.
3505 	 */
3506 	if (vap->va_mask & AT_MTIME) {
3507 		rp = VTOR4(vp);
3508 		if (nfs4_has_pages(vp)) {
3509 			mutex_enter(&rp->r_statev4_lock);
3510 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3511 				mutex_exit(&rp->r_statev4_lock);
3512 				if (rp->r_flags & R4DIRTY ||
3513 				    rp->r_awcount > 0) {
3514 					mutex_enter(&rp->r_statelock);
3515 					rp->r_gcount++;
3516 					mutex_exit(&rp->r_statelock);
3517 					error =
3518 						nfs4_putpage(vp, (u_offset_t)0,
3519 								0, 0, cr);
3520 					mutex_enter(&rp->r_statelock);
3521 					if (error && (error == ENOSPC ||
3522 							error == EDQUOT)) {
3523 						if (!rp->r_error)
3524 							rp->r_error = error;
3525 					}
3526 					if (--rp->r_gcount == 0)
3527 						cv_broadcast(&rp->r_cv);
3528 					mutex_exit(&rp->r_statelock);
3529 				}
3530 			} else {
3531 				mutex_exit(&rp->r_statev4_lock);
3532 			}
3533 		}
3534 	}
3535 	return (nfs4getattr(vp, vap, cr));
3536 }
3537 
3538 int
3539 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3540 {
3541 	/*
3542 	 * If these are the only two bits cleared
3543 	 * on the server then return 0 (OK) else
3544 	 * return 1 (BAD).
3545 	 */
3546 	on_client &= ~(S_ISUID|S_ISGID);
3547 	if (on_client == from_server)
3548 		return (0);
3549 	else
3550 		return (1);
3551 }
3552 
3553 /*ARGSUSED4*/
3554 static int
3555 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3556 		caller_context_t *ct)
3557 {
3558 	if (vap->va_mask & AT_NOSET)
3559 		return (EINVAL);
3560 
3561 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3562 		return (EIO);
3563 
3564 	/*
3565 	 * Don't call secpolicy_vnode_setattr, the client cannot
3566 	 * use its cached attributes to make security decisions
3567 	 * as the server may be faking mode bits or mapping uid/gid.
3568 	 * Always just let the server to the checking.
3569 	 * If we provide the ability to remove basic priviledges
3570 	 * to setattr (e.g. basic without chmod) then we will
3571 	 * need to add a check here before calling the server.
3572 	 */
3573 
3574 	return (nfs4setattr(vp, vap, flags, cr, NULL));
3575 }
3576 
3577 /*
3578  * To replace the "guarded" version 3 setattr, we use two types of compound
3579  * setattr requests:
3580  * 1. The "normal" setattr, used when the size of the file isn't being
3581  *    changed - { Putfh <fh>; Setattr; Getattr }/
3582  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3583  *    with only ctime as the argument. If the server ctime differs from
3584  *    what is cached on the client, the verify will fail, but we would
3585  *    already have the ctime from the preceding getattr, so just set it
3586  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3587  *	Setattr; Getattr }.
3588  *
3589  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3590  * this setattr and NULL if they are not.
3591  */
3592 static int
3593 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3594 		vsecattr_t *vsap)
3595 {
3596 	COMPOUND4args_clnt args;
3597 	COMPOUND4res_clnt res, *resp = NULL;
3598 	nfs4_ga_res_t *garp = NULL;
3599 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3600 	nfs_argop4 argop[5];
3601 	int verify_argop = -1;
3602 	int setattr_argop = 1;
3603 	nfs_resop4 *resop;
3604 	vattr_t va;
3605 	rnode4_t *rp;
3606 	int doqueue = 1;
3607 	uint_t mask = vap->va_mask;
3608 	mode_t omode;
3609 	vsecattr_t *vsp;
3610 	timestruc_t ctime;
3611 	bool_t needrecov = FALSE;
3612 	nfs4_recov_state_t recov_state;
3613 	nfs4_stateid_types_t sid_types;
3614 	stateid4 stateid;
3615 	hrtime_t t;
3616 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3617 	servinfo4_t *svp;
3618 	bitmap4 supp_attrs;
3619 
3620 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3621 	rp = VTOR4(vp);
3622 	nfs4_init_stateid_types(&sid_types);
3623 
3624 	/*
3625 	 * Only need to flush pages if there are any pages and
3626 	 * if the file is marked as dirty in some fashion.  The
3627 	 * file must be flushed so that we can accurately
3628 	 * determine the size of the file and the cached data
3629 	 * after the SETATTR returns.  A file is considered to
3630 	 * be dirty if it is either marked with R4DIRTY, has
3631 	 * outstanding i/o's active, or is mmap'd.  In this
3632 	 * last case, we can't tell whether there are dirty
3633 	 * pages, so we flush just to be sure.
3634 	 */
3635 	if (nfs4_has_pages(vp) &&
3636 	    ((rp->r_flags & R4DIRTY) ||
3637 	    rp->r_count > 0 ||
3638 	    rp->r_mapcnt > 0)) {
3639 		ASSERT(vp->v_type != VCHR);
3640 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr);
3641 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3642 			mutex_enter(&rp->r_statelock);
3643 			if (!rp->r_error)
3644 				rp->r_error = e.error;
3645 			mutex_exit(&rp->r_statelock);
3646 		}
3647 	}
3648 
3649 	if (mask & AT_SIZE) {
3650 		/*
3651 		 * Verification setattr compound for non-deleg AT_SIZE:
3652 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3653 		 * Set ctime local here (outside the do_again label)
3654 		 * so that subsequent retries (after failed VERIFY)
3655 		 * will use ctime from GETATTR results (from failed
3656 		 * verify compound) as VERIFY arg.
3657 		 * If file has delegation, then VERIFY(time_metadata)
3658 		 * is of little added value, so don't bother.
3659 		 */
3660 		mutex_enter(&rp->r_statev4_lock);
3661 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3662 						rp->r_deleg_return_pending) {
3663 			numops = 5;
3664 			ctime = rp->r_attr.va_ctime;
3665 		}
3666 		mutex_exit(&rp->r_statev4_lock);
3667 	}
3668 
3669 	recov_state.rs_flags = 0;
3670 	recov_state.rs_num_retry_despite_err = 0;
3671 
3672 	args.ctag = TAG_SETATTR;
3673 do_again:
3674 recov_retry:
3675 	setattr_argop = numops - 2;
3676 
3677 	args.array = argop;
3678 	args.array_len = numops;
3679 
3680 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3681 	if (e.error)
3682 		return (e.error);
3683 
3684 
3685 	/* putfh target fh */
3686 	argop[0].argop = OP_CPUTFH;
3687 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3688 
3689 	if (numops == 5) {
3690 		/*
3691 		 * We only care about the ctime, but need to get mtime
3692 		 * and size for proper cache update.
3693 		 */
3694 		/* getattr */
3695 		argop[1].argop = OP_GETATTR;
3696 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3697 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3698 
3699 		/* verify - set later in loop */
3700 		verify_argop = 2;
3701 	}
3702 
3703 	/* setattr */
3704 	svp = rp->r_server;
3705 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3706 	supp_attrs = svp->sv_supp_attrs;
3707 	nfs_rw_exit(&svp->sv_lock);
3708 
3709 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3710 		supp_attrs, &e.error, &sid_types);
3711 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3712 	if (e.error) {
3713 		/* req time field(s) overflow - return immediately */
3714 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3715 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3716 						opsetattr.obj_attributes);
3717 		return (e.error);
3718 	}
3719 	omode = rp->r_attr.va_mode;
3720 
3721 	/* getattr */
3722 	argop[numops-1].argop = OP_GETATTR;
3723 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3724 	/*
3725 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3726 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3727 	 * used in updating the ACL cache.
3728 	 */
3729 	if (vsap != NULL)
3730 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3731 		    FATTR4_ACL_MASK;
3732 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3733 
3734 	/*
3735 	 * setattr iterates if the object size is set and the cached ctime
3736 	 * does not match the file ctime. In that case, verify the ctime first.
3737 	 */
3738 
3739 	do {
3740 		if (verify_argop != -1) {
3741 			/*
3742 			 * Verify that the ctime match before doing setattr.
3743 			 */
3744 			va.va_mask = AT_CTIME;
3745 			va.va_ctime = ctime;
3746 			svp = rp->r_server;
3747 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3748 			supp_attrs = svp->sv_supp_attrs;
3749 			nfs_rw_exit(&svp->sv_lock);
3750 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3751 					OP_VERIFY, supp_attrs);
3752 			if (e.error) {
3753 				/* req time field(s) overflow - return */
3754 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3755 					needrecov);
3756 				break;
3757 			}
3758 		}
3759 
3760 		doqueue = 1;
3761 
3762 		t = gethrtime();
3763 
3764 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3765 
3766 		/*
3767 		 * Purge the access cache and ACL cache if changing either the
3768 		 * owner of the file, the group owner, or the mode.  These may
3769 		 * change the access permissions of the file, so purge old
3770 		 * information and start over again.
3771 		 */
3772 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3773 			(void) nfs4_access_purge_rp(rp);
3774 			if (rp->r_secattr != NULL) {
3775 				mutex_enter(&rp->r_statelock);
3776 				vsp = rp->r_secattr;
3777 				rp->r_secattr = NULL;
3778 				mutex_exit(&rp->r_statelock);
3779 				if (vsp != NULL)
3780 					nfs4_acl_free_cache(vsp);
3781 			}
3782 		}
3783 
3784 		/*
3785 		 * If res.array_len == numops, then everything succeeded,
3786 		 * except for possibly the final getattr.  If only the
3787 		 * last getattr failed, give up, and don't try recovery.
3788 		 */
3789 		if (res.array_len == numops) {
3790 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3791 			    needrecov);
3792 			if (! e.error)
3793 				resp = &res;
3794 			break;
3795 		}
3796 
3797 		/*
3798 		 * if either rpc call failed or completely succeeded - done
3799 		 */
3800 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
3801 		if (e.error) {
3802 			PURGE_ATTRCACHE4(vp);
3803 			if (!needrecov) {
3804 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3805 				    needrecov);
3806 				break;
3807 			}
3808 		}
3809 
3810 		/*
3811 		 * Do proper retry for OLD_STATEID outside of the normal
3812 		 * recovery framework.
3813 		 */
3814 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3815 		    sid_types.cur_sid_type != SPEC_SID &&
3816 		    sid_types.cur_sid_type != NO_SID) {
3817 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3818 				    needrecov);
3819 			nfs4_save_stateid(&stateid, &sid_types);
3820 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3821 						opsetattr.obj_attributes);
3822 			if (verify_argop != -1) {
3823 				nfs4args_verify_free(&argop[verify_argop]);
3824 				verify_argop = -1;
3825 			}
3826 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3827 			goto recov_retry;
3828 		}
3829 
3830 		if (needrecov) {
3831 			bool_t abort;
3832 
3833 			abort = nfs4_start_recovery(&e,
3834 				    VTOMI4(vp), vp, NULL, NULL, NULL,
3835 				    OP_SETATTR, NULL);
3836 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3837 				    needrecov);
3838 			/*
3839 			 * Do not retry if we failed with OLD_STATEID using
3840 			 * a special stateid.  This is done to avoid looping
3841 			 * with a broken server.
3842 			 */
3843 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3844 			    (sid_types.cur_sid_type == SPEC_SID ||
3845 			    sid_types.cur_sid_type == NO_SID))
3846 				abort = TRUE;
3847 			if (!e.error) {
3848 				if (res.status == NFS4ERR_BADOWNER)
3849 					nfs4_log_badowner(VTOMI4(vp),
3850 					    OP_SETATTR);
3851 
3852 				e.error = geterrno4(res.status);
3853 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3854 								(caddr_t)&res);
3855 			}
3856 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3857 						opsetattr.obj_attributes);
3858 			if (verify_argop != -1) {
3859 				nfs4args_verify_free(&argop[verify_argop]);
3860 				verify_argop = -1;
3861 			}
3862 			if (abort == FALSE) {
3863 				/*
3864 				 * Need to retry all possible stateids in
3865 				 * case the recovery error wasn't stateid
3866 				 * related or the stateids have become
3867 				 * stale (server reboot).
3868 				 */
3869 				nfs4_init_stateid_types(&sid_types);
3870 				goto recov_retry;
3871 			}
3872 			return (e.error);
3873 		}
3874 
3875 		/*
3876 		 * Need to call nfs4_end_op before nfs4getattr to
3877 		 * avoid potential nfs4_start_op deadlock. See RFE
3878 		 * 4777612.  Calls to nfs4_invalidate_pages() and
3879 		 * nfs4_purge_stale_fh() might also generate over the
3880 		 * wire calls which my cause nfs4_start_op() deadlock.
3881 		 */
3882 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3883 
3884 		/*
3885 		 * Check to update lease.
3886 		 */
3887 		resp = &res;
3888 		if (res.status == NFS4_OK) {
3889 			break;
3890 		}
3891 
3892 		/*
3893 		 * Check if verify failed to see if try again
3894 		 */
3895 		if ((verify_argop == -1) || (res.array_len != 3)) {
3896 			/*
3897 			 * can't continue...
3898 			 */
3899 			if (res.status == NFS4ERR_BADOWNER)
3900 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
3901 
3902 			e.error = geterrno4(res.status);
3903 		} else {
3904 			/*
3905 			 * When the verify request fails, the client ctime is
3906 			 * not in sync with the server. This is the same as
3907 			 * the version 3 "not synchronized" error, and we
3908 			 * handle it in a similar manner (XXX do we need to???).
3909 			 * Use the ctime returned in the first getattr for
3910 			 * the input to the next verify.
3911 			 * If we couldn't get the attributes, then we give up
3912 			 * because we can't complete the operation as required.
3913 			 */
3914 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
3915 		}
3916 		if (e.error) {
3917 			PURGE_ATTRCACHE4(vp);
3918 			nfs4_purge_stale_fh(e.error, vp, cr);
3919 		} else {
3920 			/*
3921 			 * retry with a new verify value
3922 			 */
3923 			ctime = garp->n4g_va.va_ctime;
3924 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3925 			resp = NULL;
3926 		}
3927 		if (!e.error) {
3928 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3929 						opsetattr.obj_attributes);
3930 			if (verify_argop != -1) {
3931 				nfs4args_verify_free(&argop[verify_argop]);
3932 				verify_argop = -1;
3933 			}
3934 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3935 			goto do_again;
3936 		}
3937 	} while (!e.error);
3938 
3939 	if (e.error) {
3940 		/*
3941 		 * If we are here, rfs4call has an irrecoverable error - return
3942 		 */
3943 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3944 						opsetattr.obj_attributes);
3945 		if (verify_argop != -1) {
3946 			nfs4args_verify_free(&argop[verify_argop]);
3947 			verify_argop = -1;
3948 		}
3949 		if (resp)
3950 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
3951 		return (e.error);
3952 	}
3953 
3954 
3955 
3956 	/*
3957 	 * If changing the size of the file, invalidate
3958 	 * any local cached data which is no longer part
3959 	 * of the file.  We also possibly invalidate the
3960 	 * last page in the file.  We could use
3961 	 * pvn_vpzero(), but this would mark the page as
3962 	 * modified and require it to be written back to
3963 	 * the server for no particularly good reason.
3964 	 * This way, if we access it, then we bring it
3965 	 * back in.  A read should be cheaper than a
3966 	 * write.
3967 	 */
3968 	if (mask & AT_SIZE) {
3969 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
3970 	}
3971 
3972 	/* either no error or one of the postop getattr failed */
3973 
3974 	/*
3975 	 * XXX Perform a simplified version of wcc checking. Instead of
3976 	 * have another getattr to get pre-op, just purge cache if
3977 	 * any of the ops prior to and including the getattr failed.
3978 	 * If the getattr succeeded then update the attrcache accordingly.
3979 	 */
3980 
3981 	garp = NULL;
3982 	if (res.status == NFS4_OK) {
3983 		/*
3984 		 * Last getattr
3985 		 */
3986 		resop = &res.array[numops - 1];
3987 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
3988 	}
3989 	/*
3990 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
3991 	 * rather than filling it.  See the function itself for details.
3992 	 */
3993 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
3994 	if (garp != NULL) {
3995 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
3996 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
3997 			vs_ace4_destroy(&garp->n4g_vsa);
3998 		} else {
3999 			if (vsap != NULL) {
4000 				/*
4001 				 * The ACL was supposed to be set and to be
4002 				 * returned in the last getattr of this
4003 				 * compound, but for some reason the getattr
4004 				 * result doesn't contain the ACL.  In this
4005 				 * case, purge the ACL cache.
4006 				 */
4007 				if (rp->r_secattr != NULL) {
4008 					mutex_enter(&rp->r_statelock);
4009 					vsp = rp->r_secattr;
4010 					rp->r_secattr = NULL;
4011 					mutex_exit(&rp->r_statelock);
4012 					if (vsp != NULL)
4013 						nfs4_acl_free_cache(vsp);
4014 				}
4015 			}
4016 		}
4017 	}
4018 
4019 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4020 		/*
4021 		 * Set the size, rather than relying on getting it updated
4022 		 * via a GETATTR.  With delegations the client tries to
4023 		 * suppress GETATTR calls.
4024 		 */
4025 		mutex_enter(&rp->r_statelock);
4026 		rp->r_size = vap->va_size;
4027 		mutex_exit(&rp->r_statelock);
4028 	}
4029 
4030 	/*
4031 	 * Can free up request args and res
4032 	 */
4033 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4034 						opsetattr.obj_attributes);
4035 	if (verify_argop != -1) {
4036 		nfs4args_verify_free(&argop[verify_argop]);
4037 		verify_argop = -1;
4038 	}
4039 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4040 
4041 	/*
4042 	 * Some servers will change the mode to clear the setuid
4043 	 * and setgid bits when changing the uid or gid.  The
4044 	 * client needs to compensate appropriately.
4045 	 */
4046 	if (mask & (AT_UID | AT_GID)) {
4047 		int terror, do_setattr;
4048 
4049 		do_setattr = 0;
4050 		va.va_mask = AT_MODE;
4051 		terror = nfs4getattr(vp, &va, cr);
4052 		if (!terror &&
4053 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4054 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4055 			va.va_mask = AT_MODE;
4056 			if (mask & AT_MODE) {
4057 				/*
4058 				 * We asked the mode to be changed and what
4059 				 * we just got from the server in getattr is
4060 				 * not what we wanted it to be, so set it now.
4061 				 */
4062 				va.va_mode = vap->va_mode;
4063 				do_setattr = 1;
4064 			} else {
4065 				/*
4066 				 * We did not ask the mode to be changed,
4067 				 * Check to see that the server just cleared
4068 				 * I_SUID and I_GUID from it. If not then
4069 				 * set mode to omode with UID/GID cleared.
4070 				 */
4071 				if (nfs4_compare_modes(va.va_mode, omode)) {
4072 					omode &= ~(S_ISUID|S_ISGID);
4073 					va.va_mode = omode;
4074 					do_setattr = 1;
4075 				}
4076 			}
4077 
4078 			if (do_setattr)
4079 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4080 		}
4081 	}
4082 
4083 	return (e.error);
4084 }
4085 
4086 /* ARGSUSED */
4087 static int
4088 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr)
4089 {
4090 	COMPOUND4args_clnt args;
4091 	COMPOUND4res_clnt res;
4092 	int doqueue;
4093 	uint32_t acc, resacc, argacc;
4094 	rnode4_t *rp;
4095 	cred_t *cred, *ncr, *ncrfree = NULL;
4096 	nfs4_access_type_t cacc;
4097 	int num_ops;
4098 	nfs_argop4 argop[3];
4099 	nfs_resop4 *resop;
4100 	bool_t needrecov = FALSE, do_getattr;
4101 	nfs4_recov_state_t recov_state;
4102 	int rpc_error;
4103 	hrtime_t t;
4104 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4105 	mntinfo4_t *mi = VTOMI4(vp);
4106 
4107 	if (nfs_zone() != mi->mi_zone)
4108 		return (EIO);
4109 
4110 	acc = 0;
4111 	if (mode & VREAD)
4112 		acc |= ACCESS4_READ;
4113 	if (mode & VWRITE) {
4114 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4115 			return (EROFS);
4116 		if (vp->v_type == VDIR)
4117 			acc |= ACCESS4_DELETE;
4118 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4119 	}
4120 	if (mode & VEXEC) {
4121 		if (vp->v_type == VDIR)
4122 			acc |= ACCESS4_LOOKUP;
4123 		else
4124 			acc |= ACCESS4_EXECUTE;
4125 	}
4126 
4127 	if (VTOR4(vp)->r_acache != NULL) {
4128 		e.error = nfs4_validate_caches(vp, cr);
4129 		if (e.error)
4130 			return (e.error);
4131 	}
4132 
4133 	rp = VTOR4(vp);
4134 	if (vp->v_type == VDIR) {
4135 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4136 			ACCESS4_EXTEND | ACCESS4_LOOKUP;
4137 	} else {
4138 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4139 			ACCESS4_EXECUTE;
4140 	}
4141 	recov_state.rs_flags = 0;
4142 	recov_state.rs_num_retry_despite_err = 0;
4143 
4144 	cred = cr;
4145 	/*
4146 	 * ncr and ncrfree both initially
4147 	 * point to the memory area returned
4148 	 * by crnetadjust();
4149 	 * ncrfree not NULL when exiting means
4150 	 * that we need to release it
4151 	 */
4152 	ncr = crnetadjust(cred);
4153 	ncrfree = ncr;
4154 
4155 tryagain:
4156 	cacc = nfs4_access_check(rp, acc, cred);
4157 	if (cacc == NFS4_ACCESS_ALLOWED) {
4158 		if (ncrfree != NULL)
4159 			crfree(ncrfree);
4160 		return (0);
4161 	}
4162 	if (cacc == NFS4_ACCESS_DENIED) {
4163 		/*
4164 		 * If the cred can be adjusted, try again
4165 		 * with the new cred.
4166 		 */
4167 		if (ncr != NULL) {
4168 			cred = ncr;
4169 			ncr = NULL;
4170 			goto tryagain;
4171 		}
4172 		if (ncrfree != NULL)
4173 			crfree(ncrfree);
4174 		return (EACCES);
4175 	}
4176 
4177 recov_retry:
4178 	/*
4179 	 * Don't take with r_statev4_lock here. r_deleg_type could
4180 	 * change as soon as lock is released.  Since it is an int,
4181 	 * there is no atomicity issue.
4182 	 */
4183 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4184 	num_ops = do_getattr ? 3 : 2;
4185 
4186 	args.ctag = TAG_ACCESS;
4187 
4188 	args.array_len = num_ops;
4189 	args.array = argop;
4190 
4191 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4192 					&recov_state, NULL)) {
4193 		if (ncrfree != NULL)
4194 			crfree(ncrfree);
4195 		return (e.error);
4196 	}
4197 
4198 	/* putfh target fh */
4199 	argop[0].argop = OP_CPUTFH;
4200 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4201 
4202 	/* access */
4203 	argop[1].argop = OP_ACCESS;
4204 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4205 
4206 	/* getattr */
4207 	if (do_getattr) {
4208 		argop[2].argop = OP_GETATTR;
4209 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4210 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4211 	}
4212 
4213 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4214 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4215 	    rnode4info(VTOR4(vp))));
4216 
4217 	doqueue = 1;
4218 	t = gethrtime();
4219 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4220 	rpc_error = e.error;
4221 
4222 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4223 	if (needrecov) {
4224 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4225 		    "nfs4_access: initiating recovery\n"));
4226 
4227 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4228 		    NULL, OP_ACCESS, NULL) == FALSE) {
4229 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4230 			    &recov_state, needrecov);
4231 			if (!e.error)
4232 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4233 						(caddr_t)&res);
4234 			goto recov_retry;
4235 		}
4236 	}
4237 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4238 
4239 	if (e.error)
4240 		goto out;
4241 
4242 	if (res.status) {
4243 		e.error = geterrno4(res.status);
4244 		/*
4245 		 * This might generate over the wire calls throught
4246 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4247 		 * here to avoid a deadlock.
4248 		 */
4249 		nfs4_purge_stale_fh(e.error, vp, cr);
4250 		goto out;
4251 	}
4252 	resop = &res.array[1];	/* access res */
4253 
4254 	resacc = resop->nfs_resop4_u.opaccess.access;
4255 
4256 	if (do_getattr) {
4257 		resop++;	/* getattr res */
4258 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4259 				t, cr, FALSE, NULL);
4260 	}
4261 
4262 	if (!e.error) {
4263 		nfs4_access_cache(rp, argacc, resacc, cred);
4264 		/*
4265 		 * we just cached results with cred; if cred is the
4266 		 * adjusted credentials from crnetadjust, we do not want
4267 		 * to release them before exiting: hence setting ncrfree
4268 		 * to NULL
4269 		 */
4270 		if (cred != cr)
4271 			ncrfree = NULL;
4272 		/* XXX check the supported bits too? */
4273 		if ((acc & resacc) != acc) {
4274 			/*
4275 			 * The following code implements the semantic
4276 			 * that a setuid root program has *at least* the
4277 			 * permissions of the user that is running the
4278 			 * program.  See rfs3call() for more portions
4279 			 * of the implementation of this functionality.
4280 			 */
4281 			/* XXX-LP */
4282 			if (ncr != NULL) {
4283 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4284 						(caddr_t)&res);
4285 				cred = ncr;
4286 				ncr = NULL;
4287 				goto tryagain;
4288 			}
4289 			e.error = EACCES;
4290 		}
4291 	}
4292 
4293 out:
4294 	if (!rpc_error)
4295 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4296 
4297 	if (ncrfree != NULL)
4298 		crfree(ncrfree);
4299 
4300 	return (e.error);
4301 }
4302 
4303 static int
4304 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr)
4305 {
4306 	COMPOUND4args_clnt args;
4307 	COMPOUND4res_clnt res;
4308 	int doqueue;
4309 	rnode4_t *rp;
4310 	nfs_argop4 argop[3];
4311 	nfs_resop4 *resop;
4312 	READLINK4res *lr_res;
4313 	nfs4_ga_res_t *garp;
4314 	uint_t len;
4315 	char *linkdata;
4316 	bool_t needrecov = FALSE;
4317 	nfs4_recov_state_t recov_state;
4318 	hrtime_t t;
4319 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4320 
4321 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4322 		return (EIO);
4323 	/*
4324 	 * Can't readlink anything other than a symbolic link.
4325 	 */
4326 	if (vp->v_type != VLNK)
4327 		return (EINVAL);
4328 
4329 	rp = VTOR4(vp);
4330 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4331 		e.error = nfs4_validate_caches(vp, cr);
4332 		if (e.error)
4333 			return (e.error);
4334 		mutex_enter(&rp->r_statelock);
4335 		if (rp->r_symlink.contents != NULL) {
4336 			e.error = uiomove(rp->r_symlink.contents,
4337 			    rp->r_symlink.len, UIO_READ, uiop);
4338 			mutex_exit(&rp->r_statelock);
4339 			return (e.error);
4340 		}
4341 		mutex_exit(&rp->r_statelock);
4342 	}
4343 	recov_state.rs_flags = 0;
4344 	recov_state.rs_num_retry_despite_err = 0;
4345 
4346 recov_retry:
4347 	args.array_len = 3;
4348 	args.array = argop;
4349 	args.ctag = TAG_READLINK;
4350 
4351 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4352 	if (e.error) {
4353 		return (e.error);
4354 	}
4355 
4356 	/* 0. putfh symlink fh */
4357 	argop[0].argop = OP_CPUTFH;
4358 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4359 
4360 	/* 1. readlink */
4361 	argop[1].argop = OP_READLINK;
4362 
4363 	/* 2. getattr */
4364 	argop[2].argop = OP_GETATTR;
4365 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4366 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4367 
4368 	doqueue = 1;
4369 
4370 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4371 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4372 	    rnode4info(VTOR4(vp))));
4373 
4374 	t = gethrtime();
4375 
4376 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4377 
4378 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4379 	if (needrecov) {
4380 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4381 		    "nfs4_readlink: initiating recovery\n"));
4382 
4383 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4384 		    NULL, OP_READLINK, NULL) == FALSE) {
4385 			if (!e.error)
4386 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4387 								(caddr_t)&res);
4388 
4389 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4390 			    needrecov);
4391 			goto recov_retry;
4392 		}
4393 	}
4394 
4395 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4396 
4397 	if (e.error)
4398 		return (e.error);
4399 
4400 	/*
4401 	 * There is an path in the code below which calls
4402 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4403 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4404 	 * here to avoid nfs4_start_op() deadlock.
4405 	 */
4406 
4407 	if (res.status && (res.array_len < args.array_len)) {
4408 		/*
4409 		 * either Putfh or Link failed
4410 		 */
4411 		e.error = geterrno4(res.status);
4412 		nfs4_purge_stale_fh(e.error, vp, cr);
4413 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4414 		return (e.error);
4415 	}
4416 
4417 	resop = &res.array[1];	/* readlink res */
4418 	lr_res = &resop->nfs_resop4_u.opreadlink;
4419 
4420 	/*
4421 	 * treat symlink names as data
4422 	 */
4423 	linkdata = utf8_to_str(&lr_res->link, &len, NULL);
4424 	if (linkdata != NULL) {
4425 		int uio_len = len - 1;
4426 		/* len includes null byte, which we won't uiomove */
4427 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4428 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4429 			mutex_enter(&rp->r_statelock);
4430 			if (rp->r_symlink.contents == NULL) {
4431 				rp->r_symlink.contents = linkdata;
4432 				rp->r_symlink.len = uio_len;
4433 				rp->r_symlink.size = len;
4434 				mutex_exit(&rp->r_statelock);
4435 			} else {
4436 				mutex_exit(&rp->r_statelock);
4437 				kmem_free(linkdata, len);
4438 			}
4439 		} else {
4440 			kmem_free(linkdata, len);
4441 		}
4442 	}
4443 	if (res.status == NFS4_OK) {
4444 		resop++;	/* getattr res */
4445 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4446 	}
4447 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4448 
4449 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4450 
4451 	/*
4452 	 * The over the wire error for attempting to readlink something
4453 	 * other than a symbolic link is ENXIO.  However, we need to
4454 	 * return EINVAL instead of ENXIO, so we map it here.
4455 	 */
4456 	return (e.error == ENXIO ? EINVAL : e.error);
4457 }
4458 
4459 /*
4460  * Flush local dirty pages to stable storage on the server.
4461  *
4462  * If FNODSYNC is specified, then there is nothing to do because
4463  * metadata changes are not cached on the client before being
4464  * sent to the server.
4465  */
4466 static int
4467 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr)
4468 {
4469 	int error;
4470 
4471 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4472 		return (0);
4473 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4474 		return (EIO);
4475 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4476 	if (!error)
4477 		error = VTOR4(vp)->r_error;
4478 	return (error);
4479 }
4480 
4481 /*
4482  * Weirdness: if the file was removed or the target of a rename
4483  * operation while it was open, it got renamed instead.  Here we
4484  * remove the renamed file.
4485  */
4486 static void
4487 nfs4_inactive(vnode_t *vp, cred_t *cr)
4488 {
4489 	rnode4_t *rp;
4490 
4491 	ASSERT(vp != DNLC_NO_VNODE);
4492 
4493 	rp = VTOR4(vp);
4494 
4495 	if (IS_SHADOW(vp, rp)) {
4496 		sv_inactive(vp);
4497 		return;
4498 	}
4499 
4500 	/*
4501 	 * If this is coming from the wrong zone, we let someone in the right
4502 	 * zone take care of it asynchronously.  We can get here due to
4503 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4504 	 * potentially turn into an expensive no-op if, for instance, v_count
4505 	 * gets incremented in the meantime, but it's still correct.
4506 	 */
4507 	if (nfs_zone() != VTOMI4(vp)->mi_zone) {
4508 		nfs4_async_inactive(vp, cr);
4509 		return;
4510 	}
4511 
4512 	/*
4513 	 * Some of the cleanup steps might require over-the-wire
4514 	 * operations.  Since VOP_INACTIVE can get called as a result of
4515 	 * other over-the-wire operations (e.g., an attribute cache update
4516 	 * can lead to a DNLC purge), doing those steps now would lead to a
4517 	 * nested call to the recovery framework, which can deadlock.  So
4518 	 * do any over-the-wire cleanups asynchronously, in a separate
4519 	 * thread.
4520 	 */
4521 
4522 	mutex_enter(&rp->r_os_lock);
4523 	mutex_enter(&rp->r_statelock);
4524 	mutex_enter(&rp->r_statev4_lock);
4525 
4526 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4527 		mutex_exit(&rp->r_statev4_lock);
4528 		mutex_exit(&rp->r_statelock);
4529 		mutex_exit(&rp->r_os_lock);
4530 		nfs4_async_inactive(vp, cr);
4531 		return;
4532 	}
4533 
4534 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4535 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4536 		mutex_exit(&rp->r_statev4_lock);
4537 		mutex_exit(&rp->r_statelock);
4538 		mutex_exit(&rp->r_os_lock);
4539 		nfs4_async_inactive(vp, cr);
4540 		return;
4541 	}
4542 
4543 	if (rp->r_unldvp != NULL) {
4544 		mutex_exit(&rp->r_statev4_lock);
4545 		mutex_exit(&rp->r_statelock);
4546 		mutex_exit(&rp->r_os_lock);
4547 		nfs4_async_inactive(vp, cr);
4548 		return;
4549 	}
4550 	mutex_exit(&rp->r_statev4_lock);
4551 	mutex_exit(&rp->r_statelock);
4552 	mutex_exit(&rp->r_os_lock);
4553 
4554 	rp4_addfree(rp, cr);
4555 }
4556 
4557 /*
4558  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4559  * various bits of state.  The caller must not refer to vp after this call.
4560  */
4561 
4562 void
4563 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4564 {
4565 	rnode4_t *rp = VTOR4(vp);
4566 	nfs4_recov_state_t recov_state;
4567 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4568 	vnode_t *unldvp;
4569 	char *unlname;
4570 	cred_t *unlcred;
4571 	COMPOUND4args_clnt args;
4572 	COMPOUND4res_clnt res, *resp;
4573 	nfs_argop4 argop[2];
4574 	int doqueue;
4575 #ifdef DEBUG
4576 	char *name;
4577 #endif
4578 
4579 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
4580 	ASSERT(!IS_SHADOW(vp, rp));
4581 
4582 #ifdef DEBUG
4583 	name = fn_name(VTOSV(vp)->sv_name);
4584 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4585 		"release vnode %s", name));
4586 	kmem_free(name, MAXNAMELEN);
4587 #endif
4588 
4589 	if (vp->v_type == VREG) {
4590 		bool_t recov_failed = FALSE;
4591 
4592 		e.error = nfs4close_all(vp, cr);
4593 		if (e.error) {
4594 			/* Check to see if recovery failed */
4595 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4596 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4597 				recov_failed = TRUE;
4598 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4599 			if (!recov_failed) {
4600 				mutex_enter(&rp->r_statelock);
4601 				if (rp->r_flags & R4RECOVERR)
4602 					recov_failed = TRUE;
4603 				mutex_exit(&rp->r_statelock);
4604 			}
4605 			if (recov_failed) {
4606 				NFS4_DEBUG(nfs4_client_recov_debug,
4607 					    (CE_NOTE, "nfs4_inactive_otw: "
4608 					    "close failed (recovery failure)"));
4609 			}
4610 		}
4611 	}
4612 
4613 redo:
4614 	if (rp->r_unldvp == NULL) {
4615 		rp4_addfree(rp, cr);
4616 		return;
4617 	}
4618 
4619 	/*
4620 	 * Save the vnode pointer for the directory where the
4621 	 * unlinked-open file got renamed, then set it to NULL
4622 	 * to prevent another thread from getting here before
4623 	 * we're done with the remove.  While we have the
4624 	 * statelock, make local copies of the pertinent rnode
4625 	 * fields.  If we weren't to do this in an atomic way, the
4626 	 * the unl* fields could become inconsistent with respect
4627 	 * to each other due to a race condition between this
4628 	 * code and nfs_remove().  See bug report 1034328.
4629 	 */
4630 	mutex_enter(&rp->r_statelock);
4631 	if (rp->r_unldvp == NULL) {
4632 		mutex_exit(&rp->r_statelock);
4633 		rp4_addfree(rp, cr);
4634 		return;
4635 	}
4636 
4637 	unldvp = rp->r_unldvp;
4638 	rp->r_unldvp = NULL;
4639 	unlname = rp->r_unlname;
4640 	rp->r_unlname = NULL;
4641 	unlcred = rp->r_unlcred;
4642 	rp->r_unlcred = NULL;
4643 	mutex_exit(&rp->r_statelock);
4644 
4645 	/*
4646 	 * If there are any dirty pages left, then flush
4647 	 * them.  This is unfortunate because they just
4648 	 * may get thrown away during the remove operation,
4649 	 * but we have to do this for correctness.
4650 	 */
4651 	if (nfs4_has_pages(vp) &&
4652 			    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4653 		ASSERT(vp->v_type != VCHR);
4654 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr);
4655 		if (e.error) {
4656 			mutex_enter(&rp->r_statelock);
4657 			if (!rp->r_error)
4658 				rp->r_error = e.error;
4659 			mutex_exit(&rp->r_statelock);
4660 		}
4661 	}
4662 
4663 	recov_state.rs_flags = 0;
4664 	recov_state.rs_num_retry_despite_err = 0;
4665 recov_retry_remove:
4666 	/*
4667 	 * Do the remove operation on the renamed file
4668 	 */
4669 	args.ctag = TAG_INACTIVE;
4670 
4671 	/*
4672 	 * Remove ops: putfh dir; remove
4673 	 */
4674 	args.array_len = 2;
4675 	args.array = argop;
4676 
4677 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4678 	if (e.error) {
4679 		kmem_free(unlname, MAXNAMELEN);
4680 		crfree(unlcred);
4681 		VN_RELE(unldvp);
4682 		/*
4683 		 * Try again; this time around r_unldvp will be NULL, so we'll
4684 		 * just call rp4_addfree() and return.
4685 		 */
4686 		goto redo;
4687 	}
4688 
4689 	/* putfh directory */
4690 	argop[0].argop = OP_CPUTFH;
4691 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4692 
4693 	/* remove */
4694 	argop[1].argop = OP_CREMOVE;
4695 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4696 
4697 	doqueue = 1;
4698 	resp = &res;
4699 
4700 #if 0 /* notyet */
4701 	/*
4702 	 * Can't do this yet.  We may be being called from
4703 	 * dnlc_purge_XXX while that routine is holding a
4704 	 * mutex lock to the nc_rele list.  The calls to
4705 	 * nfs3_cache_wcc_data may result in calls to
4706 	 * dnlc_purge_XXX.  This will result in a deadlock.
4707 	 */
4708 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4709 	if (e.error) {
4710 		PURGE_ATTRCACHE4(unldvp);
4711 		resp = NULL;
4712 	} else if (res.status) {
4713 		e.error = geterrno4(res.status);
4714 		PURGE_ATTRCACHE4(unldvp);
4715 		/*
4716 		 * This code is inactive right now
4717 		 * but if made active there should
4718 		 * be a nfs4_end_op() call before
4719 		 * nfs4_purge_stale_fh to avoid start_op()
4720 		 * deadlock. See BugId: 4948726
4721 		 */
4722 		nfs4_purge_stale_fh(error, unldvp, cr);
4723 	} else {
4724 		nfs_resop4 *resop;
4725 		REMOVE4res *rm_res;
4726 
4727 		resop = &res.array[1];
4728 		rm_res = &resop->nfs_resop4_u.opremove;
4729 		/*
4730 		 * Update directory cache attribute,
4731 		 * readdir and dnlc caches.
4732 		 */
4733 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4734 	}
4735 #else
4736 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4737 
4738 	PURGE_ATTRCACHE4(unldvp);
4739 #endif
4740 
4741 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4742 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4743 		    NULL, NULL, OP_REMOVE, NULL) == FALSE) {
4744 			if (!e.error)
4745 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4746 								(caddr_t)&res);
4747 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4748 							&recov_state, TRUE);
4749 			goto recov_retry_remove;
4750 		}
4751 	}
4752 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4753 
4754 	/*
4755 	 * Release stuff held for the remove
4756 	 */
4757 	VN_RELE(unldvp);
4758 	if (!e.error && resp)
4759 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4760 
4761 	kmem_free(unlname, MAXNAMELEN);
4762 	crfree(unlcred);
4763 	goto redo;
4764 }
4765 
4766 /*
4767  * Remote file system operations having to do with directory manipulation.
4768  */
4769 /* ARGSUSED3 */
4770 static int
4771 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4772 	int flags, vnode_t *rdir, cred_t *cr)
4773 {
4774 	int error;
4775 	vnode_t *vp, *avp = NULL;
4776 	rnode4_t *drp;
4777 
4778 	*vpp = NULL;
4779 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4780 		return (EPERM);
4781 	/*
4782 	 * if LOOKUP_XATTR, must replace dvp (object) with
4783 	 * object's attrdir before continuing with lookup
4784 	 */
4785 	if (flags & LOOKUP_XATTR) {
4786 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4787 		if (error)
4788 			return (error);
4789 
4790 		dvp = avp;
4791 
4792 		/*
4793 		 * If lookup is for "", just return dvp now.  The attrdir
4794 		 * has already been activated (from nfs4lookup_xattr), and
4795 		 * the caller will RELE the original dvp -- not
4796 		 * the attrdir.  So, set vpp and return.
4797 		 * Currently, when the LOOKUP_XATTR flag is
4798 		 * passed to VOP_LOOKUP, the name is always empty, and
4799 		 * shortcircuiting here avoids 3 unneeded lock/unlock
4800 		 * pairs.
4801 		 *
4802 		 * If a non-empty name was provided, then it is the
4803 		 * attribute name, and it will be looked up below.
4804 		 */
4805 		if (*nm == '\0') {
4806 			*vpp = dvp;
4807 			return (0);
4808 		}
4809 
4810 		/*
4811 		 * The vfs layer never sends a name when asking for the
4812 		 * attrdir, so we should never get here (unless of course
4813 		 * name is passed at some time in future -- at which time
4814 		 * we'll blow up here).
4815 		 */
4816 		ASSERT(0);
4817 	}
4818 
4819 	drp = VTOR4(dvp);
4820 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4821 		return (EINTR);
4822 
4823 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
4824 	nfs_rw_exit(&drp->r_rwlock);
4825 
4826 	/*
4827 	 * If vnode is a device, create special vnode.
4828 	 */
4829 	if (!error && ISVDEV((*vpp)->v_type)) {
4830 		vp = *vpp;
4831 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
4832 		VN_RELE(vp);
4833 	}
4834 
4835 	return (error);
4836 }
4837 
4838 /* ARGSUSED */
4839 static int
4840 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
4841 {
4842 	int error;
4843 	rnode4_t *drp;
4844 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
4845 	mntinfo4_t *mi;
4846 
4847 	mi = VTOMI4(dvp);
4848 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR))
4849 		return (EINVAL);
4850 
4851 	drp = VTOR4(dvp);
4852 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4853 		return (EINTR);
4854 
4855 	mutex_enter(&drp->r_statelock);
4856 	/*
4857 	 * If the server doesn't support xattrs just return EINVAL
4858 	 */
4859 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
4860 		mutex_exit(&drp->r_statelock);
4861 		nfs_rw_exit(&drp->r_rwlock);
4862 		return (EINVAL);
4863 	}
4864 
4865 	/*
4866 	 * If there is a cached xattr directory entry,
4867 	 * use it as long as the attributes are valid. If the
4868 	 * attributes are not valid, take the simple approach and
4869 	 * free the cached value and re-fetch a new value.
4870 	 *
4871 	 * We don't negative entry cache for now, if we did we
4872 	 * would need to check if the file has changed on every
4873 	 * lookup. But xattrs don't exist very often and failing
4874 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
4875 	 * so do an openattr over the wire for now.
4876 	 */
4877 	if (drp->r_xattr_dir != NULL) {
4878 		if (ATTRCACHE4_VALID(dvp)) {
4879 			VN_HOLD(drp->r_xattr_dir);
4880 			*vpp = drp->r_xattr_dir;
4881 			mutex_exit(&drp->r_statelock);
4882 			nfs_rw_exit(&drp->r_rwlock);
4883 			return (0);
4884 		}
4885 		VN_RELE(drp->r_xattr_dir);
4886 		drp->r_xattr_dir = NULL;
4887 	}
4888 	mutex_exit(&drp->r_statelock);
4889 
4890 	error = nfs4openattr(dvp, vpp, cflag, cr);
4891 
4892 	nfs_rw_exit(&drp->r_rwlock);
4893 
4894 	return (error);
4895 }
4896 
4897 static int
4898 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
4899 {
4900 	int error;
4901 	rnode4_t *drp;
4902 
4903 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
4904 
4905 	/*
4906 	 * If lookup is for "", just return dvp.  Don't need
4907 	 * to send it over the wire, look it up in the dnlc,
4908 	 * or perform any access checks.
4909 	 */
4910 	if (*nm == '\0') {
4911 		VN_HOLD(dvp);
4912 		*vpp = dvp;
4913 		return (0);
4914 	}
4915 
4916 	/*
4917 	 * Can't do lookups in non-directories.
4918 	 */
4919 	if (dvp->v_type != VDIR)
4920 		return (ENOTDIR);
4921 
4922 	/*
4923 	 * If lookup is for ".", just return dvp.  Don't need
4924 	 * to send it over the wire or look it up in the dnlc,
4925 	 * just need to check access.
4926 	 */
4927 	if (nm[0] == '.' && nm[1] == '\0') {
4928 		error = nfs4_access(dvp, VEXEC, 0, cr);
4929 		if (error)
4930 			return (error);
4931 		VN_HOLD(dvp);
4932 		*vpp = dvp;
4933 		return (0);
4934 	}
4935 
4936 	drp = VTOR4(dvp);
4937 	if (!(drp->r_flags & R4LOOKUP)) {
4938 		mutex_enter(&drp->r_statelock);
4939 		drp->r_flags |= R4LOOKUP;
4940 		mutex_exit(&drp->r_statelock);
4941 	}
4942 
4943 	*vpp = NULL;
4944 	/*
4945 	 * Lookup this name in the DNLC.  If there is no entry
4946 	 * lookup over the wire.
4947 	 */
4948 	if (!skipdnlc)
4949 		*vpp = dnlc_lookup(dvp, nm);
4950 	if (*vpp == NULL) {
4951 		/*
4952 		 * We need to go over the wire to lookup the name.
4953 		 */
4954 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
4955 	}
4956 
4957 	/*
4958 	 * We hit on the dnlc
4959 	 */
4960 	if (*vpp != DNLC_NO_VNODE ||
4961 			    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
4962 		/*
4963 		 * But our attrs may not be valid.
4964 		 */
4965 		if (ATTRCACHE4_VALID(dvp)) {
4966 			error = nfs4_waitfor_purge_complete(dvp);
4967 			if (error) {
4968 				VN_RELE(*vpp);
4969 				*vpp = NULL;
4970 				return (error);
4971 			}
4972 
4973 			/*
4974 			 * If after the purge completes, check to make sure
4975 			 * our attrs are still valid.
4976 			 */
4977 			if (ATTRCACHE4_VALID(dvp)) {
4978 				/*
4979 				 * If we waited for a purge we may have
4980 				 * lost our vnode so look it up again.
4981 				 */
4982 				VN_RELE(*vpp);
4983 				*vpp = dnlc_lookup(dvp, nm);
4984 				if (*vpp == NULL)
4985 					return (nfs4lookupnew_otw(dvp,
4986 						nm, vpp, cr));
4987 
4988 				/*
4989 				 * The access cache should almost always hit
4990 				 */
4991 				error = nfs4_access(dvp, VEXEC, 0, cr);
4992 
4993 				if (error) {
4994 					VN_RELE(*vpp);
4995 					*vpp = NULL;
4996 					return (error);
4997 				}
4998 				if (*vpp == DNLC_NO_VNODE) {
4999 					VN_RELE(*vpp);
5000 					*vpp = NULL;
5001 					return (ENOENT);
5002 				}
5003 				return (0);
5004 			}
5005 		}
5006 	}
5007 
5008 	ASSERT(*vpp != NULL);
5009 
5010 	/*
5011 	 * We may have gotten here we have one of the following cases:
5012 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5013 	 *		need to validate them.
5014 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5015 	 *		must validate.
5016 	 *
5017 	 * Go to the server and check if the directory has changed, if
5018 	 * it hasn't we are done and can use the dnlc entry.
5019 	 */
5020 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5021 }
5022 
5023 /*
5024  * Go to the server and check if the directory has changed, if
5025  * it hasn't we are done and can use the dnlc entry.  If it
5026  * has changed we get a new copy of its attributes and check
5027  * the access for VEXEC, then relookup the filename and
5028  * get its filehandle and attributes.
5029  *
5030  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5031  *	if the NVERIFY failed we must
5032  *		purge the caches
5033  *		cache new attributes (will set r_time_attr_inval)
5034  *		cache new access
5035  *		recheck VEXEC access
5036  *		add name to dnlc, possibly negative
5037  *		if LOOKUP succeeded
5038  *			cache new attributes
5039  *	else
5040  *		set a new r_time_attr_inval for dvp
5041  *		check to make sure we have access
5042  *
5043  * The vpp returned is the vnode passed in if the directory is valid,
5044  * a new vnode if successful lookup, or NULL on error.
5045  */
5046 static int
5047 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5048 {
5049 	COMPOUND4args_clnt args;
5050 	COMPOUND4res_clnt res;
5051 	fattr4 *ver_fattr;
5052 	fattr4_change dchange;
5053 	int32_t *ptr;
5054 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5055 	nfs_argop4 *argop;
5056 	int doqueue;
5057 	mntinfo4_t *mi;
5058 	nfs4_recov_state_t recov_state;
5059 	hrtime_t t;
5060 	int isdotdot;
5061 	vnode_t *nvp;
5062 	nfs_fh4 *fhp;
5063 	nfs4_sharedfh_t *sfhp;
5064 	nfs4_access_type_t cacc;
5065 	rnode4_t *nrp;
5066 	rnode4_t *drp = VTOR4(dvp);
5067 	nfs4_ga_res_t *garp = NULL;
5068 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5069 
5070 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5071 	ASSERT(nm != NULL);
5072 	ASSERT(nm[0] != '\0');
5073 	ASSERT(dvp->v_type == VDIR);
5074 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5075 	ASSERT(*vpp != NULL);
5076 
5077 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5078 		isdotdot = 1;
5079 		args.ctag = TAG_LOOKUP_VPARENT;
5080 	} else {
5081 		/*
5082 		 * Do not allow crossing of server mount points.  The
5083 		 * only visible entries in a SRVSTUB dir are . and ..
5084 		 * This code handles the non-.. case.  We can't even get
5085 		 * this far if looking up ".".
5086 		 */
5087 		if (VTOR4(dvp)->r_flags & R4SRVSTUB) {
5088 			VN_RELE(*vpp);
5089 			*vpp = NULL;
5090 			return (ENOENT);
5091 		}
5092 		isdotdot = 0;
5093 		args.ctag = TAG_LOOKUP_VALID;
5094 	}
5095 
5096 	mi = VTOMI4(dvp);
5097 	recov_state.rs_flags = 0;
5098 	recov_state.rs_num_retry_despite_err = 0;
5099 
5100 	nvp = NULL;
5101 
5102 	/* Save the original mount point security information */
5103 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5104 
5105 recov_retry:
5106 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5107 			    &recov_state, NULL);
5108 	if (e.error) {
5109 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5110 		VN_RELE(*vpp);
5111 		*vpp = NULL;
5112 		return (e.error);
5113 	}
5114 
5115 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5116 
5117 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5118 	args.array_len = 7;
5119 	args.array = argop;
5120 
5121 	/* 0. putfh file */
5122 	argop[0].argop = OP_CPUTFH;
5123 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5124 
5125 	/* 1. nverify the change info */
5126 	argop[1].argop = OP_NVERIFY;
5127 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5128 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5129 	ver_fattr->attrlist4 = (char *)&dchange;
5130 	ptr = (int32_t *)&dchange;
5131 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5132 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5133 
5134 	/* 2. getattr directory */
5135 	argop[2].argop = OP_GETATTR;
5136 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5137 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5138 
5139 	/* 3. access directory */
5140 	argop[3].argop = OP_ACCESS;
5141 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5142 			ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5143 
5144 	/* 4. lookup name */
5145 	if (isdotdot) {
5146 		argop[4].argop = OP_LOOKUPP;
5147 	} else {
5148 		argop[4].argop = OP_CLOOKUP;
5149 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5150 	}
5151 
5152 	/* 5. resulting file handle */
5153 	argop[5].argop = OP_GETFH;
5154 
5155 	/* 6. resulting file attributes */
5156 	argop[6].argop = OP_GETATTR;
5157 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5158 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5159 
5160 	doqueue = 1;
5161 	t = gethrtime();
5162 
5163 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5164 
5165 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5166 		/*
5167 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5168 		 * from this thread, do not go thru the recovery thread since
5169 		 * we need the nm information.
5170 		 *
5171 		 * Not doing dotdot case because there is no specification
5172 		 * for (PUTFH, SECINFO "..") yet.
5173 		 */
5174 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5175 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr))) {
5176 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5177 					&recov_state, FALSE);
5178 			} else {
5179 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5180 					&recov_state, TRUE);
5181 			}
5182 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5183 			kmem_free(argop, argoplist_size);
5184 			if (!e.error)
5185 				goto recov_retry;
5186 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5187 			VN_RELE(*vpp);
5188 			*vpp = NULL;
5189 			return (e.error);
5190 		}
5191 
5192 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5193 		    OP_LOOKUP, NULL) == FALSE) {
5194 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5195 				&recov_state, TRUE);
5196 
5197 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5198 			kmem_free(argop, argoplist_size);
5199 			goto recov_retry;
5200 		}
5201 	}
5202 
5203 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5204 
5205 	if (e.error || res.array_len == 0) {
5206 		/*
5207 		 * If e.error isn't set, then reply has no ops (or we couldn't
5208 		 * be here).  The only legal way to reply without an op array
5209 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5210 		 * be in the reply for all other status values.
5211 		 *
5212 		 * For valid replies without an ops array, return ENOTSUP
5213 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5214 		 * return EIO -- don't trust status.
5215 		 */
5216 		if (e.error == 0)
5217 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5218 				ENOTSUP : EIO;
5219 		VN_RELE(*vpp);
5220 		*vpp = NULL;
5221 		kmem_free(argop, argoplist_size);
5222 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5223 		return (e.error);
5224 	}
5225 
5226 	if (res.status != NFS4ERR_SAME) {
5227 		e.error = geterrno4(res.status);
5228 
5229 		/*
5230 		 * The NVERIFY "failed" so the directory has changed
5231 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5232 		 * cleanly.
5233 		 */
5234 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5235 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5236 			nfs4_purge_stale_fh(e.error, dvp, cr);
5237 			VN_RELE(*vpp);
5238 			*vpp = NULL;
5239 			goto exit;
5240 		}
5241 
5242 		/*
5243 		 * We know the NVERIFY "failed" so we must:
5244 		 *	purge the caches (access and indirectly dnlc if needed)
5245 		 */
5246 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5247 
5248 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5249 			nfs4_purge_stale_fh(e.error, dvp, cr);
5250 			VN_RELE(*vpp);
5251 			*vpp = NULL;
5252 			goto exit;
5253 		}
5254 
5255 		/*
5256 		 * Install new cached attributes for the directory
5257 		 */
5258 		nfs4_attr_cache(dvp,
5259 				&res.array[2].nfs_resop4_u.opgetattr.ga_res,
5260 				t, cr, FALSE, NULL);
5261 
5262 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5263 			nfs4_purge_stale_fh(e.error, dvp, cr);
5264 			VN_RELE(*vpp);
5265 			*vpp = NULL;
5266 			e.error = geterrno4(res.status);
5267 			goto exit;
5268 		}
5269 
5270 		/*
5271 		 * Now we know the directory is valid,
5272 		 * cache new directory access
5273 		 */
5274 		nfs4_access_cache(drp,
5275 			args.array[3].nfs_argop4_u.opaccess.access,
5276 			res.array[3].nfs_resop4_u.opaccess.access, cr);
5277 
5278 		/*
5279 		 * recheck VEXEC access
5280 		 */
5281 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5282 		if (cacc != NFS4_ACCESS_ALLOWED) {
5283 			/*
5284 			 * Directory permissions might have been revoked
5285 			 */
5286 			if (cacc == NFS4_ACCESS_DENIED) {
5287 				e.error = EACCES;
5288 				VN_RELE(*vpp);
5289 				*vpp = NULL;
5290 				goto exit;
5291 			}
5292 
5293 			/*
5294 			 * Somehow we must not have asked for enough
5295 			 * so try a singleton ACCESS, should never happen.
5296 			 */
5297 			e.error = nfs4_access(dvp, VEXEC, 0, cr);
5298 			if (e.error) {
5299 				VN_RELE(*vpp);
5300 				*vpp = NULL;
5301 				goto exit;
5302 			}
5303 		}
5304 
5305 		e.error = geterrno4(res.status);
5306 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5307 			/*
5308 			 * The lookup failed, probably no entry
5309 			 */
5310 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5311 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5312 			} else {
5313 				/*
5314 				 * Might be some other error, so remove
5315 				 * the dnlc entry to make sure we start all
5316 				 * over again, next time.
5317 				 */
5318 				dnlc_remove(dvp, nm);
5319 			}
5320 			VN_RELE(*vpp);
5321 			*vpp = NULL;
5322 			goto exit;
5323 		}
5324 
5325 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5326 			/*
5327 			 * The file exists but we can't get its fh for
5328 			 * some unknown reason.  Remove it from the dnlc
5329 			 * and error out to be safe.
5330 			 */
5331 			dnlc_remove(dvp, nm);
5332 			VN_RELE(*vpp);
5333 			*vpp = NULL;
5334 			goto exit;
5335 		}
5336 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5337 		if (fhp->nfs_fh4_len == 0) {
5338 			/*
5339 			 * The file exists but a bogus fh
5340 			 * some unknown reason.  Remove it from the dnlc
5341 			 * and error out to be safe.
5342 			 */
5343 			e.error = ENOENT;
5344 			dnlc_remove(dvp, nm);
5345 			VN_RELE(*vpp);
5346 			*vpp = NULL;
5347 			goto exit;
5348 		}
5349 		sfhp = sfh4_get(fhp, mi);
5350 
5351 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5352 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5353 
5354 		/*
5355 		 * Make the new rnode
5356 		 */
5357 		if (isdotdot) {
5358 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5359 			if (e.error) {
5360 				sfh4_rele(&sfhp);
5361 				VN_RELE(*vpp);
5362 				*vpp = NULL;
5363 				goto exit;
5364 			}
5365 			/*
5366 			 * XXX if nfs4_make_dotdot uses an existing rnode
5367 			 * XXX it doesn't update the attributes.
5368 			 * XXX for now just save them again to save an OTW
5369 			 */
5370 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5371 		} else {
5372 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5373 				dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5374 			/*
5375 			 * If v_type == VNON, then garp was NULL because
5376 			 * the last op in the compound failed and makenfs4node
5377 			 * could not find the vnode for sfhp. It created
5378 			 * a new vnode, so we have nothing to purge here.
5379 			 */
5380 			if (nvp->v_type == VNON) {
5381 				vattr_t vattr;
5382 
5383 				vattr.va_mask = AT_TYPE;
5384 				/*
5385 				 * N.B. We've already called nfs4_end_fop above.
5386 				 */
5387 				e.error = nfs4getattr(nvp, &vattr, cr);
5388 				if (e.error) {
5389 					sfh4_rele(&sfhp);
5390 					VN_RELE(*vpp);
5391 					*vpp = NULL;
5392 					VN_RELE(nvp);
5393 					goto exit;
5394 				}
5395 				nvp->v_type = vattr.va_type;
5396 			}
5397 		}
5398 		sfh4_rele(&sfhp);
5399 
5400 		nrp = VTOR4(nvp);
5401 		mutex_enter(&nrp->r_statev4_lock);
5402 		if (!nrp->created_v4) {
5403 			mutex_exit(&nrp->r_statev4_lock);
5404 			dnlc_update(dvp, nm, nvp);
5405 		} else
5406 			mutex_exit(&nrp->r_statev4_lock);
5407 
5408 		VN_RELE(*vpp);
5409 		*vpp = nvp;
5410 	} else {
5411 		hrtime_t now;
5412 		hrtime_t delta = 0;
5413 
5414 		e.error = 0;
5415 
5416 		/*
5417 		 * Because the NVERIFY "succeeded" we know that the
5418 		 * directory attributes are still valid
5419 		 * so update r_time_attr_inval
5420 		 */
5421 		now = gethrtime();
5422 		mutex_enter(&drp->r_statelock);
5423 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5424 			delta = now - drp->r_time_attr_saved;
5425 			if (delta < mi->mi_acdirmin)
5426 				delta = mi->mi_acdirmin;
5427 			else if (delta > mi->mi_acdirmax)
5428 				delta = mi->mi_acdirmax;
5429 		}
5430 		drp->r_time_attr_inval = now + delta;
5431 		mutex_exit(&drp->r_statelock);
5432 		dnlc_update(dvp, nm, *vpp);
5433 
5434 		/*
5435 		 * Even though we have a valid directory attr cache
5436 		 * and dnlc entry, we may not have access.
5437 		 * This should almost always hit the cache.
5438 		 */
5439 		e.error = nfs4_access(dvp, VEXEC, 0, cr);
5440 		if (e.error) {
5441 			VN_RELE(*vpp);
5442 			*vpp = NULL;
5443 		}
5444 
5445 		if (*vpp == DNLC_NO_VNODE) {
5446 			VN_RELE(*vpp);
5447 			*vpp = NULL;
5448 			e.error = ENOENT;
5449 		}
5450 	}
5451 
5452 exit:
5453 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5454 	kmem_free(argop, argoplist_size);
5455 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5456 	return (e.error);
5457 }
5458 
5459 /*
5460  * We need to go over the wire to lookup the name, but
5461  * while we are there verify the directory has not
5462  * changed but if it has, get new attributes and check access
5463  *
5464  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5465  *					NVERIFY GETATTR ACCESS
5466  *
5467  * With the results:
5468  *	if the NVERIFY failed we must purge the caches, add new attributes,
5469  *		and cache new access.
5470  *	set a new r_time_attr_inval
5471  *	add name to dnlc, possibly negative
5472  *	if LOOKUP succeeded
5473  *		cache new attributes
5474  */
5475 static int
5476 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5477 {
5478 	COMPOUND4args_clnt args;
5479 	COMPOUND4res_clnt res;
5480 	fattr4 *ver_fattr;
5481 	fattr4_change dchange;
5482 	int32_t *ptr;
5483 	nfs4_ga_res_t *garp = NULL;
5484 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5485 	nfs_argop4 *argop;
5486 	int doqueue;
5487 	mntinfo4_t *mi;
5488 	nfs4_recov_state_t recov_state;
5489 	hrtime_t t;
5490 	int isdotdot;
5491 	vnode_t *nvp;
5492 	nfs_fh4 *fhp;
5493 	nfs4_sharedfh_t *sfhp;
5494 	nfs4_access_type_t cacc;
5495 	rnode4_t *nrp;
5496 	rnode4_t *drp = VTOR4(dvp);
5497 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5498 
5499 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5500 	ASSERT(nm != NULL);
5501 	ASSERT(nm[0] != '\0');
5502 	ASSERT(dvp->v_type == VDIR);
5503 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5504 	ASSERT(*vpp == NULL);
5505 
5506 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5507 		isdotdot = 1;
5508 		args.ctag = TAG_LOOKUP_PARENT;
5509 	} else {
5510 		/*
5511 		 * Do not allow crossing of server mount points.  The
5512 		 * only visible entries in a SRVSTUB dir are . and ..
5513 		 * This code handles the non-.. case.  We can't even get
5514 		 * this far if looking up ".".
5515 		 */
5516 		if (VTOR4(dvp)->r_flags & R4SRVSTUB)
5517 			return (ENOENT);
5518 
5519 		isdotdot = 0;
5520 		args.ctag = TAG_LOOKUP;
5521 	}
5522 
5523 	mi = VTOMI4(dvp);
5524 	recov_state.rs_flags = 0;
5525 	recov_state.rs_num_retry_despite_err = 0;
5526 
5527 	nvp = NULL;
5528 
5529 	/* Save the original mount point security information */
5530 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5531 
5532 recov_retry:
5533 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5534 			    &recov_state, NULL);
5535 	if (e.error) {
5536 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5537 		return (e.error);
5538 	}
5539 
5540 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5541 
5542 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5543 	args.array_len = 9;
5544 	args.array = argop;
5545 
5546 	/* 0. putfh file */
5547 	argop[0].argop = OP_CPUTFH;
5548 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5549 
5550 	/* 1. savefh for the nverify */
5551 	argop[1].argop = OP_SAVEFH;
5552 
5553 	/* 2. lookup name */
5554 	if (isdotdot) {
5555 		argop[2].argop = OP_LOOKUPP;
5556 	} else {
5557 		argop[2].argop = OP_CLOOKUP;
5558 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5559 	}
5560 
5561 	/* 3. resulting file handle */
5562 	argop[3].argop = OP_GETFH;
5563 
5564 	/* 4. resulting file attributes */
5565 	argop[4].argop = OP_GETATTR;
5566 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5567 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5568 
5569 	/* 5. restorefh back the directory for the nverify */
5570 	argop[5].argop = OP_RESTOREFH;
5571 
5572 	/* 6. nverify the change info */
5573 	argop[6].argop = OP_NVERIFY;
5574 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5575 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5576 	ver_fattr->attrlist4 = (char *)&dchange;
5577 	ptr = (int32_t *)&dchange;
5578 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5579 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5580 
5581 	/* 7. getattr directory */
5582 	argop[7].argop = OP_GETATTR;
5583 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5584 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5585 
5586 	/* 8. access directory */
5587 	argop[8].argop = OP_ACCESS;
5588 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5589 			ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5590 
5591 	doqueue = 1;
5592 	t = gethrtime();
5593 
5594 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5595 
5596 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5597 		/*
5598 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5599 		 * from this thread, do not go thru the recovery thread since
5600 		 * we need the nm information.
5601 		 *
5602 		 * Not doing dotdot case because there is no specification
5603 		 * for (PUTFH, SECINFO "..") yet.
5604 		 */
5605 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5606 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr))) {
5607 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5608 					&recov_state, FALSE);
5609 			} else {
5610 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5611 					&recov_state, TRUE);
5612 			}
5613 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5614 			kmem_free(argop, argoplist_size);
5615 			if (!e.error)
5616 				goto recov_retry;
5617 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5618 			return (e.error);
5619 		}
5620 
5621 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5622 		    OP_LOOKUP, NULL) == FALSE) {
5623 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5624 				&recov_state, TRUE);
5625 
5626 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5627 			kmem_free(argop, argoplist_size);
5628 			goto recov_retry;
5629 		}
5630 	}
5631 
5632 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5633 
5634 	if (e.error || res.array_len == 0) {
5635 		/*
5636 		 * If e.error isn't set, then reply has no ops (or we couldn't
5637 		 * be here).  The only legal way to reply without an op array
5638 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5639 		 * be in the reply for all other status values.
5640 		 *
5641 		 * For valid replies without an ops array, return ENOTSUP
5642 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5643 		 * return EIO -- don't trust status.
5644 		 */
5645 		if (e.error == 0)
5646 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5647 				ENOTSUP : EIO;
5648 
5649 		kmem_free(argop, argoplist_size);
5650 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5651 		return (e.error);
5652 	}
5653 
5654 	e.error = geterrno4(res.status);
5655 
5656 	/*
5657 	 * The PUTFH and SAVEFH may have failed.
5658 	 */
5659 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5660 		    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5661 		nfs4_purge_stale_fh(e.error, dvp, cr);
5662 		goto exit;
5663 	}
5664 
5665 	/*
5666 	 * Check if the file exists, if it does delay entering
5667 	 * into the dnlc until after we update the directory
5668 	 * attributes so we don't cause it to get purged immediately.
5669 	 */
5670 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5671 		/*
5672 		 * The lookup failed, probably no entry
5673 		 */
5674 		if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5675 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5676 		}
5677 		goto exit;
5678 	}
5679 
5680 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5681 		/*
5682 		 * The file exists but we can't get its fh for
5683 		 * some unknown reason. Error out to be safe.
5684 		 */
5685 		goto exit;
5686 	}
5687 
5688 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5689 	if (fhp->nfs_fh4_len == 0) {
5690 		/*
5691 		 * The file exists but a bogus fh
5692 		 * some unknown reason.  Error out to be safe.
5693 		 */
5694 		e.error = EIO;
5695 		goto exit;
5696 	}
5697 	sfhp = sfh4_get(fhp, mi);
5698 
5699 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5700 		sfh4_rele(&sfhp);
5701 		e.error = EIO;
5702 		goto exit;
5703 	}
5704 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5705 
5706 	/*
5707 	 * The RESTOREFH may have failed
5708 	 */
5709 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5710 		sfh4_rele(&sfhp);
5711 		e.error = EIO;
5712 		goto exit;
5713 	}
5714 
5715 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5716 		/*
5717 		 * First make sure the NVERIFY failed as we expected,
5718 		 * if it didn't then be conservative and error out
5719 		 * as we can't trust the directory.
5720 		 */
5721 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5722 			sfh4_rele(&sfhp);
5723 			e.error = EIO;
5724 			goto exit;
5725 		}
5726 
5727 		/*
5728 		 * We know the NVERIFY "failed" so the directory has changed,
5729 		 * so we must:
5730 		 *	purge the caches (access and indirectly dnlc if needed)
5731 		 */
5732 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5733 
5734 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5735 			sfh4_rele(&sfhp);
5736 			goto exit;
5737 		}
5738 		nfs4_attr_cache(dvp,
5739 				&res.array[7].nfs_resop4_u.opgetattr.ga_res,
5740 				t, cr, FALSE, NULL);
5741 
5742 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5743 			nfs4_purge_stale_fh(e.error, dvp, cr);
5744 			sfh4_rele(&sfhp);
5745 			e.error = geterrno4(res.status);
5746 			goto exit;
5747 		}
5748 
5749 		/*
5750 		 * Now we know the directory is valid,
5751 		 * cache new directory access
5752 		 */
5753 		nfs4_access_cache(drp,
5754 			args.array[8].nfs_argop4_u.opaccess.access,
5755 			res.array[8].nfs_resop4_u.opaccess.access, cr);
5756 
5757 		/*
5758 		 * recheck VEXEC access
5759 		 */
5760 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5761 		if (cacc != NFS4_ACCESS_ALLOWED) {
5762 			/*
5763 			 * Directory permissions might have been revoked
5764 			 */
5765 			if (cacc == NFS4_ACCESS_DENIED) {
5766 				sfh4_rele(&sfhp);
5767 				e.error = EACCES;
5768 				goto exit;
5769 			}
5770 
5771 			/*
5772 			 * Somehow we must not have asked for enough
5773 			 * so try a singleton ACCESS should never happen
5774 			 */
5775 			e.error = nfs4_access(dvp, VEXEC, 0, cr);
5776 			if (e.error) {
5777 				sfh4_rele(&sfhp);
5778 				goto exit;
5779 			}
5780 		}
5781 
5782 		e.error = geterrno4(res.status);
5783 	} else {
5784 		hrtime_t now;
5785 		hrtime_t delta = 0;
5786 
5787 		e.error = 0;
5788 
5789 		/*
5790 		 * Because the NVERIFY "succeeded" we know that the
5791 		 * directory attributes are still valid
5792 		 * so update r_time_attr_inval
5793 		 */
5794 		now = gethrtime();
5795 		mutex_enter(&drp->r_statelock);
5796 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5797 			delta = now - drp->r_time_attr_saved;
5798 			if (delta < mi->mi_acdirmin)
5799 				delta = mi->mi_acdirmin;
5800 			else if (delta > mi->mi_acdirmax)
5801 				delta = mi->mi_acdirmax;
5802 		}
5803 		drp->r_time_attr_inval = now + delta;
5804 		mutex_exit(&drp->r_statelock);
5805 
5806 		/*
5807 		 * Even though we have a valid directory attr cache,
5808 		 * we may not have access.
5809 		 * This should almost always hit the cache.
5810 		 */
5811 		e.error = nfs4_access(dvp, VEXEC, 0, cr);
5812 		if (e.error) {
5813 			sfh4_rele(&sfhp);
5814 			goto exit;
5815 		}
5816 	}
5817 
5818 	/*
5819 	 * Now we have successfully completed the lookup, if the
5820 	 * directory has changed we now have the valid attributes.
5821 	 * We also know we have directory access.
5822 	 * Create the new rnode and insert it in the dnlc.
5823 	 */
5824 	if (isdotdot) {
5825 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5826 		if (e.error) {
5827 			sfh4_rele(&sfhp);
5828 			goto exit;
5829 		}
5830 		/*
5831 		 * XXX if nfs4_make_dotdot uses an existing rnode
5832 		 * XXX it doesn't update the attributes.
5833 		 * XXX for now just save them again to save an OTW
5834 		 */
5835 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5836 	} else {
5837 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5838 			dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5839 	}
5840 	sfh4_rele(&sfhp);
5841 
5842 	nrp = VTOR4(nvp);
5843 	mutex_enter(&nrp->r_statev4_lock);
5844 	if (!nrp->created_v4) {
5845 		mutex_exit(&nrp->r_statev4_lock);
5846 		dnlc_update(dvp, nm, nvp);
5847 	} else
5848 		mutex_exit(&nrp->r_statev4_lock);
5849 
5850 	*vpp = nvp;
5851 
5852 exit:
5853 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5854 	kmem_free(argop, argoplist_size);
5855 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5856 	return (e.error);
5857 }
5858 
5859 #ifdef DEBUG
5860 void
5861 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
5862 {
5863 	uint_t i, len;
5864 	zoneid_t zoneid = getzoneid();
5865 	char *s;
5866 
5867 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
5868 	for (i = 0; i < argcnt; i++) {
5869 		nfs_argop4 *op = &argbase[i];
5870 		switch (op->argop) {
5871 		case OP_CPUTFH:
5872 		case OP_PUTFH:
5873 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
5874 			break;
5875 		case OP_PUTROOTFH:
5876 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
5877 			break;
5878 		case OP_CLOOKUP:
5879 			s = op->nfs_argop4_u.opclookup.cname;
5880 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5881 			break;
5882 		case OP_LOOKUP:
5883 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
5884 			    &len, NULL);
5885 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5886 			kmem_free(s, len);
5887 			break;
5888 		case OP_LOOKUPP:
5889 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
5890 			break;
5891 		case OP_GETFH:
5892 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
5893 			break;
5894 		case OP_GETATTR:
5895 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
5896 			break;
5897 		case OP_OPENATTR:
5898 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
5899 			break;
5900 		default:
5901 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
5902 			    op->argop);
5903 			break;
5904 		}
5905 	}
5906 }
5907 #endif
5908 
5909 /*
5910  * nfs4lookup_setup - constructs a multi-lookup compound request.
5911  *
5912  * Given the path "nm1/nm2/.../nmn", the following compound requests
5913  * may be created:
5914  *
5915  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
5916  * is faster, for now.
5917  *
5918  * l4_getattrs indicates the type of compound requested.
5919  *
5920  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
5921  *
5922  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
5923  *
5924  *   total number of ops is n + 1.
5925  *
5926  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
5927  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
5928  *      before the last component, and only get attributes
5929  *      for the last component.  Note that the second-to-last
5930  *	pathname component is XATTR_RPATH, which does NOT go
5931  *	over-the-wire as a lookup.
5932  *
5933  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
5934  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
5935  *
5936  *   and total number of ops is n + 5.
5937  *
5938  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
5939  *      attribute directory: create lookups plus an OPENATTR
5940  *	replacing the last lookup.  Note that the last pathname
5941  *	component is XATTR_RPATH, which does NOT go over-the-wire
5942  *	as a lookup.
5943  *
5944  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
5945  *		Openattr; Getfh; Getattr }
5946  *
5947  *   and total number of ops is n + 5.
5948  *
5949  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
5950  *	nodes too.
5951  *
5952  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
5953  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
5954  *
5955  *   and total number of ops is 3*n + 1.
5956  *
5957  * All cases: returns the index in the arg array of the final LOOKUP op, or
5958  * -1 if no LOOKUPs were used.
5959  */
5960 int
5961 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
5962 {
5963 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
5964 	nfs_argop4 *argbase, *argop;
5965 	int arglen, argcnt;
5966 	int n = 1;	/* number of components */
5967 	int nga = 1;	/* number of Getattr's in request */
5968 	char c = '\0', *s, *p;
5969 	int lookup_idx = -1;
5970 	int argoplist_size;
5971 
5972 	/* set lookuparg response result to 0 */
5973 	lookupargp->resp->status = NFS4_OK;
5974 
5975 	/* skip leading "/" or "." e.g. ".//./" if there is */
5976 	for (; ; nm++) {
5977 		if (*nm != '/' && *nm != '.')
5978 			break;
5979 
5980 		/* ".." is counted as 1 component */
5981 		if (*nm == '.' && *(nm + 1) == '.')
5982 			break;
5983 	}
5984 
5985 	/*
5986 	 * Find n = number of components - nm must be null terminated
5987 	 * Skip "." components.
5988 	 */
5989 	if (*nm != '\0') {
5990 		for (n = 1, s = nm; *s != '\0'; s++) {
5991 			if ((*s == '/') && (*(s + 1) != '/') &&
5992 				    (*(s + 1) != '\0') &&
5993 				    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
5994 					*(s + 2) == '\0')))
5995 				n++;
5996 		}
5997 	} else
5998 		n = 0;
5999 
6000 	/*
6001 	 * nga is number of components that need Getfh+Getattr
6002 	 */
6003 	switch (l4_getattrs) {
6004 	case LKP4_NO_ATTRIBUTES:
6005 		nga = 0;
6006 		break;
6007 	case LKP4_ALL_ATTRIBUTES:
6008 		nga = n;
6009 		/*
6010 		 * Always have at least 1 getfh, getattr pair
6011 		 */
6012 		if (nga == 0)
6013 			nga++;
6014 		break;
6015 	case LKP4_LAST_ATTRDIR:
6016 	case LKP4_LAST_NAMED_ATTR:
6017 		nga = n+1;
6018 		break;
6019 	}
6020 
6021 	/*
6022 	 * If change to use the filehandle attr instead of getfh
6023 	 * the following line can be deleted.
6024 	 */
6025 	nga *= 2;
6026 
6027 	/*
6028 	 * calculate number of ops in request as
6029 	 * header + trailer + lookups + getattrs
6030 	 */
6031 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6032 
6033 	argoplist_size = arglen * sizeof (nfs_argop4);
6034 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6035 	lookupargp->argsp->array = argop;
6036 
6037 	argcnt = lookupargp->header_len;
6038 	argop += argcnt;
6039 
6040 	/*
6041 	 * loop and create a lookup op and possibly getattr/getfh for
6042 	 * each component. Skip "." components.
6043 	 */
6044 	for (s = nm; *s != '\0'; s = p) {
6045 		/*
6046 		 * Set up a pathname struct for each component if needed
6047 		 */
6048 		while (*s == '/')
6049 			s++;
6050 		if (*s == '\0')
6051 			break;
6052 		for (p = s; (*p != '/') && (*p != '\0'); p++);
6053 		c = *p;
6054 		*p = '\0';
6055 
6056 		if (s[0] == '.' && s[1] == '\0') {
6057 			*p = c;
6058 			continue;
6059 		}
6060 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6061 		    strcmp(s, XATTR_RPATH) == 0) {
6062 			/* getfh XXX may not be needed in future */
6063 			argop->argop = OP_GETFH;
6064 			argop++;
6065 			argcnt++;
6066 
6067 			/* getattr */
6068 			argop->argop = OP_GETATTR;
6069 			argop->nfs_argop4_u.opgetattr.attr_request =
6070 							lookupargp->ga_bits;
6071 			argop->nfs_argop4_u.opgetattr.mi =
6072 				lookupargp->mi;
6073 			argop++;
6074 			argcnt++;
6075 
6076 			/* openattr */
6077 			argop->argop = OP_OPENATTR;
6078 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6079 		    strcmp(s, XATTR_RPATH) == 0) {
6080 			/* openattr */
6081 			argop->argop = OP_OPENATTR;
6082 			argop++;
6083 			argcnt++;
6084 
6085 			/* getfh XXX may not be needed in future */
6086 			argop->argop = OP_GETFH;
6087 			argop++;
6088 			argcnt++;
6089 
6090 			/* getattr */
6091 			argop->argop = OP_GETATTR;
6092 			argop->nfs_argop4_u.opgetattr.attr_request =
6093 							lookupargp->ga_bits;
6094 			argop->nfs_argop4_u.opgetattr.mi =
6095 							lookupargp->mi;
6096 			argop++;
6097 			argcnt++;
6098 			*p = c;
6099 			continue;
6100 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6101 			/* lookupp */
6102 			argop->argop = OP_LOOKUPP;
6103 		} else {
6104 			/* lookup */
6105 			argop->argop = OP_LOOKUP;
6106 			(void) str_to_utf8(s,
6107 				&argop->nfs_argop4_u.oplookup.objname);
6108 		}
6109 		lookup_idx = argcnt;
6110 		argop++;
6111 		argcnt++;
6112 
6113 		*p = c;
6114 
6115 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6116 			/* getfh XXX may not be needed in future */
6117 			argop->argop = OP_GETFH;
6118 			argop++;
6119 			argcnt++;
6120 
6121 			/* getattr */
6122 			argop->argop = OP_GETATTR;
6123 			argop->nfs_argop4_u.opgetattr.attr_request =
6124 							lookupargp->ga_bits;
6125 			argop->nfs_argop4_u.opgetattr.mi =
6126 							lookupargp->mi;
6127 			argop++;
6128 			argcnt++;
6129 		}
6130 	}
6131 
6132 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6133 		((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6134 		if (needgetfh) {
6135 			/* stick in a post-lookup getfh */
6136 			argop->argop = OP_GETFH;
6137 			argcnt++;
6138 			argop++;
6139 		}
6140 		/* post-lookup getattr */
6141 		argop->argop = OP_GETATTR;
6142 		argop->nfs_argop4_u.opgetattr.attr_request =
6143 						lookupargp->ga_bits;
6144 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6145 		argcnt++;
6146 	}
6147 	argcnt += lookupargp->trailer_len;	/* actual op count */
6148 	lookupargp->argsp->array_len = argcnt;
6149 	lookupargp->arglen = arglen;
6150 
6151 #ifdef DEBUG
6152 	if (nfs4_client_lookup_debug)
6153 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6154 #endif
6155 
6156 	return (lookup_idx);
6157 }
6158 
6159 static int
6160 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6161 {
6162 	COMPOUND4args_clnt	args;
6163 	COMPOUND4res_clnt	res;
6164 	GETFH4res	*gf_res = NULL;
6165 	nfs_argop4	argop[4];
6166 	nfs_resop4	*resop = NULL;
6167 	nfs4_sharedfh_t *sfhp;
6168 	hrtime_t t;
6169 	nfs4_error_t	e;
6170 
6171 	rnode4_t	*drp;
6172 	int		doqueue = 1;
6173 	vnode_t		*vp;
6174 	int		needrecov = 0;
6175 	nfs4_recov_state_t recov_state;
6176 
6177 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6178 
6179 	*avp = NULL;
6180 	recov_state.rs_flags = 0;
6181 	recov_state.rs_num_retry_despite_err = 0;
6182 
6183 recov_retry:
6184 	/* COMPOUND: putfh, openattr, getfh, getattr */
6185 	args.array_len = 4;
6186 	args.array = argop;
6187 	args.ctag = TAG_OPENATTR;
6188 
6189 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6190 	if (e.error)
6191 		return (e.error);
6192 
6193 	drp = VTOR4(dvp);
6194 
6195 	/* putfh */
6196 	argop[0].argop = OP_CPUTFH;
6197 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6198 
6199 	/* openattr */
6200 	argop[1].argop = OP_OPENATTR;
6201 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6202 
6203 	/* getfh */
6204 	argop[2].argop = OP_GETFH;
6205 
6206 	/* getattr */
6207 	argop[3].argop = OP_GETATTR;
6208 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6209 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6210 
6211 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6212 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6213 	    rnode4info(drp)));
6214 
6215 	t = gethrtime();
6216 
6217 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6218 
6219 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6220 	if (needrecov) {
6221 		bool_t abort;
6222 
6223 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6224 		    "nfs4openattr: initiating recovery\n"));
6225 
6226 		abort = nfs4_start_recovery(&e,
6227 				VTOMI4(dvp), dvp, NULL, NULL, NULL,
6228 				OP_OPENATTR, NULL);
6229 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6230 		if (!e.error) {
6231 			e.error = geterrno4(res.status);
6232 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6233 		}
6234 		if (abort == FALSE)
6235 			goto recov_retry;
6236 		return (e.error);
6237 	}
6238 
6239 	if (e.error) {
6240 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6241 		return (e.error);
6242 	}
6243 
6244 	if (res.status) {
6245 		/*
6246 		 * If OTW errro is NOTSUPP, then it should be
6247 		 * translated to EINVAL.  All Solaris file system
6248 		 * implementations return EINVAL to the syscall layer
6249 		 * when the attrdir cannot be created due to an
6250 		 * implementation restriction or noxattr mount option.
6251 		 */
6252 		if (res.status == NFS4ERR_NOTSUPP) {
6253 			mutex_enter(&drp->r_statelock);
6254 			if (drp->r_xattr_dir)
6255 				VN_RELE(drp->r_xattr_dir);
6256 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6257 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6258 			mutex_exit(&drp->r_statelock);
6259 
6260 			e.error = EINVAL;
6261 		} else {
6262 			e.error = geterrno4(res.status);
6263 		}
6264 
6265 		if (e.error) {
6266 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6267 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6268 				    needrecov);
6269 			return (e.error);
6270 		}
6271 	}
6272 
6273 	resop = &res.array[0];  /* putfh res */
6274 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6275 
6276 	resop = &res.array[1];  /* openattr res */
6277 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6278 
6279 	resop = &res.array[2];  /* getfh res */
6280 	gf_res = &resop->nfs_resop4_u.opgetfh;
6281 	if (gf_res->object.nfs_fh4_len == 0) {
6282 		*avp = NULL;
6283 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6284 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6285 		return (ENOENT);
6286 	}
6287 
6288 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6289 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6290 				dvp->v_vfsp, t, cr, dvp,
6291 				fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH));
6292 	sfh4_rele(&sfhp);
6293 
6294 	if (e.error)
6295 		PURGE_ATTRCACHE4(vp);
6296 
6297 	mutex_enter(&vp->v_lock);
6298 	vp->v_flag |= V_XATTRDIR;
6299 	mutex_exit(&vp->v_lock);
6300 
6301 	*avp = vp;
6302 
6303 	mutex_enter(&drp->r_statelock);
6304 	if (drp->r_xattr_dir)
6305 		VN_RELE(drp->r_xattr_dir);
6306 	VN_HOLD(vp);
6307 	drp->r_xattr_dir = vp;
6308 
6309 	/*
6310 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6311 	 * NULL.  xattrs could be created at any time, and we have no
6312 	 * way to update pc4_xattr_exists in the base object if/when
6313 	 * it happens.
6314 	 */
6315 	drp->r_pathconf.pc4_xattr_valid = 0;
6316 
6317 	mutex_exit(&drp->r_statelock);
6318 
6319 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6320 
6321 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6322 
6323 	return (0);
6324 }
6325 
6326 /* ARGSUSED */
6327 static int
6328 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6329 	int mode, vnode_t **vpp, cred_t *cr, int flags)
6330 {
6331 	int error;
6332 	vnode_t *vp = NULL;
6333 	rnode4_t *rp;
6334 	struct vattr vattr;
6335 	rnode4_t *drp;
6336 	vnode_t *tempvp;
6337 	enum createmode4 createmode;
6338 	bool_t must_trunc = FALSE;
6339 
6340 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6341 		return (EPERM);
6342 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6343 		return (EINVAL);
6344 	}
6345 
6346 	/* . and .. have special meaning in the protocol, reject them. */
6347 
6348 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6349 		return (EISDIR);
6350 
6351 	drp = VTOR4(dvp);
6352 
6353 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6354 		return (EINTR);
6355 
6356 top:
6357 	/*
6358 	 * We make a copy of the attributes because the caller does not
6359 	 * expect us to change what va points to.
6360 	 */
6361 	vattr = *va;
6362 
6363 	/*
6364 	 * If the pathname is "", then dvp is the root vnode of
6365 	 * a remote file mounted over a local directory.
6366 	 * All that needs to be done is access
6367 	 * checking and truncation.  Note that we avoid doing
6368 	 * open w/ create because the parent directory might
6369 	 * be in pseudo-fs and the open would fail.
6370 	 */
6371 	if (*nm == '\0') {
6372 		error = 0;
6373 		VN_HOLD(dvp);
6374 		vp = dvp;
6375 		must_trunc = TRUE;
6376 	} else {
6377 		/*
6378 		 * We need to go over the wire, just to be sure whether the
6379 		 * file exists or not.  Using the DNLC can be dangerous in
6380 		 * this case when making a decision regarding existence.
6381 		 */
6382 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6383 	}
6384 
6385 	if (exclusive)
6386 		createmode = EXCLUSIVE4;
6387 	else
6388 		createmode = GUARDED4;
6389 
6390 	/*
6391 	 * error would be set if the file does not exist on the
6392 	 * server, so lets go create it.
6393 	 */
6394 	if (error) {
6395 		goto create_otw;
6396 	}
6397 
6398 	/*
6399 	 * File does exist on the server
6400 	 */
6401 	if (exclusive == EXCL)
6402 		error = EEXIST;
6403 	else if (vp->v_type == VDIR && (mode & VWRITE))
6404 		error = EISDIR;
6405 	else {
6406 		/*
6407 		 * If vnode is a device, create special vnode.
6408 		 */
6409 		if (ISVDEV(vp->v_type)) {
6410 			tempvp = vp;
6411 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6412 			VN_RELE(tempvp);
6413 		}
6414 		if (!(error = VOP_ACCESS(vp, mode, 0, cr))) {
6415 			if ((vattr.va_mask & AT_SIZE) &&
6416 			    vp->v_type == VREG) {
6417 				rp = VTOR4(vp);
6418 				/*
6419 				 * Check here for large file handled
6420 				 * by LF-unaware process (as
6421 				 * ufs_create() does)
6422 				 */
6423 				if (!(flags & FOFFMAX)) {
6424 					mutex_enter(&rp->r_statelock);
6425 					if (rp->r_size > MAXOFF32_T)
6426 						error = EOVERFLOW;
6427 					mutex_exit(&rp->r_statelock);
6428 				}
6429 
6430 				/* if error is set then we need to return */
6431 				if (error) {
6432 					nfs_rw_exit(&drp->r_rwlock);
6433 					VN_RELE(vp);
6434 					return (error);
6435 				}
6436 
6437 				if (must_trunc) {
6438 					vattr.va_mask = AT_SIZE;
6439 					error = nfs4setattr(vp, &vattr, 0, cr,
6440 						NULL);
6441 				} else {
6442 				/*
6443 				 * we know we have a regular file that already
6444 				 * exists and we may end up truncating the file
6445 				 * as a result of the open_otw, so flush out
6446 				 * any dirty pages for this file first.
6447 				 */
6448 					if (nfs4_has_pages(vp) &&
6449 					    ((rp->r_flags & R4DIRTY) ||
6450 					    rp->r_count > 0 ||
6451 					    rp->r_mapcnt > 0)) {
6452 						error = nfs4_putpage(vp,
6453 							(offset_t)0, 0, 0, cr);
6454 						if (error && (error == ENOSPC ||
6455 						    error == EDQUOT)) {
6456 							mutex_enter(
6457 							    &rp->r_statelock);
6458 							if (!rp->r_error)
6459 								rp->r_error =
6460 								    error;
6461 							mutex_exit(
6462 							    &rp->r_statelock);
6463 						}
6464 					}
6465 					vattr.va_mask = (AT_SIZE |
6466 							AT_TYPE | AT_MODE);
6467 					vattr.va_type = VREG;
6468 					createmode = UNCHECKED4;
6469 					goto create_otw;
6470 				}
6471 			}
6472 		}
6473 	}
6474 	nfs_rw_exit(&drp->r_rwlock);
6475 	if (error) {
6476 		VN_RELE(vp);
6477 	} else {
6478 		*vpp = vp;
6479 	}
6480 	return (error);
6481 
6482 create_otw:
6483 	dnlc_remove(dvp, nm);
6484 
6485 	ASSERT(vattr.va_mask & AT_TYPE);
6486 
6487 	/*
6488 	 * If not a regular file let nfs4mknod() handle it.
6489 	 */
6490 	if (vattr.va_type != VREG) {
6491 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6492 		nfs_rw_exit(&drp->r_rwlock);
6493 		return (error);
6494 	}
6495 
6496 	/*
6497 	 * It _is_ a regular file.
6498 	 */
6499 	ASSERT(vattr.va_mask & AT_MODE);
6500 	if (MANDMODE(vattr.va_mode)) {
6501 		nfs_rw_exit(&drp->r_rwlock);
6502 		return (EACCES);
6503 	}
6504 
6505 	/*
6506 	 * If this happens to be a mknod of a regular file, then flags will
6507 	 * have neither FREAD or FWRITE.  However, we must set at least one
6508 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6509 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6510 	 * set (based on openmode specified by app).
6511 	 */
6512 	if ((flags & (FREAD|FWRITE)) == 0)
6513 		flags |= (FREAD|FWRITE);
6514 
6515 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6516 
6517 	if (vp != NULL) {
6518 		/* if create was successful, throw away the file's pages */
6519 		if (!error && (vattr.va_mask & AT_SIZE))
6520 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6521 				cr);
6522 		/* release the lookup hold */
6523 		VN_RELE(vp);
6524 		vp = NULL;
6525 	}
6526 
6527 	/*
6528 	 * validate that we opened a regular file. This handles a misbehaving
6529 	 * server that returns an incorrect FH.
6530 	 */
6531 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6532 		error = EISDIR;
6533 		VN_RELE(*vpp);
6534 	}
6535 
6536 	/*
6537 	 * If this is not an exclusive create, then the CREATE
6538 	 * request will be made with the GUARDED mode set.  This
6539 	 * means that the server will return EEXIST if the file
6540 	 * exists.  The file could exist because of a retransmitted
6541 	 * request.  In this case, we recover by starting over and
6542 	 * checking to see whether the file exists.  This second
6543 	 * time through it should and a CREATE request will not be
6544 	 * sent.
6545 	 *
6546 	 * This handles the problem of a dangling CREATE request
6547 	 * which contains attributes which indicate that the file
6548 	 * should be truncated.  This retransmitted request could
6549 	 * possibly truncate valid data in the file if not caught
6550 	 * by the duplicate request mechanism on the server or if
6551 	 * not caught by other means.  The scenario is:
6552 	 *
6553 	 * Client transmits CREATE request with size = 0
6554 	 * Client times out, retransmits request.
6555 	 * Response to the first request arrives from the server
6556 	 *  and the client proceeds on.
6557 	 * Client writes data to the file.
6558 	 * The server now processes retransmitted CREATE request
6559 	 *  and truncates file.
6560 	 *
6561 	 * The use of the GUARDED CREATE request prevents this from
6562 	 * happening because the retransmitted CREATE would fail
6563 	 * with EEXIST and would not truncate the file.
6564 	 */
6565 	if (error == EEXIST && exclusive == NONEXCL) {
6566 #ifdef DEBUG
6567 		nfs4_create_misses++;
6568 #endif
6569 		goto top;
6570 	}
6571 	nfs_rw_exit(&drp->r_rwlock);
6572 	return (error);
6573 }
6574 
6575 /*
6576  * Create compound (for mkdir, mknod, symlink):
6577  * { Putfh <dfh>; Create; Getfh; Getattr }
6578  * It's okay if setattr failed to set gid - this is not considered
6579  * an error, but purge attrs in that case.
6580  */
6581 static int
6582 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6583 	vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6584 {
6585 	int need_end_op = FALSE;
6586 	COMPOUND4args_clnt args;
6587 	COMPOUND4res_clnt res, *resp = NULL;
6588 	nfs_argop4 *argop;
6589 	nfs_resop4 *resop;
6590 	int doqueue;
6591 	mntinfo4_t *mi;
6592 	rnode4_t *drp = VTOR4(dvp);
6593 	change_info4 *cinfo;
6594 	GETFH4res *gf_res;
6595 	struct vattr vattr;
6596 	vnode_t *vp;
6597 	fattr4 *crattr;
6598 	bool_t needrecov = FALSE;
6599 	nfs4_recov_state_t recov_state;
6600 	nfs4_sharedfh_t *sfhp = NULL;
6601 	hrtime_t t;
6602 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6603 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6604 	dirattr_info_t dinfo, *dinfop;
6605 	servinfo4_t *svp;
6606 	bitmap4 supp_attrs;
6607 
6608 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6609 		type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6610 
6611 	mi = VTOMI4(dvp);
6612 
6613 	/*
6614 	 * Make sure we properly deal with setting the right gid
6615 	 * on a new directory to reflect the parent's setgid bit
6616 	 */
6617 	setgid_flag = 0;
6618 	if (type == NF4DIR) {
6619 		struct vattr dva;
6620 
6621 		va->va_mode &= ~VSGID;
6622 		dva.va_mask = AT_MODE | AT_GID;
6623 		if (VOP_GETATTR(dvp, &dva, 0, cr) == 0) {
6624 
6625 			/*
6626 			 * If the parent's directory has the setgid bit set
6627 			 * _and_ the client was able to get a valid mapping
6628 			 * for the parent dir's owner_group, we want to
6629 			 * append NVERIFY(owner_group == dva.va_gid) and
6630 			 * SETTATTR to the CREATE compound.
6631 			 */
6632 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6633 				setgid_flag = 1;
6634 				va->va_mode |= VSGID;
6635 				if (dva.va_gid != GID_NOBODY) {
6636 					va->va_mask |= AT_GID;
6637 					va->va_gid = dva.va_gid;
6638 				}
6639 			}
6640 		}
6641 	}
6642 
6643 	/*
6644 	 * Create ops:
6645 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6646 	 *	5:restorefh(dir) 6:getattr(dir)
6647 	 *
6648 	 * if (setgid)
6649 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6650 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6651 	 *	8:nverify 9:setattr
6652 	 */
6653 	if (setgid_flag) {
6654 		numops = 10;
6655 		idx_create = 1;
6656 		idx_fattr = 3;
6657 	} else {
6658 		numops = 7;
6659 		idx_create = 2;
6660 		idx_fattr = 4;
6661 	}
6662 
6663 	ASSERT(nfs_zone() == mi->mi_zone);
6664 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6665 		return (EINTR);
6666 	}
6667 	recov_state.rs_flags = 0;
6668 	recov_state.rs_num_retry_despite_err = 0;
6669 
6670 	argoplist_size = numops * sizeof (nfs_argop4);
6671 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6672 
6673 recov_retry:
6674 	if (type == NF4LNK)
6675 		args.ctag = TAG_SYMLINK;
6676 	else if (type == NF4DIR)
6677 		args.ctag = TAG_MKDIR;
6678 	else
6679 		args.ctag = TAG_MKNOD;
6680 
6681 	args.array_len = numops;
6682 	args.array = argop;
6683 
6684 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6685 		nfs_rw_exit(&drp->r_rwlock);
6686 		kmem_free(argop, argoplist_size);
6687 		return (e.error);
6688 	}
6689 	need_end_op = TRUE;
6690 
6691 
6692 	/* 0: putfh directory */
6693 	argop[0].argop = OP_CPUTFH;
6694 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6695 
6696 	/* 1/2: Create object */
6697 	argop[idx_create].argop = OP_CCREATE;
6698 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6699 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6700 	if (type == NF4LNK) {
6701 		/*
6702 		 * symlink, treat name as data
6703 		 */
6704 		ASSERT(data != NULL);
6705 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6706 							(char *)data;
6707 	}
6708 	if (type == NF4BLK || type == NF4CHR) {
6709 		ASSERT(data != NULL);
6710 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6711 							*((specdata4 *)data);
6712 	}
6713 
6714 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6715 
6716 	svp = drp->r_server;
6717 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6718 	supp_attrs = svp->sv_supp_attrs;
6719 	nfs_rw_exit(&svp->sv_lock);
6720 
6721 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6722 		nfs_rw_exit(&drp->r_rwlock);
6723 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6724 		e.error = EINVAL;
6725 		kmem_free(argop, argoplist_size);
6726 		return (e.error);
6727 	}
6728 
6729 	/* 2/3: getfh fh of created object */
6730 	ASSERT(idx_create + 1 == idx_fattr - 1);
6731 	argop[idx_create + 1].argop = OP_GETFH;
6732 
6733 	/* 3/4: getattr of new object */
6734 	argop[idx_fattr].argop = OP_GETATTR;
6735 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6736 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6737 
6738 	if (setgid_flag) {
6739 		vattr_t	_v;
6740 
6741 		argop[4].argop = OP_SAVEFH;
6742 
6743 		argop[5].argop = OP_CPUTFH;
6744 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6745 
6746 		argop[6].argop = OP_GETATTR;
6747 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6748 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6749 
6750 		argop[7].argop = OP_RESTOREFH;
6751 
6752 		/*
6753 		 * nverify
6754 		 *
6755 		 * XXX - Revisit the last argument to nfs4_end_op()
6756 		 *	 once 5020486 is fixed.
6757 		 */
6758 		_v.va_mask = AT_GID;
6759 		_v.va_gid = va->va_gid;
6760 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6761 		    supp_attrs)) {
6762 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6763 			nfs_rw_exit(&drp->r_rwlock);
6764 			nfs4_fattr4_free(crattr);
6765 			kmem_free(argop, argoplist_size);
6766 			return (e.error);
6767 		}
6768 
6769 		/*
6770 		 * setattr
6771 		 *
6772 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
6773 		 * so no need for stateid or flags. Also we specify NULL
6774 		 * rp since we're only interested in setting owner_group
6775 		 * attributes.
6776 		 */
6777 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
6778 		    &e.error, 0);
6779 
6780 		if (e.error) {
6781 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6782 			nfs_rw_exit(&drp->r_rwlock);
6783 			nfs4_fattr4_free(crattr);
6784 			nfs4args_verify_free(&argop[8]);
6785 			kmem_free(argop, argoplist_size);
6786 			return (e.error);
6787 		}
6788 	} else {
6789 		argop[1].argop = OP_SAVEFH;
6790 
6791 		argop[5].argop = OP_RESTOREFH;
6792 
6793 		argop[6].argop = OP_GETATTR;
6794 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6795 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6796 	}
6797 
6798 	dnlc_remove(dvp, nm);
6799 
6800 	doqueue = 1;
6801 	t = gethrtime();
6802 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
6803 
6804 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
6805 	if (e.error) {
6806 		PURGE_ATTRCACHE4(dvp);
6807 		if (!needrecov)
6808 			goto out;
6809 	}
6810 
6811 	if (needrecov) {
6812 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
6813 		    OP_CREATE, NULL) == FALSE) {
6814 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6815 				    needrecov);
6816 			need_end_op = FALSE;
6817 			nfs4_fattr4_free(crattr);
6818 			if (setgid_flag) {
6819 				nfs4args_verify_free(&argop[8]);
6820 				nfs4args_setattr_free(&argop[9]);
6821 			}
6822 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6823 			goto recov_retry;
6824 		}
6825 	}
6826 
6827 	resp = &res;
6828 
6829 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
6830 
6831 		if (res.status == NFS4ERR_BADOWNER)
6832 			nfs4_log_badowner(mi, OP_CREATE);
6833 
6834 		e.error = geterrno4(res.status);
6835 
6836 		/*
6837 		 * This check is left over from when create was implemented
6838 		 * using a setattr op (instead of createattrs).  If the
6839 		 * putfh/create/getfh failed, the error was returned.  If
6840 		 * setattr/getattr failed, we keep going.
6841 		 *
6842 		 * It might be better to get rid of the GETFH also, and just
6843 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
6844 		 * Then if any of the operations failed, we could return the
6845 		 * error now, and remove much of the error code below.
6846 		 */
6847 		if (res.array_len <= idx_fattr) {
6848 			/*
6849 			 * Either Putfh, Create or Getfh failed.
6850 			 */
6851 			PURGE_ATTRCACHE4(dvp);
6852 			/*
6853 			 * nfs4_purge_stale_fh() may generate otw calls through
6854 			 * nfs4_invalidate_pages. Hence the need to call
6855 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
6856 			 */
6857 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6858 			    needrecov);
6859 			need_end_op = FALSE;
6860 			nfs4_purge_stale_fh(e.error, dvp, cr);
6861 			goto out;
6862 		}
6863 	}
6864 
6865 	resop = &res.array[idx_create];	/* create res */
6866 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
6867 
6868 	resop = &res.array[idx_create + 1]; /* getfh res */
6869 	gf_res = &resop->nfs_resop4_u.opgetfh;
6870 
6871 	sfhp = sfh4_get(&gf_res->object, mi);
6872 	if (e.error) {
6873 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
6874 		    fn_get(VTOSV(dvp)->sv_name, nm));
6875 		if (vp->v_type == VNON) {
6876 			vattr.va_mask = AT_TYPE;
6877 			/*
6878 			 * Need to call nfs4_end_op before nfs4getattr to avoid
6879 			 * potential nfs4_start_op deadlock. See RFE 4777612.
6880 			 */
6881 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6882 				needrecov);
6883 			need_end_op = FALSE;
6884 			e.error = nfs4getattr(vp, &vattr, cr);
6885 			if (e.error) {
6886 				VN_RELE(vp);
6887 				*vpp = NULL;
6888 				goto out;
6889 			}
6890 			vp->v_type = vattr.va_type;
6891 		}
6892 		e.error = 0;
6893 	} else {
6894 		*vpp = vp = makenfs4node(sfhp,
6895 			&res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
6896 			dvp->v_vfsp, t, cr,
6897 			dvp, fn_get(VTOSV(dvp)->sv_name, nm));
6898 	}
6899 
6900 	/*
6901 	 * If compound succeeded, then update dir attrs
6902 	 */
6903 	if (res.status == NFS4_OK) {
6904 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
6905 		dinfo.di_cred = cr;
6906 		dinfo.di_time_call = t;
6907 		dinfop = &dinfo;
6908 	} else
6909 		dinfop = NULL;
6910 
6911 	/* Update directory cache attribute, readdir and dnlc caches */
6912 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
6913 
6914 out:
6915 	if (sfhp != NULL)
6916 		sfh4_rele(&sfhp);
6917 	nfs_rw_exit(&drp->r_rwlock);
6918 	nfs4_fattr4_free(crattr);
6919 	if (setgid_flag) {
6920 		nfs4args_verify_free(&argop[8]);
6921 		nfs4args_setattr_free(&argop[9]);
6922 	}
6923 	if (resp)
6924 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
6925 	if (need_end_op)
6926 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6927 
6928 	kmem_free(argop, argoplist_size);
6929 	return (e.error);
6930 }
6931 
6932 /* ARGSUSED */
6933 static int
6934 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6935 	int mode, vnode_t **vpp, cred_t *cr)
6936 {
6937 	int error;
6938 	vnode_t *vp;
6939 	nfs_ftype4 type;
6940 	specdata4 spec, *specp = NULL;
6941 
6942 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6943 
6944 	switch (va->va_type) {
6945 	case VCHR:
6946 	case VBLK:
6947 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
6948 		spec.specdata1 = getmajor(va->va_rdev);
6949 		spec.specdata2 = getminor(va->va_rdev);
6950 		specp = &spec;
6951 		break;
6952 
6953 	case VFIFO:
6954 		type = NF4FIFO;
6955 		break;
6956 	case VSOCK:
6957 		type = NF4SOCK;
6958 		break;
6959 
6960 	default:
6961 		return (EINVAL);
6962 	}
6963 
6964 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
6965 	if (error) {
6966 		return (error);
6967 	}
6968 
6969 	/*
6970 	 * This might not be needed any more; special case to deal
6971 	 * with problematic v2/v3 servers.  Since create was unable
6972 	 * to set group correctly, not sure what hope setattr has.
6973 	 */
6974 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
6975 		va->va_mask = AT_GID;
6976 		(void) nfs4setattr(vp, va, 0, cr, NULL);
6977 	}
6978 
6979 	/*
6980 	 * If vnode is a device create special vnode
6981 	 */
6982 	if (ISVDEV(vp->v_type)) {
6983 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6984 		VN_RELE(vp);
6985 	} else {
6986 		*vpp = vp;
6987 	}
6988 	return (error);
6989 }
6990 
6991 /*
6992  * Remove requires that the current fh be the target directory.
6993  * After the operation, the current fh is unchanged.
6994  * The compound op structure is:
6995  *      PUTFH(targetdir), REMOVE
6996  *
6997  * Weirdness: if the vnode to be removed is open
6998  * we rename it instead of removing it and nfs_inactive
6999  * will remove the new name.
7000  */
7001 static int
7002 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr)
7003 {
7004 	COMPOUND4args_clnt args;
7005 	COMPOUND4res_clnt res, *resp = NULL;
7006 	REMOVE4res *rm_res;
7007 	nfs_argop4 argop[3];
7008 	nfs_resop4 *resop;
7009 	vnode_t *vp;
7010 	char *tmpname;
7011 	int doqueue;
7012 	mntinfo4_t *mi;
7013 	rnode4_t *rp;
7014 	rnode4_t *drp;
7015 	int needrecov = 0;
7016 	nfs4_recov_state_t recov_state;
7017 	int isopen;
7018 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7019 	dirattr_info_t dinfo;
7020 
7021 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7022 		return (EPERM);
7023 	drp = VTOR4(dvp);
7024 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7025 		return (EINTR);
7026 
7027 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7028 	if (e.error) {
7029 		nfs_rw_exit(&drp->r_rwlock);
7030 		return (e.error);
7031 	}
7032 
7033 	if (vp->v_type == VDIR) {
7034 		VN_RELE(vp);
7035 		nfs_rw_exit(&drp->r_rwlock);
7036 		return (EISDIR);
7037 	}
7038 
7039 	/*
7040 	 * First just remove the entry from the name cache, as it
7041 	 * is most likely the only entry for this vp.
7042 	 */
7043 	dnlc_remove(dvp, nm);
7044 
7045 	rp = VTOR4(vp);
7046 
7047 	/*
7048 	 * For regular file types, check to see if the file is open by looking
7049 	 * at the open streams.
7050 	 * For all other types, check the reference count on the vnode.  Since
7051 	 * they are not opened OTW they never have an open stream.
7052 	 *
7053 	 * If the file is open, rename it to .nfsXXXX.
7054 	 */
7055 	if (vp->v_type != VREG) {
7056 		/*
7057 		 * If the file has a v_count > 1 then there may be more than one
7058 		 * entry in the name cache due multiple links or an open file,
7059 		 * but we don't have the real reference count so flush all
7060 		 * possible entries.
7061 		 */
7062 		if (vp->v_count > 1)
7063 			dnlc_purge_vp(vp);
7064 
7065 		/*
7066 		 * Now we have the real reference count.
7067 		 */
7068 		isopen = vp->v_count > 1;
7069 	} else {
7070 		mutex_enter(&rp->r_os_lock);
7071 		isopen = list_head(&rp->r_open_streams) != NULL;
7072 		mutex_exit(&rp->r_os_lock);
7073 	}
7074 
7075 	mutex_enter(&rp->r_statelock);
7076 	if (isopen &&
7077 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7078 		mutex_exit(&rp->r_statelock);
7079 		tmpname = newname();
7080 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr);
7081 		if (e.error)
7082 			kmem_free(tmpname, MAXNAMELEN);
7083 		else {
7084 			mutex_enter(&rp->r_statelock);
7085 			if (rp->r_unldvp == NULL) {
7086 				VN_HOLD(dvp);
7087 				rp->r_unldvp = dvp;
7088 				if (rp->r_unlcred != NULL)
7089 					crfree(rp->r_unlcred);
7090 				crhold(cr);
7091 				rp->r_unlcred = cr;
7092 				rp->r_unlname = tmpname;
7093 			} else {
7094 				kmem_free(rp->r_unlname, MAXNAMELEN);
7095 				rp->r_unlname = tmpname;
7096 			}
7097 			mutex_exit(&rp->r_statelock);
7098 		}
7099 		VN_RELE(vp);
7100 		nfs_rw_exit(&drp->r_rwlock);
7101 		return (e.error);
7102 	}
7103 	/*
7104 	 * Actually remove the file/dir
7105 	 */
7106 	mutex_exit(&rp->r_statelock);
7107 
7108 	/*
7109 	 * We need to flush any dirty pages which happen to
7110 	 * be hanging around before removing the file.
7111 	 * This shouldn't happen very often since in NFSv4
7112 	 * we should be close to open consistent.
7113 	 */
7114 	if (nfs4_has_pages(vp) &&
7115 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7116 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr);
7117 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7118 			mutex_enter(&rp->r_statelock);
7119 			if (!rp->r_error)
7120 				rp->r_error = e.error;
7121 			mutex_exit(&rp->r_statelock);
7122 		}
7123 	}
7124 
7125 	mi = VTOMI4(dvp);
7126 
7127 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7128 	recov_state.rs_flags = 0;
7129 	recov_state.rs_num_retry_despite_err = 0;
7130 
7131 recov_retry:
7132 	/*
7133 	 * Remove ops: putfh dir; remove
7134 	 */
7135 	args.ctag = TAG_REMOVE;
7136 	args.array_len = 3;
7137 	args.array = argop;
7138 
7139 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7140 	if (e.error) {
7141 		nfs_rw_exit(&drp->r_rwlock);
7142 		VN_RELE(vp);
7143 		return (e.error);
7144 	}
7145 
7146 	/* putfh directory */
7147 	argop[0].argop = OP_CPUTFH;
7148 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7149 
7150 	/* remove */
7151 	argop[1].argop = OP_CREMOVE;
7152 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7153 
7154 	/* getattr dir */
7155 	argop[2].argop = OP_GETATTR;
7156 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7157 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7158 
7159 	doqueue = 1;
7160 	dinfo.di_time_call = gethrtime();
7161 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7162 
7163 	PURGE_ATTRCACHE4(vp);
7164 
7165 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7166 	if (e.error)
7167 		PURGE_ATTRCACHE4(dvp);
7168 
7169 	if (needrecov) {
7170 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7171 		    NULL, NULL, NULL, OP_REMOVE, NULL) == FALSE) {
7172 			if (!e.error)
7173 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7174 								(caddr_t)&res);
7175 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7176 					needrecov);
7177 			goto recov_retry;
7178 		}
7179 	}
7180 
7181 	/*
7182 	 * Matching nfs4_end_op() for start_op() above.
7183 	 * There is a path in the code below which calls
7184 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7185 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7186 	 * here to avoid nfs4_start_op() deadlock.
7187 	 */
7188 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7189 
7190 	if (!e.error) {
7191 		resp = &res;
7192 
7193 		if (res.status) {
7194 			e.error = geterrno4(res.status);
7195 			PURGE_ATTRCACHE4(dvp);
7196 			nfs4_purge_stale_fh(e.error, dvp, cr);
7197 		} else {
7198 			resop = &res.array[1];	/* remove res */
7199 			rm_res = &resop->nfs_resop4_u.opremove;
7200 
7201 			dinfo.di_garp =
7202 				&res.array[2].nfs_resop4_u.opgetattr.ga_res;
7203 			dinfo.di_cred = cr;
7204 
7205 			/* Update directory attr, readdir and dnlc caches */
7206 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7207 				&dinfo);
7208 		}
7209 	}
7210 	nfs_rw_exit(&drp->r_rwlock);
7211 	if (resp)
7212 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7213 
7214 	VN_RELE(vp);
7215 	return (e.error);
7216 }
7217 
7218 /*
7219  * Link requires that the current fh be the target directory and the
7220  * saved fh be the source fh. After the operation, the current fh is unchanged.
7221  * Thus the compound op structure is:
7222  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7223  *	GETATTR(file)
7224  */
7225 static int
7226 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr)
7227 {
7228 	COMPOUND4args_clnt args;
7229 	COMPOUND4res_clnt res, *resp = NULL;
7230 	LINK4res *ln_res;
7231 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7232 	nfs_argop4 *argop;
7233 	nfs_resop4 *resop;
7234 	vnode_t *realvp, *nvp;
7235 	int doqueue;
7236 	mntinfo4_t *mi;
7237 	rnode4_t *tdrp;
7238 	bool_t needrecov = FALSE;
7239 	nfs4_recov_state_t recov_state;
7240 	hrtime_t t;
7241 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7242 	dirattr_info_t dinfo;
7243 
7244 	ASSERT(*tnm != '\0');
7245 	ASSERT(tdvp->v_type == VDIR);
7246 	ASSERT(nfs4_consistent_type(tdvp));
7247 	ASSERT(nfs4_consistent_type(svp));
7248 
7249 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7250 		return (EPERM);
7251 	if (VOP_REALVP(svp, &realvp) == 0) {
7252 		svp = realvp;
7253 		ASSERT(nfs4_consistent_type(svp));
7254 	}
7255 
7256 	tdrp = VTOR4(tdvp);
7257 	mi = VTOMI4(svp);
7258 
7259 	if (!(mi->mi_flags & MI4_LINK)) {
7260 		return (EOPNOTSUPP);
7261 	}
7262 	recov_state.rs_flags = 0;
7263 	recov_state.rs_num_retry_despite_err = 0;
7264 
7265 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7266 		return (EINTR);
7267 
7268 recov_retry:
7269 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7270 
7271 	args.ctag = TAG_LINK;
7272 
7273 	/*
7274 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7275 	 * restorefh; getattr(fl)
7276 	 */
7277 	args.array_len = 7;
7278 	args.array = argop;
7279 
7280 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7281 	if (e.error) {
7282 		kmem_free(argop, argoplist_size);
7283 		nfs_rw_exit(&tdrp->r_rwlock);
7284 		return (e.error);
7285 	}
7286 
7287 	/* 0. putfh file */
7288 	argop[0].argop = OP_CPUTFH;
7289 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7290 
7291 	/* 1. save current fh to free up the space for the dir */
7292 	argop[1].argop = OP_SAVEFH;
7293 
7294 	/* 2. putfh targetdir */
7295 	argop[2].argop = OP_CPUTFH;
7296 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7297 
7298 	/* 3. link: current_fh is targetdir, saved_fh is source */
7299 	argop[3].argop = OP_CLINK;
7300 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7301 
7302 	/* 4. Get attributes of dir */
7303 	argop[4].argop = OP_GETATTR;
7304 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7305 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7306 
7307 	/* 5. If link was successful, restore current vp to file */
7308 	argop[5].argop = OP_RESTOREFH;
7309 
7310 	/* 6. Get attributes of linked object */
7311 	argop[6].argop = OP_GETATTR;
7312 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7313 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7314 
7315 	dnlc_remove(tdvp, tnm);
7316 
7317 	doqueue = 1;
7318 	t = gethrtime();
7319 
7320 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7321 
7322 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7323 	if (e.error != 0 && !needrecov) {
7324 		PURGE_ATTRCACHE4(tdvp);
7325 		PURGE_ATTRCACHE4(svp);
7326 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7327 		goto out;
7328 	}
7329 
7330 	if (needrecov) {
7331 		bool_t abort;
7332 
7333 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7334 			    NULL, NULL, OP_LINK, NULL);
7335 		if (abort == FALSE) {
7336 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7337 				    needrecov);
7338 			kmem_free(argop, argoplist_size);
7339 			if (!e.error)
7340 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7341 								(caddr_t)&res);
7342 			goto recov_retry;
7343 		} else {
7344 			if (e.error != 0) {
7345 				PURGE_ATTRCACHE4(tdvp);
7346 				PURGE_ATTRCACHE4(svp);
7347 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7348 					    &recov_state, needrecov);
7349 				goto out;
7350 			}
7351 			/* fall through for res.status case */
7352 		}
7353 	}
7354 
7355 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7356 
7357 	resp = &res;
7358 	if (res.status) {
7359 		/* If link succeeded, then don't return error */
7360 		e.error = geterrno4(res.status);
7361 		if (res.array_len <= 4) {
7362 			/*
7363 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7364 			 */
7365 			PURGE_ATTRCACHE4(svp);
7366 			PURGE_ATTRCACHE4(tdvp);
7367 			if (e.error == EOPNOTSUPP) {
7368 				mutex_enter(&mi->mi_lock);
7369 				mi->mi_flags &= ~MI4_LINK;
7370 				mutex_exit(&mi->mi_lock);
7371 			}
7372 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7373 			/* XXX-LP */
7374 			if (e.error == EISDIR && crgetuid(cr) != 0)
7375 				e.error = EPERM;
7376 			goto out;
7377 		}
7378 	}
7379 
7380 	/* either no error or one of the postop getattr failed */
7381 
7382 	/*
7383 	 * XXX - if LINK succeeded, but no attrs were returned for link
7384 	 * file, purge its cache.
7385 	 *
7386 	 * XXX Perform a simplified version of wcc checking. Instead of
7387 	 * have another getattr to get pre-op, just purge cache if
7388 	 * any of the ops prior to and including the getattr failed.
7389 	 * If the getattr succeeded then update the attrcache accordingly.
7390 	 */
7391 
7392 	/*
7393 	 * update cache with link file postattrs.
7394 	 * Note: at this point resop points to link res.
7395 	 */
7396 	resop = &res.array[3];	/* link res */
7397 	ln_res = &resop->nfs_resop4_u.oplink;
7398 	if (res.status == NFS4_OK) {
7399 		e.error = nfs4_update_attrcache(res.status,
7400 				&res.array[6].nfs_resop4_u.opgetattr.ga_res,
7401 				t, svp, cr);
7402 	}
7403 
7404 	/*
7405 	 * Call makenfs4node to create the new shadow vp for tnm.
7406 	 * We pass NULL attrs because we just cached attrs for
7407 	 * the src object.  All we're trying to accomplish is to
7408 	 * to create the new shadow vnode.
7409 	 */
7410 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7411 			tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm));
7412 
7413 	/* Update target cache attribute, readdir and dnlc caches */
7414 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7415 	dinfo.di_time_call = t;
7416 	dinfo.di_cred = cr;
7417 
7418 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7419 	ASSERT(nfs4_consistent_type(tdvp));
7420 	ASSERT(nfs4_consistent_type(svp));
7421 	ASSERT(nfs4_consistent_type(nvp));
7422 	VN_RELE(nvp);
7423 
7424 out:
7425 	kmem_free(argop, argoplist_size);
7426 	if (resp)
7427 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7428 
7429 	nfs_rw_exit(&tdrp->r_rwlock);
7430 
7431 	return (e.error);
7432 }
7433 
7434 static int
7435 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr)
7436 {
7437 	vnode_t *realvp;
7438 
7439 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7440 		return (EPERM);
7441 	if (VOP_REALVP(ndvp, &realvp) == 0)
7442 		ndvp = realvp;
7443 
7444 	return (nfs4rename(odvp, onm, ndvp, nnm, cr));
7445 }
7446 
7447 /*
7448  * nfs4rename does the real work of renaming in NFS Version 4.
7449  *
7450  * A file handle is considered volatile for renaming purposes if either
7451  * of the volatile bits are turned on. However, the compound may differ
7452  * based on the likelihood of the filehandle to change during rename.
7453  */
7454 static int
7455 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr)
7456 {
7457 	int error;
7458 	mntinfo4_t *mi;
7459 	vnode_t *nvp;
7460 	vnode_t *ovp = NULL;
7461 	char *tmpname = NULL;
7462 	rnode4_t *rp;
7463 	rnode4_t *odrp;
7464 	rnode4_t *ndrp;
7465 	int did_link = 0;
7466 	int do_link = 1;
7467 	nfsstat4 stat = NFS4_OK;
7468 
7469 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7470 	ASSERT(nfs4_consistent_type(odvp));
7471 	ASSERT(nfs4_consistent_type(ndvp));
7472 
7473 	if (onm[0] == '.' && (onm[1] == '\0' ||
7474 			(onm[1] == '.' && onm[2] == '\0')))
7475 		return (EINVAL);
7476 
7477 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7478 			(nnm[1] == '.' && nnm[2] == '\0')))
7479 		return (EINVAL);
7480 
7481 	odrp = VTOR4(odvp);
7482 	ndrp = VTOR4(ndvp);
7483 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7484 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7485 			return (EINTR);
7486 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7487 			nfs_rw_exit(&odrp->r_rwlock);
7488 			return (EINTR);
7489 		}
7490 	} else {
7491 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7492 			return (EINTR);
7493 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7494 			nfs_rw_exit(&ndrp->r_rwlock);
7495 			return (EINTR);
7496 		}
7497 	}
7498 
7499 	/*
7500 	 * Lookup the target file.  If it exists, it needs to be
7501 	 * checked to see whether it is a mount point and whether
7502 	 * it is active (open).
7503 	 */
7504 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7505 	if (!error) {
7506 		int	isactive;
7507 
7508 		ASSERT(nfs4_consistent_type(nvp));
7509 		/*
7510 		 * If this file has been mounted on, then just
7511 		 * return busy because renaming to it would remove
7512 		 * the mounted file system from the name space.
7513 		 */
7514 		if (vn_ismntpt(nvp)) {
7515 			VN_RELE(nvp);
7516 			nfs_rw_exit(&odrp->r_rwlock);
7517 			nfs_rw_exit(&ndrp->r_rwlock);
7518 			return (EBUSY);
7519 		}
7520 
7521 		/*
7522 		 * First just remove the entry from the name cache, as it
7523 		 * is most likely the only entry for this vp.
7524 		 */
7525 		dnlc_remove(ndvp, nnm);
7526 
7527 		rp = VTOR4(nvp);
7528 
7529 		if (nvp->v_type != VREG) {
7530 			/*
7531 			 * Purge the name cache of all references to this vnode
7532 			 * so that we can check the reference count to infer
7533 			 * whether it is active or not.
7534 			 */
7535 			if (nvp->v_count > 1)
7536 				dnlc_purge_vp(nvp);
7537 
7538 			isactive = nvp->v_count > 1;
7539 		} else {
7540 			mutex_enter(&rp->r_os_lock);
7541 			isactive = list_head(&rp->r_open_streams) != NULL;
7542 			mutex_exit(&rp->r_os_lock);
7543 		}
7544 
7545 		/*
7546 		 * If the vnode is active and is not a directory,
7547 		 * arrange to rename it to a
7548 		 * temporary file so that it will continue to be
7549 		 * accessible.  This implements the "unlink-open-file"
7550 		 * semantics for the target of a rename operation.
7551 		 * Before doing this though, make sure that the
7552 		 * source and target files are not already the same.
7553 		 */
7554 		if (isactive && nvp->v_type != VDIR) {
7555 			/*
7556 			 * Lookup the source name.
7557 			 */
7558 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7559 
7560 			/*
7561 			 * The source name *should* already exist.
7562 			 */
7563 			if (error) {
7564 				VN_RELE(nvp);
7565 				nfs_rw_exit(&odrp->r_rwlock);
7566 				nfs_rw_exit(&ndrp->r_rwlock);
7567 				return (error);
7568 			}
7569 
7570 			ASSERT(nfs4_consistent_type(ovp));
7571 
7572 			/*
7573 			 * Compare the two vnodes.  If they are the same,
7574 			 * just release all held vnodes and return success.
7575 			 */
7576 			if (VN_CMP(ovp, nvp)) {
7577 				VN_RELE(ovp);
7578 				VN_RELE(nvp);
7579 				nfs_rw_exit(&odrp->r_rwlock);
7580 				nfs_rw_exit(&ndrp->r_rwlock);
7581 				return (0);
7582 			}
7583 
7584 			/*
7585 			 * Can't mix and match directories and non-
7586 			 * directories in rename operations.  We already
7587 			 * know that the target is not a directory.  If
7588 			 * the source is a directory, return an error.
7589 			 */
7590 			if (ovp->v_type == VDIR) {
7591 				VN_RELE(ovp);
7592 				VN_RELE(nvp);
7593 				nfs_rw_exit(&odrp->r_rwlock);
7594 				nfs_rw_exit(&ndrp->r_rwlock);
7595 				return (ENOTDIR);
7596 			}
7597 link_call:
7598 			/*
7599 			 * The target file exists, is not the same as
7600 			 * the source file, and is active.  We first
7601 			 * try to Link it to a temporary filename to
7602 			 * avoid having the server removing the file
7603 			 * completely (which could cause data loss to
7604 			 * the user's POV in the event the Rename fails
7605 			 * -- see bug 1165874).
7606 			 */
7607 			/*
7608 			 * The do_link and did_link booleans are
7609 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7610 			 * returned for the Rename.  Some servers can
7611 			 * not Rename over an Open file, so they return
7612 			 * this error.  The client needs to Remove the
7613 			 * newly created Link and do two Renames, just
7614 			 * as if the server didn't support LINK.
7615 			 */
7616 			tmpname = newname();
7617 			error = 0;
7618 
7619 			if (do_link) {
7620 				error = nfs4_link(ndvp, nvp, tmpname, cr);
7621 			}
7622 			if (error == EOPNOTSUPP || !do_link) {
7623 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7624 				    cr);
7625 				did_link = 0;
7626 			} else {
7627 				did_link = 1;
7628 			}
7629 			if (error) {
7630 				kmem_free(tmpname, MAXNAMELEN);
7631 				VN_RELE(ovp);
7632 				VN_RELE(nvp);
7633 				nfs_rw_exit(&odrp->r_rwlock);
7634 				nfs_rw_exit(&ndrp->r_rwlock);
7635 				return (error);
7636 			}
7637 
7638 			mutex_enter(&rp->r_statelock);
7639 			if (rp->r_unldvp == NULL) {
7640 				VN_HOLD(ndvp);
7641 				rp->r_unldvp = ndvp;
7642 				if (rp->r_unlcred != NULL)
7643 					crfree(rp->r_unlcred);
7644 				crhold(cr);
7645 				rp->r_unlcred = cr;
7646 				rp->r_unlname = tmpname;
7647 			} else {
7648 				if (rp->r_unlname)
7649 					kmem_free(rp->r_unlname, MAXNAMELEN);
7650 				rp->r_unlname = tmpname;
7651 			}
7652 			mutex_exit(&rp->r_statelock);
7653 		}
7654 
7655 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7656 
7657 		ASSERT(nfs4_consistent_type(nvp));
7658 		VN_RELE(nvp);
7659 	}
7660 
7661 	if (ovp == NULL) {
7662 		/*
7663 		 * When renaming directories to be a subdirectory of a
7664 		 * different parent, the dnlc entry for ".." will no
7665 		 * longer be valid, so it must be removed.
7666 		 *
7667 		 * We do a lookup here to determine whether we are renaming
7668 		 * a directory and we need to check if we are renaming
7669 		 * an unlinked file.  This might have already been done
7670 		 * in previous code, so we check ovp == NULL to avoid
7671 		 * doing it twice.
7672 		 */
7673 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7674 		/*
7675 		 * The source name *should* already exist.
7676 		 */
7677 		if (error) {
7678 			nfs_rw_exit(&odrp->r_rwlock);
7679 			nfs_rw_exit(&ndrp->r_rwlock);
7680 			return (error);
7681 		}
7682 		ASSERT(ovp != NULL);
7683 		ASSERT(nfs4_consistent_type(ovp));
7684 	}
7685 
7686 	/*
7687 	 * Is the object being renamed a dir, and if so, is
7688 	 * it being renamed to a child of itself?  The underlying
7689 	 * fs should ultimately return EINVAL for this case;
7690 	 * however, buggy beta non-Solaris NFSv4 servers at
7691 	 * interop testing events have allowed this behavior,
7692 	 * and it caused our client to panic due to a recursive
7693 	 * mutex_enter in fn_move.
7694 	 *
7695 	 * The tedious locking in fn_move could be changed to
7696 	 * deal with this case, and the client could avoid the
7697 	 * panic; however, the client would just confuse itself
7698 	 * later and misbehave.  A better way to handle the broken
7699 	 * server is to detect this condition and return EINVAL
7700 	 * without ever sending the the bogus rename to the server.
7701 	 * We know the rename is invalid -- just fail it now.
7702 	 */
7703 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7704 		VN_RELE(ovp);
7705 		nfs_rw_exit(&odrp->r_rwlock);
7706 		nfs_rw_exit(&ndrp->r_rwlock);
7707 		return (EINVAL);
7708 	}
7709 
7710 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7711 
7712 	/*
7713 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7714 	 * possible for the filehandle to change due to the rename.
7715 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7716 	 * the fh will not change because of the rename, but we still need
7717 	 * to update its rnode entry with the new name for
7718 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7719 	 * has no effect on these for now, but for future improvements,
7720 	 * we might want to use it too to simplify handling of files
7721 	 * that are open with that flag on. (XXX)
7722 	 */
7723 	mi = VTOMI4(odvp);
7724 	if (NFS4_VOLATILE_FH(mi)) {
7725 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7726 				&stat);
7727 	} else {
7728 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7729 				&stat);
7730 	}
7731 	ASSERT(nfs4_consistent_type(odvp));
7732 	ASSERT(nfs4_consistent_type(ndvp));
7733 	ASSERT(nfs4_consistent_type(ovp));
7734 
7735 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
7736 		do_link = 0;
7737 		/*
7738 		 * Before the 'link_call' code, we did a nfs4_lookup
7739 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
7740 		 * call we call VN_RELE to match that hold.  We need
7741 		 * to place an additional VN_HOLD here since we will
7742 		 * be hitting that VN_RELE again.
7743 		 */
7744 		VN_HOLD(nvp);
7745 
7746 		(void) nfs4_remove(ndvp, tmpname, cr);
7747 
7748 		/* Undo the unlinked file naming stuff we just did */
7749 		mutex_enter(&rp->r_statelock);
7750 		if (rp->r_unldvp) {
7751 			VN_RELE(ndvp);
7752 			rp->r_unldvp = NULL;
7753 			if (rp->r_unlcred != NULL)
7754 				crfree(rp->r_unlcred);
7755 			rp->r_unlcred = NULL;
7756 			/* rp->r_unlanme points to tmpname */
7757 			if (rp->r_unlname)
7758 				kmem_free(rp->r_unlname, MAXNAMELEN);
7759 			rp->r_unlname = NULL;
7760 		}
7761 		mutex_exit(&rp->r_statelock);
7762 
7763 		goto link_call;
7764 	}
7765 
7766 	if (error) {
7767 		VN_RELE(ovp);
7768 		nfs_rw_exit(&odrp->r_rwlock);
7769 		nfs_rw_exit(&ndrp->r_rwlock);
7770 		return (error);
7771 	}
7772 
7773 	/*
7774 	 * when renaming directories to be a subdirectory of a
7775 	 * different parent, the dnlc entry for ".." will no
7776 	 * longer be valid, so it must be removed
7777 	 */
7778 	rp = VTOR4(ovp);
7779 	if (ndvp != odvp) {
7780 		if (ovp->v_type == VDIR) {
7781 			dnlc_remove(ovp, "..");
7782 			if (rp->r_dir != NULL)
7783 				nfs4_purge_rddir_cache(ovp);
7784 		}
7785 	}
7786 
7787 	/*
7788 	 * If we are renaming the unlinked file, update the
7789 	 * r_unldvp and r_unlname as needed.
7790 	 */
7791 	mutex_enter(&rp->r_statelock);
7792 	if (rp->r_unldvp != NULL) {
7793 		if (strcmp(rp->r_unlname, onm) == 0) {
7794 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
7795 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
7796 			if (ndvp != rp->r_unldvp) {
7797 				VN_RELE(rp->r_unldvp);
7798 				rp->r_unldvp = ndvp;
7799 				VN_HOLD(ndvp);
7800 			}
7801 		}
7802 	}
7803 	mutex_exit(&rp->r_statelock);
7804 
7805 	VN_RELE(ovp);
7806 
7807 	nfs_rw_exit(&odrp->r_rwlock);
7808 	nfs_rw_exit(&ndrp->r_rwlock);
7809 
7810 	return (error);
7811 }
7812 
7813 /*
7814  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
7815  * when it is known that the filehandle is persistent through rename.
7816  *
7817  * Rename requires that the current fh be the target directory and the
7818  * saved fh be the source directory. After the operation, the current fh
7819  * is unchanged.
7820  * The compound op structure for persistent fh rename is:
7821  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
7822  * Rather than bother with the directory postop args, we'll simply
7823  * update that a change occured in the cache, so no post-op getattrs.
7824  */
7825 static int
7826 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
7827 	vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
7828 {
7829 	COMPOUND4args_clnt args;
7830 	COMPOUND4res_clnt res, *resp = NULL;
7831 	nfs_argop4 *argop;
7832 	nfs_resop4 *resop;
7833 	int doqueue, argoplist_size;
7834 	mntinfo4_t *mi;
7835 	rnode4_t *odrp = VTOR4(odvp);
7836 	rnode4_t *ndrp = VTOR4(ndvp);
7837 	RENAME4res *rn_res;
7838 	bool_t needrecov;
7839 	nfs4_recov_state_t recov_state;
7840 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7841 	dirattr_info_t dinfo, *dinfop;
7842 
7843 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7844 
7845 	recov_state.rs_flags = 0;
7846 	recov_state.rs_num_retry_despite_err = 0;
7847 
7848 	/*
7849 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
7850 	 *
7851 	 * If source/target are different dirs, then append putfh(src); getattr
7852 	 */
7853 	args.array_len = (odvp == ndvp) ? 5 : 7;
7854 	argoplist_size = args.array_len * sizeof (nfs_argop4);
7855 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
7856 
7857 recov_retry:
7858 	*statp = NFS4_OK;
7859 
7860 	/* No need to Lookup the file, persistent fh */
7861 	args.ctag = TAG_RENAME;
7862 
7863 	mi = VTOMI4(odvp);
7864 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
7865 	if (e.error) {
7866 		kmem_free(argop, argoplist_size);
7867 		return (e.error);
7868 	}
7869 
7870 	/* 0: putfh source directory */
7871 	argop[0].argop = OP_CPUTFH;
7872 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
7873 
7874 	/* 1: Save source fh to free up current for target */
7875 	argop[1].argop = OP_SAVEFH;
7876 
7877 	/* 2: putfh targetdir */
7878 	argop[2].argop = OP_CPUTFH;
7879 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
7880 
7881 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
7882 	argop[3].argop = OP_CRENAME;
7883 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
7884 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
7885 
7886 	/* 4: getattr (targetdir) */
7887 	argop[4].argop = OP_GETATTR;
7888 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7889 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7890 
7891 	if (ndvp != odvp) {
7892 
7893 		/* 5: putfh (sourcedir) */
7894 		argop[5].argop = OP_CPUTFH;
7895 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
7896 
7897 		/* 6: getattr (sourcedir) */
7898 		argop[6].argop = OP_GETATTR;
7899 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7900 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
7901 	}
7902 
7903 	dnlc_remove(odvp, onm);
7904 	dnlc_remove(ndvp, nnm);
7905 
7906 	doqueue = 1;
7907 	dinfo.di_time_call = gethrtime();
7908 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7909 
7910 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7911 	if (e.error) {
7912 		PURGE_ATTRCACHE4(odvp);
7913 		PURGE_ATTRCACHE4(ndvp);
7914 	} else {
7915 		*statp = res.status;
7916 	}
7917 
7918 	if (needrecov) {
7919 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
7920 		    OP_RENAME, NULL) == FALSE) {
7921 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
7922 			if (!e.error)
7923 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7924 								(caddr_t)&res);
7925 			goto recov_retry;
7926 		}
7927 	}
7928 
7929 	if (!e.error) {
7930 		resp = &res;
7931 		/*
7932 		 * as long as OP_RENAME
7933 		 */
7934 		if (res.status != NFS4_OK && res.array_len <= 4) {
7935 			e.error = geterrno4(res.status);
7936 			PURGE_ATTRCACHE4(odvp);
7937 			PURGE_ATTRCACHE4(ndvp);
7938 			/*
7939 			 * System V defines rename to return EEXIST, not
7940 			 * ENOTEMPTY if the target directory is not empty.
7941 			 * Over the wire, the error is NFSERR_ENOTEMPTY
7942 			 * which geterrno4 maps to ENOTEMPTY.
7943 			 */
7944 			if (e.error == ENOTEMPTY)
7945 				e.error = EEXIST;
7946 		} else {
7947 
7948 			resop = &res.array[3];	/* rename res */
7949 			rn_res = &resop->nfs_resop4_u.oprename;
7950 
7951 			if (res.status == NFS4_OK) {
7952 				/*
7953 				 * Update target attribute, readdir and dnlc
7954 				 * caches.
7955 				 */
7956 				dinfo.di_garp =
7957 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7958 				dinfo.di_cred = cr;
7959 				dinfop = &dinfo;
7960 			} else
7961 				dinfop = NULL;
7962 
7963 			nfs4_update_dircaches(&rn_res->target_cinfo,
7964 						ndvp, NULL, NULL, dinfop);
7965 
7966 			/*
7967 			 * Update source attribute, readdir and dnlc caches
7968 			 *
7969 			 */
7970 			if (ndvp != odvp) {
7971 				if (dinfop)
7972 					dinfo.di_garp =
7973 					    &(res.array[6].nfs_resop4_u.
7974 					    opgetattr.ga_res);
7975 
7976 				nfs4_update_dircaches(&rn_res->source_cinfo,
7977 						odvp, NULL, NULL, dinfop);
7978 			}
7979 
7980 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
7981 									nnm);
7982 		}
7983 	}
7984 
7985 	if (resp)
7986 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7987 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
7988 	kmem_free(argop, argoplist_size);
7989 
7990 	return (e.error);
7991 }
7992 
7993 /*
7994  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
7995  * it is possible for the filehandle to change due to the rename.
7996  *
7997  * The compound req in this case includes a post-rename lookup and getattr
7998  * to ensure that we have the correct fh and attributes for the object.
7999  *
8000  * Rename requires that the current fh be the target directory and the
8001  * saved fh be the source directory. After the operation, the current fh
8002  * is unchanged.
8003  *
8004  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8005  * update the filehandle for the renamed object.  We also get the old
8006  * filehandle for historical reasons; this should be taken out sometime.
8007  * This results in a rather cumbersome compound...
8008  *
8009  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8010  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8011  *
8012  */
8013 static int
8014 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8015 	vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8016 {
8017 	COMPOUND4args_clnt args;
8018 	COMPOUND4res_clnt res, *resp = NULL;
8019 	int argoplist_size;
8020 	nfs_argop4 *argop;
8021 	nfs_resop4 *resop;
8022 	int doqueue;
8023 	mntinfo4_t *mi;
8024 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8025 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8026 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8027 	RENAME4res *rn_res;
8028 	GETFH4res *ngf_res;
8029 	bool_t needrecov;
8030 	nfs4_recov_state_t recov_state;
8031 	hrtime_t t;
8032 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8033 	dirattr_info_t dinfo, *dinfop = &dinfo;
8034 
8035 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8036 
8037 	recov_state.rs_flags = 0;
8038 	recov_state.rs_num_retry_despite_err = 0;
8039 
8040 recov_retry:
8041 	*statp = NFS4_OK;
8042 
8043 	/*
8044 	 * There is a window between the RPC and updating the path and
8045 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8046 	 * code, so that it doesn't try to use the old path during that
8047 	 * window.
8048 	 */
8049 	mutex_enter(&orp->r_statelock);
8050 	while (orp->r_flags & R4RECEXPFH) {
8051 		klwp_t *lwp = ttolwp(curthread);
8052 
8053 		if (lwp != NULL)
8054 			lwp->lwp_nostop++;
8055 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8056 			mutex_exit(&orp->r_statelock);
8057 			if (lwp != NULL)
8058 				lwp->lwp_nostop--;
8059 			return (EINTR);
8060 		}
8061 		if (lwp != NULL)
8062 			lwp->lwp_nostop--;
8063 	}
8064 	orp->r_flags |= R4RECEXPFH;
8065 	mutex_exit(&orp->r_statelock);
8066 
8067 	mi = VTOMI4(odvp);
8068 
8069 	args.ctag = TAG_RENAME_VFH;
8070 	args.array_len = (odvp == ndvp) ? 10 : 12;
8071 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8072 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8073 
8074 	/*
8075 	 * Rename ops:
8076 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8077 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8078 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8079 	 *
8080 	 *    if (odvp != ndvp)
8081 	 *	add putfh(sourcedir), getattr(sourcedir) }
8082 	 */
8083 	args.array = argop;
8084 
8085 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8086 			    &recov_state, NULL);
8087 	if (e.error) {
8088 		kmem_free(argop, argoplist_size);
8089 		mutex_enter(&orp->r_statelock);
8090 		orp->r_flags &= ~R4RECEXPFH;
8091 		cv_broadcast(&orp->r_cv);
8092 		mutex_exit(&orp->r_statelock);
8093 		return (e.error);
8094 	}
8095 
8096 	/* 0: putfh source directory */
8097 	argop[0].argop = OP_CPUTFH;
8098 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8099 
8100 	/* 1: Save source fh to free up current for target */
8101 	argop[1].argop = OP_SAVEFH;
8102 
8103 	/* 2: Lookup pre-rename fh of renamed object */
8104 	argop[2].argop = OP_CLOOKUP;
8105 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8106 
8107 	/* 3: getfh fh of renamed object (before rename) */
8108 	argop[3].argop = OP_GETFH;
8109 
8110 	/* 4: putfh targetdir */
8111 	argop[4].argop = OP_CPUTFH;
8112 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8113 
8114 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8115 	argop[5].argop = OP_CRENAME;
8116 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8117 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8118 
8119 	/* 6: getattr of target dir (post op attrs) */
8120 	argop[6].argop = OP_GETATTR;
8121 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8122 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8123 
8124 	/* 7: Lookup post-rename fh of renamed object */
8125 	argop[7].argop = OP_CLOOKUP;
8126 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8127 
8128 	/* 8: getfh fh of renamed object (after rename) */
8129 	argop[8].argop = OP_GETFH;
8130 
8131 	/* 9: getattr of renamed object */
8132 	argop[9].argop = OP_GETATTR;
8133 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8134 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8135 
8136 	/*
8137 	 * If source/target dirs are different, then get new post-op
8138 	 * attrs for source dir also.
8139 	 */
8140 	if (ndvp != odvp) {
8141 		/* 10: putfh (sourcedir) */
8142 		argop[10].argop = OP_CPUTFH;
8143 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8144 
8145 		/* 11: getattr (sourcedir) */
8146 		argop[11].argop = OP_GETATTR;
8147 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8148 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8149 	}
8150 
8151 	dnlc_remove(odvp, onm);
8152 	dnlc_remove(ndvp, nnm);
8153 
8154 	doqueue = 1;
8155 	t = gethrtime();
8156 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8157 
8158 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8159 	if (e.error) {
8160 		PURGE_ATTRCACHE4(odvp);
8161 		PURGE_ATTRCACHE4(ndvp);
8162 		if (!needrecov) {
8163 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8164 					&recov_state, needrecov);
8165 			goto out;
8166 		}
8167 	} else {
8168 		*statp = res.status;
8169 	}
8170 
8171 	if (needrecov) {
8172 		bool_t abort;
8173 
8174 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8175 			    OP_RENAME, NULL);
8176 		if (abort == FALSE) {
8177 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8178 					&recov_state, needrecov);
8179 			kmem_free(argop, argoplist_size);
8180 			if (!e.error)
8181 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8182 								(caddr_t)&res);
8183 			mutex_enter(&orp->r_statelock);
8184 			orp->r_flags &= ~R4RECEXPFH;
8185 			cv_broadcast(&orp->r_cv);
8186 			mutex_exit(&orp->r_statelock);
8187 			goto recov_retry;
8188 		} else {
8189 			if (e.error != 0) {
8190 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8191 						&recov_state, needrecov);
8192 				goto out;
8193 			}
8194 			/* fall through for res.status case */
8195 		}
8196 	}
8197 
8198 	resp = &res;
8199 	/*
8200 	 * If OP_RENAME (or any prev op) failed, then return an error.
8201 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8202 	 */
8203 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8204 		/*
8205 		 * Error in an op other than last Getattr
8206 		 */
8207 		e.error = geterrno4(res.status);
8208 		PURGE_ATTRCACHE4(odvp);
8209 		PURGE_ATTRCACHE4(ndvp);
8210 		/*
8211 		 * System V defines rename to return EEXIST, not
8212 		 * ENOTEMPTY if the target directory is not empty.
8213 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8214 		 * which geterrno4 maps to ENOTEMPTY.
8215 		 */
8216 		if (e.error == ENOTEMPTY)
8217 			e.error = EEXIST;
8218 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8219 				needrecov);
8220 		goto out;
8221 	}
8222 
8223 	/* rename results */
8224 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8225 
8226 	if (res.status == NFS4_OK) {
8227 		/* Update target attribute, readdir and dnlc caches */
8228 		dinfo.di_garp =
8229 			&res.array[6].nfs_resop4_u.opgetattr.ga_res;
8230 		dinfo.di_cred = cr;
8231 		dinfo.di_time_call = t;
8232 	} else
8233 		dinfop = NULL;
8234 
8235 	/* Update source cache attribute, readdir and dnlc caches */
8236 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8237 
8238 	/* Update source cache attribute, readdir and dnlc caches */
8239 	if (ndvp != odvp) {
8240 
8241 		/*
8242 		 * If dinfop is non-NULL, then compound succeded, so
8243 		 * set di_garp to attrs for source dir.  dinfop is only
8244 		 * set to NULL when compound fails.
8245 		 */
8246 		if (dinfop)
8247 			dinfo.di_garp =
8248 				&res.array[11].nfs_resop4_u.opgetattr.ga_res;
8249 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8250 				dinfop);
8251 	}
8252 
8253 	/*
8254 	 * Update the rnode with the new component name and args,
8255 	 * and if the file handle changed, also update it with the new fh.
8256 	 * This is only necessary if the target object has an rnode
8257 	 * entry and there is no need to create one for it.
8258 	 */
8259 	resop = &res.array[8];	/* getfh new res */
8260 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8261 
8262 	/*
8263 	 * Update the path and filehandle for the renamed object.
8264 	 */
8265 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8266 
8267 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8268 
8269 	if (res.status == NFS4_OK) {
8270 		resop++;	/* getattr res */
8271 		e.error = nfs4_update_attrcache(res.status,
8272 				&resop->nfs_resop4_u.opgetattr.ga_res,
8273 				t, ovp, cr);
8274 	}
8275 
8276 out:
8277 	kmem_free(argop, argoplist_size);
8278 	if (resp)
8279 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8280 	mutex_enter(&orp->r_statelock);
8281 	orp->r_flags &= ~R4RECEXPFH;
8282 	cv_broadcast(&orp->r_cv);
8283 	mutex_exit(&orp->r_statelock);
8284 
8285 	return (e.error);
8286 }
8287 
8288 static int
8289 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr)
8290 {
8291 	int error;
8292 	vnode_t *vp;
8293 
8294 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8295 		return (EPERM);
8296 	/*
8297 	 * As ".." has special meaning and rather than send a mkdir
8298 	 * over the wire to just let the server freak out, we just
8299 	 * short circuit it here and return EEXIST
8300 	 */
8301 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8302 		return (EEXIST);
8303 
8304 	/*
8305 	 * Decision to get the right gid and setgid bit of the
8306 	 * new directory is now made in call_nfs4_create_req.
8307 	 */
8308 	va->va_mask |= AT_MODE;
8309 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8310 	if (error)
8311 		return (error);
8312 
8313 	*vpp = vp;
8314 	return (0);
8315 }
8316 
8317 
8318 /*
8319  * rmdir is using the same remove v4 op as does remove.
8320  * Remove requires that the current fh be the target directory.
8321  * After the operation, the current fh is unchanged.
8322  * The compound op structure is:
8323  *      PUTFH(targetdir), REMOVE
8324  */
8325 static int
8326 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr)
8327 {
8328 	int need_end_op = FALSE;
8329 	COMPOUND4args_clnt args;
8330 	COMPOUND4res_clnt res, *resp = NULL;
8331 	REMOVE4res *rm_res;
8332 	nfs_argop4 argop[3];
8333 	nfs_resop4 *resop;
8334 	vnode_t *vp;
8335 	int doqueue;
8336 	mntinfo4_t *mi;
8337 	rnode4_t *drp;
8338 	bool_t needrecov = FALSE;
8339 	nfs4_recov_state_t recov_state;
8340 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8341 	dirattr_info_t dinfo, *dinfop;
8342 
8343 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8344 		return (EPERM);
8345 	/*
8346 	 * As ".." has special meaning and rather than send a rmdir
8347 	 * over the wire to just let the server freak out, we just
8348 	 * short circuit it here and return EEXIST
8349 	 */
8350 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8351 		return (EEXIST);
8352 
8353 	drp = VTOR4(dvp);
8354 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8355 		return (EINTR);
8356 
8357 	/*
8358 	 * Attempt to prevent a rmdir(".") from succeeding.
8359 	 */
8360 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8361 	if (e.error) {
8362 		nfs_rw_exit(&drp->r_rwlock);
8363 		return (e.error);
8364 	}
8365 	if (vp == cdir) {
8366 		VN_RELE(vp);
8367 		nfs_rw_exit(&drp->r_rwlock);
8368 		return (EINVAL);
8369 	}
8370 
8371 	/*
8372 	 * Since nfsv4 remove op works on both files and directories,
8373 	 * check that the removed object is indeed a directory.
8374 	 */
8375 	if (vp->v_type != VDIR) {
8376 		VN_RELE(vp);
8377 		nfs_rw_exit(&drp->r_rwlock);
8378 		return (ENOTDIR);
8379 	}
8380 
8381 	/*
8382 	 * First just remove the entry from the name cache, as it
8383 	 * is most likely an entry for this vp.
8384 	 */
8385 	dnlc_remove(dvp, nm);
8386 
8387 	/*
8388 	 * If there vnode reference count is greater than one, then
8389 	 * there may be additional references in the DNLC which will
8390 	 * need to be purged.  First, trying removing the entry for
8391 	 * the parent directory and see if that removes the additional
8392 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8393 	 * to completely remove any references to the directory which
8394 	 * might still exist in the DNLC.
8395 	 */
8396 	if (vp->v_count > 1) {
8397 		dnlc_remove(vp, "..");
8398 		if (vp->v_count > 1)
8399 			dnlc_purge_vp(vp);
8400 	}
8401 
8402 	mi = VTOMI4(dvp);
8403 	recov_state.rs_flags = 0;
8404 	recov_state.rs_num_retry_despite_err = 0;
8405 
8406 recov_retry:
8407 	args.ctag = TAG_RMDIR;
8408 
8409 	/*
8410 	 * Rmdir ops: putfh dir; remove
8411 	 */
8412 	args.array_len = 3;
8413 	args.array = argop;
8414 
8415 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8416 	if (e.error) {
8417 		nfs_rw_exit(&drp->r_rwlock);
8418 		return (e.error);
8419 	}
8420 	need_end_op = TRUE;
8421 
8422 	/* putfh directory */
8423 	argop[0].argop = OP_CPUTFH;
8424 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8425 
8426 	/* remove */
8427 	argop[1].argop = OP_CREMOVE;
8428 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8429 
8430 	/* getattr (postop attrs for dir that contained removed dir) */
8431 	argop[2].argop = OP_GETATTR;
8432 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8433 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8434 
8435 	dinfo.di_time_call = gethrtime();
8436 	doqueue = 1;
8437 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8438 
8439 	PURGE_ATTRCACHE4(vp);
8440 
8441 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8442 	if (e.error) {
8443 		PURGE_ATTRCACHE4(dvp);
8444 	}
8445 
8446 	if (needrecov) {
8447 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8448 		    NULL, OP_REMOVE, NULL) == FALSE) {
8449 			if (!e.error)
8450 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8451 								(caddr_t)&res);
8452 
8453 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8454 			    needrecov);
8455 			need_end_op = FALSE;
8456 			goto recov_retry;
8457 		}
8458 	}
8459 
8460 	if (!e.error) {
8461 		resp = &res;
8462 
8463 		/*
8464 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8465 		 * failed.
8466 		 */
8467 		if (res.status != NFS4_OK && res.array_len <= 2) {
8468 			e.error = geterrno4(res.status);
8469 			PURGE_ATTRCACHE4(dvp);
8470 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8471 						&recov_state, needrecov);
8472 			need_end_op = FALSE;
8473 			nfs4_purge_stale_fh(e.error, dvp, cr);
8474 			/*
8475 			 * System V defines rmdir to return EEXIST, not
8476 			 * ENOTEMPTY if the directory is not empty.  Over
8477 			 * the wire, the error is NFSERR_ENOTEMPTY which
8478 			 * geterrno4 maps to ENOTEMPTY.
8479 			 */
8480 			if (e.error == ENOTEMPTY)
8481 				e.error = EEXIST;
8482 		} else {
8483 			resop = &res.array[1];	/* remove res */
8484 			rm_res = &resop->nfs_resop4_u.opremove;
8485 
8486 			if (res.status == NFS4_OK) {
8487 				resop = &res.array[2];	/* dir attrs */
8488 				dinfo.di_garp =
8489 					&resop->nfs_resop4_u.opgetattr.ga_res;
8490 				dinfo.di_cred = cr;
8491 				dinfop = &dinfo;
8492 			} else
8493 				dinfop = NULL;
8494 
8495 			/* Update dir attribute, readdir and dnlc caches */
8496 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8497 				dinfop);
8498 
8499 			/* destroy rddir cache for dir that was removed */
8500 			if (VTOR4(vp)->r_dir != NULL)
8501 				nfs4_purge_rddir_cache(vp);
8502 		}
8503 	}
8504 
8505 	if (need_end_op)
8506 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8507 
8508 	nfs_rw_exit(&drp->r_rwlock);
8509 
8510 	if (resp)
8511 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8512 
8513 	VN_RELE(vp);
8514 
8515 	return (e.error);
8516 }
8517 
8518 static int
8519 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr)
8520 {
8521 	int error;
8522 	vnode_t *vp;
8523 	rnode4_t *rp;
8524 	char *contents;
8525 	mntinfo4_t *mi = VTOMI4(dvp);
8526 
8527 	if (nfs_zone() != mi->mi_zone)
8528 		return (EPERM);
8529 	if (!(mi->mi_flags & MI4_SYMLINK))
8530 		return (EOPNOTSUPP);
8531 
8532 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8533 	if (error) {
8534 		return (error);
8535 	}
8536 
8537 	ASSERT(nfs4_consistent_type(vp));
8538 	rp = VTOR4(vp);
8539 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8540 
8541 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8542 
8543 		if (contents != NULL) {
8544 			mutex_enter(&rp->r_statelock);
8545 			if (rp->r_symlink.contents == NULL) {
8546 				rp->r_symlink.len = strlen(tnm);
8547 				bcopy(tnm, contents, rp->r_symlink.len);
8548 				rp->r_symlink.contents = contents;
8549 				rp->r_symlink.size = MAXPATHLEN;
8550 				mutex_exit(&rp->r_statelock);
8551 			} else {
8552 				mutex_exit(&rp->r_statelock);
8553 				kmem_free((void *)contents, MAXPATHLEN);
8554 			}
8555 		}
8556 	}
8557 	VN_RELE(vp);
8558 
8559 	return (error);
8560 }
8561 
8562 
8563 /*
8564  * Read directory entries.
8565  * There are some weird things to look out for here.  The uio_loffset
8566  * field is either 0 or it is the offset returned from a previous
8567  * readdir.  It is an opaque value used by the server to find the
8568  * correct directory block to read. The count field is the number
8569  * of blocks to read on the server.  This is advisory only, the server
8570  * may return only one block's worth of entries.  Entries may be compressed
8571  * on the server.
8572  */
8573 static int
8574 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp)
8575 {
8576 	int error;
8577 	uint_t count;
8578 	rnode4_t *rp;
8579 	rddir4_cache *rdc;
8580 	rddir4_cache *rrdc;
8581 
8582 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8583 		return (EIO);
8584 	rp = VTOR4(vp);
8585 
8586 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8587 
8588 	/*
8589 	 * Make sure that the directory cache is valid.
8590 	 */
8591 	if (rp->r_dir != NULL) {
8592 		if (nfs_disable_rddir_cache != 0) {
8593 			/*
8594 			 * Setting nfs_disable_rddir_cache in /etc/system
8595 			 * allows interoperability with servers that do not
8596 			 * properly update the attributes of directories.
8597 			 * Any cached information gets purged before an
8598 			 * access is made to it.
8599 			 */
8600 			nfs4_purge_rddir_cache(vp);
8601 		}
8602 
8603 		error = nfs4_validate_caches(vp, cr);
8604 		if (error)
8605 			return (error);
8606 	}
8607 
8608 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8609 
8610 	/*
8611 	 * Short circuit last readdir which always returns 0 bytes.
8612 	 * This can be done after the directory has been read through
8613 	 * completely at least once.  This will set r_direof which
8614 	 * can be used to find the value of the last cookie.
8615 	 */
8616 	mutex_enter(&rp->r_statelock);
8617 	if (rp->r_direof != NULL &&
8618 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8619 		mutex_exit(&rp->r_statelock);
8620 #ifdef DEBUG
8621 		nfs4_readdir_cache_shorts++;
8622 #endif
8623 		if (eofp)
8624 			*eofp = 1;
8625 		return (0);
8626 	}
8627 
8628 	/*
8629 	 * Look for a cache entry.  Cache entries are identified
8630 	 * by the NFS cookie value and the byte count requested.
8631 	 */
8632 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8633 
8634 	/*
8635 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8636 	 */
8637 	if (rdc == NULL) {
8638 		mutex_exit(&rp->r_statelock);
8639 		return (EINTR);
8640 	}
8641 
8642 	/*
8643 	 * Check to see if we need to fill this entry in.
8644 	 */
8645 	if (rdc->flags & RDDIRREQ) {
8646 		rdc->flags &= ~RDDIRREQ;
8647 		rdc->flags |= RDDIR;
8648 		mutex_exit(&rp->r_statelock);
8649 
8650 		/*
8651 		 * Do the readdir.
8652 		 */
8653 		nfs4readdir(vp, rdc, cr);
8654 
8655 		/*
8656 		 * Reaquire the lock, so that we can continue
8657 		 */
8658 		mutex_enter(&rp->r_statelock);
8659 		/*
8660 		 * The entry is now complete
8661 		 */
8662 		rdc->flags &= ~RDDIR;
8663 	}
8664 
8665 	ASSERT(!(rdc->flags & RDDIR));
8666 
8667 	/*
8668 	 * If an error occurred while attempting
8669 	 * to fill the cache entry, mark the entry invalid and
8670 	 * just return the error.
8671 	 */
8672 	if (rdc->error) {
8673 		error = rdc->error;
8674 		rdc->flags |= RDDIRREQ;
8675 		rddir4_cache_rele(rp, rdc);
8676 		mutex_exit(&rp->r_statelock);
8677 		return (error);
8678 	}
8679 
8680 	/*
8681 	 * The cache entry is complete and good,
8682 	 * copyout the dirent structs to the calling
8683 	 * thread.
8684 	 */
8685 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
8686 
8687 	/*
8688 	 * If no error occurred during the copyout,
8689 	 * update the offset in the uio struct to
8690 	 * contain the value of the next NFS 4 cookie
8691 	 * and set the eof value appropriately.
8692 	 */
8693 	if (!error) {
8694 		uiop->uio_loffset = rdc->nfs4_ncookie;
8695 		if (eofp)
8696 			*eofp = rdc->eof;
8697 	}
8698 
8699 	/*
8700 	 * Decide whether to do readahead.  Don't if we
8701 	 * have already read to the end of directory.
8702 	 */
8703 	if (rdc->eof) {
8704 		/*
8705 		 * Make the entry the direof only if it is cached
8706 		 */
8707 		if (rdc->flags & RDDIRCACHED)
8708 			rp->r_direof = rdc;
8709 		rddir4_cache_rele(rp, rdc);
8710 		mutex_exit(&rp->r_statelock);
8711 		return (error);
8712 	}
8713 
8714 	/* Determine if a readdir readahead should be done */
8715 	if (!(rp->r_flags & R4LOOKUP)) {
8716 		rddir4_cache_rele(rp, rdc);
8717 		mutex_exit(&rp->r_statelock);
8718 		return (error);
8719 	}
8720 
8721 	/*
8722 	 * Now look for a readahead entry.
8723 	 *
8724 	 * Check to see whether we found an entry for the readahead.
8725 	 * If so, we don't need to do anything further, so free the new
8726 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
8727 	 * it to the cache, and then initiate an asynchronous readdir
8728 	 * operation to fill it.
8729 	 */
8730 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
8731 
8732 	/*
8733 	 * A readdir cache entry could not be obtained for the readahead.  In
8734 	 * this case we skip the readahead and return.
8735 	 */
8736 	if (rrdc == NULL) {
8737 		rddir4_cache_rele(rp, rdc);
8738 		mutex_exit(&rp->r_statelock);
8739 		return (error);
8740 	}
8741 
8742 	/*
8743 	 * Check to see if we need to fill this entry in.
8744 	 */
8745 	if (rrdc->flags & RDDIRREQ) {
8746 		rrdc->flags &= ~RDDIRREQ;
8747 		rrdc->flags |= RDDIR;
8748 		rddir4_cache_rele(rp, rdc);
8749 		mutex_exit(&rp->r_statelock);
8750 #ifdef DEBUG
8751 		nfs4_readdir_readahead++;
8752 #endif
8753 		/*
8754 		 * Do the readdir.
8755 		 */
8756 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
8757 		return (error);
8758 	}
8759 
8760 	rddir4_cache_rele(rp, rrdc);
8761 	rddir4_cache_rele(rp, rdc);
8762 	mutex_exit(&rp->r_statelock);
8763 	return (error);
8764 }
8765 
8766 static int
8767 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
8768 {
8769 	int error;
8770 	rnode4_t *rp;
8771 
8772 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
8773 
8774 	rp = VTOR4(vp);
8775 
8776 	/*
8777 	 * Obtain the readdir results for the caller.
8778 	 */
8779 	nfs4readdir(vp, rdc, cr);
8780 
8781 	mutex_enter(&rp->r_statelock);
8782 	/*
8783 	 * The entry is now complete
8784 	 */
8785 	rdc->flags &= ~RDDIR;
8786 
8787 	error = rdc->error;
8788 	if (error)
8789 		rdc->flags |= RDDIRREQ;
8790 	rddir4_cache_rele(rp, rdc);
8791 	mutex_exit(&rp->r_statelock);
8792 
8793 	return (error);
8794 }
8795 
8796 static void
8797 nfs4readdir_stub(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
8798 {
8799 	int stublength;
8800 	dirent64_t *dp;
8801 	u_longlong_t nodeid, pnodeid;
8802 	vnode_t *dotdotvp = NULL;
8803 	rnode4_t *rp = VTOR4(vp);
8804 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
8805 
8806 	rdc->error = 0;
8807 	rdc->entries = 0;
8808 	rdc->actlen = rdc->entlen = 0;
8809 	rdc->eof = TRUE;
8810 
8811 	/* Check for EOF case for readdir of stub */
8812 	if (cookie != 0 && cookie != 1)
8813 		return;
8814 
8815 	nodeid = rp->r_attr.va_nodeid;
8816 	if (vp->v_flag & VROOT) {
8817 		pnodeid = nodeid;	/* root of mount point */
8818 	} else {
8819 		if (rdc->error = nfs4_lookup(vp, "..", &dotdotvp, 0, 0, 0, cr))
8820 			return;
8821 		pnodeid = VTOR4(dotdotvp)->r_attr.va_nodeid;
8822 		VN_RELE(dotdotvp);
8823 	}
8824 
8825 	stublength = DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2);
8826 	rdc->entries = kmem_alloc(stublength, KM_SLEEP);
8827 	rdc->entlen = rdc->buflen = stublength;
8828 	rdc->eof = TRUE;
8829 
8830 	dp = (dirent64_t *)rdc->entries;
8831 
8832 	if (rdc->nfs4_cookie == (nfs_cookie4)0) {
8833 		bcopy(nfs4_dot_entries, rdc->entries,
8834 			DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2));
8835 		dp->d_ino = nodeid;
8836 		dp = (struct dirent64 *)(((char *)dp) + DIRENT64_RECLEN(1));
8837 		dp->d_ino = pnodeid;
8838 		rdc->actlen = DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2);
8839 	} else	{	/* for ".." entry */
8840 		bcopy(nfs4_dot_dot_entry, rdc->entries, DIRENT64_RECLEN(2));
8841 		dp->d_ino = pnodeid;
8842 		rdc->actlen = DIRENT64_RECLEN(2);
8843 	}
8844 	rdc->nfs4_ncookie = rdc->actlen;
8845 }
8846 
8847 /*
8848  * Read directory entries.
8849  * There are some weird things to look out for here.  The uio_loffset
8850  * field is either 0 or it is the offset returned from a previous
8851  * readdir.  It is an opaque value used by the server to find the
8852  * correct directory block to read. The count field is the number
8853  * of blocks to read on the server.  This is advisory only, the server
8854  * may return only one block's worth of entries.  Entries may be compressed
8855  * on the server.
8856  *
8857  * Generates the following compound request:
8858  * 1. If readdir offset is zero and no dnlc entry for parent exists,
8859  *    must include a Lookupp as well. In this case, send:
8860  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
8861  * 2. Otherwise just do: { Putfh <fh>; Readdir }
8862  *
8863  * Get complete attributes and filehandles for entries if this is the
8864  * first read of the directory. Otherwise, just get fileid's.
8865  */
8866 static void
8867 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
8868 {
8869 	COMPOUND4args_clnt args;
8870 	COMPOUND4res_clnt res;
8871 	READDIR4args *rargs;
8872 	READDIR4res_clnt *rd_res;
8873 	bitmap4 rd_bitsval;
8874 	nfs_argop4 argop[5];
8875 	nfs_resop4 *resop;
8876 	rnode4_t *rp = VTOR4(vp);
8877 	mntinfo4_t *mi = VTOMI4(vp);
8878 	int doqueue;
8879 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
8880 	vnode_t *dvp;
8881 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
8882 	int num_ops, res_opcnt;
8883 	bool_t needrecov = FALSE;
8884 	nfs4_recov_state_t recov_state;
8885 	hrtime_t t;
8886 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8887 
8888 	ASSERT(nfs_zone() == mi->mi_zone);
8889 	ASSERT(rdc->flags & RDDIR);
8890 	ASSERT(rdc->entries == NULL);
8891 
8892 	if (rp->r_flags & R4SRVSTUB) {
8893 		nfs4readdir_stub(vp, rdc, cr);
8894 		return;
8895 	}
8896 
8897 	num_ops = 2;
8898 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
8899 		/*
8900 		 * Since nfsv4 readdir may not return entries for "." and "..",
8901 		 * the client must recreate them:
8902 		 * To find the correct nodeid, do the following:
8903 		 * For current node, get nodeid from dnlc.
8904 		 * - if current node is rootvp, set pnodeid to nodeid.
8905 		 * - else if parent is in the dnlc, get its nodeid from there.
8906 		 * - else add LOOKUPP+GETATTR to compound.
8907 		 */
8908 		nodeid = rp->r_attr.va_nodeid;
8909 		if (vp->v_flag & VROOT) {
8910 			pnodeid = nodeid;	/* root of mount point */
8911 		} else {
8912 			dvp = dnlc_lookup(vp, "..");
8913 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
8914 				/* parent in dnlc cache - no need for otw */
8915 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
8916 			} else {
8917 				/*
8918 				 * parent not in dnlc cache,
8919 				 * do lookupp to get its id
8920 				 */
8921 				num_ops = 5;
8922 				pnodeid = 0; /* set later by getattr parent */
8923 			}
8924 			if (dvp)
8925 				VN_RELE(dvp);
8926 		}
8927 	}
8928 	recov_state.rs_flags = 0;
8929 	recov_state.rs_num_retry_despite_err = 0;
8930 
8931 	/* Save the original mount point security flavor */
8932 	(void) save_mnt_secinfo(mi->mi_curr_serv);
8933 
8934 recov_retry:
8935 	args.ctag = TAG_READDIR;
8936 
8937 	args.array = argop;
8938 	args.array_len = num_ops;
8939 
8940 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
8941 					&recov_state, NULL)) {
8942 		/*
8943 		 * If readdir a node that is a stub for a crossed mount point,
8944 		 * keep the original secinfo flavor for the current file
8945 		 * system, not the crossed one.
8946 		 */
8947 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
8948 		rdc->error = e.error;
8949 		return;
8950 	}
8951 
8952 	/*
8953 	 * Determine which attrs to request for dirents.  This code
8954 	 * must be protected by nfs4_start/end_fop because of r_server
8955 	 * (which will change during failover recovery).
8956 	 *
8957 	 */
8958 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
8959 		/*
8960 		 * Get all vattr attrs plus filehandle and rdattr_error
8961 		 */
8962 		rd_bitsval = NFS4_VATTR_MASK |
8963 			FATTR4_RDATTR_ERROR_MASK |
8964 			FATTR4_FILEHANDLE_MASK;
8965 
8966 		if (rp->r_flags & R4READDIRWATTR) {
8967 			mutex_enter(&rp->r_statelock);
8968 			rp->r_flags &= ~R4READDIRWATTR;
8969 			mutex_exit(&rp->r_statelock);
8970 		}
8971 	} else {
8972 		servinfo4_t *svp = rp->r_server;
8973 
8974 		/*
8975 		 * Already read directory. Use readdir with
8976 		 * no attrs (except for mounted_on_fileid) for updates.
8977 		 */
8978 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
8979 
8980 		/*
8981 		 * request mounted on fileid if supported, else request
8982 		 * fileid.  maybe we should verify that fileid is supported
8983 		 * and request something else if not.
8984 		 */
8985 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
8986 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
8987 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
8988 		nfs_rw_exit(&svp->sv_lock);
8989 	}
8990 
8991 	/* putfh directory fh */
8992 	argop[0].argop = OP_CPUTFH;
8993 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
8994 
8995 	argop[1].argop = OP_READDIR;
8996 	rargs = &argop[1].nfs_argop4_u.opreaddir;
8997 	/*
8998 	 * 1 and 2 are reserved for client "." and ".." entry offset.
8999 	 * cookie 0 should be used over-the-wire to start reading at
9000 	 * the beginning of the directory excluding "." and "..".
9001 	 */
9002 	if (rdc->nfs4_cookie == 0 ||
9003 	    rdc->nfs4_cookie == 1 ||
9004 	    rdc->nfs4_cookie == 2) {
9005 		rargs->cookie = (nfs_cookie4)0;
9006 		rargs->cookieverf = 0;
9007 	} else {
9008 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9009 		mutex_enter(&rp->r_statelock);
9010 		rargs->cookieverf = rp->r_cookieverf4;
9011 		mutex_exit(&rp->r_statelock);
9012 	}
9013 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9014 	rargs->maxcount = mi->mi_tsize;
9015 	rargs->attr_request = rd_bitsval;
9016 	rargs->rdc = rdc;
9017 	rargs->dvp = vp;
9018 	rargs->mi = mi;
9019 	rargs->cr = cr;
9020 
9021 
9022 	/*
9023 	 * If count < than the minimum required, we return no entries
9024 	 * and fail with EINVAL
9025 	 */
9026 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9027 		rdc->error = EINVAL;
9028 		goto out;
9029 	}
9030 
9031 	if (args.array_len == 5) {
9032 		/*
9033 		 * Add lookupp and getattr for parent nodeid.
9034 		 */
9035 		argop[2].argop = OP_LOOKUPP;
9036 
9037 		argop[3].argop = OP_GETFH;
9038 
9039 		/* getattr parent */
9040 		argop[4].argop = OP_GETATTR;
9041 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9042 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9043 	}
9044 
9045 	doqueue = 1;
9046 
9047 	if (mi->mi_io_kstats) {
9048 		mutex_enter(&mi->mi_lock);
9049 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9050 		mutex_exit(&mi->mi_lock);
9051 	}
9052 
9053 	/* capture the time of this call */
9054 	rargs->t = t = gethrtime();
9055 
9056 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9057 
9058 	if (mi->mi_io_kstats) {
9059 		mutex_enter(&mi->mi_lock);
9060 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9061 		mutex_exit(&mi->mi_lock);
9062 	}
9063 
9064 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9065 
9066 	/*
9067 	 * If RPC error occurred and it isn't an error that
9068 	 * triggers recovery, then go ahead and fail now.
9069 	 */
9070 	if (e.error != 0 && !needrecov) {
9071 		rdc->error = e.error;
9072 		goto out;
9073 	}
9074 
9075 	if (needrecov) {
9076 		bool_t abort;
9077 
9078 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9079 		    "nfs4readdir: initiating recovery.\n"));
9080 
9081 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9082 			    NULL, OP_READDIR, NULL);
9083 		if (abort == FALSE) {
9084 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9085 				    &recov_state, needrecov);
9086 			if (!e.error)
9087 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9088 						(caddr_t)&res);
9089 			if (rdc->entries != NULL) {
9090 				kmem_free(rdc->entries, rdc->entlen);
9091 				rdc->entries = NULL;
9092 			}
9093 			goto recov_retry;
9094 		}
9095 
9096 		if (e.error != 0) {
9097 			rdc->error = e.error;
9098 			goto out;
9099 		}
9100 
9101 		/* fall through for res.status case */
9102 	}
9103 
9104 	res_opcnt = res.array_len;
9105 
9106 	/*
9107 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9108 	 * failure here.  Subsequent ops are for filling out dot-dot
9109 	 * dirent, and if they fail, we still want to give the caller
9110 	 * the dirents returned by (the successful) READDIR op, so we need
9111 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9112 	 *
9113 	 * One example where PUTFH+READDIR ops would succeed but
9114 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9115 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9116 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9117 	 * x perm.  We need to come up with a non-vendor-specific way
9118 	 * for a POSIX server to return d_ino from dotdot's dirent if
9119 	 * client only requests mounted_on_fileid, and just say the
9120 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9121 	 * client requested any mandatory attrs, server would be required
9122 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9123 	 * for dotdot.
9124 	 */
9125 
9126 	if (res.status) {
9127 		if (res_opcnt <= 2) {
9128 			e.error = geterrno4(res.status);
9129 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9130 			    &recov_state, needrecov);
9131 			nfs4_purge_stale_fh(e.error, vp, cr);
9132 			rdc->error = e.error;
9133 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9134 			if (rdc->entries != NULL) {
9135 				kmem_free(rdc->entries, rdc->entlen);
9136 				rdc->entries = NULL;
9137 			}
9138 			/*
9139 			 * If readdir a node that is a stub for a
9140 			 * crossed mount point, keep the original
9141 			 * secinfo flavor for the current file system,
9142 			 * not the crossed one.
9143 			 */
9144 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9145 			return;
9146 		}
9147 	}
9148 
9149 	resop = &res.array[1];	/* readdir res */
9150 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9151 
9152 	mutex_enter(&rp->r_statelock);
9153 	rp->r_cookieverf4 = rd_res->cookieverf;
9154 	mutex_exit(&rp->r_statelock);
9155 
9156 	/*
9157 	 * For "." and ".." entries
9158 	 * e.g.
9159 	 *	seek(cookie=0) -> "." entry with d_off = 1
9160 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9161 	 */
9162 	if (cookie == (nfs_cookie4) 0) {
9163 		if (rd_res->dotp)
9164 			rd_res->dotp->d_ino = nodeid;
9165 		if (rd_res->dotdotp)
9166 			rd_res->dotdotp->d_ino = pnodeid;
9167 	}
9168 	if (cookie == (nfs_cookie4) 1) {
9169 		if (rd_res->dotdotp)
9170 			rd_res->dotdotp->d_ino = pnodeid;
9171 	}
9172 
9173 
9174 	/* LOOKUPP+GETATTR attemped */
9175 	if (args.array_len == 5 && rd_res->dotdotp) {
9176 		if (res.status == NFS4_OK && res_opcnt == 5) {
9177 			nfs_fh4 *fhp;
9178 			nfs4_sharedfh_t *sfhp;
9179 			vnode_t *pvp;
9180 			nfs4_ga_res_t *garp;
9181 
9182 			resop++;	/* lookupp */
9183 			resop++;	/* getfh   */
9184 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9185 
9186 			resop++;	/* getattr of parent */
9187 
9188 			/*
9189 			 * First, take care of finishing the
9190 			 * readdir results.
9191 			 */
9192 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9193 			/*
9194 			 * The d_ino of .. must be the inode number
9195 			 * of the mounted filesystem.
9196 			 */
9197 			if (garp->n4g_va.va_mask & AT_NODEID)
9198 				rd_res->dotdotp->d_ino =
9199 					garp->n4g_va.va_nodeid;
9200 
9201 
9202 			/*
9203 			 * Next, create the ".." dnlc entry
9204 			 */
9205 			sfhp = sfh4_get(fhp, mi);
9206 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9207 				dnlc_update(vp, "..", pvp);
9208 				VN_RELE(pvp);
9209 			}
9210 			sfh4_rele(&sfhp);
9211 		}
9212 	}
9213 
9214 	if (mi->mi_io_kstats) {
9215 		mutex_enter(&mi->mi_lock);
9216 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9217 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9218 		mutex_exit(&mi->mi_lock);
9219 	}
9220 
9221 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9222 
9223 out:
9224 	/*
9225 	 * If readdir a node that is a stub for a crossed mount point,
9226 	 * keep the original secinfo flavor for the current file system,
9227 	 * not the crossed one.
9228 	 */
9229 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9230 
9231 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9232 }
9233 
9234 
9235 static int
9236 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9237 {
9238 	rnode4_t *rp = VTOR4(bp->b_vp);
9239 	int count;
9240 	int error;
9241 	cred_t *cred_otw = NULL;
9242 	offset_t offset;
9243 	nfs4_open_stream_t *osp = NULL;
9244 	bool_t first_time = TRUE;	/* first time getting otw cred */
9245 	bool_t last_time = FALSE;	/* last time getting otw cred */
9246 
9247 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9248 
9249 	DTRACE_IO1(start, struct buf *, bp);
9250 	offset = ldbtob(bp->b_lblkno);
9251 
9252 	if (bp->b_flags & B_READ) {
9253 	read_again:
9254 		/*
9255 		 * Releases the osp, if it is provided.
9256 		 * Puts a hold on the cred_otw and the new osp (if found).
9257 		 */
9258 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9259 			&first_time, &last_time);
9260 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9261 						offset, bp->b_bcount,
9262 						&bp->b_resid, cred_otw,
9263 						readahead, NULL);
9264 		crfree(cred_otw);
9265 		if (!error) {
9266 			if (bp->b_resid) {
9267 				/*
9268 				 * Didn't get it all because we hit EOF,
9269 				 * zero all the memory beyond the EOF.
9270 				 */
9271 				/* bzero(rdaddr + */
9272 				bzero(bp->b_un.b_addr +
9273 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9274 			}
9275 			mutex_enter(&rp->r_statelock);
9276 			if (bp->b_resid == bp->b_bcount &&
9277 			    offset >= rp->r_size) {
9278 				/*
9279 				 * We didn't read anything at all as we are
9280 				 * past EOF.  Return an error indicator back
9281 				 * but don't destroy the pages (yet).
9282 				 */
9283 				error = NFS_EOF;
9284 			}
9285 			mutex_exit(&rp->r_statelock);
9286 		} else if (error == EACCES && last_time == FALSE) {
9287 				goto read_again;
9288 		}
9289 	} else {
9290 		if (!(rp->r_flags & R4STALE)) {
9291 		write_again:
9292 			/*
9293 			 * Releases the osp, if it is provided.
9294 			 * Puts a hold on the cred_otw and the new
9295 			 * osp (if found).
9296 			 */
9297 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9298 				&first_time, &last_time);
9299 			mutex_enter(&rp->r_statelock);
9300 			count = MIN(bp->b_bcount, rp->r_size - offset);
9301 			mutex_exit(&rp->r_statelock);
9302 			if (count < 0)
9303 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9304 #ifdef DEBUG
9305 			if (count == 0) {
9306 				zoneid_t zoneid = getzoneid();
9307 
9308 				zcmn_err(zoneid, CE_WARN,
9309 				    "nfs4_bio: zero length write at %lld",
9310 				    offset);
9311 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9312 				    "b_bcount=%ld, file size=%lld",
9313 				    rp->r_flags, (long)bp->b_bcount,
9314 				    rp->r_size);
9315 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9316 				if (nfs4_bio_do_stop)
9317 					debug_enter("nfs4_bio");
9318 			}
9319 #endif
9320 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9321 			    count, cred_otw, stab_comm);
9322 			if (error == EACCES && last_time == FALSE) {
9323 				crfree(cred_otw);
9324 				goto write_again;
9325 			}
9326 			bp->b_error = error;
9327 			if (error && error != EINTR &&
9328 			    !(bp->b_vp->v_vfsp->vfs_flag && VFS_UNMOUNTED)) {
9329 				/*
9330 				 * Don't print EDQUOT errors on the console.
9331 				 * Don't print asynchronous EACCES errors.
9332 				 * Don't print EFBIG errors.
9333 				 * Print all other write errors.
9334 				 */
9335 				if (error != EDQUOT && error != EFBIG &&
9336 				    (error != EACCES ||
9337 				    !(bp->b_flags & B_ASYNC)))
9338 					nfs4_write_error(bp->b_vp,
9339 					    error, cred_otw);
9340 				/*
9341 				 * Update r_error and r_flags as appropriate.
9342 				 * If the error was ESTALE, then mark the
9343 				 * rnode as not being writeable and save
9344 				 * the error status.  Otherwise, save any
9345 				 * errors which occur from asynchronous
9346 				 * page invalidations.  Any errors occurring
9347 				 * from other operations should be saved
9348 				 * by the caller.
9349 				 */
9350 				mutex_enter(&rp->r_statelock);
9351 				if (error == ESTALE) {
9352 					rp->r_flags |= R4STALE;
9353 					if (!rp->r_error)
9354 						rp->r_error = error;
9355 				} else if (!rp->r_error &&
9356 				    (bp->b_flags &
9357 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9358 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9359 					rp->r_error = error;
9360 				}
9361 				mutex_exit(&rp->r_statelock);
9362 			}
9363 			crfree(cred_otw);
9364 		} else
9365 			error = rp->r_error;
9366 	}
9367 
9368 	if (error != 0 && error != NFS_EOF)
9369 		bp->b_flags |= B_ERROR;
9370 
9371 	if (osp)
9372 		open_stream_rele(osp, rp);
9373 
9374 	DTRACE_IO1(done, struct buf *, bp);
9375 
9376 	return (error);
9377 }
9378 
9379 /* ARGSUSED */
9380 static int
9381 nfs4_fid(vnode_t *vp, fid_t *fidp)
9382 {
9383 	return (EREMOTE);
9384 }
9385 
9386 /* ARGSUSED2 */
9387 static int
9388 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9389 {
9390 	rnode4_t *rp = VTOR4(vp);
9391 
9392 	if (!write_lock) {
9393 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9394 		return (V_WRITELOCK_FALSE);
9395 	}
9396 
9397 	if ((rp->r_flags & R4DIRECTIO) ||
9398 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9399 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9400 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9401 			return (V_WRITELOCK_FALSE);
9402 		nfs_rw_exit(&rp->r_rwlock);
9403 	}
9404 
9405 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9406 	return (V_WRITELOCK_TRUE);
9407 }
9408 
9409 /* ARGSUSED */
9410 static void
9411 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9412 {
9413 	rnode4_t *rp = VTOR4(vp);
9414 
9415 	nfs_rw_exit(&rp->r_rwlock);
9416 }
9417 
9418 /* ARGSUSED */
9419 static int
9420 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp)
9421 {
9422 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9423 		return (EIO);
9424 
9425 	/*
9426 	 * Because we stuff the readdir cookie into the offset field
9427 	 * someone may attempt to do an lseek with the cookie which
9428 	 * we want to succeed.
9429 	 */
9430 	if (vp->v_type == VDIR)
9431 		return (0);
9432 	if (*noffp < 0)
9433 		return (EINVAL);
9434 	return (0);
9435 }
9436 
9437 
9438 /*
9439  * Return all the pages from [off..off+len) in file
9440  */
9441 static int
9442 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9443 	page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9444 	enum seg_rw rw, cred_t *cr)
9445 {
9446 	rnode4_t *rp;
9447 	int error;
9448 	mntinfo4_t *mi;
9449 
9450 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9451 		return (EIO);
9452 	rp = VTOR4(vp);
9453 	if (IS_SHADOW(vp, rp))
9454 		vp = RTOV4(rp);
9455 
9456 	if (vp->v_flag & VNOMAP)
9457 		return (ENOSYS);
9458 
9459 	if (protp != NULL)
9460 		*protp = PROT_ALL;
9461 
9462 	/*
9463 	 * Now validate that the caches are up to date.
9464 	 */
9465 	if (error = nfs4_validate_caches(vp, cr))
9466 		return (error);
9467 
9468 	mi = VTOMI4(vp);
9469 retry:
9470 	mutex_enter(&rp->r_statelock);
9471 
9472 	/*
9473 	 * Don't create dirty pages faster than they
9474 	 * can be cleaned so that the system doesn't
9475 	 * get imbalanced.  If the async queue is
9476 	 * maxed out, then wait for it to drain before
9477 	 * creating more dirty pages.  Also, wait for
9478 	 * any threads doing pagewalks in the vop_getattr
9479 	 * entry points so that they don't block for
9480 	 * long periods.
9481 	 */
9482 	if (rw == S_CREATE) {
9483 		while ((mi->mi_max_threads != 0 &&
9484 			rp->r_awcount > 2 * mi->mi_max_threads) ||
9485 			rp->r_gcount > 0)
9486 			cv_wait(&rp->r_cv, &rp->r_statelock);
9487 	}
9488 
9489 	/*
9490 	 * If we are getting called as a side effect of an nfs_write()
9491 	 * operation the local file size might not be extended yet.
9492 	 * In this case we want to be able to return pages of zeroes.
9493 	 */
9494 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9495 		NFS4_DEBUG(nfs4_pageio_debug,
9496 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9497 		    "len=%llu, size=%llu, attrsize =%llu", off,
9498 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9499 		mutex_exit(&rp->r_statelock);
9500 		return (EFAULT);		/* beyond EOF */
9501 	}
9502 
9503 	mutex_exit(&rp->r_statelock);
9504 
9505 	if (len <= PAGESIZE) {
9506 		error = nfs4_getapage(vp, off, len, protp, pl, plsz,
9507 		    seg, addr, rw, cr);
9508 		NFS4_DEBUG(nfs4_pageio_debug && error,
9509 			(CE_NOTE, "getpage error %d; off=%lld, "
9510 			"len=%lld", error, off, (u_longlong_t)len));
9511 	} else {
9512 		error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9513 		    pl, plsz, seg, addr, rw, cr);
9514 		NFS4_DEBUG(nfs4_pageio_debug && error,
9515 			(CE_NOTE, "getpages error %d; off=%lld, "
9516 			"len=%lld", error, off, (u_longlong_t)len));
9517 	}
9518 
9519 	switch (error) {
9520 	case NFS_EOF:
9521 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9522 		goto retry;
9523 	case ESTALE:
9524 		nfs4_purge_stale_fh(error, vp, cr);
9525 	}
9526 
9527 	return (error);
9528 }
9529 
9530 /*
9531  * Called from pvn_getpages or nfs4_getpage to get a particular page.
9532  */
9533 /* ARGSUSED */
9534 static int
9535 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9536 	page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9537 	enum seg_rw rw, cred_t *cr)
9538 {
9539 	rnode4_t *rp;
9540 	uint_t bsize;
9541 	struct buf *bp;
9542 	page_t *pp;
9543 	u_offset_t lbn;
9544 	u_offset_t io_off;
9545 	u_offset_t blkoff;
9546 	u_offset_t rablkoff;
9547 	size_t io_len;
9548 	uint_t blksize;
9549 	int error;
9550 	int readahead;
9551 	int readahead_issued = 0;
9552 	int ra_window; /* readahead window */
9553 	page_t *pagefound;
9554 	page_t *savepp;
9555 
9556 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9557 		return (EIO);
9558 
9559 	rp = VTOR4(vp);
9560 	ASSERT(!IS_SHADOW(vp, rp));
9561 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9562 
9563 reread:
9564 	bp = NULL;
9565 	pp = NULL;
9566 	pagefound = NULL;
9567 
9568 	if (pl != NULL)
9569 		pl[0] = NULL;
9570 
9571 	error = 0;
9572 	lbn = off / bsize;
9573 	blkoff = lbn * bsize;
9574 
9575 	/*
9576 	 * Queueing up the readahead before doing the synchronous read
9577 	 * results in a significant increase in read throughput because
9578 	 * of the increased parallelism between the async threads and
9579 	 * the process context.
9580 	 */
9581 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9582 	    rw != S_CREATE &&
9583 	    !(vp->v_flag & VNOCACHE)) {
9584 		mutex_enter(&rp->r_statelock);
9585 
9586 		/*
9587 		 * Calculate the number of readaheads to do.
9588 		 * a) No readaheads at offset = 0.
9589 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9590 		 *    window is closed.
9591 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9592 		 *    upon how far the readahead window is open or close.
9593 		 * d) No readaheads if rp->r_nextr is not within the scope
9594 		 *    of the readahead window (random i/o).
9595 		 */
9596 
9597 		if (off == 0)
9598 			readahead = 0;
9599 		else if (blkoff == rp->r_nextr)
9600 			readahead = nfs4_nra;
9601 		else if (rp->r_nextr > blkoff &&
9602 			((ra_window = (rp->r_nextr - blkoff) / bsize)
9603 					<= (nfs4_nra - 1)))
9604 			readahead = nfs4_nra - ra_window;
9605 		else
9606 			readahead = 0;
9607 
9608 		rablkoff = rp->r_nextr;
9609 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9610 			mutex_exit(&rp->r_statelock);
9611 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9612 			    addr + (rablkoff + bsize - off),
9613 			    seg, cr, nfs4_readahead) < 0) {
9614 				mutex_enter(&rp->r_statelock);
9615 				break;
9616 			}
9617 			readahead--;
9618 			rablkoff += bsize;
9619 			/*
9620 			 * Indicate that we did a readahead so
9621 			 * readahead offset is not updated
9622 			 * by the synchronous read below.
9623 			 */
9624 			readahead_issued = 1;
9625 			mutex_enter(&rp->r_statelock);
9626 			/*
9627 			 * set readahead offset to
9628 			 * offset of last async readahead
9629 			 * request.
9630 			 */
9631 			rp->r_nextr = rablkoff;
9632 		}
9633 		mutex_exit(&rp->r_statelock);
9634 	}
9635 
9636 again:
9637 	if ((pagefound = page_exists(vp, off)) == NULL) {
9638 		if (pl == NULL) {
9639 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9640 			    nfs4_readahead);
9641 		} else if (rw == S_CREATE) {
9642 			/*
9643 			 * Block for this page is not allocated, or the offset
9644 			 * is beyond the current allocation size, or we're
9645 			 * allocating a swap slot and the page was not found,
9646 			 * so allocate it and return a zero page.
9647 			 */
9648 			if ((pp = page_create_va(vp, off,
9649 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9650 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9651 			io_len = PAGESIZE;
9652 			mutex_enter(&rp->r_statelock);
9653 			rp->r_nextr = off + PAGESIZE;
9654 			mutex_exit(&rp->r_statelock);
9655 		} else {
9656 			/*
9657 			 * Need to go to server to get a block
9658 			 */
9659 			mutex_enter(&rp->r_statelock);
9660 			if (blkoff < rp->r_size &&
9661 			    blkoff + bsize > rp->r_size) {
9662 				/*
9663 				 * If less than a block left in
9664 				 * file read less than a block.
9665 				 */
9666 				if (rp->r_size <= off) {
9667 					/*
9668 					 * Trying to access beyond EOF,
9669 					 * set up to get at least one page.
9670 					 */
9671 					blksize = off + PAGESIZE - blkoff;
9672 				} else
9673 					blksize = rp->r_size - blkoff;
9674 			} else if ((off == 0) ||
9675 				(off != rp->r_nextr && !readahead_issued)) {
9676 				blksize = PAGESIZE;
9677 				blkoff = off; /* block = page here */
9678 			} else
9679 				blksize = bsize;
9680 			mutex_exit(&rp->r_statelock);
9681 
9682 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9683 			    &io_len, blkoff, blksize, 0);
9684 
9685 			/*
9686 			 * Some other thread has entered the page,
9687 			 * so just use it.
9688 			 */
9689 			if (pp == NULL)
9690 				goto again;
9691 
9692 			/*
9693 			 * Now round the request size up to page boundaries.
9694 			 * This ensures that the entire page will be
9695 			 * initialized to zeroes if EOF is encountered.
9696 			 */
9697 			io_len = ptob(btopr(io_len));
9698 
9699 			bp = pageio_setup(pp, io_len, vp, B_READ);
9700 			ASSERT(bp != NULL);
9701 
9702 			/*
9703 			 * pageio_setup should have set b_addr to 0.  This
9704 			 * is correct since we want to do I/O on a page
9705 			 * boundary.  bp_mapin will use this addr to calculate
9706 			 * an offset, and then set b_addr to the kernel virtual
9707 			 * address it allocated for us.
9708 			 */
9709 			ASSERT(bp->b_un.b_addr == 0);
9710 
9711 			bp->b_edev = 0;
9712 			bp->b_dev = 0;
9713 			bp->b_lblkno = lbtodb(io_off);
9714 			bp->b_file = vp;
9715 			bp->b_offset = (offset_t)off;
9716 			bp_mapin(bp);
9717 
9718 			/*
9719 			 * If doing a write beyond what we believe is EOF,
9720 			 * don't bother trying to read the pages from the
9721 			 * server, we'll just zero the pages here.  We
9722 			 * don't check that the rw flag is S_WRITE here
9723 			 * because some implementations may attempt a
9724 			 * read access to the buffer before copying data.
9725 			 */
9726 			mutex_enter(&rp->r_statelock);
9727 			if (io_off >= rp->r_size && seg == segkmap) {
9728 				mutex_exit(&rp->r_statelock);
9729 				bzero(bp->b_un.b_addr, io_len);
9730 			} else {
9731 				mutex_exit(&rp->r_statelock);
9732 				error = nfs4_bio(bp, NULL, cr, FALSE);
9733 			}
9734 
9735 			/*
9736 			 * Unmap the buffer before freeing it.
9737 			 */
9738 			bp_mapout(bp);
9739 			pageio_done(bp);
9740 
9741 			savepp = pp;
9742 			do {
9743 				pp->p_fsdata = C_NOCOMMIT;
9744 			} while ((pp = pp->p_next) != savepp);
9745 
9746 			if (error == NFS_EOF) {
9747 				/*
9748 				 * If doing a write system call just return
9749 				 * zeroed pages, else user tried to get pages
9750 				 * beyond EOF, return error.  We don't check
9751 				 * that the rw flag is S_WRITE here because
9752 				 * some implementations may attempt a read
9753 				 * access to the buffer before copying data.
9754 				 */
9755 				if (seg == segkmap)
9756 					error = 0;
9757 				else
9758 					error = EFAULT;
9759 			}
9760 
9761 			if (!readahead_issued && !error) {
9762 				mutex_enter(&rp->r_statelock);
9763 				rp->r_nextr = io_off + io_len;
9764 				mutex_exit(&rp->r_statelock);
9765 			}
9766 		}
9767 	}
9768 
9769 out:
9770 	if (pl == NULL)
9771 		return (error);
9772 
9773 	if (error) {
9774 		if (pp != NULL)
9775 			pvn_read_done(pp, B_ERROR);
9776 		return (error);
9777 	}
9778 
9779 	if (pagefound) {
9780 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
9781 
9782 		/*
9783 		 * Page exists in the cache, acquire the appropriate lock.
9784 		 * If this fails, start all over again.
9785 		 */
9786 		if ((pp = page_lookup(vp, off, se)) == NULL) {
9787 #ifdef DEBUG
9788 			nfs4_lostpage++;
9789 #endif
9790 			goto reread;
9791 		}
9792 		pl[0] = pp;
9793 		pl[1] = NULL;
9794 		return (0);
9795 	}
9796 
9797 	if (pp != NULL)
9798 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
9799 
9800 	return (error);
9801 }
9802 
9803 static void
9804 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
9805 	cred_t *cr)
9806 {
9807 	int error;
9808 	page_t *pp;
9809 	u_offset_t io_off;
9810 	size_t io_len;
9811 	struct buf *bp;
9812 	uint_t bsize, blksize;
9813 	rnode4_t *rp = VTOR4(vp);
9814 	page_t *savepp;
9815 
9816 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9817 
9818 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9819 
9820 	mutex_enter(&rp->r_statelock);
9821 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
9822 		/*
9823 		 * If less than a block left in file read less
9824 		 * than a block.
9825 		 */
9826 		blksize = rp->r_size - blkoff;
9827 	} else
9828 		blksize = bsize;
9829 	mutex_exit(&rp->r_statelock);
9830 
9831 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
9832 	    &io_off, &io_len, blkoff, blksize, 1);
9833 	/*
9834 	 * The isra flag passed to the kluster function is 1, we may have
9835 	 * gotten a return value of NULL for a variety of reasons (# of free
9836 	 * pages < minfree, someone entered the page on the vnode etc). In all
9837 	 * cases, we want to punt on the readahead.
9838 	 */
9839 	if (pp == NULL)
9840 		return;
9841 
9842 	/*
9843 	 * Now round the request size up to page boundaries.
9844 	 * This ensures that the entire page will be
9845 	 * initialized to zeroes if EOF is encountered.
9846 	 */
9847 	io_len = ptob(btopr(io_len));
9848 
9849 	bp = pageio_setup(pp, io_len, vp, B_READ);
9850 	ASSERT(bp != NULL);
9851 
9852 	/*
9853 	 * pageio_setup should have set b_addr to 0.  This is correct since
9854 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
9855 	 * to calculate an offset, and then set b_addr to the kernel virtual
9856 	 * address it allocated for us.
9857 	 */
9858 	ASSERT(bp->b_un.b_addr == 0);
9859 
9860 	bp->b_edev = 0;
9861 	bp->b_dev = 0;
9862 	bp->b_lblkno = lbtodb(io_off);
9863 	bp->b_file = vp;
9864 	bp->b_offset = (offset_t)blkoff;
9865 	bp_mapin(bp);
9866 
9867 	/*
9868 	 * If doing a write beyond what we believe is EOF, don't bother trying
9869 	 * to read the pages from the server, we'll just zero the pages here.
9870 	 * We don't check that the rw flag is S_WRITE here because some
9871 	 * implementations may attempt a read access to the buffer before
9872 	 * copying data.
9873 	 */
9874 	mutex_enter(&rp->r_statelock);
9875 	if (io_off >= rp->r_size && seg == segkmap) {
9876 		mutex_exit(&rp->r_statelock);
9877 		bzero(bp->b_un.b_addr, io_len);
9878 		error = 0;
9879 	} else {
9880 		mutex_exit(&rp->r_statelock);
9881 		error = nfs4_bio(bp, NULL, cr, TRUE);
9882 		if (error == NFS_EOF)
9883 			error = 0;
9884 	}
9885 
9886 	/*
9887 	 * Unmap the buffer before freeing it.
9888 	 */
9889 	bp_mapout(bp);
9890 	pageio_done(bp);
9891 
9892 	savepp = pp;
9893 	do {
9894 		pp->p_fsdata = C_NOCOMMIT;
9895 	} while ((pp = pp->p_next) != savepp);
9896 
9897 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
9898 
9899 	/*
9900 	 * In case of error set readahead offset
9901 	 * to the lowest offset.
9902 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
9903 	 */
9904 	if (error && rp->r_nextr > io_off) {
9905 		mutex_enter(&rp->r_statelock);
9906 		if (rp->r_nextr > io_off)
9907 			rp->r_nextr = io_off;
9908 		mutex_exit(&rp->r_statelock);
9909 	}
9910 }
9911 
9912 /*
9913  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
9914  * If len == 0, do from off to EOF.
9915  *
9916  * The normal cases should be len == 0 && off == 0 (entire vp list) or
9917  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
9918  * (from pageout).
9919  */
9920 static int
9921 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr)
9922 {
9923 	int error;
9924 	rnode4_t *rp;
9925 
9926 	ASSERT(cr != NULL);
9927 
9928 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
9929 		return (EIO);
9930 
9931 	rp = VTOR4(vp);
9932 	if (IS_SHADOW(vp, rp))
9933 		vp = RTOV4(rp);
9934 
9935 	/*
9936 	 * XXX - Why should this check be made here?
9937 	 */
9938 	if (vp->v_flag & VNOMAP)
9939 		return (ENOSYS);
9940 
9941 	if (len == 0 && !(flags & B_INVAL) &&
9942 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
9943 		return (0);
9944 
9945 	mutex_enter(&rp->r_statelock);
9946 	rp->r_count++;
9947 	mutex_exit(&rp->r_statelock);
9948 	error = nfs4_putpages(vp, off, len, flags, cr);
9949 	mutex_enter(&rp->r_statelock);
9950 	rp->r_count--;
9951 	cv_broadcast(&rp->r_cv);
9952 	mutex_exit(&rp->r_statelock);
9953 
9954 	return (error);
9955 }
9956 
9957 /*
9958  * Write out a single page, possibly klustering adjacent dirty pages.
9959  */
9960 int
9961 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
9962 	int flags, cred_t *cr)
9963 {
9964 	u_offset_t io_off;
9965 	u_offset_t lbn_off;
9966 	u_offset_t lbn;
9967 	size_t io_len;
9968 	uint_t bsize;
9969 	int error;
9970 	rnode4_t *rp;
9971 
9972 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
9973 	ASSERT(pp != NULL);
9974 	ASSERT(cr != NULL);
9975 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
9976 
9977 	rp = VTOR4(vp);
9978 	ASSERT(rp->r_count > 0);
9979 	ASSERT(!IS_SHADOW(vp, rp));
9980 
9981 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9982 	lbn = pp->p_offset / bsize;
9983 	lbn_off = lbn * bsize;
9984 
9985 	/*
9986 	 * Find a kluster that fits in one block, or in
9987 	 * one page if pages are bigger than blocks.  If
9988 	 * there is less file space allocated than a whole
9989 	 * page, we'll shorten the i/o request below.
9990 	 */
9991 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
9992 	    roundup(bsize, PAGESIZE), flags);
9993 
9994 	/*
9995 	 * pvn_write_kluster shouldn't have returned a page with offset
9996 	 * behind the original page we were given.  Verify that.
9997 	 */
9998 	ASSERT((pp->p_offset / bsize) >= lbn);
9999 
10000 	/*
10001 	 * Now pp will have the list of kept dirty pages marked for
10002 	 * write back.  It will also handle invalidation and freeing
10003 	 * of pages that are not dirty.  Check for page length rounding
10004 	 * problems.
10005 	 */
10006 	if (io_off + io_len > lbn_off + bsize) {
10007 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10008 		io_len = lbn_off + bsize - io_off;
10009 	}
10010 	/*
10011 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10012 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10013 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10014 	 * progress and the r_size has not been made consistent with the
10015 	 * new size of the file. When the uiomove() completes the r_size is
10016 	 * updated and the R4MODINPROGRESS flag is cleared.
10017 	 *
10018 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10019 	 * consistent value of r_size. Without this handshaking, it is
10020 	 * possible that nfs4_bio() picks  up the old value of r_size
10021 	 * before the uiomove() in writerp4() completes. This will result
10022 	 * in the write through nfs4_bio() being dropped.
10023 	 *
10024 	 * More precisely, there is a window between the time the uiomove()
10025 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10026 	 * operation intervenes in this window, the page will be picked up,
10027 	 * because it is dirty (it will be unlocked, unless it was
10028 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10029 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10030 	 * checked. This will still be the old size. Therefore the page will
10031 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10032 	 * the page will be found to be clean and the write will be dropped.
10033 	 */
10034 	if (rp->r_flags & R4MODINPROGRESS) {
10035 		mutex_enter(&rp->r_statelock);
10036 		if ((rp->r_flags & R4MODINPROGRESS) &&
10037 		    rp->r_modaddr + MAXBSIZE > io_off &&
10038 		    rp->r_modaddr < io_off + io_len) {
10039 			page_t *plist;
10040 			/*
10041 			 * A write is in progress for this region of the file.
10042 			 * If we did not detect R4MODINPROGRESS here then this
10043 			 * path through nfs_putapage() would eventually go to
10044 			 * nfs4_bio() and may not write out all of the data
10045 			 * in the pages. We end up losing data. So we decide
10046 			 * to set the modified bit on each page in the page
10047 			 * list and mark the rnode with R4DIRTY. This write
10048 			 * will be restarted at some later time.
10049 			 */
10050 			plist = pp;
10051 			while (plist != NULL) {
10052 				pp = plist;
10053 				page_sub(&plist, pp);
10054 				hat_setmod(pp);
10055 				page_io_unlock(pp);
10056 				page_unlock(pp);
10057 			}
10058 			rp->r_flags |= R4DIRTY;
10059 			mutex_exit(&rp->r_statelock);
10060 			if (offp)
10061 				*offp = io_off;
10062 			if (lenp)
10063 				*lenp = io_len;
10064 			return (0);
10065 		}
10066 		mutex_exit(&rp->r_statelock);
10067 	}
10068 
10069 	if (flags & B_ASYNC) {
10070 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10071 		    nfs4_sync_putapage);
10072 	} else
10073 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10074 
10075 	if (offp)
10076 		*offp = io_off;
10077 	if (lenp)
10078 		*lenp = io_len;
10079 	return (error);
10080 }
10081 
10082 static int
10083 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10084 	int flags, cred_t *cr)
10085 {
10086 	int error;
10087 	rnode4_t *rp;
10088 
10089 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10090 
10091 	flags |= B_WRITE;
10092 
10093 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10094 
10095 	rp = VTOR4(vp);
10096 
10097 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10098 	    error == EACCES) &&
10099 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10100 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10101 			mutex_enter(&rp->r_statelock);
10102 			rp->r_flags |= R4OUTOFSPACE;
10103 			mutex_exit(&rp->r_statelock);
10104 		}
10105 		flags |= B_ERROR;
10106 		pvn_write_done(pp, flags);
10107 		/*
10108 		 * If this was not an async thread, then try again to
10109 		 * write out the pages, but this time, also destroy
10110 		 * them whether or not the write is successful.  This
10111 		 * will prevent memory from filling up with these
10112 		 * pages and destroying them is the only alternative
10113 		 * if they can't be written out.
10114 		 *
10115 		 * Don't do this if this is an async thread because
10116 		 * when the pages are unlocked in pvn_write_done,
10117 		 * some other thread could have come along, locked
10118 		 * them, and queued for an async thread.  It would be
10119 		 * possible for all of the async threads to be tied
10120 		 * up waiting to lock the pages again and they would
10121 		 * all already be locked and waiting for an async
10122 		 * thread to handle them.  Deadlock.
10123 		 */
10124 		if (!(flags & B_ASYNC)) {
10125 			error = nfs4_putpage(vp, io_off, io_len,
10126 			    B_INVAL | B_FORCE, cr);
10127 		}
10128 	} else {
10129 		if (error)
10130 			flags |= B_ERROR;
10131 		else if (rp->r_flags & R4OUTOFSPACE) {
10132 			mutex_enter(&rp->r_statelock);
10133 			rp->r_flags &= ~R4OUTOFSPACE;
10134 			mutex_exit(&rp->r_statelock);
10135 		}
10136 		pvn_write_done(pp, flags);
10137 		if (freemem < desfree)
10138 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10139 					NFS4_WRITE_NOWAIT);
10140 	}
10141 
10142 	return (error);
10143 }
10144 
10145 #ifdef DEBUG
10146 int nfs4_force_open_before_mmap = 0;
10147 #endif
10148 
10149 static int
10150 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10151 	size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr)
10152 {
10153 	struct segvn_crargs vn_a;
10154 	int error = 0;
10155 	rnode4_t *rp = VTOR4(vp);
10156 	mntinfo4_t *mi = VTOMI4(vp);
10157 
10158 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10159 		return (EIO);
10160 
10161 	if (vp->v_flag & VNOMAP)
10162 		return (ENOSYS);
10163 
10164 	if (off < 0 || (off + len) < 0)
10165 		return (ENXIO);
10166 
10167 	if (vp->v_type != VREG)
10168 		return (ENODEV);
10169 
10170 	/*
10171 	 * If the file is delegated to the client don't do anything.
10172 	 * If the file is not delegated, then validate the data cache.
10173 	 */
10174 	mutex_enter(&rp->r_statev4_lock);
10175 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10176 		mutex_exit(&rp->r_statev4_lock);
10177 		error = nfs4_validate_caches(vp, cr);
10178 		if (error)
10179 			return (error);
10180 	} else {
10181 		mutex_exit(&rp->r_statev4_lock);
10182 	}
10183 
10184 	/*
10185 	 * Check to see if the vnode is currently marked as not cachable.
10186 	 * This means portions of the file are locked (through VOP_FRLOCK).
10187 	 * In this case the map request must be refused.  We use
10188 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10189 	 */
10190 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
10191 		return (EINTR);
10192 
10193 	if (vp->v_flag & VNOCACHE) {
10194 		error = EAGAIN;
10195 		goto done;
10196 	}
10197 
10198 	/*
10199 	 * Don't allow concurrent locks and mapping if mandatory locking is
10200 	 * enabled.
10201 	 */
10202 	if (flk_has_remote_locks(vp)) {
10203 		struct vattr va;
10204 		va.va_mask = AT_MODE;
10205 		error = nfs4getattr(vp, &va, cr);
10206 		if (error != 0)
10207 			goto done;
10208 		if (MANDLOCK(vp, va.va_mode)) {
10209 			error = EAGAIN;
10210 			goto done;
10211 		}
10212 	}
10213 
10214 	/*
10215 	 * It is possible that the rnode has a lost lock request that we
10216 	 * are still trying to recover, and that the request conflicts with
10217 	 * this map request.
10218 	 *
10219 	 * An alternative approach would be for nfs4_safemap() to consider
10220 	 * queued lock requests when deciding whether to set or clear
10221 	 * VNOCACHE.  This would require the frlock code path to call
10222 	 * nfs4_safemap() after enqueing a lost request.
10223 	 */
10224 	if (nfs4_map_lost_lock_conflict(vp)) {
10225 		error = EAGAIN;
10226 		goto done;
10227 	}
10228 
10229 	as_rangelock(as);
10230 	if (!(flags & MAP_FIXED)) {
10231 		map_addr(addrp, len, off, 1, flags);
10232 		if (*addrp == NULL) {
10233 			as_rangeunlock(as);
10234 			error = ENOMEM;
10235 			goto done;
10236 		}
10237 	} else {
10238 		/*
10239 		 * User specified address - blow away any previous mappings
10240 		 */
10241 		(void) as_unmap(as, *addrp, len);
10242 	}
10243 
10244 	if (vp->v_type == VREG) {
10245 		/*
10246 		 * We need to retrieve the open stream
10247 		 */
10248 		nfs4_open_stream_t	*osp = NULL;
10249 		nfs4_open_owner_t	*oop = NULL;
10250 
10251 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10252 		if (oop != NULL) {
10253 			/* returns with 'os_sync_lock' held */
10254 			osp = find_open_stream(oop, rp);
10255 			open_owner_rele(oop);
10256 		}
10257 		if (osp == NULL) {
10258 #ifdef DEBUG
10259 			if (nfs4_force_open_before_mmap) {
10260 				error = EIO;
10261 				goto done;
10262 			}
10263 #endif
10264 			/* returns with 'os_sync_lock' held */
10265 			osp = open_and_get_osp(vp, cr, mi);
10266 			if (osp == NULL) {
10267 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10268 				    "nfs4_map: we tried to OPEN the file "
10269 				    "but again no osp, so fail with EIO"));
10270 				error = EIO;
10271 				goto done;
10272 			}
10273 		}
10274 
10275 		if (osp->os_failed_reopen) {
10276 			mutex_exit(&osp->os_sync_lock);
10277 			open_stream_rele(osp, rp);
10278 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10279 			    "nfs4_map: os_failed_reopen set on "
10280 			    "osp %p, cr %p, rp %s", (void *)osp,
10281 			    (void *)cr, rnode4info(rp)));
10282 			error = EIO;
10283 			goto done;
10284 		}
10285 		mutex_exit(&osp->os_sync_lock);
10286 		open_stream_rele(osp, rp);
10287 	}
10288 
10289 	vn_a.vp = vp;
10290 	vn_a.offset = off;
10291 	vn_a.type = (flags & MAP_TYPE);
10292 	vn_a.prot = (uchar_t)prot;
10293 	vn_a.maxprot = (uchar_t)maxprot;
10294 	vn_a.flags = (flags & ~MAP_TYPE);
10295 	vn_a.cred = cr;
10296 	vn_a.amp = NULL;
10297 	vn_a.szc = 0;
10298 	vn_a.lgrp_mem_policy_flags = 0;
10299 
10300 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10301 	as_rangeunlock(as);
10302 
10303 done:
10304 	nfs_rw_exit(&rp->r_lkserlock);
10305 	return (error);
10306 }
10307 
10308 /*
10309  * We're most likely dealing with a kernel module that likes to READ
10310  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10311  * officially OPEN the file to create the necessary client state
10312  * for bookkeeping of os_mmap_read/write counts.
10313  *
10314  * Since VOP_MAP only passes in a pointer to the vnode rather than
10315  * a double pointer, we can't handle the case where nfs4open_otw()
10316  * returns a different vnode than the one passed into VOP_MAP (since
10317  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10318  * we return NULL and let nfs4_map() fail.  Note: the only case where
10319  * this should happen is if the file got removed and replaced with the
10320  * same name on the server (in addition to the fact that we're trying
10321  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10322  */
10323 static nfs4_open_stream_t *
10324 open_and_get_osp(vnode_t *map_vp, cred_t *cr, mntinfo4_t *mi)
10325 {
10326 	rnode4_t		*rp, *drp;
10327 	vnode_t			*dvp, *open_vp;
10328 	char			*file_name;
10329 	int			just_created;
10330 	nfs4_sharedfh_t		*sfh;
10331 	nfs4_open_stream_t	*osp;
10332 	nfs4_open_owner_t	*oop;
10333 
10334 	open_vp = map_vp;
10335 	sfh = (open_vp->v_flag & VROOT) ? mi->mi_srvparentfh :
10336 				VTOSV(open_vp)->sv_dfh;
10337 	drp = r4find_unlocked(sfh, open_vp->v_vfsp);
10338 	if (!drp)
10339 		return (NULL);
10340 
10341 	file_name = fn_name(VTOSV(open_vp)->sv_name);
10342 
10343 	rp = VTOR4(open_vp);
10344 	dvp = RTOV4(drp);
10345 	mutex_enter(&rp->r_statev4_lock);
10346 	if (rp->created_v4) {
10347 		rp->created_v4 = 0;
10348 		mutex_exit(&rp->r_statev4_lock);
10349 
10350 		dnlc_update(dvp, file_name, open_vp);
10351 		/* This is needed so we don't bump the open ref count */
10352 		just_created = 1;
10353 	} else {
10354 		mutex_exit(&rp->r_statev4_lock);
10355 		just_created = 0;
10356 	}
10357 
10358 	VN_HOLD(map_vp);
10359 
10360 	if (nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10361 	    just_created)) {
10362 		kmem_free(file_name, MAXNAMELEN);
10363 		VN_RELE(dvp);
10364 		VN_RELE(map_vp);
10365 		return (NULL);
10366 	}
10367 
10368 	kmem_free(file_name, MAXNAMELEN);
10369 	VN_RELE(dvp);
10370 
10371 	/*
10372 	 * If nfs4open_otw() returned a different vnode then "undo"
10373 	 * the open and return failure to the caller.
10374 	 */
10375 	if (!VN_CMP(open_vp, map_vp)) {
10376 		nfs4_error_t e;
10377 
10378 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10379 		    "open returned a different vnode"));
10380 		/*
10381 		 * If there's an error, ignore it,
10382 		 * and let VOP_INACTIVE handle it.
10383 		 */
10384 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10385 				CLOSE_NORM, 0, 0, 0);
10386 		VN_RELE(map_vp);
10387 		return (NULL);
10388 	}
10389 
10390 	VN_RELE(map_vp);
10391 
10392 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10393 	if (!oop) {
10394 		nfs4_error_t e;
10395 
10396 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10397 		    "no open owner"));
10398 		/*
10399 		 * If there's an error, ignore it,
10400 		 * and let VOP_INACTIVE handle it.
10401 		 */
10402 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10403 				CLOSE_NORM, 0, 0, 0);
10404 		return (NULL);
10405 	}
10406 	osp = find_open_stream(oop, rp);
10407 	open_owner_rele(oop);
10408 	return (osp);
10409 }
10410 
10411 /*
10412  * Please be aware that when this function is called, the address space write
10413  * a_lock is held.  Do not put over the wire calls in this function.
10414  */
10415 /* ARGSUSED */
10416 static int
10417 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10418 	size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr)
10419 {
10420 	rnode4_t		*rp;
10421 	int			error = 0;
10422 	mntinfo4_t		*mi;
10423 
10424 	mi = VTOMI4(vp);
10425 	rp = VTOR4(vp);
10426 
10427 	if (nfs_zone() != mi->mi_zone)
10428 		return (EIO);
10429 	if (vp->v_flag & VNOMAP)
10430 		return (ENOSYS);
10431 
10432 	/*
10433 	 * Need to hold rwlock while incrementing the mapcnt so that
10434 	 * mmap'ing can be serialized with writes so that the caching
10435 	 * can be handled correctly.
10436 	 *
10437 	 * Don't need to update the open stream first, since this
10438 	 * mmap can't add any additional share access that isn't
10439 	 * already contained in the open stream (for the case where we
10440 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10441 	 * take into account os_mmap_read[write] counts).
10442 	 */
10443 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR(vp)))
10444 		return (EINTR);
10445 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10446 	nfs_rw_exit(&rp->r_rwlock);
10447 
10448 	if (vp->v_type == VREG) {
10449 		/*
10450 		 * We need to retrieve the open stream and update the counts.
10451 		 * If there is no open stream here, something is wrong.
10452 		 */
10453 		nfs4_open_stream_t	*osp = NULL;
10454 		nfs4_open_owner_t	*oop = NULL;
10455 
10456 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10457 		if (oop != NULL) {
10458 			/* returns with 'os_sync_lock' held */
10459 			osp = find_open_stream(oop, rp);
10460 			open_owner_rele(oop);
10461 		}
10462 		if (osp == NULL) {
10463 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10464 			    "nfs4_addmap: we should have an osp"
10465 			    "but we don't, so fail with EIO"));
10466 			error = EIO;
10467 			goto out;
10468 		}
10469 
10470 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10471 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10472 
10473 		/*
10474 		 * Update the map count in the open stream.
10475 		 * This is necessary in the case where we
10476 		 * open/mmap/close/, then the server reboots, and we
10477 		 * attempt to reopen.  If the mmap doesn't add share
10478 		 * access then we send an invalid reopen with
10479 		 * access = NONE.
10480 		 *
10481 		 * We need to specifically check each PROT_* so a mmap
10482 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10483 		 * read and write access.  A simple comparison of prot
10484 		 * to ~PROT_WRITE to determine read access is insufficient
10485 		 * since prot can be |= with PROT_USER, etc.
10486 		 */
10487 
10488 		/*
10489 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10490 		 */
10491 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10492 			osp->os_mmap_write += btopr(len);
10493 		if (maxprot & PROT_READ)
10494 			osp->os_mmap_read += btopr(len);
10495 		if (maxprot & PROT_EXEC)
10496 			osp->os_mmap_read += btopr(len);
10497 		/*
10498 		 * Ensure that os_mmap_read gets incremented, even if
10499 		 * maxprot were to look like PROT_NONE.
10500 		 */
10501 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10502 		    !(maxprot & PROT_EXEC))
10503 			osp->os_mmap_read += btopr(len);
10504 		osp->os_mapcnt += btopr(len);
10505 		mutex_exit(&osp->os_sync_lock);
10506 		open_stream_rele(osp, rp);
10507 	}
10508 
10509 out:
10510 	/*
10511 	 * If we got an error, then undo our
10512 	 * incrementing of 'r_mapcnt'.
10513 	 */
10514 
10515 	if (error) {
10516 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10517 		ASSERT(rp->r_mapcnt >= 0);
10518 	}
10519 	return (error);
10520 }
10521 
10522 static int
10523 nfs4_cmp(vnode_t *vp1, vnode_t *vp2)
10524 {
10525 
10526 	return (VTOR4(vp1) == VTOR4(vp2));
10527 }
10528 
10529 static int
10530 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10531 	offset_t offset, struct flk_callback *flk_cbp, cred_t *cr)
10532 {
10533 	int rc;
10534 	u_offset_t start, end;
10535 	rnode4_t *rp;
10536 	int error = 0, intr = INTR4(vp);
10537 	nfs4_error_t e;
10538 
10539 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10540 		return (EIO);
10541 
10542 	/* check for valid cmd parameter */
10543 	if (cmd != F_GETLK && cmd != F_SETLK && cmd != F_SETLKW)
10544 		return (EINVAL);
10545 
10546 	/* Verify l_type. */
10547 	switch (bfp->l_type) {
10548 	case F_RDLCK:
10549 		if (cmd != F_GETLK && !(flag & FREAD))
10550 			return (EBADF);
10551 		break;
10552 	case F_WRLCK:
10553 		if (cmd != F_GETLK && !(flag & FWRITE))
10554 			return (EBADF);
10555 		break;
10556 	case F_UNLCK:
10557 		intr = 0;
10558 		break;
10559 
10560 	default:
10561 		return (EINVAL);
10562 	}
10563 
10564 	/* check the validity of the lock range */
10565 	if (rc = flk_convert_lock_data(vp, bfp, &start, &end, offset))
10566 		return (rc);
10567 	if (rc = flk_check_lock_data(start, end, MAXEND))
10568 		return (rc);
10569 
10570 	/*
10571 	 * If the filesystem is mounted using local locking, pass the
10572 	 * request off to the local locking code.
10573 	 */
10574 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10575 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10576 			/*
10577 			 * For complete safety, we should be holding
10578 			 * r_lkserlock.  However, we can't call
10579 			 * nfs4_safelock and then fs_frlock while
10580 			 * holding r_lkserlock, so just invoke
10581 			 * nfs4_safelock and expect that this will
10582 			 * catch enough of the cases.
10583 			 */
10584 			if (!nfs4_safelock(vp, bfp, cr))
10585 				return (EAGAIN);
10586 		}
10587 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr));
10588 	}
10589 
10590 	rp = VTOR4(vp);
10591 
10592 	/*
10593 	 * Check whether the given lock request can proceed, given the
10594 	 * current file mappings.
10595 	 */
10596 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr))
10597 		return (EINTR);
10598 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10599 		if (!nfs4_safelock(vp, bfp, cr)) {
10600 			rc = EAGAIN;
10601 			goto done;
10602 		}
10603 	}
10604 
10605 	/*
10606 	 * Flush the cache after waiting for async I/O to finish.  For new
10607 	 * locks, this is so that the process gets the latest bits from the
10608 	 * server.  For unlocks, this is so that other clients see the
10609 	 * latest bits once the file has been unlocked.  If currently dirty
10610 	 * pages can't be flushed, then don't allow a lock to be set.  But
10611 	 * allow unlocks to succeed, to avoid having orphan locks on the
10612 	 * server.
10613 	 */
10614 	if (cmd != F_GETLK) {
10615 		mutex_enter(&rp->r_statelock);
10616 		while (rp->r_count > 0) {
10617 		    if (intr) {
10618 			klwp_t *lwp = ttolwp(curthread);
10619 
10620 			if (lwp != NULL)
10621 				lwp->lwp_nostop++;
10622 			if (cv_wait_sig(&rp->r_cv, &rp->r_statelock) == 0) {
10623 				if (lwp != NULL)
10624 					lwp->lwp_nostop--;
10625 				rc = EINTR;
10626 				break;
10627 			}
10628 			if (lwp != NULL)
10629 				lwp->lwp_nostop--;
10630 		    } else
10631 			cv_wait(&rp->r_cv, &rp->r_statelock);
10632 		}
10633 		mutex_exit(&rp->r_statelock);
10634 		if (rc != 0)
10635 			goto done;
10636 		error = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr);
10637 		if (error) {
10638 			if (error == ENOSPC || error == EDQUOT) {
10639 				mutex_enter(&rp->r_statelock);
10640 				if (!rp->r_error)
10641 					rp->r_error = error;
10642 				mutex_exit(&rp->r_statelock);
10643 			}
10644 			if (bfp->l_type != F_UNLCK) {
10645 				rc = ENOLCK;
10646 				goto done;
10647 			}
10648 		}
10649 	}
10650 
10651 	/*
10652 	 * Call the lock manager to do the real work of contacting
10653 	 * the server and obtaining the lock.
10654 	 */
10655 
10656 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, flag, offset,
10657 		cr, &e, NULL, NULL);
10658 	rc = e.error;
10659 
10660 	if (rc == 0)
10661 		nfs4_lockcompletion(vp, cmd);
10662 
10663 done:
10664 	nfs_rw_exit(&rp->r_lkserlock);
10665 
10666 	return (rc);
10667 }
10668 
10669 /*
10670  * Free storage space associated with the specified vnode.  The portion
10671  * to be freed is specified by bfp->l_start and bfp->l_len (already
10672  * normalized to a "whence" of 0).
10673  *
10674  * This is an experimental facility whose continued existence is not
10675  * guaranteed.  Currently, we only support the special case
10676  * of l_len == 0, meaning free to end of file.
10677  */
10678 /* ARGSUSED */
10679 static int
10680 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10681 	offset_t offset, cred_t *cr, caller_context_t *ct)
10682 {
10683 	int error;
10684 
10685 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10686 		return (EIO);
10687 	ASSERT(vp->v_type == VREG);
10688 	if (cmd != F_FREESP)
10689 		return (EINVAL);
10690 
10691 	error = convoff(vp, bfp, 0, offset);
10692 	if (!error) {
10693 		ASSERT(bfp->l_start >= 0);
10694 		if (bfp->l_len == 0) {
10695 			struct vattr va;
10696 
10697 			va.va_mask = AT_SIZE;
10698 			va.va_size = bfp->l_start;
10699 			error = nfs4setattr(vp, &va, 0, cr, NULL);
10700 		} else
10701 			error = EINVAL;
10702 	}
10703 
10704 	return (error);
10705 }
10706 
10707 /* ARGSUSED */
10708 static int
10709 nfs4_realvp(vnode_t *vp, vnode_t **vpp)
10710 {
10711 	return (EINVAL);
10712 }
10713 
10714 /*
10715  * Setup and add an address space callback to do the work of the delmap call.
10716  * The callback will (and must be) deleted in the actual callback function.
10717  *
10718  * This is done in order to take care of the problem that we have with holding
10719  * the address space's a_lock for a long period of time (e.g. if the NFS server
10720  * is down).  Callbacks will be executed in the address space code while the
10721  * a_lock is not held.  Holding the address space's a_lock causes things such
10722  * as ps and fork to hang because they are trying to acquire this lock as well.
10723  */
10724 /* ARGSUSED */
10725 static int
10726 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10727 	size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr)
10728 {
10729 	int			caller_found;
10730 	int			error;
10731 	rnode4_t		*rp;
10732 	nfs4_delmap_args_t	*dmapp;
10733 	nfs4_delmapcall_t	*delmap_call;
10734 
10735 	if (vp->v_flag & VNOMAP)
10736 		return (ENOSYS);
10737 
10738 	/*
10739 	 * A process may not change zones if it has NFS pages mmap'ed
10740 	 * in, so we can't legitimately get here from the wrong zone.
10741 	 */
10742 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10743 
10744 	rp = VTOR4(vp);
10745 
10746 	/*
10747 	 * The way that the address space of this process deletes its mapping
10748 	 * of this file is via the following call chains:
10749 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10750 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10751 	 *
10752 	 * With the use of address space callbacks we are allowed to drop the
10753 	 * address space lock, a_lock, while executing the NFS operations that
10754 	 * need to go over the wire.  Returning EAGAIN to the caller of this
10755 	 * function is what drives the execution of the callback that we add
10756 	 * below.  The callback will be executed by the address space code
10757 	 * after dropping the a_lock.  When the callback is finished, since
10758 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
10759 	 * is called again on the same segment to finish the rest of the work
10760 	 * that needs to happen during unmapping.
10761 	 *
10762 	 * This action of calling back into the segment driver causes
10763 	 * nfs4_delmap() to get called again, but since the callback was
10764 	 * already executed at this point, it already did the work and there
10765 	 * is nothing left for us to do.
10766 	 *
10767 	 * To Summarize:
10768 	 * - The first time nfs4_delmap is called by the current thread is when
10769 	 * we add the caller associated with this delmap to the delmap caller
10770 	 * list, add the callback, and return EAGAIN.
10771 	 * - The second time in this call chain when nfs4_delmap is called we
10772 	 * will find this caller in the delmap caller list and realize there
10773 	 * is no more work to do thus removing this caller from the list and
10774 	 * returning the error that was set in the callback execution.
10775 	 */
10776 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
10777 	if (caller_found) {
10778 		/*
10779 		 * 'error' is from the actual delmap operations.  To avoid
10780 		 * hangs, we need to handle the return of EAGAIN differently
10781 		 * since this is what drives the callback execution.
10782 		 * In this case, we don't want to return EAGAIN and do the
10783 		 * callback execution because there are none to execute.
10784 		 */
10785 		if (error == EAGAIN)
10786 			return (0);
10787 		else
10788 			return (error);
10789 	}
10790 
10791 	/* current caller was not in the list */
10792 	delmap_call = nfs4_init_delmapcall();
10793 
10794 	mutex_enter(&rp->r_statelock);
10795 	list_insert_tail(&rp->r_indelmap, delmap_call);
10796 	mutex_exit(&rp->r_statelock);
10797 
10798 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
10799 
10800 	dmapp->vp = vp;
10801 	dmapp->off = off;
10802 	dmapp->addr = addr;
10803 	dmapp->len = len;
10804 	dmapp->prot = prot;
10805 	dmapp->maxprot = maxprot;
10806 	dmapp->flags = flags;
10807 	dmapp->cr = cr;
10808 	dmapp->caller = delmap_call;
10809 
10810 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
10811 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
10812 
10813 	return (error ? error : EAGAIN);
10814 }
10815 
10816 static nfs4_delmapcall_t *
10817 nfs4_init_delmapcall()
10818 {
10819 	nfs4_delmapcall_t	*delmap_call;
10820 
10821 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
10822 	delmap_call->call_id = curthread;
10823 	delmap_call->error = 0;
10824 
10825 	return (delmap_call);
10826 }
10827 
10828 static void
10829 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
10830 {
10831 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
10832 }
10833 
10834 /*
10835  * Searches for the current delmap caller (based on curthread) in the list of
10836  * callers.  If it is found, we remove it and free the delmap caller.
10837  * Returns:
10838  *      0 if the caller wasn't found
10839  *      1 if the caller was found, removed and freed.  *errp will be set
10840  *	to what the result of the delmap was.
10841  */
10842 static int
10843 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
10844 {
10845 	nfs4_delmapcall_t	*delmap_call;
10846 
10847 	/*
10848 	 * If the list doesn't exist yet, we create it and return
10849 	 * that the caller wasn't found.  No list = no callers.
10850 	 */
10851 	mutex_enter(&rp->r_statelock);
10852 	if (!(rp->r_flags & R4DELMAPLIST)) {
10853 		/* The list does not exist */
10854 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
10855 		    offsetof(nfs4_delmapcall_t, call_node));
10856 		rp->r_flags |= R4DELMAPLIST;
10857 		mutex_exit(&rp->r_statelock);
10858 		return (0);
10859 	} else {
10860 		/* The list exists so search it */
10861 		for (delmap_call = list_head(&rp->r_indelmap);
10862 		    delmap_call != NULL;
10863 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
10864 			if (delmap_call->call_id == curthread) {
10865 				/* current caller is in the list */
10866 				*errp = delmap_call->error;
10867 				list_remove(&rp->r_indelmap, delmap_call);
10868 				mutex_exit(&rp->r_statelock);
10869 				nfs4_free_delmapcall(delmap_call);
10870 				return (1);
10871 			}
10872 		}
10873 	}
10874 	mutex_exit(&rp->r_statelock);
10875 	return (0);
10876 }
10877 
10878 /*
10879  * Remove some pages from an mmap'd vnode.  Just update the
10880  * count of pages.  If doing close-to-open, then flush and
10881  * commit all of the pages associated with this file.
10882  * Otherwise, start an asynchronous page flush to write out
10883  * any dirty pages.  This will also associate a credential
10884  * with the rnode which can be used to write the pages.
10885  */
10886 /* ARGSUSED */
10887 static void
10888 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
10889 {
10890 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
10891 	rnode4_t		*rp;
10892 	mntinfo4_t		*mi;
10893 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
10894 
10895 	rp = VTOR4(dmapp->vp);
10896 	mi = VTOMI4(dmapp->vp);
10897 
10898 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
10899 	ASSERT(rp->r_mapcnt >= 0);
10900 
10901 	/*
10902 	 * Initiate a page flush and potential commit if there are
10903 	 * pages, the file system was not mounted readonly, the segment
10904 	 * was mapped shared, and the pages themselves were writeable.
10905 	 */
10906 	if (nfs4_has_pages(dmapp->vp) &&
10907 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
10908 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
10909 		mutex_enter(&rp->r_statelock);
10910 		rp->r_flags |= R4DIRTY;
10911 		mutex_exit(&rp->r_statelock);
10912 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
10913 		    dmapp->len, dmapp->cr);
10914 		if (!e.error) {
10915 			mutex_enter(&rp->r_statelock);
10916 			e.error = rp->r_error;
10917 			rp->r_error = 0;
10918 			mutex_exit(&rp->r_statelock);
10919 		}
10920 	} else
10921 		e.error = 0;
10922 
10923 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
10924 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
10925 		    B_INVAL, dmapp->cr);
10926 
10927 	if (e.error) {
10928 		e.stat = puterrno4(e.error);
10929 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
10930 			OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
10931 		dmapp->caller->error = e.error;
10932 	}
10933 
10934 	/* Check to see if we need to close the file */
10935 
10936 	if (dmapp->vp->v_type == VREG) {
10937 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
10938 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
10939 
10940 		if (e.error != 0 || e.stat != NFS4_OK) {
10941 			/*
10942 			 * Since it is possible that e.error == 0 and
10943 			 * e.stat != NFS4_OK (and vice versa),
10944 			 * we do the proper checking in order to get both
10945 			 * e.error and e.stat reporting the correct info.
10946 			 */
10947 			if (e.stat == NFS4_OK)
10948 				e.stat = puterrno4(e.error);
10949 			if (e.error == 0)
10950 				e.error = geterrno4(e.stat);
10951 
10952 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
10953 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
10954 			dmapp->caller->error = e.error;
10955 		}
10956 	}
10957 
10958 	(void) as_delete_callback(as, arg);
10959 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
10960 }
10961 
10962 
10963 static uint_t
10964 fattr4_maxfilesize_to_bits(uint64_t ll)
10965 {
10966 	uint_t l = 1;
10967 
10968 	if (ll == 0) {
10969 		return (0);
10970 	}
10971 
10972 	if (ll & 0xffffffff00000000) {
10973 		l += 32; ll >>= 32;
10974 	}
10975 	if (ll & 0xffff0000) {
10976 		l += 16; ll >>= 16;
10977 	}
10978 	if (ll & 0xff00) {
10979 		l += 8; ll >>= 8;
10980 	}
10981 	if (ll & 0xf0) {
10982 		l += 4; ll >>= 4;
10983 	}
10984 	if (ll & 0xc) {
10985 		l += 2; ll >>= 2;
10986 	}
10987 	if (ll & 0x2) {
10988 		l += 1;
10989 	}
10990 	return (l);
10991 }
10992 
10993 static int
10994 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr)
10995 {
10996 	int error;
10997 	hrtime_t t;
10998 	rnode4_t *rp;
10999 	nfs4_ga_res_t gar;
11000 	nfs4_ga_ext_res_t ger;
11001 
11002 	gar.n4g_ext_res = &ger;
11003 
11004 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11005 		return (EIO);
11006 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11007 		*valp = MAXPATHLEN;
11008 		return (0);
11009 	}
11010 	if (cmd == _PC_ACL_ENABLED) {
11011 		*valp = _ACL_ACE_ENABLED;
11012 		return (0);
11013 	}
11014 
11015 	rp = VTOR4(vp);
11016 	if (cmd == _PC_XATTR_EXISTS) {
11017 		/*
11018 		 * Eventually should attempt small client readdir before
11019 		 * going otw with GETATTR(FATTR4_NAMED_ATTR).  For now
11020 		 * just drive the OTW getattr.  This is required because
11021 		 * _PC_XATTR_EXISTS can only return true if attributes
11022 		 * exist -- simply checking for existance of the attrdir
11023 		 * is not sufficient.
11024 		 *
11025 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11026 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11027 		 * and we don't have any way to update the "base" object's
11028 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11029 		 * could help out.
11030 		 */
11031 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11032 		    rp->r_xattr_dir == NULL) {
11033 			*valp = rp->r_pathconf.pc4_xattr_exists;
11034 			return (0);
11035 		}
11036 	} else {  /* OLD CODE */
11037 		if (ATTRCACHE4_VALID(vp)) {
11038 			mutex_enter(&rp->r_statelock);
11039 			if (rp->r_pathconf.pc4_cache_valid) {
11040 				error = 0;
11041 				switch (cmd) {
11042 				case _PC_FILESIZEBITS:
11043 					*valp =
11044 					rp->r_pathconf.pc4_filesizebits;
11045 					break;
11046 				case _PC_LINK_MAX:
11047 					*valp =
11048 					rp->r_pathconf.pc4_link_max;
11049 					break;
11050 				case _PC_NAME_MAX:
11051 					*valp =
11052 					rp->r_pathconf.pc4_name_max;
11053 					break;
11054 				case _PC_CHOWN_RESTRICTED:
11055 					*valp =
11056 					rp->r_pathconf.pc4_chown_restricted;
11057 					break;
11058 				case _PC_NO_TRUNC:
11059 					*valp =
11060 					rp->r_pathconf.pc4_no_trunc;
11061 					break;
11062 				default:
11063 					error = EINVAL;
11064 					break;
11065 				}
11066 				mutex_exit(&rp->r_statelock);
11067 #ifdef DEBUG
11068 				nfs4_pathconf_cache_hits++;
11069 #endif
11070 				return (error);
11071 			}
11072 			mutex_exit(&rp->r_statelock);
11073 		}
11074 	}
11075 #ifdef DEBUG
11076 	nfs4_pathconf_cache_misses++;
11077 #endif
11078 
11079 	t = gethrtime();
11080 
11081 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11082 
11083 	if (error) {
11084 		mutex_enter(&rp->r_statelock);
11085 		rp->r_pathconf.pc4_cache_valid = FALSE;
11086 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11087 		mutex_exit(&rp->r_statelock);
11088 		return (error);
11089 	}
11090 
11091 	/* interpret the max filesize */
11092 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11093 		fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11094 
11095 	/* Store the attributes we just received */
11096 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11097 
11098 	switch (cmd) {
11099 	case _PC_FILESIZEBITS:
11100 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11101 		break;
11102 	case _PC_LINK_MAX:
11103 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11104 		break;
11105 	case _PC_NAME_MAX:
11106 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11107 		break;
11108 	case _PC_CHOWN_RESTRICTED:
11109 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11110 		break;
11111 	case _PC_NO_TRUNC:
11112 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11113 		break;
11114 	case _PC_XATTR_EXISTS:
11115 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists;
11116 		break;
11117 	default:
11118 		return (EINVAL);
11119 	}
11120 
11121 	return (0);
11122 }
11123 
11124 /*
11125  * Called by async thread to do synchronous pageio. Do the i/o, wait
11126  * for it to complete, and cleanup the page list when done.
11127  */
11128 static int
11129 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11130 	int flags, cred_t *cr)
11131 {
11132 	int error;
11133 
11134 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11135 
11136 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11137 	if (flags & B_READ)
11138 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11139 	else
11140 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11141 	return (error);
11142 }
11143 
11144 static int
11145 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11146 	int flags, cred_t *cr)
11147 {
11148 	int error;
11149 	rnode4_t *rp;
11150 
11151 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11152 		return (EIO);
11153 
11154 	if (pp == NULL)
11155 		return (EINVAL);
11156 
11157 	rp = VTOR4(vp);
11158 	mutex_enter(&rp->r_statelock);
11159 	rp->r_count++;
11160 	mutex_exit(&rp->r_statelock);
11161 
11162 	if (flags & B_ASYNC) {
11163 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11164 		    nfs4_sync_pageio);
11165 	} else
11166 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11167 	mutex_enter(&rp->r_statelock);
11168 	rp->r_count--;
11169 	cv_broadcast(&rp->r_cv);
11170 	mutex_exit(&rp->r_statelock);
11171 	return (error);
11172 }
11173 
11174 static void
11175 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr)
11176 {
11177 	int error;
11178 	rnode4_t *rp;
11179 	page_t *plist;
11180 	page_t *pptr;
11181 	offset3 offset;
11182 	count3 len;
11183 	k_sigset_t smask;
11184 
11185 	/*
11186 	 * We should get called with fl equal to either B_FREE or
11187 	 * B_INVAL.  Any other value is illegal.
11188 	 *
11189 	 * The page that we are either supposed to free or destroy
11190 	 * should be exclusive locked and its io lock should not
11191 	 * be held.
11192 	 */
11193 	ASSERT(fl == B_FREE || fl == B_INVAL);
11194 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11195 
11196 	rp = VTOR4(vp);
11197 
11198 	/*
11199 	 * If the page doesn't need to be committed or we shouldn't
11200 	 * even bother attempting to commit it, then just make sure
11201 	 * that the p_fsdata byte is clear and then either free or
11202 	 * destroy the page as appropriate.
11203 	 */
11204 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11205 		pp->p_fsdata = C_NOCOMMIT;
11206 		if (fl == B_FREE)
11207 			page_free(pp, dn);
11208 		else
11209 			page_destroy(pp, dn);
11210 		return;
11211 	}
11212 
11213 	/*
11214 	 * If there is a page invalidation operation going on, then
11215 	 * if this is one of the pages being destroyed, then just
11216 	 * clear the p_fsdata byte and then either free or destroy
11217 	 * the page as appropriate.
11218 	 */
11219 	mutex_enter(&rp->r_statelock);
11220 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11221 		mutex_exit(&rp->r_statelock);
11222 		pp->p_fsdata = C_NOCOMMIT;
11223 		if (fl == B_FREE)
11224 			page_free(pp, dn);
11225 		else
11226 			page_destroy(pp, dn);
11227 		return;
11228 	}
11229 
11230 	/*
11231 	 * If we are freeing this page and someone else is already
11232 	 * waiting to do a commit, then just unlock the page and
11233 	 * return.  That other thread will take care of commiting
11234 	 * this page.  The page can be freed sometime after the
11235 	 * commit has finished.  Otherwise, if the page is marked
11236 	 * as delay commit, then we may be getting called from
11237 	 * pvn_write_done, one page at a time.   This could result
11238 	 * in one commit per page, so we end up doing lots of small
11239 	 * commits instead of fewer larger commits.  This is bad,
11240 	 * we want do as few commits as possible.
11241 	 */
11242 	if (fl == B_FREE) {
11243 		if (rp->r_flags & R4COMMITWAIT) {
11244 			page_unlock(pp);
11245 			mutex_exit(&rp->r_statelock);
11246 			return;
11247 		}
11248 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11249 			pp->p_fsdata = C_COMMIT;
11250 			page_unlock(pp);
11251 			mutex_exit(&rp->r_statelock);
11252 			return;
11253 		}
11254 	}
11255 
11256 	/*
11257 	 * Check to see if there is a signal which would prevent an
11258 	 * attempt to commit the pages from being successful.  If so,
11259 	 * then don't bother with all of the work to gather pages and
11260 	 * generate the unsuccessful RPC.  Just return from here and
11261 	 * let the page be committed at some later time.
11262 	 */
11263 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11264 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11265 		sigunintr(&smask);
11266 		page_unlock(pp);
11267 		mutex_exit(&rp->r_statelock);
11268 		return;
11269 	}
11270 	sigunintr(&smask);
11271 
11272 	/*
11273 	 * We are starting to need to commit pages, so let's try
11274 	 * to commit as many as possible at once to reduce the
11275 	 * overhead.
11276 	 *
11277 	 * Set the `commit inprogress' state bit.  We must
11278 	 * first wait until any current one finishes.  Then
11279 	 * we initialize the c_pages list with this page.
11280 	 */
11281 	while (rp->r_flags & R4COMMIT) {
11282 		rp->r_flags |= R4COMMITWAIT;
11283 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11284 		rp->r_flags &= ~R4COMMITWAIT;
11285 	}
11286 	rp->r_flags |= R4COMMIT;
11287 	mutex_exit(&rp->r_statelock);
11288 	ASSERT(rp->r_commit.c_pages == NULL);
11289 	rp->r_commit.c_pages = pp;
11290 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11291 	rp->r_commit.c_commlen = PAGESIZE;
11292 
11293 	/*
11294 	 * Gather together all other pages which can be committed.
11295 	 * They will all be chained off r_commit.c_pages.
11296 	 */
11297 	nfs4_get_commit(vp);
11298 
11299 	/*
11300 	 * Clear the `commit inprogress' status and disconnect
11301 	 * the list of pages to be committed from the rnode.
11302 	 * At this same time, we also save the starting offset
11303 	 * and length of data to be committed on the server.
11304 	 */
11305 	plist = rp->r_commit.c_pages;
11306 	rp->r_commit.c_pages = NULL;
11307 	offset = rp->r_commit.c_commbase;
11308 	len = rp->r_commit.c_commlen;
11309 	mutex_enter(&rp->r_statelock);
11310 	rp->r_flags &= ~R4COMMIT;
11311 	cv_broadcast(&rp->r_commit.c_cv);
11312 	mutex_exit(&rp->r_statelock);
11313 
11314 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11315 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11316 		nfs4_async_commit(vp, plist, offset, len,
11317 		    cr, do_nfs4_async_commit);
11318 		return;
11319 	}
11320 
11321 	/*
11322 	 * Actually generate the COMMIT op over the wire operation.
11323 	 */
11324 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11325 
11326 	/*
11327 	 * If we got an error during the commit, just unlock all
11328 	 * of the pages.  The pages will get retransmitted to the
11329 	 * server during a putpage operation.
11330 	 */
11331 	if (error) {
11332 		while (plist != NULL) {
11333 			pptr = plist;
11334 			page_sub(&plist, pptr);
11335 			page_unlock(pptr);
11336 		}
11337 		return;
11338 	}
11339 
11340 	/*
11341 	 * We've tried as hard as we can to commit the data to stable
11342 	 * storage on the server.  We just unlock the rest of the pages
11343 	 * and clear the commit required state.  They will be put
11344 	 * onto the tail of the cachelist if they are nolonger
11345 	 * mapped.
11346 	 */
11347 	while (plist != pp) {
11348 		pptr = plist;
11349 		page_sub(&plist, pptr);
11350 		pptr->p_fsdata = C_NOCOMMIT;
11351 		page_unlock(pptr);
11352 	}
11353 
11354 	/*
11355 	 * It is possible that nfs4_commit didn't return error but
11356 	 * some other thread has modified the page we are going
11357 	 * to free/destroy.
11358 	 *    In this case we need to rewrite the page. Do an explicit check
11359 	 * before attempting to free/destroy the page. If modified, needs to
11360 	 * be rewritten so unlock the page and return.
11361 	 */
11362 	if (hat_ismod(pp)) {
11363 		pp->p_fsdata = C_NOCOMMIT;
11364 		page_unlock(pp);
11365 		return;
11366 	}
11367 
11368 	/*
11369 	 * Now, as appropriate, either free or destroy the page
11370 	 * that we were called with.
11371 	 */
11372 	pp->p_fsdata = C_NOCOMMIT;
11373 	if (fl == B_FREE)
11374 		page_free(pp, dn);
11375 	else
11376 		page_destroy(pp, dn);
11377 }
11378 
11379 /*
11380  * Commit requires that the current fh be the file written to.
11381  * The compound op structure is:
11382  *      PUTFH(file), COMMIT
11383  */
11384 static int
11385 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11386 {
11387 	COMPOUND4args_clnt args;
11388 	COMPOUND4res_clnt res;
11389 	COMMIT4res *cm_res;
11390 	nfs_argop4 argop[2];
11391 	nfs_resop4 *resop;
11392 	int doqueue;
11393 	mntinfo4_t *mi;
11394 	rnode4_t *rp;
11395 	cred_t *cred_otw = NULL;
11396 	bool_t needrecov = FALSE;
11397 	nfs4_recov_state_t recov_state;
11398 	nfs4_open_stream_t *osp = NULL;
11399 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11400 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11401 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11402 
11403 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11404 
11405 	rp = VTOR4(vp);
11406 
11407 	mi = VTOMI4(vp);
11408 	recov_state.rs_flags = 0;
11409 	recov_state.rs_num_retry_despite_err = 0;
11410 get_commit_cred:
11411 	/*
11412 	 * Releases the osp, if a valid open stream is provided.
11413 	 * Puts a hold on the cred_otw and the new osp (if found).
11414 	 */
11415 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11416 			&first_time, &last_time);
11417 	args.ctag = TAG_COMMIT;
11418 recov_retry:
11419 	/*
11420 	 * Commit ops: putfh file; commit
11421 	 */
11422 	args.array_len = 2;
11423 	args.array = argop;
11424 
11425 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11426 			    &recov_state, NULL);
11427 	if (e.error) {
11428 		crfree(cred_otw);
11429 		if (osp != NULL)
11430 			open_stream_rele(osp, rp);
11431 		return (e.error);
11432 	}
11433 
11434 	/* putfh directory */
11435 	argop[0].argop = OP_CPUTFH;
11436 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11437 
11438 	/* commit */
11439 	argop[1].argop = OP_COMMIT;
11440 	argop[1].nfs_argop4_u.opcommit.offset = offset;
11441 	argop[1].nfs_argop4_u.opcommit.count = count;
11442 
11443 	doqueue = 1;
11444 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
11445 
11446 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
11447 	if (!needrecov && e.error) {
11448 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
11449 			needrecov);
11450 		crfree(cred_otw);
11451 		if (e.error == EACCES && last_time == FALSE)
11452 			goto get_commit_cred;
11453 		if (osp != NULL)
11454 			open_stream_rele(osp, rp);
11455 		return (e.error);
11456 	}
11457 
11458 	if (needrecov) {
11459 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
11460 		    NULL, OP_COMMIT, NULL) == FALSE) {
11461 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11462 				&recov_state, needrecov);
11463 			if (!e.error)
11464 				(void) xdr_free(xdr_COMPOUND4res_clnt,
11465 								(caddr_t)&res);
11466 			goto recov_retry;
11467 		}
11468 		if (e.error) {
11469 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11470 				&recov_state, needrecov);
11471 			crfree(cred_otw);
11472 			if (osp != NULL)
11473 				open_stream_rele(osp, rp);
11474 			return (e.error);
11475 		}
11476 		/* fall through for res.status case */
11477 	}
11478 
11479 	if (res.status) {
11480 		e.error = geterrno4(res.status);
11481 		if (e.error == EACCES && last_time == FALSE) {
11482 			crfree(cred_otw);
11483 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11484 				&recov_state, needrecov);
11485 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11486 			goto get_commit_cred;
11487 		}
11488 		/*
11489 		 * Can't do a nfs4_purge_stale_fh here because this
11490 		 * can cause a deadlock.  nfs4_commit can
11491 		 * be called from nfs4_dispose which can be called
11492 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
11493 		 * can call back to pvn_vplist_dirty.
11494 		 */
11495 		if (e.error == ESTALE) {
11496 			mutex_enter(&rp->r_statelock);
11497 			rp->r_flags |= R4STALE;
11498 			if (!rp->r_error)
11499 				rp->r_error = e.error;
11500 			mutex_exit(&rp->r_statelock);
11501 			PURGE_ATTRCACHE4(vp);
11502 		} else {
11503 			mutex_enter(&rp->r_statelock);
11504 			if (!rp->r_error)
11505 				rp->r_error = e.error;
11506 			mutex_exit(&rp->r_statelock);
11507 		}
11508 	} else {
11509 		ASSERT(rp->r_flags & R4HAVEVERF);
11510 		resop = &res.array[1];	/* commit res */
11511 		cm_res = &resop->nfs_resop4_u.opcommit;
11512 		mutex_enter(&rp->r_statelock);
11513 		if (cm_res->writeverf == rp->r_writeverf) {
11514 			mutex_exit(&rp->r_statelock);
11515 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11516 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11517 				&recov_state, needrecov);
11518 			crfree(cred_otw);
11519 			if (osp != NULL)
11520 				open_stream_rele(osp, rp);
11521 			return (0);
11522 		}
11523 		nfs4_set_mod(vp);
11524 		rp->r_writeverf = cm_res->writeverf;
11525 		mutex_exit(&rp->r_statelock);
11526 		e.error = NFS_VERF_MISMATCH;
11527 	}
11528 
11529 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11530 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
11531 	crfree(cred_otw);
11532 	if (osp != NULL)
11533 		open_stream_rele(osp, rp);
11534 
11535 	return (e.error);
11536 }
11537 
11538 static void
11539 nfs4_set_mod(vnode_t *vp)
11540 {
11541 	page_t *pp;
11542 	kmutex_t *vphm;
11543 	rnode4_t *rp;
11544 
11545 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11546 
11547 	/* make sure we're looking at the master vnode, not a shadow */
11548 
11549 	rp = VTOR4(vp);
11550 	if (IS_SHADOW(vp, rp))
11551 		vp = RTOV4(rp);
11552 
11553 	vphm = page_vnode_mutex(vp);
11554 	mutex_enter(vphm);
11555 	/*
11556 	 * If there are no pages associated with this vnode, then
11557 	 * just return.
11558 	 */
11559 	if ((pp = vp->v_pages) == NULL) {
11560 		mutex_exit(vphm);
11561 		return;
11562 	}
11563 
11564 	do {
11565 		if (pp->p_fsdata != C_NOCOMMIT) {
11566 			hat_setmod(pp);
11567 			pp->p_fsdata = C_NOCOMMIT;
11568 		}
11569 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11570 	mutex_exit(vphm);
11571 }
11572 
11573 /*
11574  * This function is used to gather a page list of the pages which
11575  * can be committed on the server.
11576  *
11577  * The calling thread must have set R4COMMIT.  This bit is used to
11578  * serialize access to the commit structure in the rnode.  As long
11579  * as the thread has set R4COMMIT, then it can manipulate the commit
11580  * structure without requiring any other locks.
11581  *
11582  * When this function is called from nfs4_dispose() the page passed
11583  * into nfs4_dispose() will be SE_EXCL locked, and so this function
11584  * will skip it. This is not a problem since we initially add the
11585  * page to the r_commit page list.
11586  *
11587  */
11588 static void
11589 nfs4_get_commit(vnode_t *vp)
11590 {
11591 	rnode4_t *rp;
11592 	page_t *pp;
11593 	kmutex_t *vphm;
11594 
11595 	rp = VTOR4(vp);
11596 
11597 	ASSERT(rp->r_flags & R4COMMIT);
11598 
11599 	/* make sure we're looking at the master vnode, not a shadow */
11600 
11601 	if (IS_SHADOW(vp, rp))
11602 		vp = RTOV4(rp);
11603 
11604 	vphm = page_vnode_mutex(vp);
11605 	mutex_enter(vphm);
11606 
11607 	/*
11608 	 * If there are no pages associated with this vnode, then
11609 	 * just return.
11610 	 */
11611 	if ((pp = vp->v_pages) == NULL) {
11612 		mutex_exit(vphm);
11613 		return;
11614 	}
11615 
11616 	/*
11617 	 * Step through all of the pages associated with this vnode
11618 	 * looking for pages which need to be committed.
11619 	 */
11620 	do {
11621 		/*
11622 		 * First short-cut everything (without the page_lock)
11623 		 * and see if this page does not need to be committed
11624 		 * or is modified if so then we'll just skip it.
11625 		 */
11626 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
11627 			continue;
11628 
11629 		/*
11630 		 * Attempt to lock the page.  If we can't, then
11631 		 * someone else is messing with it or we have been
11632 		 * called from nfs4_dispose and this is the page that
11633 		 * nfs4_dispose was called with.. anyway just skip it.
11634 		 */
11635 		if (!page_trylock(pp, SE_EXCL))
11636 			continue;
11637 
11638 		/*
11639 		 * Lets check again now that we have the page lock.
11640 		 */
11641 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11642 			page_unlock(pp);
11643 			continue;
11644 		}
11645 
11646 		/* this had better not be a free page */
11647 		ASSERT(PP_ISFREE(pp) == 0);
11648 
11649 		/*
11650 		 * The page needs to be committed and we locked it.
11651 		 * Update the base and length parameters and add it
11652 		 * to r_pages.
11653 		 */
11654 		if (rp->r_commit.c_pages == NULL) {
11655 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11656 			rp->r_commit.c_commlen = PAGESIZE;
11657 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
11658 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
11659 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
11660 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11661 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
11662 			    <= pp->p_offset) {
11663 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11664 			    rp->r_commit.c_commbase + PAGESIZE;
11665 		}
11666 		page_add(&rp->r_commit.c_pages, pp);
11667 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11668 
11669 	mutex_exit(vphm);
11670 }
11671 
11672 /*
11673  * This routine is used to gather together a page list of the pages
11674  * which are to be committed on the server.  This routine must not
11675  * be called if the calling thread holds any locked pages.
11676  *
11677  * The calling thread must have set R4COMMIT.  This bit is used to
11678  * serialize access to the commit structure in the rnode.  As long
11679  * as the thread has set R4COMMIT, then it can manipulate the commit
11680  * structure without requiring any other locks.
11681  */
11682 static void
11683 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
11684 {
11685 
11686 	rnode4_t *rp;
11687 	page_t *pp;
11688 	u_offset_t end;
11689 	u_offset_t off;
11690 	ASSERT(len != 0);
11691 	rp = VTOR4(vp);
11692 	ASSERT(rp->r_flags & R4COMMIT);
11693 
11694 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11695 
11696 	/* make sure we're looking at the master vnode, not a shadow */
11697 
11698 	if (IS_SHADOW(vp, rp))
11699 		vp = RTOV4(rp);
11700 
11701 	/*
11702 	 * If there are no pages associated with this vnode, then
11703 	 * just return.
11704 	 */
11705 	if ((pp = vp->v_pages) == NULL)
11706 		return;
11707 	/*
11708 	 * Calculate the ending offset.
11709 	 */
11710 	end = soff + len;
11711 	for (off = soff; off < end; off += PAGESIZE) {
11712 		/*
11713 		 * Lookup each page by vp, offset.
11714 		 */
11715 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
11716 			continue;
11717 		/*
11718 		 * If this page does not need to be committed or is
11719 		 * modified, then just skip it.
11720 		 */
11721 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11722 			page_unlock(pp);
11723 			continue;
11724 		}
11725 
11726 		ASSERT(PP_ISFREE(pp) == 0);
11727 		/*
11728 		 * The page needs to be committed and we locked it.
11729 		 * Update the base and length parameters and add it
11730 		 * to r_pages.
11731 		 */
11732 		if (rp->r_commit.c_pages == NULL) {
11733 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11734 			rp->r_commit.c_commlen = PAGESIZE;
11735 		} else {
11736 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11737 			rp->r_commit.c_commbase + PAGESIZE;
11738 		}
11739 		page_add(&rp->r_commit.c_pages, pp);
11740 	}
11741 }
11742 
11743 /*
11744  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
11745  * Flushes and commits data to the server.
11746  */
11747 static int
11748 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
11749 {
11750 	int error;
11751 	verifier4 write_verf;
11752 	rnode4_t *rp = VTOR4(vp);
11753 
11754 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11755 
11756 	/*
11757 	 * Flush the data portion of the file and then commit any
11758 	 * portions which need to be committed.  This may need to
11759 	 * be done twice if the server has changed state since
11760 	 * data was last written.  The data will need to be
11761 	 * rewritten to the server and then a new commit done.
11762 	 *
11763 	 * In fact, this may need to be done several times if the
11764 	 * server is having problems and crashing while we are
11765 	 * attempting to do this.
11766 	 */
11767 
11768 top:
11769 	/*
11770 	 * Do a flush based on the poff and plen arguments.  This
11771 	 * will synchronously write out any modified pages in the
11772 	 * range specified by (poff, plen). This starts all of the
11773 	 * i/o operations which will be waited for in the next
11774 	 * call to nfs4_putpage
11775 	 */
11776 
11777 	mutex_enter(&rp->r_statelock);
11778 	write_verf = rp->r_writeverf;
11779 	mutex_exit(&rp->r_statelock);
11780 
11781 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr);
11782 	if (error == EAGAIN)
11783 		error = 0;
11784 
11785 	/*
11786 	 * Do a flush based on the poff and plen arguments.  This
11787 	 * will synchronously write out any modified pages in the
11788 	 * range specified by (poff, plen) and wait until all of
11789 	 * the asynchronous i/o's in that range are done as well.
11790 	 */
11791 	if (!error)
11792 		error = nfs4_putpage(vp, poff, plen, 0, cr);
11793 
11794 	if (error)
11795 		return (error);
11796 
11797 	mutex_enter(&rp->r_statelock);
11798 	if (rp->r_writeverf != write_verf) {
11799 		mutex_exit(&rp->r_statelock);
11800 		goto top;
11801 	}
11802 	mutex_exit(&rp->r_statelock);
11803 
11804 	/*
11805 	 * Now commit any pages which might need to be committed.
11806 	 * If the error, NFS_VERF_MISMATCH, is returned, then
11807 	 * start over with the flush operation.
11808 	 */
11809 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
11810 
11811 	if (error == NFS_VERF_MISMATCH)
11812 		goto top;
11813 
11814 	return (error);
11815 }
11816 
11817 /*
11818  * nfs4_commit_vp()  will wait for other pending commits and
11819  * will either commit the whole file or a range, plen dictates
11820  * if we commit whole file. a value of zero indicates the whole
11821  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
11822  */
11823 static int
11824 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
11825 		cred_t *cr, int wait_on_writes)
11826 {
11827 	rnode4_t *rp;
11828 	page_t *plist;
11829 	offset3 offset;
11830 	count3 len;
11831 
11832 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11833 
11834 	rp = VTOR4(vp);
11835 
11836 	/*
11837 	 *  before we gather commitable pages make
11838 	 *  sure there are no outstanding async writes
11839 	 */
11840 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
11841 		mutex_enter(&rp->r_statelock);
11842 		while (rp->r_count > 0) {
11843 			cv_wait(&rp->r_cv, &rp->r_statelock);
11844 		}
11845 		mutex_exit(&rp->r_statelock);
11846 	}
11847 
11848 	/*
11849 	 * Set the `commit inprogress' state bit.  We must
11850 	 * first wait until any current one finishes.
11851 	 */
11852 	mutex_enter(&rp->r_statelock);
11853 	while (rp->r_flags & R4COMMIT) {
11854 		rp->r_flags |= R4COMMITWAIT;
11855 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11856 		rp->r_flags &= ~R4COMMITWAIT;
11857 	}
11858 	rp->r_flags |= R4COMMIT;
11859 	mutex_exit(&rp->r_statelock);
11860 
11861 	/*
11862 	 * Gather all of the pages which need to be
11863 	 * committed.
11864 	 */
11865 	if (plen == 0)
11866 		nfs4_get_commit(vp);
11867 	else
11868 		nfs4_get_commit_range(vp, poff, plen);
11869 
11870 	/*
11871 	 * Clear the `commit inprogress' bit and disconnect the
11872 	 * page list which was gathered by nfs4_get_commit.
11873 	 */
11874 	plist = rp->r_commit.c_pages;
11875 	rp->r_commit.c_pages = NULL;
11876 	offset = rp->r_commit.c_commbase;
11877 	len = rp->r_commit.c_commlen;
11878 	mutex_enter(&rp->r_statelock);
11879 	rp->r_flags &= ~R4COMMIT;
11880 	cv_broadcast(&rp->r_commit.c_cv);
11881 	mutex_exit(&rp->r_statelock);
11882 
11883 	/*
11884 	 * If any pages need to be committed, commit them and
11885 	 * then unlock them so that they can be freed some
11886 	 * time later.
11887 	 */
11888 	if (plist == NULL)
11889 		return (0);
11890 
11891 	/*
11892 	 * No error occurred during the flush portion
11893 	 * of this operation, so now attempt to commit
11894 	 * the data to stable storage on the server.
11895 	 *
11896 	 * This will unlock all of the pages on the list.
11897 	 */
11898 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
11899 }
11900 
11901 static int
11902 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
11903 	cred_t *cr)
11904 {
11905 	int error;
11906 	page_t *pp;
11907 
11908 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11909 
11910 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
11911 
11912 	/*
11913 	 * If we got an error, then just unlock all of the pages
11914 	 * on the list.
11915 	 */
11916 	if (error) {
11917 		while (plist != NULL) {
11918 			pp = plist;
11919 			page_sub(&plist, pp);
11920 			page_unlock(pp);
11921 		}
11922 		return (error);
11923 	}
11924 	/*
11925 	 * We've tried as hard as we can to commit the data to stable
11926 	 * storage on the server.  We just unlock the pages and clear
11927 	 * the commit required state.  They will get freed later.
11928 	 */
11929 	while (plist != NULL) {
11930 		pp = plist;
11931 		page_sub(&plist, pp);
11932 		pp->p_fsdata = C_NOCOMMIT;
11933 		page_unlock(pp);
11934 	}
11935 
11936 	return (error);
11937 }
11938 
11939 static void
11940 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
11941 	cred_t *cr)
11942 {
11943 
11944 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
11945 }
11946 
11947 /*ARGSUSED*/
11948 static int
11949 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr)
11950 {
11951 	int		error = 0;
11952 	mntinfo4_t	*mi;
11953 	vattr_t		va;
11954 	vsecattr_t	nfsace4_vsap;
11955 
11956 	mi = VTOMI4(vp);
11957 	if (nfs_zone() != mi->mi_zone)
11958 		return (EIO);
11959 	if (mi->mi_flags & MI4_ACL) {
11960 		/* if we have a delegation, return it */
11961 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
11962 			(void) nfs4delegreturn(VTOR4(vp),
11963 					NFS4_DR_REOPEN|NFS4_DR_PUSH);
11964 
11965 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
11966 			NFS4_ACL_SET);
11967 		if (error) /* EINVAL */
11968 			return (error);
11969 
11970 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
11971 			/*
11972 			 * These are aclent_t type entries.
11973 			 */
11974 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
11975 			    vp->v_type == VDIR, FALSE);
11976 			if (error)
11977 				return (error);
11978 		} else {
11979 			/*
11980 			 * These are ace_t type entries.
11981 			 */
11982 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
11983 			    FALSE);
11984 			if (error)
11985 				return (error);
11986 		}
11987 		bzero(&va, sizeof (va));
11988 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
11989 		vs_ace4_destroy(&nfsace4_vsap);
11990 		return (error);
11991 	}
11992 	return (ENOSYS);
11993 }
11994 
11995 static int
11996 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr)
11997 {
11998 	int		error;
11999 	mntinfo4_t	*mi;
12000 	nfs4_ga_res_t	gar;
12001 	rnode4_t	*rp = VTOR4(vp);
12002 
12003 	mi = VTOMI4(vp);
12004 	if (nfs_zone() != mi->mi_zone)
12005 		return (EIO);
12006 
12007 	bzero(&gar, sizeof (gar));
12008 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12009 
12010 	/*
12011 	 * vsecattr->vsa_mask holds the original acl request mask.
12012 	 * This is needed when determining what to return.
12013 	 * (See: nfs4_create_getsecattr_return())
12014 	 */
12015 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12016 	if (error) /* EINVAL */
12017 		return (error);
12018 
12019 	if (mi->mi_flags & MI4_ACL) {
12020 		/*
12021 		 * Check if the data is cached and the cache is valid.  If it
12022 		 * is we don't go over the wire.
12023 		 */
12024 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12025 			mutex_enter(&rp->r_statelock);
12026 			if (rp->r_secattr != NULL) {
12027 				error = nfs4_create_getsecattr_return(
12028 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12029 				    rp->r_attr.va_gid,
12030 				    vp->v_type == VDIR);
12031 				if (!error) { /* error == 0 - Success! */
12032 					mutex_exit(&rp->r_statelock);
12033 					return (error);
12034 				}
12035 			}
12036 			mutex_exit(&rp->r_statelock);
12037 		}
12038 
12039 		/*
12040 		 * The getattr otw call will always get both the acl, in
12041 		 * the form of a list of nfsace4's, and the number of acl
12042 		 * entries; independent of the value of gar.n4g_vsa.vsa_mask.
12043 		 */
12044 		gar.n4g_va.va_mask = AT_ALL;
12045 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12046 		if (error) {
12047 			vs_ace4_destroy(&gar.n4g_vsa);
12048 			if (error == ENOTSUP || error == EOPNOTSUPP)
12049 				error = fs_fab_acl(vp, vsecattr, flag, cr);
12050 			return (error);
12051 		}
12052 
12053 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12054 			/*
12055 			 * No error was returned, but according to the response
12056 			 * bitmap, neither was an acl.
12057 			 */
12058 			vs_ace4_destroy(&gar.n4g_vsa);
12059 			error = fs_fab_acl(vp, vsecattr, flag, cr);
12060 			return (error);
12061 		}
12062 
12063 		/*
12064 		 * Update the cache with the ACL.
12065 		 */
12066 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12067 
12068 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12069 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12070 		    vp->v_type == VDIR);
12071 		vs_ace4_destroy(&gar.n4g_vsa);
12072 		if ((error) && (vsecattr->vsa_mask &
12073 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12074 		    (error != EACCES)) {
12075 			error = fs_fab_acl(vp, vsecattr, flag, cr);
12076 		}
12077 		return (error);
12078 	}
12079 	error = fs_fab_acl(vp, vsecattr, flag, cr);
12080 	return (error);
12081 }
12082 
12083 /*
12084  * The function returns:
12085  * 	- 0 (zero) if the passed in "acl_mask" is a valid request.
12086  * 	- EINVAL if the passed in "acl_mask" is an invalid request.
12087  *
12088  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12089  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12090  *
12091  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12092  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12093  * - We have a count field set without the corresponding acl field set. (e.g. -
12094  * VSA_ACECNT is set, but VSA_ACE is not)
12095  */
12096 static int
12097 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12098 {
12099 	/* Shortcut the masks that are always valid. */
12100 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12101 		return (0);
12102 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12103 		return (0);
12104 
12105 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12106 		/*
12107 		 * We can't have any VSA_ACL type stuff in the mask now.
12108 		 */
12109 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12110 		    VSA_DFACLCNT))
12111 			return (EINVAL);
12112 
12113 		if (op == NFS4_ACL_SET) {
12114 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12115 				return (EINVAL);
12116 		}
12117 	}
12118 
12119 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12120 		/*
12121 		 * We can't have any VSA_ACE type stuff in the mask now.
12122 		 */
12123 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12124 			return (EINVAL);
12125 
12126 		if (op == NFS4_ACL_SET) {
12127 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12128 				return (EINVAL);
12129 
12130 			if ((acl_mask & VSA_DFACLCNT) &&
12131 			    !(acl_mask & VSA_DFACL))
12132 				return (EINVAL);
12133 		}
12134 	}
12135 	return (0);
12136 }
12137 
12138 /*
12139  * The theory behind creating the correct getsecattr return is simply this:
12140  * "Don't return anything that the caller is not expecting to have to free."
12141  */
12142 static int
12143 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12144 	uid_t uid, gid_t gid, int isdir)
12145 {
12146 	int error = 0;
12147 	/* Save the mask since the translators modify it. */
12148 	uint_t	orig_mask = vsap->vsa_mask;
12149 
12150 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12151 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid,
12152 		    FALSE, ((orig_mask & VSA_ACE) ? FALSE : TRUE));
12153 
12154 		if (error)
12155 			return (error);
12156 
12157 		/*
12158 		 * If the caller only asked for the ace count (VSA_ACECNT)
12159 		 * don't give them the full acl (VSA_ACE), free it.
12160 		 */
12161 		if (!orig_mask & VSA_ACE) {
12162 			if (vsap->vsa_aclentp != NULL) {
12163 				kmem_free(vsap->vsa_aclentp,
12164 				    vsap->vsa_aclcnt * sizeof (ace_t));
12165 				vsap->vsa_aclentp = NULL;
12166 			}
12167 		}
12168 		vsap->vsa_mask = orig_mask;
12169 
12170 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12171 	    VSA_DFACLCNT)) {
12172 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12173 		    isdir, FALSE,
12174 		    ((orig_mask & (VSA_ACL | VSA_DFACL)) ? FALSE : TRUE));
12175 
12176 		if (error)
12177 			return (error);
12178 
12179 		/*
12180 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12181 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12182 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12183 		 */
12184 		if (!orig_mask & VSA_ACL) {
12185 			if (vsap->vsa_aclentp != NULL) {
12186 				kmem_free(vsap->vsa_aclentp,
12187 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12188 				vsap->vsa_aclentp = NULL;
12189 			}
12190 		}
12191 
12192 		if (!orig_mask & VSA_DFACL) {
12193 			if (vsap->vsa_dfaclentp != NULL) {
12194 				kmem_free(vsap->vsa_dfaclentp,
12195 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12196 				vsap->vsa_dfaclentp = NULL;
12197 			}
12198 		}
12199 		vsap->vsa_mask = orig_mask;
12200 	}
12201 	return (0);
12202 }
12203 
12204 static int
12205 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr)
12206 {
12207 	int error;
12208 
12209 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12210 		return (EIO);
12211 	/*
12212 	 * check for valid cmd parameter
12213 	 */
12214 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12215 		return (EINVAL);
12216 
12217 	/*
12218 	 * Check access permissions
12219 	 */
12220 	if ((cmd & F_SHARE) &&
12221 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12222 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12223 		return (EBADF);
12224 
12225 	/*
12226 	 * If the filesystem is mounted using local locking, pass the
12227 	 * request off to the local share code.
12228 	 */
12229 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12230 		return (fs_shrlock(vp, cmd, shr, flag, cr));
12231 
12232 	switch (cmd) {
12233 	case F_SHARE:
12234 	case F_UNSHARE:
12235 		/*
12236 		 * This will be properly implemented later,
12237 		 * see RFE: 4823948 .
12238 		 */
12239 		error = EAGAIN;
12240 		break;
12241 
12242 	case F_HASREMOTELOCKS:
12243 		/*
12244 		 * NFS client can't store remote locks itself
12245 		 */
12246 		shr->s_access = 0;
12247 		error = 0;
12248 		break;
12249 
12250 	default:
12251 		error = EINVAL;
12252 		break;
12253 	}
12254 
12255 	return (error);
12256 }
12257 
12258 /*
12259  * Common code called by directory ops to update the attrcache
12260  */
12261 static int
12262 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12263 	hrtime_t t, vnode_t *vp, cred_t *cr)
12264 {
12265 	int error = 0;
12266 
12267 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12268 
12269 	if (status != NFS4_OK) {
12270 		/* getattr not done or failed */
12271 		PURGE_ATTRCACHE4(vp);
12272 		return (error);
12273 	}
12274 
12275 	if (garp) {
12276 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12277 	} else {
12278 		PURGE_ATTRCACHE4(vp);
12279 	}
12280 	return (error);
12281 }
12282 
12283 /*
12284  * Update directory caches for directory modification ops (link, rename, etc.)
12285  * When dinfo is NULL, manage dircaches in the old way.
12286  */
12287 static void
12288 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12289 		dirattr_info_t *dinfo)
12290 {
12291 	rnode4_t	*drp = VTOR4(dvp);
12292 
12293 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12294 
12295 	/* Purge rddir cache for dir since it changed */
12296 	if (drp->r_dir != NULL)
12297 		nfs4_purge_rddir_cache(dvp);
12298 
12299 	/*
12300 	 * If caller provided dinfo, then use it to manage dir caches.
12301 	 */
12302 	if (dinfo != NULL) {
12303 		if (vp != NULL) {
12304 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12305 			if (!VTOR4(vp)->created_v4) {
12306 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12307 				dnlc_update(dvp, nm, vp);
12308 			} else {
12309 				/*
12310 				 * XXX don't update if the created_v4 flag is
12311 				 * set
12312 				 */
12313 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12314 				NFS4_DEBUG(nfs4_client_state_debug,
12315 					(CE_NOTE, "nfs4_update_dircaches: "
12316 					"don't update dnlc: created_v4 flag"));
12317 			}
12318 		}
12319 
12320 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12321 				dinfo->di_cred, FALSE, cinfo);
12322 
12323 		return;
12324 	}
12325 
12326 	/*
12327 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12328 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12329 	 * attrs, the dir's attrs must be purged.
12330 	 *
12331 	 * XXX this check and dnlc update/purge should really be atomic,
12332 	 * XXX but can't use rnode statelock because it'll deadlock in
12333 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12334 	 * XXX does occur.
12335 	 *
12336 	 * XXX We also may want to check that atomic is true in the
12337 	 * XXX change_info struct. If it is not, the change_info may
12338 	 * XXX reflect changes by more than one clients which means that
12339 	 * XXX our cache may not be valid.
12340 	 */
12341 	PURGE_ATTRCACHE4(dvp);
12342 	if (drp->r_change == cinfo->before) {
12343 		/* no changes took place in the directory prior to our link */
12344 		if (vp != NULL) {
12345 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12346 			if (!VTOR4(vp)->created_v4) {
12347 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12348 				dnlc_update(dvp, nm, vp);
12349 			} else {
12350 				/*
12351 				 * XXX dont' update if the created_v4 flag
12352 				 * is set
12353 				 */
12354 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12355 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12356 					"nfs4_update_dircaches: don't"
12357 					" update dnlc: created_v4 flag"));
12358 			}
12359 		}
12360 	} else {
12361 		/* Another client modified directory - purge its dnlc cache */
12362 		dnlc_purge_vp(dvp);
12363 	}
12364 }
12365 
12366 /*
12367  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12368  * file.
12369  *
12370  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12371  * file (ie: client recovery) and otherwise set to FALSE.
12372  *
12373  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12374  * initiated) calling functions.
12375  *
12376  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12377  * of resending a 'lost' open request.
12378  *
12379  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12380  * server that hands out BAD_SEQID on open confirm.
12381  *
12382  * Errors are returned via the nfs4_error_t parameter.
12383  */
12384 void
12385 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12386 	bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12387 	bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12388 {
12389 	COMPOUND4args_clnt args;
12390 	COMPOUND4res_clnt res;
12391 	nfs_argop4 argop[2];
12392 	nfs_resop4 *resop;
12393 	int doqueue = 1;
12394 	mntinfo4_t *mi;
12395 	OPEN_CONFIRM4args *open_confirm_args;
12396 	int needrecov;
12397 
12398 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12399 #if DEBUG
12400 	mutex_enter(&oop->oo_lock);
12401 	ASSERT(oop->oo_seqid_inuse);
12402 	mutex_exit(&oop->oo_lock);
12403 #endif
12404 
12405 recov_retry_confirm:
12406 	nfs4_error_zinit(ep);
12407 	*retry_open = FALSE;
12408 
12409 	if (resend)
12410 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12411 	else
12412 		args.ctag = TAG_OPEN_CONFIRM;
12413 
12414 	args.array_len = 2;
12415 	args.array = argop;
12416 
12417 	/* putfh target fh */
12418 	argop[0].argop = OP_CPUTFH;
12419 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12420 
12421 	argop[1].argop = OP_OPEN_CONFIRM;
12422 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12423 
12424 	(*seqid) += 1;
12425 	open_confirm_args->seqid = *seqid;
12426 	open_confirm_args->open_stateid = *stateid;
12427 
12428 	mi = VTOMI4(vp);
12429 
12430 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12431 
12432 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12433 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12434 	}
12435 
12436 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12437 	if (!needrecov && ep->error)
12438 		return;
12439 
12440 	if (needrecov) {
12441 		bool_t abort = FALSE;
12442 
12443 		if (reopening_file == FALSE) {
12444 			nfs4_bseqid_entry_t *bsep = NULL;
12445 
12446 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12447 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12448 					vp, 0, args.ctag,
12449 					open_confirm_args->seqid);
12450 
12451 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp,
12452 				    NULL, NULL, NULL, OP_OPEN_CONFIRM, bsep);
12453 			if (bsep) {
12454 				kmem_free(bsep, sizeof (*bsep));
12455 				if (num_bseqid_retryp &&
12456 				    --(*num_bseqid_retryp) == 0)
12457 					abort = TRUE;
12458 			}
12459 		}
12460 		if ((ep->error == ETIMEDOUT ||
12461 					res.status == NFS4ERR_RESOURCE) &&
12462 					abort == FALSE && resend == FALSE) {
12463 			if (!ep->error)
12464 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12465 								(caddr_t)&res);
12466 
12467 			delay(SEC_TO_TICK(confirm_retry_sec));
12468 			goto recov_retry_confirm;
12469 		}
12470 		/* State may have changed so retry the entire OPEN op */
12471 		if (abort == FALSE)
12472 			*retry_open = TRUE;
12473 		else
12474 			*retry_open = FALSE;
12475 		if (!ep->error)
12476 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12477 		return;
12478 	}
12479 
12480 	if (res.status) {
12481 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12482 		return;
12483 	}
12484 
12485 	resop = &res.array[1];  /* open confirm res */
12486 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
12487 				stateid, sizeof (*stateid));
12488 
12489 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12490 }
12491 
12492 /*
12493  * Return the credentials associated with a client state object.  The
12494  * caller is responsible for freeing the credentials.
12495  */
12496 
12497 static cred_t *
12498 state_to_cred(nfs4_open_stream_t *osp)
12499 {
12500 	cred_t *cr;
12501 
12502 	/*
12503 	 * It's ok to not lock the open stream and open owner to get
12504 	 * the oo_cred since this is only written once (upon creation)
12505 	 * and will not change.
12506 	 */
12507 	cr = osp->os_open_owner->oo_cred;
12508 	crhold(cr);
12509 
12510 	return (cr);
12511 }
12512 
12513 /*
12514  * nfs4_find_sysid
12515  *
12516  * Find the sysid for the knetconfig associated with the given mi.
12517  */
12518 static struct lm_sysid *
12519 nfs4_find_sysid(mntinfo4_t *mi)
12520 {
12521 	ASSERT(nfs_zone() == mi->mi_zone);
12522 
12523 	/*
12524 	 * Switch from RDMA knconf to original mount knconf
12525 	 */
12526 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
12527 		    mi->mi_curr_serv->sv_hostname, NULL));
12528 }
12529 
12530 #ifdef DEBUG
12531 /*
12532  * Return a string version of the call type for easy reading.
12533  */
12534 static char *
12535 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
12536 {
12537 	switch (ctype) {
12538 	case NFS4_LCK_CTYPE_NORM:
12539 		return ("NORMAL");
12540 	case NFS4_LCK_CTYPE_RECLAIM:
12541 		return ("RECLAIM");
12542 	case NFS4_LCK_CTYPE_RESEND:
12543 		return ("RESEND");
12544 	case NFS4_LCK_CTYPE_REINSTATE:
12545 		return ("REINSTATE");
12546 	default:
12547 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
12548 			"type %d", ctype);
12549 		return ("");
12550 	}
12551 }
12552 #endif
12553 
12554 /*
12555  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
12556  * Unlock requests don't have an over-the-wire locktype, so we just return
12557  * something non-threatening.
12558  */
12559 
12560 static nfs_lock_type4
12561 flk_to_locktype(int cmd, int l_type)
12562 {
12563 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
12564 
12565 	switch (l_type) {
12566 	case F_UNLCK:
12567 		return (READ_LT);
12568 	case F_RDLCK:
12569 		if (cmd == F_SETLK)
12570 			return (READ_LT);
12571 		else
12572 			return (READW_LT);
12573 	case F_WRLCK:
12574 		if (cmd == F_SETLK)
12575 			return (WRITE_LT);
12576 		else
12577 			return (WRITEW_LT);
12578 	}
12579 	panic("flk_to_locktype");
12580 	/*NOTREACHED*/
12581 }
12582 
12583 /*
12584  * Do some preliminary checks for nfs4frlock.
12585  */
12586 static int
12587 nfs4frlock_validate_args(int cmd, flock64_t *flk, int flag, vnode_t *vp,
12588 	u_offset_t offset)
12589 {
12590 	int error = 0;
12591 
12592 	/*
12593 	 * If we are setting a lock, check that the file is opened
12594 	 * with the correct mode.
12595 	 */
12596 	if (cmd == F_SETLK || cmd == F_SETLKW) {
12597 		if ((flk->l_type == F_RDLCK && (flag & FREAD) == 0) ||
12598 		    (flk->l_type == F_WRLCK && (flag & FWRITE) == 0)) {
12599 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12600 			    "nfs4frlock_validate_args: file was opened with "
12601 			    "incorrect mode"));
12602 			return (EBADF);
12603 		}
12604 	}
12605 
12606 	/* Convert the offset. It may need to be restored before returning. */
12607 	if (error = convoff(vp, flk, 0, offset)) {
12608 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12609 		    "nfs4frlock_validate_args: convoff  =>  error= %d\n",
12610 		    error));
12611 		return (error);
12612 	}
12613 
12614 	return (error);
12615 }
12616 
12617 /*
12618  * Set the flock64's lm_sysid for nfs4frlock.
12619  */
12620 static int
12621 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
12622 {
12623 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12624 
12625 	/* Find the lm_sysid */
12626 	*lspp = nfs4_find_sysid(VTOMI4(vp));
12627 
12628 	if (*lspp == NULL) {
12629 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12630 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
12631 		return (ENOLCK);
12632 	}
12633 
12634 	flk->l_sysid = lm_sysidt(*lspp);
12635 
12636 	return (0);
12637 }
12638 
12639 /*
12640  * Do the remaining preliminary setup for nfs4frlock.
12641  */
12642 static void
12643 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
12644 	flock64_t *flk, short *whencep, vnode_t *vp, cred_t *search_cr,
12645 	cred_t **cred_otw)
12646 {
12647 	/*
12648 	 * set tick_delay to the base delay time.
12649 	 * (NFS4_BASE_WAIT_TIME is in secs)
12650 	 */
12651 
12652 	*tick_delayp = drv_usectohz(NFS4_BASE_WAIT_TIME * 1000 * 1000);
12653 
12654 	/*
12655 	 * If lock is relative to EOF, we need the newest length of the
12656 	 * file. Therefore invalidate the ATTR_CACHE.
12657 	 */
12658 
12659 	*whencep = flk->l_whence;
12660 
12661 	if (*whencep == 2)		/* SEEK_END */
12662 		PURGE_ATTRCACHE4(vp);
12663 
12664 	recov_statep->rs_flags = 0;
12665 	recov_statep->rs_num_retry_despite_err = 0;
12666 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
12667 }
12668 
12669 /*
12670  * Initialize and allocate the data structures necessary for
12671  * the nfs4frlock call.
12672  * Allocates argsp's op array, frees up the saved_rqstpp if there is one.
12673  */
12674 static void
12675 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
12676 	nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
12677 	bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
12678 	bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
12679 {
12680 	int		argoplist_size;
12681 	int		num_ops = 2;
12682 
12683 	*retry = FALSE;
12684 	*did_start_fop = FALSE;
12685 	*skip_get_err = FALSE;
12686 	lost_rqstp->lr_op = 0;
12687 	argoplist_size  = num_ops * sizeof (nfs_argop4);
12688 	/* fill array with zero */
12689 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
12690 
12691 	*argspp = argsp;
12692 	*respp = NULL;
12693 
12694 	argsp->array_len = num_ops;
12695 	argsp->array = *argopp;
12696 
12697 	/* initialize in case of error; will get real value down below */
12698 	argsp->ctag = TAG_NONE;
12699 
12700 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
12701 		*op_hintp = OH_LOCKU;
12702 	else
12703 		*op_hintp = OH_OTHER;
12704 }
12705 
12706 /*
12707  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
12708  * the proper nfs4_server_t for this instance of nfs4frlock.
12709  * Returns 0 (success) or an errno value.
12710  */
12711 static int
12712 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
12713 	nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
12714 	bool_t *did_start_fop, bool_t *startrecovp)
12715 {
12716 	int error = 0;
12717 	rnode4_t *rp;
12718 
12719 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12720 
12721 	if (ctype == NFS4_LCK_CTYPE_NORM) {
12722 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
12723 				recov_statep, startrecovp);
12724 		if (error)
12725 			return (error);
12726 		*did_start_fop = TRUE;
12727 	} else {
12728 		*did_start_fop = FALSE;
12729 		*startrecovp = FALSE;
12730 	}
12731 
12732 	if (!error) {
12733 		rp = VTOR4(vp);
12734 
12735 		/* If the file failed recovery, just quit. */
12736 		mutex_enter(&rp->r_statelock);
12737 		if (rp->r_flags & R4RECOVERR) {
12738 			error = EIO;
12739 		}
12740 		mutex_exit(&rp->r_statelock);
12741 	}
12742 
12743 	return (error);
12744 }
12745 
12746 /*
12747  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
12748  * resend nfs4frlock call is initiated by the recovery framework.
12749  * Acquires the lop and oop seqid synchronization.
12750  */
12751 static void
12752 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
12753 	COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
12754 	nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
12755 	LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
12756 {
12757 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
12758 	int error;
12759 
12760 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
12761 		(CE_NOTE,
12762 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
12763 	ASSERT(resend_rqstp != NULL);
12764 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
12765 	    resend_rqstp->lr_op == OP_LOCKU);
12766 
12767 	*oopp = resend_rqstp->lr_oop;
12768 	if (resend_rqstp->lr_oop) {
12769 		open_owner_hold(resend_rqstp->lr_oop);
12770 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
12771 		ASSERT(error == 0);	/* recov thread always succeeds */
12772 	}
12773 
12774 	/* Must resend this lost lock/locku request. */
12775 	ASSERT(resend_rqstp->lr_lop != NULL);
12776 	*lopp = resend_rqstp->lr_lop;
12777 	lock_owner_hold(resend_rqstp->lr_lop);
12778 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
12779 	ASSERT(error == 0);	/* recov thread always succeeds */
12780 
12781 	*ospp = resend_rqstp->lr_osp;
12782 	if (*ospp)
12783 		open_stream_hold(resend_rqstp->lr_osp);
12784 
12785 	if (resend_rqstp->lr_op == OP_LOCK) {
12786 		LOCK4args *lock_args;
12787 
12788 		argop->argop = OP_LOCK;
12789 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
12790 		lock_args->locktype = resend_rqstp->lr_locktype;
12791 		lock_args->reclaim =
12792 			(resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
12793 		lock_args->offset = resend_rqstp->lr_flk->l_start;
12794 		lock_args->length = resend_rqstp->lr_flk->l_len;
12795 		if (lock_args->length == 0)
12796 			lock_args->length = ~lock_args->length;
12797 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
12798 				mi2clientid(mi), &lock_args->locker);
12799 
12800 		switch (resend_rqstp->lr_ctype) {
12801 		case NFS4_LCK_CTYPE_RESEND:
12802 			argsp->ctag = TAG_LOCK_RESEND;
12803 			break;
12804 		case NFS4_LCK_CTYPE_REINSTATE:
12805 			argsp->ctag = TAG_LOCK_REINSTATE;
12806 			break;
12807 		case NFS4_LCK_CTYPE_RECLAIM:
12808 			argsp->ctag = TAG_LOCK_RECLAIM;
12809 			break;
12810 		default:
12811 			argsp->ctag = TAG_LOCK_UNKNOWN;
12812 			break;
12813 		}
12814 	} else {
12815 		LOCKU4args *locku_args;
12816 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
12817 
12818 		argop->argop = OP_LOCKU;
12819 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
12820 		locku_args->locktype = READ_LT;
12821 		locku_args->seqid = lop->lock_seqid + 1;
12822 		mutex_enter(&lop->lo_lock);
12823 		locku_args->lock_stateid = lop->lock_stateid;
12824 		mutex_exit(&lop->lo_lock);
12825 		locku_args->offset = resend_rqstp->lr_flk->l_start;
12826 		locku_args->length = resend_rqstp->lr_flk->l_len;
12827 		if (locku_args->length == 0)
12828 			locku_args->length = ~locku_args->length;
12829 
12830 		switch (resend_rqstp->lr_ctype) {
12831 		case NFS4_LCK_CTYPE_RESEND:
12832 			argsp->ctag = TAG_LOCKU_RESEND;
12833 			break;
12834 		case NFS4_LCK_CTYPE_REINSTATE:
12835 			argsp->ctag = TAG_LOCKU_REINSTATE;
12836 			break;
12837 		default:
12838 			argsp->ctag = TAG_LOCK_UNKNOWN;
12839 			break;
12840 		}
12841 	}
12842 }
12843 
12844 /*
12845  * Setup the LOCKT4 arguments.
12846  */
12847 static void
12848 nfs4frlock_setup_lockt_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
12849 	LOCKT4args **lockt_argsp, COMPOUND4args_clnt *argsp, flock64_t *flk,
12850 	rnode4_t *rp)
12851 {
12852 	LOCKT4args *lockt_args;
12853 
12854 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
12855 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
12856 	argop->argop = OP_LOCKT;
12857 	argsp->ctag = TAG_LOCKT;
12858 	lockt_args = &argop->nfs_argop4_u.oplockt;
12859 
12860 	/*
12861 	 * The locktype will be READ_LT unless it's
12862 	 * a write lock. We do this because the Solaris
12863 	 * system call allows the combination of
12864 	 * F_UNLCK and F_GETLK* and so in that case the
12865 	 * unlock is mapped to a read.
12866 	 */
12867 	if (flk->l_type == F_WRLCK)
12868 		lockt_args->locktype = WRITE_LT;
12869 	else
12870 		lockt_args->locktype = READ_LT;
12871 
12872 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
12873 	/* set the lock owner4 args */
12874 	nfs4_setlockowner_args(&lockt_args->owner, rp,
12875 	    ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
12876 	    flk->l_pid);
12877 	lockt_args->offset = flk->l_start;
12878 	lockt_args->length = flk->l_len;
12879 	if (flk->l_len == 0)
12880 		lockt_args->length = ~lockt_args->length;
12881 
12882 	*lockt_argsp = lockt_args;
12883 }
12884 
12885 /*
12886  * If the client is holding a delegation, and the open stream to be used
12887  * with this lock request is a delegation open stream, then re-open the stream.
12888  * Sets the nfs4_error_t to all zeros unless the open stream has already
12889  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
12890  * means the caller should retry (like a recovery retry).
12891  */
12892 static void
12893 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
12894 {
12895 	open_delegation_type4	dt;
12896 	bool_t			reopen_needed, force;
12897 	nfs4_open_stream_t	*osp;
12898 	open_claim_type4 	oclaim;
12899 	rnode4_t		*rp = VTOR4(vp);
12900 	mntinfo4_t		*mi = VTOMI4(vp);
12901 
12902 	ASSERT(nfs_zone() == mi->mi_zone);
12903 
12904 	nfs4_error_zinit(ep);
12905 
12906 	mutex_enter(&rp->r_statev4_lock);
12907 	dt = rp->r_deleg_type;
12908 	mutex_exit(&rp->r_statev4_lock);
12909 
12910 	if (dt != OPEN_DELEGATE_NONE) {
12911 		nfs4_open_owner_t	*oop;
12912 
12913 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
12914 		if (!oop) {
12915 			ep->stat = NFS4ERR_IO;
12916 			return;
12917 		}
12918 		/* returns with 'os_sync_lock' held */
12919 		osp = find_open_stream(oop, rp);
12920 		if (!osp) {
12921 			open_owner_rele(oop);
12922 			ep->stat = NFS4ERR_IO;
12923 			return;
12924 		}
12925 
12926 		if (osp->os_failed_reopen) {
12927 			NFS4_DEBUG((nfs4_open_stream_debug ||
12928 				    nfs4_client_lock_debug), (CE_NOTE,
12929 			    "nfs4frlock_check_deleg: os_failed_reopen set "
12930 			    "for osp %p, cr %p, rp %s", (void *)osp,
12931 			    (void *)cr, rnode4info(rp)));
12932 			mutex_exit(&osp->os_sync_lock);
12933 			open_stream_rele(osp, rp);
12934 			open_owner_rele(oop);
12935 			ep->stat = NFS4ERR_IO;
12936 			return;
12937 		}
12938 
12939 		/*
12940 		 * Determine whether a reopen is needed.  If this
12941 		 * is a delegation open stream, then send the open
12942 		 * to the server to give visibility to the open owner.
12943 		 * Even if it isn't a delegation open stream, we need
12944 		 * to check if the previous open CLAIM_DELEGATE_CUR
12945 		 * was sufficient.
12946 		 */
12947 
12948 		reopen_needed = osp->os_delegation ||
12949 		    ((lt == F_RDLCK &&
12950 			!(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
12951 		    (lt == F_WRLCK &&
12952 			!(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
12953 
12954 		mutex_exit(&osp->os_sync_lock);
12955 		open_owner_rele(oop);
12956 
12957 		if (reopen_needed) {
12958 			/*
12959 			 * Always use CLAIM_PREVIOUS after server reboot.
12960 			 * The server will reject CLAIM_DELEGATE_CUR if
12961 			 * it is used during the grace period.
12962 			 */
12963 			mutex_enter(&mi->mi_lock);
12964 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
12965 				oclaim = CLAIM_PREVIOUS;
12966 				force = TRUE;
12967 			} else {
12968 				oclaim = CLAIM_DELEGATE_CUR;
12969 				force = FALSE;
12970 			}
12971 			mutex_exit(&mi->mi_lock);
12972 
12973 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
12974 			if (ep->error == EAGAIN) {
12975 				nfs4_error_zinit(ep);
12976 				ep->stat = NFS4ERR_DELAY;
12977 			}
12978 		}
12979 		open_stream_rele(osp, rp);
12980 		osp = NULL;
12981 	}
12982 }
12983 
12984 /*
12985  * Setup the LOCKU4 arguments.
12986  * Returns errors via the nfs4_error_t.
12987  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
12988  *			over-the-wire.  The caller must release the
12989  *			reference on *lopp.
12990  * NFS4ERR_DELAY	caller should retry (like recovery retry)
12991  * (other)		unrecoverable error.
12992  */
12993 static void
12994 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
12995 	LOCKU4args **locku_argsp, flock64_t *flk,
12996 	nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
12997 	vnode_t *vp, int flag, u_offset_t offset, cred_t *cr,
12998 	bool_t *skip_get_err, bool_t *go_otwp)
12999 {
13000 	nfs4_lock_owner_t	*lop = NULL;
13001 	LOCKU4args		*locku_args;
13002 	pid_t			pid;
13003 	bool_t			is_spec = FALSE;
13004 	rnode4_t		*rp = VTOR4(vp);
13005 
13006 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13007 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13008 
13009 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13010 	if (ep->error || ep->stat)
13011 		return;
13012 
13013 	argop->argop = OP_LOCKU;
13014 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13015 		argsp->ctag = TAG_LOCKU_REINSTATE;
13016 	else
13017 		argsp->ctag = TAG_LOCKU;
13018 	locku_args = &argop->nfs_argop4_u.oplocku;
13019 	*locku_argsp = locku_args;
13020 
13021 	/*
13022 	 * XXX what should locku_args->locktype be?
13023 	 * setting to ALWAYS be READ_LT so at least
13024 	 * it is a valid locktype.
13025 	 */
13026 
13027 	locku_args->locktype = READ_LT;
13028 
13029 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13030 		flk->l_pid;
13031 
13032 	/*
13033 	 * Get the lock owner stateid.  If no lock owner
13034 	 * exists, return success.
13035 	 */
13036 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13037 	*lopp = lop;
13038 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13039 		is_spec = TRUE;
13040 	if (!lop || is_spec) {
13041 		/*
13042 		 * No lock owner so no locks to unlock.
13043 		 * Return success.  If there was a failed
13044 		 * reclaim earlier, the lock might still be
13045 		 * registered with the local locking code,
13046 		 * so notify it of the unlock.
13047 		 *
13048 		 * If the lockowner is using a special stateid,
13049 		 * then the original lock request (that created
13050 		 * this lockowner) was never successful, so we
13051 		 * have no lock to undo OTW.
13052 		 */
13053 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13054 			"nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13055 			"(%ld) so return success", (long)pid));
13056 
13057 		if (ctype == NFS4_LCK_CTYPE_NORM)
13058 			flk->l_pid = curproc->p_pid;
13059 		nfs4_register_lock_locally(vp, flk, flag, offset);
13060 		/*
13061 		 * Release our hold and NULL out so final_cleanup
13062 		 * doesn't try to end a lock seqid sync we
13063 		 * never started.
13064 		 */
13065 		if (is_spec) {
13066 			lock_owner_rele(lop);
13067 			*lopp = NULL;
13068 		}
13069 		*skip_get_err = TRUE;
13070 		*go_otwp = FALSE;
13071 		return;
13072 	}
13073 
13074 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13075 	if (ep->error == EAGAIN) {
13076 		lock_owner_rele(lop);
13077 		*lopp = NULL;
13078 		return;
13079 	}
13080 
13081 	mutex_enter(&lop->lo_lock);
13082 	locku_args->lock_stateid = lop->lock_stateid;
13083 	mutex_exit(&lop->lo_lock);
13084 	locku_args->seqid = lop->lock_seqid + 1;
13085 
13086 	/* leave the ref count on lop, rele after RPC call */
13087 
13088 	locku_args->offset = flk->l_start;
13089 	locku_args->length = flk->l_len;
13090 	if (flk->l_len == 0)
13091 		locku_args->length = ~locku_args->length;
13092 
13093 	*go_otwp = TRUE;
13094 }
13095 
13096 /*
13097  * Setup the LOCK4 arguments.
13098  *
13099  * Returns errors via the nfs4_error_t.
13100  * NFS4_OK		no problems
13101  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13102  * (other)		unrecoverable error
13103  */
13104 static void
13105 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13106 	nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13107 	nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13108 	flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13109 {
13110 	LOCK4args		*lock_args;
13111 	nfs4_open_owner_t	*oop = NULL;
13112 	nfs4_open_stream_t	*osp = NULL;
13113 	nfs4_lock_owner_t	*lop = NULL;
13114 	pid_t			pid;
13115 	rnode4_t		*rp = VTOR4(vp);
13116 
13117 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13118 
13119 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13120 	if (ep->error || ep->stat != NFS4_OK)
13121 		return;
13122 
13123 	argop->argop = OP_LOCK;
13124 	if (ctype == NFS4_LCK_CTYPE_NORM)
13125 		argsp->ctag = TAG_LOCK;
13126 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13127 		argsp->ctag = TAG_RELOCK;
13128 	else
13129 		argsp->ctag = TAG_LOCK_REINSTATE;
13130 	lock_args = &argop->nfs_argop4_u.oplock;
13131 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13132 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13133 	/*
13134 	 * Get the lock owner.  If no lock owner exists,
13135 	 * create a 'temporary' one and grab the open seqid
13136 	 * synchronization (which puts a hold on the open
13137 	 * owner and open stream).
13138 	 * This also grabs the lock seqid synchronization.
13139 	 */
13140 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid : flk->l_pid;
13141 	ep->stat =
13142 		nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13143 
13144 	if (ep->stat != NFS4_OK)
13145 		goto out;
13146 
13147 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13148 			&lock_args->locker);
13149 
13150 	lock_args->offset = flk->l_start;
13151 	lock_args->length = flk->l_len;
13152 	if (flk->l_len == 0)
13153 		lock_args->length = ~lock_args->length;
13154 	*lock_argsp = lock_args;
13155 out:
13156 	*oopp = oop;
13157 	*ospp = osp;
13158 	*lopp = lop;
13159 }
13160 
13161 /*
13162  * After we get the reply from the server, record the proper information
13163  * for possible resend lock requests.
13164  *
13165  * Allocates memory for the saved_rqstp if we have a lost lock to save.
13166  */
13167 static void
13168 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13169 	nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13170 	nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13171 	nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13172 {
13173 	bool_t unlock = (flk->l_type == F_UNLCK);
13174 
13175 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13176 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13177 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13178 
13179 	if (error != 0 && !unlock) {
13180 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13181 			    nfs4_client_lock_debug), (CE_NOTE,
13182 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13183 		    " for lop %p", (void *)lop));
13184 		ASSERT(lop != NULL);
13185 		mutex_enter(&lop->lo_lock);
13186 		lop->lo_pending_rqsts = 1;
13187 		mutex_exit(&lop->lo_lock);
13188 	}
13189 
13190 	lost_rqstp->lr_putfirst = FALSE;
13191 	lost_rqstp->lr_op = 0;
13192 
13193 	/*
13194 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13195 	 * recovery purposes so that the lock request that was sent
13196 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13197 	 * unmount.  This is done to have the client's local locking state
13198 	 * match the v4 server's state; that is, the request was
13199 	 * potentially received and accepted by the server but the client
13200 	 * thinks it was not.
13201 	 */
13202 	if (error == ETIMEDOUT || error == EINTR ||
13203 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13204 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13205 			    nfs4_client_lock_debug), (CE_NOTE,
13206 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13207 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13208 		    (void *)lop, (void *)oop, (void *)osp));
13209 		if (unlock)
13210 			lost_rqstp->lr_op = OP_LOCKU;
13211 		else {
13212 			lost_rqstp->lr_op = OP_LOCK;
13213 			lost_rqstp->lr_locktype = locktype;
13214 		}
13215 		/*
13216 		 * Objects are held and rele'd via the recovery code.
13217 		 * See nfs4_save_lost_rqst.
13218 		 */
13219 		lost_rqstp->lr_vp = vp;
13220 		lost_rqstp->lr_dvp = NULL;
13221 		lost_rqstp->lr_oop = oop;
13222 		lost_rqstp->lr_osp = osp;
13223 		lost_rqstp->lr_lop = lop;
13224 		lost_rqstp->lr_cr = cr;
13225 		switch (ctype) {
13226 		case NFS4_LCK_CTYPE_NORM:
13227 			flk->l_pid = ttoproc(curthread)->p_pid;
13228 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13229 			break;
13230 		case NFS4_LCK_CTYPE_REINSTATE:
13231 			lost_rqstp->lr_putfirst = TRUE;
13232 			lost_rqstp->lr_ctype = ctype;
13233 			break;
13234 		default:
13235 			break;
13236 		}
13237 		lost_rqstp->lr_flk = flk;
13238 	}
13239 }
13240 
13241 /*
13242  * Update lop's seqid.  Also update the seqid stored in a resend request,
13243  * if any.  (Some recovery errors increment the seqid, and we may have to
13244  * send the resend request again.)
13245  */
13246 
13247 static void
13248 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13249     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13250 {
13251 	if (lock_args) {
13252 		if (lock_args->locker.new_lock_owner == TRUE)
13253 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13254 		else {
13255 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13256 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13257 		}
13258 	} else if (locku_args) {
13259 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13260 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13261 	}
13262 }
13263 
13264 /*
13265  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13266  * COMPOUND4 args/res for calls that need to retry.
13267  * Switches the *cred_otwp to base_cr.
13268  */
13269 static void
13270 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13271     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13272     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13273     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13274     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13275 {
13276 	nfs4_open_owner_t	*oop = *oopp;
13277 	nfs4_open_stream_t	*osp = *ospp;
13278 	nfs4_lock_owner_t	*lop = *lopp;
13279 	nfs_argop4		*argop = (*argspp)->array;
13280 
13281 	if (*did_start_fop) {
13282 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13283 			    needrecov);
13284 		*did_start_fop = FALSE;
13285 	}
13286 	ASSERT((*argspp)->array_len == 2);
13287 	if (argop[1].argop == OP_LOCK)
13288 		nfs4args_lock_free(&argop[1]);
13289 	else if (argop[1].argop == OP_LOCKT)
13290 		nfs4args_lockt_free(&argop[1]);
13291 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13292 	if (!error)
13293 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13294 	*argspp = NULL;
13295 	*respp = NULL;
13296 
13297 	if (lop) {
13298 		nfs4_end_lock_seqid_sync(lop);
13299 		lock_owner_rele(lop);
13300 		*lopp = NULL;
13301 	}
13302 
13303 	/* need to free up the reference on osp for lock args */
13304 	if (osp != NULL) {
13305 		open_stream_rele(osp, VTOR4(vp));
13306 		*ospp = NULL;
13307 	}
13308 
13309 	/* need to free up the reference on oop for lock args */
13310 	if (oop != NULL) {
13311 		nfs4_end_open_seqid_sync(oop);
13312 		open_owner_rele(oop);
13313 		*oopp = NULL;
13314 	}
13315 
13316 	crfree(*cred_otwp);
13317 	*cred_otwp = base_cr;
13318 	crhold(*cred_otwp);
13319 }
13320 
13321 /*
13322  * Function to process the client's recovery for nfs4frlock.
13323  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13324  *
13325  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13326  * COMPOUND4 args/res for calls that need to retry.
13327  *
13328  * Note: the rp's r_lkserlock is *not* dropped during this path.
13329  */
13330 static bool_t
13331 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13332 	COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13333 	LOCK4args *lock_args, LOCKU4args *locku_args,
13334 	nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13335 	nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13336 	nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13337 	bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13338 {
13339 	nfs4_open_owner_t	*oop = *oopp;
13340 	nfs4_open_stream_t	*osp = *ospp;
13341 	nfs4_lock_owner_t	*lop = *lopp;
13342 
13343 	bool_t abort, retry;
13344 
13345 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13346 	ASSERT((*argspp) != NULL);
13347 	ASSERT((*respp) != NULL);
13348 	if (lock_args || locku_args)
13349 		ASSERT(lop != NULL);
13350 
13351 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13352 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13353 
13354 	retry = TRUE;
13355 	abort = FALSE;
13356 	if (needrecov) {
13357 		nfs4_bseqid_entry_t *bsep = NULL;
13358 		nfs_opnum4 op;
13359 
13360 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13361 
13362 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13363 			seqid4 seqid;
13364 
13365 			if (lock_args) {
13366 				if (lock_args->locker.new_lock_owner == TRUE)
13367 					seqid = lock_args->locker.locker4_u.
13368 						    open_owner.open_seqid;
13369 				else
13370 					seqid = lock_args->locker.locker4_u.
13371 						    lock_owner.lock_seqid;
13372 			} else if (locku_args) {
13373 				seqid = locku_args->seqid;
13374 			} else {
13375 				seqid = 0;
13376 			}
13377 
13378 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13379 				flk->l_pid, (*argspp)->ctag, seqid);
13380 		}
13381 
13382 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13383 			    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13384 			    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13385 			    NULL, op, bsep);
13386 
13387 		if (bsep)
13388 			kmem_free(bsep, sizeof (*bsep));
13389 	}
13390 
13391 	/*
13392 	 * Return that we do not want to retry the request for 3 cases:
13393 	 * 1. If we received EINTR or are bailing out because of a forced
13394 	 *    unmount, we came into this code path just for the sake of
13395 	 *    initiating recovery, we now need to return the error.
13396 	 * 2. If we have aborted recovery.
13397 	 * 3. We received NFS4ERR_BAD_SEQID.
13398 	 */
13399 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13400 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13401 		retry = FALSE;
13402 
13403 	if (*did_start_fop == TRUE) {
13404 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13405 		    needrecov);
13406 		*did_start_fop = FALSE;
13407 	}
13408 
13409 	if (retry == TRUE) {
13410 		nfs_argop4	*argop;
13411 
13412 		argop = (*argspp)->array;
13413 		ASSERT((*argspp)->array_len == 2);
13414 
13415 		if (argop[1].argop == OP_LOCK)
13416 			nfs4args_lock_free(&argop[1]);
13417 		else if (argop[1].argop == OP_LOCKT)
13418 			nfs4args_lockt_free(&argop[1]);
13419 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13420 		if (!ep->error)
13421 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13422 		*respp = NULL;
13423 		*argspp = NULL;
13424 	}
13425 
13426 	if (lop != NULL) {
13427 		nfs4_end_lock_seqid_sync(lop);
13428 		lock_owner_rele(lop);
13429 	}
13430 
13431 	*lopp = NULL;
13432 
13433 	/* need to free up the reference on osp for lock args */
13434 	if (osp != NULL) {
13435 		open_stream_rele(osp, rp);
13436 		*ospp = NULL;
13437 	}
13438 
13439 	/* need to free up the reference on oop for lock args */
13440 	if (oop != NULL) {
13441 		nfs4_end_open_seqid_sync(oop);
13442 		open_owner_rele(oop);
13443 		*oopp = NULL;
13444 	}
13445 
13446 	return (retry);
13447 }
13448 
13449 /*
13450  * Handles the succesful reply from the server for nfs4frlock.
13451  */
13452 static void
13453 nfs4frlock_results_ok(nfs4_lock_call_type_t ctype, int cmd, flock64_t *flk,
13454 	vnode_t *vp, int flag, u_offset_t offset,
13455 	nfs4_lost_rqst_t *resend_rqstp)
13456 {
13457 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13458 	if ((cmd == F_SETLK || cmd == F_SETLKW) &&
13459 	    (flk->l_type == F_RDLCK || flk->l_type == F_WRLCK)) {
13460 		if (ctype == NFS4_LCK_CTYPE_NORM) {
13461 			flk->l_pid = ttoproc(curthread)->p_pid;
13462 			/*
13463 			 * We do not register lost locks locally in
13464 			 * the 'resend' case since the user/application
13465 			 * doesn't think we have the lock.
13466 			 */
13467 			ASSERT(!resend_rqstp);
13468 			nfs4_register_lock_locally(vp, flk, flag, offset);
13469 		}
13470 	}
13471 }
13472 
13473 /*
13474  * Handle the DENIED reply from the server for nfs4frlock.
13475  * Returns TRUE if we should retry the request; FALSE otherwise.
13476  *
13477  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13478  * COMPOUND4 args/res for calls that need to retry.  Can also
13479  * drop and regrab the r_lkserlock.
13480  */
13481 static bool_t
13482 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13483 	LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13484 	nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13485 	vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13486 	nfs4_recov_state_t *recov_statep, int needrecov,
13487 	COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13488 	clock_t *tick_delayp, short *whencep, int *errorp,
13489 	nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13490 	bool_t *skip_get_err)
13491 {
13492 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13493 
13494 	if (lock_args) {
13495 		nfs4_open_owner_t	*oop = *oopp;
13496 		nfs4_open_stream_t	*osp = *ospp;
13497 		nfs4_lock_owner_t	*lop = *lopp;
13498 		int			intr;
13499 
13500 		/*
13501 		 * Blocking lock needs to sleep and retry from the request.
13502 		 *
13503 		 * Do not block and wait for 'resend' or 'reinstate'
13504 		 * lock requests, just return the error.
13505 		 *
13506 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13507 		 */
13508 		if (cmd == F_SETLKW) {
13509 			rnode4_t *rp = VTOR4(vp);
13510 			nfs_argop4 *argop = (*argspp)->array;
13511 
13512 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13513 
13514 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13515 				recov_statep, needrecov);
13516 			*did_start_fop = FALSE;
13517 			ASSERT((*argspp)->array_len == 2);
13518 			if (argop[1].argop == OP_LOCK)
13519 				nfs4args_lock_free(&argop[1]);
13520 			else if (argop[1].argop == OP_LOCKT)
13521 				nfs4args_lockt_free(&argop[1]);
13522 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13523 			if (*respp)
13524 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13525 							(caddr_t)*respp);
13526 			*argspp = NULL;
13527 			*respp = NULL;
13528 			nfs4_end_lock_seqid_sync(lop);
13529 			lock_owner_rele(lop);
13530 			*lopp = NULL;
13531 			if (osp != NULL) {
13532 				open_stream_rele(osp, rp);
13533 				*ospp = NULL;
13534 			}
13535 			if (oop != NULL) {
13536 				nfs4_end_open_seqid_sync(oop);
13537 				open_owner_rele(oop);
13538 				*oopp = NULL;
13539 			}
13540 
13541 			nfs_rw_exit(&rp->r_lkserlock);
13542 
13543 			intr = nfs4_block_and_wait(tick_delayp, rp);
13544 
13545 			if (intr) {
13546 				(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13547 						RW_WRITER, FALSE);
13548 				*errorp = EINTR;
13549 				return (FALSE);
13550 			}
13551 
13552 			(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13553 					RW_WRITER, FALSE);
13554 
13555 			/*
13556 			 * Make sure we are still safe to lock with
13557 			 * regards to mmapping.
13558 			 */
13559 			if (!nfs4_safelock(vp, flk, cr)) {
13560 				*errorp = EAGAIN;
13561 				return (FALSE);
13562 			}
13563 
13564 			return (TRUE);
13565 		}
13566 		if (ctype == NFS4_LCK_CTYPE_NORM)
13567 			*errorp = EAGAIN;
13568 		*skip_get_err = TRUE;
13569 		flk->l_whence = 0;
13570 		*whencep = 0;
13571 		return (FALSE);
13572 	} else if (lockt_args) {
13573 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13574 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
13575 
13576 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
13577 			flk, lockt_args);
13578 
13579 		/* according to NLM code */
13580 		*errorp = 0;
13581 		*whencep = 0;
13582 		*skip_get_err = TRUE;
13583 		return (FALSE);
13584 	}
13585 	return (FALSE);
13586 }
13587 
13588 /*
13589  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
13590  */
13591 static void
13592 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
13593 {
13594 	switch (resp->status) {
13595 	case NFS4ERR_ACCESS:
13596 	case NFS4ERR_ADMIN_REVOKED:
13597 	case NFS4ERR_BADHANDLE:
13598 	case NFS4ERR_BAD_RANGE:
13599 	case NFS4ERR_BAD_SEQID:
13600 	case NFS4ERR_BAD_STATEID:
13601 	case NFS4ERR_BADXDR:
13602 	case NFS4ERR_DEADLOCK:
13603 	case NFS4ERR_DELAY:
13604 	case NFS4ERR_EXPIRED:
13605 	case NFS4ERR_FHEXPIRED:
13606 	case NFS4ERR_GRACE:
13607 	case NFS4ERR_INVAL:
13608 	case NFS4ERR_ISDIR:
13609 	case NFS4ERR_LEASE_MOVED:
13610 	case NFS4ERR_LOCK_NOTSUPP:
13611 	case NFS4ERR_LOCK_RANGE:
13612 	case NFS4ERR_MOVED:
13613 	case NFS4ERR_NOFILEHANDLE:
13614 	case NFS4ERR_NO_GRACE:
13615 	case NFS4ERR_OLD_STATEID:
13616 	case NFS4ERR_OPENMODE:
13617 	case NFS4ERR_RECLAIM_BAD:
13618 	case NFS4ERR_RECLAIM_CONFLICT:
13619 	case NFS4ERR_RESOURCE:
13620 	case NFS4ERR_SERVERFAULT:
13621 	case NFS4ERR_STALE:
13622 	case NFS4ERR_STALE_CLIENTID:
13623 	case NFS4ERR_STALE_STATEID:
13624 		return;
13625 	default:
13626 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13627 		    "nfs4frlock_results_default: got unrecognizable "
13628 		    "res.status %d", resp->status));
13629 		*errorp = NFS4ERR_INVAL;
13630 	}
13631 }
13632 
13633 /*
13634  * The lock request was successful, so update the client's state.
13635  */
13636 static void
13637 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
13638 	LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
13639 	vnode_t *vp, flock64_t *flk, cred_t *cr,
13640 	nfs4_lost_rqst_t *resend_rqstp)
13641 {
13642 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13643 
13644 	if (lock_args) {
13645 		LOCK4res *lock_res;
13646 
13647 		lock_res = &resop->nfs_resop4_u.oplock;
13648 		/* update the stateid with server's response */
13649 
13650 		if (lock_args->locker.new_lock_owner == TRUE) {
13651 			mutex_enter(&lop->lo_lock);
13652 			lop->lo_just_created = NFS4_PERM_CREATED;
13653 			mutex_exit(&lop->lo_lock);
13654 		}
13655 
13656 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
13657 
13658 		/*
13659 		 * If the lock was the result of a resending a lost
13660 		 * request, we've synched up the stateid and seqid
13661 		 * with the server, but now the server might be out of sync
13662 		 * with what the application thinks it has for locks.
13663 		 * Clean that up here.  It's unclear whether we should do
13664 		 * this even if the filesystem has been forcibly unmounted.
13665 		 * For most servers, it's probably wasted effort, but
13666 		 * RFC3530 lets servers require that unlocks exactly match
13667 		 * the locks that are held.
13668 		 */
13669 		if (resend_rqstp != NULL &&
13670 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
13671 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
13672 		} else {
13673 			flk->l_whence = 0;
13674 		}
13675 	} else if (locku_args) {
13676 		LOCKU4res *locku_res;
13677 
13678 		locku_res = &resop->nfs_resop4_u.oplocku;
13679 
13680 		/* Update the stateid with the server's response */
13681 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
13682 	} else if (lockt_args) {
13683 		/* Switch the lock type to express success, see fcntl */
13684 		flk->l_type = F_UNLCK;
13685 		flk->l_whence = 0;
13686 	}
13687 }
13688 
13689 /*
13690  * Do final cleanup before exiting nfs4frlock.
13691  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13692  * COMPOUND4 args/res for calls that haven't already.
13693  */
13694 static void
13695 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
13696 	COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
13697 	nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
13698 	nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13699 	short whence, u_offset_t offset, struct lm_sysid *ls,
13700 	int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
13701 	bool_t did_start_fop, bool_t skip_get_err,
13702 	cred_t *cred_otw, cred_t *cred)
13703 {
13704 	mntinfo4_t	*mi = VTOMI4(vp);
13705 	rnode4_t	*rp = VTOR4(vp);
13706 	int		error = *errorp;
13707 	nfs_argop4	*argop;
13708 
13709 	ASSERT(nfs_zone() == mi->mi_zone);
13710 	/*
13711 	 * The client recovery code wants the raw status information,
13712 	 * so don't map the NFS status code to an errno value for
13713 	 * non-normal call types.
13714 	 */
13715 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13716 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
13717 			*errorp = geterrno4(resp->status);
13718 		if (did_start_fop == TRUE)
13719 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
13720 				needrecov);
13721 
13722 		if (!error && resp && resp->status == NFS4_OK) {
13723 		/*
13724 		 * We've established a new lock on the server, so invalidate
13725 		 * the pages associated with the vnode to get the most up to
13726 		 * date pages from the server after acquiring the lock. We
13727 		 * want to be sure that the read operation gets the newest data.
13728 		 * N.B.
13729 		 * We used to do this in nfs4frlock_results_ok but that doesn't
13730 		 * work since VOP_PUTPAGE can call nfs4_commit which calls
13731 		 * nfs4_start_fop. We flush the pages below after calling
13732 		 * nfs4_end_fop above
13733 		 */
13734 			int error;
13735 
13736 			error = VOP_PUTPAGE(vp, (u_offset_t)0,
13737 						0, B_INVAL, cred);
13738 
13739 			if (error && (error == ENOSPC || error == EDQUOT)) {
13740 				rnode4_t *rp = VTOR4(vp);
13741 
13742 				mutex_enter(&rp->r_statelock);
13743 				if (!rp->r_error)
13744 					rp->r_error = error;
13745 				mutex_exit(&rp->r_statelock);
13746 			}
13747 		}
13748 	}
13749 	if (argsp) {
13750 		ASSERT(argsp->array_len == 2);
13751 		argop = argsp->array;
13752 		if (argop[1].argop == OP_LOCK)
13753 			nfs4args_lock_free(&argop[1]);
13754 		else if (argop[1].argop == OP_LOCKT)
13755 			nfs4args_lockt_free(&argop[1]);
13756 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13757 		if (resp)
13758 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
13759 	}
13760 
13761 	/* free the reference on the lock owner */
13762 	if (lop != NULL) {
13763 		nfs4_end_lock_seqid_sync(lop);
13764 		lock_owner_rele(lop);
13765 	}
13766 
13767 	/* need to free up the reference on osp for lock args */
13768 	if (osp != NULL)
13769 		open_stream_rele(osp, rp);
13770 
13771 	/* need to free up the reference on oop for lock args */
13772 	if (oop != NULL) {
13773 		nfs4_end_open_seqid_sync(oop);
13774 		open_owner_rele(oop);
13775 	}
13776 
13777 	(void) convoff(vp, flk, whence, offset);
13778 
13779 	lm_rel_sysid(ls);
13780 
13781 	/*
13782 	 * Record debug information in the event we get EINVAL.
13783 	 */
13784 	mutex_enter(&mi->mi_lock);
13785 	if (*errorp == EINVAL && (lock_args || locku_args) &&
13786 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
13787 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
13788 			zcmn_err(getzoneid(), CE_NOTE,
13789 			    "%s operation failed with "
13790 			    "EINVAL probably since the server, %s,"
13791 			    " doesn't support POSIX style locking",
13792 			    lock_args ? "LOCK" : "LOCKU",
13793 			    mi->mi_curr_serv->sv_hostname);
13794 			mi->mi_flags |= MI4_LOCK_DEBUG;
13795 		}
13796 	}
13797 	mutex_exit(&mi->mi_lock);
13798 
13799 	if (cred_otw)
13800 		crfree(cred_otw);
13801 }
13802 
13803 /*
13804  * This calls the server and the local locking code.
13805  *
13806  * Client locks are registerred locally by oring the sysid with
13807  * LM_SYSID_CLIENT. The server registers locks locally using just the sysid.
13808  * We need to distinguish between the two to avoid collision in case one
13809  * machine is used as both client and server.
13810  *
13811  * Blocking lock requests will continually retry to acquire the lock
13812  * forever.
13813  *
13814  * The ctype is defined as follows:
13815  * NFS4_LCK_CTYPE_NORM: normal lock request.
13816  *
13817  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
13818  * recovery, get the pid from flk instead of curproc, and don't reregister
13819  * the lock locally.
13820  *
13821  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
13822  * that we will use the information passed in via resend_rqstp to setup the
13823  * lock/locku request.  This resend is the exact same request as the 'lost
13824  * lock', and is initiated by the recovery framework. A successful resend
13825  * request can initiate one or more reinstate requests.
13826  *
13827  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
13828  * does not trigger additional reinstate requests.  This lock call type is
13829  * set for setting the v4 server's locking state back to match what the
13830  * client's local locking state is in the event of a received 'lost lock'.
13831  *
13832  * Errors are returned via the nfs4_error_t parameter.
13833  */
13834 void
13835 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
13836 		int flag, u_offset_t offset, cred_t *cr, nfs4_error_t *ep,
13837 		nfs4_lost_rqst_t *resend_rqstp, int *did_reclaimp)
13838 {
13839 	COMPOUND4args_clnt	args, *argsp = NULL;
13840 	COMPOUND4res_clnt	res, *resp = NULL;
13841 	nfs_argop4	*argop;
13842 	nfs_resop4	*resop;
13843 	rnode4_t	*rp;
13844 	int		doqueue = 1;
13845 	clock_t		tick_delay;  /* delay in clock ticks */
13846 	struct lm_sysid	*ls;
13847 	LOCK4args	*lock_args = NULL;
13848 	LOCKU4args	*locku_args = NULL;
13849 	LOCKT4args	*lockt_args = NULL;
13850 	nfs4_open_owner_t *oop = NULL;
13851 	nfs4_open_stream_t *osp = NULL;
13852 	nfs4_lock_owner_t *lop = NULL;
13853 	bool_t		needrecov = FALSE;
13854 	nfs4_recov_state_t recov_state;
13855 	short		whence;
13856 	nfs4_op_hint_t	op_hint;
13857 	nfs4_lost_rqst_t lost_rqst;
13858 	bool_t		retry = FALSE;
13859 	bool_t		did_start_fop = FALSE;
13860 	bool_t		skip_get_err = FALSE;
13861 	cred_t		*cred_otw = NULL;
13862 	bool_t		recovonly;	/* just queue request */
13863 	int		frc_no_reclaim = 0;
13864 #ifdef DEBUG
13865 	char *name;
13866 #endif
13867 
13868 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13869 
13870 #ifdef DEBUG
13871 	name = fn_name(VTOSV(vp)->sv_name);
13872 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
13873 	    "%s: cmd %d, type %d, offset %llu, start %"PRIx64", "
13874 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
13875 	    "resend request %s", name, cmd, flk->l_type, offset, flk->l_start,
13876 	    flk->l_len, ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid :
13877 	    flk->l_pid, flk->l_sysid, nfs4frlock_get_call_type(ctype),
13878 	    resend_rqstp ? "TRUE" : "FALSE"));
13879 	kmem_free(name, MAXNAMELEN);
13880 #endif
13881 
13882 	nfs4_error_zinit(ep);
13883 	ep->error = nfs4frlock_validate_args(cmd, flk, flag, vp, offset);
13884 	if (ep->error)
13885 		return;
13886 	ep->error = nfs4frlock_get_sysid(&ls, vp, flk);
13887 	if (ep->error)
13888 		return;
13889 	nfs4frlock_pre_setup(&tick_delay, &recov_state, flk, &whence,
13890 	    vp, cr, &cred_otw);
13891 
13892 recov_retry:
13893 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
13894 		&retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
13895 	rp = VTOR4(vp);
13896 
13897 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
13898 			    &did_start_fop, &recovonly);
13899 
13900 	if (ep->error)
13901 		goto out;
13902 
13903 	if (recovonly) {
13904 		/*
13905 		 * Leave the request for the recovery system to deal with.
13906 		 */
13907 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13908 		ASSERT(cmd != F_GETLK);
13909 		ASSERT(flk->l_type == F_UNLCK);
13910 
13911 		nfs4_error_init(ep, EINTR);
13912 		needrecov = TRUE;
13913 		lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
13914 		if (lop != NULL) {
13915 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
13916 				NULL, NULL, lop, flk, &lost_rqst, cr, vp);
13917 			(void) nfs4_start_recovery(ep,
13918 				VTOMI4(vp), vp, NULL, NULL,
13919 				(lost_rqst.lr_op == OP_LOCK ||
13920 				lost_rqst.lr_op == OP_LOCKU) ?
13921 				&lost_rqst : NULL, OP_LOCKU, NULL);
13922 			lock_owner_rele(lop);
13923 			lop = NULL;
13924 		}
13925 		flk->l_pid = curproc->p_pid;
13926 		nfs4_register_lock_locally(vp, flk, flag, offset);
13927 		goto out;
13928 	}
13929 
13930 	/* putfh directory fh */
13931 	argop[0].argop = OP_CPUTFH;
13932 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
13933 
13934 	/*
13935 	 * Set up the over-the-wire arguments and get references to the
13936 	 * open owner, etc.
13937 	 */
13938 
13939 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
13940 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
13941 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
13942 			&argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
13943 	} else {
13944 		bool_t go_otw = TRUE;
13945 
13946 		ASSERT(resend_rqstp == NULL);
13947 
13948 		switch (cmd) {
13949 		case F_GETLK:
13950 		case F_O_GETLK:
13951 			nfs4frlock_setup_lockt_args(ctype, &argop[1],
13952 					&lockt_args, argsp, flk, rp);
13953 			break;
13954 		case F_SETLKW:
13955 		case F_SETLK:
13956 			if (flk->l_type == F_UNLCK)
13957 				nfs4frlock_setup_locku_args(ctype,
13958 						&argop[1], &locku_args, flk,
13959 						&lop, ep, argsp,
13960 						vp, flag, offset, cr,
13961 						&skip_get_err, &go_otw);
13962 			else
13963 				nfs4frlock_setup_lock_args(ctype,
13964 					&lock_args, &oop, &osp, &lop, &argop[1],
13965 					argsp, flk, cmd, vp, cr, ep);
13966 
13967 			if (ep->error)
13968 				goto out;
13969 
13970 			switch (ep->stat) {
13971 			case NFS4_OK:
13972 				break;
13973 			case NFS4ERR_DELAY:
13974 				/* recov thread never gets this error */
13975 				ASSERT(resend_rqstp == NULL);
13976 				ASSERT(did_start_fop);
13977 
13978 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13979 				    &recov_state, TRUE);
13980 				did_start_fop = FALSE;
13981 				if (argop[1].argop == OP_LOCK)
13982 					nfs4args_lock_free(&argop[1]);
13983 				else if (argop[1].argop == OP_LOCKT)
13984 					nfs4args_lockt_free(&argop[1]);
13985 				kmem_free(argop, 2 * sizeof (nfs_argop4));
13986 				argsp = NULL;
13987 				goto recov_retry;
13988 			default:
13989 				ep->error = EIO;
13990 				goto out;
13991 			}
13992 			break;
13993 		default:
13994 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13995 				"nfs4_frlock: invalid cmd %d", cmd));
13996 			ep->error = EINVAL;
13997 			goto out;
13998 		}
13999 
14000 		if (!go_otw)
14001 			goto out;
14002 	}
14003 
14004 	/* XXX should we use the local reclock as a cache ? */
14005 	/*
14006 	 * Unregister the lock with the local locking code before
14007 	 * contacting the server.  This avoids a potential race where
14008 	 * another process gets notified that it has been granted a lock
14009 	 * before we can unregister ourselves locally.
14010 	 */
14011 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK) {
14012 		if (ctype == NFS4_LCK_CTYPE_NORM)
14013 			flk->l_pid = ttoproc(curthread)->p_pid;
14014 		nfs4_register_lock_locally(vp, flk, flag, offset);
14015 	}
14016 
14017 	/*
14018 	 * Send the server the lock request.  Continually loop with a delay
14019 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14020 	 */
14021 	resp = &res;
14022 
14023 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14024 	    (CE_NOTE,
14025 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14026 	    rnode4info(rp)));
14027 
14028 	if (lock_args && frc_no_reclaim) {
14029 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14030 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14031 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14032 		lock_args->reclaim = FALSE;
14033 		if (did_reclaimp)
14034 			*did_reclaimp = 0;
14035 	}
14036 
14037 	/*
14038 	 * Do the OTW call.
14039 	 */
14040 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14041 
14042 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14043 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14044 
14045 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14046 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14047 	    "nfs4frlock: needrecov %d", needrecov));
14048 
14049 	if (ep->error != 0 && !needrecov && ep->error != EACCES)
14050 		goto out;
14051 
14052 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14053 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14054 		    args.ctag);
14055 
14056 	if ((ep->error == EACCES ||
14057 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14058 	    cred_otw != cr) {
14059 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14060 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14061 		    cr, &cred_otw);
14062 		goto recov_retry;
14063 	}
14064 
14065 	if (needrecov) {
14066 		/*
14067 		 * LOCKT requests don't need to recover from lost
14068 		 * requests since they don't create/modify state.
14069 		 */
14070 		if ((ep->error == EINTR ||
14071 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14072 		    lockt_args)
14073 			goto out;
14074 		/*
14075 		 * Do not attempt recovery for requests initiated by
14076 		 * the recovery framework.  Let the framework redrive them.
14077 		 */
14078 		if (ctype != NFS4_LCK_CTYPE_NORM)
14079 			goto out;
14080 		else {
14081 			ASSERT(resend_rqstp == NULL);
14082 		}
14083 
14084 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14085 			flk_to_locktype(cmd, flk->l_type),
14086 			oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14087 
14088 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14089 			    &resp, lock_args, locku_args, &oop, &osp, &lop,
14090 			    rp, vp, &recov_state, op_hint, &did_start_fop,
14091 			    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14092 
14093 		if (retry) {
14094 			ASSERT(oop == NULL);
14095 			ASSERT(osp == NULL);
14096 			ASSERT(lop == NULL);
14097 			goto recov_retry;
14098 		}
14099 		goto out;
14100 	}
14101 
14102 	/*
14103 	 * Process the reply.
14104 	 */
14105 	switch (resp->status) {
14106 	case NFS4_OK:
14107 		resop = &resp->array[1];
14108 		nfs4frlock_results_ok(ctype, cmd, flk, vp, flag, offset,
14109 			resend_rqstp);
14110 		/*
14111 		 * Have a successful lock operation, now update state.
14112 		 */
14113 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14114 			resop, lop, vp, flk, cr, resend_rqstp);
14115 		break;
14116 
14117 	case NFS4ERR_DENIED:
14118 		resop = &resp->array[1];
14119 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14120 				&oop, &osp, &lop, cmd, vp, flk, op_hint,
14121 				&recov_state, needrecov, &argsp, &resp,
14122 				&tick_delay, &whence, &ep->error, resop, cr,
14123 				&did_start_fop, &skip_get_err);
14124 
14125 		if (retry) {
14126 			ASSERT(oop == NULL);
14127 			ASSERT(osp == NULL);
14128 			ASSERT(lop == NULL);
14129 			goto recov_retry;
14130 		}
14131 		break;
14132 	/*
14133 	 * If the server won't let us reclaim, fall-back to trying to lock
14134 	 * the file from scratch. Code elsewhere will check the changeinfo
14135 	 * to ensure the file hasn't been changed.
14136 	 */
14137 	case NFS4ERR_NO_GRACE:
14138 		if (lock_args && lock_args->reclaim == TRUE) {
14139 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14140 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14141 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14142 			frc_no_reclaim = 1;
14143 			/* clean up before retrying */
14144 			needrecov = 0;
14145 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14146 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14147 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14148 			goto recov_retry;
14149 		}
14150 		/* FALLTHROUGH */
14151 
14152 	default:
14153 		nfs4frlock_results_default(resp, &ep->error);
14154 		break;
14155 	}
14156 out:
14157 	/*
14158 	 * Process and cleanup from error.  Make interrupted unlock
14159 	 * requests look successful, since they will be handled by the
14160 	 * client recovery code.
14161 	 */
14162 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14163 		needrecov, oop, osp, lop, flk, whence, offset, ls, &ep->error,
14164 		lock_args, locku_args, did_start_fop,
14165 		skip_get_err, cred_otw, cr);
14166 
14167 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14168 	    (cmd == F_SETLK || cmd == F_SETLKW))
14169 		ep->error = 0;
14170 }
14171 
14172 /*
14173  * nfs4_safelock:
14174  *
14175  * Return non-zero if the given lock request can be handled without
14176  * violating the constraints on concurrent mapping and locking.
14177  */
14178 
14179 static int
14180 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14181 {
14182 	rnode4_t *rp = VTOR4(vp);
14183 	struct vattr va;
14184 	int error;
14185 
14186 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14187 	ASSERT(rp->r_mapcnt >= 0);
14188 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14189 		"(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14190 		"write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14191 		bfp->l_start, bfp->l_len, rp->r_mapcnt));
14192 
14193 	if (rp->r_mapcnt == 0)
14194 		return (1);		/* always safe if not mapped */
14195 
14196 	/*
14197 	 * If the file is already mapped and there are locks, then they
14198 	 * should be all safe locks.  So adding or removing a lock is safe
14199 	 * as long as the new request is safe (i.e., whole-file, meaning
14200 	 * length and starting offset are both zero).
14201 	 */
14202 
14203 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14204 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14205 			"cannot lock a memory mapped file unless locking the "
14206 			"entire file: start %"PRIx64", len %"PRIx64,
14207 			bfp->l_start, bfp->l_len));
14208 		return (0);
14209 	}
14210 
14211 	/* mandatory locking and mapping don't mix */
14212 	va.va_mask = AT_MODE;
14213 	error = VOP_GETATTR(vp, &va, 0, cr);
14214 	if (error != 0) {
14215 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14216 		"getattr error %d", error));
14217 		return (0);		/* treat errors conservatively */
14218 	}
14219 	if (MANDLOCK(vp, va.va_mode)) {
14220 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14221 			"cannot mandatory lock and mmap a file"));
14222 		return (0);
14223 	}
14224 
14225 	return (1);
14226 }
14227 
14228 
14229 /*
14230  * Register the lock locally within Solaris.
14231  * As the client, we "or" the sysid with LM_SYSID_CLIENT when
14232  * recording locks locally.
14233  *
14234  * This should handle conflicts/cooperation with NFS v2/v3 since all locks
14235  * are registered locally.
14236  */
14237 void
14238 nfs4_register_lock_locally(vnode_t *vp, struct flock64 *flk, int flag,
14239 	u_offset_t offset)
14240 {
14241 	int oldsysid;
14242 	int error;
14243 #ifdef DEBUG
14244 	char *name;
14245 #endif
14246 
14247 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14248 
14249 #ifdef DEBUG
14250 	name = fn_name(VTOSV(vp)->sv_name);
14251 	NFS4_DEBUG(nfs4_client_lock_debug,
14252 	    (CE_NOTE, "nfs4_register_lock_locally: %s: type %d, "
14253 	    "start %"PRIx64", length %"PRIx64", pid %ld, sysid %d",
14254 	    name, flk->l_type, flk->l_start, flk->l_len, (long)flk->l_pid,
14255 	    flk->l_sysid));
14256 	kmem_free(name, MAXNAMELEN);
14257 #endif
14258 
14259 	/* register the lock with local locking */
14260 	oldsysid = flk->l_sysid;
14261 	flk->l_sysid |= LM_SYSID_CLIENT;
14262 	error = reclock(vp, flk, SETFLCK, flag, offset, NULL);
14263 #ifdef DEBUG
14264 	if (error != 0) {
14265 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14266 			"nfs4_register_lock_locally: could not register with"
14267 			" local locking"));
14268 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14269 			"error %d, vp 0x%p, pid %d, sysid 0x%x",
14270 			error, (void *)vp, flk->l_pid, flk->l_sysid));
14271 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14272 			"type %d off 0x%" PRIx64 " len 0x%" PRIx64,
14273 			flk->l_type, flk->l_start, flk->l_len));
14274 		(void) reclock(vp, flk, 0, flag, offset, NULL);
14275 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14276 			"blocked by pid %d sysid 0x%x type %d "
14277 			"off 0x%" PRIx64 " len 0x%" PRIx64,
14278 			flk->l_pid, flk->l_sysid, flk->l_type, flk->l_start,
14279 			flk->l_len));
14280 	}
14281 #endif
14282 	flk->l_sysid = oldsysid;
14283 }
14284 
14285 /*
14286  * nfs4_lockrelease:
14287  *
14288  * Release any locks on the given vnode that are held by the current
14289  * process.  Also removes the lock owner (if one exists) from the rnode's
14290  * list.
14291  */
14292 static int
14293 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14294 {
14295 	flock64_t ld;
14296 	int ret, error;
14297 	rnode4_t *rp;
14298 	nfs4_lock_owner_t *lop;
14299 	nfs4_recov_state_t recov_state;
14300 	mntinfo4_t *mi;
14301 	bool_t possible_orphan = FALSE;
14302 	bool_t recovonly;
14303 
14304 	ASSERT((uintptr_t)vp > KERNELBASE);
14305 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14306 
14307 	rp = VTOR4(vp);
14308 	mi = VTOMI4(vp);
14309 
14310 	/*
14311 	 * If we have not locked anything then we can
14312 	 * just return since we have no work to do.
14313 	 */
14314 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14315 		return (0);
14316 	}
14317 
14318 	/*
14319 	 * We need to comprehend that another thread may
14320 	 * kick off recovery and the lock_owner we have stashed
14321 	 * in lop might be invalid so we should NOT cache it
14322 	 * locally!
14323 	 */
14324 	recov_state.rs_flags = 0;
14325 	recov_state.rs_num_retry_despite_err = 0;
14326 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14327 			    &recovonly);
14328 	if (error) {
14329 		mutex_enter(&rp->r_statelock);
14330 		rp->r_flags |= R4LODANGLERS;
14331 		mutex_exit(&rp->r_statelock);
14332 		return (error);
14333 	}
14334 
14335 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14336 
14337 	/*
14338 	 * Check if the lock owner might have a lock (request was sent but
14339 	 * no response was received).  Also check if there are any remote
14340 	 * locks on the file.  (In theory we shouldn't have to make this
14341 	 * second check if there's no lock owner, but for now we'll be
14342 	 * conservative and do it anyway.)  If either condition is true,
14343 	 * send an unlock for the entire file to the server.
14344 	 *
14345 	 * Note that no explicit synchronization is needed here.  At worst,
14346 	 * flk_has_remote_locks() will return a false positive, in which case
14347 	 * the unlock call wastes time but doesn't harm correctness.
14348 	 */
14349 
14350 	if (lop) {
14351 		mutex_enter(&lop->lo_lock);
14352 		possible_orphan = lop->lo_pending_rqsts;
14353 		mutex_exit(&lop->lo_lock);
14354 		lock_owner_rele(lop);
14355 	}
14356 
14357 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14358 
14359 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14360 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14361 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14362 	    (void *)lop));
14363 
14364 	if (possible_orphan || flk_has_remote_locks(vp)) {
14365 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14366 		ld.l_whence = 0;	/* unlock from start of file */
14367 		ld.l_start = 0;
14368 		ld.l_len = 0;		/* do entire file */
14369 
14370 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL, cr);
14371 
14372 		if (ret != 0) {
14373 			/*
14374 			 * If VOP_FRLOCK fails, make sure we unregister
14375 			 * local locks before we continue.
14376 			 */
14377 			ld.l_pid = ttoproc(curthread)->p_pid;
14378 			nfs4_register_lock_locally(vp, &ld, flag, offset);
14379 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14380 				"nfs4_lockrelease: lock release error on vp"
14381 				" %p: error %d.\n", (void *)vp, ret));
14382 		}
14383 	}
14384 
14385 	recov_state.rs_flags = 0;
14386 	recov_state.rs_num_retry_despite_err = 0;
14387 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14388 			    &recovonly);
14389 	if (error) {
14390 		mutex_enter(&rp->r_statelock);
14391 		rp->r_flags |= R4LODANGLERS;
14392 		mutex_exit(&rp->r_statelock);
14393 		return (error);
14394 	}
14395 
14396 	/*
14397 	 * So, here we're going to need to retrieve the lock-owner
14398 	 * again (in case recovery has done a switch-a-roo) and
14399 	 * remove it because we can.
14400 	 */
14401 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14402 
14403 	if (lop) {
14404 		nfs4_rnode_remove_lock_owner(rp, lop);
14405 		lock_owner_rele(lop);
14406 	}
14407 
14408 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14409 	return (0);
14410 }
14411 
14412 /*
14413  * Wait for 'tick_delay' clock ticks.
14414  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14415  * NOTE: lock_lease_time is in seconds.
14416  *
14417  * XXX For future improvements, should implement a waiting queue scheme.
14418  */
14419 static int
14420 nfs4_block_and_wait(clock_t *tick_delay, rnode4_t *rp)
14421 {
14422 	long milliseconds_delay;
14423 	time_t lock_lease_time;
14424 
14425 	/* wait tick_delay clock ticks or siginteruptus */
14426 	if (delay_sig(*tick_delay)) {
14427 		return (EINTR);
14428 	}
14429 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14430 		"reissue the lock request: blocked for %ld clock ticks: %ld "
14431 		"milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14432 
14433 	/* get the lease time */
14434 	lock_lease_time = r2lease_time(rp);
14435 
14436 	/* drv_hztousec converts ticks to microseconds */
14437 	milliseconds_delay = drv_hztousec(*tick_delay) / 1000;
14438 	if (milliseconds_delay < lock_lease_time * 1000) {
14439 		*tick_delay = 2 * *tick_delay;
14440 		if (drv_hztousec(*tick_delay) > lock_lease_time * 1000 * 1000)
14441 			*tick_delay = drv_usectohz(lock_lease_time*1000*1000);
14442 	}
14443 	return (0);
14444 }
14445 
14446 
14447 void
14448 nfs4_vnops_init(void)
14449 {
14450 }
14451 
14452 void
14453 nfs4_vnops_fini(void)
14454 {
14455 }
14456 
14457 /*
14458  * Return a reference to the directory (parent) vnode for a given vnode,
14459  * using the saved pathname information and the directory file handle.  The
14460  * caller is responsible for disposing of the reference.
14461  * Returns zero or an errno value.
14462  *
14463  * Caller should set need_start_op to FALSE if it is the recovery
14464  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14465  */
14466 int
14467 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14468 {
14469 	svnode_t *svnp;
14470 	vnode_t *dvp = NULL;
14471 	servinfo4_t *svp;
14472 	nfs4_fname_t *mfname;
14473 	int error;
14474 
14475 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14476 
14477 	if (vp->v_flag & VROOT) {
14478 		nfs4_sharedfh_t *sfh;
14479 		nfs_fh4 fh;
14480 		mntinfo4_t *mi;
14481 
14482 		ASSERT(vp->v_type == VREG);
14483 
14484 		mi = VTOMI4(vp);
14485 		svp = mi->mi_curr_serv;
14486 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14487 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14488 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14489 		sfh = sfh4_get(&fh, VTOMI4(vp));
14490 		nfs_rw_exit(&svp->sv_lock);
14491 		mfname = mi->mi_fname;
14492 		fn_hold(mfname);
14493 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14494 		sfh4_rele(&sfh);
14495 
14496 		if (dvp->v_type == VNON)
14497 			dvp->v_type = VDIR;
14498 		*dvpp = dvp;
14499 		return (0);
14500 	}
14501 
14502 	svnp = VTOSV(vp);
14503 
14504 	if (svnp == NULL) {
14505 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14506 			"shadow node is NULL"));
14507 		return (EINVAL);
14508 	}
14509 
14510 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14511 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14512 			"shadow node name or dfh val == NULL"));
14513 		return (EINVAL);
14514 	}
14515 
14516 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14517 							(int)need_start_op);
14518 	if (error != 0) {
14519 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14520 			"nfs4_make_dotdot returned %d", error));
14521 		return (error);
14522 	}
14523 	if (!dvp) {
14524 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14525 			"nfs4_make_dotdot returned a NULL dvp"));
14526 		return (EIO);
14527 	}
14528 	if (dvp->v_type == VNON)
14529 		dvp->v_type = VDIR;
14530 	ASSERT(dvp->v_type == VDIR);
14531 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14532 		mutex_enter(&dvp->v_lock);
14533 		dvp->v_flag |= V_XATTRDIR;
14534 		mutex_exit(&dvp->v_lock);
14535 	}
14536 	*dvpp = dvp;
14537 	return (0);
14538 }
14539 
14540 /*
14541  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14542  * length that fnamep can accept, including the trailing null.
14543  * Returns 0 if okay, returns an errno value if there was a problem.
14544  */
14545 
14546 int
14547 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14548 {
14549 	char *fn;
14550 	int err = 0;
14551 	servinfo4_t *svp;
14552 	svnode_t *shvp;
14553 
14554 	/*
14555 	 * If the file being opened has VROOT set, then this is
14556 	 * a "file" mount.  sv_name will not be interesting, so
14557 	 * go back to the servinfo4 to get the original mount
14558 	 * path and strip off all but the final edge.  Otherwise
14559 	 * just return the name from the shadow vnode.
14560 	 */
14561 
14562 	if (vp->v_flag & VROOT) {
14563 
14564 		svp = VTOMI4(vp)->mi_curr_serv;
14565 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14566 
14567 		fn = strrchr(svp->sv_path, '/');
14568 		if (fn == NULL)
14569 			err = EINVAL;
14570 		else
14571 			fn++;
14572 	} else {
14573 		shvp = VTOSV(vp);
14574 		fn = fn_name(shvp->sv_name);
14575 	}
14576 
14577 	if (err == 0)
14578 		if (strlen(fn) < maxlen)
14579 			(void) strcpy(fnamep, fn);
14580 		else
14581 			err = ENAMETOOLONG;
14582 
14583 	if (vp->v_flag & VROOT)
14584 		nfs_rw_exit(&svp->sv_lock);
14585 	else
14586 		kmem_free(fn, MAXNAMELEN);
14587 
14588 	return (err);
14589 }
14590 
14591 /*
14592  * If the vnode has pages, run the list and check for
14593  * any that are still dangling. We call this function
14594  * before the OTW CLOSE occurs so we can B_INVAL the
14595  * danglers.
14596  */
14597 static int
14598 nfs4_dross_pages(vnode_t *vp)
14599 {
14600 	page_t *pp;
14601 	kmutex_t *vphm;
14602 	rnode4_t *rp;
14603 
14604 	/* make sure we're looking at the master vnode, not a shadow */
14605 	rp = VTOR4(vp);
14606 	if (IS_SHADOW(vp, rp))
14607 		vp = RTOV4(rp);
14608 
14609 	vphm = page_vnode_mutex(vp);
14610 	mutex_enter(vphm);
14611 	if ((pp = vp->v_pages) != NULL) {
14612 		do {
14613 			if (pp->p_fsdata != C_NOCOMMIT) {
14614 				mutex_exit(vphm);
14615 				return (1);
14616 			}
14617 		} while ((pp = pp->p_vpnext) != vp->v_pages);
14618 	}
14619 	mutex_exit(vphm);
14620 
14621 	return (0);
14622 }
14623 
14624 /*
14625  * Bookkeeping for a close that doesn't need to go over the wire.
14626  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14627  * it is left at 1.
14628  */
14629 void
14630 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14631 {
14632 	rnode4_t		*rp;
14633 	mntinfo4_t		*mi;
14634 
14635 	mi = VTOMI4(vp);
14636 	rp = VTOR4(vp);
14637 
14638 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14639 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14640 	ASSERT(nfs_zone() == mi->mi_zone);
14641 	ASSERT(mutex_owned(&osp->os_sync_lock));
14642 	ASSERT(*have_lockp);
14643 
14644 	if (!osp->os_valid ||
14645 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14646 		return;
14647 	}
14648 
14649 	/*
14650 	 * This removes the reference obtained at OPEN; ie,
14651 	 * when the open stream structure was created.
14652 	 *
14653 	 * We don't have to worry about calling 'open_stream_rele'
14654 	 * since we our currently holding a reference to this
14655 	 * open stream which means the count can not go to 0 with
14656 	 * this decrement.
14657 	 */
14658 	ASSERT(osp->os_ref_count >= 2);
14659 	osp->os_ref_count--;
14660 	osp->os_valid = 0;
14661 	mutex_exit(&osp->os_sync_lock);
14662 	*have_lockp = 0;
14663 
14664 	nfs4_dec_state_ref_count(mi);
14665 }
14666 
14667 /*
14668  * Close all remaining open streams on the rnode.  These open streams
14669  * could be here because:
14670  * - The close attempted at either close or delmap failed
14671  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
14672  * - Someone did mknod on a regular file but never opened it
14673  */
14674 int
14675 nfs4close_all(vnode_t *vp, cred_t *cr)
14676 {
14677 	nfs4_open_stream_t *osp;
14678 	int error;
14679 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
14680 	rnode4_t *rp;
14681 
14682 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14683 
14684 	error = 0;
14685 	rp = VTOR4(vp);
14686 
14687 	/*
14688 	 * At this point, all we know is that the last time
14689 	 * someone called vn_rele, the count was 1.  Since then,
14690 	 * the vnode could have been re-activated.  We want to
14691 	 * loop through the open streams and close each one, but
14692 	 * we have to be careful since once we release the rnode
14693 	 * hash bucket lock, someone else is free to come in and
14694 	 * re-activate the rnode and add new open streams.  The
14695 	 * strategy is take the rnode hash bucket lock, verify that
14696 	 * the count is still 1, grab the open stream off the
14697 	 * head of the list and mark it invalid, then release the
14698 	 * rnode hash bucket lock and proceed with that open stream.
14699 	 * This is ok because nfs4close_one() will acquire the proper
14700 	 * open/create to close/destroy synchronization for open
14701 	 * streams, and will ensure that if someone has reopened
14702 	 * the open stream after we've dropped the hash bucket lock
14703 	 * then we'll just simply return without destroying the
14704 	 * open stream.
14705 	 * Repeat until the list is empty.
14706 	 */
14707 
14708 	for (;;) {
14709 
14710 		/* make sure vnode hasn't been reactivated */
14711 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
14712 		mutex_enter(&vp->v_lock);
14713 		if (vp->v_count > 1) {
14714 			mutex_exit(&vp->v_lock);
14715 			rw_exit(&rp->r_hashq->r_lock);
14716 			break;
14717 		}
14718 		/*
14719 		 * Grabbing r_os_lock before releasing v_lock prevents
14720 		 * a window where the rnode/open stream could get
14721 		 * reactivated (and os_force_close set to 0) before we
14722 		 * had a chance to set os_force_close to 1.
14723 		 */
14724 		mutex_enter(&rp->r_os_lock);
14725 		mutex_exit(&vp->v_lock);
14726 
14727 		osp = list_head(&rp->r_open_streams);
14728 		if (!osp) {
14729 			/* nothing left to CLOSE OTW, so return */
14730 			mutex_exit(&rp->r_os_lock);
14731 			rw_exit(&rp->r_hashq->r_lock);
14732 			break;
14733 		}
14734 
14735 		mutex_enter(&rp->r_statev4_lock);
14736 		/* the file can't still be mem mapped */
14737 		ASSERT(rp->r_mapcnt == 0);
14738 		if (rp->created_v4)
14739 			rp->created_v4 = 0;
14740 		mutex_exit(&rp->r_statev4_lock);
14741 
14742 		/*
14743 		 * Grab a ref on this open stream; nfs4close_one
14744 		 * will mark it as invalid
14745 		 */
14746 		mutex_enter(&osp->os_sync_lock);
14747 		osp->os_ref_count++;
14748 		osp->os_force_close = 1;
14749 		mutex_exit(&osp->os_sync_lock);
14750 		mutex_exit(&rp->r_os_lock);
14751 		rw_exit(&rp->r_hashq->r_lock);
14752 
14753 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
14754 
14755 		/* Update error if it isn't already non-zero */
14756 		if (error == 0) {
14757 			if (e.error)
14758 				error = e.error;
14759 			else if (e.stat)
14760 				error = geterrno4(e.stat);
14761 		}
14762 
14763 #ifdef	DEBUG
14764 		nfs4close_all_cnt++;
14765 #endif
14766 		/* Release the ref on osp acquired above. */
14767 		open_stream_rele(osp, rp);
14768 
14769 		/* Proceed to the next open stream, if any */
14770 	}
14771 	return (error);
14772 }
14773 
14774 /*
14775  * nfs4close_one - close one open stream for a file if needed.
14776  *
14777  * "close_type" indicates which close path this is:
14778  * CLOSE_NORM: close initiated via VOP_CLOSE.
14779  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
14780  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
14781  *	the close and release of client state for this open stream
14782  *	(unless someone else has the open stream open).
14783  * CLOSE_RESEND: indicates the request is a replay of an earlier request
14784  *	(e.g., due to abort because of a signal).
14785  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
14786  *
14787  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
14788  * recovery.  Instead, the caller is expected to deal with retries.
14789  *
14790  * The caller can either pass in the osp ('provided_osp') or not.
14791  *
14792  * 'access_bits' represents the access we are closing/downgrading.
14793  *
14794  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
14795  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
14796  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
14797  *
14798  * Errors are returned via the nfs4_error_t.
14799  */
14800 void
14801 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
14802 	int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
14803 	nfs4_close_type_t close_type, size_t len, uint_t maxprot,
14804 	uint_t mmap_flags)
14805 {
14806 	nfs4_open_owner_t *oop;
14807 	nfs4_open_stream_t *osp = NULL;
14808 	int retry = 0;
14809 	int num_retries = NFS4_NUM_RECOV_RETRIES;
14810 	rnode4_t *rp;
14811 	mntinfo4_t *mi;
14812 	nfs4_recov_state_t recov_state;
14813 	cred_t *cred_otw = NULL;
14814 	bool_t recovonly = FALSE;
14815 	int isrecov;
14816 	int force_close;
14817 	int close_failed = 0;
14818 	int did_dec_count = 0;
14819 	int did_start_op = 0;
14820 	int did_force_recovlock = 0;
14821 	int did_start_seqid_sync = 0;
14822 	int have_sync_lock = 0;
14823 
14824 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14825 
14826 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
14827 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
14828 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
14829 	    len, maxprot, mmap_flags, access_bits));
14830 
14831 	nfs4_error_zinit(ep);
14832 	rp = VTOR4(vp);
14833 	mi = VTOMI4(vp);
14834 	isrecov = (close_type == CLOSE_RESEND ||
14835 			close_type == CLOSE_AFTER_RESEND);
14836 
14837 	/*
14838 	 * First get the open owner.
14839 	 */
14840 	if (!provided_osp) {
14841 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
14842 	} else {
14843 		oop = provided_osp->os_open_owner;
14844 		ASSERT(oop != NULL);
14845 		open_owner_hold(oop);
14846 	}
14847 
14848 	if (!oop) {
14849 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
14850 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
14851 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
14852 		    (void *)provided_osp, close_type));
14853 		ep->error = EIO;
14854 		goto out;
14855 	}
14856 
14857 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
14858 recov_retry:
14859 	osp = NULL;
14860 	close_failed = 0;
14861 	force_close = (close_type == CLOSE_FORCE);
14862 	retry = 0;
14863 	did_start_op = 0;
14864 	did_force_recovlock = 0;
14865 	did_start_seqid_sync = 0;
14866 	have_sync_lock = 0;
14867 	recovonly = FALSE;
14868 	recov_state.rs_flags = 0;
14869 	recov_state.rs_num_retry_despite_err = 0;
14870 
14871 	/*
14872 	 * Second synchronize with recovery.
14873 	 */
14874 	if (!isrecov) {
14875 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
14876 				&recov_state, &recovonly);
14877 		if (!ep->error) {
14878 			did_start_op = 1;
14879 		} else {
14880 			close_failed = 1;
14881 			/*
14882 			 * If we couldn't get start_fop, but have to
14883 			 * cleanup state, then at least acquire the
14884 			 * mi_recovlock so we can synchronize with
14885 			 * recovery.
14886 			 */
14887 			if (close_type == CLOSE_FORCE) {
14888 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
14889 					RW_READER, FALSE);
14890 				did_force_recovlock = 1;
14891 			} else
14892 				goto out;
14893 		}
14894 	}
14895 
14896 	/*
14897 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
14898 	 * set 'recovonly' to TRUE since most likely this is due to
14899 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
14900 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
14901 	 * to retry, causing us to loop until recovery finishes.  Plus we
14902 	 * don't need protection over the open seqid since we're not going
14903 	 * OTW, hence don't need to use the seqid.
14904 	 */
14905 	if (recovonly == FALSE) {
14906 		/* need to grab the open owner sync before 'os_sync_lock' */
14907 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
14908 		if (ep->error == EAGAIN) {
14909 			ASSERT(!isrecov);
14910 			if (did_start_op)
14911 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
14912 					&recov_state, TRUE);
14913 			if (did_force_recovlock)
14914 				nfs_rw_exit(&mi->mi_recovlock);
14915 			goto recov_retry;
14916 		}
14917 		did_start_seqid_sync = 1;
14918 	}
14919 
14920 	/*
14921 	 * Third get an open stream and acquire 'os_sync_lock' to
14922 	 * sychronize the opening/creating of an open stream with the
14923 	 * closing/destroying of an open stream.
14924 	 */
14925 	if (!provided_osp) {
14926 		/* returns with 'os_sync_lock' held */
14927 		osp = find_open_stream(oop, rp);
14928 		if (!osp) {
14929 			ep->error = EIO;
14930 			goto out;
14931 		}
14932 	} else {
14933 		osp = provided_osp;
14934 		open_stream_hold(osp);
14935 		mutex_enter(&osp->os_sync_lock);
14936 	}
14937 	have_sync_lock = 1;
14938 
14939 	ASSERT(oop == osp->os_open_owner);
14940 
14941 	/*
14942 	 * Fourth, do any special pre-OTW CLOSE processing
14943 	 * based on the specific close type.
14944 	 */
14945 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
14946 	    !did_dec_count) {
14947 		ASSERT(osp->os_open_ref_count > 0);
14948 		osp->os_open_ref_count--;
14949 		did_dec_count = 1;
14950 		if (osp->os_open_ref_count == 0)
14951 			osp->os_final_close = 1;
14952 	}
14953 
14954 	if (close_type == CLOSE_FORCE) {
14955 		/* see if somebody reopened the open stream. */
14956 		if (!osp->os_force_close) {
14957 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
14958 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
14959 			    "was reopened, vp %p", (void *)osp, (void *)vp));
14960 			ep->error = 0;
14961 			ep->stat = NFS4_OK;
14962 			goto out;
14963 		}
14964 
14965 		if (!osp->os_final_close && !did_dec_count) {
14966 			osp->os_open_ref_count--;
14967 			did_dec_count = 1;
14968 		}
14969 
14970 		/*
14971 		 * We can't depend on os_open_ref_count being 0 due to the
14972 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
14973 		 */
14974 #ifdef	NOTYET
14975 		ASSERT(osp->os_open_ref_count == 0);
14976 #endif
14977 		if (osp->os_open_ref_count != 0) {
14978 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
14979 			    "nfs4close_one: should panic here on an "
14980 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
14981 			    "since this is probably the exec problem."));
14982 
14983 			osp->os_open_ref_count = 0;
14984 		}
14985 
14986 		/*
14987 		 * There is the possibility that nfs4close_one()
14988 		 * for close_type == CLOSE_DELMAP couldn't find the
14989 		 * open stream, thus couldn't decrement its os_mapcnt;
14990 		 * therefore we can't use this ASSERT yet.
14991 		 */
14992 #ifdef	NOTYET
14993 		ASSERT(osp->os_mapcnt == 0);
14994 #endif
14995 		osp->os_mapcnt = 0;
14996 	}
14997 
14998 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
14999 		ASSERT(osp->os_mapcnt >= btopr(len));
15000 
15001 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15002 			osp->os_mmap_write -= btopr(len);
15003 		if (maxprot & PROT_READ)
15004 			osp->os_mmap_read -= btopr(len);
15005 		if (maxprot & PROT_EXEC)
15006 			osp->os_mmap_read -= btopr(len);
15007 		/* mirror the PROT_NONE check in nfs4_addmap() */
15008 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15009 		    !(maxprot & PROT_EXEC))
15010 			osp->os_mmap_read -= btopr(len);
15011 		osp->os_mapcnt -= btopr(len);
15012 		did_dec_count = 1;
15013 	}
15014 
15015 	if (recovonly) {
15016 		nfs4_lost_rqst_t lost_rqst;
15017 
15018 		/* request should not already be in recovery queue */
15019 		ASSERT(lrp == NULL);
15020 		nfs4_error_init(ep, EINTR);
15021 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15022 			osp, cred_otw, vp);
15023 		mutex_exit(&osp->os_sync_lock);
15024 		have_sync_lock = 0;
15025 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15026 				lost_rqst.lr_op == OP_CLOSE ?
15027 				&lost_rqst : NULL, OP_CLOSE, NULL);
15028 		close_failed = 1;
15029 		force_close = 0;
15030 		goto close_cleanup;
15031 	}
15032 
15033 	/*
15034 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15035 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15036 	 * space, which means we stopped operating on the open stream
15037 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15038 	 * stateid could be stale, potentially triggering a false
15039 	 * setclientid), and just clean up the client's internal state.
15040 	 */
15041 	if (osp->os_orig_oo_name != oop->oo_name) {
15042 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15043 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15044 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15045 		    "oo_name %" PRIx64")",
15046 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15047 		    oop->oo_name));
15048 		close_failed = 1;
15049 	}
15050 
15051 	/* If the file failed recovery, just quit. */
15052 	mutex_enter(&rp->r_statelock);
15053 	if (rp->r_flags & R4RECOVERR) {
15054 		close_failed = 1;
15055 	}
15056 	mutex_exit(&rp->r_statelock);
15057 
15058 	/*
15059 	 * If the force close path failed to obtain start_fop
15060 	 * then skip the OTW close and just remove the state.
15061 	 */
15062 	if (close_failed)
15063 		goto close_cleanup;
15064 
15065 	/*
15066 	 * Fifth, check to see if there are still mapped pages or other
15067 	 * opens using this open stream.  If there are then we can't
15068 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15069 	 */
15070 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15071 		nfs4_lost_rqst_t	new_lost_rqst;
15072 		bool_t			needrecov = FALSE;
15073 		cred_t			*odg_cred_otw = NULL;
15074 		seqid4			open_dg_seqid = 0;
15075 
15076 		if (osp->os_delegation) {
15077 			/*
15078 			 * If this open stream was never OPENed OTW then we
15079 			 * surely can't DOWNGRADE it (especially since the
15080 			 * osp->open_stateid is really a delegation stateid
15081 			 * when os_delegation is 1).
15082 			 */
15083 			if (access_bits & FREAD)
15084 				osp->os_share_acc_read--;
15085 			if (access_bits & FWRITE)
15086 				osp->os_share_acc_write--;
15087 			osp->os_share_deny_none--;
15088 			nfs4_error_zinit(ep);
15089 			goto out;
15090 		}
15091 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15092 				lrp, ep, &odg_cred_otw, &open_dg_seqid);
15093 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15094 		if (needrecov && !isrecov) {
15095 			bool_t abort;
15096 			nfs4_bseqid_entry_t *bsep = NULL;
15097 
15098 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15099 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15100 					vp, 0,
15101 					lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15102 					open_dg_seqid);
15103 
15104 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15105 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15106 			mutex_exit(&osp->os_sync_lock);
15107 			have_sync_lock = 0;
15108 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15109 				    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15110 				    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15111 				    bsep);
15112 			if (odg_cred_otw)
15113 				crfree(odg_cred_otw);
15114 			if (bsep)
15115 				kmem_free(bsep, sizeof (*bsep));
15116 
15117 			if (abort == TRUE)
15118 				goto out;
15119 
15120 			if (did_start_seqid_sync) {
15121 				nfs4_end_open_seqid_sync(oop);
15122 				did_start_seqid_sync = 0;
15123 			}
15124 			open_stream_rele(osp, rp);
15125 
15126 			if (did_start_op)
15127 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15128 					&recov_state, FALSE);
15129 			if (did_force_recovlock)
15130 				nfs_rw_exit(&mi->mi_recovlock);
15131 
15132 			goto recov_retry;
15133 		} else {
15134 			if (odg_cred_otw)
15135 				crfree(odg_cred_otw);
15136 		}
15137 		goto out;
15138 	}
15139 
15140 	/*
15141 	 * If this open stream was created as the results of an open
15142 	 * while holding a delegation, then just release it; no need
15143 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15144 	 */
15145 	if (osp->os_delegation) {
15146 		nfs4close_notw(vp, osp, &have_sync_lock);
15147 		nfs4_error_zinit(ep);
15148 		goto out;
15149 	}
15150 
15151 	/*
15152 	 * If this stream is not valid, we're done.
15153 	 */
15154 	if (!osp->os_valid) {
15155 		nfs4_error_zinit(ep);
15156 		goto out;
15157 	}
15158 
15159 	/*
15160 	 * Last open or mmap ref has vanished, need to do an OTW close.
15161 	 * First check to see if a close is still necessary.
15162 	 */
15163 	if (osp->os_failed_reopen) {
15164 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15165 		    "don't close OTW osp %p since reopen failed.",
15166 		    (void *)osp));
15167 		/*
15168 		 * Reopen of the open stream failed, hence the
15169 		 * stateid of the open stream is invalid/stale, and
15170 		 * sending this OTW would incorrectly cause another
15171 		 * round of recovery.  In this case, we need to set
15172 		 * the 'os_valid' bit to 0 so another thread doesn't
15173 		 * come in and re-open this open stream before
15174 		 * this "closing" thread cleans up state (decrementing
15175 		 * the nfs4_server_t's state_ref_count and decrementing
15176 		 * the os_ref_count).
15177 		 */
15178 		osp->os_valid = 0;
15179 		/*
15180 		 * This removes the reference obtained at OPEN; ie,
15181 		 * when the open stream structure was created.
15182 		 *
15183 		 * We don't have to worry about calling 'open_stream_rele'
15184 		 * since we our currently holding a reference to this
15185 		 * open stream which means the count can not go to 0 with
15186 		 * this decrement.
15187 		 */
15188 		ASSERT(osp->os_ref_count >= 2);
15189 		osp->os_ref_count--;
15190 		nfs4_error_zinit(ep);
15191 		close_failed = 0;
15192 		goto close_cleanup;
15193 	}
15194 
15195 	ASSERT(osp->os_ref_count > 1);
15196 
15197 	if (!(vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
15198 		nfs4_dross_pages(vp)) {
15199 		nfs4_invalidate_pages(vp, 0, cred_otw);
15200 	}
15201 
15202 	/*
15203 	 * Sixth, try the CLOSE OTW.
15204 	 */
15205 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15206 	    close_type, ep, &have_sync_lock);
15207 
15208 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15209 		/*
15210 		 * Let the recovery thread be responsible for
15211 		 * removing the state for CLOSE.
15212 		 */
15213 		close_failed = 1;
15214 		force_close = 0;
15215 		retry = 0;
15216 	}
15217 
15218 	/* See if we need to retry with a different cred */
15219 	if ((ep->error == EACCES ||
15220 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15221 	    cred_otw != cr) {
15222 		crfree(cred_otw);
15223 		cred_otw = cr;
15224 		crhold(cred_otw);
15225 		retry = 1;
15226 	}
15227 
15228 	if (ep->error || ep->stat)
15229 		close_failed = 1;
15230 
15231 	if (retry && !isrecov && num_retries-- > 0) {
15232 		if (have_sync_lock) {
15233 			mutex_exit(&osp->os_sync_lock);
15234 			have_sync_lock = 0;
15235 		}
15236 		if (did_start_seqid_sync) {
15237 			nfs4_end_open_seqid_sync(oop);
15238 			did_start_seqid_sync = 0;
15239 		}
15240 		open_stream_rele(osp, rp);
15241 
15242 		if (did_start_op)
15243 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15244 				&recov_state, FALSE);
15245 		if (did_force_recovlock)
15246 			nfs_rw_exit(&mi->mi_recovlock);
15247 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15248 			"nfs4close_one: need to retry the close "
15249 			"operation"));
15250 		goto recov_retry;
15251 	}
15252 close_cleanup:
15253 	/*
15254 	 * Seventh and lastly, process our results.
15255 	 */
15256 	if (close_failed && force_close) {
15257 		/*
15258 		 * It's ok to drop and regrab the 'os_sync_lock' since
15259 		 * nfs4close_notw() will recheck to make sure the
15260 		 * "close"/removal of state should happen.
15261 		 */
15262 		if (!have_sync_lock) {
15263 			mutex_enter(&osp->os_sync_lock);
15264 			have_sync_lock = 1;
15265 		}
15266 		/*
15267 		 * This is last call, remove the ref on the open
15268 		 * stream created by open and clean everything up.
15269 		 */
15270 		osp->os_pending_close = 0;
15271 		nfs4close_notw(vp, osp, &have_sync_lock);
15272 		nfs4_error_zinit(ep);
15273 	}
15274 
15275 	if (!close_failed) {
15276 		if (have_sync_lock) {
15277 			osp->os_pending_close = 0;
15278 			mutex_exit(&osp->os_sync_lock);
15279 			have_sync_lock = 0;
15280 		} else {
15281 			mutex_enter(&osp->os_sync_lock);
15282 			osp->os_pending_close = 0;
15283 			mutex_exit(&osp->os_sync_lock);
15284 		}
15285 		if (did_start_op && recov_state.rs_sp != NULL) {
15286 			mutex_enter(&recov_state.rs_sp->s_lock);
15287 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15288 			mutex_exit(&recov_state.rs_sp->s_lock);
15289 		} else {
15290 			nfs4_dec_state_ref_count(mi);
15291 		}
15292 		nfs4_error_zinit(ep);
15293 	}
15294 
15295 out:
15296 	if (have_sync_lock)
15297 		mutex_exit(&osp->os_sync_lock);
15298 	if (did_start_op)
15299 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15300 		    recovonly ? TRUE : FALSE);
15301 	if (did_force_recovlock)
15302 		nfs_rw_exit(&mi->mi_recovlock);
15303 	if (cred_otw)
15304 		crfree(cred_otw);
15305 	if (osp)
15306 		open_stream_rele(osp, rp);
15307 	if (oop) {
15308 		if (did_start_seqid_sync)
15309 			nfs4_end_open_seqid_sync(oop);
15310 		open_owner_rele(oop);
15311 	}
15312 }
15313 
15314 /*
15315  * Convert information returned by the server in the LOCK4denied
15316  * structure to the form required by fcntl.
15317  */
15318 static void
15319 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15320 {
15321 	nfs4_lo_name_t *lo;
15322 
15323 #ifdef	DEBUG
15324 	if (denied_to_flk_debug) {
15325 		lockt_denied_debug = lockt_denied;
15326 		debug_enter("lockt_denied");
15327 	}
15328 #endif
15329 
15330 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15331 	flk->l_whence = 0;	/* aka SEEK_SET */
15332 	flk->l_start = lockt_denied->offset;
15333 	flk->l_len = lockt_denied->length;
15334 
15335 	/*
15336 	 * If the blocking clientid matches our client id, then we can
15337 	 * interpret the lockowner (since we built it).  If not, then
15338 	 * fabricate a sysid and pid.  Note that the l_sysid field
15339 	 * in *flk already has the local sysid.
15340 	 */
15341 
15342 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15343 
15344 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15345 			lo = (nfs4_lo_name_t *)
15346 				lockt_denied->owner.owner_val;
15347 
15348 			flk->l_pid = lo->ln_pid;
15349 		} else {
15350 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15351 			"denied_to_flk: bad lock owner length\n"));
15352 
15353 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15354 		}
15355 	} else {
15356 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15357 		"denied_to_flk: foreign clientid\n"));
15358 
15359 		/*
15360 		 * Construct a new sysid which should be different from
15361 		 * sysids of other systems.
15362 		 */
15363 
15364 		flk->l_sysid++;
15365 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15366 	}
15367 }
15368 
15369 static pid_t
15370 lo_to_pid(lock_owner4 *lop)
15371 {
15372 	pid_t pid = 0;
15373 	uchar_t *cp;
15374 	int i;
15375 
15376 	cp = (uchar_t *)&lop->clientid;
15377 
15378 	for (i = 0; i < sizeof (lop->clientid); i++)
15379 		pid += (pid_t)*cp++;
15380 
15381 	cp = (uchar_t *)lop->owner_val;
15382 
15383 	for (i = 0; i < lop->owner_len; i++)
15384 		pid += (pid_t)*cp++;
15385 
15386 	return (pid);
15387 }
15388 
15389 /*
15390  * Given a lock pointer, returns the length of that lock.
15391  * "end" is the last locked offset the "l_len" covers from
15392  * the start of the lock.
15393  */
15394 static off64_t
15395 lock_to_end(flock64_t *lock)
15396 {
15397 	off64_t lock_end;
15398 
15399 	if (lock->l_len == 0)
15400 		lock_end = (off64_t)MAXEND;
15401 	else
15402 		lock_end = lock->l_start + lock->l_len - 1;
15403 
15404 	return (lock_end);
15405 }
15406 
15407 /*
15408  * Given the end of a lock, it will return you the length "l_len" for that lock.
15409  */
15410 static off64_t
15411 end_to_len(off64_t start, off64_t end)
15412 {
15413 	off64_t lock_len;
15414 
15415 	ASSERT(end >= start);
15416 	if (end == MAXEND)
15417 		lock_len = 0;
15418 	else
15419 		lock_len = end - start + 1;
15420 
15421 	return (lock_len);
15422 }
15423 
15424 /*
15425  * On given end for a lock it determines if it is the last locked offset
15426  * or not, if so keeps it as is, else adds one to return the length for
15427  * valid start.
15428  */
15429 static off64_t
15430 start_check(off64_t x)
15431 {
15432 	if (x == MAXEND)
15433 		return (x);
15434 	else
15435 		return (x + 1);
15436 }
15437 
15438 /*
15439  * See if these two locks overlap, and if so return 1;
15440  * otherwise, return 0.
15441  */
15442 static int
15443 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15444 {
15445 	off64_t llfp_end, curfp_end;
15446 
15447 	llfp_end = lock_to_end(llfp);
15448 	curfp_end = lock_to_end(curfp);
15449 
15450 	if (((llfp_end >= curfp->l_start) &&
15451 		(llfp->l_start <= curfp->l_start)) ||
15452 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15453 		return (1);
15454 	return (0);
15455 }
15456 
15457 /*
15458  * Determine what the interseting lock region is, and add that to the
15459  * 'nl_llpp' locklist in increasing order (by l_start).
15460  */
15461 static void
15462 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15463 	locklist_t **nl_llpp, vnode_t *vp)
15464 {
15465 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15466 	off64_t lost_flp_end, local_flp_end, len, start;
15467 
15468 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15469 
15470 	if (!locks_intersect(lost_flp, local_flp))
15471 		return;
15472 
15473 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15474 	    "locks intersect"));
15475 
15476 	lost_flp_end = lock_to_end(lost_flp);
15477 	local_flp_end = lock_to_end(local_flp);
15478 
15479 	/* Find the starting point of the intersecting region */
15480 	if (local_flp->l_start > lost_flp->l_start)
15481 		start = local_flp->l_start;
15482 	else
15483 		start = lost_flp->l_start;
15484 
15485 	/* Find the lenght of the intersecting region */
15486 	if (lost_flp_end < local_flp_end)
15487 		len = end_to_len(start, lost_flp_end);
15488 	else
15489 		len = end_to_len(start, local_flp_end);
15490 
15491 	/*
15492 	 * Prepare the flock structure for the intersection found and insert
15493 	 * it into the new list in increasing l_start order. This list contains
15494 	 * intersections of locks registered by the client with the local host
15495 	 * and the lost lock.
15496 	 * The lock type of this lock is the same as that of the local_flp.
15497 	 */
15498 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15499 	intersect_llp->ll_flock.l_start = start;
15500 	intersect_llp->ll_flock.l_len = len;
15501 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15502 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15503 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15504 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15505 	intersect_llp->ll_vp = vp;
15506 
15507 	tmp_fllp = *nl_llpp;
15508 	cur_fllp = NULL;
15509 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15510 		intersect_llp->ll_flock.l_start) {
15511 			cur_fllp = tmp_fllp;
15512 			tmp_fllp = tmp_fllp->ll_next;
15513 	}
15514 	if (cur_fllp == NULL) {
15515 		/* first on the list */
15516 		intersect_llp->ll_next = *nl_llpp;
15517 		*nl_llpp = intersect_llp;
15518 	} else {
15519 		intersect_llp->ll_next = cur_fllp->ll_next;
15520 		cur_fllp->ll_next = intersect_llp;
15521 	}
15522 
15523 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15524 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15525 	    intersect_llp->ll_flock.l_start,
15526 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15527 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15528 }
15529 
15530 /*
15531  * Our local locking current state is potentially different than
15532  * what the NFSv4 server thinks we have due to a lost lock that was
15533  * resent and then received.  We need to reset our "NFSv4" locking
15534  * state to match the current local locking state for this pid since
15535  * that is what the user/application sees as what the world is.
15536  *
15537  * We cannot afford to drop the open/lock seqid sync since then we can
15538  * get confused about what the current local locking state "is" versus
15539  * "was".
15540  *
15541  * If we are unable to fix up the locks, we send SIGLOST to the affected
15542  * process.  This is not done if the filesystem has been forcibly
15543  * unmounted, in case the process has already exited and a new process
15544  * exists with the same pid.
15545  */
15546 static void
15547 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15548 		nfs4_lock_owner_t *lop)
15549 {
15550 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15551 	mntinfo4_t *mi = VTOMI4(vp);
15552 	const int cmd = F_SETLK;
15553 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15554 	flock64_t ul_fl;
15555 
15556 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15557 		"nfs4_reinstitute_local_lock_state"));
15558 
15559 	/*
15560 	 * Find active locks for this vp from the local locking code.
15561 	 * Scan through this list and find out the locks that intersect with
15562 	 * the lost lock. Once we find the lock that intersects, add the
15563 	 * intersection area as a new lock to a new list "ri_llp". The lock
15564 	 * type of the intersection region lock added to ri_llp is the same
15565 	 * as that found in the active lock list, "list". The intersecting
15566 	 * region locks are added to ri_llp in increasing l_start order.
15567 	 */
15568 	ASSERT(nfs_zone() == mi->mi_zone);
15569 
15570 	locks = flk_active_locks_for_vp(vp);
15571 	ri_llp = NULL;
15572 
15573 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15574 		ASSERT(llp->ll_vp == vp);
15575 		/*
15576 		 * Pick locks that belong to this pid/lockowner
15577 		 */
15578 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15579 			continue;
15580 
15581 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15582 	}
15583 
15584 	/*
15585 	 * Now we have the list of intersections with the lost lock. These are
15586 	 * the locks that were/are active before the server replied to the
15587 	 * last/lost lock. Issue these locks to the server here. Playing these
15588 	 * locks to the server will re-establish aur current local locking state
15589 	 * with the v4 server.
15590 	 * If we get an error, send SIGLOST to the application for that lock.
15591 	 */
15592 
15593 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15594 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15595 		    "nfs4_reinstitute_local_lock_state: need to issue "
15596 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15597 		    llp->ll_flock.l_start,
15598 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15599 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15600 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15601 		/*
15602 		 * No need to relock what we already have
15603 		 */
15604 		if (llp->ll_flock.l_type == lost_flp->l_type)
15605 			continue;
15606 
15607 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15608 	}
15609 
15610 	/*
15611 	 * Now keeping the start of the lost lock as our reference parse the
15612 	 * newly created ri_llp locklist to find the ranges that we have locked
15613 	 * with the v4 server but not in the current local locking. We need
15614 	 * to unlock these ranges.
15615 	 * These ranges can also be reffered to as those ranges, where the lost
15616 	 * lock does not overlap with the locks in the ri_llp but are locked
15617 	 * since the server replied to the lost lock.
15618 	 */
15619 	cur_start = lost_flp->l_start;
15620 	lost_flp_end = lock_to_end(lost_flp);
15621 
15622 	ul_fl.l_type = F_UNLCK;
15623 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15624 	ul_fl.l_sysid = lost_flp->l_sysid;
15625 	ul_fl.l_pid = lost_flp->l_pid;
15626 
15627 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15628 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15629 
15630 		if (llp->ll_flock.l_start <= cur_start) {
15631 			cur_start = start_check(llp_ll_flock_end);
15632 			continue;
15633 		}
15634 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15635 			"nfs4_reinstitute_local_lock_state: "
15636 			"UNLOCK [%"PRIx64" - %"PRIx64"]",
15637 			cur_start, llp->ll_flock.l_start));
15638 
15639 		ul_fl.l_start = cur_start;
15640 		ul_fl.l_len = end_to_len(cur_start,
15641 		    (llp->ll_flock.l_start - 1));
15642 
15643 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15644 		cur_start = start_check(llp_ll_flock_end);
15645 	}
15646 
15647 	/*
15648 	 * In the case where the lost lock ends after all intersecting locks,
15649 	 * unlock the last part of the lost lock range.
15650 	 */
15651 	if (cur_start != start_check(lost_flp_end)) {
15652 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15653 			"nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15654 			"lost lock region [%"PRIx64" - %"PRIx64"]",
15655 			cur_start, lost_flp->l_start + lost_flp->l_len));
15656 
15657 		ul_fl.l_start = cur_start;
15658 		/*
15659 		 * Is it an to-EOF lock? if so unlock till the end
15660 		 */
15661 		if (lost_flp->l_len == 0)
15662 			ul_fl.l_len = 0;
15663 		else
15664 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15665 
15666 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15667 	}
15668 
15669 	if (locks != NULL)
15670 		flk_free_locklist(locks);
15671 
15672 	/* Free up our newly created locklist */
15673 	for (llp = ri_llp; llp != NULL; ) {
15674 		tmp_llp = llp->ll_next;
15675 		kmem_free(llp, sizeof (locklist_t));
15676 		llp = tmp_llp;
15677 	}
15678 
15679 	/*
15680 	 * Now return back to the original calling nfs4frlock()
15681 	 * and let us naturally drop our seqid syncs.
15682 	 */
15683 }
15684 
15685 /*
15686  * Create a lost state record for the given lock reinstantiation request
15687  * and push it onto the lost state queue.
15688  */
15689 static void
15690 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
15691 	nfs4_lock_owner_t *lop)
15692 {
15693 	nfs4_lost_rqst_t req;
15694 	nfs_lock_type4 locktype;
15695 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
15696 
15697 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15698 
15699 	locktype = flk_to_locktype(cmd, flk->l_type);
15700 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
15701 				NULL, NULL, lop, flk, &req, cr, vp);
15702 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
15703 		    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
15704 		    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
15705 		    NULL);
15706 }
15707