xref: /illumos-gate/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision 0dee7919e2f2a6479d16b370af93747b9416b242)
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 		/*NOTREACHED*/
513 		break;
514 	}
515 	if (!error)
516 		error = vattr_to_fattr4(vap, NULL, attr, 0, op, supp);
517 	if (error)
518 		bzero(attr, sizeof (*attr));
519 	return (error);
520 }
521 
522 static void
523 nfs4args_verify_free(nfs_argop4 *argop)
524 {
525 	switch (argop->argop) {
526 	case OP_VERIFY:
527 		nfs4_fattr4_free(&argop->nfs_argop4_u.opverify.obj_attributes);
528 		break;
529 	case OP_NVERIFY:
530 		nfs4_fattr4_free(&argop->nfs_argop4_u.opnverify.obj_attributes);
531 		break;
532 	default:
533 		break;
534 	}
535 }
536 
537 static void
538 nfs4args_write(nfs_argop4 *argop, stable_how4 stable, rnode4_t *rp, cred_t *cr,
539 	WRITE4args **wargs_pp, nfs4_stateid_types_t *sid_tp)
540 {
541 	WRITE4args *wargs = &argop->nfs_argop4_u.opwrite;
542 	mntinfo4_t *mi = VTOMI4(RTOV4(rp));
543 
544 	argop->argop = OP_WRITE;
545 	wargs->stable = stable;
546 	wargs->stateid = nfs4_get_w_stateid(cr, rp, curproc->p_pidp->pid_id,
547 				mi, OP_WRITE, sid_tp);
548 	wargs->mblk = NULL;
549 	*wargs_pp = wargs;
550 }
551 
552 void
553 nfs4args_copen_free(OPEN4cargs *open_args)
554 {
555 	if (open_args->owner.owner_val) {
556 		kmem_free(open_args->owner.owner_val,
557 					open_args->owner.owner_len);
558 	}
559 	if ((open_args->opentype == OPEN4_CREATE) &&
560 	    (open_args->mode != EXCLUSIVE4)) {
561 		nfs4_fattr4_free(&open_args->createhow4_u.createattrs);
562 	}
563 }
564 
565 /*
566  * XXX:  This is referenced in modstubs.s
567  */
568 struct vnodeops *
569 nfs4_getvnodeops(void)
570 {
571 	return (nfs4_vnodeops);
572 }
573 
574 /*
575  * The OPEN operation opens a regular file.
576  *
577  * ARGSUSED
578  */
579 static int
580 nfs4_open(vnode_t **vpp, int flag, cred_t *cr)
581 {
582 	vnode_t *dvp = NULL;
583 	rnode4_t *rp;
584 	int error;
585 	int just_been_created;
586 	char fn[MAXNAMELEN];
587 
588 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4_open: "));
589 	if (curproc->p_zone != VTOMI4(*vpp)->mi_zone)
590 		return (EIO);
591 	rp = VTOR4(*vpp);
592 
593 	/*
594 	 * Check to see if opening something besides a regular file;
595 	 * if so skip the OTW call
596 	 */
597 	if ((*vpp)->v_type != VREG) {
598 		error = nfs4_open_non_reg_file(vpp, flag, cr);
599 		return (error);
600 	}
601 
602 	/*
603 	 * XXX - would like a check right here to know if the file is
604 	 * executable or not, so as to skip OTW
605 	 */
606 
607 	if ((error = vtoname(*vpp, fn, MAXNAMELEN)) != 0)
608 		return (error);
609 
610 	if ((error = vtodv(*vpp, &dvp, cr, TRUE)) != 0)
611 		return (error);
612 
613 	/*
614 	 * See if this file has just been CREATEd.
615 	 * If so, clear the flag and update the dnlc, which was previously
616 	 * skipped in nfs4_create.
617 	 * XXX need better serilization on this.
618 	 * XXX move this into the nf4open_otw call, after we have
619 	 * XXX acquired the open owner seqid sync.
620 	 */
621 	mutex_enter(&rp->r_statev4_lock);
622 	if (rp->created_v4) {
623 		rp->created_v4 = 0;
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 		just_been_created = 0;
629 	}
630 	mutex_exit(&rp->r_statev4_lock);
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(curproc->p_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(curproc->p_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(curproc->p_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 != curproc->p_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(curproc->p_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 (curproc->p_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 (curproc->p_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(curproc->p_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(curproc->p_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(curproc->p_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(curproc->p_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 (curproc->p_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 (curproc->p_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 (curproc->p_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(curproc->p_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;
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 (curproc->p_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 	cacc = nfs4_access_check(rp, acc, cr);
4135 	if (cacc == NFS4_ACCESS_ALLOWED)
4136 		return (0);
4137 	if (cacc == NFS4_ACCESS_DENIED)
4138 		return (EACCES);
4139 	if (vp->v_type == VDIR) {
4140 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4141 			ACCESS4_EXTEND | ACCESS4_LOOKUP;
4142 	} else {
4143 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4144 			ACCESS4_EXECUTE;
4145 	}
4146 	recov_state.rs_flags = 0;
4147 	recov_state.rs_num_retry_despite_err = 0;
4148 
4149 	cred = cr;
4150 
4151 tryagain:
4152 recov_retry:
4153 	/*
4154 	 * Don't take with r_statev4_lock here. r_deleg_type could
4155 	 * change as soon as lock is released.  Since it is an int,
4156 	 * there is no atomicity issue.
4157 	 */
4158 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4159 	num_ops = do_getattr ? 3 : 2;
4160 
4161 	args.ctag = TAG_ACCESS;
4162 
4163 	args.array_len = num_ops;
4164 	args.array = argop;
4165 
4166 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4167 					&recov_state, NULL)) {
4168 		return (e.error);
4169 	}
4170 
4171 	/* putfh target fh */
4172 	argop[0].argop = OP_CPUTFH;
4173 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4174 
4175 	/* access */
4176 	argop[1].argop = OP_ACCESS;
4177 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4178 
4179 	/* getattr */
4180 	if (do_getattr) {
4181 		argop[2].argop = OP_GETATTR;
4182 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4183 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4184 	}
4185 
4186 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4187 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4188 	    rnode4info(VTOR4(vp))));
4189 
4190 	doqueue = 1;
4191 	t = gethrtime();
4192 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4193 	rpc_error = e.error;
4194 
4195 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4196 	if (needrecov) {
4197 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4198 		    "nfs4_access: initiating recovery\n"));
4199 
4200 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4201 		    NULL, OP_ACCESS, NULL) == FALSE) {
4202 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4203 			    &recov_state, needrecov);
4204 			if (!e.error)
4205 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4206 						(caddr_t)&res);
4207 			goto recov_retry;
4208 		}
4209 	}
4210 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4211 
4212 	if (e.error)
4213 		goto out;
4214 
4215 	if (res.status) {
4216 		e.error = geterrno4(res.status);
4217 		/*
4218 		 * This might generate over the wire calls throught
4219 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4220 		 * here to avoid a deadlock.
4221 		 */
4222 		nfs4_purge_stale_fh(e.error, vp, cr);
4223 		goto out;
4224 	}
4225 	resop = &res.array[1];	/* access res */
4226 
4227 	resacc = resop->nfs_resop4_u.opaccess.access;
4228 
4229 	if (do_getattr) {
4230 		resop++;	/* getattr res */
4231 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4232 				t, cr, FALSE, NULL);
4233 	}
4234 
4235 	if (!e.error) {
4236 		/* XXX check the supported bits too? */
4237 		if ((acc & resacc) != acc) {
4238 			/*
4239 			 * The following code implements the semantic
4240 			 * that a setuid root program has *at least* the
4241 			 * permissions of the user that is running the
4242 			 * program.  See rfs3call() for more portions
4243 			 * of the implementation of this functionality.
4244 			 */
4245 			/* XXX-LP */
4246 			if (crgetuid(cred) == 0 && crgetruid(cred) != 0) {
4247 				cred_t *ncr = crnetadjust(cred);
4248 
4249 				if (ncr != NULL) {
4250 					(void) xdr_free(xdr_COMPOUND4res_clnt,
4251 							(caddr_t)&res);
4252 					cred = ncr;
4253 					goto tryagain;
4254 				}
4255 			}
4256 			e.error = EACCES;
4257 		}
4258 		nfs4_access_cache(rp, argacc, resacc, cr);
4259 	}
4260 
4261 out:
4262 	if (!rpc_error)
4263 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4264 
4265 	if (cred != cr)
4266 		crfree(cred);
4267 
4268 	return (e.error);
4269 }
4270 
4271 static int
4272 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr)
4273 {
4274 	COMPOUND4args_clnt args;
4275 	COMPOUND4res_clnt res;
4276 	int doqueue;
4277 	rnode4_t *rp;
4278 	nfs_argop4 argop[3];
4279 	nfs_resop4 *resop;
4280 	READLINK4res *lr_res;
4281 	nfs4_ga_res_t *garp;
4282 	uint_t len;
4283 	char *linkdata;
4284 	bool_t needrecov = FALSE;
4285 	nfs4_recov_state_t recov_state;
4286 	hrtime_t t;
4287 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4288 
4289 	if (curproc->p_zone != VTOMI4(vp)->mi_zone)
4290 		return (EIO);
4291 	/*
4292 	 * Can't readlink anything other than a symbolic link.
4293 	 */
4294 	if (vp->v_type != VLNK)
4295 		return (EINVAL);
4296 
4297 	rp = VTOR4(vp);
4298 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4299 		e.error = nfs4_validate_caches(vp, cr);
4300 		if (e.error)
4301 			return (e.error);
4302 		mutex_enter(&rp->r_statelock);
4303 		if (rp->r_symlink.contents != NULL) {
4304 			e.error = uiomove(rp->r_symlink.contents,
4305 			    rp->r_symlink.len, UIO_READ, uiop);
4306 			mutex_exit(&rp->r_statelock);
4307 			return (e.error);
4308 		}
4309 		mutex_exit(&rp->r_statelock);
4310 	}
4311 	recov_state.rs_flags = 0;
4312 	recov_state.rs_num_retry_despite_err = 0;
4313 
4314 recov_retry:
4315 	args.array_len = 3;
4316 	args.array = argop;
4317 	args.ctag = TAG_READLINK;
4318 
4319 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4320 	if (e.error) {
4321 		return (e.error);
4322 	}
4323 
4324 	/* 0. putfh symlink fh */
4325 	argop[0].argop = OP_CPUTFH;
4326 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4327 
4328 	/* 1. readlink */
4329 	argop[1].argop = OP_READLINK;
4330 
4331 	/* 2. getattr */
4332 	argop[2].argop = OP_GETATTR;
4333 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4334 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4335 
4336 	doqueue = 1;
4337 
4338 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4339 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4340 	    rnode4info(VTOR4(vp))));
4341 
4342 	t = gethrtime();
4343 
4344 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4345 
4346 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4347 	if (needrecov) {
4348 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4349 		    "nfs4_readlink: initiating recovery\n"));
4350 
4351 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4352 		    NULL, OP_READLINK, NULL) == FALSE) {
4353 			if (!e.error)
4354 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4355 								(caddr_t)&res);
4356 
4357 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4358 			    needrecov);
4359 			goto recov_retry;
4360 		}
4361 	}
4362 
4363 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4364 
4365 	if (e.error)
4366 		return (e.error);
4367 
4368 	/*
4369 	 * There is an path in the code below which calls
4370 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4371 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4372 	 * here to avoid nfs4_start_op() deadlock.
4373 	 */
4374 
4375 	if (res.status && (res.array_len < args.array_len)) {
4376 		/*
4377 		 * either Putfh or Link failed
4378 		 */
4379 		e.error = geterrno4(res.status);
4380 		nfs4_purge_stale_fh(e.error, vp, cr);
4381 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4382 		return (e.error);
4383 	}
4384 
4385 	resop = &res.array[1];	/* readlink res */
4386 	lr_res = &resop->nfs_resop4_u.opreadlink;
4387 
4388 	/*
4389 	 * treat symlink names as data
4390 	 */
4391 	linkdata = utf8_to_str(&lr_res->link, &len, NULL);
4392 	if (linkdata != NULL) {
4393 		int uio_len = len - 1;
4394 		/* len includes null byte, which we won't uiomove */
4395 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4396 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4397 			mutex_enter(&rp->r_statelock);
4398 			if (rp->r_symlink.contents == NULL) {
4399 				rp->r_symlink.contents = linkdata;
4400 				rp->r_symlink.len = uio_len;
4401 				rp->r_symlink.size = len;
4402 				mutex_exit(&rp->r_statelock);
4403 			} else {
4404 				mutex_exit(&rp->r_statelock);
4405 				kmem_free(linkdata, len);
4406 			}
4407 		} else {
4408 			kmem_free(linkdata, len);
4409 		}
4410 	}
4411 	if (res.status == NFS4_OK) {
4412 		resop++;	/* getattr res */
4413 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4414 	}
4415 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4416 
4417 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4418 
4419 	/*
4420 	 * The over the wire error for attempting to readlink something
4421 	 * other than a symbolic link is ENXIO.  However, we need to
4422 	 * return EINVAL instead of ENXIO, so we map it here.
4423 	 */
4424 	return (e.error == ENXIO ? EINVAL : e.error);
4425 }
4426 
4427 /*
4428  * Flush local dirty pages to stable storage on the server.
4429  *
4430  * If FNODSYNC is specified, then there is nothing to do because
4431  * metadata changes are not cached on the client before being
4432  * sent to the server.
4433  */
4434 static int
4435 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr)
4436 {
4437 	int error;
4438 
4439 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4440 		return (0);
4441 	if (curproc->p_zone != VTOMI4(vp)->mi_zone)
4442 		return (EIO);
4443 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4444 	if (!error)
4445 		error = VTOR4(vp)->r_error;
4446 	return (error);
4447 }
4448 
4449 /*
4450  * Weirdness: if the file was removed or the target of a rename
4451  * operation while it was open, it got renamed instead.  Here we
4452  * remove the renamed file.
4453  */
4454 static void
4455 nfs4_inactive(vnode_t *vp, cred_t *cr)
4456 {
4457 	rnode4_t *rp;
4458 
4459 	ASSERT(vp != DNLC_NO_VNODE);
4460 
4461 	rp = VTOR4(vp);
4462 
4463 	if (IS_SHADOW(vp, rp)) {
4464 		sv_inactive(vp);
4465 		return;
4466 	}
4467 
4468 	/*
4469 	 * If this is coming from the wrong zone, we let someone in the right
4470 	 * zone take care of it asynchronously.  We can get here due to
4471 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4472 	 * potentially turn into an expensive no-op if, for instance, v_count
4473 	 * gets incremented in the meantime, but it's still correct.
4474 	 */
4475 	if (curproc->p_zone != VTOMI4(vp)->mi_zone) {
4476 		nfs4_async_inactive(vp, cr);
4477 		return;
4478 	}
4479 
4480 	/*
4481 	 * Some of the cleanup steps might require over-the-wire
4482 	 * operations.  Since VOP_INACTIVE can get called as a result of
4483 	 * other over-the-wire operations (e.g., an attribute cache update
4484 	 * can lead to a DNLC purge), doing those steps now would lead to a
4485 	 * nested call to the recovery framework, which can deadlock.  So
4486 	 * do any over-the-wire cleanups asynchronously, in a separate
4487 	 * thread.
4488 	 */
4489 
4490 	mutex_enter(&rp->r_os_lock);
4491 	mutex_enter(&rp->r_statelock);
4492 	mutex_enter(&rp->r_statev4_lock);
4493 
4494 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4495 		mutex_exit(&rp->r_statev4_lock);
4496 		mutex_exit(&rp->r_statelock);
4497 		mutex_exit(&rp->r_os_lock);
4498 		nfs4_async_inactive(vp, cr);
4499 		return;
4500 	}
4501 
4502 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4503 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4504 		mutex_exit(&rp->r_statev4_lock);
4505 		mutex_exit(&rp->r_statelock);
4506 		mutex_exit(&rp->r_os_lock);
4507 		nfs4_async_inactive(vp, cr);
4508 		return;
4509 	}
4510 
4511 	if (rp->r_unldvp != NULL) {
4512 		mutex_exit(&rp->r_statev4_lock);
4513 		mutex_exit(&rp->r_statelock);
4514 		mutex_exit(&rp->r_os_lock);
4515 		nfs4_async_inactive(vp, cr);
4516 		return;
4517 	}
4518 	mutex_exit(&rp->r_statev4_lock);
4519 	mutex_exit(&rp->r_statelock);
4520 	mutex_exit(&rp->r_os_lock);
4521 
4522 	rp4_addfree(rp, cr);
4523 }
4524 
4525 /*
4526  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4527  * various bits of state.  The caller must not refer to vp after this call.
4528  */
4529 
4530 void
4531 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4532 {
4533 	rnode4_t *rp = VTOR4(vp);
4534 	nfs4_recov_state_t recov_state;
4535 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4536 	vnode_t *unldvp;
4537 	char *unlname;
4538 	cred_t *unlcred;
4539 	COMPOUND4args_clnt args;
4540 	COMPOUND4res_clnt res, *resp;
4541 	nfs_argop4 argop[2];
4542 	int doqueue;
4543 #ifdef DEBUG
4544 	char *name;
4545 #endif
4546 
4547 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
4548 	ASSERT(!IS_SHADOW(vp, rp));
4549 
4550 #ifdef DEBUG
4551 	name = fn_name(VTOSV(vp)->sv_name);
4552 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4553 		"release vnode %s", name));
4554 	kmem_free(name, MAXNAMELEN);
4555 #endif
4556 
4557 	if (vp->v_type == VREG) {
4558 		bool_t recov_failed = FALSE;
4559 
4560 		e.error = nfs4close_all(vp, cr);
4561 		if (e.error) {
4562 			/* Check to see if recovery failed */
4563 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4564 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4565 				recov_failed = TRUE;
4566 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4567 			if (!recov_failed) {
4568 				mutex_enter(&rp->r_statelock);
4569 				if (rp->r_flags & R4RECOVERR)
4570 					recov_failed = TRUE;
4571 				mutex_exit(&rp->r_statelock);
4572 			}
4573 			if (recov_failed) {
4574 				NFS4_DEBUG(nfs4_client_recov_debug,
4575 					    (CE_NOTE, "nfs4_inactive_otw: "
4576 					    "close failed (recovery failure)"));
4577 			}
4578 		}
4579 	}
4580 
4581 redo:
4582 	if (rp->r_unldvp == NULL) {
4583 		rp4_addfree(rp, cr);
4584 		return;
4585 	}
4586 
4587 	/*
4588 	 * Save the vnode pointer for the directory where the
4589 	 * unlinked-open file got renamed, then set it to NULL
4590 	 * to prevent another thread from getting here before
4591 	 * we're done with the remove.  While we have the
4592 	 * statelock, make local copies of the pertinent rnode
4593 	 * fields.  If we weren't to do this in an atomic way, the
4594 	 * the unl* fields could become inconsistent with respect
4595 	 * to each other due to a race condition between this
4596 	 * code and nfs_remove().  See bug report 1034328.
4597 	 */
4598 	mutex_enter(&rp->r_statelock);
4599 	if (rp->r_unldvp == NULL) {
4600 		mutex_exit(&rp->r_statelock);
4601 		rp4_addfree(rp, cr);
4602 		return;
4603 	}
4604 
4605 	unldvp = rp->r_unldvp;
4606 	rp->r_unldvp = NULL;
4607 	unlname = rp->r_unlname;
4608 	rp->r_unlname = NULL;
4609 	unlcred = rp->r_unlcred;
4610 	rp->r_unlcred = NULL;
4611 	mutex_exit(&rp->r_statelock);
4612 
4613 	/*
4614 	 * If there are any dirty pages left, then flush
4615 	 * them.  This is unfortunate because they just
4616 	 * may get thrown away during the remove operation,
4617 	 * but we have to do this for correctness.
4618 	 */
4619 	if (nfs4_has_pages(vp) &&
4620 			    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4621 		ASSERT(vp->v_type != VCHR);
4622 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr);
4623 		if (e.error) {
4624 			mutex_enter(&rp->r_statelock);
4625 			if (!rp->r_error)
4626 				rp->r_error = e.error;
4627 			mutex_exit(&rp->r_statelock);
4628 		}
4629 	}
4630 
4631 	recov_state.rs_flags = 0;
4632 	recov_state.rs_num_retry_despite_err = 0;
4633 recov_retry_remove:
4634 	/*
4635 	 * Do the remove operation on the renamed file
4636 	 */
4637 	args.ctag = TAG_INACTIVE;
4638 
4639 	/*
4640 	 * Remove ops: putfh dir; remove
4641 	 */
4642 	args.array_len = 2;
4643 	args.array = argop;
4644 
4645 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4646 	if (e.error) {
4647 		kmem_free(unlname, MAXNAMELEN);
4648 		crfree(unlcred);
4649 		VN_RELE(unldvp);
4650 		/*
4651 		 * Try again; this time around r_unldvp will be NULL, so we'll
4652 		 * just call rp4_addfree() and return.
4653 		 */
4654 		goto redo;
4655 	}
4656 
4657 	/* putfh directory */
4658 	argop[0].argop = OP_CPUTFH;
4659 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4660 
4661 	/* remove */
4662 	argop[1].argop = OP_CREMOVE;
4663 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4664 
4665 	doqueue = 1;
4666 	resp = &res;
4667 
4668 #if 0 /* notyet */
4669 	/*
4670 	 * Can't do this yet.  We may be being called from
4671 	 * dnlc_purge_XXX while that routine is holding a
4672 	 * mutex lock to the nc_rele list.  The calls to
4673 	 * nfs3_cache_wcc_data may result in calls to
4674 	 * dnlc_purge_XXX.  This will result in a deadlock.
4675 	 */
4676 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4677 	if (e.error) {
4678 		PURGE_ATTRCACHE4(unldvp);
4679 		resp = NULL;
4680 	} else if (res.status) {
4681 		e.error = geterrno4(res.status);
4682 		PURGE_ATTRCACHE4(unldvp);
4683 		/*
4684 		 * This code is inactive right now
4685 		 * but if made active there should
4686 		 * be a nfs4_end_op() call before
4687 		 * nfs4_purge_stale_fh to avoid start_op()
4688 		 * deadlock. See BugId: 4948726
4689 		 */
4690 		nfs4_purge_stale_fh(error, unldvp, cr);
4691 	} else {
4692 		nfs_resop4 *resop;
4693 		REMOVE4res *rm_res;
4694 
4695 		resop = &res.array[1];
4696 		rm_res = &resop->nfs_resop4_u.opremove;
4697 		/*
4698 		 * Update directory cache attribute,
4699 		 * readdir and dnlc caches.
4700 		 */
4701 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4702 	}
4703 #else
4704 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4705 
4706 	PURGE_ATTRCACHE4(unldvp);
4707 #endif
4708 
4709 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4710 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4711 		    NULL, NULL, OP_REMOVE, NULL) == FALSE) {
4712 			if (!e.error)
4713 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4714 								(caddr_t)&res);
4715 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4716 							&recov_state, TRUE);
4717 			goto recov_retry_remove;
4718 		}
4719 	}
4720 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4721 
4722 	/*
4723 	 * Release stuff held for the remove
4724 	 */
4725 	VN_RELE(unldvp);
4726 	if (!e.error && resp)
4727 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4728 
4729 	kmem_free(unlname, MAXNAMELEN);
4730 	crfree(unlcred);
4731 	goto redo;
4732 }
4733 
4734 /*
4735  * Remote file system operations having to do with directory manipulation.
4736  */
4737 /* ARGSUSED3 */
4738 static int
4739 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4740 	int flags, vnode_t *rdir, cred_t *cr)
4741 {
4742 	int error;
4743 	vnode_t *vp, *avp = NULL;
4744 	rnode4_t *drp;
4745 
4746 	*vpp = NULL;
4747 	if (curproc->p_zone != VTOMI4(dvp)->mi_zone)
4748 		return (EPERM);
4749 	/*
4750 	 * if LOOKUP_XATTR, must replace dvp (object) with
4751 	 * object's attrdir before continuing with lookup
4752 	 */
4753 	if (flags & LOOKUP_XATTR) {
4754 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4755 		if (error)
4756 			return (error);
4757 
4758 		dvp = avp;
4759 
4760 		/*
4761 		 * If lookup is for "", just return dvp now.  The attrdir
4762 		 * has already been activated (from nfs4lookup_xattr), and
4763 		 * the caller will RELE the original dvp -- not
4764 		 * the attrdir.  So, set vpp and return.
4765 		 * Currently, when the LOOKUP_XATTR flag is
4766 		 * passed to VOP_LOOKUP, the name is always empty, and
4767 		 * shortcircuiting here avoids 3 unneeded lock/unlock
4768 		 * pairs.
4769 		 *
4770 		 * If a non-empty name was provided, then it is the
4771 		 * attribute name, and it will be looked up below.
4772 		 */
4773 		if (*nm == '\0') {
4774 			*vpp = dvp;
4775 			return (0);
4776 		}
4777 
4778 		/*
4779 		 * The vfs layer never sends a name when asking for the
4780 		 * attrdir, so we should never get here (unless of course
4781 		 * name is passed at some time in future -- at which time
4782 		 * we'll blow up here).
4783 		 */
4784 		ASSERT(0);
4785 	}
4786 
4787 	drp = VTOR4(dvp);
4788 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4789 		return (EINTR);
4790 
4791 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
4792 	nfs_rw_exit(&drp->r_rwlock);
4793 
4794 	/*
4795 	 * If vnode is a device, create special vnode.
4796 	 */
4797 	if (!error && ISVDEV((*vpp)->v_type)) {
4798 		vp = *vpp;
4799 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
4800 		VN_RELE(vp);
4801 	}
4802 
4803 	return (error);
4804 }
4805 
4806 /* ARGSUSED */
4807 static int
4808 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
4809 {
4810 	int error;
4811 	rnode4_t *drp;
4812 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
4813 	mntinfo4_t *mi;
4814 
4815 	mi = VTOMI4(dvp);
4816 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR))
4817 		return (EINVAL);
4818 
4819 	drp = VTOR4(dvp);
4820 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4821 		return (EINTR);
4822 
4823 	mutex_enter(&drp->r_statelock);
4824 	/*
4825 	 * If the server doesn't support xattrs just return EINVAL
4826 	 */
4827 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
4828 		mutex_exit(&drp->r_statelock);
4829 		nfs_rw_exit(&drp->r_rwlock);
4830 		return (EINVAL);
4831 	}
4832 
4833 	/*
4834 	 * If there is a cached xattr directory entry,
4835 	 * use it as long as the attributes are valid. If the
4836 	 * attributes are not valid, take the simple approach and
4837 	 * free the cached value and re-fetch a new value.
4838 	 *
4839 	 * We don't negative entry cache for now, if we did we
4840 	 * would need to check if the file has changed on every
4841 	 * lookup. But xattrs don't exist very often and failing
4842 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
4843 	 * so do an openattr over the wire for now.
4844 	 */
4845 	if (drp->r_xattr_dir != NULL) {
4846 		if (ATTRCACHE4_VALID(dvp)) {
4847 			VN_HOLD(drp->r_xattr_dir);
4848 			*vpp = drp->r_xattr_dir;
4849 			mutex_exit(&drp->r_statelock);
4850 			nfs_rw_exit(&drp->r_rwlock);
4851 			return (0);
4852 		}
4853 		VN_RELE(drp->r_xattr_dir);
4854 		drp->r_xattr_dir = NULL;
4855 	}
4856 	mutex_exit(&drp->r_statelock);
4857 
4858 	error = nfs4openattr(dvp, vpp, cflag, cr);
4859 
4860 	nfs_rw_exit(&drp->r_rwlock);
4861 
4862 	return (error);
4863 }
4864 
4865 static int
4866 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
4867 {
4868 	int error;
4869 	rnode4_t *drp;
4870 
4871 	ASSERT(curproc->p_zone == VTOMI4(dvp)->mi_zone);
4872 
4873 	/*
4874 	 * If lookup is for "", just return dvp.  Don't need
4875 	 * to send it over the wire, look it up in the dnlc,
4876 	 * or perform any access checks.
4877 	 */
4878 	if (*nm == '\0') {
4879 		VN_HOLD(dvp);
4880 		*vpp = dvp;
4881 		return (0);
4882 	}
4883 
4884 	/*
4885 	 * Can't do lookups in non-directories.
4886 	 */
4887 	if (dvp->v_type != VDIR)
4888 		return (ENOTDIR);
4889 
4890 	/*
4891 	 * If lookup is for ".", just return dvp.  Don't need
4892 	 * to send it over the wire or look it up in the dnlc,
4893 	 * just need to check access.
4894 	 */
4895 	if (nm[0] == '.' && nm[1] == '\0') {
4896 		error = nfs4_access(dvp, VEXEC, 0, cr);
4897 		if (error)
4898 			return (error);
4899 		VN_HOLD(dvp);
4900 		*vpp = dvp;
4901 		return (0);
4902 	}
4903 
4904 	drp = VTOR4(dvp);
4905 	if (!(drp->r_flags & R4LOOKUP)) {
4906 		mutex_enter(&drp->r_statelock);
4907 		drp->r_flags |= R4LOOKUP;
4908 		mutex_exit(&drp->r_statelock);
4909 	}
4910 
4911 	*vpp = NULL;
4912 	/*
4913 	 * Lookup this name in the DNLC.  If there is no entry
4914 	 * lookup over the wire.
4915 	 */
4916 	if (!skipdnlc)
4917 		*vpp = dnlc_lookup(dvp, nm);
4918 	if (*vpp == NULL) {
4919 		/*
4920 		 * We need to go over the wire to lookup the name.
4921 		 */
4922 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
4923 	}
4924 
4925 	/*
4926 	 * We hit on the dnlc
4927 	 */
4928 	if (*vpp != DNLC_NO_VNODE ||
4929 			    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
4930 		/*
4931 		 * But our attrs may not be valid.
4932 		 */
4933 		if (ATTRCACHE4_VALID(dvp)) {
4934 			error = nfs4_waitfor_purge_complete(dvp);
4935 			if (error) {
4936 				VN_RELE(*vpp);
4937 				*vpp = NULL;
4938 				return (error);
4939 			}
4940 
4941 			/*
4942 			 * If after the purge completes, check to make sure
4943 			 * our attrs are still valid.
4944 			 */
4945 			if (ATTRCACHE4_VALID(dvp)) {
4946 				/*
4947 				 * If we waited for a purge we may have
4948 				 * lost our vnode so look it up again.
4949 				 */
4950 				VN_RELE(*vpp);
4951 				*vpp = dnlc_lookup(dvp, nm);
4952 				if (*vpp == NULL)
4953 					return (nfs4lookupnew_otw(dvp,
4954 						nm, vpp, cr));
4955 
4956 				/*
4957 				 * The access cache should almost always hit
4958 				 */
4959 				error = nfs4_access(dvp, VEXEC, 0, cr);
4960 
4961 				if (error) {
4962 					VN_RELE(*vpp);
4963 					*vpp = NULL;
4964 					return (error);
4965 				}
4966 				if (*vpp == DNLC_NO_VNODE) {
4967 					VN_RELE(*vpp);
4968 					*vpp = NULL;
4969 					return (ENOENT);
4970 				}
4971 				return (0);
4972 			}
4973 		}
4974 	}
4975 
4976 	ASSERT(*vpp != NULL);
4977 
4978 	/*
4979 	 * We may have gotten here we have one of the following cases:
4980 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
4981 	 *		need to validate them.
4982 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
4983 	 *		must validate.
4984 	 *
4985 	 * Go to the server and check if the directory has changed, if
4986 	 * it hasn't we are done and can use the dnlc entry.
4987 	 */
4988 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
4989 }
4990 
4991 /*
4992  * Go to the server and check if the directory has changed, if
4993  * it hasn't we are done and can use the dnlc entry.  If it
4994  * has changed we get a new copy of its attributes and check
4995  * the access for VEXEC, then relookup the filename and
4996  * get its filehandle and attributes.
4997  *
4998  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
4999  *	if the NVERIFY failed we must
5000  *		purge the caches
5001  *		cache new attributes (will set r_time_attr_inval)
5002  *		cache new access
5003  *		recheck VEXEC access
5004  *		add name to dnlc, possibly negative
5005  *		if LOOKUP succeeded
5006  *			cache new attributes
5007  *	else
5008  *		set a new r_time_attr_inval for dvp
5009  *		check to make sure we have access
5010  *
5011  * The vpp returned is the vnode passed in if the directory is valid,
5012  * a new vnode if successful lookup, or NULL on error.
5013  */
5014 static int
5015 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5016 {
5017 	COMPOUND4args_clnt args;
5018 	COMPOUND4res_clnt res;
5019 	fattr4 *ver_fattr;
5020 	fattr4_change dchange;
5021 	int32_t *ptr;
5022 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5023 	nfs_argop4 *argop;
5024 	int doqueue;
5025 	mntinfo4_t *mi;
5026 	nfs4_recov_state_t recov_state;
5027 	hrtime_t t;
5028 	int isdotdot;
5029 	vnode_t *nvp;
5030 	nfs_fh4 *fhp;
5031 	nfs4_sharedfh_t *sfhp;
5032 	nfs4_access_type_t cacc;
5033 	rnode4_t *nrp;
5034 	rnode4_t *drp = VTOR4(dvp);
5035 	nfs4_ga_res_t *garp = NULL;
5036 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5037 
5038 	ASSERT(curproc->p_zone == VTOMI4(dvp)->mi_zone);
5039 	ASSERT(nm != NULL);
5040 	ASSERT(nm[0] != '\0');
5041 	ASSERT(dvp->v_type == VDIR);
5042 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5043 	ASSERT(*vpp != NULL);
5044 
5045 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5046 		isdotdot = 1;
5047 		args.ctag = TAG_LOOKUP_VPARENT;
5048 	} else {
5049 		/*
5050 		 * Do not allow crossing of server mount points.  The
5051 		 * only visible entries in a SRVSTUB dir are . and ..
5052 		 * This code handles the non-.. case.  We can't even get
5053 		 * this far if looking up ".".
5054 		 */
5055 		if (VTOR4(dvp)->r_flags & R4SRVSTUB) {
5056 			VN_RELE(*vpp);
5057 			*vpp = NULL;
5058 			return (ENOENT);
5059 		}
5060 		isdotdot = 0;
5061 		args.ctag = TAG_LOOKUP_VALID;
5062 	}
5063 
5064 	mi = VTOMI4(dvp);
5065 	recov_state.rs_flags = 0;
5066 	recov_state.rs_num_retry_despite_err = 0;
5067 
5068 	nvp = NULL;
5069 
5070 	/* Save the original mount point security information */
5071 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5072 
5073 recov_retry:
5074 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5075 			    &recov_state, NULL);
5076 	if (e.error) {
5077 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5078 		VN_RELE(*vpp);
5079 		*vpp = NULL;
5080 		return (e.error);
5081 	}
5082 
5083 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5084 
5085 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5086 	args.array_len = 7;
5087 	args.array = argop;
5088 
5089 	/* 0. putfh file */
5090 	argop[0].argop = OP_CPUTFH;
5091 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5092 
5093 	/* 1. nverify the change info */
5094 	argop[1].argop = OP_NVERIFY;
5095 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5096 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5097 	ver_fattr->attrlist4 = (char *)&dchange;
5098 	ptr = (int32_t *)&dchange;
5099 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5100 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5101 
5102 	/* 2. getattr directory */
5103 	argop[2].argop = OP_GETATTR;
5104 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5105 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5106 
5107 	/* 3. access directory */
5108 	argop[3].argop = OP_ACCESS;
5109 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5110 			ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5111 
5112 	/* 4. lookup name */
5113 	if (isdotdot) {
5114 		argop[4].argop = OP_LOOKUPP;
5115 	} else {
5116 		argop[4].argop = OP_CLOOKUP;
5117 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5118 	}
5119 
5120 	/* 5. resulting file handle */
5121 	argop[5].argop = OP_GETFH;
5122 
5123 	/* 6. resulting file attributes */
5124 	argop[6].argop = OP_GETATTR;
5125 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5126 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5127 
5128 	doqueue = 1;
5129 	t = gethrtime();
5130 
5131 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5132 
5133 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5134 		/*
5135 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5136 		 * from this thread, do not go thru the recovery thread since
5137 		 * we need the nm information.
5138 		 *
5139 		 * Not doing dotdot case because there is no specification
5140 		 * for (PUTFH, SECINFO "..") yet.
5141 		 */
5142 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5143 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr))) {
5144 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5145 					&recov_state, FALSE);
5146 			} else {
5147 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5148 					&recov_state, TRUE);
5149 			}
5150 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5151 			kmem_free(argop, argoplist_size);
5152 			if (!e.error)
5153 				goto recov_retry;
5154 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5155 			VN_RELE(*vpp);
5156 			*vpp = NULL;
5157 			return (e.error);
5158 		}
5159 
5160 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5161 		    OP_LOOKUP, NULL) == FALSE) {
5162 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5163 				&recov_state, TRUE);
5164 
5165 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5166 			kmem_free(argop, argoplist_size);
5167 			goto recov_retry;
5168 		}
5169 	}
5170 
5171 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5172 
5173 	if (e.error || res.array_len == 0) {
5174 		/*
5175 		 * If e.error isn't set, then reply has no ops (or we couldn't
5176 		 * be here).  The only legal way to reply without an op array
5177 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5178 		 * be in the reply for all other status values.
5179 		 *
5180 		 * For valid replies without an ops array, return ENOTSUP
5181 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5182 		 * return EIO -- don't trust status.
5183 		 */
5184 		if (e.error == 0)
5185 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5186 				ENOTSUP : EIO;
5187 		VN_RELE(*vpp);
5188 		*vpp = NULL;
5189 		kmem_free(argop, argoplist_size);
5190 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5191 		return (e.error);
5192 	}
5193 
5194 	if (res.status != NFS4ERR_SAME) {
5195 		e.error = geterrno4(res.status);
5196 
5197 		/*
5198 		 * The NVERIFY "failed" so the directory has changed
5199 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5200 		 * cleanly.
5201 		 */
5202 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5203 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5204 			nfs4_purge_stale_fh(e.error, dvp, cr);
5205 			VN_RELE(*vpp);
5206 			*vpp = NULL;
5207 			goto exit;
5208 		}
5209 
5210 		/*
5211 		 * We know the NVERIFY "failed" so we must:
5212 		 *	purge the caches (access and indirectly dnlc if needed)
5213 		 */
5214 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5215 
5216 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5217 			nfs4_purge_stale_fh(e.error, dvp, cr);
5218 			VN_RELE(*vpp);
5219 			*vpp = NULL;
5220 			goto exit;
5221 		}
5222 
5223 		/*
5224 		 * Install new cached attributes for the directory
5225 		 */
5226 		nfs4_attr_cache(dvp,
5227 				&res.array[2].nfs_resop4_u.opgetattr.ga_res,
5228 				t, cr, FALSE, NULL);
5229 
5230 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5231 			nfs4_purge_stale_fh(e.error, dvp, cr);
5232 			VN_RELE(*vpp);
5233 			*vpp = NULL;
5234 			e.error = geterrno4(res.status);
5235 			goto exit;
5236 		}
5237 
5238 		/*
5239 		 * Now we know the directory is valid,
5240 		 * cache new directory access
5241 		 */
5242 		nfs4_access_cache(drp,
5243 			args.array[3].nfs_argop4_u.opaccess.access,
5244 			res.array[3].nfs_resop4_u.opaccess.access, cr);
5245 
5246 		/*
5247 		 * recheck VEXEC access
5248 		 */
5249 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5250 		if (cacc != NFS4_ACCESS_ALLOWED) {
5251 			/*
5252 			 * Directory permissions might have been revoked
5253 			 */
5254 			if (cacc == NFS4_ACCESS_DENIED) {
5255 				e.error = EACCES;
5256 				VN_RELE(*vpp);
5257 				*vpp = NULL;
5258 				goto exit;
5259 			}
5260 
5261 			/*
5262 			 * Somehow we must not have asked for enough
5263 			 * so try a singleton ACCESS, should never happen.
5264 			 */
5265 			e.error = nfs4_access(dvp, VEXEC, 0, cr);
5266 			if (e.error) {
5267 				VN_RELE(*vpp);
5268 				*vpp = NULL;
5269 				goto exit;
5270 			}
5271 		}
5272 
5273 		e.error = geterrno4(res.status);
5274 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5275 			/*
5276 			 * The lookup failed, probably no entry
5277 			 */
5278 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5279 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5280 			} else {
5281 				/*
5282 				 * Might be some other error, so remove
5283 				 * the dnlc entry to make sure we start all
5284 				 * over again, next time.
5285 				 */
5286 				dnlc_remove(dvp, nm);
5287 			}
5288 			VN_RELE(*vpp);
5289 			*vpp = NULL;
5290 			goto exit;
5291 		}
5292 
5293 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5294 			/*
5295 			 * The file exists but we can't get its fh for
5296 			 * some unknown reason.  Remove it from the dnlc
5297 			 * and error out to be safe.
5298 			 */
5299 			dnlc_remove(dvp, nm);
5300 			VN_RELE(*vpp);
5301 			*vpp = NULL;
5302 			goto exit;
5303 		}
5304 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5305 		if (fhp->nfs_fh4_len == 0) {
5306 			/*
5307 			 * The file exists but a bogus fh
5308 			 * some unknown reason.  Remove it from the dnlc
5309 			 * and error out to be safe.
5310 			 */
5311 			e.error = ENOENT;
5312 			dnlc_remove(dvp, nm);
5313 			VN_RELE(*vpp);
5314 			*vpp = NULL;
5315 			goto exit;
5316 		}
5317 		sfhp = sfh4_get(fhp, mi);
5318 
5319 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5320 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5321 
5322 		/*
5323 		 * Make the new rnode
5324 		 */
5325 		if (isdotdot) {
5326 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5327 			if (e.error) {
5328 				sfh4_rele(&sfhp);
5329 				VN_RELE(*vpp);
5330 				*vpp = NULL;
5331 				goto exit;
5332 			}
5333 			/*
5334 			 * XXX if nfs4_make_dotdot uses an existing rnode
5335 			 * XXX it doesn't update the attributes.
5336 			 * XXX for now just save them again to save an OTW
5337 			 */
5338 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5339 		} else {
5340 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5341 				dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5342 			/*
5343 			 * If v_type == VNON, then garp was NULL because
5344 			 * the last op in the compound failed and makenfs4node
5345 			 * could not find the vnode for sfhp. It created
5346 			 * a new vnode, so we have nothing to purge here.
5347 			 */
5348 			if (nvp->v_type == VNON) {
5349 				vattr_t vattr;
5350 
5351 				vattr.va_mask = AT_TYPE;
5352 				/*
5353 				 * N.B. We've already called nfs4_end_fop above.
5354 				 */
5355 				e.error = nfs4getattr(nvp, &vattr, cr);
5356 				if (e.error) {
5357 					sfh4_rele(&sfhp);
5358 					VN_RELE(*vpp);
5359 					*vpp = NULL;
5360 					VN_RELE(nvp);
5361 					goto exit;
5362 				}
5363 				nvp->v_type = vattr.va_type;
5364 			}
5365 		}
5366 		sfh4_rele(&sfhp);
5367 
5368 		nrp = VTOR4(nvp);
5369 		mutex_enter(&nrp->r_statev4_lock);
5370 		if (!nrp->created_v4)
5371 			dnlc_update(dvp, nm, nvp);
5372 		mutex_exit(&nrp->r_statev4_lock);
5373 
5374 		VN_RELE(*vpp);
5375 		*vpp = nvp;
5376 	} else {
5377 		hrtime_t now;
5378 		hrtime_t delta = 0;
5379 
5380 		e.error = 0;
5381 
5382 		/*
5383 		 * Because the NVERIFY "succeeded" we know that the
5384 		 * directory attributes are still valid
5385 		 * so update r_time_attr_inval
5386 		 */
5387 		now = gethrtime();
5388 		mutex_enter(&drp->r_statelock);
5389 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5390 			delta = now - drp->r_time_attr_saved;
5391 			if (delta < mi->mi_acdirmin)
5392 				delta = mi->mi_acdirmin;
5393 			else if (delta > mi->mi_acdirmax)
5394 				delta = mi->mi_acdirmax;
5395 		}
5396 		drp->r_time_attr_inval = now + delta;
5397 		mutex_exit(&drp->r_statelock);
5398 		dnlc_update(dvp, nm, *vpp);
5399 
5400 		/*
5401 		 * Even though we have a valid directory attr cache
5402 		 * and dnlc entry, we may not have access.
5403 		 * This should almost always hit the cache.
5404 		 */
5405 		e.error = nfs4_access(dvp, VEXEC, 0, cr);
5406 		if (e.error) {
5407 			VN_RELE(*vpp);
5408 			*vpp = NULL;
5409 		}
5410 
5411 		if (*vpp == DNLC_NO_VNODE) {
5412 			VN_RELE(*vpp);
5413 			*vpp = NULL;
5414 			e.error = ENOENT;
5415 		}
5416 	}
5417 
5418 exit:
5419 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5420 	kmem_free(argop, argoplist_size);
5421 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5422 	return (e.error);
5423 }
5424 
5425 /*
5426  * We need to go over the wire to lookup the name, but
5427  * while we are there verify the directory has not
5428  * changed but if it has, get new attributes and check access
5429  *
5430  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5431  *					NVERIFY GETATTR ACCESS
5432  *
5433  * With the results:
5434  *	if the NVERIFY failed we must purge the caches, add new attributes,
5435  *		and cache new access.
5436  *	set a new r_time_attr_inval
5437  *	add name to dnlc, possibly negative
5438  *	if LOOKUP succeeded
5439  *		cache new attributes
5440  */
5441 static int
5442 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5443 {
5444 	COMPOUND4args_clnt args;
5445 	COMPOUND4res_clnt res;
5446 	fattr4 *ver_fattr;
5447 	fattr4_change dchange;
5448 	int32_t *ptr;
5449 	nfs4_ga_res_t *garp = NULL;
5450 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5451 	nfs_argop4 *argop;
5452 	int doqueue;
5453 	mntinfo4_t *mi;
5454 	nfs4_recov_state_t recov_state;
5455 	hrtime_t t;
5456 	int isdotdot;
5457 	vnode_t *nvp;
5458 	nfs_fh4 *fhp;
5459 	nfs4_sharedfh_t *sfhp;
5460 	nfs4_access_type_t cacc;
5461 	rnode4_t *nrp;
5462 	rnode4_t *drp = VTOR4(dvp);
5463 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5464 
5465 	ASSERT(curproc->p_zone == VTOMI4(dvp)->mi_zone);
5466 	ASSERT(nm != NULL);
5467 	ASSERT(nm[0] != '\0');
5468 	ASSERT(dvp->v_type == VDIR);
5469 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5470 	ASSERT(*vpp == NULL);
5471 
5472 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5473 		isdotdot = 1;
5474 		args.ctag = TAG_LOOKUP_PARENT;
5475 	} else {
5476 		/*
5477 		 * Do not allow crossing of server mount points.  The
5478 		 * only visible entries in a SRVSTUB dir are . and ..
5479 		 * This code handles the non-.. case.  We can't even get
5480 		 * this far if looking up ".".
5481 		 */
5482 		if (VTOR4(dvp)->r_flags & R4SRVSTUB)
5483 			return (ENOENT);
5484 
5485 		isdotdot = 0;
5486 		args.ctag = TAG_LOOKUP;
5487 	}
5488 
5489 	mi = VTOMI4(dvp);
5490 	recov_state.rs_flags = 0;
5491 	recov_state.rs_num_retry_despite_err = 0;
5492 
5493 	nvp = NULL;
5494 
5495 	/* Save the original mount point security information */
5496 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5497 
5498 recov_retry:
5499 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5500 			    &recov_state, NULL);
5501 	if (e.error) {
5502 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5503 		return (e.error);
5504 	}
5505 
5506 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5507 
5508 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5509 	args.array_len = 9;
5510 	args.array = argop;
5511 
5512 	/* 0. putfh file */
5513 	argop[0].argop = OP_CPUTFH;
5514 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5515 
5516 	/* 1. savefh for the nverify */
5517 	argop[1].argop = OP_SAVEFH;
5518 
5519 	/* 2. lookup name */
5520 	if (isdotdot) {
5521 		argop[2].argop = OP_LOOKUPP;
5522 	} else {
5523 		argop[2].argop = OP_CLOOKUP;
5524 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5525 	}
5526 
5527 	/* 3. resulting file handle */
5528 	argop[3].argop = OP_GETFH;
5529 
5530 	/* 4. resulting file attributes */
5531 	argop[4].argop = OP_GETATTR;
5532 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5533 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5534 
5535 	/* 5. restorefh back the directory for the nverify */
5536 	argop[5].argop = OP_RESTOREFH;
5537 
5538 	/* 6. nverify the change info */
5539 	argop[6].argop = OP_NVERIFY;
5540 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5541 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5542 	ver_fattr->attrlist4 = (char *)&dchange;
5543 	ptr = (int32_t *)&dchange;
5544 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5545 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5546 
5547 	/* 7. getattr directory */
5548 	argop[7].argop = OP_GETATTR;
5549 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5550 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5551 
5552 	/* 8. access directory */
5553 	argop[8].argop = OP_ACCESS;
5554 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5555 			ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5556 
5557 	doqueue = 1;
5558 	t = gethrtime();
5559 
5560 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5561 
5562 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5563 		/*
5564 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5565 		 * from this thread, do not go thru the recovery thread since
5566 		 * we need the nm information.
5567 		 *
5568 		 * Not doing dotdot case because there is no specification
5569 		 * for (PUTFH, SECINFO "..") yet.
5570 		 */
5571 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5572 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr))) {
5573 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5574 					&recov_state, FALSE);
5575 			} else {
5576 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5577 					&recov_state, TRUE);
5578 			}
5579 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5580 			kmem_free(argop, argoplist_size);
5581 			if (!e.error)
5582 				goto recov_retry;
5583 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5584 			return (e.error);
5585 		}
5586 
5587 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5588 		    OP_LOOKUP, NULL) == FALSE) {
5589 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5590 				&recov_state, TRUE);
5591 
5592 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5593 			kmem_free(argop, argoplist_size);
5594 			goto recov_retry;
5595 		}
5596 	}
5597 
5598 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5599 
5600 	if (e.error || res.array_len == 0) {
5601 		/*
5602 		 * If e.error isn't set, then reply has no ops (or we couldn't
5603 		 * be here).  The only legal way to reply without an op array
5604 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5605 		 * be in the reply for all other status values.
5606 		 *
5607 		 * For valid replies without an ops array, return ENOTSUP
5608 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5609 		 * return EIO -- don't trust status.
5610 		 */
5611 		if (e.error == 0)
5612 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5613 				ENOTSUP : EIO;
5614 
5615 		kmem_free(argop, argoplist_size);
5616 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5617 		return (e.error);
5618 	}
5619 
5620 	e.error = geterrno4(res.status);
5621 
5622 	/*
5623 	 * The PUTFH and SAVEFH may have failed.
5624 	 */
5625 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5626 		    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5627 		nfs4_purge_stale_fh(e.error, dvp, cr);
5628 		goto exit;
5629 	}
5630 
5631 	/*
5632 	 * Check if the file exists, if it does delay entering
5633 	 * into the dnlc until after we update the directory
5634 	 * attributes so we don't cause it to get purged immediately.
5635 	 */
5636 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5637 		/*
5638 		 * The lookup failed, probably no entry
5639 		 */
5640 		if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5641 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5642 		}
5643 		goto exit;
5644 	}
5645 
5646 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5647 		/*
5648 		 * The file exists but we can't get its fh for
5649 		 * some unknown reason. Error out to be safe.
5650 		 */
5651 		goto exit;
5652 	}
5653 
5654 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5655 	if (fhp->nfs_fh4_len == 0) {
5656 		/*
5657 		 * The file exists but a bogus fh
5658 		 * some unknown reason.  Error out to be safe.
5659 		 */
5660 		e.error = EIO;
5661 		goto exit;
5662 	}
5663 	sfhp = sfh4_get(fhp, mi);
5664 
5665 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5666 		sfh4_rele(&sfhp);
5667 		e.error = EIO;
5668 		goto exit;
5669 	}
5670 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5671 
5672 	/*
5673 	 * The RESTOREFH may have failed
5674 	 */
5675 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5676 		sfh4_rele(&sfhp);
5677 		e.error = EIO;
5678 		goto exit;
5679 	}
5680 
5681 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5682 		/*
5683 		 * First make sure the NVERIFY failed as we expected,
5684 		 * if it didn't then be conservative and error out
5685 		 * as we can't trust the directory.
5686 		 */
5687 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5688 			sfh4_rele(&sfhp);
5689 			e.error = EIO;
5690 			goto exit;
5691 		}
5692 
5693 		/*
5694 		 * We know the NVERIFY "failed" so the directory has changed,
5695 		 * so we must:
5696 		 *	purge the caches (access and indirectly dnlc if needed)
5697 		 */
5698 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5699 
5700 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5701 			sfh4_rele(&sfhp);
5702 			goto exit;
5703 		}
5704 		nfs4_attr_cache(dvp,
5705 				&res.array[7].nfs_resop4_u.opgetattr.ga_res,
5706 				t, cr, FALSE, NULL);
5707 
5708 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5709 			nfs4_purge_stale_fh(e.error, dvp, cr);
5710 			sfh4_rele(&sfhp);
5711 			e.error = geterrno4(res.status);
5712 			goto exit;
5713 		}
5714 
5715 		/*
5716 		 * Now we know the directory is valid,
5717 		 * cache new directory access
5718 		 */
5719 		nfs4_access_cache(drp,
5720 			args.array[8].nfs_argop4_u.opaccess.access,
5721 			res.array[8].nfs_resop4_u.opaccess.access, cr);
5722 
5723 		/*
5724 		 * recheck VEXEC access
5725 		 */
5726 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5727 		if (cacc != NFS4_ACCESS_ALLOWED) {
5728 			/*
5729 			 * Directory permissions might have been revoked
5730 			 */
5731 			if (cacc == NFS4_ACCESS_DENIED) {
5732 				sfh4_rele(&sfhp);
5733 				e.error = EACCES;
5734 				goto exit;
5735 			}
5736 
5737 			/*
5738 			 * Somehow we must not have asked for enough
5739 			 * so try a singleton ACCESS should never happen
5740 			 */
5741 			e.error = nfs4_access(dvp, VEXEC, 0, cr);
5742 			if (e.error) {
5743 				sfh4_rele(&sfhp);
5744 				goto exit;
5745 			}
5746 		}
5747 
5748 		e.error = geterrno4(res.status);
5749 	} else {
5750 		hrtime_t now;
5751 		hrtime_t delta = 0;
5752 
5753 		e.error = 0;
5754 
5755 		/*
5756 		 * Because the NVERIFY "succeeded" we know that the
5757 		 * directory attributes are still valid
5758 		 * so update r_time_attr_inval
5759 		 */
5760 		now = gethrtime();
5761 		mutex_enter(&drp->r_statelock);
5762 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5763 			delta = now - drp->r_time_attr_saved;
5764 			if (delta < mi->mi_acdirmin)
5765 				delta = mi->mi_acdirmin;
5766 			else if (delta > mi->mi_acdirmax)
5767 				delta = mi->mi_acdirmax;
5768 		}
5769 		drp->r_time_attr_inval = now + delta;
5770 		mutex_exit(&drp->r_statelock);
5771 
5772 		/*
5773 		 * Even though we have a valid directory attr cache,
5774 		 * we may not have access.
5775 		 * This should almost always hit the cache.
5776 		 */
5777 		e.error = nfs4_access(dvp, VEXEC, 0, cr);
5778 		if (e.error) {
5779 			sfh4_rele(&sfhp);
5780 			goto exit;
5781 		}
5782 	}
5783 
5784 	/*
5785 	 * Now we have successfully completed the lookup, if the
5786 	 * directory has changed we now have the valid attributes.
5787 	 * We also know we have directory access.
5788 	 * Create the new rnode and insert it in the dnlc.
5789 	 */
5790 	if (isdotdot) {
5791 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5792 		if (e.error) {
5793 			sfh4_rele(&sfhp);
5794 			goto exit;
5795 		}
5796 		/*
5797 		 * XXX if nfs4_make_dotdot uses an existing rnode
5798 		 * XXX it doesn't update the attributes.
5799 		 * XXX for now just save them again to save an OTW
5800 		 */
5801 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5802 	} else {
5803 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5804 			dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5805 	}
5806 	sfh4_rele(&sfhp);
5807 
5808 	nrp = VTOR4(nvp);
5809 	mutex_enter(&nrp->r_statev4_lock);
5810 	if (!nrp->created_v4)
5811 		dnlc_update(dvp, nm, nvp);
5812 	mutex_exit(&nrp->r_statev4_lock);
5813 
5814 	*vpp = nvp;
5815 
5816 exit:
5817 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5818 	kmem_free(argop, argoplist_size);
5819 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5820 	return (e.error);
5821 }
5822 
5823 #ifdef DEBUG
5824 void
5825 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
5826 {
5827 	uint_t i, len;
5828 	zoneid_t zoneid = getzoneid();
5829 	char *s;
5830 
5831 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
5832 	for (i = 0; i < argcnt; i++) {
5833 		nfs_argop4 *op = &argbase[i];
5834 		switch (op->argop) {
5835 		case OP_CPUTFH:
5836 		case OP_PUTFH:
5837 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
5838 			break;
5839 		case OP_PUTROOTFH:
5840 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
5841 			break;
5842 		case OP_CLOOKUP:
5843 			s = op->nfs_argop4_u.opclookup.cname;
5844 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5845 			break;
5846 		case OP_LOOKUP:
5847 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
5848 			    &len, NULL);
5849 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5850 			kmem_free(s, len);
5851 			break;
5852 		case OP_LOOKUPP:
5853 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
5854 			break;
5855 		case OP_GETFH:
5856 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
5857 			break;
5858 		case OP_GETATTR:
5859 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
5860 			break;
5861 		case OP_OPENATTR:
5862 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
5863 			break;
5864 		default:
5865 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
5866 			    op->argop);
5867 			break;
5868 		}
5869 	}
5870 }
5871 #endif
5872 
5873 /*
5874  * nfs4lookup_setup - constructs a multi-lookup compound request.
5875  *
5876  * Given the path "nm1/nm2/.../nmn", the following compound requests
5877  * may be created:
5878  *
5879  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
5880  * is faster, for now.
5881  *
5882  * l4_getattrs indicates the type of compound requested.
5883  *
5884  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
5885  *
5886  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
5887  *
5888  *   total number of ops is n + 1.
5889  *
5890  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
5891  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
5892  *      before the last component, and only get attributes
5893  *      for the last component.  Note that the second-to-last
5894  *	pathname component is XATTR_RPATH, which does NOT go
5895  *	over-the-wire as a lookup.
5896  *
5897  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
5898  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
5899  *
5900  *   and total number of ops is n + 5.
5901  *
5902  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
5903  *      attribute directory: create lookups plus an OPENATTR
5904  *	replacing the last lookup.  Note that the last pathname
5905  *	component is XATTR_RPATH, which does NOT go over-the-wire
5906  *	as a lookup.
5907  *
5908  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
5909  *		Openattr; Getfh; Getattr }
5910  *
5911  *   and total number of ops is n + 5.
5912  *
5913  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
5914  *	nodes too.
5915  *
5916  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
5917  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
5918  *
5919  *   and total number of ops is 3*n + 1.
5920  *
5921  * All cases: returns the index in the arg array of the final LOOKUP op, or
5922  * -1 if no LOOKUPs were used.
5923  */
5924 int
5925 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
5926 {
5927 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
5928 	nfs_argop4 *argbase, *argop;
5929 	int arglen, argcnt;
5930 	int n = 1;	/* number of components */
5931 	int nga = 1;	/* number of Getattr's in request */
5932 	char c = '\0', *s, *p;
5933 	int lookup_idx = -1;
5934 	int argoplist_size;
5935 
5936 	/* set lookuparg response result to 0 */
5937 	lookupargp->resp->status = NFS4_OK;
5938 
5939 	/* skip leading "/" or "." e.g. ".//./" if there is */
5940 	for (; ; nm++) {
5941 		if (*nm != '/' && *nm != '.')
5942 			break;
5943 
5944 		/* ".." is counted as 1 component */
5945 		if (*nm == '.' && *(nm + 1) == '.')
5946 			break;
5947 	}
5948 
5949 	/*
5950 	 * Find n = number of components - nm must be null terminated
5951 	 * Skip "." components.
5952 	 */
5953 	if (*nm != '\0') {
5954 		for (n = 1, s = nm; *s != '\0'; s++) {
5955 			if ((*s == '/') && (*(s + 1) != '/') &&
5956 				    (*(s + 1) != '\0') &&
5957 				    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
5958 					*(s + 2) == '\0')))
5959 				n++;
5960 		}
5961 	} else
5962 		n = 0;
5963 
5964 	/*
5965 	 * nga is number of components that need Getfh+Getattr
5966 	 */
5967 	switch (l4_getattrs) {
5968 	case LKP4_NO_ATTRIBUTES:
5969 		nga = 0;
5970 		break;
5971 	case LKP4_ALL_ATTRIBUTES:
5972 		nga = n;
5973 		/*
5974 		 * Always have at least 1 getfh, getattr pair
5975 		 */
5976 		if (nga == 0)
5977 			nga++;
5978 		break;
5979 	case LKP4_LAST_ATTRDIR:
5980 	case LKP4_LAST_NAMED_ATTR:
5981 		nga = n+1;
5982 		break;
5983 	}
5984 
5985 	/*
5986 	 * If change to use the filehandle attr instead of getfh
5987 	 * the following line can be deleted.
5988 	 */
5989 	nga *= 2;
5990 
5991 	/*
5992 	 * calculate number of ops in request as
5993 	 * header + trailer + lookups + getattrs
5994 	 */
5995 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
5996 
5997 	argoplist_size = arglen * sizeof (nfs_argop4);
5998 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
5999 	lookupargp->argsp->array = argop;
6000 
6001 	argcnt = lookupargp->header_len;
6002 	argop += argcnt;
6003 
6004 	/*
6005 	 * loop and create a lookup op and possibly getattr/getfh for
6006 	 * each component. Skip "." components.
6007 	 */
6008 	for (s = nm; *s != '\0'; s = p) {
6009 		/*
6010 		 * Set up a pathname struct for each component if needed
6011 		 */
6012 		while (*s == '/')
6013 			s++;
6014 		if (*s == '\0')
6015 			break;
6016 		for (p = s; (*p != '/') && (*p != '\0'); p++);
6017 		c = *p;
6018 		*p = '\0';
6019 
6020 		if (s[0] == '.' && s[1] == '\0') {
6021 			*p = c;
6022 			continue;
6023 		}
6024 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6025 		    strcmp(s, XATTR_RPATH) == 0) {
6026 			/* getfh XXX may not be needed in future */
6027 			argop->argop = OP_GETFH;
6028 			argop++;
6029 			argcnt++;
6030 
6031 			/* getattr */
6032 			argop->argop = OP_GETATTR;
6033 			argop->nfs_argop4_u.opgetattr.attr_request =
6034 							lookupargp->ga_bits;
6035 			argop->nfs_argop4_u.opgetattr.mi =
6036 				lookupargp->mi;
6037 			argop++;
6038 			argcnt++;
6039 
6040 			/* openattr */
6041 			argop->argop = OP_OPENATTR;
6042 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6043 		    strcmp(s, XATTR_RPATH) == 0) {
6044 			/* openattr */
6045 			argop->argop = OP_OPENATTR;
6046 			argop++;
6047 			argcnt++;
6048 
6049 			/* getfh XXX may not be needed in future */
6050 			argop->argop = OP_GETFH;
6051 			argop++;
6052 			argcnt++;
6053 
6054 			/* getattr */
6055 			argop->argop = OP_GETATTR;
6056 			argop->nfs_argop4_u.opgetattr.attr_request =
6057 							lookupargp->ga_bits;
6058 			argop->nfs_argop4_u.opgetattr.mi =
6059 							lookupargp->mi;
6060 			argop++;
6061 			argcnt++;
6062 			*p = c;
6063 			continue;
6064 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6065 			/* lookupp */
6066 			argop->argop = OP_LOOKUPP;
6067 		} else {
6068 			/* lookup */
6069 			argop->argop = OP_LOOKUP;
6070 			(void) str_to_utf8(s,
6071 				&argop->nfs_argop4_u.oplookup.objname);
6072 		}
6073 		lookup_idx = argcnt;
6074 		argop++;
6075 		argcnt++;
6076 
6077 		*p = c;
6078 
6079 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6080 			/* getfh XXX may not be needed in future */
6081 			argop->argop = OP_GETFH;
6082 			argop++;
6083 			argcnt++;
6084 
6085 			/* getattr */
6086 			argop->argop = OP_GETATTR;
6087 			argop->nfs_argop4_u.opgetattr.attr_request =
6088 							lookupargp->ga_bits;
6089 			argop->nfs_argop4_u.opgetattr.mi =
6090 							lookupargp->mi;
6091 			argop++;
6092 			argcnt++;
6093 		}
6094 	}
6095 
6096 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6097 		((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6098 		if (needgetfh) {
6099 			/* stick in a post-lookup getfh */
6100 			argop->argop = OP_GETFH;
6101 			argcnt++;
6102 			argop++;
6103 		}
6104 		/* post-lookup getattr */
6105 		argop->argop = OP_GETATTR;
6106 		argop->nfs_argop4_u.opgetattr.attr_request =
6107 						lookupargp->ga_bits;
6108 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6109 		argcnt++;
6110 	}
6111 	argcnt += lookupargp->trailer_len;	/* actual op count */
6112 	lookupargp->argsp->array_len = argcnt;
6113 	lookupargp->arglen = arglen;
6114 
6115 #ifdef DEBUG
6116 	if (nfs4_client_lookup_debug)
6117 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6118 #endif
6119 
6120 	return (lookup_idx);
6121 }
6122 
6123 static int
6124 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6125 {
6126 	COMPOUND4args_clnt	args;
6127 	COMPOUND4res_clnt	res;
6128 	GETFH4res	*gf_res = NULL;
6129 	nfs_argop4	argop[4];
6130 	nfs_resop4	*resop = NULL;
6131 	nfs4_sharedfh_t *sfhp;
6132 	hrtime_t t;
6133 	nfs4_error_t	e;
6134 
6135 	rnode4_t	*drp;
6136 	int		doqueue = 1;
6137 	vnode_t		*vp;
6138 	int		needrecov = 0;
6139 	nfs4_recov_state_t recov_state;
6140 
6141 	ASSERT(curproc->p_zone == VTOMI4(dvp)->mi_zone);
6142 
6143 	*avp = NULL;
6144 	recov_state.rs_flags = 0;
6145 	recov_state.rs_num_retry_despite_err = 0;
6146 
6147 recov_retry:
6148 	/* COMPOUND: putfh, openattr, getfh, getattr */
6149 	args.array_len = 4;
6150 	args.array = argop;
6151 	args.ctag = TAG_OPENATTR;
6152 
6153 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6154 	if (e.error)
6155 		return (e.error);
6156 
6157 	drp = VTOR4(dvp);
6158 
6159 	/* putfh */
6160 	argop[0].argop = OP_CPUTFH;
6161 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6162 
6163 	/* openattr */
6164 	argop[1].argop = OP_OPENATTR;
6165 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6166 
6167 	/* getfh */
6168 	argop[2].argop = OP_GETFH;
6169 
6170 	/* getattr */
6171 	argop[3].argop = OP_GETATTR;
6172 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6173 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6174 
6175 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6176 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6177 	    rnode4info(drp)));
6178 
6179 	t = gethrtime();
6180 
6181 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6182 
6183 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6184 	if (needrecov) {
6185 		bool_t abort;
6186 
6187 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6188 		    "nfs4openattr: initiating recovery\n"));
6189 
6190 		abort = nfs4_start_recovery(&e,
6191 				VTOMI4(dvp), dvp, NULL, NULL, NULL,
6192 				OP_OPENATTR, NULL);
6193 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6194 		if (!e.error) {
6195 			e.error = geterrno4(res.status);
6196 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6197 		}
6198 		if (abort == FALSE)
6199 			goto recov_retry;
6200 		return (e.error);
6201 	}
6202 
6203 	if (e.error) {
6204 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6205 		return (e.error);
6206 	}
6207 
6208 	if (res.status) {
6209 		/*
6210 		 * If OTW errro is NOTSUPP, then it should be
6211 		 * translated to EINVAL.  All Solaris file system
6212 		 * implementations return EINVAL to the syscall layer
6213 		 * when the attrdir cannot be created due to an
6214 		 * implementation restriction or noxattr mount option.
6215 		 */
6216 		if (res.status == NFS4ERR_NOTSUPP) {
6217 			mutex_enter(&drp->r_statelock);
6218 			if (drp->r_xattr_dir)
6219 				VN_RELE(drp->r_xattr_dir);
6220 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6221 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6222 			mutex_exit(&drp->r_statelock);
6223 
6224 			e.error = EINVAL;
6225 		} else {
6226 			e.error = geterrno4(res.status);
6227 		}
6228 
6229 		if (e.error) {
6230 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6231 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6232 				    needrecov);
6233 			return (e.error);
6234 		}
6235 	}
6236 
6237 	resop = &res.array[0];  /* putfh res */
6238 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6239 
6240 	resop = &res.array[1];  /* openattr res */
6241 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6242 
6243 	resop = &res.array[2];  /* getfh res */
6244 	gf_res = &resop->nfs_resop4_u.opgetfh;
6245 	if (gf_res->object.nfs_fh4_len == 0) {
6246 		*avp = NULL;
6247 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6248 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6249 		return (ENOENT);
6250 	}
6251 
6252 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6253 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6254 				dvp->v_vfsp, t, cr, dvp,
6255 				fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH));
6256 	sfh4_rele(&sfhp);
6257 
6258 	if (e.error)
6259 		PURGE_ATTRCACHE4(vp);
6260 
6261 	mutex_enter(&vp->v_lock);
6262 	vp->v_flag |= V_XATTRDIR;
6263 	mutex_exit(&vp->v_lock);
6264 
6265 	*avp = vp;
6266 
6267 	mutex_enter(&drp->r_statelock);
6268 	if (drp->r_xattr_dir)
6269 		VN_RELE(drp->r_xattr_dir);
6270 	VN_HOLD(vp);
6271 	drp->r_xattr_dir = vp;
6272 
6273 	/*
6274 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6275 	 * NULL.  xattrs could be created at any time, and we have no
6276 	 * way to update pc4_xattr_exists in the base object if/when
6277 	 * it happens.
6278 	 */
6279 	drp->r_pathconf.pc4_xattr_valid = 0;
6280 
6281 	mutex_exit(&drp->r_statelock);
6282 
6283 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6284 
6285 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6286 
6287 	return (0);
6288 }
6289 
6290 /* ARGSUSED */
6291 static int
6292 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6293 	int mode, vnode_t **vpp, cred_t *cr, int flags)
6294 {
6295 	int error;
6296 	vnode_t *vp = NULL;
6297 	rnode4_t *rp;
6298 	struct vattr vattr;
6299 	rnode4_t *drp;
6300 	vnode_t *tempvp;
6301 	enum createmode4 createmode;
6302 	bool_t must_trunc = FALSE;
6303 
6304 	if (curproc->p_zone != VTOMI4(dvp)->mi_zone)
6305 		return (EPERM);
6306 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6307 		return (EINVAL);
6308 	}
6309 
6310 	/* . and .. have special meaning in the protocol, reject them. */
6311 
6312 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6313 		return (EISDIR);
6314 
6315 	drp = VTOR4(dvp);
6316 
6317 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6318 		return (EINTR);
6319 
6320 top:
6321 	/*
6322 	 * We make a copy of the attributes because the caller does not
6323 	 * expect us to change what va points to.
6324 	 */
6325 	vattr = *va;
6326 
6327 	/*
6328 	 * If the pathname is "", then dvp is the root vnode of
6329 	 * a remote file mounted over a local directory.
6330 	 * All that needs to be done is access
6331 	 * checking and truncation.  Note that we avoid doing
6332 	 * open w/ create because the parent directory might
6333 	 * be in pseudo-fs and the open would fail.
6334 	 */
6335 	if (*nm == '\0') {
6336 		error = 0;
6337 		VN_HOLD(dvp);
6338 		vp = dvp;
6339 		must_trunc = TRUE;
6340 	} else {
6341 		/*
6342 		 * We need to go over the wire, just to be sure whether the
6343 		 * file exists or not.  Using the DNLC can be dangerous in
6344 		 * this case when making a decision regarding existence.
6345 		 */
6346 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6347 	}
6348 
6349 	if (exclusive)
6350 		createmode = EXCLUSIVE4;
6351 	else
6352 		createmode = GUARDED4;
6353 
6354 	/*
6355 	 * error would be set if the file does not exist on the
6356 	 * server, so lets go create it.
6357 	 */
6358 	if (error) {
6359 		goto create_otw;
6360 	}
6361 
6362 	/*
6363 	 * File does exist on the server
6364 	 */
6365 	if (exclusive == EXCL)
6366 		error = EEXIST;
6367 	else if (vp->v_type == VDIR && (mode & VWRITE))
6368 		error = EISDIR;
6369 	else {
6370 		/*
6371 		 * If vnode is a device, create special vnode.
6372 		 */
6373 		if (ISVDEV(vp->v_type)) {
6374 			tempvp = vp;
6375 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6376 			VN_RELE(tempvp);
6377 		}
6378 		if (!(error = VOP_ACCESS(vp, mode, 0, cr))) {
6379 			if ((vattr.va_mask & AT_SIZE) &&
6380 			    vp->v_type == VREG) {
6381 				rp = VTOR4(vp);
6382 				/*
6383 				 * Check here for large file handled
6384 				 * by LF-unaware process (as
6385 				 * ufs_create() does)
6386 				 */
6387 				if (!(flags & FOFFMAX)) {
6388 					mutex_enter(&rp->r_statelock);
6389 					if (rp->r_size > MAXOFF32_T)
6390 						error = EOVERFLOW;
6391 					mutex_exit(&rp->r_statelock);
6392 				}
6393 
6394 				/* if error is set then we need to return */
6395 				if (error) {
6396 					nfs_rw_exit(&drp->r_rwlock);
6397 					VN_RELE(vp);
6398 					return (error);
6399 				}
6400 
6401 				if (must_trunc) {
6402 					vattr.va_mask = AT_SIZE;
6403 					error = nfs4setattr(vp, &vattr, 0, cr,
6404 						NULL);
6405 				} else {
6406 				/*
6407 				 * we know we have a regular file that already
6408 				 * exists and we may end up truncating the file
6409 				 * as a result of the open_otw, so flush out
6410 				 * any dirty pages for this file first.
6411 				 */
6412 					if (nfs4_has_pages(vp) &&
6413 					    ((rp->r_flags & R4DIRTY) ||
6414 					    rp->r_count > 0 ||
6415 					    rp->r_mapcnt > 0)) {
6416 						error = nfs4_putpage(vp,
6417 							(offset_t)0, 0, 0, cr);
6418 						if (error && (error == ENOSPC ||
6419 						    error == EDQUOT)) {
6420 							mutex_enter(
6421 							    &rp->r_statelock);
6422 							if (!rp->r_error)
6423 								rp->r_error =
6424 								    error;
6425 							mutex_exit(
6426 							    &rp->r_statelock);
6427 						}
6428 					}
6429 					vattr.va_mask = (AT_SIZE |
6430 							AT_TYPE | AT_MODE);
6431 					vattr.va_type = VREG;
6432 					createmode = UNCHECKED4;
6433 					goto create_otw;
6434 				}
6435 			}
6436 		}
6437 	}
6438 	nfs_rw_exit(&drp->r_rwlock);
6439 	if (error) {
6440 		VN_RELE(vp);
6441 	} else {
6442 		*vpp = vp;
6443 	}
6444 	return (error);
6445 
6446 create_otw:
6447 	dnlc_remove(dvp, nm);
6448 
6449 	ASSERT(vattr.va_mask & AT_TYPE);
6450 
6451 	/*
6452 	 * If not a regular file let nfs4mknod() handle it.
6453 	 */
6454 	if (vattr.va_type != VREG) {
6455 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6456 		nfs_rw_exit(&drp->r_rwlock);
6457 		return (error);
6458 	}
6459 
6460 	/*
6461 	 * It _is_ a regular file.
6462 	 */
6463 	ASSERT(vattr.va_mask & AT_MODE);
6464 	if (MANDMODE(vattr.va_mode)) {
6465 		nfs_rw_exit(&drp->r_rwlock);
6466 		return (EACCES);
6467 	}
6468 
6469 	/*
6470 	 * If this happens to be a mknod of a regular file, then flags will
6471 	 * have neither FREAD or FWRITE.  However, we must set at least one
6472 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6473 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6474 	 * set (based on openmode specified by app).
6475 	 */
6476 	if ((flags & (FREAD|FWRITE)) == 0)
6477 		flags |= (FREAD|FWRITE);
6478 
6479 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6480 
6481 	if (vp != NULL) {
6482 		/* if create was successful, throw away the file's pages */
6483 		if (!error && (vattr.va_mask & AT_SIZE))
6484 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6485 				cr);
6486 		/* release the lookup hold */
6487 		VN_RELE(vp);
6488 		vp = NULL;
6489 	}
6490 
6491 	/*
6492 	 * validate that we opened a regular file. This handles a misbehaving
6493 	 * server that returns an incorrect FH.
6494 	 */
6495 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6496 		error = EISDIR;
6497 		VN_RELE(*vpp);
6498 	}
6499 
6500 	/*
6501 	 * If this is not an exclusive create, then the CREATE
6502 	 * request will be made with the GUARDED mode set.  This
6503 	 * means that the server will return EEXIST if the file
6504 	 * exists.  The file could exist because of a retransmitted
6505 	 * request.  In this case, we recover by starting over and
6506 	 * checking to see whether the file exists.  This second
6507 	 * time through it should and a CREATE request will not be
6508 	 * sent.
6509 	 *
6510 	 * This handles the problem of a dangling CREATE request
6511 	 * which contains attributes which indicate that the file
6512 	 * should be truncated.  This retransmitted request could
6513 	 * possibly truncate valid data in the file if not caught
6514 	 * by the duplicate request mechanism on the server or if
6515 	 * not caught by other means.  The scenario is:
6516 	 *
6517 	 * Client transmits CREATE request with size = 0
6518 	 * Client times out, retransmits request.
6519 	 * Response to the first request arrives from the server
6520 	 *  and the client proceeds on.
6521 	 * Client writes data to the file.
6522 	 * The server now processes retransmitted CREATE request
6523 	 *  and truncates file.
6524 	 *
6525 	 * The use of the GUARDED CREATE request prevents this from
6526 	 * happening because the retransmitted CREATE would fail
6527 	 * with EEXIST and would not truncate the file.
6528 	 */
6529 	if (error == EEXIST && exclusive == NONEXCL) {
6530 #ifdef DEBUG
6531 		nfs4_create_misses++;
6532 #endif
6533 		goto top;
6534 	}
6535 	nfs_rw_exit(&drp->r_rwlock);
6536 	return (error);
6537 }
6538 
6539 /*
6540  * Create compound (for mkdir, mknod, symlink):
6541  * { Putfh <dfh>; Create; Getfh; Getattr }
6542  * It's okay if setattr failed to set gid - this is not considered
6543  * an error, but purge attrs in that case.
6544  */
6545 static int
6546 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6547 	vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6548 {
6549 	int need_end_op = FALSE;
6550 	COMPOUND4args_clnt args;
6551 	COMPOUND4res_clnt res, *resp = NULL;
6552 	nfs_argop4 *argop;
6553 	nfs_resop4 *resop;
6554 	int doqueue;
6555 	mntinfo4_t *mi;
6556 	rnode4_t *drp = VTOR4(dvp);
6557 	change_info4 *cinfo;
6558 	GETFH4res *gf_res;
6559 	struct vattr vattr;
6560 	vnode_t *vp;
6561 	fattr4 *crattr;
6562 	bool_t needrecov = FALSE;
6563 	nfs4_recov_state_t recov_state;
6564 	nfs4_sharedfh_t *sfhp = NULL;
6565 	hrtime_t t;
6566 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6567 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6568 	dirattr_info_t dinfo, *dinfop;
6569 	servinfo4_t *svp;
6570 	bitmap4 supp_attrs;
6571 
6572 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6573 		type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6574 
6575 	mi = VTOMI4(dvp);
6576 
6577 	/*
6578 	 * Make sure we properly deal with setting the right gid
6579 	 * on a new directory to reflect the parent's setgid bit
6580 	 */
6581 	setgid_flag = 0;
6582 	if (type == NF4DIR) {
6583 		struct vattr dva;
6584 
6585 		va->va_mode &= ~VSGID;
6586 		dva.va_mask = AT_MODE | AT_GID;
6587 		if (VOP_GETATTR(dvp, &dva, 0, cr) == 0) {
6588 
6589 			/*
6590 			 * If the parent's directory has the setgid bit set
6591 			 * _and_ the client was able to get a valid mapping
6592 			 * for the parent dir's owner_group, we want to
6593 			 * append NVERIFY(owner_group == dva.va_gid) and
6594 			 * SETTATTR to the CREATE compound.
6595 			 */
6596 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6597 				setgid_flag = 1;
6598 				va->va_mode |= VSGID;
6599 				if (dva.va_gid != GID_NOBODY) {
6600 					va->va_mask |= AT_GID;
6601 					va->va_gid = dva.va_gid;
6602 				}
6603 			}
6604 		}
6605 	}
6606 
6607 	/*
6608 	 * Create ops:
6609 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6610 	 *	5:restorefh(dir) 6:getattr(dir)
6611 	 *
6612 	 * if (setgid)
6613 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6614 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6615 	 *	8:nverify 9:setattr
6616 	 */
6617 	if (setgid_flag) {
6618 		numops = 10;
6619 		idx_create = 1;
6620 		idx_fattr = 3;
6621 	} else {
6622 		numops = 7;
6623 		idx_create = 2;
6624 		idx_fattr = 4;
6625 	}
6626 
6627 	ASSERT(curproc->p_zone == mi->mi_zone);
6628 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6629 		return (EINTR);
6630 	}
6631 	recov_state.rs_flags = 0;
6632 	recov_state.rs_num_retry_despite_err = 0;
6633 
6634 	argoplist_size = numops * sizeof (nfs_argop4);
6635 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6636 
6637 recov_retry:
6638 	if (type == NF4LNK)
6639 		args.ctag = TAG_SYMLINK;
6640 	else if (type == NF4DIR)
6641 		args.ctag = TAG_MKDIR;
6642 	else
6643 		args.ctag = TAG_MKNOD;
6644 
6645 	args.array_len = numops;
6646 	args.array = argop;
6647 
6648 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6649 		nfs_rw_exit(&drp->r_rwlock);
6650 		kmem_free(argop, argoplist_size);
6651 		return (e.error);
6652 	}
6653 	need_end_op = TRUE;
6654 
6655 
6656 	/* 0: putfh directory */
6657 	argop[0].argop = OP_CPUTFH;
6658 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6659 
6660 	/* 1/2: Create object */
6661 	argop[idx_create].argop = OP_CCREATE;
6662 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6663 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6664 	if (type == NF4LNK) {
6665 		/*
6666 		 * symlink, treat name as data
6667 		 */
6668 		ASSERT(data != NULL);
6669 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6670 							(char *)data;
6671 	}
6672 	if (type == NF4BLK || type == NF4CHR) {
6673 		ASSERT(data != NULL);
6674 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6675 							*((specdata4 *)data);
6676 	}
6677 
6678 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6679 
6680 	svp = drp->r_server;
6681 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6682 	supp_attrs = svp->sv_supp_attrs;
6683 	nfs_rw_exit(&svp->sv_lock);
6684 
6685 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6686 		nfs_rw_exit(&drp->r_rwlock);
6687 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6688 		e.error = EINVAL;
6689 		kmem_free(argop, argoplist_size);
6690 		return (e.error);
6691 	}
6692 
6693 	/* 2/3: getfh fh of created object */
6694 	ASSERT(idx_create + 1 == idx_fattr - 1);
6695 	argop[idx_create + 1].argop = OP_GETFH;
6696 
6697 	/* 3/4: getattr of new object */
6698 	argop[idx_fattr].argop = OP_GETATTR;
6699 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6700 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6701 
6702 	if (setgid_flag) {
6703 		vattr_t	_v;
6704 
6705 		argop[4].argop = OP_SAVEFH;
6706 
6707 		argop[5].argop = OP_CPUTFH;
6708 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6709 
6710 		argop[6].argop = OP_GETATTR;
6711 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6712 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6713 
6714 		argop[7].argop = OP_RESTOREFH;
6715 
6716 		/*
6717 		 * nverify
6718 		 *
6719 		 * XXX - Revisit the last argument to nfs4_end_op()
6720 		 *	 once 5020486 is fixed.
6721 		 */
6722 		_v.va_mask = AT_GID;
6723 		_v.va_gid = va->va_gid;
6724 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6725 		    supp_attrs)) {
6726 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6727 			nfs_rw_exit(&drp->r_rwlock);
6728 			nfs4_fattr4_free(crattr);
6729 			kmem_free(argop, argoplist_size);
6730 			return (e.error);
6731 		}
6732 
6733 		/*
6734 		 * setattr
6735 		 *
6736 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
6737 		 * so no need for stateid or flags. Also we specify NULL
6738 		 * rp since we're only interested in setting owner_group
6739 		 * attributes.
6740 		 */
6741 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
6742 		    &e.error, 0);
6743 
6744 		if (e.error) {
6745 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6746 			nfs_rw_exit(&drp->r_rwlock);
6747 			nfs4_fattr4_free(crattr);
6748 			nfs4args_verify_free(&argop[8]);
6749 			kmem_free(argop, argoplist_size);
6750 			return (e.error);
6751 		}
6752 	} else {
6753 		argop[1].argop = OP_SAVEFH;
6754 
6755 		argop[5].argop = OP_RESTOREFH;
6756 
6757 		argop[6].argop = OP_GETATTR;
6758 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6759 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6760 	}
6761 
6762 	dnlc_remove(dvp, nm);
6763 
6764 	doqueue = 1;
6765 	t = gethrtime();
6766 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
6767 
6768 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
6769 	if (e.error) {
6770 		PURGE_ATTRCACHE4(dvp);
6771 		if (!needrecov)
6772 			goto out;
6773 	}
6774 
6775 	if (needrecov) {
6776 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
6777 		    OP_CREATE, NULL) == FALSE) {
6778 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6779 				    needrecov);
6780 			need_end_op = FALSE;
6781 			nfs4_fattr4_free(crattr);
6782 			if (setgid_flag) {
6783 				nfs4args_verify_free(&argop[8]);
6784 				nfs4args_setattr_free(&argop[9]);
6785 			}
6786 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6787 			goto recov_retry;
6788 		}
6789 	}
6790 
6791 	resp = &res;
6792 
6793 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
6794 
6795 		if (res.status == NFS4ERR_BADOWNER)
6796 			nfs4_log_badowner(mi, OP_CREATE);
6797 
6798 		e.error = geterrno4(res.status);
6799 
6800 		/*
6801 		 * This check is left over from when create was implemented
6802 		 * using a setattr op (instead of createattrs).  If the
6803 		 * putfh/create/getfh failed, the error was returned.  If
6804 		 * setattr/getattr failed, we keep going.
6805 		 *
6806 		 * It might be better to get rid of the GETFH also, and just
6807 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
6808 		 * Then if any of the operations failed, we could return the
6809 		 * error now, and remove much of the error code below.
6810 		 */
6811 		if (res.array_len <= idx_fattr) {
6812 			/*
6813 			 * Either Putfh, Create or Getfh failed.
6814 			 */
6815 			PURGE_ATTRCACHE4(dvp);
6816 			/*
6817 			 * nfs4_purge_stale_fh() may generate otw calls through
6818 			 * nfs4_invalidate_pages. Hence the need to call
6819 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
6820 			 */
6821 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6822 			    needrecov);
6823 			need_end_op = FALSE;
6824 			nfs4_purge_stale_fh(e.error, dvp, cr);
6825 			goto out;
6826 		}
6827 	}
6828 
6829 	resop = &res.array[idx_create];	/* create res */
6830 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
6831 
6832 	resop = &res.array[idx_create + 1]; /* getfh res */
6833 	gf_res = &resop->nfs_resop4_u.opgetfh;
6834 
6835 	sfhp = sfh4_get(&gf_res->object, mi);
6836 	if (e.error) {
6837 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
6838 		    fn_get(VTOSV(dvp)->sv_name, nm));
6839 		if (vp->v_type == VNON) {
6840 			vattr.va_mask = AT_TYPE;
6841 			/*
6842 			 * Need to call nfs4_end_op before nfs4getattr to avoid
6843 			 * potential nfs4_start_op deadlock. See RFE 4777612.
6844 			 */
6845 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6846 				needrecov);
6847 			need_end_op = FALSE;
6848 			e.error = nfs4getattr(vp, &vattr, cr);
6849 			if (e.error) {
6850 				VN_RELE(vp);
6851 				*vpp = NULL;
6852 				goto out;
6853 			}
6854 			vp->v_type = vattr.va_type;
6855 		}
6856 		e.error = 0;
6857 	} else {
6858 		*vpp = vp = makenfs4node(sfhp,
6859 			&res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
6860 			dvp->v_vfsp, t, cr,
6861 			dvp, fn_get(VTOSV(dvp)->sv_name, nm));
6862 	}
6863 
6864 	/*
6865 	 * If compound succeeded, then update dir attrs
6866 	 */
6867 	if (res.status == NFS4_OK) {
6868 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
6869 		dinfo.di_cred = cr;
6870 		dinfo.di_time_call = t;
6871 		dinfop = &dinfo;
6872 	} else
6873 		dinfop = NULL;
6874 
6875 	/* Update directory cache attribute, readdir and dnlc caches */
6876 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
6877 
6878 out:
6879 	if (sfhp != NULL)
6880 		sfh4_rele(&sfhp);
6881 	nfs_rw_exit(&drp->r_rwlock);
6882 	nfs4_fattr4_free(crattr);
6883 	if (setgid_flag) {
6884 		nfs4args_verify_free(&argop[8]);
6885 		nfs4args_setattr_free(&argop[9]);
6886 	}
6887 	if (resp)
6888 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
6889 	if (need_end_op)
6890 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6891 
6892 	kmem_free(argop, argoplist_size);
6893 	return (e.error);
6894 }
6895 
6896 /* ARGSUSED */
6897 static int
6898 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6899 	int mode, vnode_t **vpp, cred_t *cr)
6900 {
6901 	int error;
6902 	vnode_t *vp;
6903 	nfs_ftype4 type;
6904 	specdata4 spec, *specp = NULL;
6905 
6906 	ASSERT(curproc->p_zone == VTOMI4(dvp)->mi_zone);
6907 
6908 	switch (va->va_type) {
6909 	case VCHR:
6910 	case VBLK:
6911 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
6912 		spec.specdata1 = getmajor(va->va_rdev);
6913 		spec.specdata2 = getminor(va->va_rdev);
6914 		specp = &spec;
6915 		break;
6916 
6917 	case VFIFO:
6918 		type = NF4FIFO;
6919 		break;
6920 	case VSOCK:
6921 		type = NF4SOCK;
6922 		break;
6923 
6924 	default:
6925 		return (EINVAL);
6926 	}
6927 
6928 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
6929 	if (error) {
6930 		return (error);
6931 	}
6932 
6933 	/*
6934 	 * This might not be needed any more; special case to deal
6935 	 * with problematic v2/v3 servers.  Since create was unable
6936 	 * to set group correctly, not sure what hope setattr has.
6937 	 */
6938 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
6939 		va->va_mask = AT_GID;
6940 		(void) nfs4setattr(vp, va, 0, cr, NULL);
6941 	}
6942 
6943 	/*
6944 	 * If vnode is a device create special vnode
6945 	 */
6946 	if (ISVDEV(vp->v_type)) {
6947 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6948 		VN_RELE(vp);
6949 	} else {
6950 		*vpp = vp;
6951 	}
6952 	return (error);
6953 }
6954 
6955 /*
6956  * Remove requires that the current fh be the target directory.
6957  * After the operation, the current fh is unchanged.
6958  * The compound op structure is:
6959  *      PUTFH(targetdir), REMOVE
6960  *
6961  * Weirdness: if the vnode to be removed is open
6962  * we rename it instead of removing it and nfs_inactive
6963  * will remove the new name.
6964  */
6965 static int
6966 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr)
6967 {
6968 	COMPOUND4args_clnt args;
6969 	COMPOUND4res_clnt res, *resp = NULL;
6970 	REMOVE4res *rm_res;
6971 	nfs_argop4 argop[3];
6972 	nfs_resop4 *resop;
6973 	vnode_t *vp;
6974 	char *tmpname;
6975 	int doqueue;
6976 	mntinfo4_t *mi;
6977 	rnode4_t *rp;
6978 	rnode4_t *drp;
6979 	int needrecov = 0;
6980 	nfs4_recov_state_t recov_state;
6981 	int isopen;
6982 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6983 	dirattr_info_t dinfo;
6984 
6985 	if (curproc->p_zone != VTOMI4(dvp)->mi_zone)
6986 		return (EPERM);
6987 	drp = VTOR4(dvp);
6988 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6989 		return (EINTR);
6990 
6991 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
6992 	if (e.error) {
6993 		nfs_rw_exit(&drp->r_rwlock);
6994 		return (e.error);
6995 	}
6996 
6997 	if (vp->v_type == VDIR) {
6998 		VN_RELE(vp);
6999 		nfs_rw_exit(&drp->r_rwlock);
7000 		return (EISDIR);
7001 	}
7002 
7003 	/*
7004 	 * First just remove the entry from the name cache, as it
7005 	 * is most likely the only entry for this vp.
7006 	 */
7007 	dnlc_remove(dvp, nm);
7008 
7009 	rp = VTOR4(vp);
7010 
7011 	/*
7012 	 * For regular file types, check to see if the file is open by looking
7013 	 * at the open streams.
7014 	 * For all other types, check the reference count on the vnode.  Since
7015 	 * they are not opened OTW they never have an open stream.
7016 	 *
7017 	 * If the file is open, rename it to .nfsXXXX.
7018 	 */
7019 	if (vp->v_type != VREG) {
7020 		/*
7021 		 * If the file has a v_count > 1 then there may be more than one
7022 		 * entry in the name cache due multiple links or an open file,
7023 		 * but we don't have the real reference count so flush all
7024 		 * possible entries.
7025 		 */
7026 		if (vp->v_count > 1)
7027 			dnlc_purge_vp(vp);
7028 
7029 		/*
7030 		 * Now we have the real reference count.
7031 		 */
7032 		isopen = vp->v_count > 1;
7033 	} else {
7034 		mutex_enter(&rp->r_os_lock);
7035 		isopen = list_head(&rp->r_open_streams) != NULL;
7036 		mutex_exit(&rp->r_os_lock);
7037 	}
7038 
7039 	mutex_enter(&rp->r_statelock);
7040 	if (isopen &&
7041 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7042 		mutex_exit(&rp->r_statelock);
7043 		tmpname = newname();
7044 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr);
7045 		if (e.error)
7046 			kmem_free(tmpname, MAXNAMELEN);
7047 		else {
7048 			mutex_enter(&rp->r_statelock);
7049 			if (rp->r_unldvp == NULL) {
7050 				VN_HOLD(dvp);
7051 				rp->r_unldvp = dvp;
7052 				if (rp->r_unlcred != NULL)
7053 					crfree(rp->r_unlcred);
7054 				crhold(cr);
7055 				rp->r_unlcred = cr;
7056 				rp->r_unlname = tmpname;
7057 			} else {
7058 				kmem_free(rp->r_unlname, MAXNAMELEN);
7059 				rp->r_unlname = tmpname;
7060 			}
7061 			mutex_exit(&rp->r_statelock);
7062 		}
7063 		VN_RELE(vp);
7064 		nfs_rw_exit(&drp->r_rwlock);
7065 		return (e.error);
7066 	}
7067 	/*
7068 	 * Actually remove the file/dir
7069 	 */
7070 	mutex_exit(&rp->r_statelock);
7071 
7072 	/*
7073 	 * We need to flush any dirty pages which happen to
7074 	 * be hanging around before removing the file.
7075 	 * This shouldn't happen very often since in NFSv4
7076 	 * we should be close to open consistent.
7077 	 */
7078 	if (nfs4_has_pages(vp) &&
7079 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7080 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr);
7081 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7082 			mutex_enter(&rp->r_statelock);
7083 			if (!rp->r_error)
7084 				rp->r_error = e.error;
7085 			mutex_exit(&rp->r_statelock);
7086 		}
7087 	}
7088 
7089 	mi = VTOMI4(dvp);
7090 
7091 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7092 	recov_state.rs_flags = 0;
7093 	recov_state.rs_num_retry_despite_err = 0;
7094 
7095 recov_retry:
7096 	/*
7097 	 * Remove ops: putfh dir; remove
7098 	 */
7099 	args.ctag = TAG_REMOVE;
7100 	args.array_len = 3;
7101 	args.array = argop;
7102 
7103 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7104 	if (e.error) {
7105 		nfs_rw_exit(&drp->r_rwlock);
7106 		VN_RELE(vp);
7107 		return (e.error);
7108 	}
7109 
7110 	/* putfh directory */
7111 	argop[0].argop = OP_CPUTFH;
7112 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7113 
7114 	/* remove */
7115 	argop[1].argop = OP_CREMOVE;
7116 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7117 
7118 	/* getattr dir */
7119 	argop[2].argop = OP_GETATTR;
7120 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7121 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7122 
7123 	doqueue = 1;
7124 	dinfo.di_time_call = gethrtime();
7125 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7126 
7127 	PURGE_ATTRCACHE4(vp);
7128 
7129 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7130 	if (e.error)
7131 		PURGE_ATTRCACHE4(dvp);
7132 
7133 	if (needrecov) {
7134 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7135 		    NULL, NULL, NULL, OP_REMOVE, NULL) == FALSE) {
7136 			if (!e.error)
7137 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7138 								(caddr_t)&res);
7139 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7140 					needrecov);
7141 			goto recov_retry;
7142 		}
7143 	}
7144 
7145 	/*
7146 	 * Matching nfs4_end_op() for start_op() above.
7147 	 * There is a path in the code below which calls
7148 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7149 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7150 	 * here to avoid nfs4_start_op() deadlock.
7151 	 */
7152 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7153 
7154 	if (!e.error) {
7155 		resp = &res;
7156 
7157 		if (res.status) {
7158 			e.error = geterrno4(res.status);
7159 			PURGE_ATTRCACHE4(dvp);
7160 			nfs4_purge_stale_fh(e.error, dvp, cr);
7161 		} else {
7162 			resop = &res.array[1];	/* remove res */
7163 			rm_res = &resop->nfs_resop4_u.opremove;
7164 
7165 			dinfo.di_garp =
7166 				&res.array[2].nfs_resop4_u.opgetattr.ga_res;
7167 			dinfo.di_cred = cr;
7168 
7169 			/* Update directory attr, readdir and dnlc caches */
7170 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7171 				&dinfo);
7172 		}
7173 	}
7174 	nfs_rw_exit(&drp->r_rwlock);
7175 	if (resp)
7176 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7177 
7178 	VN_RELE(vp);
7179 	return (e.error);
7180 }
7181 
7182 /*
7183  * Link requires that the current fh be the target directory and the
7184  * saved fh be the source fh. After the operation, the current fh is unchanged.
7185  * Thus the compound op structure is:
7186  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7187  *	GETATTR(file)
7188  */
7189 static int
7190 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr)
7191 {
7192 	COMPOUND4args_clnt args;
7193 	COMPOUND4res_clnt res, *resp = NULL;
7194 	LINK4res *ln_res;
7195 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7196 	nfs_argop4 *argop;
7197 	nfs_resop4 *resop;
7198 	vnode_t *realvp, *nvp;
7199 	int doqueue;
7200 	mntinfo4_t *mi;
7201 	rnode4_t *tdrp;
7202 	bool_t needrecov = FALSE;
7203 	nfs4_recov_state_t recov_state;
7204 	hrtime_t t;
7205 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7206 	dirattr_info_t dinfo;
7207 
7208 	ASSERT(*tnm != '\0');
7209 	ASSERT(tdvp->v_type == VDIR);
7210 	ASSERT(nfs4_consistent_type(tdvp));
7211 	ASSERT(nfs4_consistent_type(svp));
7212 
7213 	if (curproc->p_zone != VTOMI4(tdvp)->mi_zone)
7214 		return (EPERM);
7215 	if (VOP_REALVP(svp, &realvp) == 0) {
7216 		svp = realvp;
7217 		ASSERT(nfs4_consistent_type(svp));
7218 	}
7219 
7220 	tdrp = VTOR4(tdvp);
7221 	mi = VTOMI4(svp);
7222 
7223 	if (!(mi->mi_flags & MI4_LINK)) {
7224 		return (EOPNOTSUPP);
7225 	}
7226 	recov_state.rs_flags = 0;
7227 	recov_state.rs_num_retry_despite_err = 0;
7228 
7229 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7230 		return (EINTR);
7231 
7232 recov_retry:
7233 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7234 
7235 	args.ctag = TAG_LINK;
7236 
7237 	/*
7238 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7239 	 * restorefh; getattr(fl)
7240 	 */
7241 	args.array_len = 7;
7242 	args.array = argop;
7243 
7244 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7245 	if (e.error) {
7246 		kmem_free(argop, argoplist_size);
7247 		nfs_rw_exit(&tdrp->r_rwlock);
7248 		return (e.error);
7249 	}
7250 
7251 	/* 0. putfh file */
7252 	argop[0].argop = OP_CPUTFH;
7253 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7254 
7255 	/* 1. save current fh to free up the space for the dir */
7256 	argop[1].argop = OP_SAVEFH;
7257 
7258 	/* 2. putfh targetdir */
7259 	argop[2].argop = OP_CPUTFH;
7260 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7261 
7262 	/* 3. link: current_fh is targetdir, saved_fh is source */
7263 	argop[3].argop = OP_CLINK;
7264 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7265 
7266 	/* 4. Get attributes of dir */
7267 	argop[4].argop = OP_GETATTR;
7268 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7269 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7270 
7271 	/* 5. If link was successful, restore current vp to file */
7272 	argop[5].argop = OP_RESTOREFH;
7273 
7274 	/* 6. Get attributes of linked object */
7275 	argop[6].argop = OP_GETATTR;
7276 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7277 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7278 
7279 	dnlc_remove(tdvp, tnm);
7280 
7281 	doqueue = 1;
7282 	t = gethrtime();
7283 
7284 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7285 
7286 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7287 	if (e.error != 0 && !needrecov) {
7288 		PURGE_ATTRCACHE4(tdvp);
7289 		PURGE_ATTRCACHE4(svp);
7290 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7291 		goto out;
7292 	}
7293 
7294 	if (needrecov) {
7295 		bool_t abort;
7296 
7297 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7298 			    NULL, NULL, OP_LINK, NULL);
7299 		if (abort == FALSE) {
7300 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7301 				    needrecov);
7302 			kmem_free(argop, argoplist_size);
7303 			if (!e.error)
7304 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7305 								(caddr_t)&res);
7306 			goto recov_retry;
7307 		} else {
7308 			if (e.error != 0) {
7309 				PURGE_ATTRCACHE4(tdvp);
7310 				PURGE_ATTRCACHE4(svp);
7311 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7312 					    &recov_state, needrecov);
7313 				goto out;
7314 			}
7315 			/* fall through for res.status case */
7316 		}
7317 	}
7318 
7319 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7320 
7321 	resp = &res;
7322 	if (res.status) {
7323 		/* If link succeeded, then don't return error */
7324 		e.error = geterrno4(res.status);
7325 		if (res.array_len <= 4) {
7326 			/*
7327 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7328 			 */
7329 			PURGE_ATTRCACHE4(svp);
7330 			PURGE_ATTRCACHE4(tdvp);
7331 			if (e.error == EOPNOTSUPP) {
7332 				mutex_enter(&mi->mi_lock);
7333 				mi->mi_flags &= ~MI4_LINK;
7334 				mutex_exit(&mi->mi_lock);
7335 			}
7336 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7337 			/* XXX-LP */
7338 			if (e.error == EISDIR && crgetuid(cr) != 0)
7339 				e.error = EPERM;
7340 			goto out;
7341 		}
7342 	}
7343 
7344 	/* either no error or one of the postop getattr failed */
7345 
7346 	/*
7347 	 * XXX - if LINK succeeded, but no attrs were returned for link
7348 	 * file, purge its cache.
7349 	 *
7350 	 * XXX Perform a simplified version of wcc checking. Instead of
7351 	 * have another getattr to get pre-op, just purge cache if
7352 	 * any of the ops prior to and including the getattr failed.
7353 	 * If the getattr succeeded then update the attrcache accordingly.
7354 	 */
7355 
7356 	/*
7357 	 * update cache with link file postattrs.
7358 	 * Note: at this point resop points to link res.
7359 	 */
7360 	resop = &res.array[3];	/* link res */
7361 	ln_res = &resop->nfs_resop4_u.oplink;
7362 	if (res.status == NFS4_OK) {
7363 		e.error = nfs4_update_attrcache(res.status,
7364 				&res.array[6].nfs_resop4_u.opgetattr.ga_res,
7365 				t, svp, cr);
7366 	}
7367 
7368 	/*
7369 	 * Call makenfs4node to create the new shadow vp for tnm.
7370 	 * We pass NULL attrs because we just cached attrs for
7371 	 * the src object.  All we're trying to accomplish is to
7372 	 * to create the new shadow vnode.
7373 	 */
7374 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7375 			tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm));
7376 
7377 	/* Update target cache attribute, readdir and dnlc caches */
7378 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7379 	dinfo.di_time_call = t;
7380 	dinfo.di_cred = cr;
7381 
7382 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7383 	ASSERT(nfs4_consistent_type(tdvp));
7384 	ASSERT(nfs4_consistent_type(svp));
7385 	ASSERT(nfs4_consistent_type(nvp));
7386 	VN_RELE(nvp);
7387 
7388 out:
7389 	kmem_free(argop, argoplist_size);
7390 	if (resp)
7391 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7392 
7393 	nfs_rw_exit(&tdrp->r_rwlock);
7394 
7395 	return (e.error);
7396 }
7397 
7398 static int
7399 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr)
7400 {
7401 	vnode_t *realvp;
7402 
7403 	if (curproc->p_zone != VTOMI4(odvp)->mi_zone)
7404 		return (EPERM);
7405 	if (VOP_REALVP(ndvp, &realvp) == 0)
7406 		ndvp = realvp;
7407 
7408 	return (nfs4rename(odvp, onm, ndvp, nnm, cr));
7409 }
7410 
7411 /*
7412  * nfs4rename does the real work of renaming in NFS Version 4.
7413  *
7414  * A file handle is considered volatile for renaming purposes if either
7415  * of the volatile bits are turned on. However, the compound may differ
7416  * based on the likelihood of the filehandle to change during rename.
7417  */
7418 static int
7419 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr)
7420 {
7421 	int error;
7422 	mntinfo4_t *mi;
7423 	vnode_t *nvp;
7424 	vnode_t *ovp = NULL;
7425 	char *tmpname = NULL;
7426 	rnode4_t *rp;
7427 	rnode4_t *odrp;
7428 	rnode4_t *ndrp;
7429 	int did_link = 0;
7430 	int do_link = 1;
7431 	nfsstat4 stat = NFS4_OK;
7432 
7433 	ASSERT(curproc->p_zone == VTOMI4(odvp)->mi_zone);
7434 	ASSERT(nfs4_consistent_type(odvp));
7435 	ASSERT(nfs4_consistent_type(ndvp));
7436 
7437 	if (onm[0] == '.' && (onm[1] == '\0' ||
7438 			(onm[1] == '.' && onm[2] == '\0')))
7439 		return (EINVAL);
7440 
7441 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7442 			(nnm[1] == '.' && nnm[2] == '\0')))
7443 		return (EINVAL);
7444 
7445 	odrp = VTOR4(odvp);
7446 	ndrp = VTOR4(ndvp);
7447 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7448 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7449 			return (EINTR);
7450 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7451 			nfs_rw_exit(&odrp->r_rwlock);
7452 			return (EINTR);
7453 		}
7454 	} else {
7455 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7456 			return (EINTR);
7457 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7458 			nfs_rw_exit(&ndrp->r_rwlock);
7459 			return (EINTR);
7460 		}
7461 	}
7462 
7463 	/*
7464 	 * Lookup the target file.  If it exists, it needs to be
7465 	 * checked to see whether it is a mount point and whether
7466 	 * it is active (open).
7467 	 */
7468 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7469 	if (!error) {
7470 		int	isactive;
7471 
7472 		ASSERT(nfs4_consistent_type(nvp));
7473 		/*
7474 		 * If this file has been mounted on, then just
7475 		 * return busy because renaming to it would remove
7476 		 * the mounted file system from the name space.
7477 		 */
7478 		if (vn_ismntpt(nvp)) {
7479 			VN_RELE(nvp);
7480 			nfs_rw_exit(&odrp->r_rwlock);
7481 			nfs_rw_exit(&ndrp->r_rwlock);
7482 			return (EBUSY);
7483 		}
7484 
7485 		/*
7486 		 * First just remove the entry from the name cache, as it
7487 		 * is most likely the only entry for this vp.
7488 		 */
7489 		dnlc_remove(ndvp, nnm);
7490 
7491 		rp = VTOR4(nvp);
7492 
7493 		if (nvp->v_type != VREG) {
7494 			/*
7495 			 * Purge the name cache of all references to this vnode
7496 			 * so that we can check the reference count to infer
7497 			 * whether it is active or not.
7498 			 */
7499 			if (nvp->v_count > 1)
7500 				dnlc_purge_vp(nvp);
7501 
7502 			isactive = nvp->v_count > 1;
7503 		} else {
7504 			mutex_enter(&rp->r_os_lock);
7505 			isactive = list_head(&rp->r_open_streams) != NULL;
7506 			mutex_exit(&rp->r_os_lock);
7507 		}
7508 
7509 		/*
7510 		 * If the vnode is active and is not a directory,
7511 		 * arrange to rename it to a
7512 		 * temporary file so that it will continue to be
7513 		 * accessible.  This implements the "unlink-open-file"
7514 		 * semantics for the target of a rename operation.
7515 		 * Before doing this though, make sure that the
7516 		 * source and target files are not already the same.
7517 		 */
7518 		if (isactive && nvp->v_type != VDIR) {
7519 			/*
7520 			 * Lookup the source name.
7521 			 */
7522 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7523 
7524 			/*
7525 			 * The source name *should* already exist.
7526 			 */
7527 			if (error) {
7528 				VN_RELE(nvp);
7529 				nfs_rw_exit(&odrp->r_rwlock);
7530 				nfs_rw_exit(&ndrp->r_rwlock);
7531 				return (error);
7532 			}
7533 
7534 			ASSERT(nfs4_consistent_type(ovp));
7535 
7536 			/*
7537 			 * Compare the two vnodes.  If they are the same,
7538 			 * just release all held vnodes and return success.
7539 			 */
7540 			if (VN_CMP(ovp, nvp)) {
7541 				VN_RELE(ovp);
7542 				VN_RELE(nvp);
7543 				nfs_rw_exit(&odrp->r_rwlock);
7544 				nfs_rw_exit(&ndrp->r_rwlock);
7545 				return (0);
7546 			}
7547 
7548 			/*
7549 			 * Can't mix and match directories and non-
7550 			 * directories in rename operations.  We already
7551 			 * know that the target is not a directory.  If
7552 			 * the source is a directory, return an error.
7553 			 */
7554 			if (ovp->v_type == VDIR) {
7555 				VN_RELE(ovp);
7556 				VN_RELE(nvp);
7557 				nfs_rw_exit(&odrp->r_rwlock);
7558 				nfs_rw_exit(&ndrp->r_rwlock);
7559 				return (ENOTDIR);
7560 			}
7561 link_call:
7562 			/*
7563 			 * The target file exists, is not the same as
7564 			 * the source file, and is active.  We first
7565 			 * try to Link it to a temporary filename to
7566 			 * avoid having the server removing the file
7567 			 * completely (which could cause data loss to
7568 			 * the user's POV in the event the Rename fails
7569 			 * -- see bug 1165874).
7570 			 */
7571 			/*
7572 			 * The do_link and did_link booleans are
7573 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7574 			 * returned for the Rename.  Some servers can
7575 			 * not Rename over an Open file, so they return
7576 			 * this error.  The client needs to Remove the
7577 			 * newly created Link and do two Renames, just
7578 			 * as if the server didn't support LINK.
7579 			 */
7580 			tmpname = newname();
7581 			error = 0;
7582 
7583 			if (do_link) {
7584 				error = nfs4_link(ndvp, nvp, tmpname, cr);
7585 			}
7586 			if (error == EOPNOTSUPP || !do_link) {
7587 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7588 				    cr);
7589 				did_link = 0;
7590 			} else {
7591 				did_link = 1;
7592 			}
7593 			if (error) {
7594 				kmem_free(tmpname, MAXNAMELEN);
7595 				VN_RELE(ovp);
7596 				VN_RELE(nvp);
7597 				nfs_rw_exit(&odrp->r_rwlock);
7598 				nfs_rw_exit(&ndrp->r_rwlock);
7599 				return (error);
7600 			}
7601 
7602 			mutex_enter(&rp->r_statelock);
7603 			if (rp->r_unldvp == NULL) {
7604 				VN_HOLD(ndvp);
7605 				rp->r_unldvp = ndvp;
7606 				if (rp->r_unlcred != NULL)
7607 					crfree(rp->r_unlcred);
7608 				crhold(cr);
7609 				rp->r_unlcred = cr;
7610 				rp->r_unlname = tmpname;
7611 			} else {
7612 				if (rp->r_unlname)
7613 					kmem_free(rp->r_unlname, MAXNAMELEN);
7614 				rp->r_unlname = tmpname;
7615 			}
7616 			mutex_exit(&rp->r_statelock);
7617 		}
7618 
7619 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7620 
7621 		ASSERT(nfs4_consistent_type(nvp));
7622 		VN_RELE(nvp);
7623 	}
7624 
7625 	if (ovp == NULL) {
7626 		/*
7627 		 * When renaming directories to be a subdirectory of a
7628 		 * different parent, the dnlc entry for ".." will no
7629 		 * longer be valid, so it must be removed.
7630 		 *
7631 		 * We do a lookup here to determine whether we are renaming
7632 		 * a directory and we need to check if we are renaming
7633 		 * an unlinked file.  This might have already been done
7634 		 * in previous code, so we check ovp == NULL to avoid
7635 		 * doing it twice.
7636 		 */
7637 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7638 		/*
7639 		 * The source name *should* already exist.
7640 		 */
7641 		if (error) {
7642 			nfs_rw_exit(&odrp->r_rwlock);
7643 			nfs_rw_exit(&ndrp->r_rwlock);
7644 			return (error);
7645 		}
7646 		ASSERT(ovp != NULL);
7647 		ASSERT(nfs4_consistent_type(ovp));
7648 	}
7649 
7650 	/*
7651 	 * Is the object being renamed a dir, and if so, is
7652 	 * it being renamed to a child of itself?  The underlying
7653 	 * fs should ultimately return EINVAL for this case;
7654 	 * however, buggy beta non-Solaris NFSv4 servers at
7655 	 * interop testing events have allowed this behavior,
7656 	 * and it caused our client to panic due to a recursive
7657 	 * mutex_enter in fn_move.
7658 	 *
7659 	 * The tedious locking in fn_move could be changed to
7660 	 * deal with this case, and the client could avoid the
7661 	 * panic; however, the client would just confuse itself
7662 	 * later and misbehave.  A better way to handle the broken
7663 	 * server is to detect this condition and return EINVAL
7664 	 * without ever sending the the bogus rename to the server.
7665 	 * We know the rename is invalid -- just fail it now.
7666 	 */
7667 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7668 		VN_RELE(ovp);
7669 		nfs_rw_exit(&odrp->r_rwlock);
7670 		nfs_rw_exit(&ndrp->r_rwlock);
7671 		return (EINVAL);
7672 	}
7673 
7674 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7675 
7676 	/*
7677 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7678 	 * possible for the filehandle to change due to the rename.
7679 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7680 	 * the fh will not change because of the rename, but we still need
7681 	 * to update its rnode entry with the new name for
7682 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7683 	 * has no effect on these for now, but for future improvements,
7684 	 * we might want to use it too to simplify handling of files
7685 	 * that are open with that flag on. (XXX)
7686 	 */
7687 	mi = VTOMI4(odvp);
7688 	if (NFS4_VOLATILE_FH(mi)) {
7689 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7690 				&stat);
7691 	} else {
7692 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7693 				&stat);
7694 	}
7695 	ASSERT(nfs4_consistent_type(odvp));
7696 	ASSERT(nfs4_consistent_type(ndvp));
7697 	ASSERT(nfs4_consistent_type(ovp));
7698 
7699 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
7700 		do_link = 0;
7701 		/*
7702 		 * Before the 'link_call' code, we did a nfs4_lookup
7703 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
7704 		 * call we call VN_RELE to match that hold.  We need
7705 		 * to place an additional VN_HOLD here since we will
7706 		 * be hitting that VN_RELE again.
7707 		 */
7708 		VN_HOLD(nvp);
7709 
7710 		(void) nfs4_remove(ndvp, tmpname, cr);
7711 
7712 		/* Undo the unlinked file naming stuff we just did */
7713 		mutex_enter(&rp->r_statelock);
7714 		if (rp->r_unldvp) {
7715 			VN_RELE(ndvp);
7716 			rp->r_unldvp = NULL;
7717 			if (rp->r_unlcred != NULL)
7718 				crfree(rp->r_unlcred);
7719 			rp->r_unlcred = NULL;
7720 			/* rp->r_unlanme points to tmpname */
7721 			if (rp->r_unlname)
7722 				kmem_free(rp->r_unlname, MAXNAMELEN);
7723 			rp->r_unlname = NULL;
7724 		}
7725 		mutex_exit(&rp->r_statelock);
7726 
7727 		goto link_call;
7728 	}
7729 
7730 	if (error) {
7731 		VN_RELE(ovp);
7732 		nfs_rw_exit(&odrp->r_rwlock);
7733 		nfs_rw_exit(&ndrp->r_rwlock);
7734 		return (error);
7735 	}
7736 
7737 	/*
7738 	 * when renaming directories to be a subdirectory of a
7739 	 * different parent, the dnlc entry for ".." will no
7740 	 * longer be valid, so it must be removed
7741 	 */
7742 	rp = VTOR4(ovp);
7743 	if (ndvp != odvp) {
7744 		if (ovp->v_type == VDIR) {
7745 			dnlc_remove(ovp, "..");
7746 			if (rp->r_dir != NULL)
7747 				nfs4_purge_rddir_cache(ovp);
7748 		}
7749 	}
7750 
7751 	/*
7752 	 * If we are renaming the unlinked file, update the
7753 	 * r_unldvp and r_unlname as needed.
7754 	 */
7755 	mutex_enter(&rp->r_statelock);
7756 	if (rp->r_unldvp != NULL) {
7757 		if (strcmp(rp->r_unlname, onm) == 0) {
7758 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
7759 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
7760 			if (ndvp != rp->r_unldvp) {
7761 				VN_RELE(rp->r_unldvp);
7762 				rp->r_unldvp = ndvp;
7763 				VN_HOLD(ndvp);
7764 			}
7765 		}
7766 	}
7767 	mutex_exit(&rp->r_statelock);
7768 
7769 	VN_RELE(ovp);
7770 
7771 	nfs_rw_exit(&odrp->r_rwlock);
7772 	nfs_rw_exit(&ndrp->r_rwlock);
7773 
7774 	return (error);
7775 }
7776 
7777 /*
7778  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
7779  * when it is known that the filehandle is persistent through rename.
7780  *
7781  * Rename requires that the current fh be the target directory and the
7782  * saved fh be the source directory. After the operation, the current fh
7783  * is unchanged.
7784  * The compound op structure for persistent fh rename is:
7785  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
7786  * Rather than bother with the directory postop args, we'll simply
7787  * update that a change occured in the cache, so no post-op getattrs.
7788  */
7789 static int
7790 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
7791 	vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
7792 {
7793 	COMPOUND4args_clnt args;
7794 	COMPOUND4res_clnt res, *resp = NULL;
7795 	nfs_argop4 *argop;
7796 	nfs_resop4 *resop;
7797 	int doqueue, argoplist_size;
7798 	mntinfo4_t *mi;
7799 	rnode4_t *odrp = VTOR4(odvp);
7800 	rnode4_t *ndrp = VTOR4(ndvp);
7801 	RENAME4res *rn_res;
7802 	bool_t needrecov;
7803 	nfs4_recov_state_t recov_state;
7804 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7805 	dirattr_info_t dinfo, *dinfop;
7806 
7807 	ASSERT(curproc->p_zone == VTOMI4(odvp)->mi_zone);
7808 
7809 	recov_state.rs_flags = 0;
7810 	recov_state.rs_num_retry_despite_err = 0;
7811 
7812 	/*
7813 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
7814 	 *
7815 	 * If source/target are different dirs, then append putfh(src); getattr
7816 	 */
7817 	args.array_len = (odvp == ndvp) ? 5 : 7;
7818 	argoplist_size = args.array_len * sizeof (nfs_argop4);
7819 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
7820 
7821 recov_retry:
7822 	*statp = NFS4_OK;
7823 
7824 	/* No need to Lookup the file, persistent fh */
7825 	args.ctag = TAG_RENAME;
7826 
7827 	mi = VTOMI4(odvp);
7828 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
7829 	if (e.error) {
7830 		kmem_free(argop, argoplist_size);
7831 		return (e.error);
7832 	}
7833 
7834 	/* 0: putfh source directory */
7835 	argop[0].argop = OP_CPUTFH;
7836 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
7837 
7838 	/* 1: Save source fh to free up current for target */
7839 	argop[1].argop = OP_SAVEFH;
7840 
7841 	/* 2: putfh targetdir */
7842 	argop[2].argop = OP_CPUTFH;
7843 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
7844 
7845 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
7846 	argop[3].argop = OP_CRENAME;
7847 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
7848 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
7849 
7850 	/* 4: getattr (targetdir) */
7851 	argop[4].argop = OP_GETATTR;
7852 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7853 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7854 
7855 	if (ndvp != odvp) {
7856 
7857 		/* 5: putfh (sourcedir) */
7858 		argop[5].argop = OP_CPUTFH;
7859 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
7860 
7861 		/* 6: getattr (sourcedir) */
7862 		argop[6].argop = OP_GETATTR;
7863 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7864 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
7865 	}
7866 
7867 	dnlc_remove(odvp, onm);
7868 	dnlc_remove(ndvp, nnm);
7869 
7870 	doqueue = 1;
7871 	dinfo.di_time_call = gethrtime();
7872 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7873 
7874 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7875 	if (e.error) {
7876 		PURGE_ATTRCACHE4(odvp);
7877 		PURGE_ATTRCACHE4(ndvp);
7878 	} else {
7879 		*statp = res.status;
7880 	}
7881 
7882 	if (needrecov) {
7883 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
7884 		    OP_RENAME, NULL) == FALSE) {
7885 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
7886 			if (!e.error)
7887 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7888 								(caddr_t)&res);
7889 			goto recov_retry;
7890 		}
7891 	}
7892 
7893 	if (!e.error) {
7894 		resp = &res;
7895 		/*
7896 		 * as long as OP_RENAME
7897 		 */
7898 		if (res.status != NFS4_OK && res.array_len <= 4) {
7899 			e.error = geterrno4(res.status);
7900 			PURGE_ATTRCACHE4(odvp);
7901 			PURGE_ATTRCACHE4(ndvp);
7902 			/*
7903 			 * System V defines rename to return EEXIST, not
7904 			 * ENOTEMPTY if the target directory is not empty.
7905 			 * Over the wire, the error is NFSERR_ENOTEMPTY
7906 			 * which geterrno4 maps to ENOTEMPTY.
7907 			 */
7908 			if (e.error == ENOTEMPTY)
7909 				e.error = EEXIST;
7910 		} else {
7911 
7912 			resop = &res.array[3];	/* rename res */
7913 			rn_res = &resop->nfs_resop4_u.oprename;
7914 
7915 			if (res.status == NFS4_OK) {
7916 				/*
7917 				 * Update target attribute, readdir and dnlc
7918 				 * caches.
7919 				 */
7920 				dinfo.di_garp =
7921 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7922 				dinfo.di_cred = cr;
7923 				dinfop = &dinfo;
7924 			} else
7925 				dinfop = NULL;
7926 
7927 			nfs4_update_dircaches(&rn_res->target_cinfo,
7928 						ndvp, NULL, NULL, dinfop);
7929 
7930 			/*
7931 			 * Update source attribute, readdir and dnlc caches
7932 			 *
7933 			 */
7934 			if (ndvp != odvp) {
7935 				if (dinfop)
7936 					dinfo.di_garp =
7937 					    &(res.array[6].nfs_resop4_u.
7938 					    opgetattr.ga_res);
7939 
7940 				nfs4_update_dircaches(&rn_res->source_cinfo,
7941 						odvp, NULL, NULL, dinfop);
7942 			}
7943 
7944 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
7945 									nnm);
7946 		}
7947 	}
7948 
7949 	if (resp)
7950 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7951 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
7952 	kmem_free(argop, argoplist_size);
7953 
7954 	return (e.error);
7955 }
7956 
7957 /*
7958  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
7959  * it is possible for the filehandle to change due to the rename.
7960  *
7961  * The compound req in this case includes a post-rename lookup and getattr
7962  * to ensure that we have the correct fh and attributes for the object.
7963  *
7964  * Rename requires that the current fh be the target directory and the
7965  * saved fh be the source directory. After the operation, the current fh
7966  * is unchanged.
7967  *
7968  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
7969  * update the filehandle for the renamed object.  We also get the old
7970  * filehandle for historical reasons; this should be taken out sometime.
7971  * This results in a rather cumbersome compound...
7972  *
7973  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
7974  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
7975  *
7976  */
7977 static int
7978 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
7979 	vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
7980 {
7981 	COMPOUND4args_clnt args;
7982 	COMPOUND4res_clnt res, *resp = NULL;
7983 	int argoplist_size;
7984 	nfs_argop4 *argop;
7985 	nfs_resop4 *resop;
7986 	int doqueue;
7987 	mntinfo4_t *mi;
7988 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
7989 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
7990 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
7991 	RENAME4res *rn_res;
7992 	GETFH4res *ngf_res;
7993 	bool_t needrecov;
7994 	nfs4_recov_state_t recov_state;
7995 	hrtime_t t;
7996 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7997 	dirattr_info_t dinfo, *dinfop = &dinfo;
7998 
7999 	ASSERT(curproc->p_zone == VTOMI4(odvp)->mi_zone);
8000 
8001 	recov_state.rs_flags = 0;
8002 	recov_state.rs_num_retry_despite_err = 0;
8003 
8004 recov_retry:
8005 	*statp = NFS4_OK;
8006 
8007 	/*
8008 	 * There is a window between the RPC and updating the path and
8009 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8010 	 * code, so that it doesn't try to use the old path during that
8011 	 * window.
8012 	 */
8013 	mutex_enter(&orp->r_statelock);
8014 	while (orp->r_flags & R4RECEXPFH) {
8015 		klwp_t *lwp = ttolwp(curthread);
8016 
8017 		if (lwp != NULL)
8018 			lwp->lwp_nostop++;
8019 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8020 			mutex_exit(&orp->r_statelock);
8021 			if (lwp != NULL)
8022 				lwp->lwp_nostop--;
8023 			return (EINTR);
8024 		}
8025 		if (lwp != NULL)
8026 			lwp->lwp_nostop--;
8027 	}
8028 	orp->r_flags |= R4RECEXPFH;
8029 	mutex_exit(&orp->r_statelock);
8030 
8031 	mi = VTOMI4(odvp);
8032 
8033 	args.ctag = TAG_RENAME_VFH;
8034 	args.array_len = (odvp == ndvp) ? 10 : 12;
8035 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8036 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8037 
8038 	/*
8039 	 * Rename ops:
8040 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8041 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8042 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8043 	 *
8044 	 *    if (odvp != ndvp)
8045 	 *	add putfh(sourcedir), getattr(sourcedir) }
8046 	 */
8047 	args.array = argop;
8048 
8049 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8050 			    &recov_state, NULL);
8051 	if (e.error) {
8052 		kmem_free(argop, argoplist_size);
8053 		mutex_enter(&orp->r_statelock);
8054 		orp->r_flags &= ~R4RECEXPFH;
8055 		cv_broadcast(&orp->r_cv);
8056 		mutex_exit(&orp->r_statelock);
8057 		return (e.error);
8058 	}
8059 
8060 	/* 0: putfh source directory */
8061 	argop[0].argop = OP_CPUTFH;
8062 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8063 
8064 	/* 1: Save source fh to free up current for target */
8065 	argop[1].argop = OP_SAVEFH;
8066 
8067 	/* 2: Lookup pre-rename fh of renamed object */
8068 	argop[2].argop = OP_CLOOKUP;
8069 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8070 
8071 	/* 3: getfh fh of renamed object (before rename) */
8072 	argop[3].argop = OP_GETFH;
8073 
8074 	/* 4: putfh targetdir */
8075 	argop[4].argop = OP_CPUTFH;
8076 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8077 
8078 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8079 	argop[5].argop = OP_CRENAME;
8080 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8081 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8082 
8083 	/* 6: getattr of target dir (post op attrs) */
8084 	argop[6].argop = OP_GETATTR;
8085 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8086 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8087 
8088 	/* 7: Lookup post-rename fh of renamed object */
8089 	argop[7].argop = OP_CLOOKUP;
8090 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8091 
8092 	/* 8: getfh fh of renamed object (after rename) */
8093 	argop[8].argop = OP_GETFH;
8094 
8095 	/* 9: getattr of renamed object */
8096 	argop[9].argop = OP_GETATTR;
8097 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8098 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8099 
8100 	/*
8101 	 * If source/target dirs are different, then get new post-op
8102 	 * attrs for source dir also.
8103 	 */
8104 	if (ndvp != odvp) {
8105 		/* 10: putfh (sourcedir) */
8106 		argop[10].argop = OP_CPUTFH;
8107 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8108 
8109 		/* 11: getattr (sourcedir) */
8110 		argop[11].argop = OP_GETATTR;
8111 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8112 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8113 	}
8114 
8115 	dnlc_remove(odvp, onm);
8116 	dnlc_remove(ndvp, nnm);
8117 
8118 	doqueue = 1;
8119 	t = gethrtime();
8120 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8121 
8122 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8123 	if (e.error) {
8124 		PURGE_ATTRCACHE4(odvp);
8125 		PURGE_ATTRCACHE4(ndvp);
8126 		if (!needrecov) {
8127 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8128 					&recov_state, needrecov);
8129 			goto out;
8130 		}
8131 	} else {
8132 		*statp = res.status;
8133 	}
8134 
8135 	if (needrecov) {
8136 		bool_t abort;
8137 
8138 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8139 			    OP_RENAME, NULL);
8140 		if (abort == FALSE) {
8141 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8142 					&recov_state, needrecov);
8143 			kmem_free(argop, argoplist_size);
8144 			if (!e.error)
8145 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8146 								(caddr_t)&res);
8147 			mutex_enter(&orp->r_statelock);
8148 			orp->r_flags &= ~R4RECEXPFH;
8149 			cv_broadcast(&orp->r_cv);
8150 			mutex_exit(&orp->r_statelock);
8151 			goto recov_retry;
8152 		} else {
8153 			if (e.error != 0) {
8154 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8155 						&recov_state, needrecov);
8156 				goto out;
8157 			}
8158 			/* fall through for res.status case */
8159 		}
8160 	}
8161 
8162 	resp = &res;
8163 	/*
8164 	 * If OP_RENAME (or any prev op) failed, then return an error.
8165 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8166 	 */
8167 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8168 		/*
8169 		 * Error in an op other than last Getattr
8170 		 */
8171 		e.error = geterrno4(res.status);
8172 		PURGE_ATTRCACHE4(odvp);
8173 		PURGE_ATTRCACHE4(ndvp);
8174 		/*
8175 		 * System V defines rename to return EEXIST, not
8176 		 * ENOTEMPTY if the target directory is not empty.
8177 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8178 		 * which geterrno4 maps to ENOTEMPTY.
8179 		 */
8180 		if (e.error == ENOTEMPTY)
8181 			e.error = EEXIST;
8182 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8183 				needrecov);
8184 		goto out;
8185 	}
8186 
8187 	/* rename results */
8188 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8189 
8190 	if (res.status == NFS4_OK) {
8191 		/* Update target attribute, readdir and dnlc caches */
8192 		dinfo.di_garp =
8193 			&res.array[6].nfs_resop4_u.opgetattr.ga_res;
8194 		dinfo.di_cred = cr;
8195 		dinfo.di_time_call = t;
8196 	} else
8197 		dinfop = NULL;
8198 
8199 	/* Update source cache attribute, readdir and dnlc caches */
8200 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8201 
8202 	/* Update source cache attribute, readdir and dnlc caches */
8203 	if (ndvp != odvp) {
8204 
8205 		/*
8206 		 * If dinfop is non-NULL, then compound succeded, so
8207 		 * set di_garp to attrs for source dir.  dinfop is only
8208 		 * set to NULL when compound fails.
8209 		 */
8210 		if (dinfop)
8211 			dinfo.di_garp =
8212 				&res.array[11].nfs_resop4_u.opgetattr.ga_res;
8213 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8214 				dinfop);
8215 	}
8216 
8217 	/*
8218 	 * Update the rnode with the new component name and args,
8219 	 * and if the file handle changed, also update it with the new fh.
8220 	 * This is only necessary if the target object has an rnode
8221 	 * entry and there is no need to create one for it.
8222 	 */
8223 	resop = &res.array[8];	/* getfh new res */
8224 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8225 
8226 	/*
8227 	 * Update the path and filehandle for the renamed object.
8228 	 */
8229 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8230 
8231 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8232 
8233 	if (res.status == NFS4_OK) {
8234 		resop++;	/* getattr res */
8235 		e.error = nfs4_update_attrcache(res.status,
8236 				&resop->nfs_resop4_u.opgetattr.ga_res,
8237 				t, ovp, cr);
8238 	}
8239 
8240 out:
8241 	kmem_free(argop, argoplist_size);
8242 	if (resp)
8243 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8244 	mutex_enter(&orp->r_statelock);
8245 	orp->r_flags &= ~R4RECEXPFH;
8246 	cv_broadcast(&orp->r_cv);
8247 	mutex_exit(&orp->r_statelock);
8248 
8249 	return (e.error);
8250 }
8251 
8252 static int
8253 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr)
8254 {
8255 	int error;
8256 	vnode_t *vp;
8257 
8258 	if (curproc->p_zone != VTOMI4(dvp)->mi_zone)
8259 		return (EPERM);
8260 	/*
8261 	 * As ".." has special meaning and rather than send a mkdir
8262 	 * over the wire to just let the server freak out, we just
8263 	 * short circuit it here and return EEXIST
8264 	 */
8265 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8266 		return (EEXIST);
8267 
8268 	/*
8269 	 * Decision to get the right gid and setgid bit of the
8270 	 * new directory is now made in call_nfs4_create_req.
8271 	 */
8272 	va->va_mask |= AT_MODE;
8273 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8274 	if (error)
8275 		return (error);
8276 
8277 	*vpp = vp;
8278 	return (0);
8279 }
8280 
8281 
8282 /*
8283  * rmdir is using the same remove v4 op as does remove.
8284  * Remove requires that the current fh be the target directory.
8285  * After the operation, the current fh is unchanged.
8286  * The compound op structure is:
8287  *      PUTFH(targetdir), REMOVE
8288  */
8289 static int
8290 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr)
8291 {
8292 	int need_end_op = FALSE;
8293 	COMPOUND4args_clnt args;
8294 	COMPOUND4res_clnt res, *resp = NULL;
8295 	REMOVE4res *rm_res;
8296 	nfs_argop4 argop[3];
8297 	nfs_resop4 *resop;
8298 	vnode_t *vp;
8299 	int doqueue;
8300 	mntinfo4_t *mi;
8301 	rnode4_t *drp;
8302 	bool_t needrecov = FALSE;
8303 	nfs4_recov_state_t recov_state;
8304 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8305 	dirattr_info_t dinfo, *dinfop;
8306 
8307 	if (curproc->p_zone != VTOMI4(dvp)->mi_zone)
8308 		return (EPERM);
8309 	/*
8310 	 * As ".." has special meaning and rather than send a rmdir
8311 	 * over the wire to just let the server freak out, we just
8312 	 * short circuit it here and return EEXIST
8313 	 */
8314 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8315 		return (EEXIST);
8316 
8317 	drp = VTOR4(dvp);
8318 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8319 		return (EINTR);
8320 
8321 	/*
8322 	 * Attempt to prevent a rmdir(".") from succeeding.
8323 	 */
8324 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8325 	if (e.error) {
8326 		nfs_rw_exit(&drp->r_rwlock);
8327 		return (e.error);
8328 	}
8329 	if (vp == cdir) {
8330 		VN_RELE(vp);
8331 		nfs_rw_exit(&drp->r_rwlock);
8332 		return (EINVAL);
8333 	}
8334 
8335 	/*
8336 	 * Since nfsv4 remove op works on both files and directories,
8337 	 * check that the removed object is indeed a directory.
8338 	 */
8339 	if (vp->v_type != VDIR) {
8340 		VN_RELE(vp);
8341 		nfs_rw_exit(&drp->r_rwlock);
8342 		return (ENOTDIR);
8343 	}
8344 
8345 	/*
8346 	 * First just remove the entry from the name cache, as it
8347 	 * is most likely an entry for this vp.
8348 	 */
8349 	dnlc_remove(dvp, nm);
8350 
8351 	/*
8352 	 * If there vnode reference count is greater than one, then
8353 	 * there may be additional references in the DNLC which will
8354 	 * need to be purged.  First, trying removing the entry for
8355 	 * the parent directory and see if that removes the additional
8356 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8357 	 * to completely remove any references to the directory which
8358 	 * might still exist in the DNLC.
8359 	 */
8360 	if (vp->v_count > 1) {
8361 		dnlc_remove(vp, "..");
8362 		if (vp->v_count > 1)
8363 			dnlc_purge_vp(vp);
8364 	}
8365 
8366 	mi = VTOMI4(dvp);
8367 	recov_state.rs_flags = 0;
8368 	recov_state.rs_num_retry_despite_err = 0;
8369 
8370 recov_retry:
8371 	args.ctag = TAG_RMDIR;
8372 
8373 	/*
8374 	 * Rmdir ops: putfh dir; remove
8375 	 */
8376 	args.array_len = 3;
8377 	args.array = argop;
8378 
8379 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8380 	if (e.error) {
8381 		nfs_rw_exit(&drp->r_rwlock);
8382 		return (e.error);
8383 	}
8384 	need_end_op = TRUE;
8385 
8386 	/* putfh directory */
8387 	argop[0].argop = OP_CPUTFH;
8388 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8389 
8390 	/* remove */
8391 	argop[1].argop = OP_CREMOVE;
8392 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8393 
8394 	/* getattr (postop attrs for dir that contained removed dir) */
8395 	argop[2].argop = OP_GETATTR;
8396 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8397 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8398 
8399 	dinfo.di_time_call = gethrtime();
8400 	doqueue = 1;
8401 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8402 
8403 	PURGE_ATTRCACHE4(vp);
8404 
8405 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8406 	if (e.error) {
8407 		PURGE_ATTRCACHE4(dvp);
8408 	}
8409 
8410 	if (needrecov) {
8411 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8412 		    NULL, OP_REMOVE, NULL) == FALSE) {
8413 			if (!e.error)
8414 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8415 								(caddr_t)&res);
8416 
8417 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8418 			    needrecov);
8419 			need_end_op = FALSE;
8420 			goto recov_retry;
8421 		}
8422 	}
8423 
8424 	if (!e.error) {
8425 		resp = &res;
8426 
8427 		/*
8428 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8429 		 * failed.
8430 		 */
8431 		if (res.status != NFS4_OK && res.array_len <= 2) {
8432 			e.error = geterrno4(res.status);
8433 			PURGE_ATTRCACHE4(dvp);
8434 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8435 						&recov_state, needrecov);
8436 			need_end_op = FALSE;
8437 			nfs4_purge_stale_fh(e.error, dvp, cr);
8438 			/*
8439 			 * System V defines rmdir to return EEXIST, not
8440 			 * ENOTEMPTY if the directory is not empty.  Over
8441 			 * the wire, the error is NFSERR_ENOTEMPTY which
8442 			 * geterrno4 maps to ENOTEMPTY.
8443 			 */
8444 			if (e.error == ENOTEMPTY)
8445 				e.error = EEXIST;
8446 		} else {
8447 			resop = &res.array[1];	/* remove res */
8448 			rm_res = &resop->nfs_resop4_u.opremove;
8449 
8450 			if (res.status == NFS4_OK) {
8451 				resop = &res.array[2];	/* dir attrs */
8452 				dinfo.di_garp =
8453 					&resop->nfs_resop4_u.opgetattr.ga_res;
8454 				dinfo.di_cred = cr;
8455 				dinfop = &dinfo;
8456 			} else
8457 				dinfop = NULL;
8458 
8459 			/* Update dir attribute, readdir and dnlc caches */
8460 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8461 				dinfop);
8462 
8463 			/* destroy rddir cache for dir that was removed */
8464 			if (VTOR4(vp)->r_dir != NULL)
8465 				nfs4_purge_rddir_cache(vp);
8466 		}
8467 	}
8468 
8469 	if (need_end_op)
8470 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8471 
8472 	nfs_rw_exit(&drp->r_rwlock);
8473 
8474 	if (resp)
8475 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8476 
8477 	VN_RELE(vp);
8478 
8479 	return (e.error);
8480 }
8481 
8482 static int
8483 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr)
8484 {
8485 	int error;
8486 	vnode_t *vp;
8487 	rnode4_t *rp;
8488 	char *contents;
8489 	mntinfo4_t *mi = VTOMI4(dvp);
8490 
8491 	if (curproc->p_zone != mi->mi_zone)
8492 		return (EPERM);
8493 	if (!(mi->mi_flags & MI4_SYMLINK))
8494 		return (EOPNOTSUPP);
8495 
8496 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8497 	if (error) {
8498 		return (error);
8499 	}
8500 
8501 	ASSERT(nfs4_consistent_type(vp));
8502 	rp = VTOR4(vp);
8503 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8504 
8505 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8506 
8507 		if (contents != NULL) {
8508 			mutex_enter(&rp->r_statelock);
8509 			if (rp->r_symlink.contents == NULL) {
8510 				rp->r_symlink.len = strlen(tnm);
8511 				bcopy(tnm, contents, rp->r_symlink.len);
8512 				rp->r_symlink.contents = contents;
8513 				rp->r_symlink.size = MAXPATHLEN;
8514 				mutex_exit(&rp->r_statelock);
8515 			} else {
8516 				mutex_exit(&rp->r_statelock);
8517 				kmem_free((void *)contents, MAXPATHLEN);
8518 			}
8519 		}
8520 	}
8521 	VN_RELE(vp);
8522 
8523 	return (error);
8524 }
8525 
8526 
8527 /*
8528  * Read directory entries.
8529  * There are some weird things to look out for here.  The uio_loffset
8530  * field is either 0 or it is the offset returned from a previous
8531  * readdir.  It is an opaque value used by the server to find the
8532  * correct directory block to read. The count field is the number
8533  * of blocks to read on the server.  This is advisory only, the server
8534  * may return only one block's worth of entries.  Entries may be compressed
8535  * on the server.
8536  */
8537 static int
8538 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp)
8539 {
8540 	int error;
8541 	uint_t count;
8542 	rnode4_t *rp;
8543 	rddir4_cache *rdc;
8544 	rddir4_cache *rrdc;
8545 
8546 	if (curproc->p_zone != VTOMI4(vp)->mi_zone)
8547 		return (EIO);
8548 	rp = VTOR4(vp);
8549 
8550 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8551 
8552 	/*
8553 	 * Make sure that the directory cache is valid.
8554 	 */
8555 	if (rp->r_dir != NULL) {
8556 		if (nfs_disable_rddir_cache != 0) {
8557 			/*
8558 			 * Setting nfs_disable_rddir_cache in /etc/system
8559 			 * allows interoperability with servers that do not
8560 			 * properly update the attributes of directories.
8561 			 * Any cached information gets purged before an
8562 			 * access is made to it.
8563 			 */
8564 			nfs4_purge_rddir_cache(vp);
8565 		}
8566 
8567 		error = nfs4_validate_caches(vp, cr);
8568 		if (error)
8569 			return (error);
8570 	}
8571 
8572 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8573 
8574 	/*
8575 	 * Short circuit last readdir which always returns 0 bytes.
8576 	 * This can be done after the directory has been read through
8577 	 * completely at least once.  This will set r_direof which
8578 	 * can be used to find the value of the last cookie.
8579 	 */
8580 	mutex_enter(&rp->r_statelock);
8581 	if (rp->r_direof != NULL &&
8582 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8583 		mutex_exit(&rp->r_statelock);
8584 #ifdef DEBUG
8585 		nfs4_readdir_cache_shorts++;
8586 #endif
8587 		if (eofp)
8588 			*eofp = 1;
8589 		return (0);
8590 	}
8591 
8592 	/*
8593 	 * Look for a cache entry.  Cache entries are identified
8594 	 * by the NFS cookie value and the byte count requested.
8595 	 */
8596 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8597 
8598 	/*
8599 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8600 	 */
8601 	if (rdc == NULL) {
8602 		mutex_exit(&rp->r_statelock);
8603 		return (EINTR);
8604 	}
8605 
8606 	/*
8607 	 * Check to see if we need to fill this entry in.
8608 	 */
8609 	if (rdc->flags & RDDIRREQ) {
8610 		rdc->flags &= ~RDDIRREQ;
8611 		rdc->flags |= RDDIR;
8612 		mutex_exit(&rp->r_statelock);
8613 
8614 		/*
8615 		 * Do the readdir.
8616 		 */
8617 		nfs4readdir(vp, rdc, cr);
8618 
8619 		/*
8620 		 * Reaquire the lock, so that we can continue
8621 		 */
8622 		mutex_enter(&rp->r_statelock);
8623 		/*
8624 		 * The entry is now complete
8625 		 */
8626 		rdc->flags &= ~RDDIR;
8627 	}
8628 
8629 	ASSERT(!(rdc->flags & RDDIR));
8630 
8631 	/*
8632 	 * If an error occurred while attempting
8633 	 * to fill the cache entry, mark the entry invalid and
8634 	 * just return the error.
8635 	 */
8636 	if (rdc->error) {
8637 		error = rdc->error;
8638 		rdc->flags |= RDDIRREQ;
8639 		rddir4_cache_rele(rp, rdc);
8640 		mutex_exit(&rp->r_statelock);
8641 		return (error);
8642 	}
8643 
8644 	/*
8645 	 * The cache entry is complete and good,
8646 	 * copyout the dirent structs to the calling
8647 	 * thread.
8648 	 */
8649 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
8650 
8651 	/*
8652 	 * If no error occurred during the copyout,
8653 	 * update the offset in the uio struct to
8654 	 * contain the value of the next NFS 4 cookie
8655 	 * and set the eof value appropriately.
8656 	 */
8657 	if (!error) {
8658 		uiop->uio_loffset = rdc->nfs4_ncookie;
8659 		if (eofp)
8660 			*eofp = rdc->eof;
8661 	}
8662 
8663 	/*
8664 	 * Decide whether to do readahead.  Don't if we
8665 	 * have already read to the end of directory.
8666 	 */
8667 	if (rdc->eof) {
8668 		/*
8669 		 * Make the entry the direof only if it is cached
8670 		 */
8671 		if (rdc->flags & RDDIRCACHED)
8672 			rp->r_direof = rdc;
8673 		rddir4_cache_rele(rp, rdc);
8674 		mutex_exit(&rp->r_statelock);
8675 		return (error);
8676 	}
8677 
8678 	/* Determine if a readdir readahead should be done */
8679 	if (!(rp->r_flags & R4LOOKUP)) {
8680 		rddir4_cache_rele(rp, rdc);
8681 		mutex_exit(&rp->r_statelock);
8682 		return (error);
8683 	}
8684 
8685 	/*
8686 	 * Now look for a readahead entry.
8687 	 *
8688 	 * Check to see whether we found an entry for the readahead.
8689 	 * If so, we don't need to do anything further, so free the new
8690 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
8691 	 * it to the cache, and then initiate an asynchronous readdir
8692 	 * operation to fill it.
8693 	 */
8694 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
8695 
8696 	/*
8697 	 * A readdir cache entry could not be obtained for the readahead.  In
8698 	 * this case we skip the readahead and return.
8699 	 */
8700 	if (rrdc == NULL) {
8701 		rddir4_cache_rele(rp, rdc);
8702 		mutex_exit(&rp->r_statelock);
8703 		return (error);
8704 	}
8705 
8706 	/*
8707 	 * Check to see if we need to fill this entry in.
8708 	 */
8709 	if (rrdc->flags & RDDIRREQ) {
8710 		rrdc->flags &= ~RDDIRREQ;
8711 		rrdc->flags |= RDDIR;
8712 		rddir4_cache_rele(rp, rdc);
8713 		mutex_exit(&rp->r_statelock);
8714 #ifdef DEBUG
8715 		nfs4_readdir_readahead++;
8716 #endif
8717 		/*
8718 		 * Do the readdir.
8719 		 */
8720 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
8721 		return (error);
8722 	}
8723 
8724 	rddir4_cache_rele(rp, rrdc);
8725 	rddir4_cache_rele(rp, rdc);
8726 	mutex_exit(&rp->r_statelock);
8727 	return (error);
8728 }
8729 
8730 static int
8731 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
8732 {
8733 	int error;
8734 	rnode4_t *rp;
8735 
8736 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
8737 
8738 	rp = VTOR4(vp);
8739 
8740 	/*
8741 	 * Obtain the readdir results for the caller.
8742 	 */
8743 	nfs4readdir(vp, rdc, cr);
8744 
8745 	mutex_enter(&rp->r_statelock);
8746 	/*
8747 	 * The entry is now complete
8748 	 */
8749 	rdc->flags &= ~RDDIR;
8750 
8751 	error = rdc->error;
8752 	if (error)
8753 		rdc->flags |= RDDIRREQ;
8754 	rddir4_cache_rele(rp, rdc);
8755 	mutex_exit(&rp->r_statelock);
8756 
8757 	return (error);
8758 }
8759 
8760 static void
8761 nfs4readdir_stub(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
8762 {
8763 	int stublength;
8764 	dirent64_t *dp;
8765 	u_longlong_t nodeid, pnodeid;
8766 	vnode_t *dotdotvp = NULL;
8767 	rnode4_t *rp = VTOR4(vp);
8768 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
8769 
8770 	rdc->error = 0;
8771 	rdc->entries = 0;
8772 	rdc->actlen = rdc->entlen = 0;
8773 	rdc->eof = TRUE;
8774 
8775 	/* Check for EOF case for readdir of stub */
8776 	if (cookie != 0 && cookie != 1)
8777 		return;
8778 
8779 	nodeid = rp->r_attr.va_nodeid;
8780 	if (vp->v_flag & VROOT) {
8781 		pnodeid = nodeid;	/* root of mount point */
8782 	} else {
8783 		if (rdc->error = nfs4_lookup(vp, "..", &dotdotvp, 0, 0, 0, cr))
8784 			return;
8785 		pnodeid = VTOR4(dotdotvp)->r_attr.va_nodeid;
8786 		VN_RELE(dotdotvp);
8787 	}
8788 
8789 	stublength = DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2);
8790 	rdc->entries = kmem_alloc(stublength, KM_SLEEP);
8791 	rdc->entlen = rdc->buflen = stublength;
8792 	rdc->eof = TRUE;
8793 
8794 	dp = (dirent64_t *)rdc->entries;
8795 
8796 	if (rdc->nfs4_cookie == (nfs_cookie4)0) {
8797 		bcopy(nfs4_dot_entries, rdc->entries,
8798 			DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2));
8799 		dp->d_ino = nodeid;
8800 		dp = (struct dirent64 *)(((char *)dp) + DIRENT64_RECLEN(1));
8801 		dp->d_ino = pnodeid;
8802 		rdc->actlen = DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2);
8803 	} else	{	/* for ".." entry */
8804 		bcopy(nfs4_dot_dot_entry, rdc->entries, DIRENT64_RECLEN(2));
8805 		dp->d_ino = pnodeid;
8806 		rdc->actlen = DIRENT64_RECLEN(2);
8807 	}
8808 	rdc->nfs4_ncookie = rdc->actlen;
8809 }
8810 
8811 /*
8812  * Read directory entries.
8813  * There are some weird things to look out for here.  The uio_loffset
8814  * field is either 0 or it is the offset returned from a previous
8815  * readdir.  It is an opaque value used by the server to find the
8816  * correct directory block to read. The count field is the number
8817  * of blocks to read on the server.  This is advisory only, the server
8818  * may return only one block's worth of entries.  Entries may be compressed
8819  * on the server.
8820  *
8821  * Generates the following compound request:
8822  * 1. If readdir offset is zero and no dnlc entry for parent exists,
8823  *    must include a Lookupp as well. In this case, send:
8824  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
8825  * 2. Otherwise just do: { Putfh <fh>; Readdir }
8826  *
8827  * Get complete attributes and filehandles for entries if this is the
8828  * first read of the directory. Otherwise, just get fileid's.
8829  */
8830 static void
8831 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
8832 {
8833 	COMPOUND4args_clnt args;
8834 	COMPOUND4res_clnt res;
8835 	READDIR4args *rargs;
8836 	READDIR4res_clnt *rd_res;
8837 	bitmap4 rd_bitsval;
8838 	nfs_argop4 argop[5];
8839 	nfs_resop4 *resop;
8840 	rnode4_t *rp = VTOR4(vp);
8841 	mntinfo4_t *mi = VTOMI4(vp);
8842 	int doqueue;
8843 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
8844 	vnode_t *dvp;
8845 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
8846 	int num_ops, res_opcnt;
8847 	bool_t needrecov = FALSE;
8848 	nfs4_recov_state_t recov_state;
8849 	hrtime_t t;
8850 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8851 
8852 	ASSERT(curproc->p_zone == mi->mi_zone);
8853 	ASSERT(rdc->flags & RDDIR);
8854 	ASSERT(rdc->entries == NULL);
8855 
8856 	if (rp->r_flags & R4SRVSTUB) {
8857 		nfs4readdir_stub(vp, rdc, cr);
8858 		return;
8859 	}
8860 
8861 	num_ops = 2;
8862 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
8863 		/*
8864 		 * Since nfsv4 readdir may not return entries for "." and "..",
8865 		 * the client must recreate them:
8866 		 * To find the correct nodeid, do the following:
8867 		 * For current node, get nodeid from dnlc.
8868 		 * - if current node is rootvp, set pnodeid to nodeid.
8869 		 * - else if parent is in the dnlc, get its nodeid from there.
8870 		 * - else add LOOKUPP+GETATTR to compound.
8871 		 */
8872 		nodeid = rp->r_attr.va_nodeid;
8873 		if (vp->v_flag & VROOT) {
8874 			pnodeid = nodeid;	/* root of mount point */
8875 		} else {
8876 			dvp = dnlc_lookup(vp, "..");
8877 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
8878 				/* parent in dnlc cache - no need for otw */
8879 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
8880 			} else {
8881 				/*
8882 				 * parent not in dnlc cache,
8883 				 * do lookupp to get its id
8884 				 */
8885 				num_ops = 5;
8886 				pnodeid = 0; /* set later by getattr parent */
8887 			}
8888 			if (dvp)
8889 				VN_RELE(dvp);
8890 		}
8891 	}
8892 	recov_state.rs_flags = 0;
8893 	recov_state.rs_num_retry_despite_err = 0;
8894 
8895 	/* Save the original mount point security flavor */
8896 	(void) save_mnt_secinfo(mi->mi_curr_serv);
8897 
8898 recov_retry:
8899 	args.ctag = TAG_READDIR;
8900 
8901 	args.array = argop;
8902 	args.array_len = num_ops;
8903 
8904 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
8905 					&recov_state, NULL)) {
8906 		/*
8907 		 * If readdir a node that is a stub for a crossed mount point,
8908 		 * keep the original secinfo flavor for the current file
8909 		 * system, not the crossed one.
8910 		 */
8911 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
8912 		rdc->error = e.error;
8913 		return;
8914 	}
8915 
8916 	/*
8917 	 * Determine which attrs to request for dirents.  This code
8918 	 * must be protected by nfs4_start/end_fop because of r_server
8919 	 * (which will change during failover recovery).
8920 	 *
8921 	 */
8922 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
8923 		/*
8924 		 * Get all vattr attrs plus filehandle and rdattr_error
8925 		 */
8926 		rd_bitsval = NFS4_VATTR_MASK |
8927 			FATTR4_RDATTR_ERROR_MASK |
8928 			FATTR4_FILEHANDLE_MASK;
8929 
8930 		if (rp->r_flags & R4READDIRWATTR) {
8931 			mutex_enter(&rp->r_statelock);
8932 			rp->r_flags &= ~R4READDIRWATTR;
8933 			mutex_exit(&rp->r_statelock);
8934 		}
8935 	} else {
8936 		servinfo4_t *svp = rp->r_server;
8937 
8938 		/*
8939 		 * Already read directory. Use readdir with
8940 		 * no attrs (except for mounted_on_fileid) for updates.
8941 		 */
8942 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
8943 
8944 		/*
8945 		 * request mounted on fileid if supported, else request
8946 		 * fileid.  maybe we should verify that fileid is supported
8947 		 * and request something else if not.
8948 		 */
8949 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
8950 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
8951 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
8952 		nfs_rw_exit(&svp->sv_lock);
8953 	}
8954 
8955 	/* putfh directory fh */
8956 	argop[0].argop = OP_CPUTFH;
8957 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
8958 
8959 	argop[1].argop = OP_READDIR;
8960 	rargs = &argop[1].nfs_argop4_u.opreaddir;
8961 	/*
8962 	 * 1 and 2 are reserved for client "." and ".." entry offset.
8963 	 * cookie 0 should be used over-the-wire to start reading at
8964 	 * the beginning of the directory excluding "." and "..".
8965 	 */
8966 	if (rdc->nfs4_cookie == 0 ||
8967 	    rdc->nfs4_cookie == 1 ||
8968 	    rdc->nfs4_cookie == 2) {
8969 		rargs->cookie = (nfs_cookie4)0;
8970 		rargs->cookieverf = 0;
8971 	} else {
8972 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
8973 		mutex_enter(&rp->r_statelock);
8974 		rargs->cookieverf = rp->r_cookieverf4;
8975 		mutex_exit(&rp->r_statelock);
8976 	}
8977 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
8978 	rargs->maxcount = mi->mi_tsize;
8979 	rargs->attr_request = rd_bitsval;
8980 	rargs->rdc = rdc;
8981 	rargs->dvp = vp;
8982 	rargs->mi = mi;
8983 	rargs->cr = cr;
8984 
8985 
8986 	/*
8987 	 * If count < than the minimum required, we return no entries
8988 	 * and fail with EINVAL
8989 	 */
8990 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
8991 		rdc->error = EINVAL;
8992 		goto out;
8993 	}
8994 
8995 	if (args.array_len == 5) {
8996 		/*
8997 		 * Add lookupp and getattr for parent nodeid.
8998 		 */
8999 		argop[2].argop = OP_LOOKUPP;
9000 
9001 		argop[3].argop = OP_GETFH;
9002 
9003 		/* getattr parent */
9004 		argop[4].argop = OP_GETATTR;
9005 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9006 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9007 	}
9008 
9009 	doqueue = 1;
9010 
9011 	if (mi->mi_io_kstats) {
9012 		mutex_enter(&mi->mi_lock);
9013 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9014 		mutex_exit(&mi->mi_lock);
9015 	}
9016 
9017 	/* capture the time of this call */
9018 	rargs->t = t = gethrtime();
9019 
9020 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9021 
9022 	if (mi->mi_io_kstats) {
9023 		mutex_enter(&mi->mi_lock);
9024 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9025 		mutex_exit(&mi->mi_lock);
9026 	}
9027 
9028 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9029 
9030 	/*
9031 	 * If RPC error occurred and it isn't an error that
9032 	 * triggers recovery, then go ahead and fail now.
9033 	 */
9034 	if (e.error != 0 && !needrecov) {
9035 		rdc->error = e.error;
9036 		goto out;
9037 	}
9038 
9039 	if (needrecov) {
9040 		bool_t abort;
9041 
9042 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9043 		    "nfs4readdir: initiating recovery.\n"));
9044 
9045 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9046 			    NULL, OP_READDIR, NULL);
9047 		if (abort == FALSE) {
9048 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9049 				    &recov_state, needrecov);
9050 			if (!e.error)
9051 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9052 						(caddr_t)&res);
9053 			if (rdc->entries != NULL) {
9054 				kmem_free(rdc->entries, rdc->entlen);
9055 				rdc->entries = NULL;
9056 			}
9057 			goto recov_retry;
9058 		}
9059 
9060 		if (e.error != 0) {
9061 			rdc->error = e.error;
9062 			goto out;
9063 		}
9064 
9065 		/* fall through for res.status case */
9066 	}
9067 
9068 	res_opcnt = res.array_len;
9069 
9070 	/*
9071 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9072 	 * failure here.  Subsequent ops are for filling out dot-dot
9073 	 * dirent, and if they fail, we still want to give the caller
9074 	 * the dirents returned by (the successful) READDIR op, so we need
9075 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9076 	 *
9077 	 * One example where PUTFH+READDIR ops would succeed but
9078 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9079 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9080 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9081 	 * x perm.  We need to come up with a non-vendor-specific way
9082 	 * for a POSIX server to return d_ino from dotdot's dirent if
9083 	 * client only requests mounted_on_fileid, and just say the
9084 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9085 	 * client requested any mandatory attrs, server would be required
9086 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9087 	 * for dotdot.
9088 	 */
9089 
9090 	if (res.status) {
9091 		if (res_opcnt <= 2) {
9092 			e.error = geterrno4(res.status);
9093 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9094 			    &recov_state, needrecov);
9095 			nfs4_purge_stale_fh(e.error, vp, cr);
9096 			rdc->error = e.error;
9097 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9098 			if (rdc->entries != NULL) {
9099 				kmem_free(rdc->entries, rdc->entlen);
9100 				rdc->entries = NULL;
9101 			}
9102 			/*
9103 			 * If readdir a node that is a stub for a
9104 			 * crossed mount point, keep the original
9105 			 * secinfo flavor for the current file system,
9106 			 * not the crossed one.
9107 			 */
9108 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9109 			return;
9110 		}
9111 	}
9112 
9113 	resop = &res.array[1];	/* readdir res */
9114 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9115 
9116 	mutex_enter(&rp->r_statelock);
9117 	rp->r_cookieverf4 = rd_res->cookieverf;
9118 	mutex_exit(&rp->r_statelock);
9119 
9120 	/*
9121 	 * For "." and ".." entries
9122 	 * e.g.
9123 	 *	seek(cookie=0) -> "." entry with d_off = 1
9124 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9125 	 */
9126 	if (cookie == (nfs_cookie4) 0) {
9127 		if (rd_res->dotp)
9128 			rd_res->dotp->d_ino = nodeid;
9129 		if (rd_res->dotdotp)
9130 			rd_res->dotdotp->d_ino = pnodeid;
9131 	}
9132 	if (cookie == (nfs_cookie4) 1) {
9133 		if (rd_res->dotdotp)
9134 			rd_res->dotdotp->d_ino = pnodeid;
9135 	}
9136 
9137 
9138 	/* LOOKUPP+GETATTR attemped */
9139 	if (args.array_len == 5 && rd_res->dotdotp) {
9140 		if (res.status == NFS4_OK && res_opcnt == 5) {
9141 			nfs_fh4 *fhp;
9142 			nfs4_sharedfh_t *sfhp;
9143 			vnode_t *pvp;
9144 			nfs4_ga_res_t *garp;
9145 
9146 			resop++;	/* lookupp */
9147 			resop++;	/* getfh   */
9148 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9149 
9150 			resop++;	/* getattr of parent */
9151 
9152 			/*
9153 			 * First, take care of finishing the
9154 			 * readdir results.
9155 			 */
9156 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9157 			/*
9158 			 * The d_ino of .. must be the inode number
9159 			 * of the mounted filesystem.
9160 			 */
9161 			if (garp->n4g_va.va_mask & AT_NODEID)
9162 				rd_res->dotdotp->d_ino =
9163 					garp->n4g_va.va_nodeid;
9164 
9165 
9166 			/*
9167 			 * Next, create the ".." dnlc entry
9168 			 */
9169 			sfhp = sfh4_get(fhp, mi);
9170 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9171 				dnlc_update(vp, "..", pvp);
9172 				VN_RELE(pvp);
9173 			}
9174 			sfh4_rele(&sfhp);
9175 		}
9176 	}
9177 
9178 	if (mi->mi_io_kstats) {
9179 		mutex_enter(&mi->mi_lock);
9180 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9181 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9182 		mutex_exit(&mi->mi_lock);
9183 	}
9184 
9185 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9186 
9187 out:
9188 	/*
9189 	 * If readdir a node that is a stub for a crossed mount point,
9190 	 * keep the original secinfo flavor for the current file system,
9191 	 * not the crossed one.
9192 	 */
9193 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9194 
9195 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9196 }
9197 
9198 
9199 static int
9200 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9201 {
9202 	rnode4_t *rp = VTOR4(bp->b_vp);
9203 	int count;
9204 	int error;
9205 	cred_t *cred_otw = NULL;
9206 	offset_t offset;
9207 	nfs4_open_stream_t *osp = NULL;
9208 	bool_t first_time = TRUE;	/* first time getting otw cred */
9209 	bool_t last_time = FALSE;	/* last time getting otw cred */
9210 
9211 	ASSERT(curproc->p_zone == VTOMI4(bp->b_vp)->mi_zone);
9212 
9213 	DTRACE_IO1(start, struct buf *, bp);
9214 	offset = ldbtob(bp->b_lblkno);
9215 
9216 	if (bp->b_flags & B_READ) {
9217 	read_again:
9218 		/*
9219 		 * Releases the osp, if it is provided.
9220 		 * Puts a hold on the cred_otw and the new osp (if found).
9221 		 */
9222 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9223 			&first_time, &last_time);
9224 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9225 						offset, bp->b_bcount,
9226 						&bp->b_resid, cred_otw,
9227 						readahead, NULL);
9228 		crfree(cred_otw);
9229 		if (!error) {
9230 			if (bp->b_resid) {
9231 				/*
9232 				 * Didn't get it all because we hit EOF,
9233 				 * zero all the memory beyond the EOF.
9234 				 */
9235 				/* bzero(rdaddr + */
9236 				bzero(bp->b_un.b_addr +
9237 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9238 			}
9239 			mutex_enter(&rp->r_statelock);
9240 			if (bp->b_resid == bp->b_bcount &&
9241 			    offset >= rp->r_size) {
9242 				/*
9243 				 * We didn't read anything at all as we are
9244 				 * past EOF.  Return an error indicator back
9245 				 * but don't destroy the pages (yet).
9246 				 */
9247 				error = NFS_EOF;
9248 			}
9249 			mutex_exit(&rp->r_statelock);
9250 		} else if (error == EACCES && last_time == FALSE) {
9251 				goto read_again;
9252 		}
9253 	} else {
9254 		if (!(rp->r_flags & R4STALE)) {
9255 		write_again:
9256 			/*
9257 			 * Releases the osp, if it is provided.
9258 			 * Puts a hold on the cred_otw and the new
9259 			 * osp (if found).
9260 			 */
9261 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9262 				&first_time, &last_time);
9263 			mutex_enter(&rp->r_statelock);
9264 			count = MIN(bp->b_bcount, rp->r_size - offset);
9265 			mutex_exit(&rp->r_statelock);
9266 			if (count < 0)
9267 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9268 #ifdef DEBUG
9269 			if (count == 0) {
9270 				zoneid_t zoneid = getzoneid();
9271 
9272 				zcmn_err(zoneid, CE_WARN,
9273 				    "nfs4_bio: zero length write at %lld",
9274 				    offset);
9275 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9276 				    "b_bcount=%ld, file size=%lld",
9277 				    rp->r_flags, (long)bp->b_bcount,
9278 				    rp->r_size);
9279 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9280 				if (nfs4_bio_do_stop)
9281 					debug_enter("nfs4_bio");
9282 			}
9283 #endif
9284 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9285 			    count, cred_otw, stab_comm);
9286 			if (error == EACCES && last_time == FALSE) {
9287 				crfree(cred_otw);
9288 				goto write_again;
9289 			}
9290 			bp->b_error = error;
9291 			if (error && error != EINTR &&
9292 			    !(bp->b_vp->v_vfsp->vfs_flag && VFS_UNMOUNTED)) {
9293 				/*
9294 				 * Don't print EDQUOT errors on the console.
9295 				 * Don't print asynchronous EACCES errors.
9296 				 * Don't print EFBIG errors.
9297 				 * Print all other write errors.
9298 				 */
9299 				if (error != EDQUOT && error != EFBIG &&
9300 				    (error != EACCES ||
9301 				    !(bp->b_flags & B_ASYNC)))
9302 					nfs4_write_error(bp->b_vp,
9303 					    error, cred_otw);
9304 				/*
9305 				 * Update r_error and r_flags as appropriate.
9306 				 * If the error was ESTALE, then mark the
9307 				 * rnode as not being writeable and save
9308 				 * the error status.  Otherwise, save any
9309 				 * errors which occur from asynchronous
9310 				 * page invalidations.  Any errors occurring
9311 				 * from other operations should be saved
9312 				 * by the caller.
9313 				 */
9314 				mutex_enter(&rp->r_statelock);
9315 				if (error == ESTALE) {
9316 					rp->r_flags |= R4STALE;
9317 					if (!rp->r_error)
9318 						rp->r_error = error;
9319 				} else if (!rp->r_error &&
9320 				    (bp->b_flags &
9321 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9322 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9323 					rp->r_error = error;
9324 				}
9325 				mutex_exit(&rp->r_statelock);
9326 			}
9327 			crfree(cred_otw);
9328 		} else
9329 			error = rp->r_error;
9330 	}
9331 
9332 	if (error != 0 && error != NFS_EOF)
9333 		bp->b_flags |= B_ERROR;
9334 
9335 	if (osp)
9336 		open_stream_rele(osp, rp);
9337 
9338 	DTRACE_IO1(done, struct buf *, bp);
9339 
9340 	return (error);
9341 }
9342 
9343 /* ARGSUSED */
9344 static int
9345 nfs4_fid(vnode_t *vp, fid_t *fidp)
9346 {
9347 	return (EREMOTE);
9348 }
9349 
9350 /* ARGSUSED2 */
9351 static int
9352 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9353 {
9354 	rnode4_t *rp = VTOR4(vp);
9355 
9356 	if (!write_lock) {
9357 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9358 		return (V_WRITELOCK_FALSE);
9359 	}
9360 
9361 	if ((rp->r_flags & R4DIRECTIO) ||
9362 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9363 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9364 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9365 			return (V_WRITELOCK_FALSE);
9366 		nfs_rw_exit(&rp->r_rwlock);
9367 	}
9368 
9369 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9370 	return (V_WRITELOCK_TRUE);
9371 }
9372 
9373 /* ARGSUSED */
9374 static void
9375 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9376 {
9377 	rnode4_t *rp = VTOR4(vp);
9378 
9379 	nfs_rw_exit(&rp->r_rwlock);
9380 }
9381 
9382 /* ARGSUSED */
9383 static int
9384 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp)
9385 {
9386 	if (curproc->p_zone != VTOMI4(vp)->mi_zone)
9387 		return (EIO);
9388 
9389 	/*
9390 	 * Because we stuff the readdir cookie into the offset field
9391 	 * someone may attempt to do an lseek with the cookie which
9392 	 * we want to succeed.
9393 	 */
9394 	if (vp->v_type == VDIR)
9395 		return (0);
9396 	if (*noffp < 0)
9397 		return (EINVAL);
9398 	return (0);
9399 }
9400 
9401 
9402 /*
9403  * Return all the pages from [off..off+len) in file
9404  */
9405 static int
9406 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9407 	page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9408 	enum seg_rw rw, cred_t *cr)
9409 {
9410 	rnode4_t *rp;
9411 	int error;
9412 	mntinfo4_t *mi;
9413 
9414 	if (curproc->p_zone != VTOMI4(vp)->mi_zone)
9415 		return (EIO);
9416 	rp = VTOR4(vp);
9417 	if (IS_SHADOW(vp, rp))
9418 		vp = RTOV4(rp);
9419 
9420 	if (vp->v_flag & VNOMAP)
9421 		return (ENOSYS);
9422 
9423 	if (protp != NULL)
9424 		*protp = PROT_ALL;
9425 
9426 	/*
9427 	 * Now validate that the caches are up to date.
9428 	 */
9429 	if (error = nfs4_validate_caches(vp, cr))
9430 		return (error);
9431 
9432 	mi = VTOMI4(vp);
9433 retry:
9434 	mutex_enter(&rp->r_statelock);
9435 
9436 	/*
9437 	 * Don't create dirty pages faster than they
9438 	 * can be cleaned so that the system doesn't
9439 	 * get imbalanced.  If the async queue is
9440 	 * maxed out, then wait for it to drain before
9441 	 * creating more dirty pages.  Also, wait for
9442 	 * any threads doing pagewalks in the vop_getattr
9443 	 * entry points so that they don't block for
9444 	 * long periods.
9445 	 */
9446 	if (rw == S_CREATE) {
9447 		while ((mi->mi_max_threads != 0 &&
9448 			rp->r_awcount > 2 * mi->mi_max_threads) ||
9449 			rp->r_gcount > 0)
9450 			cv_wait(&rp->r_cv, &rp->r_statelock);
9451 	}
9452 
9453 	/*
9454 	 * If we are getting called as a side effect of an nfs_write()
9455 	 * operation the local file size might not be extended yet.
9456 	 * In this case we want to be able to return pages of zeroes.
9457 	 */
9458 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9459 		NFS4_DEBUG(nfs4_pageio_debug,
9460 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9461 		    "len=%llu, size=%llu, attrsize =%llu", off,
9462 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9463 		mutex_exit(&rp->r_statelock);
9464 		return (EFAULT);		/* beyond EOF */
9465 	}
9466 
9467 	mutex_exit(&rp->r_statelock);
9468 
9469 	if (len <= PAGESIZE) {
9470 		error = nfs4_getapage(vp, off, len, protp, pl, plsz,
9471 		    seg, addr, rw, cr);
9472 		NFS4_DEBUG(nfs4_pageio_debug && error,
9473 			(CE_NOTE, "getpage error %d; off=%lld, "
9474 			"len=%lld", error, off, (u_longlong_t)len));
9475 	} else {
9476 		error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9477 		    pl, plsz, seg, addr, rw, cr);
9478 		NFS4_DEBUG(nfs4_pageio_debug && error,
9479 			(CE_NOTE, "getpages error %d; off=%lld, "
9480 			"len=%lld", error, off, (u_longlong_t)len));
9481 	}
9482 
9483 	switch (error) {
9484 	case NFS_EOF:
9485 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9486 		goto retry;
9487 	case ESTALE:
9488 		nfs4_purge_stale_fh(error, vp, cr);
9489 	}
9490 
9491 	return (error);
9492 }
9493 
9494 /*
9495  * Called from pvn_getpages or nfs4_getpage to get a particular page.
9496  */
9497 /* ARGSUSED */
9498 static int
9499 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9500 	page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9501 	enum seg_rw rw, cred_t *cr)
9502 {
9503 	rnode4_t *rp;
9504 	uint_t bsize;
9505 	struct buf *bp;
9506 	page_t *pp;
9507 	u_offset_t lbn;
9508 	u_offset_t io_off;
9509 	u_offset_t blkoff;
9510 	u_offset_t rablkoff;
9511 	size_t io_len;
9512 	uint_t blksize;
9513 	int error;
9514 	int readahead;
9515 	int readahead_issued = 0;
9516 	int ra_window; /* readahead window */
9517 	page_t *pagefound;
9518 	page_t *savepp;
9519 
9520 	if (curproc->p_zone != VTOMI4(vp)->mi_zone)
9521 		return (EIO);
9522 
9523 	rp = VTOR4(vp);
9524 	ASSERT(!IS_SHADOW(vp, rp));
9525 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9526 
9527 reread:
9528 	bp = NULL;
9529 	pp = NULL;
9530 	pagefound = NULL;
9531 
9532 	if (pl != NULL)
9533 		pl[0] = NULL;
9534 
9535 	error = 0;
9536 	lbn = off / bsize;
9537 	blkoff = lbn * bsize;
9538 
9539 	/*
9540 	 * Queueing up the readahead before doing the synchronous read
9541 	 * results in a significant increase in read throughput because
9542 	 * of the increased parallelism between the async threads and
9543 	 * the process context.
9544 	 */
9545 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9546 	    rw != S_CREATE &&
9547 	    !(vp->v_flag & VNOCACHE)) {
9548 		mutex_enter(&rp->r_statelock);
9549 
9550 		/*
9551 		 * Calculate the number of readaheads to do.
9552 		 * a) No readaheads at offset = 0.
9553 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9554 		 *    window is closed.
9555 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9556 		 *    upon how far the readahead window is open or close.
9557 		 * d) No readaheads if rp->r_nextr is not within the scope
9558 		 *    of the readahead window (random i/o).
9559 		 */
9560 
9561 		if (off == 0)
9562 			readahead = 0;
9563 		else if (blkoff == rp->r_nextr)
9564 			readahead = nfs4_nra;
9565 		else if (rp->r_nextr > blkoff &&
9566 			((ra_window = (rp->r_nextr - blkoff) / bsize)
9567 					<= (nfs4_nra - 1)))
9568 			readahead = nfs4_nra - ra_window;
9569 		else
9570 			readahead = 0;
9571 
9572 		rablkoff = rp->r_nextr;
9573 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9574 			mutex_exit(&rp->r_statelock);
9575 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9576 			    addr + (rablkoff + bsize - off),
9577 			    seg, cr, nfs4_readahead) < 0) {
9578 				mutex_enter(&rp->r_statelock);
9579 				break;
9580 			}
9581 			readahead--;
9582 			rablkoff += bsize;
9583 			/*
9584 			 * Indicate that we did a readahead so
9585 			 * readahead offset is not updated
9586 			 * by the synchronous read below.
9587 			 */
9588 			readahead_issued = 1;
9589 			mutex_enter(&rp->r_statelock);
9590 			/*
9591 			 * set readahead offset to
9592 			 * offset of last async readahead
9593 			 * request.
9594 			 */
9595 			rp->r_nextr = rablkoff;
9596 		}
9597 		mutex_exit(&rp->r_statelock);
9598 	}
9599 
9600 again:
9601 	if ((pagefound = page_exists(vp, off)) == NULL) {
9602 		if (pl == NULL) {
9603 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9604 			    nfs4_readahead);
9605 		} else if (rw == S_CREATE) {
9606 			/*
9607 			 * Block for this page is not allocated, or the offset
9608 			 * is beyond the current allocation size, or we're
9609 			 * allocating a swap slot and the page was not found,
9610 			 * so allocate it and return a zero page.
9611 			 */
9612 			if ((pp = page_create_va(vp, off,
9613 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9614 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9615 			io_len = PAGESIZE;
9616 			mutex_enter(&rp->r_statelock);
9617 			rp->r_nextr = off + PAGESIZE;
9618 			mutex_exit(&rp->r_statelock);
9619 		} else {
9620 			/*
9621 			 * Need to go to server to get a block
9622 			 */
9623 			mutex_enter(&rp->r_statelock);
9624 			if (blkoff < rp->r_size &&
9625 			    blkoff + bsize > rp->r_size) {
9626 				/*
9627 				 * If less than a block left in
9628 				 * file read less than a block.
9629 				 */
9630 				if (rp->r_size <= off) {
9631 					/*
9632 					 * Trying to access beyond EOF,
9633 					 * set up to get at least one page.
9634 					 */
9635 					blksize = off + PAGESIZE - blkoff;
9636 				} else
9637 					blksize = rp->r_size - blkoff;
9638 			} else if ((off == 0) ||
9639 				(off != rp->r_nextr && !readahead_issued)) {
9640 				blksize = PAGESIZE;
9641 				blkoff = off; /* block = page here */
9642 			} else
9643 				blksize = bsize;
9644 			mutex_exit(&rp->r_statelock);
9645 
9646 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9647 			    &io_len, blkoff, blksize, 0);
9648 
9649 			/*
9650 			 * Some other thread has entered the page,
9651 			 * so just use it.
9652 			 */
9653 			if (pp == NULL)
9654 				goto again;
9655 
9656 			/*
9657 			 * Now round the request size up to page boundaries.
9658 			 * This ensures that the entire page will be
9659 			 * initialized to zeroes if EOF is encountered.
9660 			 */
9661 			io_len = ptob(btopr(io_len));
9662 
9663 			bp = pageio_setup(pp, io_len, vp, B_READ);
9664 			ASSERT(bp != NULL);
9665 
9666 			/*
9667 			 * pageio_setup should have set b_addr to 0.  This
9668 			 * is correct since we want to do I/O on a page
9669 			 * boundary.  bp_mapin will use this addr to calculate
9670 			 * an offset, and then set b_addr to the kernel virtual
9671 			 * address it allocated for us.
9672 			 */
9673 			ASSERT(bp->b_un.b_addr == 0);
9674 
9675 			bp->b_edev = 0;
9676 			bp->b_dev = 0;
9677 			bp->b_lblkno = lbtodb(io_off);
9678 			bp->b_file = vp;
9679 			bp->b_offset = (offset_t)off;
9680 			bp_mapin(bp);
9681 
9682 			/*
9683 			 * If doing a write beyond what we believe is EOF,
9684 			 * don't bother trying to read the pages from the
9685 			 * server, we'll just zero the pages here.  We
9686 			 * don't check that the rw flag is S_WRITE here
9687 			 * because some implementations may attempt a
9688 			 * read access to the buffer before copying data.
9689 			 */
9690 			mutex_enter(&rp->r_statelock);
9691 			if (io_off >= rp->r_size && seg == segkmap) {
9692 				mutex_exit(&rp->r_statelock);
9693 				bzero(bp->b_un.b_addr, io_len);
9694 			} else {
9695 				mutex_exit(&rp->r_statelock);
9696 				error = nfs4_bio(bp, NULL, cr, FALSE);
9697 			}
9698 
9699 			/*
9700 			 * Unmap the buffer before freeing it.
9701 			 */
9702 			bp_mapout(bp);
9703 			pageio_done(bp);
9704 
9705 			savepp = pp;
9706 			do {
9707 				pp->p_fsdata = C_NOCOMMIT;
9708 			} while ((pp = pp->p_next) != savepp);
9709 
9710 			if (error == NFS_EOF) {
9711 				/*
9712 				 * If doing a write system call just return
9713 				 * zeroed pages, else user tried to get pages
9714 				 * beyond EOF, return error.  We don't check
9715 				 * that the rw flag is S_WRITE here because
9716 				 * some implementations may attempt a read
9717 				 * access to the buffer before copying data.
9718 				 */
9719 				if (seg == segkmap)
9720 					error = 0;
9721 				else
9722 					error = EFAULT;
9723 			}
9724 
9725 			if (!readahead_issued && !error) {
9726 				mutex_enter(&rp->r_statelock);
9727 				rp->r_nextr = io_off + io_len;
9728 				mutex_exit(&rp->r_statelock);
9729 			}
9730 		}
9731 	}
9732 
9733 out:
9734 	if (pl == NULL)
9735 		return (error);
9736 
9737 	if (error) {
9738 		if (pp != NULL)
9739 			pvn_read_done(pp, B_ERROR);
9740 		return (error);
9741 	}
9742 
9743 	if (pagefound) {
9744 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
9745 
9746 		/*
9747 		 * Page exists in the cache, acquire the appropriate lock.
9748 		 * If this fails, start all over again.
9749 		 */
9750 		if ((pp = page_lookup(vp, off, se)) == NULL) {
9751 #ifdef DEBUG
9752 			nfs4_lostpage++;
9753 #endif
9754 			goto reread;
9755 		}
9756 		pl[0] = pp;
9757 		pl[1] = NULL;
9758 		return (0);
9759 	}
9760 
9761 	if (pp != NULL)
9762 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
9763 
9764 	return (error);
9765 }
9766 
9767 static void
9768 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
9769 	cred_t *cr)
9770 {
9771 	int error;
9772 	page_t *pp;
9773 	u_offset_t io_off;
9774 	size_t io_len;
9775 	struct buf *bp;
9776 	uint_t bsize, blksize;
9777 	rnode4_t *rp = VTOR4(vp);
9778 	page_t *savepp;
9779 
9780 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
9781 
9782 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9783 
9784 	mutex_enter(&rp->r_statelock);
9785 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
9786 		/*
9787 		 * If less than a block left in file read less
9788 		 * than a block.
9789 		 */
9790 		blksize = rp->r_size - blkoff;
9791 	} else
9792 		blksize = bsize;
9793 	mutex_exit(&rp->r_statelock);
9794 
9795 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
9796 	    &io_off, &io_len, blkoff, blksize, 1);
9797 	/*
9798 	 * The isra flag passed to the kluster function is 1, we may have
9799 	 * gotten a return value of NULL for a variety of reasons (# of free
9800 	 * pages < minfree, someone entered the page on the vnode etc). In all
9801 	 * cases, we want to punt on the readahead.
9802 	 */
9803 	if (pp == NULL)
9804 		return;
9805 
9806 	/*
9807 	 * Now round the request size up to page boundaries.
9808 	 * This ensures that the entire page will be
9809 	 * initialized to zeroes if EOF is encountered.
9810 	 */
9811 	io_len = ptob(btopr(io_len));
9812 
9813 	bp = pageio_setup(pp, io_len, vp, B_READ);
9814 	ASSERT(bp != NULL);
9815 
9816 	/*
9817 	 * pageio_setup should have set b_addr to 0.  This is correct since
9818 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
9819 	 * to calculate an offset, and then set b_addr to the kernel virtual
9820 	 * address it allocated for us.
9821 	 */
9822 	ASSERT(bp->b_un.b_addr == 0);
9823 
9824 	bp->b_edev = 0;
9825 	bp->b_dev = 0;
9826 	bp->b_lblkno = lbtodb(io_off);
9827 	bp->b_file = vp;
9828 	bp->b_offset = (offset_t)blkoff;
9829 	bp_mapin(bp);
9830 
9831 	/*
9832 	 * If doing a write beyond what we believe is EOF, don't bother trying
9833 	 * to read the pages from the server, we'll just zero the pages here.
9834 	 * We don't check that the rw flag is S_WRITE here because some
9835 	 * implementations may attempt a read access to the buffer before
9836 	 * copying data.
9837 	 */
9838 	mutex_enter(&rp->r_statelock);
9839 	if (io_off >= rp->r_size && seg == segkmap) {
9840 		mutex_exit(&rp->r_statelock);
9841 		bzero(bp->b_un.b_addr, io_len);
9842 		error = 0;
9843 	} else {
9844 		mutex_exit(&rp->r_statelock);
9845 		error = nfs4_bio(bp, NULL, cr, TRUE);
9846 		if (error == NFS_EOF)
9847 			error = 0;
9848 	}
9849 
9850 	/*
9851 	 * Unmap the buffer before freeing it.
9852 	 */
9853 	bp_mapout(bp);
9854 	pageio_done(bp);
9855 
9856 	savepp = pp;
9857 	do {
9858 		pp->p_fsdata = C_NOCOMMIT;
9859 	} while ((pp = pp->p_next) != savepp);
9860 
9861 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
9862 
9863 	/*
9864 	 * In case of error set readahead offset
9865 	 * to the lowest offset.
9866 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
9867 	 */
9868 	if (error && rp->r_nextr > io_off) {
9869 		mutex_enter(&rp->r_statelock);
9870 		if (rp->r_nextr > io_off)
9871 			rp->r_nextr = io_off;
9872 		mutex_exit(&rp->r_statelock);
9873 	}
9874 }
9875 
9876 /*
9877  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
9878  * If len == 0, do from off to EOF.
9879  *
9880  * The normal cases should be len == 0 && off == 0 (entire vp list) or
9881  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
9882  * (from pageout).
9883  */
9884 static int
9885 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr)
9886 {
9887 	int error;
9888 	rnode4_t *rp;
9889 
9890 	ASSERT(cr != NULL);
9891 
9892 	if (!(flags & B_ASYNC) && curproc->p_zone != VTOMI4(vp)->mi_zone)
9893 		return (EIO);
9894 
9895 	rp = VTOR4(vp);
9896 	if (IS_SHADOW(vp, rp))
9897 		vp = RTOV4(rp);
9898 
9899 	/*
9900 	 * XXX - Why should this check be made here?
9901 	 */
9902 	if (vp->v_flag & VNOMAP)
9903 		return (ENOSYS);
9904 
9905 	if (len == 0 && !(flags & B_INVAL) &&
9906 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
9907 		return (0);
9908 
9909 	mutex_enter(&rp->r_statelock);
9910 	rp->r_count++;
9911 	mutex_exit(&rp->r_statelock);
9912 	error = nfs4_putpages(vp, off, len, flags, cr);
9913 	mutex_enter(&rp->r_statelock);
9914 	rp->r_count--;
9915 	cv_broadcast(&rp->r_cv);
9916 	mutex_exit(&rp->r_statelock);
9917 
9918 	return (error);
9919 }
9920 
9921 /*
9922  * Write out a single page, possibly klustering adjacent dirty pages.
9923  */
9924 int
9925 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
9926 	int flags, cred_t *cr)
9927 {
9928 	u_offset_t io_off;
9929 	u_offset_t lbn_off;
9930 	u_offset_t lbn;
9931 	size_t io_len;
9932 	uint_t bsize;
9933 	int error;
9934 	rnode4_t *rp;
9935 
9936 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
9937 	ASSERT(pp != NULL);
9938 	ASSERT(cr != NULL);
9939 	ASSERT((flags & B_ASYNC) || curproc->p_zone == VTOMI4(vp)->mi_zone);
9940 
9941 	rp = VTOR4(vp);
9942 	ASSERT(rp->r_count > 0);
9943 	ASSERT(!IS_SHADOW(vp, rp));
9944 
9945 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9946 	lbn = pp->p_offset / bsize;
9947 	lbn_off = lbn * bsize;
9948 
9949 	/*
9950 	 * Find a kluster that fits in one block, or in
9951 	 * one page if pages are bigger than blocks.  If
9952 	 * there is less file space allocated than a whole
9953 	 * page, we'll shorten the i/o request below.
9954 	 */
9955 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
9956 	    roundup(bsize, PAGESIZE), flags);
9957 
9958 	/*
9959 	 * pvn_write_kluster shouldn't have returned a page with offset
9960 	 * behind the original page we were given.  Verify that.
9961 	 */
9962 	ASSERT((pp->p_offset / bsize) >= lbn);
9963 
9964 	/*
9965 	 * Now pp will have the list of kept dirty pages marked for
9966 	 * write back.  It will also handle invalidation and freeing
9967 	 * of pages that are not dirty.  Check for page length rounding
9968 	 * problems.
9969 	 */
9970 	if (io_off + io_len > lbn_off + bsize) {
9971 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
9972 		io_len = lbn_off + bsize - io_off;
9973 	}
9974 	/*
9975 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
9976 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
9977 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
9978 	 * progress and the r_size has not been made consistent with the
9979 	 * new size of the file. When the uiomove() completes the r_size is
9980 	 * updated and the R4MODINPROGRESS flag is cleared.
9981 	 *
9982 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
9983 	 * consistent value of r_size. Without this handshaking, it is
9984 	 * possible that nfs4_bio() picks  up the old value of r_size
9985 	 * before the uiomove() in writerp4() completes. This will result
9986 	 * in the write through nfs4_bio() being dropped.
9987 	 *
9988 	 * More precisely, there is a window between the time the uiomove()
9989 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
9990 	 * operation intervenes in this window, the page will be picked up,
9991 	 * because it is dirty (it will be unlocked, unless it was
9992 	 * pagecreate'd). When the page is picked up as dirty, the dirty
9993 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
9994 	 * checked. This will still be the old size. Therefore the page will
9995 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
9996 	 * the page will be found to be clean and the write will be dropped.
9997 	 */
9998 	if (rp->r_flags & R4MODINPROGRESS) {
9999 		mutex_enter(&rp->r_statelock);
10000 		if ((rp->r_flags & R4MODINPROGRESS) &&
10001 		    rp->r_modaddr + MAXBSIZE > io_off &&
10002 		    rp->r_modaddr < io_off + io_len) {
10003 			page_t *plist;
10004 			/*
10005 			 * A write is in progress for this region of the file.
10006 			 * If we did not detect R4MODINPROGRESS here then this
10007 			 * path through nfs_putapage() would eventually go to
10008 			 * nfs4_bio() and may not write out all of the data
10009 			 * in the pages. We end up losing data. So we decide
10010 			 * to set the modified bit on each page in the page
10011 			 * list and mark the rnode with R4DIRTY. This write
10012 			 * will be restarted at some later time.
10013 			 */
10014 			plist = pp;
10015 			while (plist != NULL) {
10016 				pp = plist;
10017 				page_sub(&plist, pp);
10018 				hat_setmod(pp);
10019 				page_io_unlock(pp);
10020 				page_unlock(pp);
10021 			}
10022 			rp->r_flags |= R4DIRTY;
10023 			mutex_exit(&rp->r_statelock);
10024 			if (offp)
10025 				*offp = io_off;
10026 			if (lenp)
10027 				*lenp = io_len;
10028 			return (0);
10029 		}
10030 		mutex_exit(&rp->r_statelock);
10031 	}
10032 
10033 	if (flags & B_ASYNC) {
10034 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10035 		    nfs4_sync_putapage);
10036 	} else
10037 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10038 
10039 	if (offp)
10040 		*offp = io_off;
10041 	if (lenp)
10042 		*lenp = io_len;
10043 	return (error);
10044 }
10045 
10046 static int
10047 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10048 	int flags, cred_t *cr)
10049 {
10050 	int error;
10051 	rnode4_t *rp;
10052 
10053 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
10054 
10055 	flags |= B_WRITE;
10056 
10057 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10058 
10059 	rp = VTOR4(vp);
10060 
10061 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10062 	    error == EACCES) &&
10063 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10064 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10065 			mutex_enter(&rp->r_statelock);
10066 			rp->r_flags |= R4OUTOFSPACE;
10067 			mutex_exit(&rp->r_statelock);
10068 		}
10069 		flags |= B_ERROR;
10070 		pvn_write_done(pp, flags);
10071 		/*
10072 		 * If this was not an async thread, then try again to
10073 		 * write out the pages, but this time, also destroy
10074 		 * them whether or not the write is successful.  This
10075 		 * will prevent memory from filling up with these
10076 		 * pages and destroying them is the only alternative
10077 		 * if they can't be written out.
10078 		 *
10079 		 * Don't do this if this is an async thread because
10080 		 * when the pages are unlocked in pvn_write_done,
10081 		 * some other thread could have come along, locked
10082 		 * them, and queued for an async thread.  It would be
10083 		 * possible for all of the async threads to be tied
10084 		 * up waiting to lock the pages again and they would
10085 		 * all already be locked and waiting for an async
10086 		 * thread to handle them.  Deadlock.
10087 		 */
10088 		if (!(flags & B_ASYNC)) {
10089 			error = nfs4_putpage(vp, io_off, io_len,
10090 			    B_INVAL | B_FORCE, cr);
10091 		}
10092 	} else {
10093 		if (error)
10094 			flags |= B_ERROR;
10095 		else if (rp->r_flags & R4OUTOFSPACE) {
10096 			mutex_enter(&rp->r_statelock);
10097 			rp->r_flags &= ~R4OUTOFSPACE;
10098 			mutex_exit(&rp->r_statelock);
10099 		}
10100 		pvn_write_done(pp, flags);
10101 		if (freemem < desfree)
10102 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10103 					NFS4_WRITE_NOWAIT);
10104 	}
10105 
10106 	return (error);
10107 }
10108 
10109 #ifdef DEBUG
10110 int nfs4_force_open_before_mmap = 0;
10111 #endif
10112 
10113 static int
10114 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10115 	size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr)
10116 {
10117 	struct segvn_crargs vn_a;
10118 	int error = 0;
10119 	rnode4_t *rp = VTOR4(vp);
10120 	mntinfo4_t *mi = VTOMI4(vp);
10121 
10122 	if (curproc->p_zone != VTOMI4(vp)->mi_zone)
10123 		return (EIO);
10124 
10125 	if (vp->v_flag & VNOMAP)
10126 		return (ENOSYS);
10127 
10128 	if (off < 0 || (off + len) < 0)
10129 		return (ENXIO);
10130 
10131 	if (vp->v_type != VREG)
10132 		return (ENODEV);
10133 
10134 	/*
10135 	 * If the file is delegated to the client don't do anything.
10136 	 * If the file is not delegated, then validate the data cache.
10137 	 */
10138 	mutex_enter(&rp->r_statev4_lock);
10139 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10140 		mutex_exit(&rp->r_statev4_lock);
10141 		error = nfs4_validate_caches(vp, cr);
10142 		if (error)
10143 			return (error);
10144 	} else {
10145 		mutex_exit(&rp->r_statev4_lock);
10146 	}
10147 
10148 	/*
10149 	 * Check to see if the vnode is currently marked as not cachable.
10150 	 * This means portions of the file are locked (through VOP_FRLOCK).
10151 	 * In this case the map request must be refused.  We use
10152 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10153 	 */
10154 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
10155 		return (EINTR);
10156 
10157 	if (vp->v_flag & VNOCACHE) {
10158 		error = EAGAIN;
10159 		goto done;
10160 	}
10161 
10162 	/*
10163 	 * Don't allow concurrent locks and mapping if mandatory locking is
10164 	 * enabled.
10165 	 */
10166 	if (flk_has_remote_locks(vp)) {
10167 		struct vattr va;
10168 		va.va_mask = AT_MODE;
10169 		error = nfs4getattr(vp, &va, cr);
10170 		if (error != 0)
10171 			goto done;
10172 		if (MANDLOCK(vp, va.va_mode)) {
10173 			error = EAGAIN;
10174 			goto done;
10175 		}
10176 	}
10177 
10178 	/*
10179 	 * It is possible that the rnode has a lost lock request that we
10180 	 * are still trying to recover, and that the request conflicts with
10181 	 * this map request.
10182 	 *
10183 	 * An alternative approach would be for nfs4_safemap() to consider
10184 	 * queued lock requests when deciding whether to set or clear
10185 	 * VNOCACHE.  This would require the frlock code path to call
10186 	 * nfs4_safemap() after enqueing a lost request.
10187 	 */
10188 	if (nfs4_map_lost_lock_conflict(vp)) {
10189 		error = EAGAIN;
10190 		goto done;
10191 	}
10192 
10193 	as_rangelock(as);
10194 	if (!(flags & MAP_FIXED)) {
10195 		map_addr(addrp, len, off, 1, flags);
10196 		if (*addrp == NULL) {
10197 			as_rangeunlock(as);
10198 			error = ENOMEM;
10199 			goto done;
10200 		}
10201 	} else {
10202 		/*
10203 		 * User specified address - blow away any previous mappings
10204 		 */
10205 		(void) as_unmap(as, *addrp, len);
10206 	}
10207 
10208 	if (vp->v_type == VREG) {
10209 		/*
10210 		 * We need to retrieve the open stream
10211 		 */
10212 		nfs4_open_stream_t	*osp = NULL;
10213 		nfs4_open_owner_t	*oop = NULL;
10214 
10215 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10216 		if (oop != NULL) {
10217 			/* returns with 'os_sync_lock' held */
10218 			osp = find_open_stream(oop, rp);
10219 			open_owner_rele(oop);
10220 		}
10221 		if (osp == NULL) {
10222 #ifdef DEBUG
10223 			if (nfs4_force_open_before_mmap) {
10224 				error = EIO;
10225 				goto done;
10226 			}
10227 #endif
10228 			/* returns with 'os_sync_lock' held */
10229 			osp = open_and_get_osp(vp, cr, mi);
10230 			if (osp == NULL) {
10231 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10232 				    "nfs4_map: we tried to OPEN the file "
10233 				    "but again no osp, so fail with EIO"));
10234 				error = EIO;
10235 				goto done;
10236 			}
10237 		}
10238 
10239 		if (osp->os_failed_reopen) {
10240 			mutex_exit(&osp->os_sync_lock);
10241 			open_stream_rele(osp, rp);
10242 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10243 			    "nfs4_map: os_failed_reopen set on "
10244 			    "osp %p, cr %p, rp %s", (void *)osp,
10245 			    (void *)cr, rnode4info(rp)));
10246 			error = EIO;
10247 			goto done;
10248 		}
10249 		mutex_exit(&osp->os_sync_lock);
10250 		open_stream_rele(osp, rp);
10251 	}
10252 
10253 	vn_a.vp = vp;
10254 	vn_a.offset = off;
10255 	vn_a.type = (flags & MAP_TYPE);
10256 	vn_a.prot = (uchar_t)prot;
10257 	vn_a.maxprot = (uchar_t)maxprot;
10258 	vn_a.flags = (flags & ~MAP_TYPE);
10259 	vn_a.cred = cr;
10260 	vn_a.amp = NULL;
10261 	vn_a.szc = 0;
10262 	vn_a.lgrp_mem_policy_flags = 0;
10263 
10264 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10265 	as_rangeunlock(as);
10266 
10267 done:
10268 	nfs_rw_exit(&rp->r_lkserlock);
10269 	return (error);
10270 }
10271 
10272 /*
10273  * We're most likely dealing with a kernel module that likes to READ
10274  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10275  * officially OPEN the file to create the necessary client state
10276  * for bookkeeping of os_mmap_read/write counts.
10277  *
10278  * Since VOP_MAP only passes in a pointer to the vnode rather than
10279  * a double pointer, we can't handle the case where nfs4open_otw()
10280  * returns a different vnode than the one passed into VOP_MAP (since
10281  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10282  * we return NULL and let nfs4_map() fail.  Note: the only case where
10283  * this should happen is if the file got removed and replaced with the
10284  * same name on the server (in addition to the fact that we're trying
10285  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10286  */
10287 static nfs4_open_stream_t *
10288 open_and_get_osp(vnode_t *map_vp, cred_t *cr, mntinfo4_t *mi)
10289 {
10290 	rnode4_t		*rp, *drp;
10291 	vnode_t			*dvp, *open_vp;
10292 	char			*file_name;
10293 	int			just_created;
10294 	nfs4_sharedfh_t		*sfh;
10295 	nfs4_open_stream_t	*osp;
10296 	nfs4_open_owner_t	*oop;
10297 
10298 	open_vp = map_vp;
10299 	sfh = (open_vp->v_flag & VROOT) ? mi->mi_srvparentfh :
10300 				VTOSV(open_vp)->sv_dfh;
10301 	drp = r4find_unlocked(sfh, open_vp->v_vfsp);
10302 	if (!drp)
10303 		return (NULL);
10304 
10305 	file_name = fn_name(VTOSV(open_vp)->sv_name);
10306 
10307 	rp = VTOR4(open_vp);
10308 	dvp = RTOV4(drp);
10309 	mutex_enter(&rp->r_statev4_lock);
10310 	if (rp->created_v4) {
10311 		rp->created_v4 = 0;
10312 		dnlc_update(dvp, file_name, open_vp);
10313 		/* This is needed so we don't bump the open ref count */
10314 		just_created = 1;
10315 	} else {
10316 		just_created = 0;
10317 	}
10318 	mutex_exit(&rp->r_statev4_lock);
10319 
10320 	VN_HOLD(map_vp);
10321 
10322 	if (nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10323 	    just_created)) {
10324 		kmem_free(file_name, MAXNAMELEN);
10325 		VN_RELE(dvp);
10326 		VN_RELE(map_vp);
10327 		return (NULL);
10328 	}
10329 
10330 	kmem_free(file_name, MAXNAMELEN);
10331 	VN_RELE(dvp);
10332 
10333 	/*
10334 	 * If nfs4open_otw() returned a different vnode then "undo"
10335 	 * the open and return failure to the caller.
10336 	 */
10337 	if (!VN_CMP(open_vp, map_vp)) {
10338 		nfs4_error_t e;
10339 
10340 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10341 		    "open returned a different vnode"));
10342 		/*
10343 		 * If there's an error, ignore it,
10344 		 * and let VOP_INACTIVE handle it.
10345 		 */
10346 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10347 				CLOSE_NORM, 0, 0, 0);
10348 		VN_RELE(map_vp);
10349 		return (NULL);
10350 	}
10351 
10352 	VN_RELE(map_vp);
10353 
10354 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10355 	if (!oop) {
10356 		nfs4_error_t e;
10357 
10358 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10359 		    "no open owner"));
10360 		/*
10361 		 * If there's an error, ignore it,
10362 		 * and let VOP_INACTIVE handle it.
10363 		 */
10364 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10365 				CLOSE_NORM, 0, 0, 0);
10366 		return (NULL);
10367 	}
10368 	osp = find_open_stream(oop, rp);
10369 	open_owner_rele(oop);
10370 	return (osp);
10371 }
10372 
10373 /*
10374  * Please be aware that when this function is called, the address space write
10375  * a_lock is held.  Do not put over the wire calls in this function.
10376  */
10377 /* ARGSUSED */
10378 static int
10379 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10380 	size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr)
10381 {
10382 	rnode4_t		*rp;
10383 	int			error = 0;
10384 	mntinfo4_t		*mi;
10385 
10386 	mi = VTOMI4(vp);
10387 	rp = VTOR4(vp);
10388 
10389 	if (curproc->p_zone != mi->mi_zone)
10390 		return (EIO);
10391 	if (vp->v_flag & VNOMAP)
10392 		return (ENOSYS);
10393 
10394 	/*
10395 	 * Need to hold rwlock while incrementing the mapcnt so that
10396 	 * mmap'ing can be serialized with writes so that the caching
10397 	 * can be handled correctly.
10398 	 *
10399 	 * Don't need to update the open stream first, since this
10400 	 * mmap can't add any additional share access that isn't
10401 	 * already contained in the open stream (for the case where we
10402 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10403 	 * take into account os_mmap_read[write] counts).
10404 	 */
10405 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR(vp)))
10406 		return (EINTR);
10407 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10408 	nfs_rw_exit(&rp->r_rwlock);
10409 
10410 	if (vp->v_type == VREG) {
10411 		/*
10412 		 * We need to retrieve the open stream and update the counts.
10413 		 * If there is no open stream here, something is wrong.
10414 		 */
10415 		nfs4_open_stream_t	*osp = NULL;
10416 		nfs4_open_owner_t	*oop = NULL;
10417 
10418 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10419 		if (oop != NULL) {
10420 			/* returns with 'os_sync_lock' held */
10421 			osp = find_open_stream(oop, rp);
10422 			open_owner_rele(oop);
10423 		}
10424 		if (osp == NULL) {
10425 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10426 			    "nfs4_addmap: we should have an osp"
10427 			    "but we don't, so fail with EIO"));
10428 			error = EIO;
10429 			goto out;
10430 		}
10431 
10432 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10433 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10434 
10435 		/*
10436 		 * Update the map count in the open stream.
10437 		 * This is necessary in the case where we
10438 		 * open/mmap/close/, then the server reboots, and we
10439 		 * attempt to reopen.  If the mmap doesn't add share
10440 		 * access then we send an invalid reopen with
10441 		 * access = NONE.
10442 		 *
10443 		 * We need to specifically check each PROT_* so a mmap
10444 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10445 		 * read and write access.  A simple comparison of prot
10446 		 * to ~PROT_WRITE to determine read access is insufficient
10447 		 * since prot can be |= with PROT_USER, etc.
10448 		 */
10449 
10450 		/*
10451 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10452 		 */
10453 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10454 			osp->os_mmap_write += btopr(len);
10455 		if (maxprot & PROT_READ)
10456 			osp->os_mmap_read += btopr(len);
10457 		if (maxprot & PROT_EXEC)
10458 			osp->os_mmap_read += btopr(len);
10459 		/*
10460 		 * Ensure that os_mmap_read gets incremented, even if
10461 		 * maxprot were to look like PROT_NONE.
10462 		 */
10463 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10464 		    !(maxprot & PROT_EXEC))
10465 			osp->os_mmap_read += btopr(len);
10466 		osp->os_mapcnt += btopr(len);
10467 		mutex_exit(&osp->os_sync_lock);
10468 		open_stream_rele(osp, rp);
10469 	}
10470 
10471 out:
10472 	/*
10473 	 * If we got an error, then undo our
10474 	 * incrementing of 'r_mapcnt'.
10475 	 */
10476 
10477 	if (error) {
10478 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10479 		ASSERT(rp->r_mapcnt >= 0);
10480 	}
10481 	return (error);
10482 }
10483 
10484 static int
10485 nfs4_cmp(vnode_t *vp1, vnode_t *vp2)
10486 {
10487 
10488 	return (VTOR4(vp1) == VTOR4(vp2));
10489 }
10490 
10491 static int
10492 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10493 	offset_t offset, struct flk_callback *flk_cbp, cred_t *cr)
10494 {
10495 	int rc;
10496 	u_offset_t start, end;
10497 	rnode4_t *rp;
10498 	int error = 0, intr = INTR4(vp);
10499 	nfs4_error_t e;
10500 
10501 	if (curproc->p_zone != VTOMI4(vp)->mi_zone)
10502 		return (EIO);
10503 
10504 	/* check for valid cmd parameter */
10505 	if (cmd != F_GETLK && cmd != F_SETLK && cmd != F_SETLKW)
10506 		return (EINVAL);
10507 
10508 	/* Verify l_type. */
10509 	switch (bfp->l_type) {
10510 	case F_RDLCK:
10511 		if (cmd != F_GETLK && !(flag & FREAD))
10512 			return (EBADF);
10513 		break;
10514 	case F_WRLCK:
10515 		if (cmd != F_GETLK && !(flag & FWRITE))
10516 			return (EBADF);
10517 		break;
10518 	case F_UNLCK:
10519 		intr = 0;
10520 		break;
10521 
10522 	default:
10523 		return (EINVAL);
10524 	}
10525 
10526 	/* check the validity of the lock range */
10527 	if (rc = flk_convert_lock_data(vp, bfp, &start, &end, offset))
10528 		return (rc);
10529 	if (rc = flk_check_lock_data(start, end, MAXEND))
10530 		return (rc);
10531 
10532 	/*
10533 	 * If the filesystem is mounted using local locking, pass the
10534 	 * request off to the local locking code.
10535 	 */
10536 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10537 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10538 			/*
10539 			 * For complete safety, we should be holding
10540 			 * r_lkserlock.  However, we can't call
10541 			 * nfs4_safelock and then fs_frlock while
10542 			 * holding r_lkserlock, so just invoke
10543 			 * nfs4_safelock and expect that this will
10544 			 * catch enough of the cases.
10545 			 */
10546 			if (!nfs4_safelock(vp, bfp, cr))
10547 				return (EAGAIN);
10548 		}
10549 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr));
10550 	}
10551 
10552 	rp = VTOR4(vp);
10553 
10554 	/*
10555 	 * Check whether the given lock request can proceed, given the
10556 	 * current file mappings.
10557 	 */
10558 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr))
10559 		return (EINTR);
10560 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10561 		if (!nfs4_safelock(vp, bfp, cr)) {
10562 			rc = EAGAIN;
10563 			goto done;
10564 		}
10565 	}
10566 
10567 	/*
10568 	 * Flush the cache after waiting for async I/O to finish.  For new
10569 	 * locks, this is so that the process gets the latest bits from the
10570 	 * server.  For unlocks, this is so that other clients see the
10571 	 * latest bits once the file has been unlocked.  If currently dirty
10572 	 * pages can't be flushed, then don't allow a lock to be set.  But
10573 	 * allow unlocks to succeed, to avoid having orphan locks on the
10574 	 * server.
10575 	 */
10576 	if (cmd != F_GETLK) {
10577 		mutex_enter(&rp->r_statelock);
10578 		while (rp->r_count > 0) {
10579 		    if (intr) {
10580 			klwp_t *lwp = ttolwp(curthread);
10581 
10582 			if (lwp != NULL)
10583 				lwp->lwp_nostop++;
10584 			if (cv_wait_sig(&rp->r_cv, &rp->r_statelock) == 0) {
10585 				if (lwp != NULL)
10586 					lwp->lwp_nostop--;
10587 				rc = EINTR;
10588 				break;
10589 			}
10590 			if (lwp != NULL)
10591 				lwp->lwp_nostop--;
10592 		    } else
10593 			cv_wait(&rp->r_cv, &rp->r_statelock);
10594 		}
10595 		mutex_exit(&rp->r_statelock);
10596 		if (rc != 0)
10597 			goto done;
10598 		error = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr);
10599 		if (error) {
10600 			if (error == ENOSPC || error == EDQUOT) {
10601 				mutex_enter(&rp->r_statelock);
10602 				if (!rp->r_error)
10603 					rp->r_error = error;
10604 				mutex_exit(&rp->r_statelock);
10605 			}
10606 			if (bfp->l_type != F_UNLCK) {
10607 				rc = ENOLCK;
10608 				goto done;
10609 			}
10610 		}
10611 	}
10612 
10613 	/*
10614 	 * Call the lock manager to do the real work of contacting
10615 	 * the server and obtaining the lock.
10616 	 */
10617 
10618 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, flag, offset,
10619 		cr, &e, NULL, NULL);
10620 	rc = e.error;
10621 
10622 	if (rc == 0)
10623 		nfs4_lockcompletion(vp, cmd);
10624 
10625 done:
10626 	nfs_rw_exit(&rp->r_lkserlock);
10627 
10628 	return (rc);
10629 }
10630 
10631 /*
10632  * Free storage space associated with the specified vnode.  The portion
10633  * to be freed is specified by bfp->l_start and bfp->l_len (already
10634  * normalized to a "whence" of 0).
10635  *
10636  * This is an experimental facility whose continued existence is not
10637  * guaranteed.  Currently, we only support the special case
10638  * of l_len == 0, meaning free to end of file.
10639  */
10640 /* ARGSUSED */
10641 static int
10642 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10643 	offset_t offset, cred_t *cr, caller_context_t *ct)
10644 {
10645 	int error;
10646 
10647 	if (curproc->p_zone != VTOMI4(vp)->mi_zone)
10648 		return (EIO);
10649 	ASSERT(vp->v_type == VREG);
10650 	if (cmd != F_FREESP)
10651 		return (EINVAL);
10652 
10653 	error = convoff(vp, bfp, 0, offset);
10654 	if (!error) {
10655 		ASSERT(bfp->l_start >= 0);
10656 		if (bfp->l_len == 0) {
10657 			struct vattr va;
10658 
10659 			va.va_mask = AT_SIZE;
10660 			va.va_size = bfp->l_start;
10661 			error = nfs4setattr(vp, &va, 0, cr, NULL);
10662 		} else
10663 			error = EINVAL;
10664 	}
10665 
10666 	return (error);
10667 }
10668 
10669 /* ARGSUSED */
10670 static int
10671 nfs4_realvp(vnode_t *vp, vnode_t **vpp)
10672 {
10673 	return (EINVAL);
10674 }
10675 
10676 /*
10677  * Setup and add an address space callback to do the work of the delmap call.
10678  * The callback will (and must be) deleted in the actual callback function.
10679  *
10680  * This is done in order to take care of the problem that we have with holding
10681  * the address space's a_lock for a long period of time (e.g. if the NFS server
10682  * is down).  Callbacks will be executed in the address space code while the
10683  * a_lock is not held.  Holding the address space's a_lock causes things such
10684  * as ps and fork to hang because they are trying to acquire this lock as well.
10685  */
10686 /* ARGSUSED */
10687 static int
10688 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10689 	size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr)
10690 {
10691 	int			caller_found;
10692 	int			error;
10693 	rnode4_t		*rp;
10694 	nfs4_delmap_args_t	*dmapp;
10695 	nfs4_delmapcall_t	*delmap_call;
10696 
10697 	if (vp->v_flag & VNOMAP)
10698 		return (ENOSYS);
10699 
10700 	/*
10701 	 * A process may not change zones if it has NFS pages mmap'ed
10702 	 * in, so we can't legitimately get here from the wrong zone.
10703 	 */
10704 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
10705 
10706 	rp = VTOR4(vp);
10707 
10708 	/*
10709 	 * The way that the address space of this process deletes its mapping
10710 	 * of this file is via the following call chains:
10711 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10712 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10713 	 *
10714 	 * With the use of address space callbacks we are allowed to drop the
10715 	 * address space lock, a_lock, while executing the NFS operations that
10716 	 * need to go over the wire.  Returning EAGAIN to the caller of this
10717 	 * function is what drives the execution of the callback that we add
10718 	 * below.  The callback will be executed by the address space code
10719 	 * after dropping the a_lock.  When the callback is finished, since
10720 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
10721 	 * is called again on the same segment to finish the rest of the work
10722 	 * that needs to happen during unmapping.
10723 	 *
10724 	 * This action of calling back into the segment driver causes
10725 	 * nfs4_delmap() to get called again, but since the callback was
10726 	 * already executed at this point, it already did the work and there
10727 	 * is nothing left for us to do.
10728 	 *
10729 	 * To Summarize:
10730 	 * - The first time nfs4_delmap is called by the current thread is when
10731 	 * we add the caller associated with this delmap to the delmap caller
10732 	 * list, add the callback, and return EAGAIN.
10733 	 * - The second time in this call chain when nfs4_delmap is called we
10734 	 * will find this caller in the delmap caller list and realize there
10735 	 * is no more work to do thus removing this caller from the list and
10736 	 * returning the error that was set in the callback execution.
10737 	 */
10738 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
10739 	if (caller_found) {
10740 		/*
10741 		 * 'error' is from the actual delmap operations.  To avoid
10742 		 * hangs, we need to handle the return of EAGAIN differently
10743 		 * since this is what drives the callback execution.
10744 		 * In this case, we don't want to return EAGAIN and do the
10745 		 * callback execution because there are none to execute.
10746 		 */
10747 		if (error == EAGAIN)
10748 			return (0);
10749 		else
10750 			return (error);
10751 	}
10752 
10753 	/* current caller was not in the list */
10754 	delmap_call = nfs4_init_delmapcall();
10755 
10756 	mutex_enter(&rp->r_statelock);
10757 	list_insert_tail(&rp->r_indelmap, delmap_call);
10758 	mutex_exit(&rp->r_statelock);
10759 
10760 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
10761 
10762 	dmapp->vp = vp;
10763 	dmapp->off = off;
10764 	dmapp->addr = addr;
10765 	dmapp->len = len;
10766 	dmapp->prot = prot;
10767 	dmapp->maxprot = maxprot;
10768 	dmapp->flags = flags;
10769 	dmapp->cr = cr;
10770 	dmapp->caller = delmap_call;
10771 
10772 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
10773 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
10774 
10775 	return (error ? error : EAGAIN);
10776 }
10777 
10778 static nfs4_delmapcall_t *
10779 nfs4_init_delmapcall()
10780 {
10781 	nfs4_delmapcall_t	*delmap_call;
10782 
10783 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
10784 	delmap_call->call_id = curthread;
10785 	delmap_call->error = 0;
10786 
10787 	return (delmap_call);
10788 }
10789 
10790 static void
10791 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
10792 {
10793 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
10794 }
10795 
10796 /*
10797  * Searches for the current delmap caller (based on curthread) in the list of
10798  * callers.  If it is found, we remove it and free the delmap caller.
10799  * Returns:
10800  *      0 if the caller wasn't found
10801  *      1 if the caller was found, removed and freed.  *errp will be set
10802  *	to what the result of the delmap was.
10803  */
10804 static int
10805 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
10806 {
10807 	nfs4_delmapcall_t	*delmap_call;
10808 
10809 	/*
10810 	 * If the list doesn't exist yet, we create it and return
10811 	 * that the caller wasn't found.  No list = no callers.
10812 	 */
10813 	mutex_enter(&rp->r_statelock);
10814 	if (!(rp->r_flags & R4DELMAPLIST)) {
10815 		/* The list does not exist */
10816 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
10817 		    offsetof(nfs4_delmapcall_t, call_node));
10818 		rp->r_flags |= R4DELMAPLIST;
10819 		mutex_exit(&rp->r_statelock);
10820 		return (0);
10821 	} else {
10822 		/* The list exists so search it */
10823 		for (delmap_call = list_head(&rp->r_indelmap);
10824 		    delmap_call != NULL;
10825 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
10826 			if (delmap_call->call_id == curthread) {
10827 				/* current caller is in the list */
10828 				*errp = delmap_call->error;
10829 				list_remove(&rp->r_indelmap, delmap_call);
10830 				mutex_exit(&rp->r_statelock);
10831 				nfs4_free_delmapcall(delmap_call);
10832 				return (1);
10833 			}
10834 		}
10835 	}
10836 	mutex_exit(&rp->r_statelock);
10837 	return (0);
10838 }
10839 
10840 /*
10841  * Remove some pages from an mmap'd vnode.  Just update the
10842  * count of pages.  If doing close-to-open, then flush and
10843  * commit all of the pages associated with this file.
10844  * Otherwise, start an asynchronous page flush to write out
10845  * any dirty pages.  This will also associate a credential
10846  * with the rnode which can be used to write the pages.
10847  */
10848 /* ARGSUSED */
10849 static void
10850 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
10851 {
10852 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
10853 	rnode4_t		*rp;
10854 	mntinfo4_t		*mi;
10855 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
10856 
10857 	rp = VTOR4(dmapp->vp);
10858 	mi = VTOMI4(dmapp->vp);
10859 
10860 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
10861 	ASSERT(rp->r_mapcnt >= 0);
10862 
10863 	/*
10864 	 * Initiate a page flush and potential commit if there are
10865 	 * pages, the file system was not mounted readonly, the segment
10866 	 * was mapped shared, and the pages themselves were writeable.
10867 	 */
10868 	if (nfs4_has_pages(dmapp->vp) &&
10869 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
10870 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
10871 		mutex_enter(&rp->r_statelock);
10872 		rp->r_flags |= R4DIRTY;
10873 		mutex_exit(&rp->r_statelock);
10874 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
10875 		    dmapp->len, dmapp->cr);
10876 		if (!e.error) {
10877 			mutex_enter(&rp->r_statelock);
10878 			e.error = rp->r_error;
10879 			rp->r_error = 0;
10880 			mutex_exit(&rp->r_statelock);
10881 		}
10882 	} else
10883 		e.error = 0;
10884 
10885 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
10886 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
10887 		    B_INVAL, dmapp->cr);
10888 
10889 	if (e.error) {
10890 		e.stat = puterrno4(e.error);
10891 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
10892 			OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
10893 		dmapp->caller->error = e.error;
10894 	}
10895 
10896 	/* Check to see if we need to close the file */
10897 
10898 	if (dmapp->vp->v_type == VREG) {
10899 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
10900 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
10901 
10902 		if (e.error != 0 || e.stat != NFS4_OK) {
10903 			/*
10904 			 * Since it is possible that e.error == 0 and
10905 			 * e.stat != NFS4_OK (and vice versa),
10906 			 * we do the proper checking in order to get both
10907 			 * e.error and e.stat reporting the correct info.
10908 			 */
10909 			if (e.stat == NFS4_OK)
10910 				e.stat = puterrno4(e.error);
10911 			if (e.error == 0)
10912 				e.error = geterrno4(e.stat);
10913 
10914 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
10915 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
10916 			dmapp->caller->error = e.error;
10917 		}
10918 	}
10919 
10920 	(void) as_delete_callback(as, arg);
10921 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
10922 }
10923 
10924 
10925 static uint_t
10926 fattr4_maxfilesize_to_bits(uint64_t ll)
10927 {
10928 	uint_t l = 1;
10929 
10930 	if (ll == 0) {
10931 		return (0);
10932 	}
10933 
10934 	if (ll & 0xffffffff00000000) {
10935 		l += 32; ll >>= 32;
10936 	}
10937 	if (ll & 0xffff0000) {
10938 		l += 16; ll >>= 16;
10939 	}
10940 	if (ll & 0xff00) {
10941 		l += 8; ll >>= 8;
10942 	}
10943 	if (ll & 0xf0) {
10944 		l += 4; ll >>= 4;
10945 	}
10946 	if (ll & 0xc) {
10947 		l += 2; ll >>= 2;
10948 	}
10949 	if (ll & 0x2) {
10950 		l += 1;
10951 	}
10952 	return (l);
10953 }
10954 
10955 static int
10956 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr)
10957 {
10958 	int error;
10959 	hrtime_t t;
10960 	rnode4_t *rp;
10961 	nfs4_ga_res_t gar;
10962 	nfs4_ga_ext_res_t ger;
10963 
10964 	gar.n4g_ext_res = &ger;
10965 
10966 	if (curproc->p_zone != VTOMI4(vp)->mi_zone)
10967 		return (EIO);
10968 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
10969 		*valp = MAXPATHLEN;
10970 		return (0);
10971 	}
10972 	if (cmd == _PC_ACL_ENABLED) {
10973 		*valp = _ACL_ACE_ENABLED;
10974 		return (0);
10975 	}
10976 
10977 	rp = VTOR4(vp);
10978 	if (cmd == _PC_XATTR_EXISTS) {
10979 		/*
10980 		 * Eventually should attempt small client readdir before
10981 		 * going otw with GETATTR(FATTR4_NAMED_ATTR).  For now
10982 		 * just drive the OTW getattr.  This is required because
10983 		 * _PC_XATTR_EXISTS can only return true if attributes
10984 		 * exist -- simply checking for existance of the attrdir
10985 		 * is not sufficient.
10986 		 *
10987 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
10988 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
10989 		 * and we don't have any way to update the "base" object's
10990 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
10991 		 * could help out.
10992 		 */
10993 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
10994 		    rp->r_xattr_dir == NULL) {
10995 			*valp = rp->r_pathconf.pc4_xattr_exists;
10996 			return (0);
10997 		}
10998 	} else {  /* OLD CODE */
10999 		if (ATTRCACHE4_VALID(vp)) {
11000 			mutex_enter(&rp->r_statelock);
11001 			if (rp->r_pathconf.pc4_cache_valid) {
11002 				error = 0;
11003 				switch (cmd) {
11004 				case _PC_FILESIZEBITS:
11005 					*valp =
11006 					rp->r_pathconf.pc4_filesizebits;
11007 					break;
11008 				case _PC_LINK_MAX:
11009 					*valp =
11010 					rp->r_pathconf.pc4_link_max;
11011 					break;
11012 				case _PC_NAME_MAX:
11013 					*valp =
11014 					rp->r_pathconf.pc4_name_max;
11015 					break;
11016 				case _PC_CHOWN_RESTRICTED:
11017 					*valp =
11018 					rp->r_pathconf.pc4_chown_restricted;
11019 					break;
11020 				case _PC_NO_TRUNC:
11021 					*valp =
11022 					rp->r_pathconf.pc4_no_trunc;
11023 					break;
11024 				default:
11025 					error = EINVAL;
11026 					break;
11027 				}
11028 				mutex_exit(&rp->r_statelock);
11029 #ifdef DEBUG
11030 				nfs4_pathconf_cache_hits++;
11031 #endif
11032 				return (error);
11033 			}
11034 			mutex_exit(&rp->r_statelock);
11035 		}
11036 	}
11037 #ifdef DEBUG
11038 	nfs4_pathconf_cache_misses++;
11039 #endif
11040 
11041 	t = gethrtime();
11042 
11043 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11044 
11045 	if (error) {
11046 		mutex_enter(&rp->r_statelock);
11047 		rp->r_pathconf.pc4_cache_valid = FALSE;
11048 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11049 		mutex_exit(&rp->r_statelock);
11050 		return (error);
11051 	}
11052 
11053 	/* interpret the max filesize */
11054 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11055 		fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11056 
11057 	/* Store the attributes we just received */
11058 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11059 
11060 	switch (cmd) {
11061 	case _PC_FILESIZEBITS:
11062 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11063 		break;
11064 	case _PC_LINK_MAX:
11065 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11066 		break;
11067 	case _PC_NAME_MAX:
11068 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11069 		break;
11070 	case _PC_CHOWN_RESTRICTED:
11071 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11072 		break;
11073 	case _PC_NO_TRUNC:
11074 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11075 		break;
11076 	case _PC_XATTR_EXISTS:
11077 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists;
11078 		break;
11079 	default:
11080 		return (EINVAL);
11081 	}
11082 
11083 	return (0);
11084 }
11085 
11086 /*
11087  * Called by async thread to do synchronous pageio. Do the i/o, wait
11088  * for it to complete, and cleanup the page list when done.
11089  */
11090 static int
11091 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11092 	int flags, cred_t *cr)
11093 {
11094 	int error;
11095 
11096 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
11097 
11098 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11099 	if (flags & B_READ)
11100 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11101 	else
11102 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11103 	return (error);
11104 }
11105 
11106 static int
11107 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11108 	int flags, cred_t *cr)
11109 {
11110 	int error;
11111 	rnode4_t *rp;
11112 
11113 	if (!(flags & B_ASYNC) && curproc->p_zone != VTOMI4(vp)->mi_zone)
11114 		return (EIO);
11115 
11116 	if (pp == NULL)
11117 		return (EINVAL);
11118 
11119 	rp = VTOR4(vp);
11120 	mutex_enter(&rp->r_statelock);
11121 	rp->r_count++;
11122 	mutex_exit(&rp->r_statelock);
11123 
11124 	if (flags & B_ASYNC) {
11125 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11126 		    nfs4_sync_pageio);
11127 	} else
11128 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11129 	mutex_enter(&rp->r_statelock);
11130 	rp->r_count--;
11131 	cv_broadcast(&rp->r_cv);
11132 	mutex_exit(&rp->r_statelock);
11133 	return (error);
11134 }
11135 
11136 static void
11137 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr)
11138 {
11139 	int error;
11140 	rnode4_t *rp;
11141 	page_t *plist;
11142 	page_t *pptr;
11143 	offset3 offset;
11144 	count3 len;
11145 	k_sigset_t smask;
11146 
11147 	/*
11148 	 * We should get called with fl equal to either B_FREE or
11149 	 * B_INVAL.  Any other value is illegal.
11150 	 *
11151 	 * The page that we are either supposed to free or destroy
11152 	 * should be exclusive locked and its io lock should not
11153 	 * be held.
11154 	 */
11155 	ASSERT(fl == B_FREE || fl == B_INVAL);
11156 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11157 
11158 	rp = VTOR4(vp);
11159 
11160 	/*
11161 	 * If the page doesn't need to be committed or we shouldn't
11162 	 * even bother attempting to commit it, then just make sure
11163 	 * that the p_fsdata byte is clear and then either free or
11164 	 * destroy the page as appropriate.
11165 	 */
11166 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11167 		pp->p_fsdata = C_NOCOMMIT;
11168 		if (fl == B_FREE)
11169 			page_free(pp, dn);
11170 		else
11171 			page_destroy(pp, dn);
11172 		return;
11173 	}
11174 
11175 	/*
11176 	 * If there is a page invalidation operation going on, then
11177 	 * if this is one of the pages being destroyed, then just
11178 	 * clear the p_fsdata byte and then either free or destroy
11179 	 * the page as appropriate.
11180 	 */
11181 	mutex_enter(&rp->r_statelock);
11182 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11183 		mutex_exit(&rp->r_statelock);
11184 		pp->p_fsdata = C_NOCOMMIT;
11185 		if (fl == B_FREE)
11186 			page_free(pp, dn);
11187 		else
11188 			page_destroy(pp, dn);
11189 		return;
11190 	}
11191 
11192 	/*
11193 	 * If we are freeing this page and someone else is already
11194 	 * waiting to do a commit, then just unlock the page and
11195 	 * return.  That other thread will take care of commiting
11196 	 * this page.  The page can be freed sometime after the
11197 	 * commit has finished.  Otherwise, if the page is marked
11198 	 * as delay commit, then we may be getting called from
11199 	 * pvn_write_done, one page at a time.   This could result
11200 	 * in one commit per page, so we end up doing lots of small
11201 	 * commits instead of fewer larger commits.  This is bad,
11202 	 * we want do as few commits as possible.
11203 	 */
11204 	if (fl == B_FREE) {
11205 		if (rp->r_flags & R4COMMITWAIT) {
11206 			page_unlock(pp);
11207 			mutex_exit(&rp->r_statelock);
11208 			return;
11209 		}
11210 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11211 			pp->p_fsdata = C_COMMIT;
11212 			page_unlock(pp);
11213 			mutex_exit(&rp->r_statelock);
11214 			return;
11215 		}
11216 	}
11217 
11218 	/*
11219 	 * Check to see if there is a signal which would prevent an
11220 	 * attempt to commit the pages from being successful.  If so,
11221 	 * then don't bother with all of the work to gather pages and
11222 	 * generate the unsuccessful RPC.  Just return from here and
11223 	 * let the page be committed at some later time.
11224 	 */
11225 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11226 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11227 		sigunintr(&smask);
11228 		page_unlock(pp);
11229 		mutex_exit(&rp->r_statelock);
11230 		return;
11231 	}
11232 	sigunintr(&smask);
11233 
11234 	/*
11235 	 * We are starting to need to commit pages, so let's try
11236 	 * to commit as many as possible at once to reduce the
11237 	 * overhead.
11238 	 *
11239 	 * Set the `commit inprogress' state bit.  We must
11240 	 * first wait until any current one finishes.  Then
11241 	 * we initialize the c_pages list with this page.
11242 	 */
11243 	while (rp->r_flags & R4COMMIT) {
11244 		rp->r_flags |= R4COMMITWAIT;
11245 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11246 		rp->r_flags &= ~R4COMMITWAIT;
11247 	}
11248 	rp->r_flags |= R4COMMIT;
11249 	mutex_exit(&rp->r_statelock);
11250 	ASSERT(rp->r_commit.c_pages == NULL);
11251 	rp->r_commit.c_pages = pp;
11252 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11253 	rp->r_commit.c_commlen = PAGESIZE;
11254 
11255 	/*
11256 	 * Gather together all other pages which can be committed.
11257 	 * They will all be chained off r_commit.c_pages.
11258 	 */
11259 	nfs4_get_commit(vp);
11260 
11261 	/*
11262 	 * Clear the `commit inprogress' status and disconnect
11263 	 * the list of pages to be committed from the rnode.
11264 	 * At this same time, we also save the starting offset
11265 	 * and length of data to be committed on the server.
11266 	 */
11267 	plist = rp->r_commit.c_pages;
11268 	rp->r_commit.c_pages = NULL;
11269 	offset = rp->r_commit.c_commbase;
11270 	len = rp->r_commit.c_commlen;
11271 	mutex_enter(&rp->r_statelock);
11272 	rp->r_flags &= ~R4COMMIT;
11273 	cv_broadcast(&rp->r_commit.c_cv);
11274 	mutex_exit(&rp->r_statelock);
11275 
11276 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11277 	    curproc->p_zone != VTOMI4(vp)->mi_zone) {
11278 		nfs4_async_commit(vp, plist, offset, len,
11279 		    cr, do_nfs4_async_commit);
11280 		return;
11281 	}
11282 
11283 	/*
11284 	 * Actually generate the COMMIT op over the wire operation.
11285 	 */
11286 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11287 
11288 	/*
11289 	 * If we got an error during the commit, just unlock all
11290 	 * of the pages.  The pages will get retransmitted to the
11291 	 * server during a putpage operation.
11292 	 */
11293 	if (error) {
11294 		while (plist != NULL) {
11295 			pptr = plist;
11296 			page_sub(&plist, pptr);
11297 			page_unlock(pptr);
11298 		}
11299 		return;
11300 	}
11301 
11302 	/*
11303 	 * We've tried as hard as we can to commit the data to stable
11304 	 * storage on the server.  We just unlock the rest of the pages
11305 	 * and clear the commit required state.  They will be put
11306 	 * onto the tail of the cachelist if they are nolonger
11307 	 * mapped.
11308 	 */
11309 	while (plist != pp) {
11310 		pptr = plist;
11311 		page_sub(&plist, pptr);
11312 		pptr->p_fsdata = C_NOCOMMIT;
11313 		page_unlock(pptr);
11314 	}
11315 
11316 	/*
11317 	 * It is possible that nfs4_commit didn't return error but
11318 	 * some other thread has modified the page we are going
11319 	 * to free/destroy.
11320 	 *    In this case we need to rewrite the page. Do an explicit check
11321 	 * before attempting to free/destroy the page. If modified, needs to
11322 	 * be rewritten so unlock the page and return.
11323 	 */
11324 	if (hat_ismod(pp)) {
11325 		pp->p_fsdata = C_NOCOMMIT;
11326 		page_unlock(pp);
11327 		return;
11328 	}
11329 
11330 	/*
11331 	 * Now, as appropriate, either free or destroy the page
11332 	 * that we were called with.
11333 	 */
11334 	pp->p_fsdata = C_NOCOMMIT;
11335 	if (fl == B_FREE)
11336 		page_free(pp, dn);
11337 	else
11338 		page_destroy(pp, dn);
11339 }
11340 
11341 /*
11342  * Commit requires that the current fh be the file written to.
11343  * The compound op structure is:
11344  *      PUTFH(file), COMMIT
11345  */
11346 static int
11347 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11348 {
11349 	COMPOUND4args_clnt args;
11350 	COMPOUND4res_clnt res;
11351 	COMMIT4res *cm_res;
11352 	nfs_argop4 argop[2];
11353 	nfs_resop4 *resop;
11354 	int doqueue;
11355 	mntinfo4_t *mi;
11356 	rnode4_t *rp;
11357 	cred_t *cred_otw = NULL;
11358 	bool_t needrecov = FALSE;
11359 	nfs4_recov_state_t recov_state;
11360 	nfs4_open_stream_t *osp = NULL;
11361 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11362 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11363 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11364 
11365 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
11366 
11367 	rp = VTOR4(vp);
11368 
11369 	mi = VTOMI4(vp);
11370 	recov_state.rs_flags = 0;
11371 	recov_state.rs_num_retry_despite_err = 0;
11372 get_commit_cred:
11373 	/*
11374 	 * Releases the osp, if a valid open stream is provided.
11375 	 * Puts a hold on the cred_otw and the new osp (if found).
11376 	 */
11377 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11378 			&first_time, &last_time);
11379 	args.ctag = TAG_COMMIT;
11380 recov_retry:
11381 	/*
11382 	 * Commit ops: putfh file; commit
11383 	 */
11384 	args.array_len = 2;
11385 	args.array = argop;
11386 
11387 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11388 			    &recov_state, NULL);
11389 	if (e.error) {
11390 		crfree(cred_otw);
11391 		if (osp != NULL)
11392 			open_stream_rele(osp, rp);
11393 		return (e.error);
11394 	}
11395 
11396 	/* putfh directory */
11397 	argop[0].argop = OP_CPUTFH;
11398 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11399 
11400 	/* commit */
11401 	argop[1].argop = OP_COMMIT;
11402 	argop[1].nfs_argop4_u.opcommit.offset = offset;
11403 	argop[1].nfs_argop4_u.opcommit.count = count;
11404 
11405 	doqueue = 1;
11406 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
11407 
11408 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
11409 	if (!needrecov && e.error) {
11410 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
11411 			needrecov);
11412 		crfree(cred_otw);
11413 		if (e.error == EACCES && last_time == FALSE)
11414 			goto get_commit_cred;
11415 		if (osp != NULL)
11416 			open_stream_rele(osp, rp);
11417 		return (e.error);
11418 	}
11419 
11420 	if (needrecov) {
11421 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
11422 		    NULL, OP_COMMIT, NULL) == FALSE) {
11423 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11424 				&recov_state, needrecov);
11425 			if (!e.error)
11426 				(void) xdr_free(xdr_COMPOUND4res_clnt,
11427 								(caddr_t)&res);
11428 			goto recov_retry;
11429 		}
11430 		if (e.error) {
11431 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11432 				&recov_state, needrecov);
11433 			crfree(cred_otw);
11434 			if (osp != NULL)
11435 				open_stream_rele(osp, rp);
11436 			return (e.error);
11437 		}
11438 		/* fall through for res.status case */
11439 	}
11440 
11441 	if (res.status) {
11442 		e.error = geterrno4(res.status);
11443 		if (e.error == EACCES && last_time == FALSE) {
11444 			crfree(cred_otw);
11445 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11446 				&recov_state, needrecov);
11447 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11448 			goto get_commit_cred;
11449 		}
11450 		/*
11451 		 * Can't do a nfs4_purge_stale_fh here because this
11452 		 * can cause a deadlock.  nfs4_commit can
11453 		 * be called from nfs4_dispose which can be called
11454 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
11455 		 * can call back to pvn_vplist_dirty.
11456 		 */
11457 		if (e.error == ESTALE) {
11458 			mutex_enter(&rp->r_statelock);
11459 			rp->r_flags |= R4STALE;
11460 			if (!rp->r_error)
11461 				rp->r_error = e.error;
11462 			mutex_exit(&rp->r_statelock);
11463 			PURGE_ATTRCACHE4(vp);
11464 		} else {
11465 			mutex_enter(&rp->r_statelock);
11466 			if (!rp->r_error)
11467 				rp->r_error = e.error;
11468 			mutex_exit(&rp->r_statelock);
11469 		}
11470 	} else {
11471 		ASSERT(rp->r_flags & R4HAVEVERF);
11472 		resop = &res.array[1];	/* commit res */
11473 		cm_res = &resop->nfs_resop4_u.opcommit;
11474 		mutex_enter(&rp->r_statelock);
11475 		if (cm_res->writeverf == rp->r_writeverf) {
11476 			mutex_exit(&rp->r_statelock);
11477 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11478 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11479 				&recov_state, needrecov);
11480 			crfree(cred_otw);
11481 			if (osp != NULL)
11482 				open_stream_rele(osp, rp);
11483 			return (0);
11484 		}
11485 		nfs4_set_mod(vp);
11486 		rp->r_writeverf = cm_res->writeverf;
11487 		mutex_exit(&rp->r_statelock);
11488 		e.error = NFS_VERF_MISMATCH;
11489 	}
11490 
11491 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11492 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
11493 	crfree(cred_otw);
11494 	if (osp != NULL)
11495 		open_stream_rele(osp, rp);
11496 
11497 	return (e.error);
11498 }
11499 
11500 static void
11501 nfs4_set_mod(vnode_t *vp)
11502 {
11503 	page_t *pp;
11504 	kmutex_t *vphm;
11505 	rnode4_t *rp;
11506 
11507 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
11508 
11509 	/* make sure we're looking at the master vnode, not a shadow */
11510 
11511 	rp = VTOR4(vp);
11512 	if (IS_SHADOW(vp, rp))
11513 		vp = RTOV4(rp);
11514 
11515 	vphm = page_vnode_mutex(vp);
11516 	mutex_enter(vphm);
11517 	/*
11518 	 * If there are no pages associated with this vnode, then
11519 	 * just return.
11520 	 */
11521 	if ((pp = vp->v_pages) == NULL) {
11522 		mutex_exit(vphm);
11523 		return;
11524 	}
11525 
11526 	do {
11527 		if (pp->p_fsdata != C_NOCOMMIT) {
11528 			hat_setmod(pp);
11529 			pp->p_fsdata = C_NOCOMMIT;
11530 		}
11531 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11532 	mutex_exit(vphm);
11533 }
11534 
11535 /*
11536  * This function is used to gather a page list of the pages which
11537  * can be committed on the server.
11538  *
11539  * The calling thread must have set R4COMMIT.  This bit is used to
11540  * serialize access to the commit structure in the rnode.  As long
11541  * as the thread has set R4COMMIT, then it can manipulate the commit
11542  * structure without requiring any other locks.
11543  *
11544  * When this function is called from nfs4_dispose() the page passed
11545  * into nfs4_dispose() will be SE_EXCL locked, and so this function
11546  * will skip it. This is not a problem since we initially add the
11547  * page to the r_commit page list.
11548  *
11549  */
11550 static void
11551 nfs4_get_commit(vnode_t *vp)
11552 {
11553 	rnode4_t *rp;
11554 	page_t *pp;
11555 	kmutex_t *vphm;
11556 
11557 	rp = VTOR4(vp);
11558 
11559 	ASSERT(rp->r_flags & R4COMMIT);
11560 
11561 	/* make sure we're looking at the master vnode, not a shadow */
11562 
11563 	if (IS_SHADOW(vp, rp))
11564 		vp = RTOV4(rp);
11565 
11566 	vphm = page_vnode_mutex(vp);
11567 	mutex_enter(vphm);
11568 
11569 	/*
11570 	 * If there are no pages associated with this vnode, then
11571 	 * just return.
11572 	 */
11573 	if ((pp = vp->v_pages) == NULL) {
11574 		mutex_exit(vphm);
11575 		return;
11576 	}
11577 
11578 	/*
11579 	 * Step through all of the pages associated with this vnode
11580 	 * looking for pages which need to be committed.
11581 	 */
11582 	do {
11583 		/*
11584 		 * First short-cut everything (without the page_lock)
11585 		 * and see if this page does not need to be committed
11586 		 * or is modified if so then we'll just skip it.
11587 		 */
11588 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
11589 			continue;
11590 
11591 		/*
11592 		 * Attempt to lock the page.  If we can't, then
11593 		 * someone else is messing with it or we have been
11594 		 * called from nfs4_dispose and this is the page that
11595 		 * nfs4_dispose was called with.. anyway just skip it.
11596 		 */
11597 		if (!page_trylock(pp, SE_EXCL))
11598 			continue;
11599 
11600 		/*
11601 		 * Lets check again now that we have the page lock.
11602 		 */
11603 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11604 			page_unlock(pp);
11605 			continue;
11606 		}
11607 
11608 		/* this had better not be a free page */
11609 		ASSERT(PP_ISFREE(pp) == 0);
11610 
11611 		/*
11612 		 * The page needs to be committed and we locked it.
11613 		 * Update the base and length parameters and add it
11614 		 * to r_pages.
11615 		 */
11616 		if (rp->r_commit.c_pages == NULL) {
11617 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11618 			rp->r_commit.c_commlen = PAGESIZE;
11619 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
11620 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
11621 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
11622 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11623 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
11624 			    <= pp->p_offset) {
11625 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11626 			    rp->r_commit.c_commbase + PAGESIZE;
11627 		}
11628 		page_add(&rp->r_commit.c_pages, pp);
11629 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11630 
11631 	mutex_exit(vphm);
11632 }
11633 
11634 /*
11635  * This routine is used to gather together a page list of the pages
11636  * which are to be committed on the server.  This routine must not
11637  * be called if the calling thread holds any locked pages.
11638  *
11639  * The calling thread must have set R4COMMIT.  This bit is used to
11640  * serialize access to the commit structure in the rnode.  As long
11641  * as the thread has set R4COMMIT, then it can manipulate the commit
11642  * structure without requiring any other locks.
11643  */
11644 static void
11645 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
11646 {
11647 
11648 	rnode4_t *rp;
11649 	page_t *pp;
11650 	u_offset_t end;
11651 	u_offset_t off;
11652 	ASSERT(len != 0);
11653 	rp = VTOR4(vp);
11654 	ASSERT(rp->r_flags & R4COMMIT);
11655 
11656 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
11657 
11658 	/* make sure we're looking at the master vnode, not a shadow */
11659 
11660 	if (IS_SHADOW(vp, rp))
11661 		vp = RTOV4(rp);
11662 
11663 	/*
11664 	 * If there are no pages associated with this vnode, then
11665 	 * just return.
11666 	 */
11667 	if ((pp = vp->v_pages) == NULL)
11668 		return;
11669 	/*
11670 	 * Calculate the ending offset.
11671 	 */
11672 	end = soff + len;
11673 	for (off = soff; off < end; off += PAGESIZE) {
11674 		/*
11675 		 * Lookup each page by vp, offset.
11676 		 */
11677 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
11678 			continue;
11679 		/*
11680 		 * If this page does not need to be committed or is
11681 		 * modified, then just skip it.
11682 		 */
11683 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11684 			page_unlock(pp);
11685 			continue;
11686 		}
11687 
11688 		ASSERT(PP_ISFREE(pp) == 0);
11689 		/*
11690 		 * The page needs to be committed and we locked it.
11691 		 * Update the base and length parameters and add it
11692 		 * to r_pages.
11693 		 */
11694 		if (rp->r_commit.c_pages == NULL) {
11695 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11696 			rp->r_commit.c_commlen = PAGESIZE;
11697 		} else {
11698 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11699 			rp->r_commit.c_commbase + PAGESIZE;
11700 		}
11701 		page_add(&rp->r_commit.c_pages, pp);
11702 	}
11703 }
11704 
11705 /*
11706  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
11707  * Flushes and commits data to the server.
11708  */
11709 static int
11710 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
11711 {
11712 	int error;
11713 	verifier4 write_verf;
11714 	rnode4_t *rp = VTOR4(vp);
11715 
11716 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
11717 
11718 	/*
11719 	 * Flush the data portion of the file and then commit any
11720 	 * portions which need to be committed.  This may need to
11721 	 * be done twice if the server has changed state since
11722 	 * data was last written.  The data will need to be
11723 	 * rewritten to the server and then a new commit done.
11724 	 *
11725 	 * In fact, this may need to be done several times if the
11726 	 * server is having problems and crashing while we are
11727 	 * attempting to do this.
11728 	 */
11729 
11730 top:
11731 	/*
11732 	 * Do a flush based on the poff and plen arguments.  This
11733 	 * will synchronously write out any modified pages in the
11734 	 * range specified by (poff, plen). This starts all of the
11735 	 * i/o operations which will be waited for in the next
11736 	 * call to nfs4_putpage
11737 	 */
11738 
11739 	mutex_enter(&rp->r_statelock);
11740 	write_verf = rp->r_writeverf;
11741 	mutex_exit(&rp->r_statelock);
11742 
11743 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr);
11744 	if (error == EAGAIN)
11745 		error = 0;
11746 
11747 	/*
11748 	 * Do a flush based on the poff and plen arguments.  This
11749 	 * will synchronously write out any modified pages in the
11750 	 * range specified by (poff, plen) and wait until all of
11751 	 * the asynchronous i/o's in that range are done as well.
11752 	 */
11753 	if (!error)
11754 		error = nfs4_putpage(vp, poff, plen, 0, cr);
11755 
11756 	if (error)
11757 		return (error);
11758 
11759 	mutex_enter(&rp->r_statelock);
11760 	if (rp->r_writeverf != write_verf) {
11761 		mutex_exit(&rp->r_statelock);
11762 		goto top;
11763 	}
11764 	mutex_exit(&rp->r_statelock);
11765 
11766 	/*
11767 	 * Now commit any pages which might need to be committed.
11768 	 * If the error, NFS_VERF_MISMATCH, is returned, then
11769 	 * start over with the flush operation.
11770 	 */
11771 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
11772 
11773 	if (error == NFS_VERF_MISMATCH)
11774 		goto top;
11775 
11776 	return (error);
11777 }
11778 
11779 /*
11780  * nfs4_commit_vp()  will wait for other pending commits and
11781  * will either commit the whole file or a range, plen dictates
11782  * if we commit whole file. a value of zero indicates the whole
11783  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
11784  */
11785 static int
11786 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
11787 		cred_t *cr, int wait_on_writes)
11788 {
11789 	rnode4_t *rp;
11790 	page_t *plist;
11791 	offset3 offset;
11792 	count3 len;
11793 
11794 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
11795 
11796 	rp = VTOR4(vp);
11797 
11798 	/*
11799 	 *  before we gather commitable pages make
11800 	 *  sure there are no outstanding async writes
11801 	 */
11802 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
11803 		mutex_enter(&rp->r_statelock);
11804 		while (rp->r_count > 0) {
11805 			cv_wait(&rp->r_cv, &rp->r_statelock);
11806 		}
11807 		mutex_exit(&rp->r_statelock);
11808 	}
11809 
11810 	/*
11811 	 * Set the `commit inprogress' state bit.  We must
11812 	 * first wait until any current one finishes.
11813 	 */
11814 	mutex_enter(&rp->r_statelock);
11815 	while (rp->r_flags & R4COMMIT) {
11816 		rp->r_flags |= R4COMMITWAIT;
11817 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11818 		rp->r_flags &= ~R4COMMITWAIT;
11819 	}
11820 	rp->r_flags |= R4COMMIT;
11821 	mutex_exit(&rp->r_statelock);
11822 
11823 	/*
11824 	 * Gather all of the pages which need to be
11825 	 * committed.
11826 	 */
11827 	if (plen == 0)
11828 		nfs4_get_commit(vp);
11829 	else
11830 		nfs4_get_commit_range(vp, poff, plen);
11831 
11832 	/*
11833 	 * Clear the `commit inprogress' bit and disconnect the
11834 	 * page list which was gathered by nfs4_get_commit.
11835 	 */
11836 	plist = rp->r_commit.c_pages;
11837 	rp->r_commit.c_pages = NULL;
11838 	offset = rp->r_commit.c_commbase;
11839 	len = rp->r_commit.c_commlen;
11840 	mutex_enter(&rp->r_statelock);
11841 	rp->r_flags &= ~R4COMMIT;
11842 	cv_broadcast(&rp->r_commit.c_cv);
11843 	mutex_exit(&rp->r_statelock);
11844 
11845 	/*
11846 	 * If any pages need to be committed, commit them and
11847 	 * then unlock them so that they can be freed some
11848 	 * time later.
11849 	 */
11850 	if (plist == NULL)
11851 		return (0);
11852 
11853 	/*
11854 	 * No error occurred during the flush portion
11855 	 * of this operation, so now attempt to commit
11856 	 * the data to stable storage on the server.
11857 	 *
11858 	 * This will unlock all of the pages on the list.
11859 	 */
11860 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
11861 }
11862 
11863 static int
11864 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
11865 	cred_t *cr)
11866 {
11867 	int error;
11868 	page_t *pp;
11869 
11870 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
11871 
11872 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
11873 
11874 	/*
11875 	 * If we got an error, then just unlock all of the pages
11876 	 * on the list.
11877 	 */
11878 	if (error) {
11879 		while (plist != NULL) {
11880 			pp = plist;
11881 			page_sub(&plist, pp);
11882 			page_unlock(pp);
11883 		}
11884 		return (error);
11885 	}
11886 	/*
11887 	 * We've tried as hard as we can to commit the data to stable
11888 	 * storage on the server.  We just unlock the pages and clear
11889 	 * the commit required state.  They will get freed later.
11890 	 */
11891 	while (plist != NULL) {
11892 		pp = plist;
11893 		page_sub(&plist, pp);
11894 		pp->p_fsdata = C_NOCOMMIT;
11895 		page_unlock(pp);
11896 	}
11897 
11898 	return (error);
11899 }
11900 
11901 static void
11902 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
11903 	cred_t *cr)
11904 {
11905 
11906 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
11907 }
11908 
11909 /*ARGSUSED*/
11910 static int
11911 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr)
11912 {
11913 	int		error = 0;
11914 	mntinfo4_t	*mi;
11915 	vattr_t		va;
11916 	vsecattr_t	nfsace4_vsap;
11917 
11918 	mi = VTOMI4(vp);
11919 	if (curproc->p_zone != mi->mi_zone)
11920 		return (EIO);
11921 	if (mi->mi_flags & MI4_ACL) {
11922 		/* if we have a delegation, return it */
11923 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
11924 			(void) nfs4delegreturn(VTOR4(vp),
11925 					NFS4_DR_REOPEN|NFS4_DR_PUSH);
11926 
11927 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
11928 			NFS4_ACL_SET);
11929 		if (error) /* EINVAL */
11930 			return (error);
11931 
11932 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
11933 			/*
11934 			 * These are aclent_t type entries.
11935 			 */
11936 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
11937 			    vp->v_type == VDIR, FALSE);
11938 			if (error)
11939 				return (error);
11940 		} else {
11941 			/*
11942 			 * These are ace_t type entries.
11943 			 */
11944 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
11945 			    vp->v_type == VDIR, FALSE);
11946 			if (error)
11947 				return (error);
11948 		}
11949 		bzero(&va, sizeof (va));
11950 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
11951 		vs_ace4_destroy(&nfsace4_vsap);
11952 		return (error);
11953 	}
11954 	return (ENOSYS);
11955 }
11956 
11957 static int
11958 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr)
11959 {
11960 	int		error;
11961 	mntinfo4_t	*mi;
11962 	nfs4_ga_res_t	gar;
11963 	rnode4_t	*rp = VTOR4(vp);
11964 
11965 	mi = VTOMI4(vp);
11966 	if (curproc->p_zone != mi->mi_zone)
11967 		return (EIO);
11968 
11969 	bzero(&gar, sizeof (gar));
11970 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
11971 
11972 	/*
11973 	 * vsecattr->vsa_mask holds the original acl request mask.
11974 	 * This is needed when determining what to return.
11975 	 * (See: nfs4_create_getsecattr_return())
11976 	 */
11977 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
11978 	if (error) /* EINVAL */
11979 		return (error);
11980 
11981 	if (mi->mi_flags & MI4_ACL) {
11982 		/*
11983 		 * Check if the data is cached and the cache is valid.  If it
11984 		 * is we don't go over the wire.
11985 		 */
11986 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
11987 			mutex_enter(&rp->r_statelock);
11988 			if (rp->r_secattr != NULL) {
11989 				error = nfs4_create_getsecattr_return(
11990 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
11991 				    rp->r_attr.va_gid,
11992 				    vp->v_type == VDIR);
11993 				if (!error) { /* error == 0 - Success! */
11994 					mutex_exit(&rp->r_statelock);
11995 					return (error);
11996 				}
11997 			}
11998 			mutex_exit(&rp->r_statelock);
11999 		}
12000 
12001 		/*
12002 		 * The getattr otw call will always get both the acl, in
12003 		 * the form of a list of nfsace4's, and the number of acl
12004 		 * entries; independent of the value of gar.n4g_vsa.vsa_mask.
12005 		 */
12006 		gar.n4g_va.va_mask = AT_ALL;
12007 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12008 		if (error) {
12009 			vs_ace4_destroy(&gar.n4g_vsa);
12010 			if (error == ENOTSUP || error == EOPNOTSUPP)
12011 				error = fs_fab_acl(vp, vsecattr, flag, cr);
12012 			return (error);
12013 		}
12014 
12015 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12016 			/*
12017 			 * No error was returned, but according to the response
12018 			 * bitmap, neither was an acl.
12019 			 */
12020 			vs_ace4_destroy(&gar.n4g_vsa);
12021 			error = fs_fab_acl(vp, vsecattr, flag, cr);
12022 			return (error);
12023 		}
12024 
12025 		/*
12026 		 * Update the cache with the ACL.
12027 		 */
12028 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12029 
12030 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12031 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12032 		    vp->v_type == VDIR);
12033 		vs_ace4_destroy(&gar.n4g_vsa);
12034 		if ((error) && (vsecattr->vsa_mask &
12035 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12036 		    (error != EACCES)) {
12037 			error = fs_fab_acl(vp, vsecattr, flag, cr);
12038 		}
12039 		return (error);
12040 	}
12041 	error = fs_fab_acl(vp, vsecattr, flag, cr);
12042 	return (error);
12043 }
12044 
12045 /*
12046  * The function returns:
12047  * 	- 0 (zero) if the passed in "acl_mask" is a valid request.
12048  * 	- EINVAL if the passed in "acl_mask" is an invalid request.
12049  *
12050  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12051  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12052  *
12053  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12054  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12055  * - We have a count field set without the corresponding acl field set. (e.g. -
12056  * VSA_ACECNT is set, but VSA_ACE is not)
12057  */
12058 static int
12059 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12060 {
12061 	/* Shortcut the masks that are always valid. */
12062 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12063 		return (0);
12064 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12065 		return (0);
12066 
12067 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12068 		/*
12069 		 * We can't have any VSA_ACL type stuff in the mask now.
12070 		 */
12071 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12072 		    VSA_DFACLCNT))
12073 			return (EINVAL);
12074 
12075 		if (op == NFS4_ACL_SET) {
12076 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12077 				return (EINVAL);
12078 		}
12079 	}
12080 
12081 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12082 		/*
12083 		 * We can't have any VSA_ACE type stuff in the mask now.
12084 		 */
12085 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12086 			return (EINVAL);
12087 
12088 		if (op == NFS4_ACL_SET) {
12089 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12090 				return (EINVAL);
12091 
12092 			if ((acl_mask & VSA_DFACLCNT) &&
12093 			    !(acl_mask & VSA_DFACL))
12094 				return (EINVAL);
12095 		}
12096 	}
12097 	return (0);
12098 }
12099 
12100 /*
12101  * The theory behind creating the correct getsecattr return is simply this:
12102  * "Don't return anything that the caller is not expecting to have to free."
12103  */
12104 static int
12105 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12106 	uid_t uid, gid_t gid, int isdir)
12107 {
12108 	int error = 0;
12109 	/* Save the mask since the translators modify it. */
12110 	uint_t	orig_mask = vsap->vsa_mask;
12111 
12112 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12113 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid,
12114 		    isdir, FALSE, ((orig_mask & VSA_ACE) ? FALSE : TRUE));
12115 
12116 		if (error)
12117 			return (error);
12118 
12119 		/*
12120 		 * If the caller only asked for the ace count (VSA_ACECNT)
12121 		 * don't give them the full acl (VSA_ACE), free it.
12122 		 */
12123 		if (!orig_mask & VSA_ACE) {
12124 			if (vsap->vsa_aclentp != NULL) {
12125 				kmem_free(vsap->vsa_aclentp,
12126 				    vsap->vsa_aclcnt * sizeof (ace_t));
12127 				vsap->vsa_aclentp = NULL;
12128 			}
12129 		}
12130 		vsap->vsa_mask = orig_mask;
12131 
12132 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12133 	    VSA_DFACLCNT)) {
12134 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12135 		    isdir, FALSE,
12136 		    ((orig_mask & (VSA_ACL | VSA_DFACL)) ? FALSE : TRUE));
12137 
12138 		if (error)
12139 			return (error);
12140 
12141 		/*
12142 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12143 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12144 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12145 		 */
12146 		if (!orig_mask & VSA_ACL) {
12147 			if (vsap->vsa_aclentp != NULL) {
12148 				kmem_free(vsap->vsa_aclentp,
12149 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12150 				vsap->vsa_aclentp = NULL;
12151 			}
12152 		}
12153 
12154 		if (!orig_mask & VSA_DFACL) {
12155 			if (vsap->vsa_dfaclentp != NULL) {
12156 				kmem_free(vsap->vsa_dfaclentp,
12157 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12158 				vsap->vsa_dfaclentp = NULL;
12159 			}
12160 		}
12161 		vsap->vsa_mask = orig_mask;
12162 	}
12163 	return (0);
12164 }
12165 
12166 static int
12167 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr)
12168 {
12169 	int error;
12170 
12171 	if (curproc->p_zone != VTOMI4(vp)->mi_zone)
12172 		return (EIO);
12173 	/*
12174 	 * check for valid cmd parameter
12175 	 */
12176 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12177 		return (EINVAL);
12178 
12179 	/*
12180 	 * Check access permissions
12181 	 */
12182 	if ((cmd & F_SHARE) &&
12183 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12184 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12185 		return (EBADF);
12186 
12187 	/*
12188 	 * If the filesystem is mounted using local locking, pass the
12189 	 * request off to the local share code.
12190 	 */
12191 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12192 		return (fs_shrlock(vp, cmd, shr, flag, cr));
12193 
12194 	switch (cmd) {
12195 	case F_SHARE:
12196 	case F_UNSHARE:
12197 		/*
12198 		 * This will be properly implemented later,
12199 		 * see RFE: 4823948 .
12200 		 */
12201 		error = EAGAIN;
12202 		break;
12203 
12204 	case F_HASREMOTELOCKS:
12205 		/*
12206 		 * NFS client can't store remote locks itself
12207 		 */
12208 		shr->s_access = 0;
12209 		error = 0;
12210 		break;
12211 
12212 	default:
12213 		error = EINVAL;
12214 		break;
12215 	}
12216 
12217 	return (error);
12218 }
12219 
12220 /*
12221  * Common code called by directory ops to update the attrcache
12222  */
12223 static int
12224 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12225 	hrtime_t t, vnode_t *vp, cred_t *cr)
12226 {
12227 	int error = 0;
12228 
12229 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
12230 
12231 	if (status != NFS4_OK) {
12232 		/* getattr not done or failed */
12233 		PURGE_ATTRCACHE4(vp);
12234 		return (error);
12235 	}
12236 
12237 	if (garp) {
12238 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12239 	} else {
12240 		PURGE_ATTRCACHE4(vp);
12241 	}
12242 	return (error);
12243 }
12244 
12245 /*
12246  * Update directory caches for directory modification ops (link, rename, etc.)
12247  * When dinfo is NULL, manage dircaches in the old way.
12248  */
12249 static void
12250 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12251 		dirattr_info_t *dinfo)
12252 {
12253 	rnode4_t	*drp = VTOR4(dvp);
12254 
12255 	ASSERT(curproc->p_zone == VTOMI4(dvp)->mi_zone);
12256 
12257 	/* Purge rddir cache for dir since it changed */
12258 	if (drp->r_dir != NULL)
12259 		nfs4_purge_rddir_cache(dvp);
12260 
12261 	/*
12262 	 * If caller provided dinfo, then use it to manage dir caches.
12263 	 */
12264 	if (dinfo != NULL) {
12265 		if (vp != NULL) {
12266 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12267 			if (!VTOR4(vp)->created_v4) {
12268 				dnlc_update(dvp, nm, vp);
12269 			} else {
12270 				/*
12271 				 * XXX don't update if the created_v4 flag is
12272 				 * set
12273 				 */
12274 				NFS4_DEBUG(nfs4_client_state_debug,
12275 					(CE_NOTE, "nfs4_update_dircaches: "
12276 					"don't update dnlc: created_v4 flag"));
12277 			}
12278 			mutex_exit(&VTOR4(vp)->r_statev4_lock);
12279 		}
12280 
12281 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12282 				dinfo->di_cred, FALSE, cinfo);
12283 
12284 		return;
12285 	}
12286 
12287 	/*
12288 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12289 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12290 	 * attrs, the dir's attrs must be purged.
12291 	 *
12292 	 * XXX this check and dnlc update/purge should really be atomic,
12293 	 * XXX but can't use rnode statelock because it'll deadlock in
12294 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12295 	 * XXX does occur.
12296 	 *
12297 	 * XXX We also may want to check that atomic is true in the
12298 	 * XXX change_info struct. If it is not, the change_info may
12299 	 * XXX reflect changes by more than one clients which means that
12300 	 * XXX our cache may not be valid.
12301 	 */
12302 	PURGE_ATTRCACHE4(dvp);
12303 	if (drp->r_change == cinfo->before) {
12304 		/* no changes took place in the directory prior to our link */
12305 		if (vp != NULL) {
12306 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12307 			if (!VTOR4(vp)->created_v4) {
12308 				dnlc_update(dvp, nm, vp);
12309 			} else {
12310 				/*
12311 				 * XXX dont' update if the created_v4 flag
12312 				 * is set
12313 				 */
12314 
12315 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12316 					"nfs4_update_dircaches: don't"
12317 					" update dnlc: created_v4 flag"));
12318 			}
12319 			mutex_exit(&VTOR4(vp)->r_statev4_lock);
12320 		}
12321 	} else {
12322 		/* Another client modified directory - purge its dnlc cache */
12323 		dnlc_purge_vp(dvp);
12324 	}
12325 }
12326 
12327 /*
12328  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12329  * file.
12330  *
12331  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12332  * file (ie: client recovery) and otherwise set to FALSE.
12333  *
12334  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12335  * initiated) calling functions.
12336  *
12337  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12338  * of resending a 'lost' open request.
12339  *
12340  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12341  * server that hands out BAD_SEQID on open confirm.
12342  *
12343  * Errors are returned via the nfs4_error_t parameter.
12344  */
12345 void
12346 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12347 	bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12348 	bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12349 {
12350 	COMPOUND4args_clnt args;
12351 	COMPOUND4res_clnt res;
12352 	nfs_argop4 argop[2];
12353 	nfs_resop4 *resop;
12354 	int doqueue = 1;
12355 	mntinfo4_t *mi;
12356 	OPEN_CONFIRM4args *open_confirm_args;
12357 	int needrecov;
12358 
12359 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
12360 #if DEBUG
12361 	mutex_enter(&oop->oo_lock);
12362 	ASSERT(oop->oo_seqid_inuse);
12363 	mutex_exit(&oop->oo_lock);
12364 #endif
12365 
12366 recov_retry_confirm:
12367 	nfs4_error_zinit(ep);
12368 	*retry_open = FALSE;
12369 
12370 	if (resend)
12371 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12372 	else
12373 		args.ctag = TAG_OPEN_CONFIRM;
12374 
12375 	args.array_len = 2;
12376 	args.array = argop;
12377 
12378 	/* putfh target fh */
12379 	argop[0].argop = OP_CPUTFH;
12380 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12381 
12382 	argop[1].argop = OP_OPEN_CONFIRM;
12383 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12384 
12385 	(*seqid) += 1;
12386 	open_confirm_args->seqid = *seqid;
12387 	open_confirm_args->open_stateid = *stateid;
12388 
12389 	mi = VTOMI4(vp);
12390 
12391 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12392 
12393 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12394 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12395 	}
12396 
12397 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12398 	if (!needrecov && ep->error)
12399 		return;
12400 
12401 	if (needrecov) {
12402 		bool_t abort = FALSE;
12403 
12404 		if (reopening_file == FALSE) {
12405 			nfs4_bseqid_entry_t *bsep = NULL;
12406 
12407 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12408 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12409 					vp, 0, args.ctag,
12410 					open_confirm_args->seqid);
12411 
12412 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp,
12413 				    NULL, NULL, NULL, OP_OPEN_CONFIRM, bsep);
12414 			if (bsep) {
12415 				kmem_free(bsep, sizeof (*bsep));
12416 				if (num_bseqid_retryp &&
12417 				    --(*num_bseqid_retryp) == 0)
12418 					abort = TRUE;
12419 			}
12420 		}
12421 		if ((ep->error == ETIMEDOUT ||
12422 					res.status == NFS4ERR_RESOURCE) &&
12423 					abort == FALSE && resend == FALSE) {
12424 			if (!ep->error)
12425 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12426 								(caddr_t)&res);
12427 
12428 			delay(SEC_TO_TICK(confirm_retry_sec));
12429 			goto recov_retry_confirm;
12430 		}
12431 		/* State may have changed so retry the entire OPEN op */
12432 		if (abort == FALSE)
12433 			*retry_open = TRUE;
12434 		else
12435 			*retry_open = FALSE;
12436 		if (!ep->error)
12437 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12438 		return;
12439 	}
12440 
12441 	if (res.status) {
12442 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12443 		return;
12444 	}
12445 
12446 	resop = &res.array[1];  /* open confirm res */
12447 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
12448 				stateid, sizeof (*stateid));
12449 
12450 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12451 }
12452 
12453 /*
12454  * Return the credentials associated with a client state object.  The
12455  * caller is responsible for freeing the credentials.
12456  */
12457 
12458 static cred_t *
12459 state_to_cred(nfs4_open_stream_t *osp)
12460 {
12461 	cred_t *cr;
12462 
12463 	/*
12464 	 * It's ok to not lock the open stream and open owner to get
12465 	 * the oo_cred since this is only written once (upon creation)
12466 	 * and will not change.
12467 	 */
12468 	cr = osp->os_open_owner->oo_cred;
12469 	crhold(cr);
12470 
12471 	return (cr);
12472 }
12473 
12474 /*
12475  * nfs4_find_sysid
12476  *
12477  * Find the sysid for the knetconfig associated with the given mi.
12478  */
12479 static struct lm_sysid *
12480 nfs4_find_sysid(mntinfo4_t *mi)
12481 {
12482 	ASSERT(curproc->p_zone == mi->mi_zone);
12483 
12484 	/*
12485 	 * Switch from RDMA knconf to original mount knconf
12486 	 */
12487 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
12488 		    mi->mi_curr_serv->sv_hostname, NULL));
12489 }
12490 
12491 #ifdef DEBUG
12492 /*
12493  * Return a string version of the call type for easy reading.
12494  */
12495 static char *
12496 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
12497 {
12498 	switch (ctype) {
12499 	case NFS4_LCK_CTYPE_NORM:
12500 		return ("NORMAL");
12501 	case NFS4_LCK_CTYPE_RECLAIM:
12502 		return ("RECLAIM");
12503 	case NFS4_LCK_CTYPE_RESEND:
12504 		return ("RESEND");
12505 	case NFS4_LCK_CTYPE_REINSTATE:
12506 		return ("REINSTATE");
12507 	default:
12508 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
12509 			"type %d", ctype);
12510 		return ("");
12511 	}
12512 }
12513 #endif
12514 
12515 /*
12516  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
12517  * Unlock requests don't have an over-the-wire locktype, so we just return
12518  * something non-threatening.
12519  */
12520 
12521 static nfs_lock_type4
12522 flk_to_locktype(int cmd, int l_type)
12523 {
12524 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
12525 
12526 	switch (l_type) {
12527 	case F_UNLCK:
12528 		return (READ_LT);
12529 	case F_RDLCK:
12530 		if (cmd == F_SETLK)
12531 			return (READ_LT);
12532 		else
12533 			return (READW_LT);
12534 	case F_WRLCK:
12535 		if (cmd == F_SETLK)
12536 			return (WRITE_LT);
12537 		else
12538 			return (WRITEW_LT);
12539 	}
12540 	panic("flk_to_locktype");
12541 	/*NOTREACHED*/
12542 }
12543 
12544 /*
12545  * Do some preliminary checks for nfs4frlock.
12546  */
12547 static int
12548 nfs4frlock_validate_args(int cmd, flock64_t *flk, int flag, vnode_t *vp,
12549 	u_offset_t offset)
12550 {
12551 	int error = 0;
12552 
12553 	/*
12554 	 * If we are setting a lock, check that the file is opened
12555 	 * with the correct mode.
12556 	 */
12557 	if (cmd == F_SETLK || cmd == F_SETLKW) {
12558 		if ((flk->l_type == F_RDLCK && (flag & FREAD) == 0) ||
12559 		    (flk->l_type == F_WRLCK && (flag & FWRITE) == 0)) {
12560 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12561 			    "nfs4frlock_validate_args: file was opened with "
12562 			    "incorrect mode"));
12563 			return (EBADF);
12564 		}
12565 	}
12566 
12567 	/* Convert the offset. It may need to be restored before returning. */
12568 	if (error = convoff(vp, flk, 0, offset)) {
12569 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12570 		    "nfs4frlock_validate_args: convoff  =>  error= %d\n",
12571 		    error));
12572 		return (error);
12573 	}
12574 
12575 	return (error);
12576 }
12577 
12578 /*
12579  * Set the flock64's lm_sysid for nfs4frlock.
12580  */
12581 static int
12582 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
12583 {
12584 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
12585 
12586 	/* Find the lm_sysid */
12587 	*lspp = nfs4_find_sysid(VTOMI4(vp));
12588 
12589 	if (*lspp == NULL) {
12590 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12591 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
12592 		return (ENOLCK);
12593 	}
12594 
12595 	flk->l_sysid = lm_sysidt(*lspp);
12596 
12597 	return (0);
12598 }
12599 
12600 /*
12601  * Do the remaining preliminary setup for nfs4frlock.
12602  */
12603 static void
12604 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
12605 	flock64_t *flk, short *whencep, vnode_t *vp, cred_t *search_cr,
12606 	cred_t **cred_otw)
12607 {
12608 	/*
12609 	 * set tick_delay to the base delay time.
12610 	 * (NFS4_BASE_WAIT_TIME is in secs)
12611 	 */
12612 
12613 	*tick_delayp = drv_usectohz(NFS4_BASE_WAIT_TIME * 1000 * 1000);
12614 
12615 	/*
12616 	 * If lock is relative to EOF, we need the newest length of the
12617 	 * file. Therefore invalidate the ATTR_CACHE.
12618 	 */
12619 
12620 	*whencep = flk->l_whence;
12621 
12622 	if (*whencep == 2)		/* SEEK_END */
12623 		PURGE_ATTRCACHE4(vp);
12624 
12625 	recov_statep->rs_flags = 0;
12626 	recov_statep->rs_num_retry_despite_err = 0;
12627 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
12628 }
12629 
12630 /*
12631  * Initialize and allocate the data structures necessary for
12632  * the nfs4frlock call.
12633  * Allocates argsp's op array, frees up the saved_rqstpp if there is one.
12634  */
12635 static void
12636 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
12637 	nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
12638 	bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
12639 	bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
12640 {
12641 	int		argoplist_size;
12642 	int		num_ops = 2;
12643 
12644 	*retry = FALSE;
12645 	*did_start_fop = FALSE;
12646 	*skip_get_err = FALSE;
12647 	lost_rqstp->lr_op = 0;
12648 	argoplist_size  = num_ops * sizeof (nfs_argop4);
12649 	/* fill array with zero */
12650 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
12651 
12652 	*argspp = argsp;
12653 	*respp = NULL;
12654 
12655 	argsp->array_len = num_ops;
12656 	argsp->array = *argopp;
12657 
12658 	/* initialize in case of error; will get real value down below */
12659 	argsp->ctag = TAG_NONE;
12660 
12661 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
12662 		*op_hintp = OH_LOCKU;
12663 	else
12664 		*op_hintp = OH_OTHER;
12665 }
12666 
12667 /*
12668  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
12669  * the proper nfs4_server_t for this instance of nfs4frlock.
12670  * Returns 0 (success) or an errno value.
12671  */
12672 static int
12673 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
12674 	nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
12675 	bool_t *did_start_fop, bool_t *startrecovp)
12676 {
12677 	int error = 0;
12678 	rnode4_t *rp;
12679 
12680 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
12681 
12682 	if (ctype == NFS4_LCK_CTYPE_NORM) {
12683 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
12684 				recov_statep, startrecovp);
12685 		if (error)
12686 			return (error);
12687 		*did_start_fop = TRUE;
12688 	} else {
12689 		*did_start_fop = FALSE;
12690 		*startrecovp = FALSE;
12691 	}
12692 
12693 	if (!error) {
12694 		rp = VTOR4(vp);
12695 
12696 		/* If the file failed recovery, just quit. */
12697 		mutex_enter(&rp->r_statelock);
12698 		if (rp->r_flags & R4RECOVERR) {
12699 			error = EIO;
12700 		}
12701 		mutex_exit(&rp->r_statelock);
12702 	}
12703 
12704 	return (error);
12705 }
12706 
12707 /*
12708  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
12709  * resend nfs4frlock call is initiated by the recovery framework.
12710  * Acquires the lop and oop seqid synchronization.
12711  */
12712 static void
12713 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
12714 	COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
12715 	nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
12716 	LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
12717 {
12718 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
12719 	int error;
12720 
12721 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
12722 		(CE_NOTE,
12723 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
12724 	ASSERT(resend_rqstp != NULL);
12725 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
12726 	    resend_rqstp->lr_op == OP_LOCKU);
12727 
12728 	*oopp = resend_rqstp->lr_oop;
12729 	if (resend_rqstp->lr_oop) {
12730 		open_owner_hold(resend_rqstp->lr_oop);
12731 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
12732 		ASSERT(error == 0);	/* recov thread always succeeds */
12733 	}
12734 
12735 	/* Must resend this lost lock/locku request. */
12736 	ASSERT(resend_rqstp->lr_lop != NULL);
12737 	*lopp = resend_rqstp->lr_lop;
12738 	lock_owner_hold(resend_rqstp->lr_lop);
12739 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
12740 	ASSERT(error == 0);	/* recov thread always succeeds */
12741 
12742 	*ospp = resend_rqstp->lr_osp;
12743 	if (*ospp)
12744 		open_stream_hold(resend_rqstp->lr_osp);
12745 
12746 	if (resend_rqstp->lr_op == OP_LOCK) {
12747 		LOCK4args *lock_args;
12748 
12749 		argop->argop = OP_LOCK;
12750 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
12751 		lock_args->locktype = resend_rqstp->lr_locktype;
12752 		lock_args->reclaim =
12753 			(resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
12754 		lock_args->offset = resend_rqstp->lr_flk->l_start;
12755 		lock_args->length = resend_rqstp->lr_flk->l_len;
12756 		if (lock_args->length == 0)
12757 			lock_args->length = ~lock_args->length;
12758 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
12759 				mi2clientid(mi), &lock_args->locker);
12760 
12761 		switch (resend_rqstp->lr_ctype) {
12762 		case NFS4_LCK_CTYPE_RESEND:
12763 			argsp->ctag = TAG_LOCK_RESEND;
12764 			break;
12765 		case NFS4_LCK_CTYPE_REINSTATE:
12766 			argsp->ctag = TAG_LOCK_REINSTATE;
12767 			break;
12768 		case NFS4_LCK_CTYPE_RECLAIM:
12769 			argsp->ctag = TAG_LOCK_RECLAIM;
12770 			break;
12771 		default:
12772 			argsp->ctag = TAG_LOCK_UNKNOWN;
12773 			break;
12774 		}
12775 	} else {
12776 		LOCKU4args *locku_args;
12777 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
12778 
12779 		argop->argop = OP_LOCKU;
12780 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
12781 		locku_args->locktype = READ_LT;
12782 		locku_args->seqid = lop->lock_seqid + 1;
12783 		mutex_enter(&lop->lo_lock);
12784 		locku_args->lock_stateid = lop->lock_stateid;
12785 		mutex_exit(&lop->lo_lock);
12786 		locku_args->offset = resend_rqstp->lr_flk->l_start;
12787 		locku_args->length = resend_rqstp->lr_flk->l_len;
12788 		if (locku_args->length == 0)
12789 			locku_args->length = ~locku_args->length;
12790 
12791 		switch (resend_rqstp->lr_ctype) {
12792 		case NFS4_LCK_CTYPE_RESEND:
12793 			argsp->ctag = TAG_LOCKU_RESEND;
12794 			break;
12795 		case NFS4_LCK_CTYPE_REINSTATE:
12796 			argsp->ctag = TAG_LOCKU_REINSTATE;
12797 			break;
12798 		default:
12799 			argsp->ctag = TAG_LOCK_UNKNOWN;
12800 			break;
12801 		}
12802 	}
12803 }
12804 
12805 /*
12806  * Setup the LOCKT4 arguments.
12807  */
12808 static void
12809 nfs4frlock_setup_lockt_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
12810 	LOCKT4args **lockt_argsp, COMPOUND4args_clnt *argsp, flock64_t *flk,
12811 	rnode4_t *rp)
12812 {
12813 	LOCKT4args *lockt_args;
12814 
12815 	ASSERT(curproc->p_zone == VTOMI4(RTOV4(rp))->mi_zone);
12816 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
12817 	argop->argop = OP_LOCKT;
12818 	argsp->ctag = TAG_LOCKT;
12819 	lockt_args = &argop->nfs_argop4_u.oplockt;
12820 
12821 	/*
12822 	 * The locktype will be READ_LT unless it's
12823 	 * a write lock. We do this because the Solaris
12824 	 * system call allows the combination of
12825 	 * F_UNLCK and F_GETLK* and so in that case the
12826 	 * unlock is mapped to a read.
12827 	 */
12828 	if (flk->l_type == F_WRLCK)
12829 		lockt_args->locktype = WRITE_LT;
12830 	else
12831 		lockt_args->locktype = READ_LT;
12832 
12833 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
12834 	/* set the lock owner4 args */
12835 	nfs4_setlockowner_args(&lockt_args->owner, rp,
12836 	    ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
12837 	    flk->l_pid);
12838 	lockt_args->offset = flk->l_start;
12839 	lockt_args->length = flk->l_len;
12840 	if (flk->l_len == 0)
12841 		lockt_args->length = ~lockt_args->length;
12842 
12843 	*lockt_argsp = lockt_args;
12844 }
12845 
12846 /*
12847  * If the client is holding a delegation, and the open stream to be used
12848  * with this lock request is a delegation open stream, then re-open the stream.
12849  * Sets the nfs4_error_t to all zeros unless the open stream has already
12850  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
12851  * means the caller should retry (like a recovery retry).
12852  */
12853 static void
12854 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
12855 {
12856 	open_delegation_type4	dt;
12857 	bool_t			reopen_needed, force;
12858 	nfs4_open_stream_t	*osp;
12859 	open_claim_type4 	oclaim;
12860 	rnode4_t		*rp = VTOR4(vp);
12861 	mntinfo4_t		*mi = VTOMI4(vp);
12862 
12863 	ASSERT(curproc->p_zone == mi->mi_zone);
12864 
12865 	nfs4_error_zinit(ep);
12866 
12867 	mutex_enter(&rp->r_statev4_lock);
12868 	dt = rp->r_deleg_type;
12869 	mutex_exit(&rp->r_statev4_lock);
12870 
12871 	if (dt != OPEN_DELEGATE_NONE) {
12872 		nfs4_open_owner_t	*oop;
12873 
12874 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
12875 		if (!oop) {
12876 			ep->stat = NFS4ERR_IO;
12877 			return;
12878 		}
12879 		/* returns with 'os_sync_lock' held */
12880 		osp = find_open_stream(oop, rp);
12881 		if (!osp) {
12882 			open_owner_rele(oop);
12883 			ep->stat = NFS4ERR_IO;
12884 			return;
12885 		}
12886 
12887 		if (osp->os_failed_reopen) {
12888 			NFS4_DEBUG((nfs4_open_stream_debug ||
12889 				    nfs4_client_lock_debug), (CE_NOTE,
12890 			    "nfs4frlock_check_deleg: os_failed_reopen set "
12891 			    "for osp %p, cr %p, rp %s", (void *)osp,
12892 			    (void *)cr, rnode4info(rp)));
12893 			mutex_exit(&osp->os_sync_lock);
12894 			open_stream_rele(osp, rp);
12895 			open_owner_rele(oop);
12896 			ep->stat = NFS4ERR_IO;
12897 			return;
12898 		}
12899 
12900 		/*
12901 		 * Determine whether a reopen is needed.  If this
12902 		 * is a delegation open stream, then send the open
12903 		 * to the server to give visibility to the open owner.
12904 		 * Even if it isn't a delegation open stream, we need
12905 		 * to check if the previous open CLAIM_DELEGATE_CUR
12906 		 * was sufficient.
12907 		 */
12908 
12909 		reopen_needed = osp->os_delegation ||
12910 		    ((lt == F_RDLCK &&
12911 			!(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
12912 		    (lt == F_WRLCK &&
12913 			!(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
12914 
12915 		mutex_exit(&osp->os_sync_lock);
12916 		open_owner_rele(oop);
12917 
12918 		if (reopen_needed) {
12919 			/*
12920 			 * Always use CLAIM_PREVIOUS after server reboot.
12921 			 * The server will reject CLAIM_DELEGATE_CUR if
12922 			 * it is used during the grace period.
12923 			 */
12924 			mutex_enter(&mi->mi_lock);
12925 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
12926 				oclaim = CLAIM_PREVIOUS;
12927 				force = TRUE;
12928 			} else {
12929 				oclaim = CLAIM_DELEGATE_CUR;
12930 				force = FALSE;
12931 			}
12932 			mutex_exit(&mi->mi_lock);
12933 
12934 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
12935 			if (ep->error == EAGAIN) {
12936 				nfs4_error_zinit(ep);
12937 				ep->stat = NFS4ERR_DELAY;
12938 			}
12939 		}
12940 		open_stream_rele(osp, rp);
12941 		osp = NULL;
12942 	}
12943 }
12944 
12945 /*
12946  * Setup the LOCKU4 arguments.
12947  * Returns errors via the nfs4_error_t.
12948  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
12949  *			over-the-wire.  The caller must release the
12950  *			reference on *lopp.
12951  * NFS4ERR_DELAY	caller should retry (like recovery retry)
12952  * (other)		unrecoverable error.
12953  */
12954 static void
12955 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
12956 	LOCKU4args **locku_argsp, flock64_t *flk,
12957 	nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
12958 	vnode_t *vp, int flag, u_offset_t offset, cred_t *cr,
12959 	bool_t *skip_get_err, bool_t *go_otwp)
12960 {
12961 	nfs4_lock_owner_t	*lop = NULL;
12962 	LOCKU4args		*locku_args;
12963 	pid_t			pid;
12964 	bool_t			is_spec = FALSE;
12965 	rnode4_t		*rp = VTOR4(vp);
12966 
12967 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
12968 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
12969 
12970 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
12971 	if (ep->error || ep->stat)
12972 		return;
12973 
12974 	argop->argop = OP_LOCKU;
12975 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
12976 		argsp->ctag = TAG_LOCKU_REINSTATE;
12977 	else
12978 		argsp->ctag = TAG_LOCKU;
12979 	locku_args = &argop->nfs_argop4_u.oplocku;
12980 	*locku_argsp = locku_args;
12981 
12982 	/*
12983 	 * XXX what should locku_args->locktype be?
12984 	 * setting to ALWAYS be READ_LT so at least
12985 	 * it is a valid locktype.
12986 	 */
12987 
12988 	locku_args->locktype = READ_LT;
12989 
12990 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
12991 		flk->l_pid;
12992 
12993 	/*
12994 	 * Get the lock owner stateid.  If no lock owner
12995 	 * exists, return success.
12996 	 */
12997 	lop = find_lock_owner(rp, pid, LOWN_ANY);
12998 	*lopp = lop;
12999 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13000 		is_spec = TRUE;
13001 	if (!lop || is_spec) {
13002 		/*
13003 		 * No lock owner so no locks to unlock.
13004 		 * Return success.  If there was a failed
13005 		 * reclaim earlier, the lock might still be
13006 		 * registered with the local locking code,
13007 		 * so notify it of the unlock.
13008 		 *
13009 		 * If the lockowner is using a special stateid,
13010 		 * then the original lock request (that created
13011 		 * this lockowner) was never successful, so we
13012 		 * have no lock to undo OTW.
13013 		 */
13014 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13015 			"nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13016 			"(%ld) so return success", (long)pid));
13017 
13018 		if (ctype == NFS4_LCK_CTYPE_NORM)
13019 			flk->l_pid = curproc->p_pid;
13020 		nfs4_register_lock_locally(vp, flk, flag, offset);
13021 		/*
13022 		 * Release our hold and NULL out so final_cleanup
13023 		 * doesn't try to end a lock seqid sync we
13024 		 * never started.
13025 		 */
13026 		if (is_spec) {
13027 			lock_owner_rele(lop);
13028 			*lopp = NULL;
13029 		}
13030 		*skip_get_err = TRUE;
13031 		*go_otwp = FALSE;
13032 		return;
13033 	}
13034 
13035 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13036 	if (ep->error == EAGAIN) {
13037 		lock_owner_rele(lop);
13038 		*lopp = NULL;
13039 		return;
13040 	}
13041 
13042 	mutex_enter(&lop->lo_lock);
13043 	locku_args->lock_stateid = lop->lock_stateid;
13044 	mutex_exit(&lop->lo_lock);
13045 	locku_args->seqid = lop->lock_seqid + 1;
13046 
13047 	/* leave the ref count on lop, rele after RPC call */
13048 
13049 	locku_args->offset = flk->l_start;
13050 	locku_args->length = flk->l_len;
13051 	if (flk->l_len == 0)
13052 		locku_args->length = ~locku_args->length;
13053 
13054 	*go_otwp = TRUE;
13055 }
13056 
13057 /*
13058  * Setup the LOCK4 arguments.
13059  *
13060  * Returns errors via the nfs4_error_t.
13061  * NFS4_OK		no problems
13062  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13063  * (other)		unrecoverable error
13064  */
13065 static void
13066 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13067 	nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13068 	nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13069 	flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13070 {
13071 	LOCK4args		*lock_args;
13072 	nfs4_open_owner_t	*oop = NULL;
13073 	nfs4_open_stream_t	*osp = NULL;
13074 	nfs4_lock_owner_t	*lop = NULL;
13075 	pid_t			pid;
13076 	rnode4_t		*rp = VTOR4(vp);
13077 
13078 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
13079 
13080 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13081 	if (ep->error || ep->stat != NFS4_OK)
13082 		return;
13083 
13084 	argop->argop = OP_LOCK;
13085 	if (ctype == NFS4_LCK_CTYPE_NORM)
13086 		argsp->ctag = TAG_LOCK;
13087 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13088 		argsp->ctag = TAG_RELOCK;
13089 	else
13090 		argsp->ctag = TAG_LOCK_REINSTATE;
13091 	lock_args = &argop->nfs_argop4_u.oplock;
13092 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13093 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13094 	/*
13095 	 * Get the lock owner.  If no lock owner exists,
13096 	 * create a 'temporary' one and grab the open seqid
13097 	 * synchronization (which puts a hold on the open
13098 	 * owner and open stream).
13099 	 * This also grabs the lock seqid synchronization.
13100 	 */
13101 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid : flk->l_pid;
13102 	ep->stat =
13103 		nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13104 
13105 	if (ep->stat != NFS4_OK)
13106 		goto out;
13107 
13108 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13109 			&lock_args->locker);
13110 
13111 	lock_args->offset = flk->l_start;
13112 	lock_args->length = flk->l_len;
13113 	if (flk->l_len == 0)
13114 		lock_args->length = ~lock_args->length;
13115 	*lock_argsp = lock_args;
13116 out:
13117 	*oopp = oop;
13118 	*ospp = osp;
13119 	*lopp = lop;
13120 }
13121 
13122 /*
13123  * After we get the reply from the server, record the proper information
13124  * for possible resend lock requests.
13125  *
13126  * Allocates memory for the saved_rqstp if we have a lost lock to save.
13127  */
13128 static void
13129 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13130 	nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13131 	nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13132 	nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13133 {
13134 	bool_t unlock = (flk->l_type == F_UNLCK);
13135 
13136 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
13137 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13138 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13139 
13140 	if (error != 0 && !unlock) {
13141 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13142 			    nfs4_client_lock_debug), (CE_NOTE,
13143 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13144 		    " for lop %p", (void *)lop));
13145 		ASSERT(lop != NULL);
13146 		mutex_enter(&lop->lo_lock);
13147 		lop->lo_pending_rqsts = 1;
13148 		mutex_exit(&lop->lo_lock);
13149 	}
13150 
13151 	lost_rqstp->lr_putfirst = FALSE;
13152 	lost_rqstp->lr_op = 0;
13153 
13154 	/*
13155 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13156 	 * recovery purposes so that the lock request that was sent
13157 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13158 	 * unmount.  This is done to have the client's local locking state
13159 	 * match the v4 server's state; that is, the request was
13160 	 * potentially received and accepted by the server but the client
13161 	 * thinks it was not.
13162 	 */
13163 	if (error == ETIMEDOUT || error == EINTR ||
13164 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13165 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13166 			    nfs4_client_lock_debug), (CE_NOTE,
13167 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13168 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13169 		    (void *)lop, (void *)oop, (void *)osp));
13170 		if (unlock)
13171 			lost_rqstp->lr_op = OP_LOCKU;
13172 		else {
13173 			lost_rqstp->lr_op = OP_LOCK;
13174 			lost_rqstp->lr_locktype = locktype;
13175 		}
13176 		/*
13177 		 * Objects are held and rele'd via the recovery code.
13178 		 * See nfs4_save_lost_rqst.
13179 		 */
13180 		lost_rqstp->lr_vp = vp;
13181 		lost_rqstp->lr_dvp = NULL;
13182 		lost_rqstp->lr_oop = oop;
13183 		lost_rqstp->lr_osp = osp;
13184 		lost_rqstp->lr_lop = lop;
13185 		lost_rqstp->lr_cr = cr;
13186 		switch (ctype) {
13187 		case NFS4_LCK_CTYPE_NORM:
13188 			flk->l_pid = ttoproc(curthread)->p_pid;
13189 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13190 			break;
13191 		case NFS4_LCK_CTYPE_REINSTATE:
13192 			lost_rqstp->lr_putfirst = TRUE;
13193 			lost_rqstp->lr_ctype = ctype;
13194 			break;
13195 		default:
13196 			break;
13197 		}
13198 		lost_rqstp->lr_flk = flk;
13199 	}
13200 }
13201 
13202 /*
13203  * Update lop's seqid.  Also update the seqid stored in a resend request,
13204  * if any.  (Some recovery errors increment the seqid, and we may have to
13205  * send the resend request again.)
13206  */
13207 
13208 static void
13209 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13210     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13211 {
13212 	if (lock_args) {
13213 		if (lock_args->locker.new_lock_owner == TRUE)
13214 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13215 		else {
13216 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13217 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13218 		}
13219 	} else if (locku_args) {
13220 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13221 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13222 	}
13223 }
13224 
13225 /*
13226  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13227  * COMPOUND4 args/res for calls that need to retry.
13228  * Switches the *cred_otwp to base_cr.
13229  */
13230 static void
13231 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13232     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13233     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13234     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13235     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13236 {
13237 	nfs4_open_owner_t	*oop = *oopp;
13238 	nfs4_open_stream_t	*osp = *ospp;
13239 	nfs4_lock_owner_t	*lop = *lopp;
13240 	nfs_argop4		*argop = (*argspp)->array;
13241 
13242 	if (*did_start_fop) {
13243 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13244 			    needrecov);
13245 		*did_start_fop = FALSE;
13246 	}
13247 	ASSERT((*argspp)->array_len == 2);
13248 	if (argop[1].argop == OP_LOCK)
13249 		nfs4args_lock_free(&argop[1]);
13250 	else if (argop[1].argop == OP_LOCKT)
13251 		nfs4args_lockt_free(&argop[1]);
13252 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13253 	if (!error)
13254 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13255 	*argspp = NULL;
13256 	*respp = NULL;
13257 
13258 	if (lop) {
13259 		nfs4_end_lock_seqid_sync(lop);
13260 		lock_owner_rele(lop);
13261 		*lopp = NULL;
13262 	}
13263 
13264 	/* need to free up the reference on osp for lock args */
13265 	if (osp != NULL) {
13266 		open_stream_rele(osp, VTOR4(vp));
13267 		*ospp = NULL;
13268 	}
13269 
13270 	/* need to free up the reference on oop for lock args */
13271 	if (oop != NULL) {
13272 		nfs4_end_open_seqid_sync(oop);
13273 		open_owner_rele(oop);
13274 		*oopp = NULL;
13275 	}
13276 
13277 	crfree(*cred_otwp);
13278 	*cred_otwp = base_cr;
13279 	crhold(*cred_otwp);
13280 }
13281 
13282 /*
13283  * Function to process the client's recovery for nfs4frlock.
13284  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13285  *
13286  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13287  * COMPOUND4 args/res for calls that need to retry.
13288  *
13289  * Note: the rp's r_lkserlock is *not* dropped during this path.
13290  */
13291 static bool_t
13292 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13293 	COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13294 	LOCK4args *lock_args, LOCKU4args *locku_args,
13295 	nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13296 	nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13297 	nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13298 	bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13299 {
13300 	nfs4_open_owner_t	*oop = *oopp;
13301 	nfs4_open_stream_t	*osp = *ospp;
13302 	nfs4_lock_owner_t	*lop = *lopp;
13303 
13304 	bool_t abort, retry;
13305 
13306 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
13307 	ASSERT((*argspp) != NULL);
13308 	ASSERT((*respp) != NULL);
13309 	if (lock_args || locku_args)
13310 		ASSERT(lop != NULL);
13311 
13312 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13313 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13314 
13315 	retry = TRUE;
13316 	abort = FALSE;
13317 	if (needrecov) {
13318 		nfs4_bseqid_entry_t *bsep = NULL;
13319 		nfs_opnum4 op;
13320 
13321 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13322 
13323 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13324 			seqid4 seqid;
13325 
13326 			if (lock_args) {
13327 				if (lock_args->locker.new_lock_owner == TRUE)
13328 					seqid = lock_args->locker.locker4_u.
13329 						    open_owner.open_seqid;
13330 				else
13331 					seqid = lock_args->locker.locker4_u.
13332 						    lock_owner.lock_seqid;
13333 			} else if (locku_args) {
13334 				seqid = locku_args->seqid;
13335 			} else {
13336 				seqid = 0;
13337 			}
13338 
13339 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13340 				flk->l_pid, (*argspp)->ctag, seqid);
13341 		}
13342 
13343 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13344 			    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13345 			    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13346 			    NULL, op, bsep);
13347 
13348 		if (bsep)
13349 			kmem_free(bsep, sizeof (*bsep));
13350 	}
13351 
13352 	/*
13353 	 * Return that we do not want to retry the request for 3 cases:
13354 	 * 1. If we received EINTR or are bailing out because of a forced
13355 	 *    unmount, we came into this code path just for the sake of
13356 	 *    initiating recovery, we now need to return the error.
13357 	 * 2. If we have aborted recovery.
13358 	 * 3. We received NFS4ERR_BAD_SEQID.
13359 	 */
13360 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13361 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13362 		retry = FALSE;
13363 
13364 	if (*did_start_fop == TRUE) {
13365 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13366 		    needrecov);
13367 		*did_start_fop = FALSE;
13368 	}
13369 
13370 	if (retry == TRUE) {
13371 		nfs_argop4	*argop;
13372 
13373 		argop = (*argspp)->array;
13374 		ASSERT((*argspp)->array_len == 2);
13375 
13376 		if (argop[1].argop == OP_LOCK)
13377 			nfs4args_lock_free(&argop[1]);
13378 		else if (argop[1].argop == OP_LOCKT)
13379 			nfs4args_lockt_free(&argop[1]);
13380 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13381 		if (!ep->error)
13382 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13383 		*respp = NULL;
13384 		*argspp = NULL;
13385 	}
13386 
13387 	if (lop != NULL) {
13388 		nfs4_end_lock_seqid_sync(lop);
13389 		lock_owner_rele(lop);
13390 	}
13391 
13392 	*lopp = NULL;
13393 
13394 	/* need to free up the reference on osp for lock args */
13395 	if (osp != NULL) {
13396 		open_stream_rele(osp, rp);
13397 		*ospp = NULL;
13398 	}
13399 
13400 	/* need to free up the reference on oop for lock args */
13401 	if (oop != NULL) {
13402 		nfs4_end_open_seqid_sync(oop);
13403 		open_owner_rele(oop);
13404 		*oopp = NULL;
13405 	}
13406 
13407 	return (retry);
13408 }
13409 
13410 /*
13411  * Handles the succesful reply from the server for nfs4frlock.
13412  */
13413 static void
13414 nfs4frlock_results_ok(nfs4_lock_call_type_t ctype, int cmd, flock64_t *flk,
13415 	vnode_t *vp, int flag, u_offset_t offset,
13416 	nfs4_lost_rqst_t *resend_rqstp)
13417 {
13418 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
13419 	if ((cmd == F_SETLK || cmd == F_SETLKW) &&
13420 	    (flk->l_type == F_RDLCK || flk->l_type == F_WRLCK)) {
13421 		if (ctype == NFS4_LCK_CTYPE_NORM) {
13422 			flk->l_pid = ttoproc(curthread)->p_pid;
13423 			/*
13424 			 * We do not register lost locks locally in
13425 			 * the 'resend' case since the user/application
13426 			 * doesn't think we have the lock.
13427 			 */
13428 			ASSERT(!resend_rqstp);
13429 			nfs4_register_lock_locally(vp, flk, flag, offset);
13430 		}
13431 	}
13432 }
13433 
13434 /*
13435  * Handle the DENIED reply from the server for nfs4frlock.
13436  * Returns TRUE if we should retry the request; FALSE otherwise.
13437  *
13438  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13439  * COMPOUND4 args/res for calls that need to retry.  Can also
13440  * drop and regrab the r_lkserlock.
13441  */
13442 static bool_t
13443 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13444 	LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13445 	nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13446 	vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13447 	nfs4_recov_state_t *recov_statep, int needrecov,
13448 	COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13449 	clock_t *tick_delayp, short *whencep, int *errorp,
13450 	nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13451 	bool_t *skip_get_err)
13452 {
13453 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
13454 
13455 	if (lock_args) {
13456 		nfs4_open_owner_t	*oop = *oopp;
13457 		nfs4_open_stream_t	*osp = *ospp;
13458 		nfs4_lock_owner_t	*lop = *lopp;
13459 		int			intr;
13460 
13461 		/*
13462 		 * Blocking lock needs to sleep and retry from the request.
13463 		 *
13464 		 * Do not block and wait for 'resend' or 'reinstate'
13465 		 * lock requests, just return the error.
13466 		 *
13467 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13468 		 */
13469 		if (cmd == F_SETLKW) {
13470 			rnode4_t *rp = VTOR4(vp);
13471 			nfs_argop4 *argop = (*argspp)->array;
13472 
13473 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13474 
13475 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13476 				recov_statep, needrecov);
13477 			*did_start_fop = FALSE;
13478 			ASSERT((*argspp)->array_len == 2);
13479 			if (argop[1].argop == OP_LOCK)
13480 				nfs4args_lock_free(&argop[1]);
13481 			else if (argop[1].argop == OP_LOCKT)
13482 				nfs4args_lockt_free(&argop[1]);
13483 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13484 			if (*respp)
13485 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13486 							(caddr_t)*respp);
13487 			*argspp = NULL;
13488 			*respp = NULL;
13489 			nfs4_end_lock_seqid_sync(lop);
13490 			lock_owner_rele(lop);
13491 			*lopp = NULL;
13492 			if (osp != NULL) {
13493 				open_stream_rele(osp, rp);
13494 				*ospp = NULL;
13495 			}
13496 			if (oop != NULL) {
13497 				nfs4_end_open_seqid_sync(oop);
13498 				open_owner_rele(oop);
13499 				*oopp = NULL;
13500 			}
13501 
13502 			nfs_rw_exit(&rp->r_lkserlock);
13503 
13504 			intr = nfs4_block_and_wait(tick_delayp, rp);
13505 
13506 			if (intr) {
13507 				(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13508 						RW_WRITER, FALSE);
13509 				*errorp = EINTR;
13510 				return (FALSE);
13511 			}
13512 
13513 			(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13514 					RW_WRITER, FALSE);
13515 
13516 			/*
13517 			 * Make sure we are still safe to lock with
13518 			 * regards to mmapping.
13519 			 */
13520 			if (!nfs4_safelock(vp, flk, cr)) {
13521 				*errorp = EAGAIN;
13522 				return (FALSE);
13523 			}
13524 
13525 			return (TRUE);
13526 		}
13527 		if (ctype == NFS4_LCK_CTYPE_NORM)
13528 			*errorp = EAGAIN;
13529 		*skip_get_err = TRUE;
13530 		flk->l_whence = 0;
13531 		*whencep = 0;
13532 		return (FALSE);
13533 	} else if (lockt_args) {
13534 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13535 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
13536 
13537 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
13538 			flk, lockt_args);
13539 
13540 		/* according to NLM code */
13541 		*errorp = 0;
13542 		*whencep = 0;
13543 		*skip_get_err = TRUE;
13544 		return (FALSE);
13545 	}
13546 	return (FALSE);
13547 }
13548 
13549 /*
13550  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
13551  */
13552 static void
13553 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
13554 {
13555 	switch (resp->status) {
13556 	case NFS4ERR_ACCESS:
13557 	case NFS4ERR_ADMIN_REVOKED:
13558 	case NFS4ERR_BADHANDLE:
13559 	case NFS4ERR_BAD_RANGE:
13560 	case NFS4ERR_BAD_SEQID:
13561 	case NFS4ERR_BAD_STATEID:
13562 	case NFS4ERR_BADXDR:
13563 	case NFS4ERR_DEADLOCK:
13564 	case NFS4ERR_DELAY:
13565 	case NFS4ERR_EXPIRED:
13566 	case NFS4ERR_FHEXPIRED:
13567 	case NFS4ERR_GRACE:
13568 	case NFS4ERR_INVAL:
13569 	case NFS4ERR_ISDIR:
13570 	case NFS4ERR_LEASE_MOVED:
13571 	case NFS4ERR_LOCK_NOTSUPP:
13572 	case NFS4ERR_LOCK_RANGE:
13573 	case NFS4ERR_MOVED:
13574 	case NFS4ERR_NOFILEHANDLE:
13575 	case NFS4ERR_NO_GRACE:
13576 	case NFS4ERR_OLD_STATEID:
13577 	case NFS4ERR_OPENMODE:
13578 	case NFS4ERR_RECLAIM_BAD:
13579 	case NFS4ERR_RECLAIM_CONFLICT:
13580 	case NFS4ERR_RESOURCE:
13581 	case NFS4ERR_SERVERFAULT:
13582 	case NFS4ERR_STALE:
13583 	case NFS4ERR_STALE_CLIENTID:
13584 	case NFS4ERR_STALE_STATEID:
13585 		return;
13586 	default:
13587 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13588 		    "nfs4frlock_results_default: got unrecognizable "
13589 		    "res.status %d", resp->status));
13590 		*errorp = NFS4ERR_INVAL;
13591 	}
13592 }
13593 
13594 /*
13595  * The lock request was successful, so update the client's state.
13596  */
13597 static void
13598 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
13599 	LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
13600 	vnode_t *vp, flock64_t *flk, cred_t *cr,
13601 	nfs4_lost_rqst_t *resend_rqstp)
13602 {
13603 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
13604 
13605 	if (lock_args) {
13606 		LOCK4res *lock_res;
13607 
13608 		lock_res = &resop->nfs_resop4_u.oplock;
13609 		/* update the stateid with server's response */
13610 
13611 		if (lock_args->locker.new_lock_owner == TRUE) {
13612 			mutex_enter(&lop->lo_lock);
13613 			lop->lo_just_created = NFS4_PERM_CREATED;
13614 			mutex_exit(&lop->lo_lock);
13615 		}
13616 
13617 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
13618 
13619 		/*
13620 		 * If the lock was the result of a resending a lost
13621 		 * request, we've synched up the stateid and seqid
13622 		 * with the server, but now the server might be out of sync
13623 		 * with what the application thinks it has for locks.
13624 		 * Clean that up here.  It's unclear whether we should do
13625 		 * this even if the filesystem has been forcibly unmounted.
13626 		 * For most servers, it's probably wasted effort, but
13627 		 * RFC3530 lets servers require that unlocks exactly match
13628 		 * the locks that are held.
13629 		 */
13630 		if (resend_rqstp != NULL &&
13631 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
13632 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
13633 		} else {
13634 			flk->l_whence = 0;
13635 		}
13636 	} else if (locku_args) {
13637 		LOCKU4res *locku_res;
13638 
13639 		locku_res = &resop->nfs_resop4_u.oplocku;
13640 
13641 		/* Update the stateid with the server's response */
13642 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
13643 	} else if (lockt_args) {
13644 		/* Switch the lock type to express success, see fcntl */
13645 		flk->l_type = F_UNLCK;
13646 		flk->l_whence = 0;
13647 	}
13648 }
13649 
13650 /*
13651  * Do final cleanup before exiting nfs4frlock.
13652  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13653  * COMPOUND4 args/res for calls that haven't already.
13654  */
13655 static void
13656 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
13657 	COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
13658 	nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
13659 	nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13660 	short whence, u_offset_t offset, struct lm_sysid *ls,
13661 	int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
13662 	bool_t did_start_fop, bool_t skip_get_err,
13663 	cred_t *cred_otw, cred_t *cred)
13664 {
13665 	mntinfo4_t	*mi = VTOMI4(vp);
13666 	rnode4_t	*rp = VTOR4(vp);
13667 	int		error = *errorp;
13668 	nfs_argop4	*argop;
13669 
13670 	ASSERT(curproc->p_zone == mi->mi_zone);
13671 	/*
13672 	 * The client recovery code wants the raw status information,
13673 	 * so don't map the NFS status code to an errno value for
13674 	 * non-normal call types.
13675 	 */
13676 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13677 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
13678 			*errorp = geterrno4(resp->status);
13679 		if (did_start_fop == TRUE)
13680 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
13681 				needrecov);
13682 
13683 		if (!error && resp && resp->status == NFS4_OK) {
13684 		/*
13685 		 * We've established a new lock on the server, so invalidate
13686 		 * the pages associated with the vnode to get the most up to
13687 		 * date pages from the server after acquiring the lock. We
13688 		 * want to be sure that the read operation gets the newest data.
13689 		 * N.B.
13690 		 * We used to do this in nfs4frlock_results_ok but that doesn't
13691 		 * work since VOP_PUTPAGE can call nfs4_commit which calls
13692 		 * nfs4_start_fop. We flush the pages below after calling
13693 		 * nfs4_end_fop above
13694 		 */
13695 			int error;
13696 
13697 			error = VOP_PUTPAGE(vp, (u_offset_t)0,
13698 						0, B_INVAL, cred);
13699 
13700 			if (error && (error == ENOSPC || error == EDQUOT)) {
13701 				rnode4_t *rp = VTOR4(vp);
13702 
13703 				mutex_enter(&rp->r_statelock);
13704 				if (!rp->r_error)
13705 					rp->r_error = error;
13706 				mutex_exit(&rp->r_statelock);
13707 			}
13708 		}
13709 	}
13710 	if (argsp) {
13711 		ASSERT(argsp->array_len == 2);
13712 		argop = argsp->array;
13713 		if (argop[1].argop == OP_LOCK)
13714 			nfs4args_lock_free(&argop[1]);
13715 		else if (argop[1].argop == OP_LOCKT)
13716 			nfs4args_lockt_free(&argop[1]);
13717 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13718 		if (resp)
13719 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
13720 	}
13721 
13722 	/* free the reference on the lock owner */
13723 	if (lop != NULL) {
13724 		nfs4_end_lock_seqid_sync(lop);
13725 		lock_owner_rele(lop);
13726 	}
13727 
13728 	/* need to free up the reference on osp for lock args */
13729 	if (osp != NULL)
13730 		open_stream_rele(osp, rp);
13731 
13732 	/* need to free up the reference on oop for lock args */
13733 	if (oop != NULL) {
13734 		nfs4_end_open_seqid_sync(oop);
13735 		open_owner_rele(oop);
13736 	}
13737 
13738 	(void) convoff(vp, flk, whence, offset);
13739 
13740 	lm_rel_sysid(ls);
13741 
13742 	/*
13743 	 * Record debug information in the event we get EINVAL.
13744 	 */
13745 	mutex_enter(&mi->mi_lock);
13746 	if (*errorp == EINVAL && (lock_args || locku_args) &&
13747 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
13748 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
13749 			zcmn_err(getzoneid(), CE_NOTE,
13750 			    "%s operation failed with "
13751 			    "EINVAL probably since the server, %s,"
13752 			    " doesn't support POSIX style locking",
13753 			    lock_args ? "LOCK" : "LOCKU",
13754 			    mi->mi_curr_serv->sv_hostname);
13755 			mi->mi_flags |= MI4_LOCK_DEBUG;
13756 		}
13757 	}
13758 	mutex_exit(&mi->mi_lock);
13759 
13760 	if (cred_otw)
13761 		crfree(cred_otw);
13762 }
13763 
13764 /*
13765  * This calls the server and the local locking code.
13766  *
13767  * Client locks are registerred locally by oring the sysid with
13768  * LM_SYSID_CLIENT. The server registers locks locally using just the sysid.
13769  * We need to distinguish between the two to avoid collision in case one
13770  * machine is used as both client and server.
13771  *
13772  * Blocking lock requests will continually retry to acquire the lock
13773  * forever.
13774  *
13775  * The ctype is defined as follows:
13776  * NFS4_LCK_CTYPE_NORM: normal lock request.
13777  *
13778  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
13779  * recovery, get the pid from flk instead of curproc, and don't reregister
13780  * the lock locally.
13781  *
13782  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
13783  * that we will use the information passed in via resend_rqstp to setup the
13784  * lock/locku request.  This resend is the exact same request as the 'lost
13785  * lock', and is initiated by the recovery framework. A successful resend
13786  * request can initiate one or more reinstate requests.
13787  *
13788  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
13789  * does not trigger additional reinstate requests.  This lock call type is
13790  * set for setting the v4 server's locking state back to match what the
13791  * client's local locking state is in the event of a received 'lost lock'.
13792  *
13793  * Errors are returned via the nfs4_error_t parameter.
13794  */
13795 void
13796 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
13797 		int flag, u_offset_t offset, cred_t *cr, nfs4_error_t *ep,
13798 		nfs4_lost_rqst_t *resend_rqstp, int *did_reclaimp)
13799 {
13800 	COMPOUND4args_clnt	args, *argsp = NULL;
13801 	COMPOUND4res_clnt	res, *resp = NULL;
13802 	nfs_argop4	*argop;
13803 	nfs_resop4	*resop;
13804 	rnode4_t	*rp;
13805 	int		doqueue = 1;
13806 	clock_t		tick_delay;  /* delay in clock ticks */
13807 	struct lm_sysid	*ls;
13808 	LOCK4args	*lock_args = NULL;
13809 	LOCKU4args	*locku_args = NULL;
13810 	LOCKT4args	*lockt_args = NULL;
13811 	nfs4_open_owner_t *oop = NULL;
13812 	nfs4_open_stream_t *osp = NULL;
13813 	nfs4_lock_owner_t *lop = NULL;
13814 	bool_t		needrecov = FALSE;
13815 	nfs4_recov_state_t recov_state;
13816 	short		whence;
13817 	nfs4_op_hint_t	op_hint;
13818 	nfs4_lost_rqst_t lost_rqst;
13819 	bool_t		retry = FALSE;
13820 	bool_t		did_start_fop = FALSE;
13821 	bool_t		skip_get_err = FALSE;
13822 	cred_t		*cred_otw = NULL;
13823 	bool_t		recovonly;	/* just queue request */
13824 	int		frc_no_reclaim = 0;
13825 #ifdef DEBUG
13826 	char *name;
13827 #endif
13828 
13829 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
13830 
13831 #ifdef DEBUG
13832 	name = fn_name(VTOSV(vp)->sv_name);
13833 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
13834 	    "%s: cmd %d, type %d, offset %llu, start %"PRIx64", "
13835 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
13836 	    "resend request %s", name, cmd, flk->l_type, offset, flk->l_start,
13837 	    flk->l_len, ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid :
13838 	    flk->l_pid, flk->l_sysid, nfs4frlock_get_call_type(ctype),
13839 	    resend_rqstp ? "TRUE" : "FALSE"));
13840 	kmem_free(name, MAXNAMELEN);
13841 #endif
13842 
13843 	nfs4_error_zinit(ep);
13844 	ep->error = nfs4frlock_validate_args(cmd, flk, flag, vp, offset);
13845 	if (ep->error)
13846 		return;
13847 	ep->error = nfs4frlock_get_sysid(&ls, vp, flk);
13848 	if (ep->error)
13849 		return;
13850 	nfs4frlock_pre_setup(&tick_delay, &recov_state, flk, &whence,
13851 	    vp, cr, &cred_otw);
13852 
13853 recov_retry:
13854 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
13855 		&retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
13856 	rp = VTOR4(vp);
13857 
13858 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
13859 			    &did_start_fop, &recovonly);
13860 
13861 	if (ep->error)
13862 		goto out;
13863 
13864 	if (recovonly) {
13865 		/*
13866 		 * Leave the request for the recovery system to deal with.
13867 		 */
13868 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13869 		ASSERT(cmd != F_GETLK);
13870 		ASSERT(flk->l_type == F_UNLCK);
13871 
13872 		nfs4_error_init(ep, EINTR);
13873 		needrecov = TRUE;
13874 		lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
13875 		if (lop != NULL) {
13876 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
13877 				NULL, NULL, lop, flk, &lost_rqst, cr, vp);
13878 			(void) nfs4_start_recovery(ep,
13879 				VTOMI4(vp), vp, NULL, NULL,
13880 				(lost_rqst.lr_op == OP_LOCK ||
13881 				lost_rqst.lr_op == OP_LOCKU) ?
13882 				&lost_rqst : NULL, OP_LOCKU, NULL);
13883 			lock_owner_rele(lop);
13884 			lop = NULL;
13885 		}
13886 		flk->l_pid = curproc->p_pid;
13887 		nfs4_register_lock_locally(vp, flk, flag, offset);
13888 		goto out;
13889 	}
13890 
13891 	/* putfh directory fh */
13892 	argop[0].argop = OP_CPUTFH;
13893 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
13894 
13895 	/*
13896 	 * Set up the over-the-wire arguments and get references to the
13897 	 * open owner, etc.
13898 	 */
13899 
13900 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
13901 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
13902 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
13903 			&argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
13904 	} else {
13905 		bool_t go_otw = TRUE;
13906 
13907 		ASSERT(resend_rqstp == NULL);
13908 
13909 		switch (cmd) {
13910 		case F_GETLK:
13911 		case F_O_GETLK:
13912 			nfs4frlock_setup_lockt_args(ctype, &argop[1],
13913 					&lockt_args, argsp, flk, rp);
13914 			break;
13915 		case F_SETLKW:
13916 		case F_SETLK:
13917 			if (flk->l_type == F_UNLCK)
13918 				nfs4frlock_setup_locku_args(ctype,
13919 						&argop[1], &locku_args, flk,
13920 						&lop, ep, argsp,
13921 						vp, flag, offset, cr,
13922 						&skip_get_err, &go_otw);
13923 			else
13924 				nfs4frlock_setup_lock_args(ctype,
13925 					&lock_args, &oop, &osp, &lop, &argop[1],
13926 					argsp, flk, cmd, vp, cr, ep);
13927 
13928 			if (ep->error)
13929 				goto out;
13930 
13931 			switch (ep->stat) {
13932 			case NFS4_OK:
13933 				break;
13934 			case NFS4ERR_DELAY:
13935 				/* recov thread never gets this error */
13936 				ASSERT(resend_rqstp == NULL);
13937 				ASSERT(did_start_fop);
13938 
13939 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13940 				    &recov_state, TRUE);
13941 				did_start_fop = FALSE;
13942 				if (argop[1].argop == OP_LOCK)
13943 					nfs4args_lock_free(&argop[1]);
13944 				else if (argop[1].argop == OP_LOCKT)
13945 					nfs4args_lockt_free(&argop[1]);
13946 				kmem_free(argop, 2 * sizeof (nfs_argop4));
13947 				argsp = NULL;
13948 				goto recov_retry;
13949 			default:
13950 				ep->error = EIO;
13951 				goto out;
13952 			}
13953 			break;
13954 		default:
13955 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13956 				"nfs4_frlock: invalid cmd %d", cmd));
13957 			ep->error = EINVAL;
13958 			goto out;
13959 		}
13960 
13961 		if (!go_otw)
13962 			goto out;
13963 	}
13964 
13965 	/* XXX should we use the local reclock as a cache ? */
13966 	/*
13967 	 * Unregister the lock with the local locking code before
13968 	 * contacting the server.  This avoids a potential race where
13969 	 * another process gets notified that it has been granted a lock
13970 	 * before we can unregister ourselves locally.
13971 	 */
13972 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK) {
13973 		if (ctype == NFS4_LCK_CTYPE_NORM)
13974 			flk->l_pid = ttoproc(curthread)->p_pid;
13975 		nfs4_register_lock_locally(vp, flk, flag, offset);
13976 	}
13977 
13978 	/*
13979 	 * Send the server the lock request.  Continually loop with a delay
13980 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
13981 	 */
13982 	resp = &res;
13983 
13984 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
13985 	    (CE_NOTE,
13986 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
13987 	    rnode4info(rp)));
13988 
13989 	if (lock_args && frc_no_reclaim) {
13990 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
13991 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13992 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
13993 		lock_args->reclaim = FALSE;
13994 		if (did_reclaimp)
13995 			*did_reclaimp = 0;
13996 	}
13997 
13998 	/*
13999 	 * Do the OTW call.
14000 	 */
14001 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14002 
14003 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14004 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14005 
14006 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14007 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14008 	    "nfs4frlock: needrecov %d", needrecov));
14009 
14010 	if (ep->error != 0 && !needrecov && ep->error != EACCES)
14011 		goto out;
14012 
14013 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14014 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14015 		    args.ctag);
14016 
14017 	if ((ep->error == EACCES ||
14018 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14019 	    cred_otw != cr) {
14020 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14021 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14022 		    cr, &cred_otw);
14023 		goto recov_retry;
14024 	}
14025 
14026 	if (needrecov) {
14027 		/*
14028 		 * LOCKT requests don't need to recover from lost
14029 		 * requests since they don't create/modify state.
14030 		 */
14031 		if ((ep->error == EINTR ||
14032 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14033 		    lockt_args)
14034 			goto out;
14035 		/*
14036 		 * Do not attempt recovery for requests initiated by
14037 		 * the recovery framework.  Let the framework redrive them.
14038 		 */
14039 		if (ctype != NFS4_LCK_CTYPE_NORM)
14040 			goto out;
14041 		else {
14042 			ASSERT(resend_rqstp == NULL);
14043 		}
14044 
14045 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14046 			flk_to_locktype(cmd, flk->l_type),
14047 			oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14048 
14049 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14050 			    &resp, lock_args, locku_args, &oop, &osp, &lop,
14051 			    rp, vp, &recov_state, op_hint, &did_start_fop,
14052 			    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14053 
14054 		if (retry) {
14055 			ASSERT(oop == NULL);
14056 			ASSERT(osp == NULL);
14057 			ASSERT(lop == NULL);
14058 			goto recov_retry;
14059 		}
14060 		goto out;
14061 	}
14062 
14063 	/*
14064 	 * Process the reply.
14065 	 */
14066 	switch (resp->status) {
14067 	case NFS4_OK:
14068 		resop = &resp->array[1];
14069 		nfs4frlock_results_ok(ctype, cmd, flk, vp, flag, offset,
14070 			resend_rqstp);
14071 		/*
14072 		 * Have a successful lock operation, now update state.
14073 		 */
14074 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14075 			resop, lop, vp, flk, cr, resend_rqstp);
14076 		break;
14077 
14078 	case NFS4ERR_DENIED:
14079 		resop = &resp->array[1];
14080 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14081 				&oop, &osp, &lop, cmd, vp, flk, op_hint,
14082 				&recov_state, needrecov, &argsp, &resp,
14083 				&tick_delay, &whence, &ep->error, resop, cr,
14084 				&did_start_fop, &skip_get_err);
14085 
14086 		if (retry) {
14087 			ASSERT(oop == NULL);
14088 			ASSERT(osp == NULL);
14089 			ASSERT(lop == NULL);
14090 			goto recov_retry;
14091 		}
14092 		break;
14093 	/*
14094 	 * If the server won't let us reclaim, fall-back to trying to lock
14095 	 * the file from scratch. Code elsewhere will check the changeinfo
14096 	 * to ensure the file hasn't been changed.
14097 	 */
14098 	case NFS4ERR_NO_GRACE:
14099 		if (lock_args && lock_args->reclaim == TRUE) {
14100 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14101 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14102 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14103 			frc_no_reclaim = 1;
14104 			/* clean up before retrying */
14105 			needrecov = 0;
14106 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14107 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14108 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14109 			goto recov_retry;
14110 		}
14111 		/* FALLTHROUGH */
14112 
14113 	default:
14114 		nfs4frlock_results_default(resp, &ep->error);
14115 		break;
14116 	}
14117 out:
14118 	/*
14119 	 * Process and cleanup from error.  Make interrupted unlock
14120 	 * requests look successful, since they will be handled by the
14121 	 * client recovery code.
14122 	 */
14123 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14124 		needrecov, oop, osp, lop, flk, whence, offset, ls, &ep->error,
14125 		lock_args, locku_args, did_start_fop,
14126 		skip_get_err, cred_otw, cr);
14127 
14128 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14129 	    (cmd == F_SETLK || cmd == F_SETLKW))
14130 		ep->error = 0;
14131 }
14132 
14133 /*
14134  * nfs4_safelock:
14135  *
14136  * Return non-zero if the given lock request can be handled without
14137  * violating the constraints on concurrent mapping and locking.
14138  */
14139 
14140 static int
14141 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14142 {
14143 	rnode4_t *rp = VTOR4(vp);
14144 	struct vattr va;
14145 	int error;
14146 
14147 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
14148 	ASSERT(rp->r_mapcnt >= 0);
14149 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14150 		"(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14151 		"write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14152 		bfp->l_start, bfp->l_len, rp->r_mapcnt));
14153 
14154 	if (rp->r_mapcnt == 0)
14155 		return (1);		/* always safe if not mapped */
14156 
14157 	/*
14158 	 * If the file is already mapped and there are locks, then they
14159 	 * should be all safe locks.  So adding or removing a lock is safe
14160 	 * as long as the new request is safe (i.e., whole-file, meaning
14161 	 * length and starting offset are both zero).
14162 	 */
14163 
14164 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14165 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14166 			"cannot lock a memory mapped file unless locking the "
14167 			"entire file: start %"PRIx64", len %"PRIx64,
14168 			bfp->l_start, bfp->l_len));
14169 		return (0);
14170 	}
14171 
14172 	/* mandatory locking and mapping don't mix */
14173 	va.va_mask = AT_MODE;
14174 	error = VOP_GETATTR(vp, &va, 0, cr);
14175 	if (error != 0) {
14176 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14177 		"getattr error %d", error));
14178 		return (0);		/* treat errors conservatively */
14179 	}
14180 	if (MANDLOCK(vp, va.va_mode)) {
14181 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14182 			"cannot mandatory lock and mmap a file"));
14183 		return (0);
14184 	}
14185 
14186 	return (1);
14187 }
14188 
14189 
14190 /*
14191  * Register the lock locally within Solaris.
14192  * As the client, we "or" the sysid with LM_SYSID_CLIENT when
14193  * recording locks locally.
14194  *
14195  * This should handle conflicts/cooperation with NFS v2/v3 since all locks
14196  * are registered locally.
14197  */
14198 void
14199 nfs4_register_lock_locally(vnode_t *vp, struct flock64 *flk, int flag,
14200 	u_offset_t offset)
14201 {
14202 	int oldsysid;
14203 	int error;
14204 #ifdef DEBUG
14205 	char *name;
14206 #endif
14207 
14208 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
14209 
14210 #ifdef DEBUG
14211 	name = fn_name(VTOSV(vp)->sv_name);
14212 	NFS4_DEBUG(nfs4_client_lock_debug,
14213 	    (CE_NOTE, "nfs4_register_lock_locally: %s: type %d, "
14214 	    "start %"PRIx64", length %"PRIx64", pid %ld, sysid %d",
14215 	    name, flk->l_type, flk->l_start, flk->l_len, (long)flk->l_pid,
14216 	    flk->l_sysid));
14217 	kmem_free(name, MAXNAMELEN);
14218 #endif
14219 
14220 	/* register the lock with local locking */
14221 	oldsysid = flk->l_sysid;
14222 	flk->l_sysid |= LM_SYSID_CLIENT;
14223 	error = reclock(vp, flk, SETFLCK, flag, offset, NULL);
14224 #ifdef DEBUG
14225 	if (error != 0) {
14226 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14227 			"nfs4_register_lock_locally: could not register with"
14228 			" local locking"));
14229 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14230 			"error %d, vp 0x%p, pid %d, sysid 0x%x",
14231 			error, (void *)vp, flk->l_pid, flk->l_sysid));
14232 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14233 			"type %d off 0x%" PRIx64 " len 0x%" PRIx64,
14234 			flk->l_type, flk->l_start, flk->l_len));
14235 		(void) reclock(vp, flk, 0, flag, offset, NULL);
14236 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14237 			"blocked by pid %d sysid 0x%x type %d "
14238 			"off 0x%" PRIx64 " len 0x%" PRIx64,
14239 			flk->l_pid, flk->l_sysid, flk->l_type, flk->l_start,
14240 			flk->l_len));
14241 	}
14242 #endif
14243 	flk->l_sysid = oldsysid;
14244 }
14245 
14246 /*
14247  * nfs4_lockrelease:
14248  *
14249  * Release any locks on the given vnode that are held by the current
14250  * process.  Also removes the lock owner (if one exists) from the rnode's
14251  * list.
14252  */
14253 static int
14254 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14255 {
14256 	flock64_t ld;
14257 	int ret, error;
14258 	rnode4_t *rp;
14259 	nfs4_lock_owner_t *lop;
14260 	nfs4_recov_state_t recov_state;
14261 	mntinfo4_t *mi;
14262 	bool_t possible_orphan = FALSE;
14263 	bool_t recovonly;
14264 
14265 	ASSERT((uintptr_t)vp > KERNELBASE);
14266 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
14267 
14268 	rp = VTOR4(vp);
14269 	mi = VTOMI4(vp);
14270 
14271 	/*
14272 	 * If we have not locked anything then we can
14273 	 * just return since we have no work to do.
14274 	 */
14275 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14276 		return (0);
14277 	}
14278 
14279 	/*
14280 	 * We need to comprehend that another thread may
14281 	 * kick off recovery and the lock_owner we have stashed
14282 	 * in lop might be invalid so we should NOT cache it
14283 	 * locally!
14284 	 */
14285 	recov_state.rs_flags = 0;
14286 	recov_state.rs_num_retry_despite_err = 0;
14287 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14288 			    &recovonly);
14289 	if (error) {
14290 		mutex_enter(&rp->r_statelock);
14291 		rp->r_flags |= R4LODANGLERS;
14292 		mutex_exit(&rp->r_statelock);
14293 		return (error);
14294 	}
14295 
14296 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14297 
14298 	/*
14299 	 * Check if the lock owner might have a lock (request was sent but
14300 	 * no response was received).  Also check if there are any remote
14301 	 * locks on the file.  (In theory we shouldn't have to make this
14302 	 * second check if there's no lock owner, but for now we'll be
14303 	 * conservative and do it anyway.)  If either condition is true,
14304 	 * send an unlock for the entire file to the server.
14305 	 *
14306 	 * Note that no explicit synchronization is needed here.  At worst,
14307 	 * flk_has_remote_locks() will return a false positive, in which case
14308 	 * the unlock call wastes time but doesn't harm correctness.
14309 	 */
14310 
14311 	if (lop) {
14312 		mutex_enter(&lop->lo_lock);
14313 		possible_orphan = lop->lo_pending_rqsts;
14314 		mutex_exit(&lop->lo_lock);
14315 		lock_owner_rele(lop);
14316 	}
14317 
14318 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14319 
14320 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14321 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14322 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14323 	    (void *)lop));
14324 
14325 	if (possible_orphan || flk_has_remote_locks(vp)) {
14326 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14327 		ld.l_whence = 0;	/* unlock from start of file */
14328 		ld.l_start = 0;
14329 		ld.l_len = 0;		/* do entire file */
14330 
14331 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL, cr);
14332 
14333 		if (ret != 0) {
14334 			/*
14335 			 * If VOP_FRLOCK fails, make sure we unregister
14336 			 * local locks before we continue.
14337 			 */
14338 			ld.l_pid = ttoproc(curthread)->p_pid;
14339 			nfs4_register_lock_locally(vp, &ld, flag, offset);
14340 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14341 				"nfs4_lockrelease: lock release error on vp"
14342 				" %p: error %d.\n", (void *)vp, ret));
14343 		}
14344 	}
14345 
14346 	recov_state.rs_flags = 0;
14347 	recov_state.rs_num_retry_despite_err = 0;
14348 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14349 			    &recovonly);
14350 	if (error) {
14351 		mutex_enter(&rp->r_statelock);
14352 		rp->r_flags |= R4LODANGLERS;
14353 		mutex_exit(&rp->r_statelock);
14354 		return (error);
14355 	}
14356 
14357 	/*
14358 	 * So, here we're going to need to retrieve the lock-owner
14359 	 * again (in case recovery has done a switch-a-roo) and
14360 	 * remove it because we can.
14361 	 */
14362 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14363 
14364 	if (lop) {
14365 		nfs4_rnode_remove_lock_owner(rp, lop);
14366 		lock_owner_rele(lop);
14367 	}
14368 
14369 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14370 	return (0);
14371 }
14372 
14373 /*
14374  * Wait for 'tick_delay' clock ticks.
14375  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14376  * NOTE: lock_lease_time is in seconds.
14377  *
14378  * XXX For future improvements, should implement a waiting queue scheme.
14379  */
14380 static int
14381 nfs4_block_and_wait(clock_t *tick_delay, rnode4_t *rp)
14382 {
14383 	long milliseconds_delay;
14384 	time_t lock_lease_time;
14385 
14386 	/* wait tick_delay clock ticks or siginteruptus */
14387 	if (delay_sig(*tick_delay)) {
14388 		return (EINTR);
14389 	}
14390 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14391 		"reissue the lock request: blocked for %ld clock ticks: %ld "
14392 		"milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14393 
14394 	/* get the lease time */
14395 	lock_lease_time = r2lease_time(rp);
14396 
14397 	/* drv_hztousec converts ticks to microseconds */
14398 	milliseconds_delay = drv_hztousec(*tick_delay) / 1000;
14399 	if (milliseconds_delay < lock_lease_time * 1000) {
14400 		*tick_delay = 2 * *tick_delay;
14401 		if (drv_hztousec(*tick_delay) > lock_lease_time * 1000 * 1000)
14402 			*tick_delay = drv_usectohz(lock_lease_time*1000*1000);
14403 	}
14404 	return (0);
14405 }
14406 
14407 
14408 void
14409 nfs4_vnops_init(void)
14410 {
14411 }
14412 
14413 void
14414 nfs4_vnops_fini(void)
14415 {
14416 }
14417 
14418 /*
14419  * Return a reference to the directory (parent) vnode for a given vnode,
14420  * using the saved pathname information and the directory file handle.  The
14421  * caller is responsible for disposing of the reference.
14422  * Returns zero or an errno value.
14423  *
14424  * Caller should set need_start_op to FALSE if it is the recovery
14425  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14426  */
14427 int
14428 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14429 {
14430 	svnode_t *svnp;
14431 	vnode_t *dvp = NULL;
14432 	servinfo4_t *svp;
14433 	nfs4_fname_t *mfname;
14434 	int error;
14435 
14436 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
14437 
14438 	if (vp->v_flag & VROOT) {
14439 		nfs4_sharedfh_t *sfh;
14440 		nfs_fh4 fh;
14441 		mntinfo4_t *mi;
14442 
14443 		ASSERT(vp->v_type == VREG);
14444 
14445 		mi = VTOMI4(vp);
14446 		svp = mi->mi_curr_serv;
14447 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14448 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14449 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14450 		sfh = sfh4_get(&fh, VTOMI4(vp));
14451 		nfs_rw_exit(&svp->sv_lock);
14452 		mfname = mi->mi_fname;
14453 		fn_hold(mfname);
14454 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14455 		sfh4_rele(&sfh);
14456 
14457 		if (dvp->v_type == VNON)
14458 			dvp->v_type = VDIR;
14459 		*dvpp = dvp;
14460 		return (0);
14461 	}
14462 
14463 	svnp = VTOSV(vp);
14464 
14465 	if (svnp == NULL) {
14466 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14467 			"shadow node is NULL"));
14468 		return (EINVAL);
14469 	}
14470 
14471 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14472 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14473 			"shadow node name or dfh val == NULL"));
14474 		return (EINVAL);
14475 	}
14476 
14477 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14478 							(int)need_start_op);
14479 	if (error != 0) {
14480 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14481 			"nfs4_make_dotdot returned %d", error));
14482 		return (error);
14483 	}
14484 	if (!dvp) {
14485 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14486 			"nfs4_make_dotdot returned a NULL dvp"));
14487 		return (EIO);
14488 	}
14489 	if (dvp->v_type == VNON)
14490 		dvp->v_type = VDIR;
14491 	ASSERT(dvp->v_type == VDIR);
14492 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14493 		mutex_enter(&dvp->v_lock);
14494 		dvp->v_flag |= V_XATTRDIR;
14495 		mutex_exit(&dvp->v_lock);
14496 	}
14497 	*dvpp = dvp;
14498 	return (0);
14499 }
14500 
14501 /*
14502  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14503  * length that fnamep can accept, including the trailing null.
14504  * Returns 0 if okay, returns an errno value if there was a problem.
14505  */
14506 
14507 int
14508 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14509 {
14510 	char *fn;
14511 	int err = 0;
14512 	servinfo4_t *svp;
14513 	svnode_t *shvp;
14514 
14515 	/*
14516 	 * If the file being opened has VROOT set, then this is
14517 	 * a "file" mount.  sv_name will not be interesting, so
14518 	 * go back to the servinfo4 to get the original mount
14519 	 * path and strip off all but the final edge.  Otherwise
14520 	 * just return the name from the shadow vnode.
14521 	 */
14522 
14523 	if (vp->v_flag & VROOT) {
14524 
14525 		svp = VTOMI4(vp)->mi_curr_serv;
14526 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14527 
14528 		fn = strrchr(svp->sv_path, '/');
14529 		if (fn == NULL)
14530 			err = EINVAL;
14531 		else
14532 			fn++;
14533 	} else {
14534 		shvp = VTOSV(vp);
14535 		fn = fn_name(shvp->sv_name);
14536 	}
14537 
14538 	if (err == 0)
14539 		if (strlen(fn) < maxlen)
14540 			(void) strcpy(fnamep, fn);
14541 		else
14542 			err = ENAMETOOLONG;
14543 
14544 	if (vp->v_flag & VROOT)
14545 		nfs_rw_exit(&svp->sv_lock);
14546 	else
14547 		kmem_free(fn, MAXNAMELEN);
14548 
14549 	return (err);
14550 }
14551 
14552 /*
14553  * If the vnode has pages, run the list and check for
14554  * any that are still dangling. We call this function
14555  * before the OTW CLOSE occurs so we can B_INVAL the
14556  * danglers.
14557  */
14558 static int
14559 nfs4_dross_pages(vnode_t *vp)
14560 {
14561 	page_t *pp;
14562 	kmutex_t *vphm;
14563 	rnode4_t *rp;
14564 
14565 	/* make sure we're looking at the master vnode, not a shadow */
14566 	rp = VTOR4(vp);
14567 	if (IS_SHADOW(vp, rp))
14568 		vp = RTOV4(rp);
14569 
14570 	vphm = page_vnode_mutex(vp);
14571 	mutex_enter(vphm);
14572 	if ((pp = vp->v_pages) != NULL) {
14573 		do {
14574 			if (pp->p_fsdata != C_NOCOMMIT) {
14575 				mutex_exit(vphm);
14576 				return (1);
14577 			}
14578 		} while ((pp = pp->p_vpnext) != vp->v_pages);
14579 	}
14580 	mutex_exit(vphm);
14581 
14582 	return (0);
14583 }
14584 
14585 /*
14586  * Bookkeeping for a close that doesn't need to go over the wire.
14587  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14588  * it is left at 1.
14589  */
14590 void
14591 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14592 {
14593 	rnode4_t		*rp;
14594 	mntinfo4_t		*mi;
14595 
14596 	mi = VTOMI4(vp);
14597 	rp = VTOR4(vp);
14598 
14599 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14600 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14601 	ASSERT(curproc->p_zone == mi->mi_zone);
14602 	ASSERT(mutex_owned(&osp->os_sync_lock));
14603 	ASSERT(*have_lockp);
14604 
14605 	if (!osp->os_valid ||
14606 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14607 		return;
14608 	}
14609 
14610 	/*
14611 	 * This removes the reference obtained at OPEN; ie,
14612 	 * when the open stream structure was created.
14613 	 *
14614 	 * We don't have to worry about calling 'open_stream_rele'
14615 	 * since we our currently holding a reference to this
14616 	 * open stream which means the count can not go to 0 with
14617 	 * this decrement.
14618 	 */
14619 	ASSERT(osp->os_ref_count >= 2);
14620 	osp->os_ref_count--;
14621 	osp->os_valid = 0;
14622 	mutex_exit(&osp->os_sync_lock);
14623 	*have_lockp = 0;
14624 
14625 	nfs4_dec_state_ref_count(mi);
14626 }
14627 
14628 /*
14629  * Close all remaining open streams on the rnode.  These open streams
14630  * could be here because:
14631  * - The close attempted at either close or delmap failed
14632  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
14633  * - Someone did mknod on a regular file but never opened it
14634  */
14635 int
14636 nfs4close_all(vnode_t *vp, cred_t *cr)
14637 {
14638 	nfs4_open_stream_t *osp;
14639 	int error;
14640 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
14641 	rnode4_t *rp;
14642 
14643 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
14644 
14645 	error = 0;
14646 	rp = VTOR4(vp);
14647 
14648 	/*
14649 	 * At this point, all we know is that the last time
14650 	 * someone called vn_rele, the count was 1.  Since then,
14651 	 * the vnode could have been re-activated.  We want to
14652 	 * loop through the open streams and close each one, but
14653 	 * we have to be careful since once we release the rnode
14654 	 * hash bucket lock, someone else is free to come in and
14655 	 * re-activate the rnode and add new open streams.  The
14656 	 * strategy is take the rnode hash bucket lock, verify that
14657 	 * the count is still 1, grab the open stream off the
14658 	 * head of the list and mark it invalid, then release the
14659 	 * rnode hash bucket lock and proceed with that open stream.
14660 	 * This is ok because nfs4close_one() will acquire the proper
14661 	 * open/create to close/destroy synchronization for open
14662 	 * streams, and will ensure that if someone has reopened
14663 	 * the open stream after we've dropped the hash bucket lock
14664 	 * then we'll just simply return without destroying the
14665 	 * open stream.
14666 	 * Repeat until the list is empty.
14667 	 */
14668 
14669 	for (;;) {
14670 
14671 		/* make sure vnode hasn't been reactivated */
14672 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
14673 		mutex_enter(&vp->v_lock);
14674 		if (vp->v_count > 1) {
14675 			mutex_exit(&vp->v_lock);
14676 			rw_exit(&rp->r_hashq->r_lock);
14677 			break;
14678 		}
14679 		/*
14680 		 * Grabbing r_os_lock before releasing v_lock prevents
14681 		 * a window where the rnode/open stream could get
14682 		 * reactivated (and os_force_close set to 0) before we
14683 		 * had a chance to set os_force_close to 1.
14684 		 */
14685 		mutex_enter(&rp->r_os_lock);
14686 		mutex_exit(&vp->v_lock);
14687 
14688 		osp = list_head(&rp->r_open_streams);
14689 		if (!osp) {
14690 			/* nothing left to CLOSE OTW, so return */
14691 			mutex_exit(&rp->r_os_lock);
14692 			rw_exit(&rp->r_hashq->r_lock);
14693 			break;
14694 		}
14695 
14696 		mutex_enter(&rp->r_statev4_lock);
14697 		/* the file can't still be mem mapped */
14698 		ASSERT(rp->r_mapcnt == 0);
14699 		if (rp->created_v4)
14700 			rp->created_v4 = 0;
14701 		mutex_exit(&rp->r_statev4_lock);
14702 
14703 		/*
14704 		 * Grab a ref on this open stream; nfs4close_one
14705 		 * will mark it as invalid
14706 		 */
14707 		mutex_enter(&osp->os_sync_lock);
14708 		osp->os_ref_count++;
14709 		osp->os_force_close = 1;
14710 		mutex_exit(&osp->os_sync_lock);
14711 		mutex_exit(&rp->r_os_lock);
14712 		rw_exit(&rp->r_hashq->r_lock);
14713 
14714 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
14715 
14716 		/* Update error if it isn't already non-zero */
14717 		if (error == 0) {
14718 			if (e.error)
14719 				error = e.error;
14720 			else if (e.stat)
14721 				error = geterrno4(e.stat);
14722 		}
14723 
14724 #ifdef	DEBUG
14725 		nfs4close_all_cnt++;
14726 #endif
14727 		/* Release the ref on osp acquired above. */
14728 		open_stream_rele(osp, rp);
14729 
14730 		/* Proceed to the next open stream, if any */
14731 	}
14732 	return (error);
14733 }
14734 
14735 /*
14736  * nfs4close_one - close one open stream for a file if needed.
14737  *
14738  * "close_type" indicates which close path this is:
14739  * CLOSE_NORM: close initiated via VOP_CLOSE.
14740  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
14741  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
14742  *	the close and release of client state for this open stream
14743  *	(unless someone else has the open stream open).
14744  * CLOSE_RESEND: indicates the request is a replay of an earlier request
14745  *	(e.g., due to abort because of a signal).
14746  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
14747  *
14748  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
14749  * recovery.  Instead, the caller is expected to deal with retries.
14750  *
14751  * The caller can either pass in the osp ('provided_osp') or not.
14752  *
14753  * 'access_bits' represents the access we are closing/downgrading.
14754  *
14755  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
14756  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
14757  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
14758  *
14759  * Errors are returned via the nfs4_error_t.
14760  */
14761 void
14762 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
14763 	int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
14764 	nfs4_close_type_t close_type, size_t len, uint_t maxprot,
14765 	uint_t mmap_flags)
14766 {
14767 	nfs4_open_owner_t *oop;
14768 	nfs4_open_stream_t *osp = NULL;
14769 	int retry = 0;
14770 	int num_retries = NFS4_NUM_RECOV_RETRIES;
14771 	rnode4_t *rp;
14772 	mntinfo4_t *mi;
14773 	nfs4_recov_state_t recov_state;
14774 	cred_t *cred_otw = NULL;
14775 	bool_t recovonly = FALSE;
14776 	int isrecov;
14777 	int force_close;
14778 	int close_failed = 0;
14779 	int did_dec_count = 0;
14780 	int did_start_op = 0;
14781 	int did_force_recovlock = 0;
14782 	int did_start_seqid_sync = 0;
14783 	int have_sync_lock = 0;
14784 
14785 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
14786 
14787 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
14788 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
14789 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
14790 	    len, maxprot, mmap_flags, access_bits));
14791 
14792 	nfs4_error_zinit(ep);
14793 	rp = VTOR4(vp);
14794 	mi = VTOMI4(vp);
14795 	isrecov = (close_type == CLOSE_RESEND ||
14796 			close_type == CLOSE_AFTER_RESEND);
14797 
14798 	/*
14799 	 * First get the open owner.
14800 	 */
14801 	if (!provided_osp) {
14802 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
14803 	} else {
14804 		oop = provided_osp->os_open_owner;
14805 		ASSERT(oop != NULL);
14806 		open_owner_hold(oop);
14807 	}
14808 
14809 	if (!oop) {
14810 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
14811 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
14812 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
14813 		    (void *)provided_osp, close_type));
14814 		ep->error = EIO;
14815 		goto out;
14816 	}
14817 
14818 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
14819 recov_retry:
14820 	osp = NULL;
14821 	close_failed = 0;
14822 	force_close = (close_type == CLOSE_FORCE);
14823 	retry = 0;
14824 	did_start_op = 0;
14825 	did_force_recovlock = 0;
14826 	did_start_seqid_sync = 0;
14827 	have_sync_lock = 0;
14828 	recovonly = FALSE;
14829 	recov_state.rs_flags = 0;
14830 	recov_state.rs_num_retry_despite_err = 0;
14831 
14832 	/*
14833 	 * Second synchronize with recovery.
14834 	 */
14835 	if (!isrecov) {
14836 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
14837 				&recov_state, &recovonly);
14838 		if (!ep->error) {
14839 			did_start_op = 1;
14840 		} else {
14841 			close_failed = 1;
14842 			/*
14843 			 * If we couldn't get start_fop, but have to
14844 			 * cleanup state, then at least acquire the
14845 			 * mi_recovlock so we can synchronize with
14846 			 * recovery.
14847 			 */
14848 			if (close_type == CLOSE_FORCE) {
14849 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
14850 					RW_READER, FALSE);
14851 				did_force_recovlock = 1;
14852 			} else
14853 				goto out;
14854 		}
14855 	}
14856 
14857 	/*
14858 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
14859 	 * set 'recovonly' to TRUE since most likely this is due to
14860 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
14861 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
14862 	 * to retry, causing us to loop until recovery finishes.  Plus we
14863 	 * don't need protection over the open seqid since we're not going
14864 	 * OTW, hence don't need to use the seqid.
14865 	 */
14866 	if (recovonly == FALSE) {
14867 		/* need to grab the open owner sync before 'os_sync_lock' */
14868 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
14869 		if (ep->error == EAGAIN) {
14870 			ASSERT(!isrecov);
14871 			if (did_start_op)
14872 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
14873 					&recov_state, TRUE);
14874 			if (did_force_recovlock)
14875 				nfs_rw_exit(&mi->mi_recovlock);
14876 			goto recov_retry;
14877 		}
14878 		did_start_seqid_sync = 1;
14879 	}
14880 
14881 	/*
14882 	 * Third get an open stream and acquire 'os_sync_lock' to
14883 	 * sychronize the opening/creating of an open stream with the
14884 	 * closing/destroying of an open stream.
14885 	 */
14886 	if (!provided_osp) {
14887 		/* returns with 'os_sync_lock' held */
14888 		osp = find_open_stream(oop, rp);
14889 		if (!osp) {
14890 			ep->error = EIO;
14891 			goto out;
14892 		}
14893 	} else {
14894 		osp = provided_osp;
14895 		open_stream_hold(osp);
14896 		mutex_enter(&osp->os_sync_lock);
14897 	}
14898 	have_sync_lock = 1;
14899 
14900 	ASSERT(oop == osp->os_open_owner);
14901 
14902 	/*
14903 	 * Fourth, do any special pre-OTW CLOSE processing
14904 	 * based on the specific close type.
14905 	 */
14906 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
14907 	    !did_dec_count) {
14908 		ASSERT(osp->os_open_ref_count > 0);
14909 		osp->os_open_ref_count--;
14910 		did_dec_count = 1;
14911 		if (osp->os_open_ref_count == 0)
14912 			osp->os_final_close = 1;
14913 	}
14914 
14915 	if (close_type == CLOSE_FORCE) {
14916 		/* see if somebody reopened the open stream. */
14917 		if (!osp->os_force_close) {
14918 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
14919 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
14920 			    "was reopened, vp %p", (void *)osp, (void *)vp));
14921 			ep->error = 0;
14922 			ep->stat = NFS4_OK;
14923 			goto out;
14924 		}
14925 
14926 		if (!osp->os_final_close && !did_dec_count) {
14927 			osp->os_open_ref_count--;
14928 			did_dec_count = 1;
14929 		}
14930 
14931 		/*
14932 		 * We can't depend on os_open_ref_count being 0 due to the
14933 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
14934 		 */
14935 #ifdef	NOTYET
14936 		ASSERT(osp->os_open_ref_count == 0);
14937 #endif
14938 		if (osp->os_open_ref_count != 0) {
14939 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
14940 			    "nfs4close_one: should panic here on an "
14941 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
14942 			    "since this is probably the exec problem."));
14943 
14944 			osp->os_open_ref_count = 0;
14945 		}
14946 
14947 		/*
14948 		 * There is the possibility that nfs4close_one()
14949 		 * for close_type == CLOSE_DELMAP couldn't find the
14950 		 * open stream, thus couldn't decrement its os_mapcnt;
14951 		 * therefore we can't use this ASSERT yet.
14952 		 */
14953 #ifdef	NOTYET
14954 		ASSERT(osp->os_mapcnt == 0);
14955 #endif
14956 		osp->os_mapcnt = 0;
14957 	}
14958 
14959 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
14960 		ASSERT(osp->os_mapcnt >= btopr(len));
14961 
14962 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
14963 			osp->os_mmap_write -= btopr(len);
14964 		if (maxprot & PROT_READ)
14965 			osp->os_mmap_read -= btopr(len);
14966 		if (maxprot & PROT_EXEC)
14967 			osp->os_mmap_read -= btopr(len);
14968 		/* mirror the PROT_NONE check in nfs4_addmap() */
14969 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
14970 		    !(maxprot & PROT_EXEC))
14971 			osp->os_mmap_read -= btopr(len);
14972 		osp->os_mapcnt -= btopr(len);
14973 		did_dec_count = 1;
14974 	}
14975 
14976 	if (recovonly) {
14977 		nfs4_lost_rqst_t lost_rqst;
14978 
14979 		/* request should not already be in recovery queue */
14980 		ASSERT(lrp == NULL);
14981 		nfs4_error_init(ep, EINTR);
14982 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
14983 			osp, cred_otw, vp);
14984 		mutex_exit(&osp->os_sync_lock);
14985 		have_sync_lock = 0;
14986 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
14987 				lost_rqst.lr_op == OP_CLOSE ?
14988 				&lost_rqst : NULL, OP_CLOSE, NULL);
14989 		close_failed = 1;
14990 		force_close = 0;
14991 		goto close_cleanup;
14992 	}
14993 
14994 	/*
14995 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
14996 	 * we stopped operating on the open owner's <old oo_name, old seqid>
14997 	 * space, which means we stopped operating on the open stream
14998 	 * too.  So don't go OTW (as the seqid is likely bad, and the
14999 	 * stateid could be stale, potentially triggering a false
15000 	 * setclientid), and just clean up the client's internal state.
15001 	 */
15002 	if (osp->os_orig_oo_name != oop->oo_name) {
15003 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15004 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15005 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15006 		    "oo_name %" PRIx64")",
15007 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15008 		    oop->oo_name));
15009 		close_failed = 1;
15010 	}
15011 
15012 	/* If the file failed recovery, just quit. */
15013 	mutex_enter(&rp->r_statelock);
15014 	if (rp->r_flags & R4RECOVERR) {
15015 		close_failed = 1;
15016 	}
15017 	mutex_exit(&rp->r_statelock);
15018 
15019 	/*
15020 	 * If the force close path failed to obtain start_fop
15021 	 * then skip the OTW close and just remove the state.
15022 	 */
15023 	if (close_failed)
15024 		goto close_cleanup;
15025 
15026 	/*
15027 	 * Fifth, check to see if there are still mapped pages or other
15028 	 * opens using this open stream.  If there are then we can't
15029 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15030 	 */
15031 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15032 		nfs4_lost_rqst_t	new_lost_rqst;
15033 		bool_t			needrecov = FALSE;
15034 		cred_t			*odg_cred_otw = NULL;
15035 		seqid4			open_dg_seqid = 0;
15036 
15037 		if (osp->os_delegation) {
15038 			/*
15039 			 * If this open stream was never OPENed OTW then we
15040 			 * surely can't DOWNGRADE it (especially since the
15041 			 * osp->open_stateid is really a delegation stateid
15042 			 * when os_delegation is 1).
15043 			 */
15044 			if (access_bits & FREAD)
15045 				osp->os_share_acc_read--;
15046 			if (access_bits & FWRITE)
15047 				osp->os_share_acc_write--;
15048 			osp->os_share_deny_none--;
15049 			nfs4_error_zinit(ep);
15050 			goto out;
15051 		}
15052 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15053 				lrp, ep, &odg_cred_otw, &open_dg_seqid);
15054 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15055 		if (needrecov && !isrecov) {
15056 			bool_t abort;
15057 			nfs4_bseqid_entry_t *bsep = NULL;
15058 
15059 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15060 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15061 					vp, 0,
15062 					lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15063 					open_dg_seqid);
15064 
15065 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15066 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15067 			mutex_exit(&osp->os_sync_lock);
15068 			have_sync_lock = 0;
15069 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15070 				    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15071 				    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15072 				    bsep);
15073 			if (odg_cred_otw)
15074 				crfree(odg_cred_otw);
15075 			if (bsep)
15076 				kmem_free(bsep, sizeof (*bsep));
15077 
15078 			if (abort == TRUE)
15079 				goto out;
15080 
15081 			if (did_start_seqid_sync) {
15082 				nfs4_end_open_seqid_sync(oop);
15083 				did_start_seqid_sync = 0;
15084 			}
15085 			open_stream_rele(osp, rp);
15086 
15087 			if (did_start_op)
15088 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15089 					&recov_state, FALSE);
15090 			if (did_force_recovlock)
15091 				nfs_rw_exit(&mi->mi_recovlock);
15092 
15093 			goto recov_retry;
15094 		} else {
15095 			if (odg_cred_otw)
15096 				crfree(odg_cred_otw);
15097 		}
15098 		goto out;
15099 	}
15100 
15101 	/*
15102 	 * If this open stream was created as the results of an open
15103 	 * while holding a delegation, then just release it; no need
15104 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15105 	 */
15106 	if (osp->os_delegation) {
15107 		nfs4close_notw(vp, osp, &have_sync_lock);
15108 		nfs4_error_zinit(ep);
15109 		goto out;
15110 	}
15111 
15112 	/*
15113 	 * If this stream is not valid, we're done.
15114 	 */
15115 	if (!osp->os_valid) {
15116 		nfs4_error_zinit(ep);
15117 		goto out;
15118 	}
15119 
15120 	/*
15121 	 * Last open or mmap ref has vanished, need to do an OTW close.
15122 	 * First check to see if a close is still necessary.
15123 	 */
15124 	if (osp->os_failed_reopen) {
15125 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15126 		    "don't close OTW osp %p since reopen failed.",
15127 		    (void *)osp));
15128 		/*
15129 		 * Reopen of the open stream failed, hence the
15130 		 * stateid of the open stream is invalid/stale, and
15131 		 * sending this OTW would incorrectly cause another
15132 		 * round of recovery.  In this case, we need to set
15133 		 * the 'os_valid' bit to 0 so another thread doesn't
15134 		 * come in and re-open this open stream before
15135 		 * this "closing" thread cleans up state (decrementing
15136 		 * the nfs4_server_t's state_ref_count and decrementing
15137 		 * the os_ref_count).
15138 		 */
15139 		osp->os_valid = 0;
15140 		/*
15141 		 * This removes the reference obtained at OPEN; ie,
15142 		 * when the open stream structure was created.
15143 		 *
15144 		 * We don't have to worry about calling 'open_stream_rele'
15145 		 * since we our currently holding a reference to this
15146 		 * open stream which means the count can not go to 0 with
15147 		 * this decrement.
15148 		 */
15149 		ASSERT(osp->os_ref_count >= 2);
15150 		osp->os_ref_count--;
15151 		nfs4_error_zinit(ep);
15152 		close_failed = 0;
15153 		goto close_cleanup;
15154 	}
15155 
15156 	ASSERT(osp->os_ref_count > 1);
15157 
15158 	if (!(vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
15159 		nfs4_dross_pages(vp)) {
15160 		nfs4_invalidate_pages(vp, 0, cred_otw);
15161 	}
15162 
15163 	/*
15164 	 * Sixth, try the CLOSE OTW.
15165 	 */
15166 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15167 	    close_type, ep, &have_sync_lock);
15168 
15169 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15170 		/*
15171 		 * Let the recovery thread be responsible for
15172 		 * removing the state for CLOSE.
15173 		 */
15174 		close_failed = 1;
15175 		force_close = 0;
15176 		retry = 0;
15177 	}
15178 
15179 	/* See if we need to retry with a different cred */
15180 	if ((ep->error == EACCES ||
15181 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15182 	    cred_otw != cr) {
15183 		crfree(cred_otw);
15184 		cred_otw = cr;
15185 		crhold(cred_otw);
15186 		retry = 1;
15187 	}
15188 
15189 	if (ep->error || ep->stat)
15190 		close_failed = 1;
15191 
15192 	if (retry && !isrecov && num_retries-- > 0) {
15193 		if (have_sync_lock) {
15194 			mutex_exit(&osp->os_sync_lock);
15195 			have_sync_lock = 0;
15196 		}
15197 		if (did_start_seqid_sync) {
15198 			nfs4_end_open_seqid_sync(oop);
15199 			did_start_seqid_sync = 0;
15200 		}
15201 		open_stream_rele(osp, rp);
15202 
15203 		if (did_start_op)
15204 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15205 				&recov_state, FALSE);
15206 		if (did_force_recovlock)
15207 			nfs_rw_exit(&mi->mi_recovlock);
15208 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15209 			"nfs4close_one: need to retry the close "
15210 			"operation"));
15211 		goto recov_retry;
15212 	}
15213 close_cleanup:
15214 	/*
15215 	 * Seventh and lastly, process our results.
15216 	 */
15217 	if (close_failed && force_close) {
15218 		/*
15219 		 * It's ok to drop and regrab the 'os_sync_lock' since
15220 		 * nfs4close_notw() will recheck to make sure the
15221 		 * "close"/removal of state should happen.
15222 		 */
15223 		if (!have_sync_lock) {
15224 			mutex_enter(&osp->os_sync_lock);
15225 			have_sync_lock = 1;
15226 		}
15227 		/*
15228 		 * This is last call, remove the ref on the open
15229 		 * stream created by open and clean everything up.
15230 		 */
15231 		osp->os_pending_close = 0;
15232 		nfs4close_notw(vp, osp, &have_sync_lock);
15233 		nfs4_error_zinit(ep);
15234 	}
15235 
15236 	if (!close_failed) {
15237 		if (have_sync_lock) {
15238 			osp->os_pending_close = 0;
15239 			mutex_exit(&osp->os_sync_lock);
15240 			have_sync_lock = 0;
15241 		} else {
15242 			mutex_enter(&osp->os_sync_lock);
15243 			osp->os_pending_close = 0;
15244 			mutex_exit(&osp->os_sync_lock);
15245 		}
15246 		if (did_start_op && recov_state.rs_sp != NULL) {
15247 			mutex_enter(&recov_state.rs_sp->s_lock);
15248 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15249 			mutex_exit(&recov_state.rs_sp->s_lock);
15250 		} else {
15251 			nfs4_dec_state_ref_count(mi);
15252 		}
15253 		nfs4_error_zinit(ep);
15254 	}
15255 
15256 out:
15257 	if (have_sync_lock)
15258 		mutex_exit(&osp->os_sync_lock);
15259 	if (did_start_op)
15260 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15261 		    recovonly ? TRUE : FALSE);
15262 	if (did_force_recovlock)
15263 		nfs_rw_exit(&mi->mi_recovlock);
15264 	if (cred_otw)
15265 		crfree(cred_otw);
15266 	if (osp)
15267 		open_stream_rele(osp, rp);
15268 	if (oop) {
15269 		if (did_start_seqid_sync)
15270 			nfs4_end_open_seqid_sync(oop);
15271 		open_owner_rele(oop);
15272 	}
15273 }
15274 
15275 /*
15276  * Convert information returned by the server in the LOCK4denied
15277  * structure to the form required by fcntl.
15278  */
15279 static void
15280 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15281 {
15282 	nfs4_lo_name_t *lo;
15283 
15284 #ifdef	DEBUG
15285 	if (denied_to_flk_debug) {
15286 		lockt_denied_debug = lockt_denied;
15287 		debug_enter("lockt_denied");
15288 	}
15289 #endif
15290 
15291 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15292 	flk->l_whence = 0;	/* aka SEEK_SET */
15293 	flk->l_start = lockt_denied->offset;
15294 	flk->l_len = lockt_denied->length;
15295 
15296 	/*
15297 	 * If the blocking clientid matches our client id, then we can
15298 	 * interpret the lockowner (since we built it).  If not, then
15299 	 * fabricate a sysid and pid.  Note that the l_sysid field
15300 	 * in *flk already has the local sysid.
15301 	 */
15302 
15303 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15304 
15305 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15306 			lo = (nfs4_lo_name_t *)
15307 				lockt_denied->owner.owner_val;
15308 
15309 			flk->l_pid = lo->ln_pid;
15310 		} else {
15311 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15312 			"denied_to_flk: bad lock owner length\n"));
15313 
15314 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15315 		}
15316 	} else {
15317 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15318 		"denied_to_flk: foreign clientid\n"));
15319 
15320 		/*
15321 		 * Construct a new sysid which should be different from
15322 		 * sysids of other systems.
15323 		 */
15324 
15325 		flk->l_sysid++;
15326 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15327 	}
15328 }
15329 
15330 static pid_t
15331 lo_to_pid(lock_owner4 *lop)
15332 {
15333 	pid_t pid = 0;
15334 	uchar_t *cp;
15335 	int i;
15336 
15337 	cp = (uchar_t *)&lop->clientid;
15338 
15339 	for (i = 0; i < sizeof (lop->clientid); i++)
15340 		pid += (pid_t)*cp++;
15341 
15342 	cp = (uchar_t *)lop->owner_val;
15343 
15344 	for (i = 0; i < lop->owner_len; i++)
15345 		pid += (pid_t)*cp++;
15346 
15347 	return (pid);
15348 }
15349 
15350 /*
15351  * Given a lock pointer, returns the length of that lock.
15352  * "end" is the last locked offset the "l_len" covers from
15353  * the start of the lock.
15354  */
15355 static off64_t
15356 lock_to_end(flock64_t *lock)
15357 {
15358 	off64_t lock_end;
15359 
15360 	if (lock->l_len == 0)
15361 		lock_end = (off64_t)MAXEND;
15362 	else
15363 		lock_end = lock->l_start + lock->l_len - 1;
15364 
15365 	return (lock_end);
15366 }
15367 
15368 /*
15369  * Given the end of a lock, it will return you the length "l_len" for that lock.
15370  */
15371 static off64_t
15372 end_to_len(off64_t start, off64_t end)
15373 {
15374 	off64_t lock_len;
15375 
15376 	ASSERT(end >= start);
15377 	if (end == MAXEND)
15378 		lock_len = 0;
15379 	else
15380 		lock_len = end - start + 1;
15381 
15382 	return (lock_len);
15383 }
15384 
15385 /*
15386  * On given end for a lock it determines if it is the last locked offset
15387  * or not, if so keeps it as is, else adds one to return the length for
15388  * valid start.
15389  */
15390 static off64_t
15391 start_check(off64_t x)
15392 {
15393 	if (x == MAXEND)
15394 		return (x);
15395 	else
15396 		return (x + 1);
15397 }
15398 
15399 /*
15400  * See if these two locks overlap, and if so return 1;
15401  * otherwise, return 0.
15402  */
15403 static int
15404 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15405 {
15406 	off64_t llfp_end, curfp_end;
15407 
15408 	llfp_end = lock_to_end(llfp);
15409 	curfp_end = lock_to_end(curfp);
15410 
15411 	if (((llfp_end >= curfp->l_start) &&
15412 		(llfp->l_start <= curfp->l_start)) ||
15413 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15414 		return (1);
15415 	return (0);
15416 }
15417 
15418 /*
15419  * Determine what the interseting lock region is, and add that to the
15420  * 'nl_llpp' locklist in increasing order (by l_start).
15421  */
15422 static void
15423 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15424 	locklist_t **nl_llpp, vnode_t *vp)
15425 {
15426 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15427 	off64_t lost_flp_end, local_flp_end, len, start;
15428 
15429 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15430 
15431 	if (!locks_intersect(lost_flp, local_flp))
15432 		return;
15433 
15434 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15435 	    "locks intersect"));
15436 
15437 	lost_flp_end = lock_to_end(lost_flp);
15438 	local_flp_end = lock_to_end(local_flp);
15439 
15440 	/* Find the starting point of the intersecting region */
15441 	if (local_flp->l_start > lost_flp->l_start)
15442 		start = local_flp->l_start;
15443 	else
15444 		start = lost_flp->l_start;
15445 
15446 	/* Find the lenght of the intersecting region */
15447 	if (lost_flp_end < local_flp_end)
15448 		len = end_to_len(start, lost_flp_end);
15449 	else
15450 		len = end_to_len(start, local_flp_end);
15451 
15452 	/*
15453 	 * Prepare the flock structure for the intersection found and insert
15454 	 * it into the new list in increasing l_start order. This list contains
15455 	 * intersections of locks registered by the client with the local host
15456 	 * and the lost lock.
15457 	 * The lock type of this lock is the same as that of the local_flp.
15458 	 */
15459 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15460 	intersect_llp->ll_flock.l_start = start;
15461 	intersect_llp->ll_flock.l_len = len;
15462 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15463 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15464 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15465 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15466 	intersect_llp->ll_vp = vp;
15467 
15468 	tmp_fllp = *nl_llpp;
15469 	cur_fllp = NULL;
15470 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15471 		intersect_llp->ll_flock.l_start) {
15472 			cur_fllp = tmp_fllp;
15473 			tmp_fllp = tmp_fllp->ll_next;
15474 	}
15475 	if (cur_fllp == NULL) {
15476 		/* first on the list */
15477 		intersect_llp->ll_next = *nl_llpp;
15478 		*nl_llpp = intersect_llp;
15479 	} else {
15480 		intersect_llp->ll_next = cur_fllp->ll_next;
15481 		cur_fllp->ll_next = intersect_llp;
15482 	}
15483 
15484 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15485 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15486 	    intersect_llp->ll_flock.l_start,
15487 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15488 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15489 }
15490 
15491 /*
15492  * Our local locking current state is potentially different than
15493  * what the NFSv4 server thinks we have due to a lost lock that was
15494  * resent and then received.  We need to reset our "NFSv4" locking
15495  * state to match the current local locking state for this pid since
15496  * that is what the user/application sees as what the world is.
15497  *
15498  * We cannot afford to drop the open/lock seqid sync since then we can
15499  * get confused about what the current local locking state "is" versus
15500  * "was".
15501  *
15502  * If we are unable to fix up the locks, we send SIGLOST to the affected
15503  * process.  This is not done if the filesystem has been forcibly
15504  * unmounted, in case the process has already exited and a new process
15505  * exists with the same pid.
15506  */
15507 static void
15508 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15509 		nfs4_lock_owner_t *lop)
15510 {
15511 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15512 	mntinfo4_t *mi = VTOMI4(vp);
15513 	const int cmd = F_SETLK;
15514 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15515 	flock64_t ul_fl;
15516 
15517 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15518 		"nfs4_reinstitute_local_lock_state"));
15519 
15520 	/*
15521 	 * Find active locks for this vp from the local locking code.
15522 	 * Scan through this list and find out the locks that intersect with
15523 	 * the lost lock. Once we find the lock that intersects, add the
15524 	 * intersection area as a new lock to a new list "ri_llp". The lock
15525 	 * type of the intersection region lock added to ri_llp is the same
15526 	 * as that found in the active lock list, "list". The intersecting
15527 	 * region locks are added to ri_llp in increasing l_start order.
15528 	 */
15529 	ASSERT(curproc->p_zone == mi->mi_zone);
15530 
15531 	locks = flk_active_locks_for_vp(vp);
15532 	ri_llp = NULL;
15533 
15534 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15535 		ASSERT(llp->ll_vp == vp);
15536 		/*
15537 		 * Pick locks that belong to this pid/lockowner
15538 		 */
15539 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15540 			continue;
15541 
15542 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15543 	}
15544 
15545 	/*
15546 	 * Now we have the list of intersections with the lost lock. These are
15547 	 * the locks that were/are active before the server replied to the
15548 	 * last/lost lock. Issue these locks to the server here. Playing these
15549 	 * locks to the server will re-establish aur current local locking state
15550 	 * with the v4 server.
15551 	 * If we get an error, send SIGLOST to the application for that lock.
15552 	 */
15553 
15554 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15555 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15556 		    "nfs4_reinstitute_local_lock_state: need to issue "
15557 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15558 		    llp->ll_flock.l_start,
15559 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15560 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15561 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15562 		/*
15563 		 * No need to relock what we already have
15564 		 */
15565 		if (llp->ll_flock.l_type == lost_flp->l_type)
15566 			continue;
15567 
15568 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15569 	}
15570 
15571 	/*
15572 	 * Now keeping the start of the lost lock as our reference parse the
15573 	 * newly created ri_llp locklist to find the ranges that we have locked
15574 	 * with the v4 server but not in the current local locking. We need
15575 	 * to unlock these ranges.
15576 	 * These ranges can also be reffered to as those ranges, where the lost
15577 	 * lock does not overlap with the locks in the ri_llp but are locked
15578 	 * since the server replied to the lost lock.
15579 	 */
15580 	cur_start = lost_flp->l_start;
15581 	lost_flp_end = lock_to_end(lost_flp);
15582 
15583 	ul_fl.l_type = F_UNLCK;
15584 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15585 	ul_fl.l_sysid = lost_flp->l_sysid;
15586 	ul_fl.l_pid = lost_flp->l_pid;
15587 
15588 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15589 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15590 
15591 		if (llp->ll_flock.l_start <= cur_start) {
15592 			cur_start = start_check(llp_ll_flock_end);
15593 			continue;
15594 		}
15595 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15596 			"nfs4_reinstitute_local_lock_state: "
15597 			"UNLOCK [%"PRIx64" - %"PRIx64"]",
15598 			cur_start, llp->ll_flock.l_start));
15599 
15600 		ul_fl.l_start = cur_start;
15601 		ul_fl.l_len = end_to_len(cur_start,
15602 		    (llp->ll_flock.l_start - 1));
15603 
15604 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15605 		cur_start = start_check(llp_ll_flock_end);
15606 	}
15607 
15608 	/*
15609 	 * In the case where the lost lock ends after all intersecting locks,
15610 	 * unlock the last part of the lost lock range.
15611 	 */
15612 	if (cur_start != start_check(lost_flp_end)) {
15613 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15614 			"nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15615 			"lost lock region [%"PRIx64" - %"PRIx64"]",
15616 			cur_start, lost_flp->l_start + lost_flp->l_len));
15617 
15618 		ul_fl.l_start = cur_start;
15619 		/*
15620 		 * Is it an to-EOF lock? if so unlock till the end
15621 		 */
15622 		if (lost_flp->l_len == 0)
15623 			ul_fl.l_len = 0;
15624 		else
15625 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15626 
15627 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15628 	}
15629 
15630 	if (locks != NULL)
15631 		flk_free_locklist(locks);
15632 
15633 	/* Free up our newly created locklist */
15634 	for (llp = ri_llp; llp != NULL; ) {
15635 		tmp_llp = llp->ll_next;
15636 		kmem_free(llp, sizeof (locklist_t));
15637 		llp = tmp_llp;
15638 	}
15639 
15640 	/*
15641 	 * Now return back to the original calling nfs4frlock()
15642 	 * and let us naturally drop our seqid syncs.
15643 	 */
15644 }
15645 
15646 /*
15647  * Create a lost state record for the given lock reinstantiation request
15648  * and push it onto the lost state queue.
15649  */
15650 static void
15651 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
15652 	nfs4_lock_owner_t *lop)
15653 {
15654 	nfs4_lost_rqst_t req;
15655 	nfs_lock_type4 locktype;
15656 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
15657 
15658 	ASSERT(curproc->p_zone == VTOMI4(vp)->mi_zone);
15659 
15660 	locktype = flk_to_locktype(cmd, flk->l_type);
15661 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
15662 				NULL, NULL, lop, flk, &req, cr, vp);
15663 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
15664 		    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
15665 		    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
15666 		    NULL);
15667 }
15668