xref: /titanic_51/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision cee4d2b4c15c3051b6a16c97b77d71585cc663a2)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  *	Copyright 1983,1984,1985,1986,1987,1988,1989 AT&T.
28  *	All Rights Reserved
29  */
30 
31 #pragma ident	"%Z%%M%	%I%	%E% SMI"
32 
33 #include <sys/param.h>
34 #include <sys/types.h>
35 #include <sys/systm.h>
36 #include <sys/cred.h>
37 #include <sys/time.h>
38 #include <sys/vnode.h>
39 #include <sys/vfs.h>
40 #include <sys/vfs_opreg.h>
41 #include <sys/file.h>
42 #include <sys/filio.h>
43 #include <sys/uio.h>
44 #include <sys/buf.h>
45 #include <sys/mman.h>
46 #include <sys/pathname.h>
47 #include <sys/dirent.h>
48 #include <sys/debug.h>
49 #include <sys/vmsystm.h>
50 #include <sys/fcntl.h>
51 #include <sys/flock.h>
52 #include <sys/swap.h>
53 #include <sys/errno.h>
54 #include <sys/strsubr.h>
55 #include <sys/sysmacros.h>
56 #include <sys/kmem.h>
57 #include <sys/cmn_err.h>
58 #include <sys/pathconf.h>
59 #include <sys/utsname.h>
60 #include <sys/dnlc.h>
61 #include <sys/acl.h>
62 #include <sys/systeminfo.h>
63 #include <sys/policy.h>
64 #include <sys/sdt.h>
65 #include <sys/list.h>
66 #include <sys/stat.h>
67 
68 #include <rpc/types.h>
69 #include <rpc/auth.h>
70 #include <rpc/clnt.h>
71 
72 #include <nfs/nfs.h>
73 #include <nfs/nfs_clnt.h>
74 #include <nfs/nfs_acl.h>
75 #include <nfs/lm.h>
76 #include <nfs/nfs4.h>
77 #include <nfs/nfs4_kprot.h>
78 #include <nfs/rnode4.h>
79 #include <nfs/nfs4_clnt.h>
80 
81 #include <vm/hat.h>
82 #include <vm/as.h>
83 #include <vm/page.h>
84 #include <vm/pvn.h>
85 #include <vm/seg.h>
86 #include <vm/seg_map.h>
87 #include <vm/seg_kpm.h>
88 #include <vm/seg_vn.h>
89 
90 #include <fs/fs_subr.h>
91 
92 #include <sys/ddi.h>
93 #include <sys/int_fmtio.h>
94 
95 typedef struct {
96 	nfs4_ga_res_t	*di_garp;
97 	cred_t		*di_cred;
98 	hrtime_t	di_time_call;
99 } dirattr_info_t;
100 
101 typedef enum nfs4_acl_op {
102 	NFS4_ACL_GET,
103 	NFS4_ACL_SET
104 } nfs4_acl_op_t;
105 
106 static void	nfs4_update_dircaches(change_info4 *, vnode_t *, vnode_t *,
107 			char *, dirattr_info_t *);
108 
109 static void	nfs4close_otw(rnode4_t *, cred_t *, nfs4_open_owner_t *,
110 		    nfs4_open_stream_t *, int *, int *, nfs4_close_type_t,
111 		    nfs4_error_t *, int *);
112 static int	nfs4_rdwrlbn(vnode_t *, page_t *, u_offset_t, size_t, int,
113 			cred_t *);
114 static int	nfs4write(vnode_t *, caddr_t, u_offset_t, int, cred_t *,
115 			stable_how4 *);
116 static int	nfs4read(vnode_t *, caddr_t, offset_t, int, size_t *,
117 			cred_t *, bool_t, struct uio *);
118 static int	nfs4setattr(vnode_t *, struct vattr *, int, cred_t *,
119 			vsecattr_t *);
120 static int	nfs4openattr(vnode_t *, vnode_t **, int, cred_t *);
121 static int	nfs4lookup(vnode_t *, char *, vnode_t **, cred_t *, int);
122 static int	nfs4lookup_xattr(vnode_t *, char *, vnode_t **, int, cred_t *);
123 static int	nfs4lookupvalidate_otw(vnode_t *, char *, vnode_t **, cred_t *);
124 static int	nfs4lookupnew_otw(vnode_t *, char *, vnode_t **, cred_t *);
125 static int	nfs4mknod(vnode_t *, char *, struct vattr *, enum vcexcl,
126 			int, vnode_t **, cred_t *);
127 static int	nfs4open_otw(vnode_t *, char *, struct vattr *, vnode_t **,
128 			cred_t *, int, int, enum createmode4, int);
129 static int	nfs4rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
130 			caller_context_t *);
131 static int	nfs4rename_persistent_fh(vnode_t *, char *, vnode_t *,
132 			vnode_t *, char *, cred_t *, nfsstat4 *);
133 static int	nfs4rename_volatile_fh(vnode_t *, char *, vnode_t *,
134 			vnode_t *, char *, cred_t *, nfsstat4 *);
135 static int	do_nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
136 static void	nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
137 static int	nfs4_bio(struct buf *, stable_how4 *, cred_t *, bool_t);
138 static int	nfs4_getapage(vnode_t *, u_offset_t, size_t, uint_t *,
139 			page_t *[], size_t, struct seg *, caddr_t,
140 			enum seg_rw, cred_t *);
141 static void	nfs4_readahead(vnode_t *, u_offset_t, caddr_t, struct seg *,
142 			cred_t *);
143 static int	nfs4_sync_putapage(vnode_t *, page_t *, u_offset_t, size_t,
144 			int, cred_t *);
145 static int	nfs4_sync_pageio(vnode_t *, page_t *, u_offset_t, size_t,
146 			int, cred_t *);
147 static int	nfs4_commit(vnode_t *, offset4, count4, cred_t *);
148 static void	nfs4_set_mod(vnode_t *);
149 static void	nfs4_get_commit(vnode_t *);
150 static void	nfs4_get_commit_range(vnode_t *, u_offset_t, size_t);
151 static int	nfs4_putpage_commit(vnode_t *, offset_t, size_t, cred_t *);
152 static int	nfs4_commit_vp(vnode_t *, u_offset_t, size_t, cred_t *, int);
153 static int	nfs4_sync_commit(vnode_t *, page_t *, offset3, count3,
154 			cred_t *);
155 static void	do_nfs4_async_commit(vnode_t *, page_t *, offset3, count3,
156 			cred_t *);
157 static int	nfs4_update_attrcache(nfsstat4, nfs4_ga_res_t *,
158 			hrtime_t, vnode_t *, cred_t *);
159 static int	nfs4_open_non_reg_file(vnode_t **, int, cred_t *);
160 static int	nfs4_safelock(vnode_t *, const struct flock64 *, cred_t *);
161 static void	nfs4_register_lock_locally(vnode_t *, struct flock64 *, int,
162 			u_offset_t);
163 static int 	nfs4_lockrelease(vnode_t *, int, offset_t, cred_t *);
164 static int	nfs4_block_and_wait(clock_t *, rnode4_t *);
165 static cred_t  *state_to_cred(nfs4_open_stream_t *);
166 static int	vtoname(vnode_t *, char *, ssize_t);
167 static void	denied_to_flk(LOCK4denied *, flock64_t *, LOCKT4args *);
168 static pid_t	lo_to_pid(lock_owner4 *);
169 static void	nfs4_reinstitute_local_lock_state(vnode_t *, flock64_t *,
170 			cred_t *, nfs4_lock_owner_t *);
171 static void	push_reinstate(vnode_t *, int, flock64_t *, cred_t *,
172 			nfs4_lock_owner_t *);
173 static int 	open_and_get_osp(vnode_t *, cred_t *, nfs4_open_stream_t **);
174 static void	nfs4_delmap_callback(struct as *, void *, uint_t);
175 static void	nfs4_free_delmapcall(nfs4_delmapcall_t *);
176 static nfs4_delmapcall_t	*nfs4_init_delmapcall();
177 static int	nfs4_find_and_delete_delmapcall(rnode4_t *, int *);
178 static int	nfs4_is_acl_mask_valid(uint_t, nfs4_acl_op_t);
179 static int	nfs4_create_getsecattr_return(vsecattr_t *, vsecattr_t *,
180 			uid_t, gid_t, int);
181 
182 /*
183  * Routines that implement the setting of v4 args for the misc. ops
184  */
185 static void	nfs4args_lock_free(nfs_argop4 *);
186 static void	nfs4args_lockt_free(nfs_argop4 *);
187 static void	nfs4args_setattr(nfs_argop4 *, vattr_t *, vsecattr_t *,
188 			int, rnode4_t *, cred_t *, bitmap4, int *,
189 			nfs4_stateid_types_t *);
190 static void	nfs4args_setattr_free(nfs_argop4 *);
191 static int	nfs4args_verify(nfs_argop4 *, vattr_t *, enum nfs_opnum4,
192 			bitmap4);
193 static void	nfs4args_verify_free(nfs_argop4 *);
194 static void	nfs4args_write(nfs_argop4 *, stable_how4, rnode4_t *, cred_t *,
195 			WRITE4args **, nfs4_stateid_types_t *);
196 
197 /*
198  * These are the vnode ops functions that implement the vnode interface to
199  * the networked file system.  See more comments below at nfs4_vnodeops.
200  */
201 static int	nfs4_open(vnode_t **, int, cred_t *, caller_context_t *);
202 static int	nfs4_close(vnode_t *, int, int, offset_t, cred_t *,
203 			caller_context_t *);
204 static int	nfs4_read(vnode_t *, struct uio *, int, cred_t *,
205 			caller_context_t *);
206 static int	nfs4_write(vnode_t *, struct uio *, int, cred_t *,
207 			caller_context_t *);
208 static int	nfs4_ioctl(vnode_t *, int, intptr_t, int, cred_t *, int *,
209 			caller_context_t *);
210 static int	nfs4_setattr(vnode_t *, struct vattr *, int, cred_t *,
211 			caller_context_t *);
212 static int	nfs4_access(vnode_t *, int, int, cred_t *, caller_context_t *);
213 static int	nfs4_readlink(vnode_t *, struct uio *, cred_t *,
214 			caller_context_t *);
215 static int	nfs4_fsync(vnode_t *, int, cred_t *, caller_context_t *);
216 static int	nfs4_create(vnode_t *, char *, struct vattr *, enum vcexcl,
217 			int, vnode_t **, cred_t *, int, caller_context_t *,
218 			vsecattr_t *);
219 static int	nfs4_remove(vnode_t *, char *, cred_t *, caller_context_t *,
220 			int);
221 static int	nfs4_link(vnode_t *, vnode_t *, char *, cred_t *,
222 			caller_context_t *, int);
223 static int	nfs4_rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
224 			caller_context_t *, int);
225 static int	nfs4_mkdir(vnode_t *, char *, struct vattr *, vnode_t **,
226 			cred_t *, caller_context_t *, int, vsecattr_t *);
227 static int	nfs4_rmdir(vnode_t *, char *, vnode_t *, cred_t *,
228 			caller_context_t *, int);
229 static int	nfs4_symlink(vnode_t *, char *, struct vattr *, char *,
230 			cred_t *, caller_context_t *, int);
231 static int	nfs4_readdir(vnode_t *, struct uio *, cred_t *, int *,
232 			caller_context_t *, int);
233 static int	nfs4_seek(vnode_t *, offset_t, offset_t *, caller_context_t *);
234 static int	nfs4_getpage(vnode_t *, offset_t, size_t, uint_t *,
235 			page_t *[], size_t, struct seg *, caddr_t,
236 			enum seg_rw, cred_t *, caller_context_t *);
237 static int	nfs4_putpage(vnode_t *, offset_t, size_t, int, cred_t *,
238 			caller_context_t *);
239 static int	nfs4_map(vnode_t *, offset_t, struct as *, caddr_t *, size_t,
240 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
241 static int	nfs4_addmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
242 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
243 static int	nfs4_cmp(vnode_t *, vnode_t *, caller_context_t *);
244 static int	nfs4_frlock(vnode_t *, int, struct flock64 *, int, offset_t,
245 			struct flk_callback *, cred_t *, caller_context_t *);
246 static int	nfs4_space(vnode_t *, int, struct flock64 *, int, offset_t,
247 			cred_t *, caller_context_t *);
248 static int	nfs4_delmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
249 			uint_t, uint_t, uint_t, cred_t *, caller_context_t *);
250 static int	nfs4_pageio(vnode_t *, page_t *, u_offset_t, size_t, int,
251 			cred_t *, caller_context_t *);
252 static void	nfs4_dispose(vnode_t *, page_t *, int, int, cred_t *,
253 			caller_context_t *);
254 static int	nfs4_setsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
255 			caller_context_t *);
256 /*
257  * These vnode ops are required to be called from outside this source file,
258  * e.g. by ephemeral mount stub vnode ops, and so may not be declared
259  * as static.
260  */
261 int	nfs4_getattr(vnode_t *, struct vattr *, int, cred_t *,
262 	    caller_context_t *);
263 void	nfs4_inactive(vnode_t *, cred_t *, caller_context_t *);
264 int	nfs4_lookup(vnode_t *, char *, vnode_t **,
265 	    struct pathname *, int, vnode_t *, cred_t *,
266 	    caller_context_t *, int *, pathname_t *);
267 int	nfs4_fid(vnode_t *, fid_t *, caller_context_t *);
268 int	nfs4_rwlock(vnode_t *, int, caller_context_t *);
269 void	nfs4_rwunlock(vnode_t *, int, caller_context_t *);
270 int	nfs4_realvp(vnode_t *, vnode_t **, caller_context_t *);
271 int	nfs4_pathconf(vnode_t *, int, ulong_t *, cred_t *,
272 	    caller_context_t *);
273 int	nfs4_getsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
274 	    caller_context_t *);
275 int	nfs4_shrlock(vnode_t *, int, struct shrlock *, int, cred_t *,
276 	    caller_context_t *);
277 
278 /*
279  * Used for nfs4_commit_vp() to indicate if we should
280  * wait on pending writes.
281  */
282 #define	NFS4_WRITE_NOWAIT	0
283 #define	NFS4_WRITE_WAIT		1
284 
285 #define	NFS4_BASE_WAIT_TIME 1	/* 1 second */
286 
287 /*
288  * Error flags used to pass information about certain special errors
289  * which need to be handled specially.
290  */
291 #define	NFS_EOF			-98
292 #define	NFS_VERF_MISMATCH	-97
293 
294 /*
295  * Flags used to differentiate between which operation drove the
296  * potential CLOSE OTW. (see nfs4_close_otw_if_necessary)
297  */
298 #define	NFS4_CLOSE_OP		0x1
299 #define	NFS4_DELMAP_OP		0x2
300 #define	NFS4_INACTIVE_OP	0x3
301 
302 #define	ISVDEV(t) ((t == VBLK) || (t == VCHR) || (t == VFIFO))
303 
304 /* ALIGN64 aligns the given buffer and adjust buffer size to 64 bit */
305 #define	ALIGN64(x, ptr, sz)						\
306 	x = ((uintptr_t)(ptr)) & (sizeof (uint64_t) - 1);		\
307 	if (x) {							\
308 		x = sizeof (uint64_t) - (x);				\
309 		sz -= (x);						\
310 		ptr += (x);						\
311 	}
312 
313 #ifdef DEBUG
314 int nfs4_client_attr_debug = 0;
315 int nfs4_client_state_debug = 0;
316 int nfs4_client_shadow_debug = 0;
317 int nfs4_client_lock_debug = 0;
318 int nfs4_seqid_sync = 0;
319 int nfs4_client_map_debug = 0;
320 static int nfs4_pageio_debug = 0;
321 int nfs4_client_inactive_debug = 0;
322 int nfs4_client_recov_debug = 0;
323 int nfs4_client_failover_debug = 0;
324 int nfs4_client_call_debug = 0;
325 int nfs4_client_lookup_debug = 0;
326 int nfs4_client_zone_debug = 0;
327 int nfs4_lost_rqst_debug = 0;
328 int nfs4_rdattrerr_debug = 0;
329 int nfs4_open_stream_debug = 0;
330 
331 int nfs4read_error_inject;
332 
333 static int nfs4_create_misses = 0;
334 
335 static int nfs4_readdir_cache_shorts = 0;
336 static int nfs4_readdir_readahead = 0;
337 
338 static int nfs4_bio_do_stop = 0;
339 
340 static int nfs4_lostpage = 0;	/* number of times we lost original page */
341 
342 int nfs4_mmap_debug = 0;
343 
344 static int nfs4_pathconf_cache_hits = 0;
345 static int nfs4_pathconf_cache_misses = 0;
346 
347 int nfs4close_all_cnt;
348 int nfs4close_one_debug = 0;
349 int nfs4close_notw_debug = 0;
350 
351 int denied_to_flk_debug = 0;
352 void *lockt_denied_debug;
353 
354 #endif
355 
356 /*
357  * How long to wait before trying again if OPEN_CONFIRM gets ETIMEDOUT
358  * or NFS4ERR_RESOURCE.
359  */
360 static int confirm_retry_sec = 30;
361 
362 static int nfs4_lookup_neg_cache = 1;
363 
364 /*
365  * number of pages to read ahead
366  * optimized for 100 base-T.
367  */
368 static int nfs4_nra = 4;
369 
370 static int nfs4_do_symlink_cache = 1;
371 
372 static int nfs4_pathconf_disable_cache = 0;
373 
374 /*
375  * These are the vnode ops routines which implement the vnode interface to
376  * the networked file system.  These routines just take their parameters,
377  * make them look networkish by putting the right info into interface structs,
378  * and then calling the appropriate remote routine(s) to do the work.
379  *
380  * Note on directory name lookup cacheing:  If we detect a stale fhandle,
381  * we purge the directory cache relative to that vnode.  This way, the
382  * user won't get burned by the cache repeatedly.  See <nfs/rnode4.h> for
383  * more details on rnode locking.
384  */
385 
386 struct vnodeops *nfs4_vnodeops;
387 
388 const fs_operation_def_t nfs4_vnodeops_template[] = {
389 	VOPNAME_OPEN,		{ .vop_open = nfs4_open },
390 	VOPNAME_CLOSE,		{ .vop_close = nfs4_close },
391 	VOPNAME_READ,		{ .vop_read = nfs4_read },
392 	VOPNAME_WRITE,		{ .vop_write = nfs4_write },
393 	VOPNAME_IOCTL,		{ .vop_ioctl = nfs4_ioctl },
394 	VOPNAME_GETATTR,	{ .vop_getattr = nfs4_getattr },
395 	VOPNAME_SETATTR,	{ .vop_setattr = nfs4_setattr },
396 	VOPNAME_ACCESS,		{ .vop_access = nfs4_access },
397 	VOPNAME_LOOKUP,		{ .vop_lookup = nfs4_lookup },
398 	VOPNAME_CREATE,		{ .vop_create = nfs4_create },
399 	VOPNAME_REMOVE,		{ .vop_remove = nfs4_remove },
400 	VOPNAME_LINK,		{ .vop_link = nfs4_link },
401 	VOPNAME_RENAME,		{ .vop_rename = nfs4_rename },
402 	VOPNAME_MKDIR,		{ .vop_mkdir = nfs4_mkdir },
403 	VOPNAME_RMDIR,		{ .vop_rmdir = nfs4_rmdir },
404 	VOPNAME_READDIR,	{ .vop_readdir = nfs4_readdir },
405 	VOPNAME_SYMLINK,	{ .vop_symlink = nfs4_symlink },
406 	VOPNAME_READLINK,	{ .vop_readlink = nfs4_readlink },
407 	VOPNAME_FSYNC,		{ .vop_fsync = nfs4_fsync },
408 	VOPNAME_INACTIVE,	{ .vop_inactive = nfs4_inactive },
409 	VOPNAME_FID,		{ .vop_fid = nfs4_fid },
410 	VOPNAME_RWLOCK,		{ .vop_rwlock = nfs4_rwlock },
411 	VOPNAME_RWUNLOCK,	{ .vop_rwunlock = nfs4_rwunlock },
412 	VOPNAME_SEEK,		{ .vop_seek = nfs4_seek },
413 	VOPNAME_FRLOCK,		{ .vop_frlock = nfs4_frlock },
414 	VOPNAME_SPACE,		{ .vop_space = nfs4_space },
415 	VOPNAME_REALVP,		{ .vop_realvp = nfs4_realvp },
416 	VOPNAME_GETPAGE,	{ .vop_getpage = nfs4_getpage },
417 	VOPNAME_PUTPAGE,	{ .vop_putpage = nfs4_putpage },
418 	VOPNAME_MAP,		{ .vop_map = nfs4_map },
419 	VOPNAME_ADDMAP,		{ .vop_addmap = nfs4_addmap },
420 	VOPNAME_DELMAP,		{ .vop_delmap = nfs4_delmap },
421 	/* no separate nfs4_dump */
422 	VOPNAME_DUMP,		{ .vop_dump = nfs_dump },
423 	VOPNAME_PATHCONF,	{ .vop_pathconf = nfs4_pathconf },
424 	VOPNAME_PAGEIO,		{ .vop_pageio = nfs4_pageio },
425 	VOPNAME_DISPOSE,	{ .vop_dispose = nfs4_dispose },
426 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = nfs4_setsecattr },
427 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = nfs4_getsecattr },
428 	VOPNAME_SHRLOCK,	{ .vop_shrlock = nfs4_shrlock },
429 	VOPNAME_VNEVENT, 	{ .vop_vnevent = fs_vnevent_support },
430 	NULL,			NULL
431 };
432 
433 /*
434  * The following are subroutines and definitions to set args or get res
435  * for the different nfsv4 ops
436  */
437 
438 void
439 nfs4args_lookup_free(nfs_argop4 *argop, int arglen)
440 {
441 	int		i;
442 
443 	for (i = 0; i < arglen; i++) {
444 		if (argop[i].argop == OP_LOOKUP) {
445 			kmem_free(
446 			    argop[i].nfs_argop4_u.oplookup.
447 			    objname.utf8string_val,
448 			    argop[i].nfs_argop4_u.oplookup.
449 			    objname.utf8string_len);
450 		}
451 	}
452 }
453 
454 static void
455 nfs4args_lock_free(nfs_argop4 *argop)
456 {
457 	locker4 *locker = &argop->nfs_argop4_u.oplock.locker;
458 
459 	if (locker->new_lock_owner == TRUE) {
460 		open_to_lock_owner4 *open_owner;
461 
462 		open_owner = &locker->locker4_u.open_owner;
463 		if (open_owner->lock_owner.owner_val != NULL) {
464 			kmem_free(open_owner->lock_owner.owner_val,
465 			    open_owner->lock_owner.owner_len);
466 		}
467 	}
468 }
469 
470 static void
471 nfs4args_lockt_free(nfs_argop4 *argop)
472 {
473 	lock_owner4 *lowner = &argop->nfs_argop4_u.oplockt.owner;
474 
475 	if (lowner->owner_val != NULL) {
476 		kmem_free(lowner->owner_val, lowner->owner_len);
477 	}
478 }
479 
480 static void
481 nfs4args_setattr(nfs_argop4 *argop, vattr_t *vap, vsecattr_t *vsap, int flags,
482     rnode4_t *rp, cred_t *cr, bitmap4 supp, int *error,
483     nfs4_stateid_types_t *sid_types)
484 {
485 	fattr4		*attr = &argop->nfs_argop4_u.opsetattr.obj_attributes;
486 	mntinfo4_t	*mi;
487 
488 	argop->argop = OP_SETATTR;
489 	/*
490 	 * The stateid is set to 0 if client is not modifying the size
491 	 * and otherwise to whatever nfs4_get_stateid() returns.
492 	 *
493 	 * XXX Note: nfs4_get_stateid() returns 0 if no lockowner and/or no
494 	 * state struct could be found for the process/file pair.  We may
495 	 * want to change this in the future (by OPENing the file).  See
496 	 * bug # 4474852.
497 	 */
498 	if (vap->va_mask & AT_SIZE) {
499 
500 		ASSERT(rp != NULL);
501 		mi = VTOMI4(RTOV4(rp));
502 
503 		argop->nfs_argop4_u.opsetattr.stateid =
504 		    nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
505 		    OP_SETATTR, sid_types, FALSE);
506 	} else {
507 		bzero(&argop->nfs_argop4_u.opsetattr.stateid,
508 		    sizeof (stateid4));
509 	}
510 
511 	*error = vattr_to_fattr4(vap, vsap, attr, flags, OP_SETATTR, supp);
512 	if (*error)
513 		bzero(attr, sizeof (*attr));
514 }
515 
516 static void
517 nfs4args_setattr_free(nfs_argop4 *argop)
518 {
519 	nfs4_fattr4_free(&argop->nfs_argop4_u.opsetattr.obj_attributes);
520 }
521 
522 static int
523 nfs4args_verify(nfs_argop4 *argop, vattr_t *vap, enum nfs_opnum4 op,
524     bitmap4 supp)
525 {
526 	fattr4 *attr;
527 	int error = 0;
528 
529 	argop->argop = op;
530 	switch (op) {
531 	case OP_VERIFY:
532 		attr = &argop->nfs_argop4_u.opverify.obj_attributes;
533 		break;
534 	case OP_NVERIFY:
535 		attr = &argop->nfs_argop4_u.opnverify.obj_attributes;
536 		break;
537 	default:
538 		return (EINVAL);
539 	}
540 	if (!error)
541 		error = vattr_to_fattr4(vap, NULL, attr, 0, op, supp);
542 	if (error)
543 		bzero(attr, sizeof (*attr));
544 	return (error);
545 }
546 
547 static void
548 nfs4args_verify_free(nfs_argop4 *argop)
549 {
550 	switch (argop->argop) {
551 	case OP_VERIFY:
552 		nfs4_fattr4_free(&argop->nfs_argop4_u.opverify.obj_attributes);
553 		break;
554 	case OP_NVERIFY:
555 		nfs4_fattr4_free(&argop->nfs_argop4_u.opnverify.obj_attributes);
556 		break;
557 	default:
558 		break;
559 	}
560 }
561 
562 static void
563 nfs4args_write(nfs_argop4 *argop, stable_how4 stable, rnode4_t *rp, cred_t *cr,
564     WRITE4args **wargs_pp, nfs4_stateid_types_t *sid_tp)
565 {
566 	WRITE4args *wargs = &argop->nfs_argop4_u.opwrite;
567 	mntinfo4_t *mi = VTOMI4(RTOV4(rp));
568 
569 	argop->argop = OP_WRITE;
570 	wargs->stable = stable;
571 	wargs->stateid = nfs4_get_w_stateid(cr, rp, curproc->p_pidp->pid_id,
572 	    mi, OP_WRITE, sid_tp);
573 	wargs->mblk = NULL;
574 	*wargs_pp = wargs;
575 }
576 
577 void
578 nfs4args_copen_free(OPEN4cargs *open_args)
579 {
580 	if (open_args->owner.owner_val) {
581 		kmem_free(open_args->owner.owner_val,
582 		    open_args->owner.owner_len);
583 	}
584 	if ((open_args->opentype == OPEN4_CREATE) &&
585 	    (open_args->mode != EXCLUSIVE4)) {
586 		nfs4_fattr4_free(&open_args->createhow4_u.createattrs);
587 	}
588 }
589 
590 /*
591  * XXX:  This is referenced in modstubs.s
592  */
593 struct vnodeops *
594 nfs4_getvnodeops(void)
595 {
596 	return (nfs4_vnodeops);
597 }
598 
599 /*
600  * The OPEN operation opens a regular file.
601  */
602 /*ARGSUSED3*/
603 static int
604 nfs4_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
605 {
606 	vnode_t *dvp = NULL;
607 	rnode4_t *rp, *drp;
608 	int error;
609 	int just_been_created;
610 	char fn[MAXNAMELEN];
611 
612 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4_open: "));
613 	if (nfs_zone() != VTOMI4(*vpp)->mi_zone)
614 		return (EIO);
615 	rp = VTOR4(*vpp);
616 
617 	/*
618 	 * Check to see if opening something besides a regular file;
619 	 * if so skip the OTW call
620 	 */
621 	if ((*vpp)->v_type != VREG) {
622 		error = nfs4_open_non_reg_file(vpp, flag, cr);
623 		return (error);
624 	}
625 
626 	/*
627 	 * XXX - would like a check right here to know if the file is
628 	 * executable or not, so as to skip OTW
629 	 */
630 
631 	if ((error = vtodv(*vpp, &dvp, cr, TRUE)) != 0)
632 		return (error);
633 
634 	drp = VTOR4(dvp);
635 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
636 		return (EINTR);
637 
638 	if ((error = vtoname(*vpp, fn, MAXNAMELEN)) != 0) {
639 		nfs_rw_exit(&drp->r_rwlock);
640 		return (error);
641 	}
642 
643 	/*
644 	 * See if this file has just been CREATEd.
645 	 * If so, clear the flag and update the dnlc, which was previously
646 	 * skipped in nfs4_create.
647 	 * XXX need better serilization on this.
648 	 * XXX move this into the nf4open_otw call, after we have
649 	 * XXX acquired the open owner seqid sync.
650 	 */
651 	mutex_enter(&rp->r_statev4_lock);
652 	if (rp->created_v4) {
653 		rp->created_v4 = 0;
654 		mutex_exit(&rp->r_statev4_lock);
655 
656 		dnlc_update(dvp, fn, *vpp);
657 		/* This is needed so we don't bump the open ref count */
658 		just_been_created = 1;
659 	} else {
660 		mutex_exit(&rp->r_statev4_lock);
661 		just_been_created = 0;
662 	}
663 
664 	/*
665 	 * If caller specified O_TRUNC/FTRUNC, then be sure to set
666 	 * FWRITE (to drive successful setattr(size=0) after open)
667 	 */
668 	if (flag & FTRUNC)
669 		flag |= FWRITE;
670 
671 	error = nfs4open_otw(dvp, fn, NULL, vpp, cr, 0, flag, 0,
672 	    just_been_created);
673 
674 	if (!error && !((*vpp)->v_flag & VROOT))
675 		dnlc_update(dvp, fn, *vpp);
676 
677 	nfs_rw_exit(&drp->r_rwlock);
678 
679 	/* release the hold from vtodv */
680 	VN_RELE(dvp);
681 
682 	/* exchange the shadow for the master vnode, if needed */
683 
684 	if (error == 0 && IS_SHADOW(*vpp, rp))
685 		sv_exchange(vpp);
686 
687 	return (error);
688 }
689 
690 /*
691  * See if there's a "lost open" request to be saved and recovered.
692  */
693 static void
694 nfs4open_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
695     nfs4_open_owner_t *oop, cred_t *cr, vnode_t *vp,
696     vnode_t *dvp, OPEN4cargs *open_args)
697 {
698 	vfs_t *vfsp;
699 	char *srccfp;
700 
701 	vfsp = (dvp ? dvp->v_vfsp : vp->v_vfsp);
702 
703 	if (error != ETIMEDOUT && error != EINTR &&
704 	    !NFS4_FRC_UNMT_ERR(error, vfsp)) {
705 		lost_rqstp->lr_op = 0;
706 		return;
707 	}
708 
709 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
710 	    "nfs4open_save_lost_rqst: error %d", error));
711 
712 	lost_rqstp->lr_op = OP_OPEN;
713 
714 	/*
715 	 * The vp (if it is not NULL) and dvp are held and rele'd via
716 	 * the recovery code.  See nfs4_save_lost_rqst.
717 	 */
718 	lost_rqstp->lr_vp = vp;
719 	lost_rqstp->lr_dvp = dvp;
720 	lost_rqstp->lr_oop = oop;
721 	lost_rqstp->lr_osp = NULL;
722 	lost_rqstp->lr_lop = NULL;
723 	lost_rqstp->lr_cr = cr;
724 	lost_rqstp->lr_flk = NULL;
725 	lost_rqstp->lr_oacc = open_args->share_access;
726 	lost_rqstp->lr_odeny = open_args->share_deny;
727 	lost_rqstp->lr_oclaim = open_args->claim;
728 	if (open_args->claim == CLAIM_DELEGATE_CUR) {
729 		lost_rqstp->lr_ostateid =
730 		    open_args->open_claim4_u.delegate_cur_info.delegate_stateid;
731 		srccfp = open_args->open_claim4_u.delegate_cur_info.cfile;
732 	} else {
733 		srccfp = open_args->open_claim4_u.cfile;
734 	}
735 	lost_rqstp->lr_ofile.utf8string_len = 0;
736 	lost_rqstp->lr_ofile.utf8string_val = NULL;
737 	(void) str_to_utf8(srccfp, &lost_rqstp->lr_ofile);
738 	lost_rqstp->lr_putfirst = FALSE;
739 }
740 
741 struct nfs4_excl_time {
742 	uint32 seconds;
743 	uint32 nseconds;
744 };
745 
746 /*
747  * The OPEN operation creates and/or opens a regular file
748  *
749  * ARGSUSED
750  */
751 static int
752 nfs4open_otw(vnode_t *dvp, char *file_name, struct vattr *in_va,
753     vnode_t **vpp, cred_t *cr, int create_flag, int open_flag,
754     enum createmode4 createmode, int file_just_been_created)
755 {
756 	rnode4_t *rp;
757 	rnode4_t *drp = VTOR4(dvp);
758 	vnode_t *vp = NULL;
759 	vnode_t *vpi = *vpp;
760 	bool_t needrecov = FALSE;
761 
762 	int doqueue = 1;
763 
764 	COMPOUND4args_clnt args;
765 	COMPOUND4res_clnt res;
766 	nfs_argop4 *argop;
767 	nfs_resop4 *resop;
768 	int argoplist_size;
769 	int idx_open, idx_fattr;
770 
771 	GETFH4res *gf_res = NULL;
772 	OPEN4res *op_res = NULL;
773 	nfs4_ga_res_t *garp;
774 	fattr4 *attr = NULL;
775 	struct nfs4_excl_time verf;
776 	bool_t did_excl_setup = FALSE;
777 	int created_osp;
778 
779 	OPEN4cargs *open_args;
780 	nfs4_open_owner_t	*oop = NULL;
781 	nfs4_open_stream_t	*osp = NULL;
782 	seqid4 seqid = 0;
783 	bool_t retry_open = FALSE;
784 	nfs4_recov_state_t recov_state;
785 	nfs4_lost_rqst_t lost_rqst;
786 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
787 	hrtime_t t;
788 	int acc = 0;
789 	cred_t *cred_otw = NULL;	/* cred used to do the RPC call */
790 	cred_t *ncr = NULL;
791 
792 	nfs4_sharedfh_t *otw_sfh;
793 	nfs4_sharedfh_t *orig_sfh;
794 	int fh_differs = 0;
795 	int numops, setgid_flag;
796 	int num_bseqid_retry = NFS4_NUM_RETRY_BAD_SEQID + 1;
797 
798 	/*
799 	 * Make sure we properly deal with setting the right gid on
800 	 * a newly created file to reflect the parent's setgid bit
801 	 */
802 	setgid_flag = 0;
803 	if (create_flag && in_va) {
804 
805 		/*
806 		 * If the parent's directory has the setgid bit set
807 		 * _and_ the client was able to get a valid mapping
808 		 * for the parent dir's owner_group, we want to
809 		 * append NVERIFY(owner_group == dva.va_gid) and
810 		 * SETATTR to the CREATE compound.
811 		 */
812 		mutex_enter(&drp->r_statelock);
813 		if (drp->r_attr.va_mode & VSGID &&
814 		    drp->r_attr.va_gid != GID_NOBODY) {
815 			in_va->va_gid = drp->r_attr.va_gid;
816 			setgid_flag = 1;
817 		}
818 		mutex_exit(&drp->r_statelock);
819 	}
820 
821 	/*
822 	 * Normal/non-create compound:
823 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new)
824 	 *
825 	 * Open(create) compound no setgid:
826 	 * PUTFH(dfh) + SAVEFH + OPEN(create) + GETFH + GETATTR(new) +
827 	 * RESTOREFH + GETATTR
828 	 *
829 	 * Open(create) setgid:
830 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new) +
831 	 * SAVEFH + PUTFH(dfh) + GETATTR(dvp) + RESTOREFH +
832 	 * NVERIFY(grp) + SETATTR
833 	 */
834 	if (setgid_flag) {
835 		numops = 10;
836 		idx_open = 1;
837 		idx_fattr = 3;
838 	} else if (create_flag) {
839 		numops = 7;
840 		idx_open = 2;
841 		idx_fattr = 4;
842 	} else {
843 		numops = 4;
844 		idx_open = 1;
845 		idx_fattr = 3;
846 	}
847 
848 	args.array_len = numops;
849 	argoplist_size = numops * sizeof (nfs_argop4);
850 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
851 
852 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw: "
853 	    "open %s open flag 0x%x cred %p", file_name, open_flag,
854 	    (void *)cr));
855 
856 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
857 	if (create_flag) {
858 		/*
859 		 * We are to create a file.  Initialize the passed in vnode
860 		 * pointer.
861 		 */
862 		vpi = NULL;
863 	} else {
864 		/*
865 		 * Check to see if the client owns a read delegation and is
866 		 * trying to open for write.  If so, then return the delegation
867 		 * to avoid the server doing a cb_recall and returning DELAY.
868 		 * NB - we don't use the statev4_lock here because we'd have
869 		 * to drop the lock anyway and the result would be stale.
870 		 */
871 		if ((open_flag & FWRITE) &&
872 		    VTOR4(vpi)->r_deleg_type == OPEN_DELEGATE_READ)
873 			(void) nfs4delegreturn(VTOR4(vpi), NFS4_DR_REOPEN);
874 
875 		/*
876 		 * If the file has a delegation, then do an access check up
877 		 * front.  This avoids having to an access check later after
878 		 * we've already done start_op, which could deadlock.
879 		 */
880 		if (VTOR4(vpi)->r_deleg_type != OPEN_DELEGATE_NONE) {
881 			if (open_flag & FREAD &&
882 			    nfs4_access(vpi, VREAD, 0, cr, NULL) == 0)
883 				acc |= VREAD;
884 			if (open_flag & FWRITE &&
885 			    nfs4_access(vpi, VWRITE, 0, cr, NULL) == 0)
886 				acc |= VWRITE;
887 		}
888 	}
889 
890 	drp = VTOR4(dvp);
891 
892 	recov_state.rs_flags = 0;
893 	recov_state.rs_num_retry_despite_err = 0;
894 	cred_otw = cr;
895 
896 recov_retry:
897 	fh_differs = 0;
898 	nfs4_error_zinit(&e);
899 
900 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, vpi, &recov_state);
901 	if (e.error) {
902 		if (ncr != NULL)
903 			crfree(ncr);
904 		kmem_free(argop, argoplist_size);
905 		return (e.error);
906 	}
907 
908 	args.ctag = TAG_OPEN;
909 	args.array_len = numops;
910 	args.array = argop;
911 
912 	/* putfh directory fh */
913 	argop[0].argop = OP_CPUTFH;
914 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
915 
916 	/* OPEN: either op 1 or op 2 depending upon create/setgid flags */
917 	argop[idx_open].argop = OP_COPEN;
918 	open_args = &argop[idx_open].nfs_argop4_u.opcopen;
919 	open_args->claim = CLAIM_NULL;
920 
921 	/* name of file */
922 	open_args->open_claim4_u.cfile = file_name;
923 	open_args->owner.owner_len = 0;
924 	open_args->owner.owner_val = NULL;
925 
926 	if (create_flag) {
927 		/* CREATE a file */
928 		open_args->opentype = OPEN4_CREATE;
929 		open_args->mode = createmode;
930 		if (createmode == EXCLUSIVE4) {
931 			if (did_excl_setup == FALSE) {
932 				verf.seconds = nfs_atoi(hw_serial);
933 				if (verf.seconds != 0)
934 					verf.nseconds = newnum();
935 				else {
936 					timestruc_t now;
937 
938 					gethrestime(&now);
939 					verf.seconds = now.tv_sec;
940 					verf.nseconds = now.tv_nsec;
941 				}
942 				/*
943 				 * Since the server will use this value for the
944 				 * mtime, make sure that it can't overflow. Zero
945 				 * out the MSB. The actual value does not matter
946 				 * here, only its uniqeness.
947 				 */
948 				verf.seconds &= INT32_MAX;
949 				did_excl_setup = TRUE;
950 			}
951 
952 			/* Now copy over verifier to OPEN4args. */
953 			open_args->createhow4_u.createverf = *(uint64_t *)&verf;
954 		} else {
955 			int v_error;
956 			bitmap4 supp_attrs;
957 			servinfo4_t *svp;
958 
959 			attr = &open_args->createhow4_u.createattrs;
960 
961 			svp = drp->r_server;
962 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
963 			supp_attrs = svp->sv_supp_attrs;
964 			nfs_rw_exit(&svp->sv_lock);
965 
966 			/* GUARDED4 or UNCHECKED4 */
967 			v_error = vattr_to_fattr4(in_va, NULL, attr, 0, OP_OPEN,
968 			    supp_attrs);
969 			if (v_error) {
970 				bzero(attr, sizeof (*attr));
971 				nfs4args_copen_free(open_args);
972 				nfs4_end_op(VTOMI4(dvp), dvp, vpi,
973 				    &recov_state, FALSE);
974 				if (ncr != NULL)
975 					crfree(ncr);
976 				kmem_free(argop, argoplist_size);
977 				return (v_error);
978 			}
979 		}
980 	} else {
981 		/* NO CREATE */
982 		open_args->opentype = OPEN4_NOCREATE;
983 	}
984 
985 	if (recov_state.rs_sp != NULL) {
986 		mutex_enter(&recov_state.rs_sp->s_lock);
987 		open_args->owner.clientid = recov_state.rs_sp->clientid;
988 		mutex_exit(&recov_state.rs_sp->s_lock);
989 	} else {
990 		/* XXX should we just fail here? */
991 		open_args->owner.clientid = 0;
992 	}
993 
994 	/*
995 	 * This increments oop's ref count or creates a temporary 'just_created'
996 	 * open owner that will become valid when this OPEN/OPEN_CONFIRM call
997 	 * completes.
998 	 */
999 	mutex_enter(&VTOMI4(dvp)->mi_lock);
1000 
1001 	/* See if a permanent or just created open owner exists */
1002 	oop = find_open_owner_nolock(cr, NFS4_JUST_CREATED, VTOMI4(dvp));
1003 	if (!oop) {
1004 		/*
1005 		 * This open owner does not exist so create a temporary
1006 		 * just created one.
1007 		 */
1008 		oop = create_open_owner(cr, VTOMI4(dvp));
1009 		ASSERT(oop != NULL);
1010 	}
1011 	mutex_exit(&VTOMI4(dvp)->mi_lock);
1012 
1013 	/* this length never changes, do alloc before seqid sync */
1014 	open_args->owner.owner_len = sizeof (oop->oo_name);
1015 	open_args->owner.owner_val =
1016 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1017 
1018 	e.error = nfs4_start_open_seqid_sync(oop, VTOMI4(dvp));
1019 	if (e.error == EAGAIN) {
1020 		open_owner_rele(oop);
1021 		nfs4args_copen_free(open_args);
1022 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1023 		if (ncr != NULL) {
1024 			crfree(ncr);
1025 			ncr = NULL;
1026 		}
1027 		goto recov_retry;
1028 	}
1029 
1030 	/* Check to see if we need to do the OTW call */
1031 	if (!create_flag) {
1032 		if (!nfs4_is_otw_open_necessary(oop, open_flag, vpi,
1033 		    file_just_been_created, &e.error, acc, &recov_state)) {
1034 
1035 			/*
1036 			 * The OTW open is not necessary.  Either
1037 			 * the open can succeed without it (eg.
1038 			 * delegation, error == 0) or the open
1039 			 * must fail due to an access failure
1040 			 * (error != 0).  In either case, tidy
1041 			 * up and return.
1042 			 */
1043 
1044 			nfs4_end_open_seqid_sync(oop);
1045 			open_owner_rele(oop);
1046 			nfs4args_copen_free(open_args);
1047 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, FALSE);
1048 			if (ncr != NULL)
1049 				crfree(ncr);
1050 			kmem_free(argop, argoplist_size);
1051 			return (e.error);
1052 		}
1053 	}
1054 
1055 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1056 	    open_args->owner.owner_len);
1057 
1058 	seqid = nfs4_get_open_seqid(oop) + 1;
1059 	open_args->seqid = seqid;
1060 	open_args->share_access = 0;
1061 	if (open_flag & FREAD)
1062 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1063 	if (open_flag & FWRITE)
1064 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1065 	open_args->share_deny = OPEN4_SHARE_DENY_NONE;
1066 
1067 
1068 
1069 	/*
1070 	 * getfh w/sanity check for idx_open/idx_fattr
1071 	 */
1072 	ASSERT((idx_open + 1) == (idx_fattr - 1));
1073 	argop[idx_open + 1].argop = OP_GETFH;
1074 
1075 	/* getattr */
1076 	argop[idx_fattr].argop = OP_GETATTR;
1077 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1078 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1079 
1080 	if (setgid_flag) {
1081 		vattr_t	_v;
1082 		servinfo4_t *svp;
1083 		bitmap4	supp_attrs;
1084 
1085 		svp = drp->r_server;
1086 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1087 		supp_attrs = svp->sv_supp_attrs;
1088 		nfs_rw_exit(&svp->sv_lock);
1089 
1090 		/*
1091 		 * For setgid case, we need to:
1092 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1093 		 */
1094 		argop[4].argop = OP_SAVEFH;
1095 
1096 		argop[5].argop = OP_CPUTFH;
1097 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
1098 
1099 		argop[6].argop = OP_GETATTR;
1100 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1101 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1102 
1103 		argop[7].argop = OP_RESTOREFH;
1104 
1105 		/*
1106 		 * nverify
1107 		 */
1108 		_v.va_mask = AT_GID;
1109 		_v.va_gid = in_va->va_gid;
1110 		if (!(e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
1111 		    supp_attrs))) {
1112 
1113 			/*
1114 			 * setattr
1115 			 *
1116 			 * We _know_ we're not messing with AT_SIZE or
1117 			 * AT_XTIME, so no need for stateid or flags.
1118 			 * Also we specify NULL rp since we're only
1119 			 * interested in setting owner_group attributes.
1120 			 */
1121 			nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr,
1122 			    supp_attrs, &e.error, 0);
1123 			if (e.error)
1124 				nfs4args_verify_free(&argop[8]);
1125 		}
1126 
1127 		if (e.error) {
1128 			/*
1129 			 * XXX - Revisit the last argument to nfs4_end_op()
1130 			 *	 once 5020486 is fixed.
1131 			 */
1132 			nfs4_end_open_seqid_sync(oop);
1133 			open_owner_rele(oop);
1134 			nfs4args_copen_free(open_args);
1135 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1136 			if (ncr != NULL)
1137 				crfree(ncr);
1138 			kmem_free(argop, argoplist_size);
1139 			return (e.error);
1140 		}
1141 	} else if (create_flag) {
1142 		/*
1143 		 * For setgid case, we need to:
1144 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1145 		 */
1146 		argop[1].argop = OP_SAVEFH;
1147 
1148 		argop[5].argop = OP_RESTOREFH;
1149 
1150 		argop[6].argop = OP_GETATTR;
1151 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1152 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1153 	}
1154 
1155 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1156 	    "nfs4open_otw: %s call, nm %s, rp %s",
1157 	    needrecov ? "recov" : "first", file_name,
1158 	    rnode4info(VTOR4(dvp))));
1159 
1160 	t = gethrtime();
1161 
1162 	rfs4call(VTOMI4(dvp), &args, &res, cred_otw, &doqueue, 0, &e);
1163 
1164 	if (!e.error && nfs4_need_to_bump_seqid(&res))
1165 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1166 
1167 	needrecov = nfs4_needs_recovery(&e, TRUE, dvp->v_vfsp);
1168 
1169 	if (e.error || needrecov) {
1170 		bool_t abort = FALSE;
1171 
1172 		if (needrecov) {
1173 			nfs4_bseqid_entry_t *bsep = NULL;
1174 
1175 			nfs4open_save_lost_rqst(e.error, &lost_rqst, oop,
1176 			    cred_otw, vpi, dvp, open_args);
1177 
1178 			if (!e.error && res.status == NFS4ERR_BAD_SEQID) {
1179 				bsep = nfs4_create_bseqid_entry(oop, NULL,
1180 				    vpi, 0, args.ctag, open_args->seqid);
1181 				num_bseqid_retry--;
1182 			}
1183 
1184 			abort = nfs4_start_recovery(&e, VTOMI4(dvp), dvp, vpi,
1185 			    NULL, lost_rqst.lr_op == OP_OPEN ?
1186 			    &lost_rqst : NULL, OP_OPEN, bsep);
1187 
1188 			if (bsep)
1189 				kmem_free(bsep, sizeof (*bsep));
1190 			/* give up if we keep getting BAD_SEQID */
1191 			if (num_bseqid_retry == 0)
1192 				abort = TRUE;
1193 			if (abort == TRUE && e.error == 0)
1194 				e.error = geterrno4(res.status);
1195 		}
1196 		nfs4_end_open_seqid_sync(oop);
1197 		open_owner_rele(oop);
1198 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1199 		nfs4args_copen_free(open_args);
1200 		if (setgid_flag) {
1201 			nfs4args_verify_free(&argop[8]);
1202 			nfs4args_setattr_free(&argop[9]);
1203 		}
1204 		if (!e.error)
1205 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1206 		if (ncr != NULL) {
1207 			crfree(ncr);
1208 			ncr = NULL;
1209 		}
1210 		if (!needrecov || abort == TRUE || e.error == EINTR ||
1211 		    NFS4_FRC_UNMT_ERR(e.error, dvp->v_vfsp)) {
1212 			kmem_free(argop, argoplist_size);
1213 			return (e.error);
1214 		}
1215 		goto recov_retry;
1216 	}
1217 
1218 	/*
1219 	 * Will check and update lease after checking the rflag for
1220 	 * OPEN_CONFIRM in the successful OPEN call.
1221 	 */
1222 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
1223 
1224 		/*
1225 		 * XXX what if we're crossing mount points from server1:/drp
1226 		 * to server2:/drp/rp.
1227 		 */
1228 
1229 		/* Signal our end of use of the open seqid */
1230 		nfs4_end_open_seqid_sync(oop);
1231 
1232 		/*
1233 		 * This will destroy the open owner if it was just created,
1234 		 * and no one else has put a reference on it.
1235 		 */
1236 		open_owner_rele(oop);
1237 		if (create_flag && (createmode != EXCLUSIVE4) &&
1238 		    res.status == NFS4ERR_BADOWNER)
1239 			nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1240 
1241 		e.error = geterrno4(res.status);
1242 		nfs4args_copen_free(open_args);
1243 		if (setgid_flag) {
1244 			nfs4args_verify_free(&argop[8]);
1245 			nfs4args_setattr_free(&argop[9]);
1246 		}
1247 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1248 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1249 		/*
1250 		 * If the reply is NFS4ERR_ACCESS, it may be because
1251 		 * we are root (no root net access).  If the real uid
1252 		 * is not root, then retry with the real uid instead.
1253 		 */
1254 		if (ncr != NULL) {
1255 			crfree(ncr);
1256 			ncr = NULL;
1257 		}
1258 		if (res.status == NFS4ERR_ACCESS &&
1259 		    (ncr = crnetadjust(cred_otw)) != NULL) {
1260 			cred_otw = ncr;
1261 			goto recov_retry;
1262 		}
1263 		kmem_free(argop, argoplist_size);
1264 		return (e.error);
1265 	}
1266 
1267 	resop = &res.array[idx_open];  /* open res */
1268 	op_res = &resop->nfs_resop4_u.opopen;
1269 
1270 #ifdef DEBUG
1271 	/*
1272 	 * verify attrset bitmap
1273 	 */
1274 	if (create_flag &&
1275 	    (createmode == UNCHECKED4 || createmode == GUARDED4)) {
1276 		/* make sure attrset returned is what we asked for */
1277 		/* XXX Ignore this 'error' for now */
1278 		if (attr->attrmask != op_res->attrset)
1279 			/* EMPTY */;
1280 	}
1281 #endif
1282 
1283 	if (op_res->rflags & OPEN4_RESULT_LOCKTYPE_POSIX) {
1284 		mutex_enter(&VTOMI4(dvp)->mi_lock);
1285 		VTOMI4(dvp)->mi_flags |= MI4_POSIX_LOCK;
1286 		mutex_exit(&VTOMI4(dvp)->mi_lock);
1287 	}
1288 
1289 	resop = &res.array[idx_open + 1];  /* getfh res */
1290 	gf_res = &resop->nfs_resop4_u.opgetfh;
1291 
1292 	otw_sfh = sfh4_get(&gf_res->object, VTOMI4(dvp));
1293 
1294 	/*
1295 	 * The open stateid has been updated on the server but not
1296 	 * on the client yet.  There is a path: makenfs4node->nfs4_attr_cache->
1297 	 * flush_pages->VOP_PUTPAGE->...->nfs4write where we will issue an OTW
1298 	 * WRITE call.  That, however, will use the old stateid, so go ahead
1299 	 * and upate the open stateid now, before any call to makenfs4node.
1300 	 */
1301 	if (vpi) {
1302 		nfs4_open_stream_t	*tmp_osp;
1303 		rnode4_t		*tmp_rp = VTOR4(vpi);
1304 
1305 		tmp_osp = find_open_stream(oop, tmp_rp);
1306 		if (tmp_osp) {
1307 			tmp_osp->open_stateid = op_res->stateid;
1308 			mutex_exit(&tmp_osp->os_sync_lock);
1309 			open_stream_rele(tmp_osp, tmp_rp);
1310 		}
1311 
1312 		/*
1313 		 * We must determine if the file handle given by the otw open
1314 		 * is the same as the file handle which was passed in with
1315 		 * *vpp.  This case can be reached if the file we are trying
1316 		 * to open has been removed and another file has been created
1317 		 * having the same file name.  The passed in vnode is released
1318 		 * later.
1319 		 */
1320 		orig_sfh = VTOR4(vpi)->r_fh;
1321 		fh_differs = nfs4cmpfh(&orig_sfh->sfh_fh, &otw_sfh->sfh_fh);
1322 	}
1323 
1324 	garp = &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res;
1325 
1326 	if (create_flag || fh_differs) {
1327 		int rnode_err = 0;
1328 
1329 		vp = makenfs4node(otw_sfh, garp, dvp->v_vfsp, t, cr,
1330 		    dvp, fn_get(VTOSV(dvp)->sv_name, file_name));
1331 
1332 		if (e.error)
1333 			PURGE_ATTRCACHE4(vp);
1334 		/*
1335 		 * For the newly created vp case, make sure the rnode
1336 		 * isn't bad before using it.
1337 		 */
1338 		mutex_enter(&(VTOR4(vp))->r_statelock);
1339 		if (VTOR4(vp)->r_flags & R4RECOVERR)
1340 			rnode_err = EIO;
1341 		mutex_exit(&(VTOR4(vp))->r_statelock);
1342 
1343 		if (rnode_err) {
1344 			nfs4_end_open_seqid_sync(oop);
1345 			nfs4args_copen_free(open_args);
1346 			if (setgid_flag) {
1347 				nfs4args_verify_free(&argop[8]);
1348 				nfs4args_setattr_free(&argop[9]);
1349 			}
1350 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1351 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1352 			    needrecov);
1353 			open_owner_rele(oop);
1354 			VN_RELE(vp);
1355 			if (ncr != NULL)
1356 				crfree(ncr);
1357 			sfh4_rele(&otw_sfh);
1358 			kmem_free(argop, argoplist_size);
1359 			return (EIO);
1360 		}
1361 	} else {
1362 		vp = vpi;
1363 	}
1364 	sfh4_rele(&otw_sfh);
1365 
1366 	/*
1367 	 * It seems odd to get a full set of attrs and then not update
1368 	 * the object's attrcache in the non-create case.  Create case uses
1369 	 * the attrs since makenfs4node checks to see if the attrs need to
1370 	 * be updated (and then updates them).  The non-create case should
1371 	 * update attrs also.
1372 	 */
1373 	if (! create_flag && ! fh_differs && !e.error) {
1374 		nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
1375 	}
1376 
1377 	nfs4_error_zinit(&e);
1378 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
1379 		/* This does not do recovery for vp explicitly. */
1380 		nfs4open_confirm(vp, &seqid, &op_res->stateid, cred_otw, FALSE,
1381 		    &retry_open, oop, FALSE, &e, &num_bseqid_retry);
1382 
1383 		if (e.error || e.stat) {
1384 			nfs4_end_open_seqid_sync(oop);
1385 			nfs4args_copen_free(open_args);
1386 			if (setgid_flag) {
1387 				nfs4args_verify_free(&argop[8]);
1388 				nfs4args_setattr_free(&argop[9]);
1389 			}
1390 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1391 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1392 			    needrecov);
1393 			open_owner_rele(oop);
1394 			if (create_flag || fh_differs) {
1395 				/* rele the makenfs4node */
1396 				VN_RELE(vp);
1397 			}
1398 			if (ncr != NULL) {
1399 				crfree(ncr);
1400 				ncr = NULL;
1401 			}
1402 			if (retry_open == TRUE) {
1403 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1404 				    "nfs4open_otw: retry the open since OPEN "
1405 				    "CONFIRM failed with error %d stat %d",
1406 				    e.error, e.stat));
1407 				if (create_flag && createmode == GUARDED4) {
1408 					NFS4_DEBUG(nfs4_client_recov_debug,
1409 					    (CE_NOTE, "nfs4open_otw: switch "
1410 					    "createmode from GUARDED4 to "
1411 					    "UNCHECKED4"));
1412 					createmode = UNCHECKED4;
1413 				}
1414 				goto recov_retry;
1415 			}
1416 			if (!e.error) {
1417 				if (create_flag && (createmode != EXCLUSIVE4) &&
1418 				    e.stat == NFS4ERR_BADOWNER)
1419 					nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1420 
1421 				e.error = geterrno4(e.stat);
1422 			}
1423 			kmem_free(argop, argoplist_size);
1424 			return (e.error);
1425 		}
1426 	}
1427 
1428 	rp = VTOR4(vp);
1429 
1430 	mutex_enter(&rp->r_statev4_lock);
1431 	if (create_flag)
1432 		rp->created_v4 = 1;
1433 	mutex_exit(&rp->r_statev4_lock);
1434 
1435 	mutex_enter(&oop->oo_lock);
1436 	/* Doesn't matter if 'oo_just_created' already was set as this */
1437 	oop->oo_just_created = NFS4_PERM_CREATED;
1438 	if (oop->oo_cred_otw)
1439 		crfree(oop->oo_cred_otw);
1440 	oop->oo_cred_otw = cred_otw;
1441 	crhold(oop->oo_cred_otw);
1442 	mutex_exit(&oop->oo_lock);
1443 
1444 	/* returns with 'os_sync_lock' held */
1445 	osp = find_or_create_open_stream(oop, rp, &created_osp);
1446 	if (!osp) {
1447 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1448 		    "nfs4open_otw: failed to create an open stream"));
1449 		NFS4_DEBUG(nfs4_seqid_sync, (CE_NOTE, "nfs4open_otw: "
1450 		    "signal our end of use of the open seqid"));
1451 
1452 		nfs4_end_open_seqid_sync(oop);
1453 		open_owner_rele(oop);
1454 		nfs4args_copen_free(open_args);
1455 		if (setgid_flag) {
1456 			nfs4args_verify_free(&argop[8]);
1457 			nfs4args_setattr_free(&argop[9]);
1458 		}
1459 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1460 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1461 		if (create_flag || fh_differs)
1462 			VN_RELE(vp);
1463 		if (ncr != NULL)
1464 			crfree(ncr);
1465 
1466 		kmem_free(argop, argoplist_size);
1467 		return (EINVAL);
1468 
1469 	}
1470 
1471 	osp->open_stateid = op_res->stateid;
1472 
1473 	if (open_flag & FREAD)
1474 		osp->os_share_acc_read++;
1475 	if (open_flag & FWRITE)
1476 		osp->os_share_acc_write++;
1477 	osp->os_share_deny_none++;
1478 
1479 	/*
1480 	 * Need to reset this bitfield for the possible case where we were
1481 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
1482 	 * we could retry the CLOSE, OPENed the file again.
1483 	 */
1484 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
1485 	osp->os_final_close = 0;
1486 	osp->os_force_close = 0;
1487 #ifdef DEBUG
1488 	if (osp->os_failed_reopen)
1489 		NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE, "nfs4open_otw:"
1490 		    " clearing os_failed_reopen for osp %p, cr %p, rp %s",
1491 		    (void *)osp, (void *)cr, rnode4info(rp)));
1492 #endif
1493 	osp->os_failed_reopen = 0;
1494 
1495 	mutex_exit(&osp->os_sync_lock);
1496 
1497 	nfs4_end_open_seqid_sync(oop);
1498 
1499 	if (created_osp && recov_state.rs_sp != NULL) {
1500 		mutex_enter(&recov_state.rs_sp->s_lock);
1501 		nfs4_inc_state_ref_count_nolock(recov_state.rs_sp, VTOMI4(dvp));
1502 		mutex_exit(&recov_state.rs_sp->s_lock);
1503 	}
1504 
1505 	/* get rid of our reference to find oop */
1506 	open_owner_rele(oop);
1507 
1508 	open_stream_rele(osp, rp);
1509 
1510 	/* accept delegation, if any */
1511 	nfs4_delegation_accept(rp, CLAIM_NULL, op_res, garp, cred_otw);
1512 
1513 	nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1514 
1515 	if (createmode == EXCLUSIVE4 &&
1516 	    (in_va->va_mask & ~(AT_GID | AT_SIZE))) {
1517 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw:"
1518 		    " EXCLUSIVE4: sending a SETATTR"));
1519 		/*
1520 		 * If doing an exclusive create, then generate
1521 		 * a SETATTR to set the initial attributes.
1522 		 * Try to set the mtime and the atime to the
1523 		 * server's current time.  It is somewhat
1524 		 * expected that these fields will be used to
1525 		 * store the exclusive create cookie.  If not,
1526 		 * server implementors will need to know that
1527 		 * a SETATTR will follow an exclusive create
1528 		 * and the cookie should be destroyed if
1529 		 * appropriate.
1530 		 *
1531 		 * The AT_GID and AT_SIZE bits are turned off
1532 		 * so that the SETATTR request will not attempt
1533 		 * to process these.  The gid will be set
1534 		 * separately if appropriate.  The size is turned
1535 		 * off because it is assumed that a new file will
1536 		 * be created empty and if the file wasn't empty,
1537 		 * then the exclusive create will have failed
1538 		 * because the file must have existed already.
1539 		 * Therefore, no truncate operation is needed.
1540 		 */
1541 		in_va->va_mask &= ~(AT_GID | AT_SIZE);
1542 		in_va->va_mask |= (AT_MTIME | AT_ATIME);
1543 
1544 		e.error = nfs4setattr(vp, in_va, 0, cr, NULL);
1545 		if (e.error) {
1546 			/*
1547 			 * Couldn't correct the attributes of
1548 			 * the newly created file and the
1549 			 * attributes are wrong.  Remove the
1550 			 * file and return an error to the
1551 			 * application.
1552 			 */
1553 			/* XXX will this take care of client state ? */
1554 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1555 			    "nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1556 			    " remove file", e.error));
1557 			VN_RELE(vp);
1558 			(void) nfs4_remove(dvp, file_name, cr, NULL, 0);
1559 			/*
1560 			 * Since we've reled the vnode and removed
1561 			 * the file we now need to return the error.
1562 			 * At this point we don't want to update the
1563 			 * dircaches, call nfs4_waitfor_purge_complete
1564 			 * or set vpp to vp so we need to skip these
1565 			 * as well.
1566 			 */
1567 			goto skip_update_dircaches;
1568 		}
1569 	}
1570 
1571 	/*
1572 	 * If we created or found the correct vnode, due to create_flag or
1573 	 * fh_differs being set, then update directory cache attribute, readdir
1574 	 * and dnlc caches.
1575 	 */
1576 	if (create_flag || fh_differs) {
1577 		dirattr_info_t dinfo, *dinfop;
1578 
1579 		/*
1580 		 * Make sure getattr succeeded before using results.
1581 		 * note: op 7 is getattr(dir) for both flavors of
1582 		 * open(create).
1583 		 */
1584 		if (create_flag && res.status == NFS4_OK) {
1585 			dinfo.di_time_call = t;
1586 			dinfo.di_cred = cr;
1587 			dinfo.di_garp =
1588 			    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
1589 			dinfop = &dinfo;
1590 		} else {
1591 			dinfop = NULL;
1592 		}
1593 
1594 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1595 		    dinfop);
1596 	}
1597 
1598 	/*
1599 	 * If the page cache for this file was flushed from actions
1600 	 * above, it was done asynchronously and if that is true,
1601 	 * there is a need to wait here for it to complete.  This must
1602 	 * be done outside of start_fop/end_fop.
1603 	 */
1604 	(void) nfs4_waitfor_purge_complete(vp);
1605 
1606 	/*
1607 	 * It is implicit that we are in the open case (create_flag == 0) since
1608 	 * fh_differs can only be set to a non-zero value in the open case.
1609 	 */
1610 	if (fh_differs != 0 && vpi != NULL)
1611 		VN_RELE(vpi);
1612 
1613 	/*
1614 	 * Be sure to set *vpp to the correct value before returning.
1615 	 */
1616 	*vpp = vp;
1617 
1618 skip_update_dircaches:
1619 
1620 	nfs4args_copen_free(open_args);
1621 	if (setgid_flag) {
1622 		nfs4args_verify_free(&argop[8]);
1623 		nfs4args_setattr_free(&argop[9]);
1624 	}
1625 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1626 
1627 	if (ncr)
1628 		crfree(ncr);
1629 	kmem_free(argop, argoplist_size);
1630 	return (e.error);
1631 }
1632 
1633 /*
1634  * Reopen an open instance.  cf. nfs4open_otw().
1635  *
1636  * Errors are returned by the nfs4_error_t parameter.
1637  * - ep->error contains an errno value or zero.
1638  * - if it is zero, ep->stat is set to an NFS status code, if any.
1639  *   If the file could not be reopened, but the caller should continue, the
1640  *   file is marked dead and no error values are returned.  If the caller
1641  *   should stop recovering open files and start over, either the ep->error
1642  *   value or ep->stat will indicate an error (either something that requires
1643  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1644  *   filehandles) may be handled silently by this routine.
1645  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1646  *   will be started, so the caller should not do it.
1647  *
1648  * Gotos:
1649  * - kill_file : reopen failed in such a fashion to constitute marking the
1650  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1651  *   is for cases where recovery is not possible.
1652  * - failed_reopen : same as above, except that the file has already been
1653  *   marked dead, so no need to do it again.
1654  * - bailout : reopen failed but we are able to recover and retry the reopen -
1655  *   either within this function immediately or via the calling function.
1656  */
1657 
1658 void
1659 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1660     open_claim_type4 claim, bool_t frc_use_claim_previous,
1661     bool_t is_recov)
1662 {
1663 	COMPOUND4args_clnt args;
1664 	COMPOUND4res_clnt res;
1665 	nfs_argop4 argop[4];
1666 	nfs_resop4 *resop;
1667 	OPEN4res *op_res = NULL;
1668 	OPEN4cargs *open_args;
1669 	GETFH4res *gf_res;
1670 	rnode4_t *rp = VTOR4(vp);
1671 	int doqueue = 1;
1672 	cred_t *cr = NULL, *cred_otw = NULL;
1673 	nfs4_open_owner_t *oop = NULL;
1674 	seqid4 seqid;
1675 	nfs4_ga_res_t *garp;
1676 	char fn[MAXNAMELEN];
1677 	nfs4_recov_state_t recov = {NULL, 0};
1678 	nfs4_lost_rqst_t lost_rqst;
1679 	mntinfo4_t *mi = VTOMI4(vp);
1680 	bool_t abort;
1681 	char *failed_msg = "";
1682 	int fh_different;
1683 	hrtime_t t;
1684 	nfs4_bseqid_entry_t *bsep = NULL;
1685 
1686 	ASSERT(nfs4_consistent_type(vp));
1687 	ASSERT(nfs_zone() == mi->mi_zone);
1688 
1689 	nfs4_error_zinit(ep);
1690 
1691 	/* this is the cred used to find the open owner */
1692 	cr = state_to_cred(osp);
1693 	if (cr == NULL) {
1694 		failed_msg = "Couldn't reopen: no cred";
1695 		goto kill_file;
1696 	}
1697 	/* use this cred for OTW operations */
1698 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1699 
1700 top:
1701 	nfs4_error_zinit(ep);
1702 
1703 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1704 		/* File system has been unmounted, quit */
1705 		ep->error = EIO;
1706 		failed_msg = "Couldn't reopen: file system has been unmounted";
1707 		goto kill_file;
1708 	}
1709 
1710 	oop = osp->os_open_owner;
1711 
1712 	ASSERT(oop != NULL);
1713 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1714 		failed_msg = "can't reopen: no open owner";
1715 		goto kill_file;
1716 	}
1717 	open_owner_hold(oop);
1718 
1719 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1720 	if (ep->error) {
1721 		open_owner_rele(oop);
1722 		oop = NULL;
1723 		goto bailout;
1724 	}
1725 
1726 	/*
1727 	 * If the rnode has a delegation and the delegation has been
1728 	 * recovered and the server didn't request a recall and the caller
1729 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1730 	 * recovery) and the rnode hasn't been marked dead, then install
1731 	 * the delegation stateid in the open stream.  Otherwise, proceed
1732 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1733 	 */
1734 	mutex_enter(&rp->r_statev4_lock);
1735 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1736 	    !rp->r_deleg_return_pending &&
1737 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1738 	    !rp->r_deleg_needs_recall &&
1739 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1740 	    !(rp->r_flags & R4RECOVERR)) {
1741 		mutex_enter(&osp->os_sync_lock);
1742 		osp->os_delegation = 1;
1743 		osp->open_stateid = rp->r_deleg_stateid;
1744 		mutex_exit(&osp->os_sync_lock);
1745 		mutex_exit(&rp->r_statev4_lock);
1746 		goto bailout;
1747 	}
1748 	mutex_exit(&rp->r_statev4_lock);
1749 
1750 	/*
1751 	 * If the file failed recovery, just quit.  This failure need not
1752 	 * affect other reopens, so don't return an error.
1753 	 */
1754 	mutex_enter(&rp->r_statelock);
1755 	if (rp->r_flags & R4RECOVERR) {
1756 		mutex_exit(&rp->r_statelock);
1757 		ep->error = 0;
1758 		goto failed_reopen;
1759 	}
1760 	mutex_exit(&rp->r_statelock);
1761 
1762 	/*
1763 	 * argop is empty here
1764 	 *
1765 	 * PUTFH, OPEN, GETATTR
1766 	 */
1767 	args.ctag = TAG_REOPEN;
1768 	args.array_len = 4;
1769 	args.array = argop;
1770 
1771 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1772 	    "nfs4_reopen: file is type %d, id %s",
1773 	    vp->v_type, rnode4info(VTOR4(vp))));
1774 
1775 	argop[0].argop = OP_CPUTFH;
1776 
1777 	if (claim != CLAIM_PREVIOUS) {
1778 		/*
1779 		 * if this is a file mount then
1780 		 * use the mntinfo parentfh
1781 		 */
1782 		argop[0].nfs_argop4_u.opcputfh.sfh =
1783 		    (vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1784 		    VTOSV(vp)->sv_dfh;
1785 	} else {
1786 		/* putfh fh to reopen */
1787 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1788 	}
1789 
1790 	argop[1].argop = OP_COPEN;
1791 	open_args = &argop[1].nfs_argop4_u.opcopen;
1792 	open_args->claim = claim;
1793 
1794 	if (claim == CLAIM_NULL) {
1795 
1796 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1797 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1798 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1799 			    (void *)vp);
1800 			failed_msg = "Couldn't reopen: vtoname failed for "
1801 			    "CLAIM_NULL";
1802 			/* nothing allocated yet */
1803 			goto kill_file;
1804 		}
1805 
1806 		open_args->open_claim4_u.cfile = fn;
1807 	} else if (claim == CLAIM_PREVIOUS) {
1808 
1809 		/*
1810 		 * We have two cases to deal with here:
1811 		 * 1) We're being called to reopen files in order to satisfy
1812 		 *    a lock operation request which requires us to explicitly
1813 		 *    reopen files which were opened under a delegation.  If
1814 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1815 		 *    that case, frc_use_claim_previous is TRUE and we must
1816 		 *    use the rnode's current delegation type (r_deleg_type).
1817 		 * 2) We're reopening files during some form of recovery.
1818 		 *    In this case, frc_use_claim_previous is FALSE and we
1819 		 *    use the delegation type appropriate for recovery
1820 		 *    (r_deleg_needs_recovery).
1821 		 */
1822 		mutex_enter(&rp->r_statev4_lock);
1823 		open_args->open_claim4_u.delegate_type =
1824 		    frc_use_claim_previous ?
1825 		    rp->r_deleg_type :
1826 		    rp->r_deleg_needs_recovery;
1827 		mutex_exit(&rp->r_statev4_lock);
1828 
1829 	} else if (claim == CLAIM_DELEGATE_CUR) {
1830 
1831 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1832 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1833 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1834 			    "with %m", (void *)vp);
1835 			failed_msg = "Couldn't reopen: vtoname failed for "
1836 			    "CLAIM_DELEGATE_CUR";
1837 			/* nothing allocated yet */
1838 			goto kill_file;
1839 		}
1840 
1841 		mutex_enter(&rp->r_statev4_lock);
1842 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1843 		    rp->r_deleg_stateid;
1844 		mutex_exit(&rp->r_statev4_lock);
1845 
1846 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1847 	}
1848 	open_args->opentype = OPEN4_NOCREATE;
1849 	open_args->owner.clientid = mi2clientid(mi);
1850 	open_args->owner.owner_len = sizeof (oop->oo_name);
1851 	open_args->owner.owner_val =
1852 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1853 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1854 	    open_args->owner.owner_len);
1855 	open_args->share_access = 0;
1856 	open_args->share_deny = 0;
1857 
1858 	mutex_enter(&osp->os_sync_lock);
1859 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1860 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1861 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1862 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1863 	    osp->os_share_acc_write, osp->os_open_ref_count,
1864 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1865 
1866 	if (osp->os_share_acc_read || osp->os_mmap_read)
1867 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1868 	if (osp->os_share_acc_write || osp->os_mmap_write)
1869 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1870 	if (osp->os_share_deny_read)
1871 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1872 	if (osp->os_share_deny_write)
1873 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1874 	mutex_exit(&osp->os_sync_lock);
1875 
1876 	seqid = nfs4_get_open_seqid(oop) + 1;
1877 	open_args->seqid = seqid;
1878 
1879 	/* Construct the getfh part of the compound */
1880 	argop[2].argop = OP_GETFH;
1881 
1882 	/* Construct the getattr part of the compound */
1883 	argop[3].argop = OP_GETATTR;
1884 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1885 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1886 
1887 	t = gethrtime();
1888 
1889 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1890 
1891 	if (ep->error) {
1892 		if (!is_recov && !frc_use_claim_previous &&
1893 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1894 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1895 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1896 			    cred_otw, vp, NULL, open_args);
1897 			abort = nfs4_start_recovery(ep,
1898 			    VTOMI4(vp), vp, NULL, NULL,
1899 			    lost_rqst.lr_op == OP_OPEN ?
1900 			    &lost_rqst : NULL, OP_OPEN, NULL);
1901 			nfs4args_copen_free(open_args);
1902 			goto bailout;
1903 		}
1904 
1905 		nfs4args_copen_free(open_args);
1906 
1907 		if (ep->error == EACCES && cred_otw != cr) {
1908 			crfree(cred_otw);
1909 			cred_otw = cr;
1910 			crhold(cred_otw);
1911 			nfs4_end_open_seqid_sync(oop);
1912 			open_owner_rele(oop);
1913 			oop = NULL;
1914 			goto top;
1915 		}
1916 		if (ep->error == ETIMEDOUT)
1917 			goto bailout;
1918 		failed_msg = "Couldn't reopen: rpc error";
1919 		goto kill_file;
1920 	}
1921 
1922 	if (nfs4_need_to_bump_seqid(&res))
1923 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1924 
1925 	switch (res.status) {
1926 	case NFS4_OK:
1927 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1928 			mutex_enter(&rp->r_statelock);
1929 			rp->r_delay_interval = 0;
1930 			mutex_exit(&rp->r_statelock);
1931 		}
1932 		break;
1933 	case NFS4ERR_BAD_SEQID:
1934 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1935 		    args.ctag, open_args->seqid);
1936 
1937 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1938 		    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1939 		    NULL, OP_OPEN, bsep);
1940 
1941 		nfs4args_copen_free(open_args);
1942 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1943 		nfs4_end_open_seqid_sync(oop);
1944 		open_owner_rele(oop);
1945 		oop = NULL;
1946 		kmem_free(bsep, sizeof (*bsep));
1947 
1948 		goto kill_file;
1949 	case NFS4ERR_NO_GRACE:
1950 		nfs4args_copen_free(open_args);
1951 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1952 		nfs4_end_open_seqid_sync(oop);
1953 		open_owner_rele(oop);
1954 		oop = NULL;
1955 		if (claim == CLAIM_PREVIOUS) {
1956 			/*
1957 			 * Retry as a plain open. We don't need to worry about
1958 			 * checking the changeinfo: it is acceptable for a
1959 			 * client to re-open a file and continue processing
1960 			 * (in the absence of locks).
1961 			 */
1962 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1963 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1964 			    "will retry as CLAIM_NULL"));
1965 			claim = CLAIM_NULL;
1966 			nfs4_mi_kstat_inc_no_grace(mi);
1967 			goto top;
1968 		}
1969 		failed_msg =
1970 		    "Couldn't reopen: tried reclaim outside grace period. ";
1971 		goto kill_file;
1972 	case NFS4ERR_GRACE:
1973 		nfs4_set_grace_wait(mi);
1974 		nfs4args_copen_free(open_args);
1975 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1976 		nfs4_end_open_seqid_sync(oop);
1977 		open_owner_rele(oop);
1978 		oop = NULL;
1979 		ep->error = nfs4_wait_for_grace(mi, &recov);
1980 		if (ep->error != 0)
1981 			goto bailout;
1982 		goto top;
1983 	case NFS4ERR_DELAY:
1984 		nfs4_set_delay_wait(vp);
1985 		nfs4args_copen_free(open_args);
1986 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1987 		nfs4_end_open_seqid_sync(oop);
1988 		open_owner_rele(oop);
1989 		oop = NULL;
1990 		ep->error = nfs4_wait_for_delay(vp, &recov);
1991 		nfs4_mi_kstat_inc_delay(mi);
1992 		if (ep->error != 0)
1993 			goto bailout;
1994 		goto top;
1995 	case NFS4ERR_FHEXPIRED:
1996 		/* recover filehandle and retry */
1997 		abort = nfs4_start_recovery(ep,
1998 		    mi, vp, NULL, NULL, NULL, OP_OPEN, NULL);
1999 		nfs4args_copen_free(open_args);
2000 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2001 		nfs4_end_open_seqid_sync(oop);
2002 		open_owner_rele(oop);
2003 		oop = NULL;
2004 		if (abort == FALSE)
2005 			goto top;
2006 		failed_msg = "Couldn't reopen: recovery aborted";
2007 		goto kill_file;
2008 	case NFS4ERR_RESOURCE:
2009 	case NFS4ERR_STALE_CLIENTID:
2010 	case NFS4ERR_WRONGSEC:
2011 	case NFS4ERR_EXPIRED:
2012 		/*
2013 		 * Do not mark the file dead and let the calling
2014 		 * function initiate recovery.
2015 		 */
2016 		nfs4args_copen_free(open_args);
2017 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2018 		nfs4_end_open_seqid_sync(oop);
2019 		open_owner_rele(oop);
2020 		oop = NULL;
2021 		goto bailout;
2022 	case NFS4ERR_ACCESS:
2023 		if (cred_otw != cr) {
2024 			crfree(cred_otw);
2025 			cred_otw = cr;
2026 			crhold(cred_otw);
2027 			nfs4args_copen_free(open_args);
2028 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2029 			nfs4_end_open_seqid_sync(oop);
2030 			open_owner_rele(oop);
2031 			oop = NULL;
2032 			goto top;
2033 		}
2034 		/* fall through */
2035 	default:
2036 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2037 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2038 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2039 		    rnode4info(VTOR4(vp))));
2040 		failed_msg = "Couldn't reopen: NFSv4 error";
2041 		nfs4args_copen_free(open_args);
2042 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2043 		goto kill_file;
2044 	}
2045 
2046 	resop = &res.array[1];  /* open res */
2047 	op_res = &resop->nfs_resop4_u.opopen;
2048 
2049 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2050 
2051 	/*
2052 	 * Check if the path we reopened really is the same
2053 	 * file. We could end up in a situation where the file
2054 	 * was removed and a new file created with the same name.
2055 	 */
2056 	resop = &res.array[2];
2057 	gf_res = &resop->nfs_resop4_u.opgetfh;
2058 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2059 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2060 	if (fh_different) {
2061 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2062 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2063 			/* Oops, we don't have the same file */
2064 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2065 				failed_msg = "Couldn't reopen: Persistent "
2066 				    "file handle changed";
2067 			else
2068 				failed_msg = "Couldn't reopen: Volatile "
2069 				    "(no expire on open) file handle changed";
2070 
2071 			nfs4args_copen_free(open_args);
2072 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2073 			nfs_rw_exit(&mi->mi_fh_lock);
2074 			goto kill_file;
2075 
2076 		} else {
2077 			/*
2078 			 * We have volatile file handles that don't compare.
2079 			 * If the fids are the same then we assume that the
2080 			 * file handle expired but the rnode still refers to
2081 			 * the same file object.
2082 			 *
2083 			 * First check that we have fids or not.
2084 			 * If we don't we have a dumb server so we will
2085 			 * just assume every thing is ok for now.
2086 			 */
2087 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2088 			    rp->r_attr.va_mask & AT_NODEID &&
2089 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2090 				/*
2091 				 * We have fids, but they don't
2092 				 * compare. So kill the file.
2093 				 */
2094 				failed_msg =
2095 				    "Couldn't reopen: file handle changed"
2096 				    " due to mismatched fids";
2097 				nfs4args_copen_free(open_args);
2098 				(void) xdr_free(xdr_COMPOUND4res_clnt,
2099 				    (caddr_t)&res);
2100 				nfs_rw_exit(&mi->mi_fh_lock);
2101 				goto kill_file;
2102 			} else {
2103 				/*
2104 				 * We have volatile file handles that refers
2105 				 * to the same file (at least they have the
2106 				 * same fid) or we don't have fids so we
2107 				 * can't tell. :(. We'll be a kind and accepting
2108 				 * client so we'll update the rnode's file
2109 				 * handle with the otw handle.
2110 				 *
2111 				 * We need to drop mi->mi_fh_lock since
2112 				 * sh4_update acquires it. Since there is
2113 				 * only one recovery thread there is no
2114 				 * race.
2115 				 */
2116 				nfs_rw_exit(&mi->mi_fh_lock);
2117 				sfh4_update(rp->r_fh, &gf_res->object);
2118 			}
2119 		}
2120 	} else {
2121 		nfs_rw_exit(&mi->mi_fh_lock);
2122 	}
2123 
2124 	ASSERT(nfs4_consistent_type(vp));
2125 
2126 	/*
2127 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2128 	 * over.  Presumably if there is a persistent error it will show up
2129 	 * when we resend the OPEN.
2130 	 */
2131 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2132 		bool_t retry_open = FALSE;
2133 
2134 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2135 		    cred_otw, is_recov, &retry_open,
2136 		    oop, FALSE, ep, NULL);
2137 		if (ep->error || ep->stat) {
2138 			nfs4args_copen_free(open_args);
2139 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2140 			nfs4_end_open_seqid_sync(oop);
2141 			open_owner_rele(oop);
2142 			oop = NULL;
2143 			goto top;
2144 		}
2145 	}
2146 
2147 	mutex_enter(&osp->os_sync_lock);
2148 	osp->open_stateid = op_res->stateid;
2149 	osp->os_delegation = 0;
2150 	/*
2151 	 * Need to reset this bitfield for the possible case where we were
2152 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2153 	 * we could retry the CLOSE, OPENed the file again.
2154 	 */
2155 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2156 	osp->os_final_close = 0;
2157 	osp->os_force_close = 0;
2158 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2159 		osp->os_dc_openacc = open_args->share_access;
2160 	mutex_exit(&osp->os_sync_lock);
2161 
2162 	nfs4_end_open_seqid_sync(oop);
2163 
2164 	/* accept delegation, if any */
2165 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2166 
2167 	nfs4args_copen_free(open_args);
2168 
2169 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2170 
2171 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2172 
2173 	ASSERT(nfs4_consistent_type(vp));
2174 
2175 	open_owner_rele(oop);
2176 	crfree(cr);
2177 	crfree(cred_otw);
2178 	return;
2179 
2180 kill_file:
2181 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2182 failed_reopen:
2183 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2184 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2185 	    (void *)osp, (void *)cr, rnode4info(rp)));
2186 	mutex_enter(&osp->os_sync_lock);
2187 	osp->os_failed_reopen = 1;
2188 	mutex_exit(&osp->os_sync_lock);
2189 bailout:
2190 	if (oop != NULL) {
2191 		nfs4_end_open_seqid_sync(oop);
2192 		open_owner_rele(oop);
2193 	}
2194 	if (cr != NULL)
2195 		crfree(cr);
2196 	if (cred_otw != NULL)
2197 		crfree(cred_otw);
2198 }
2199 
2200 /* for . and .. OPENs */
2201 /* ARGSUSED */
2202 static int
2203 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2204 {
2205 	rnode4_t *rp;
2206 	nfs4_ga_res_t gar;
2207 
2208 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2209 
2210 	/*
2211 	 * If close-to-open consistency checking is turned off or
2212 	 * if there is no cached data, we can avoid
2213 	 * the over the wire getattr.  Otherwise, force a
2214 	 * call to the server to get fresh attributes and to
2215 	 * check caches. This is required for close-to-open
2216 	 * consistency.
2217 	 */
2218 	rp = VTOR4(*vpp);
2219 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2220 	    (rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2221 		return (0);
2222 
2223 	gar.n4g_va.va_mask = AT_ALL;
2224 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2225 }
2226 
2227 /*
2228  * CLOSE a file
2229  */
2230 /* ARGSUSED */
2231 static int
2232 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
2233 	caller_context_t *ct)
2234 {
2235 	rnode4_t	*rp;
2236 	int		 error = 0;
2237 	int		 r_error = 0;
2238 	int		 n4error = 0;
2239 	nfs4_error_t	 e = { 0, NFS4_OK, RPC_SUCCESS };
2240 
2241 	/*
2242 	 * Remove client state for this (lockowner, file) pair.
2243 	 * Issue otw v4 call to have the server do the same.
2244 	 */
2245 
2246 	rp = VTOR4(vp);
2247 
2248 	/*
2249 	 * zone_enter(2) prevents processes from changing zones with NFS files
2250 	 * open; if we happen to get here from the wrong zone we can't do
2251 	 * anything over the wire.
2252 	 */
2253 	if (VTOMI4(vp)->mi_zone != nfs_zone()) {
2254 		/*
2255 		 * We could attempt to clean up locks, except we're sure
2256 		 * that the current process didn't acquire any locks on
2257 		 * the file: any attempt to lock a file belong to another zone
2258 		 * will fail, and one can't lock an NFS file and then change
2259 		 * zones, as that fails too.
2260 		 *
2261 		 * Returning an error here is the sane thing to do.  A
2262 		 * subsequent call to VN_RELE() which translates to a
2263 		 * nfs4_inactive() will clean up state: if the zone of the
2264 		 * vnode's origin is still alive and kicking, the inactive
2265 		 * thread will handle the request (from the correct zone), and
2266 		 * everything (minus the OTW close call) should be OK.  If the
2267 		 * zone is going away nfs4_async_inactive() will throw away
2268 		 * delegations, open streams and cached pages inline.
2269 		 */
2270 		return (EIO);
2271 	}
2272 
2273 	/*
2274 	 * If we are using local locking for this filesystem, then
2275 	 * release all of the SYSV style record locks.  Otherwise,
2276 	 * we are doing network locking and we need to release all
2277 	 * of the network locks.  All of the locks held by this
2278 	 * process on this file are released no matter what the
2279 	 * incoming reference count is.
2280 	 */
2281 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK) {
2282 		cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
2283 		cleanshares(vp, ttoproc(curthread)->p_pid);
2284 	} else
2285 		e.error = nfs4_lockrelease(vp, flag, offset, cr);
2286 
2287 	if (e.error)
2288 		return (e.error);
2289 
2290 	if (count > 1)
2291 		return (0);
2292 
2293 	/*
2294 	 * If the file has been `unlinked', then purge the
2295 	 * DNLC so that this vnode will get reycled quicker
2296 	 * and the .nfs* file on the server will get removed.
2297 	 */
2298 	if (rp->r_unldvp != NULL)
2299 		dnlc_purge_vp(vp);
2300 
2301 	/*
2302 	 * If the file was open for write and there are pages,
2303 	 * do a synchronous flush and commit of all of the
2304 	 * dirty and uncommitted pages.
2305 	 */
2306 	ASSERT(!e.error);
2307 	if ((flag & FWRITE) && nfs4_has_pages(vp))
2308 		error = nfs4_putpage_commit(vp, 0, 0, cr);
2309 
2310 	mutex_enter(&rp->r_statelock);
2311 	r_error = rp->r_error;
2312 	rp->r_error = 0;
2313 	mutex_exit(&rp->r_statelock);
2314 
2315 	/*
2316 	 * If this file type is one for which no explicit 'open' was
2317 	 * done, then bail now (ie. no need for protocol 'close'). If
2318 	 * there was an error w/the vm subsystem, return _that_ error,
2319 	 * otherwise, return any errors that may've been reported via
2320 	 * the rnode.
2321 	 */
2322 	if (vp->v_type != VREG)
2323 		return (error ? error : r_error);
2324 
2325 	/*
2326 	 * The sync putpage commit may have failed above, but since
2327 	 * we're working w/a regular file, we need to do the protocol
2328 	 * 'close' (nfs4close_one will figure out if an otw close is
2329 	 * needed or not). Report any errors _after_ doing the protocol
2330 	 * 'close'.
2331 	 */
2332 	nfs4close_one(vp, NULL, cr, flag, NULL, &e, CLOSE_NORM, 0, 0, 0);
2333 	n4error = e.error ? e.error : geterrno4(e.stat);
2334 
2335 	/*
2336 	 * Error reporting prio (Hi -> Lo)
2337 	 *
2338 	 *   i) nfs4_putpage_commit (error)
2339 	 *  ii) rnode's (r_error)
2340 	 * iii) nfs4close_one (n4error)
2341 	 */
2342 	return (error ? error : (r_error ? r_error : n4error));
2343 }
2344 
2345 /*
2346  * Initialize *lost_rqstp.
2347  */
2348 
2349 static void
2350 nfs4close_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
2351     nfs4_open_owner_t *oop, nfs4_open_stream_t *osp, cred_t *cr,
2352     vnode_t *vp)
2353 {
2354 	if (error != ETIMEDOUT && error != EINTR &&
2355 	    !NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
2356 		lost_rqstp->lr_op = 0;
2357 		return;
2358 	}
2359 
2360 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
2361 	    "nfs4close_save_lost_rqst: error %d", error));
2362 
2363 	lost_rqstp->lr_op = OP_CLOSE;
2364 	/*
2365 	 * The vp is held and rele'd via the recovery code.
2366 	 * See nfs4_save_lost_rqst.
2367 	 */
2368 	lost_rqstp->lr_vp = vp;
2369 	lost_rqstp->lr_dvp = NULL;
2370 	lost_rqstp->lr_oop = oop;
2371 	lost_rqstp->lr_osp = osp;
2372 	ASSERT(osp != NULL);
2373 	ASSERT(mutex_owned(&osp->os_sync_lock));
2374 	osp->os_pending_close = 1;
2375 	lost_rqstp->lr_lop = NULL;
2376 	lost_rqstp->lr_cr = cr;
2377 	lost_rqstp->lr_flk = NULL;
2378 	lost_rqstp->lr_putfirst = FALSE;
2379 }
2380 
2381 /*
2382  * Assumes you already have the open seqid sync grabbed as well as the
2383  * 'os_sync_lock'.  Note: this will release the open seqid sync and
2384  * 'os_sync_lock' if client recovery starts.  Calling functions have to
2385  * be prepared to handle this.
2386  *
2387  * 'recov' is returned as 1 if the CLOSE operation detected client recovery
2388  * was needed and was started, and that the calling function should retry
2389  * this function; otherwise it is returned as 0.
2390  *
2391  * Errors are returned via the nfs4_error_t parameter.
2392  */
2393 static void
2394 nfs4close_otw(rnode4_t *rp, cred_t *cred_otw, nfs4_open_owner_t *oop,
2395     nfs4_open_stream_t *osp, int *recov, int *did_start_seqid_syncp,
2396     nfs4_close_type_t close_type, nfs4_error_t *ep, int *have_sync_lockp)
2397 {
2398 	COMPOUND4args_clnt args;
2399 	COMPOUND4res_clnt res;
2400 	CLOSE4args *close_args;
2401 	nfs_resop4 *resop;
2402 	nfs_argop4 argop[3];
2403 	int doqueue = 1;
2404 	mntinfo4_t *mi;
2405 	seqid4 seqid;
2406 	vnode_t *vp;
2407 	bool_t needrecov = FALSE;
2408 	nfs4_lost_rqst_t lost_rqst;
2409 	hrtime_t t;
2410 
2411 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
2412 
2413 	ASSERT(MUTEX_HELD(&osp->os_sync_lock));
2414 
2415 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw"));
2416 
2417 	/* Only set this to 1 if recovery is started */
2418 	*recov = 0;
2419 
2420 	/* do the OTW call to close the file */
2421 
2422 	if (close_type == CLOSE_RESEND)
2423 		args.ctag = TAG_CLOSE_LOST;
2424 	else if (close_type == CLOSE_AFTER_RESEND)
2425 		args.ctag = TAG_CLOSE_UNDO;
2426 	else
2427 		args.ctag = TAG_CLOSE;
2428 
2429 	args.array_len = 3;
2430 	args.array = argop;
2431 
2432 	vp = RTOV4(rp);
2433 
2434 	mi = VTOMI4(vp);
2435 
2436 	/* putfh target fh */
2437 	argop[0].argop = OP_CPUTFH;
2438 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
2439 
2440 	argop[1].argop = OP_GETATTR;
2441 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
2442 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
2443 
2444 	argop[2].argop = OP_CLOSE;
2445 	close_args = &argop[2].nfs_argop4_u.opclose;
2446 
2447 	seqid = nfs4_get_open_seqid(oop) + 1;
2448 
2449 	close_args->seqid = seqid;
2450 	close_args->open_stateid = osp->open_stateid;
2451 
2452 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
2453 	    "nfs4close_otw: %s call, rp %s", needrecov ? "recov" : "first",
2454 	    rnode4info(rp)));
2455 
2456 	t = gethrtime();
2457 
2458 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
2459 
2460 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
2461 		nfs4_set_open_seqid(seqid, oop, args.ctag);
2462 	}
2463 
2464 	needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
2465 	if (ep->error && !needrecov) {
2466 		/*
2467 		 * if there was an error and no recovery is to be done
2468 		 * then then set up the file to flush its cache if
2469 		 * needed for the next caller.
2470 		 */
2471 		mutex_enter(&rp->r_statelock);
2472 		PURGE_ATTRCACHE4_LOCKED(rp);
2473 		rp->r_flags &= ~R4WRITEMODIFIED;
2474 		mutex_exit(&rp->r_statelock);
2475 		return;
2476 	}
2477 
2478 	if (needrecov) {
2479 		bool_t abort;
2480 		nfs4_bseqid_entry_t *bsep = NULL;
2481 
2482 		if (close_type != CLOSE_RESEND)
2483 			nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
2484 			    osp, cred_otw, vp);
2485 
2486 		if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
2487 			bsep = nfs4_create_bseqid_entry(oop, NULL, vp,
2488 			    0, args.ctag, close_args->seqid);
2489 
2490 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
2491 		    "nfs4close_otw: initiating recovery. error %d "
2492 		    "res.status %d", ep->error, res.status));
2493 
2494 		/*
2495 		 * Drop the 'os_sync_lock' here so we don't hit
2496 		 * a potential recursive mutex_enter via an
2497 		 * 'open_stream_hold()'.
2498 		 */
2499 		mutex_exit(&osp->os_sync_lock);
2500 		*have_sync_lockp = 0;
2501 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
2502 		    (close_type != CLOSE_RESEND &&
2503 		    lost_rqst.lr_op == OP_CLOSE) ? &lost_rqst : NULL,
2504 		    OP_CLOSE, bsep);
2505 
2506 		/* drop open seq sync, and let the calling function regrab it */
2507 		nfs4_end_open_seqid_sync(oop);
2508 		*did_start_seqid_syncp = 0;
2509 
2510 		if (bsep)
2511 			kmem_free(bsep, sizeof (*bsep));
2512 		/*
2513 		 * For signals, the caller wants to quit, so don't say to
2514 		 * retry.  For forced unmount, if it's a user thread, it
2515 		 * wants to quit.  If it's a recovery thread, the retry
2516 		 * will happen higher-up on the call stack.  Either way,
2517 		 * don't say to retry.
2518 		 */
2519 		if (abort == FALSE && ep->error != EINTR &&
2520 		    !NFS4_FRC_UNMT_ERR(ep->error, mi->mi_vfsp) &&
2521 		    close_type != CLOSE_RESEND &&
2522 		    close_type != CLOSE_AFTER_RESEND)
2523 			*recov = 1;
2524 		else
2525 			*recov = 0;
2526 
2527 		if (!ep->error)
2528 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2529 		return;
2530 	}
2531 
2532 	if (res.status) {
2533 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2534 		return;
2535 	}
2536 
2537 	mutex_enter(&rp->r_statev4_lock);
2538 	rp->created_v4 = 0;
2539 	mutex_exit(&rp->r_statev4_lock);
2540 
2541 	resop = &res.array[2];
2542 	osp->open_stateid = resop->nfs_resop4_u.opclose.open_stateid;
2543 	osp->os_valid = 0;
2544 
2545 	/*
2546 	 * This removes the reference obtained at OPEN; ie, when the
2547 	 * open stream structure was created.
2548 	 *
2549 	 * We don't have to worry about calling 'open_stream_rele'
2550 	 * since we our currently holding a reference to the open
2551 	 * stream which means the count cannot go to 0 with this
2552 	 * decrement.
2553 	 */
2554 	ASSERT(osp->os_ref_count >= 2);
2555 	osp->os_ref_count--;
2556 
2557 	if (!ep->error)
2558 		nfs4_attr_cache(vp,
2559 		    &res.array[1].nfs_resop4_u.opgetattr.ga_res,
2560 		    t, cred_otw, TRUE, NULL);
2561 
2562 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw:"
2563 	    " returning %d", ep->error));
2564 
2565 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2566 }
2567 
2568 /* ARGSUSED */
2569 static int
2570 nfs4_read(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2571     caller_context_t *ct)
2572 {
2573 	rnode4_t *rp;
2574 	u_offset_t off;
2575 	offset_t diff;
2576 	uint_t on;
2577 	uint_t n;
2578 	caddr_t base;
2579 	uint_t flags;
2580 	int error;
2581 	mntinfo4_t *mi;
2582 
2583 	rp = VTOR4(vp);
2584 
2585 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2586 
2587 	if (IS_SHADOW(vp, rp))
2588 		vp = RTOV4(rp);
2589 
2590 	if (vp->v_type != VREG)
2591 		return (EISDIR);
2592 
2593 	mi = VTOMI4(vp);
2594 
2595 	if (nfs_zone() != mi->mi_zone)
2596 		return (EIO);
2597 
2598 	if (uiop->uio_resid == 0)
2599 		return (0);
2600 
2601 	if (uiop->uio_loffset < 0 || uiop->uio_loffset + uiop->uio_resid < 0)
2602 		return (EINVAL);
2603 
2604 	mutex_enter(&rp->r_statelock);
2605 	if (rp->r_flags & R4RECOVERRP)
2606 		error = (rp->r_error ? rp->r_error : EIO);
2607 	else
2608 		error = 0;
2609 	mutex_exit(&rp->r_statelock);
2610 	if (error)
2611 		return (error);
2612 
2613 	/*
2614 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2615 	 * using client-side direct I/O and the file is not mmap'd and
2616 	 * there are no cached pages.
2617 	 */
2618 	if ((vp->v_flag & VNOCACHE) ||
2619 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2620 	    rp->r_mapcnt == 0 && !nfs4_has_pages(vp))) {
2621 		size_t resid = 0;
2622 
2623 		return (nfs4read(vp, NULL, uiop->uio_loffset,
2624 		    uiop->uio_resid, &resid, cr, FALSE, uiop));
2625 	}
2626 
2627 	error = 0;
2628 
2629 	do {
2630 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2631 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2632 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2633 
2634 		if (error = nfs4_validate_caches(vp, cr))
2635 			break;
2636 
2637 		mutex_enter(&rp->r_statelock);
2638 		while (rp->r_flags & R4INCACHEPURGE) {
2639 			if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2640 				mutex_exit(&rp->r_statelock);
2641 				return (EINTR);
2642 			}
2643 		}
2644 		diff = rp->r_size - uiop->uio_loffset;
2645 		mutex_exit(&rp->r_statelock);
2646 		if (diff <= 0)
2647 			break;
2648 		if (diff < n)
2649 			n = (uint_t)diff;
2650 
2651 		if (vpm_enable) {
2652 			/*
2653 			 * Copy data.
2654 			 */
2655 			error = vpm_data_copy(vp, off + on, n, uiop,
2656 			    1, NULL, 0, S_READ);
2657 		} else {
2658 			base = segmap_getmapflt(segkmap, vp, off + on, n, 1,
2659 			    S_READ);
2660 
2661 			error = uiomove(base + on, n, UIO_READ, uiop);
2662 		}
2663 
2664 		if (!error) {
2665 			/*
2666 			 * If read a whole block or read to eof,
2667 			 * won't need this buffer again soon.
2668 			 */
2669 			mutex_enter(&rp->r_statelock);
2670 			if (n + on == MAXBSIZE ||
2671 			    uiop->uio_loffset == rp->r_size)
2672 				flags = SM_DONTNEED;
2673 			else
2674 				flags = 0;
2675 			mutex_exit(&rp->r_statelock);
2676 			if (vpm_enable) {
2677 				error = vpm_sync_pages(vp, off, n, flags);
2678 			} else {
2679 				error = segmap_release(segkmap, base, flags);
2680 			}
2681 		} else {
2682 			if (vpm_enable) {
2683 				(void) vpm_sync_pages(vp, off, n, 0);
2684 			} else {
2685 				(void) segmap_release(segkmap, base, 0);
2686 			}
2687 		}
2688 	} while (!error && uiop->uio_resid > 0);
2689 
2690 	return (error);
2691 }
2692 
2693 /* ARGSUSED */
2694 static int
2695 nfs4_write(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2696     caller_context_t *ct)
2697 {
2698 	rlim64_t limit = uiop->uio_llimit;
2699 	rnode4_t *rp;
2700 	u_offset_t off;
2701 	caddr_t base;
2702 	uint_t flags;
2703 	int remainder;
2704 	size_t n;
2705 	int on;
2706 	int error;
2707 	int resid;
2708 	u_offset_t offset;
2709 	mntinfo4_t *mi;
2710 	uint_t bsize;
2711 
2712 	rp = VTOR4(vp);
2713 
2714 	if (IS_SHADOW(vp, rp))
2715 		vp = RTOV4(rp);
2716 
2717 	if (vp->v_type != VREG)
2718 		return (EISDIR);
2719 
2720 	mi = VTOMI4(vp);
2721 
2722 	if (nfs_zone() != mi->mi_zone)
2723 		return (EIO);
2724 
2725 	if (uiop->uio_resid == 0)
2726 		return (0);
2727 
2728 	mutex_enter(&rp->r_statelock);
2729 	if (rp->r_flags & R4RECOVERRP)
2730 		error = (rp->r_error ? rp->r_error : EIO);
2731 	else
2732 		error = 0;
2733 	mutex_exit(&rp->r_statelock);
2734 	if (error)
2735 		return (error);
2736 
2737 	if (ioflag & FAPPEND) {
2738 		struct vattr va;
2739 
2740 		/*
2741 		 * Must serialize if appending.
2742 		 */
2743 		if (nfs_rw_lock_held(&rp->r_rwlock, RW_READER)) {
2744 			nfs_rw_exit(&rp->r_rwlock);
2745 			if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER,
2746 			    INTR(vp)))
2747 				return (EINTR);
2748 		}
2749 
2750 		va.va_mask = AT_SIZE;
2751 		error = nfs4getattr(vp, &va, cr);
2752 		if (error)
2753 			return (error);
2754 		uiop->uio_loffset = va.va_size;
2755 	}
2756 
2757 	offset = uiop->uio_loffset + uiop->uio_resid;
2758 
2759 	if (uiop->uio_loffset < (offset_t)0 || offset < 0)
2760 		return (EINVAL);
2761 
2762 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
2763 		limit = MAXOFFSET_T;
2764 
2765 	/*
2766 	 * Check to make sure that the process will not exceed
2767 	 * its limit on file size.  It is okay to write up to
2768 	 * the limit, but not beyond.  Thus, the write which
2769 	 * reaches the limit will be short and the next write
2770 	 * will return an error.
2771 	 */
2772 	remainder = 0;
2773 	if (offset > uiop->uio_llimit) {
2774 		remainder = offset - uiop->uio_llimit;
2775 		uiop->uio_resid = uiop->uio_llimit - uiop->uio_loffset;
2776 		if (uiop->uio_resid <= 0) {
2777 			proc_t *p = ttoproc(curthread);
2778 
2779 			uiop->uio_resid += remainder;
2780 			mutex_enter(&p->p_lock);
2781 			(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE],
2782 			    p->p_rctls, p, RCA_UNSAFE_SIGINFO);
2783 			mutex_exit(&p->p_lock);
2784 			return (EFBIG);
2785 		}
2786 	}
2787 
2788 	/* update the change attribute, if we have a write delegation */
2789 
2790 	mutex_enter(&rp->r_statev4_lock);
2791 	if (rp->r_deleg_type == OPEN_DELEGATE_WRITE)
2792 		rp->r_deleg_change++;
2793 
2794 	mutex_exit(&rp->r_statev4_lock);
2795 
2796 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
2797 		return (EINTR);
2798 
2799 	/*
2800 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2801 	 * using client-side direct I/O and the file is not mmap'd and
2802 	 * there are no cached pages.
2803 	 */
2804 	if ((vp->v_flag & VNOCACHE) ||
2805 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2806 	    rp->r_mapcnt == 0 && !nfs4_has_pages(vp))) {
2807 		size_t bufsize;
2808 		int count;
2809 		u_offset_t org_offset;
2810 		stable_how4 stab_comm;
2811 nfs4_fwrite:
2812 		if (rp->r_flags & R4STALE) {
2813 			resid = uiop->uio_resid;
2814 			offset = uiop->uio_loffset;
2815 			error = rp->r_error;
2816 			goto bottom;
2817 		}
2818 
2819 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2820 		base = kmem_alloc(bufsize, KM_SLEEP);
2821 		do {
2822 			if (ioflag & FDSYNC)
2823 				stab_comm = DATA_SYNC4;
2824 			else
2825 				stab_comm = FILE_SYNC4;
2826 			resid = uiop->uio_resid;
2827 			offset = uiop->uio_loffset;
2828 			count = MIN(uiop->uio_resid, bufsize);
2829 			org_offset = uiop->uio_loffset;
2830 			error = uiomove(base, count, UIO_WRITE, uiop);
2831 			if (!error) {
2832 				error = nfs4write(vp, base, org_offset,
2833 				    count, cr, &stab_comm);
2834 				if (!error) {
2835 					mutex_enter(&rp->r_statelock);
2836 					if (rp->r_size < uiop->uio_loffset)
2837 						rp->r_size = uiop->uio_loffset;
2838 					mutex_exit(&rp->r_statelock);
2839 				}
2840 			}
2841 		} while (!error && uiop->uio_resid > 0);
2842 		kmem_free(base, bufsize);
2843 		goto bottom;
2844 	}
2845 
2846 	bsize = vp->v_vfsp->vfs_bsize;
2847 
2848 	do {
2849 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2850 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2851 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2852 
2853 		resid = uiop->uio_resid;
2854 		offset = uiop->uio_loffset;
2855 
2856 		if (rp->r_flags & R4STALE) {
2857 			error = rp->r_error;
2858 			break;
2859 		}
2860 
2861 		/*
2862 		 * Don't create dirty pages faster than they
2863 		 * can be cleaned so that the system doesn't
2864 		 * get imbalanced.  If the async queue is
2865 		 * maxed out, then wait for it to drain before
2866 		 * creating more dirty pages.  Also, wait for
2867 		 * any threads doing pagewalks in the vop_getattr
2868 		 * entry points so that they don't block for
2869 		 * long periods.
2870 		 */
2871 		mutex_enter(&rp->r_statelock);
2872 		while ((mi->mi_max_threads != 0 &&
2873 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2874 		    rp->r_gcount > 0)
2875 			cv_wait(&rp->r_cv, &rp->r_statelock);
2876 		mutex_exit(&rp->r_statelock);
2877 
2878 		if (vpm_enable) {
2879 			/*
2880 			 * It will use kpm mappings, so no need to
2881 			 * pass an address.
2882 			 */
2883 			error = writerp4(rp, NULL, n, uiop, 0);
2884 		} else  {
2885 			if (segmap_kpm) {
2886 				int pon = uiop->uio_loffset & PAGEOFFSET;
2887 				size_t pn = MIN(PAGESIZE - pon,
2888 				    uiop->uio_resid);
2889 				int pagecreate;
2890 
2891 				mutex_enter(&rp->r_statelock);
2892 				pagecreate = (pon == 0) && (pn == PAGESIZE ||
2893 				    uiop->uio_loffset + pn >= rp->r_size);
2894 				mutex_exit(&rp->r_statelock);
2895 
2896 				base = segmap_getmapflt(segkmap, vp, off + on,
2897 				    pn, !pagecreate, S_WRITE);
2898 
2899 				error = writerp4(rp, base + pon, n, uiop,
2900 				    pagecreate);
2901 
2902 			} else {
2903 				base = segmap_getmapflt(segkmap, vp, off + on,
2904 				    n, 0, S_READ);
2905 				error = writerp4(rp, base + on, n, uiop, 0);
2906 			}
2907 		}
2908 
2909 		if (!error) {
2910 			if (mi->mi_flags & MI4_NOAC)
2911 				flags = SM_WRITE;
2912 			else if ((uiop->uio_loffset % bsize) == 0 ||
2913 			    IS_SWAPVP(vp)) {
2914 				/*
2915 				 * Have written a whole block.
2916 				 * Start an asynchronous write
2917 				 * and mark the buffer to
2918 				 * indicate that it won't be
2919 				 * needed again soon.
2920 				 */
2921 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
2922 			} else
2923 				flags = 0;
2924 			if ((ioflag & (FSYNC|FDSYNC)) ||
2925 			    (rp->r_flags & R4OUTOFSPACE)) {
2926 				flags &= ~SM_ASYNC;
2927 				flags |= SM_WRITE;
2928 			}
2929 			if (vpm_enable) {
2930 				error = vpm_sync_pages(vp, off, n, flags);
2931 			} else {
2932 				error = segmap_release(segkmap, base, flags);
2933 			}
2934 		} else {
2935 			if (vpm_enable) {
2936 				(void) vpm_sync_pages(vp, off, n, 0);
2937 			} else {
2938 				(void) segmap_release(segkmap, base, 0);
2939 			}
2940 			/*
2941 			 * In the event that we got an access error while
2942 			 * faulting in a page for a write-only file just
2943 			 * force a write.
2944 			 */
2945 			if (error == EACCES)
2946 				goto nfs4_fwrite;
2947 		}
2948 	} while (!error && uiop->uio_resid > 0);
2949 
2950 bottom:
2951 	if (error) {
2952 		uiop->uio_resid = resid + remainder;
2953 		uiop->uio_loffset = offset;
2954 	} else {
2955 		uiop->uio_resid += remainder;
2956 
2957 		mutex_enter(&rp->r_statev4_lock);
2958 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
2959 			gethrestime(&rp->r_attr.va_mtime);
2960 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
2961 		}
2962 		mutex_exit(&rp->r_statev4_lock);
2963 	}
2964 
2965 	nfs_rw_exit(&rp->r_lkserlock);
2966 
2967 	return (error);
2968 }
2969 
2970 /*
2971  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
2972  */
2973 static int
2974 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
2975     int flags, cred_t *cr)
2976 {
2977 	struct buf *bp;
2978 	int error;
2979 	page_t *savepp;
2980 	uchar_t fsdata;
2981 	stable_how4 stab_comm;
2982 
2983 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
2984 	bp = pageio_setup(pp, len, vp, flags);
2985 	ASSERT(bp != NULL);
2986 
2987 	/*
2988 	 * pageio_setup should have set b_addr to 0.  This
2989 	 * is correct since we want to do I/O on a page
2990 	 * boundary.  bp_mapin will use this addr to calculate
2991 	 * an offset, and then set b_addr to the kernel virtual
2992 	 * address it allocated for us.
2993 	 */
2994 	ASSERT(bp->b_un.b_addr == 0);
2995 
2996 	bp->b_edev = 0;
2997 	bp->b_dev = 0;
2998 	bp->b_lblkno = lbtodb(off);
2999 	bp->b_file = vp;
3000 	bp->b_offset = (offset_t)off;
3001 	bp_mapin(bp);
3002 
3003 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
3004 	    freemem > desfree)
3005 		stab_comm = UNSTABLE4;
3006 	else
3007 		stab_comm = FILE_SYNC4;
3008 
3009 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
3010 
3011 	bp_mapout(bp);
3012 	pageio_done(bp);
3013 
3014 	if (stab_comm == UNSTABLE4)
3015 		fsdata = C_DELAYCOMMIT;
3016 	else
3017 		fsdata = C_NOCOMMIT;
3018 
3019 	savepp = pp;
3020 	do {
3021 		pp->p_fsdata = fsdata;
3022 	} while ((pp = pp->p_next) != savepp);
3023 
3024 	return (error);
3025 }
3026 
3027 /*
3028  */
3029 static int
3030 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
3031 {
3032 	nfs4_open_owner_t	*oop;
3033 	nfs4_open_stream_t	*osp;
3034 	rnode4_t		*rp = VTOR4(vp);
3035 	mntinfo4_t 		*mi = VTOMI4(vp);
3036 	int 			reopen_needed;
3037 
3038 	ASSERT(nfs_zone() == mi->mi_zone);
3039 
3040 
3041 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
3042 	if (!oop)
3043 		return (EIO);
3044 
3045 	/* returns with 'os_sync_lock' held */
3046 	osp = find_open_stream(oop, rp);
3047 	if (!osp) {
3048 		open_owner_rele(oop);
3049 		return (EIO);
3050 	}
3051 
3052 	if (osp->os_failed_reopen) {
3053 		mutex_exit(&osp->os_sync_lock);
3054 		open_stream_rele(osp, rp);
3055 		open_owner_rele(oop);
3056 		return (EIO);
3057 	}
3058 
3059 	/*
3060 	 * Determine whether a reopen is needed.  If this
3061 	 * is a delegation open stream, then the os_delegation bit
3062 	 * should be set.
3063 	 */
3064 
3065 	reopen_needed = osp->os_delegation;
3066 
3067 	mutex_exit(&osp->os_sync_lock);
3068 	open_owner_rele(oop);
3069 
3070 	if (reopen_needed) {
3071 		nfs4_error_zinit(ep);
3072 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
3073 		mutex_enter(&osp->os_sync_lock);
3074 		if (ep->error || ep->stat || osp->os_failed_reopen) {
3075 			mutex_exit(&osp->os_sync_lock);
3076 			open_stream_rele(osp, rp);
3077 			return (EIO);
3078 		}
3079 		mutex_exit(&osp->os_sync_lock);
3080 	}
3081 	open_stream_rele(osp, rp);
3082 
3083 	return (0);
3084 }
3085 
3086 /*
3087  * Write to file.  Writes to remote server in largest size
3088  * chunks that the server can handle.  Write is synchronous.
3089  */
3090 static int
3091 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3092     stable_how4 *stab_comm)
3093 {
3094 	mntinfo4_t *mi;
3095 	COMPOUND4args_clnt args;
3096 	COMPOUND4res_clnt res;
3097 	WRITE4args *wargs;
3098 	WRITE4res *wres;
3099 	nfs_argop4 argop[2];
3100 	nfs_resop4 *resop;
3101 	int tsize;
3102 	stable_how4 stable;
3103 	rnode4_t *rp;
3104 	int doqueue = 1;
3105 	bool_t needrecov;
3106 	nfs4_recov_state_t recov_state;
3107 	nfs4_stateid_types_t sid_types;
3108 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3109 
3110 	rp = VTOR4(vp);
3111 	mi = VTOMI4(vp);
3112 
3113 	ASSERT(nfs_zone() == mi->mi_zone);
3114 
3115 	stable = *stab_comm;
3116 	*stab_comm = FILE_SYNC4;
3117 
3118 	needrecov = FALSE;
3119 	recov_state.rs_flags = 0;
3120 	recov_state.rs_num_retry_despite_err = 0;
3121 	nfs4_init_stateid_types(&sid_types);
3122 
3123 recov_retry:
3124 	args.ctag = TAG_WRITE;
3125 	args.array_len = 2;
3126 	args.array = argop;
3127 
3128 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3129 	    &recov_state, NULL);
3130 	if (e.error)
3131 		return (e.error);
3132 
3133 	/* 0. putfh target fh */
3134 	argop[0].argop = OP_CPUTFH;
3135 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3136 
3137 	/* 1. write */
3138 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3139 
3140 	do {
3141 
3142 		wargs->offset = (offset4)offset;
3143 		wargs->data_val = base;
3144 
3145 		if (mi->mi_io_kstats) {
3146 			mutex_enter(&mi->mi_lock);
3147 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3148 			mutex_exit(&mi->mi_lock);
3149 		}
3150 
3151 		if ((vp->v_flag & VNOCACHE) ||
3152 		    (rp->r_flags & R4DIRECTIO) ||
3153 		    (mi->mi_flags & MI4_DIRECTIO))
3154 			tsize = MIN(mi->mi_stsize, count);
3155 		else
3156 			tsize = MIN(mi->mi_curwrite, count);
3157 		wargs->data_len = (uint_t)tsize;
3158 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3159 
3160 		if (mi->mi_io_kstats) {
3161 			mutex_enter(&mi->mi_lock);
3162 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3163 			mutex_exit(&mi->mi_lock);
3164 		}
3165 
3166 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3167 		if (e.error && !needrecov) {
3168 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3169 			    &recov_state, needrecov);
3170 			return (e.error);
3171 		}
3172 
3173 
3174 		/*
3175 		 * Do handling of OLD_STATEID outside
3176 		 * of the normal recovery framework.
3177 		 *
3178 		 * If write receives a BAD stateid error while using a
3179 		 * delegation stateid, retry using the open stateid (if it
3180 		 * exists).  If it doesn't have an open stateid, reopen the
3181 		 * file first, then retry.
3182 		 */
3183 		if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3184 		    sid_types.cur_sid_type != SPEC_SID) {
3185 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3186 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3187 			    &recov_state, needrecov);
3188 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3189 			goto recov_retry;
3190 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3191 		    sid_types.cur_sid_type == DEL_SID) {
3192 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3193 			mutex_enter(&rp->r_statev4_lock);
3194 			rp->r_deleg_return_pending = TRUE;
3195 			mutex_exit(&rp->r_statev4_lock);
3196 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3197 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3198 				    &recov_state, needrecov);
3199 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3200 				    (caddr_t)&res);
3201 				return (EIO);
3202 			}
3203 			nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3204 			    &recov_state, needrecov);
3205 			/* hold needed for nfs4delegreturn_thread */
3206 			VN_HOLD(vp);
3207 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3208 			    NFS4_DR_DISCARD), FALSE);
3209 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3210 			goto recov_retry;
3211 		}
3212 
3213 		if (needrecov) {
3214 			bool_t abort;
3215 
3216 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3217 			    "nfs4write: client got error %d, res.status %d"
3218 			    ", so start recovery", e.error, res.status));
3219 
3220 			abort = nfs4_start_recovery(&e,
3221 			    VTOMI4(vp), vp, NULL, &wargs->stateid,
3222 			    NULL, OP_WRITE, NULL);
3223 			if (!e.error) {
3224 				e.error = geterrno4(res.status);
3225 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3226 				    (caddr_t)&res);
3227 			}
3228 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3229 			    &recov_state, needrecov);
3230 			if (abort == FALSE)
3231 				goto recov_retry;
3232 			return (e.error);
3233 		}
3234 
3235 		if (res.status) {
3236 			e.error = geterrno4(res.status);
3237 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3238 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3239 			    &recov_state, needrecov);
3240 			return (e.error);
3241 		}
3242 
3243 		resop = &res.array[1];	/* write res */
3244 		wres = &resop->nfs_resop4_u.opwrite;
3245 
3246 		if ((int)wres->count > tsize) {
3247 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3248 
3249 			zcmn_err(getzoneid(), CE_WARN,
3250 			    "nfs4write: server wrote %u, requested was %u",
3251 			    (int)wres->count, tsize);
3252 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3253 			    &recov_state, needrecov);
3254 			return (EIO);
3255 		}
3256 		if (wres->committed == UNSTABLE4) {
3257 			*stab_comm = UNSTABLE4;
3258 			if (wargs->stable == DATA_SYNC4 ||
3259 			    wargs->stable == FILE_SYNC4) {
3260 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3261 				    (caddr_t)&res);
3262 				zcmn_err(getzoneid(), CE_WARN,
3263 				    "nfs4write: server %s did not commit "
3264 				    "to stable storage",
3265 				    rp->r_server->sv_hostname);
3266 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3267 				    &recov_state, needrecov);
3268 				return (EIO);
3269 			}
3270 		}
3271 
3272 		tsize = (int)wres->count;
3273 		count -= tsize;
3274 		base += tsize;
3275 		offset += tsize;
3276 		if (mi->mi_io_kstats) {
3277 			mutex_enter(&mi->mi_lock);
3278 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3279 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3280 			    tsize;
3281 			mutex_exit(&mi->mi_lock);
3282 		}
3283 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3284 		mutex_enter(&rp->r_statelock);
3285 		if (rp->r_flags & R4HAVEVERF) {
3286 			if (rp->r_writeverf != wres->writeverf) {
3287 				nfs4_set_mod(vp);
3288 				rp->r_writeverf = wres->writeverf;
3289 			}
3290 		} else {
3291 			rp->r_writeverf = wres->writeverf;
3292 			rp->r_flags |= R4HAVEVERF;
3293 		}
3294 		PURGE_ATTRCACHE4_LOCKED(rp);
3295 		rp->r_flags |= R4WRITEMODIFIED;
3296 		gethrestime(&rp->r_attr.va_mtime);
3297 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3298 		mutex_exit(&rp->r_statelock);
3299 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3300 	} while (count);
3301 
3302 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state, needrecov);
3303 
3304 	return (e.error);
3305 }
3306 
3307 /*
3308  * Read from a file.  Reads data in largest chunks our interface can handle.
3309  */
3310 static int
3311 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3312     size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3313 {
3314 	mntinfo4_t *mi;
3315 	COMPOUND4args_clnt args;
3316 	COMPOUND4res_clnt res;
3317 	READ4args *rargs;
3318 	nfs_argop4 argop[2];
3319 	int tsize;
3320 	int doqueue;
3321 	rnode4_t *rp;
3322 	int data_len;
3323 	bool_t is_eof;
3324 	bool_t needrecov = FALSE;
3325 	nfs4_recov_state_t recov_state;
3326 	nfs4_stateid_types_t sid_types;
3327 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3328 
3329 	rp = VTOR4(vp);
3330 	mi = VTOMI4(vp);
3331 	doqueue = 1;
3332 
3333 	ASSERT(nfs_zone() == mi->mi_zone);
3334 
3335 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3336 
3337 	args.array_len = 2;
3338 	args.array = argop;
3339 
3340 	nfs4_init_stateid_types(&sid_types);
3341 
3342 	recov_state.rs_flags = 0;
3343 	recov_state.rs_num_retry_despite_err = 0;
3344 
3345 recov_retry:
3346 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3347 	    &recov_state, NULL);
3348 	if (e.error)
3349 		return (e.error);
3350 
3351 	/* putfh target fh */
3352 	argop[0].argop = OP_CPUTFH;
3353 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3354 
3355 	/* read */
3356 	argop[1].argop = OP_READ;
3357 	rargs = &argop[1].nfs_argop4_u.opread;
3358 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3359 	    OP_READ, &sid_types, async);
3360 
3361 	do {
3362 		if (mi->mi_io_kstats) {
3363 			mutex_enter(&mi->mi_lock);
3364 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3365 			mutex_exit(&mi->mi_lock);
3366 		}
3367 
3368 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3369 		    "nfs4read: %s call, rp %s",
3370 		    needrecov ? "recov" : "first",
3371 		    rnode4info(rp)));
3372 
3373 		if ((vp->v_flag & VNOCACHE) ||
3374 		    (rp->r_flags & R4DIRECTIO) ||
3375 		    (mi->mi_flags & MI4_DIRECTIO))
3376 			tsize = MIN(mi->mi_tsize, count);
3377 		else
3378 			tsize = MIN(mi->mi_curread, count);
3379 		rargs->offset = (offset4)offset;
3380 		rargs->count = (count4)tsize;
3381 		rargs->res_data_val_alt = NULL;
3382 		rargs->res_mblk = NULL;
3383 		rargs->res_uiop = NULL;
3384 		rargs->res_maxsize = 0;
3385 		if (uiop)
3386 			rargs->res_uiop = uiop;
3387 		else
3388 			rargs->res_data_val_alt = base;
3389 		rargs->res_maxsize = tsize;
3390 
3391 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3392 #ifdef	DEBUG
3393 		if (nfs4read_error_inject) {
3394 			res.status = nfs4read_error_inject;
3395 			nfs4read_error_inject = 0;
3396 		}
3397 #endif
3398 
3399 		if (mi->mi_io_kstats) {
3400 			mutex_enter(&mi->mi_lock);
3401 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3402 			mutex_exit(&mi->mi_lock);
3403 		}
3404 
3405 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3406 		if (e.error != 0 && !needrecov) {
3407 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3408 			    &recov_state, needrecov);
3409 			return (e.error);
3410 		}
3411 
3412 		/*
3413 		 * Do proper retry for OLD and BAD stateid errors outside
3414 		 * of the normal recovery framework.  There are two differences
3415 		 * between async and sync reads.  The first is that we allow
3416 		 * retry on BAD_STATEID for async reads, but not sync reads.
3417 		 * The second is that we mark the file dead for a failed
3418 		 * attempt with a special stateid for sync reads, but just
3419 		 * return EIO for async reads.
3420 		 *
3421 		 * If a sync read receives a BAD stateid error while using a
3422 		 * delegation stateid, retry using the open stateid (if it
3423 		 * exists).  If it doesn't have an open stateid, reopen the
3424 		 * file first, then retry.
3425 		 */
3426 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3427 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3428 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3429 			    &recov_state, needrecov);
3430 			if (sid_types.cur_sid_type == SPEC_SID) {
3431 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3432 				    (caddr_t)&res);
3433 				return (EIO);
3434 			}
3435 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3436 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3437 			goto recov_retry;
3438 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3439 		    !async && sid_types.cur_sid_type != SPEC_SID) {
3440 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3441 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3442 			    &recov_state, needrecov);
3443 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3444 			goto recov_retry;
3445 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3446 		    sid_types.cur_sid_type == DEL_SID) {
3447 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3448 			mutex_enter(&rp->r_statev4_lock);
3449 			rp->r_deleg_return_pending = TRUE;
3450 			mutex_exit(&rp->r_statev4_lock);
3451 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3452 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3453 				    &recov_state, needrecov);
3454 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3455 				    (caddr_t)&res);
3456 				return (EIO);
3457 			}
3458 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3459 			    &recov_state, needrecov);
3460 			/* hold needed for nfs4delegreturn_thread */
3461 			VN_HOLD(vp);
3462 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3463 			    NFS4_DR_DISCARD), FALSE);
3464 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3465 			goto recov_retry;
3466 		}
3467 		if (needrecov) {
3468 			bool_t abort;
3469 
3470 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3471 			    "nfs4read: initiating recovery\n"));
3472 
3473 			abort = nfs4_start_recovery(&e,
3474 			    mi, vp, NULL, &rargs->stateid,
3475 			    NULL, OP_READ, NULL);
3476 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3477 			    &recov_state, needrecov);
3478 			/*
3479 			 * Do not retry if we got OLD_STATEID using a special
3480 			 * stateid.  This avoids looping with a broken server.
3481 			 */
3482 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3483 			    sid_types.cur_sid_type == SPEC_SID)
3484 				abort = TRUE;
3485 
3486 			if (abort == FALSE) {
3487 				/*
3488 				 * Need to retry all possible stateids in
3489 				 * case the recovery error wasn't stateid
3490 				 * related or the stateids have become
3491 				 * stale (server reboot).
3492 				 */
3493 				nfs4_init_stateid_types(&sid_types);
3494 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3495 				    (caddr_t)&res);
3496 				goto recov_retry;
3497 			}
3498 
3499 			if (!e.error) {
3500 				e.error = geterrno4(res.status);
3501 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3502 				    (caddr_t)&res);
3503 			}
3504 			return (e.error);
3505 		}
3506 
3507 		if (res.status) {
3508 			e.error = geterrno4(res.status);
3509 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3510 			    &recov_state, needrecov);
3511 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3512 			return (e.error);
3513 		}
3514 
3515 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3516 		count -= data_len;
3517 		if (base)
3518 			base += data_len;
3519 		offset += data_len;
3520 		if (mi->mi_io_kstats) {
3521 			mutex_enter(&mi->mi_lock);
3522 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3523 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3524 			mutex_exit(&mi->mi_lock);
3525 		}
3526 		lwp_stat_update(LWP_STAT_INBLK, 1);
3527 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3528 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3529 
3530 	} while (count && !is_eof);
3531 
3532 	*residp = count;
3533 
3534 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3535 
3536 	return (e.error);
3537 }
3538 
3539 /* ARGSUSED */
3540 static int
3541 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp,
3542 	caller_context_t *ct)
3543 {
3544 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3545 		return (EIO);
3546 	switch (cmd) {
3547 		case _FIODIRECTIO:
3548 			return (nfs4_directio(vp, (int)arg, cr));
3549 		default:
3550 			return (ENOTTY);
3551 	}
3552 }
3553 
3554 /* ARGSUSED */
3555 int
3556 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3557     caller_context_t *ct)
3558 {
3559 	int error;
3560 	rnode4_t *rp = VTOR4(vp);
3561 
3562 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3563 		return (EIO);
3564 	/*
3565 	 * If it has been specified that the return value will
3566 	 * just be used as a hint, and we are only being asked
3567 	 * for size, fsid or rdevid, then return the client's
3568 	 * notion of these values without checking to make sure
3569 	 * that the attribute cache is up to date.
3570 	 * The whole point is to avoid an over the wire GETATTR
3571 	 * call.
3572 	 */
3573 	if (flags & ATTR_HINT) {
3574 		if (vap->va_mask ==
3575 		    (vap->va_mask & (AT_SIZE | AT_FSID | AT_RDEV))) {
3576 			mutex_enter(&rp->r_statelock);
3577 			if (vap->va_mask | AT_SIZE)
3578 				vap->va_size = rp->r_size;
3579 			if (vap->va_mask | AT_FSID)
3580 				vap->va_fsid = rp->r_attr.va_fsid;
3581 			if (vap->va_mask | AT_RDEV)
3582 				vap->va_rdev = rp->r_attr.va_rdev;
3583 			mutex_exit(&rp->r_statelock);
3584 			return (0);
3585 		}
3586 	}
3587 
3588 	/*
3589 	 * Only need to flush pages if asking for the mtime
3590 	 * and if there any dirty pages or any outstanding
3591 	 * asynchronous (write) requests for this file.
3592 	 */
3593 	if (vap->va_mask & AT_MTIME) {
3594 		rp = VTOR4(vp);
3595 		if (nfs4_has_pages(vp)) {
3596 			mutex_enter(&rp->r_statev4_lock);
3597 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3598 				mutex_exit(&rp->r_statev4_lock);
3599 				if (rp->r_flags & R4DIRTY ||
3600 				    rp->r_awcount > 0) {
3601 					mutex_enter(&rp->r_statelock);
3602 					rp->r_gcount++;
3603 					mutex_exit(&rp->r_statelock);
3604 					error =
3605 					    nfs4_putpage(vp, (u_offset_t)0,
3606 					    0, 0, cr, NULL);
3607 					mutex_enter(&rp->r_statelock);
3608 					if (error && (error == ENOSPC ||
3609 					    error == EDQUOT)) {
3610 						if (!rp->r_error)
3611 							rp->r_error = error;
3612 					}
3613 					if (--rp->r_gcount == 0)
3614 						cv_broadcast(&rp->r_cv);
3615 					mutex_exit(&rp->r_statelock);
3616 				}
3617 			} else {
3618 				mutex_exit(&rp->r_statev4_lock);
3619 			}
3620 		}
3621 	}
3622 	return (nfs4getattr(vp, vap, cr));
3623 }
3624 
3625 int
3626 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3627 {
3628 	/*
3629 	 * If these are the only two bits cleared
3630 	 * on the server then return 0 (OK) else
3631 	 * return 1 (BAD).
3632 	 */
3633 	on_client &= ~(S_ISUID|S_ISGID);
3634 	if (on_client == from_server)
3635 		return (0);
3636 	else
3637 		return (1);
3638 }
3639 
3640 /*ARGSUSED4*/
3641 static int
3642 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3643     caller_context_t *ct)
3644 {
3645 	if (vap->va_mask & AT_NOSET)
3646 		return (EINVAL);
3647 
3648 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3649 		return (EIO);
3650 
3651 	/*
3652 	 * Don't call secpolicy_vnode_setattr, the client cannot
3653 	 * use its cached attributes to make security decisions
3654 	 * as the server may be faking mode bits or mapping uid/gid.
3655 	 * Always just let the server to the checking.
3656 	 * If we provide the ability to remove basic priviledges
3657 	 * to setattr (e.g. basic without chmod) then we will
3658 	 * need to add a check here before calling the server.
3659 	 */
3660 
3661 	return (nfs4setattr(vp, vap, flags, cr, NULL));
3662 }
3663 
3664 /*
3665  * To replace the "guarded" version 3 setattr, we use two types of compound
3666  * setattr requests:
3667  * 1. The "normal" setattr, used when the size of the file isn't being
3668  *    changed - { Putfh <fh>; Setattr; Getattr }/
3669  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3670  *    with only ctime as the argument. If the server ctime differs from
3671  *    what is cached on the client, the verify will fail, but we would
3672  *    already have the ctime from the preceding getattr, so just set it
3673  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3674  *	Setattr; Getattr }.
3675  *
3676  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3677  * this setattr and NULL if they are not.
3678  */
3679 static int
3680 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3681     vsecattr_t *vsap)
3682 {
3683 	COMPOUND4args_clnt args;
3684 	COMPOUND4res_clnt res, *resp = NULL;
3685 	nfs4_ga_res_t *garp = NULL;
3686 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3687 	nfs_argop4 argop[5];
3688 	int verify_argop = -1;
3689 	int setattr_argop = 1;
3690 	nfs_resop4 *resop;
3691 	vattr_t va;
3692 	rnode4_t *rp;
3693 	int doqueue = 1;
3694 	uint_t mask = vap->va_mask;
3695 	mode_t omode;
3696 	vsecattr_t *vsp;
3697 	timestruc_t ctime;
3698 	bool_t needrecov = FALSE;
3699 	nfs4_recov_state_t recov_state;
3700 	nfs4_stateid_types_t sid_types;
3701 	stateid4 stateid;
3702 	hrtime_t t;
3703 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3704 	servinfo4_t *svp;
3705 	bitmap4 supp_attrs;
3706 
3707 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3708 	rp = VTOR4(vp);
3709 	nfs4_init_stateid_types(&sid_types);
3710 
3711 	/*
3712 	 * Only need to flush pages if there are any pages and
3713 	 * if the file is marked as dirty in some fashion.  The
3714 	 * file must be flushed so that we can accurately
3715 	 * determine the size of the file and the cached data
3716 	 * after the SETATTR returns.  A file is considered to
3717 	 * be dirty if it is either marked with R4DIRTY, has
3718 	 * outstanding i/o's active, or is mmap'd.  In this
3719 	 * last case, we can't tell whether there are dirty
3720 	 * pages, so we flush just to be sure.
3721 	 */
3722 	if (nfs4_has_pages(vp) &&
3723 	    ((rp->r_flags & R4DIRTY) ||
3724 	    rp->r_count > 0 ||
3725 	    rp->r_mapcnt > 0)) {
3726 		ASSERT(vp->v_type != VCHR);
3727 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr, NULL);
3728 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3729 			mutex_enter(&rp->r_statelock);
3730 			if (!rp->r_error)
3731 				rp->r_error = e.error;
3732 			mutex_exit(&rp->r_statelock);
3733 		}
3734 	}
3735 
3736 	if (mask & AT_SIZE) {
3737 		/*
3738 		 * Verification setattr compound for non-deleg AT_SIZE:
3739 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3740 		 * Set ctime local here (outside the do_again label)
3741 		 * so that subsequent retries (after failed VERIFY)
3742 		 * will use ctime from GETATTR results (from failed
3743 		 * verify compound) as VERIFY arg.
3744 		 * If file has delegation, then VERIFY(time_metadata)
3745 		 * is of little added value, so don't bother.
3746 		 */
3747 		mutex_enter(&rp->r_statev4_lock);
3748 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3749 		    rp->r_deleg_return_pending) {
3750 			numops = 5;
3751 			ctime = rp->r_attr.va_ctime;
3752 		}
3753 		mutex_exit(&rp->r_statev4_lock);
3754 	}
3755 
3756 	recov_state.rs_flags = 0;
3757 	recov_state.rs_num_retry_despite_err = 0;
3758 
3759 	args.ctag = TAG_SETATTR;
3760 do_again:
3761 recov_retry:
3762 	setattr_argop = numops - 2;
3763 
3764 	args.array = argop;
3765 	args.array_len = numops;
3766 
3767 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3768 	if (e.error)
3769 		return (e.error);
3770 
3771 
3772 	/* putfh target fh */
3773 	argop[0].argop = OP_CPUTFH;
3774 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3775 
3776 	if (numops == 5) {
3777 		/*
3778 		 * We only care about the ctime, but need to get mtime
3779 		 * and size for proper cache update.
3780 		 */
3781 		/* getattr */
3782 		argop[1].argop = OP_GETATTR;
3783 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3784 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3785 
3786 		/* verify - set later in loop */
3787 		verify_argop = 2;
3788 	}
3789 
3790 	/* setattr */
3791 	svp = rp->r_server;
3792 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3793 	supp_attrs = svp->sv_supp_attrs;
3794 	nfs_rw_exit(&svp->sv_lock);
3795 
3796 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3797 	    supp_attrs, &e.error, &sid_types);
3798 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3799 	if (e.error) {
3800 		/* req time field(s) overflow - return immediately */
3801 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3802 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3803 		    opsetattr.obj_attributes);
3804 		return (e.error);
3805 	}
3806 	omode = rp->r_attr.va_mode;
3807 
3808 	/* getattr */
3809 	argop[numops-1].argop = OP_GETATTR;
3810 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3811 	/*
3812 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3813 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3814 	 * used in updating the ACL cache.
3815 	 */
3816 	if (vsap != NULL)
3817 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3818 		    FATTR4_ACL_MASK;
3819 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3820 
3821 	/*
3822 	 * setattr iterates if the object size is set and the cached ctime
3823 	 * does not match the file ctime. In that case, verify the ctime first.
3824 	 */
3825 
3826 	do {
3827 		if (verify_argop != -1) {
3828 			/*
3829 			 * Verify that the ctime match before doing setattr.
3830 			 */
3831 			va.va_mask = AT_CTIME;
3832 			va.va_ctime = ctime;
3833 			svp = rp->r_server;
3834 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3835 			supp_attrs = svp->sv_supp_attrs;
3836 			nfs_rw_exit(&svp->sv_lock);
3837 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3838 			    OP_VERIFY, supp_attrs);
3839 			if (e.error) {
3840 				/* req time field(s) overflow - return */
3841 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3842 				    needrecov);
3843 				break;
3844 			}
3845 		}
3846 
3847 		doqueue = 1;
3848 
3849 		t = gethrtime();
3850 
3851 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3852 
3853 		/*
3854 		 * Purge the access cache and ACL cache if changing either the
3855 		 * owner of the file, the group owner, or the mode.  These may
3856 		 * change the access permissions of the file, so purge old
3857 		 * information and start over again.
3858 		 */
3859 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3860 			(void) nfs4_access_purge_rp(rp);
3861 			if (rp->r_secattr != NULL) {
3862 				mutex_enter(&rp->r_statelock);
3863 				vsp = rp->r_secattr;
3864 				rp->r_secattr = NULL;
3865 				mutex_exit(&rp->r_statelock);
3866 				if (vsp != NULL)
3867 					nfs4_acl_free_cache(vsp);
3868 			}
3869 		}
3870 
3871 		/*
3872 		 * If res.array_len == numops, then everything succeeded,
3873 		 * except for possibly the final getattr.  If only the
3874 		 * last getattr failed, give up, and don't try recovery.
3875 		 */
3876 		if (res.array_len == numops) {
3877 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3878 			    needrecov);
3879 			if (! e.error)
3880 				resp = &res;
3881 			break;
3882 		}
3883 
3884 		/*
3885 		 * if either rpc call failed or completely succeeded - done
3886 		 */
3887 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
3888 		if (e.error) {
3889 			PURGE_ATTRCACHE4(vp);
3890 			if (!needrecov) {
3891 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3892 				    needrecov);
3893 				break;
3894 			}
3895 		}
3896 
3897 		/*
3898 		 * Do proper retry for OLD_STATEID outside of the normal
3899 		 * recovery framework.
3900 		 */
3901 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3902 		    sid_types.cur_sid_type != SPEC_SID &&
3903 		    sid_types.cur_sid_type != NO_SID) {
3904 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3905 			    needrecov);
3906 			nfs4_save_stateid(&stateid, &sid_types);
3907 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3908 			    opsetattr.obj_attributes);
3909 			if (verify_argop != -1) {
3910 				nfs4args_verify_free(&argop[verify_argop]);
3911 				verify_argop = -1;
3912 			}
3913 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3914 			goto recov_retry;
3915 		}
3916 
3917 		if (needrecov) {
3918 			bool_t abort;
3919 
3920 			abort = nfs4_start_recovery(&e,
3921 			    VTOMI4(vp), vp, NULL, NULL, NULL,
3922 			    OP_SETATTR, NULL);
3923 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3924 			    needrecov);
3925 			/*
3926 			 * Do not retry if we failed with OLD_STATEID using
3927 			 * a special stateid.  This is done to avoid looping
3928 			 * with a broken server.
3929 			 */
3930 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3931 			    (sid_types.cur_sid_type == SPEC_SID ||
3932 			    sid_types.cur_sid_type == NO_SID))
3933 				abort = TRUE;
3934 			if (!e.error) {
3935 				if (res.status == NFS4ERR_BADOWNER)
3936 					nfs4_log_badowner(VTOMI4(vp),
3937 					    OP_SETATTR);
3938 
3939 				e.error = geterrno4(res.status);
3940 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3941 				    (caddr_t)&res);
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 (abort == FALSE) {
3950 				/*
3951 				 * Need to retry all possible stateids in
3952 				 * case the recovery error wasn't stateid
3953 				 * related or the stateids have become
3954 				 * stale (server reboot).
3955 				 */
3956 				nfs4_init_stateid_types(&sid_types);
3957 				goto recov_retry;
3958 			}
3959 			return (e.error);
3960 		}
3961 
3962 		/*
3963 		 * Need to call nfs4_end_op before nfs4getattr to
3964 		 * avoid potential nfs4_start_op deadlock. See RFE
3965 		 * 4777612.  Calls to nfs4_invalidate_pages() and
3966 		 * nfs4_purge_stale_fh() might also generate over the
3967 		 * wire calls which my cause nfs4_start_op() deadlock.
3968 		 */
3969 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3970 
3971 		/*
3972 		 * Check to update lease.
3973 		 */
3974 		resp = &res;
3975 		if (res.status == NFS4_OK) {
3976 			break;
3977 		}
3978 
3979 		/*
3980 		 * Check if verify failed to see if try again
3981 		 */
3982 		if ((verify_argop == -1) || (res.array_len != 3)) {
3983 			/*
3984 			 * can't continue...
3985 			 */
3986 			if (res.status == NFS4ERR_BADOWNER)
3987 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
3988 
3989 			e.error = geterrno4(res.status);
3990 		} else {
3991 			/*
3992 			 * When the verify request fails, the client ctime is
3993 			 * not in sync with the server. This is the same as
3994 			 * the version 3 "not synchronized" error, and we
3995 			 * handle it in a similar manner (XXX do we need to???).
3996 			 * Use the ctime returned in the first getattr for
3997 			 * the input to the next verify.
3998 			 * If we couldn't get the attributes, then we give up
3999 			 * because we can't complete the operation as required.
4000 			 */
4001 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
4002 		}
4003 		if (e.error) {
4004 			PURGE_ATTRCACHE4(vp);
4005 			nfs4_purge_stale_fh(e.error, vp, cr);
4006 		} else {
4007 			/*
4008 			 * retry with a new verify value
4009 			 */
4010 			ctime = garp->n4g_va.va_ctime;
4011 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4012 			resp = NULL;
4013 		}
4014 		if (!e.error) {
4015 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4016 			    opsetattr.obj_attributes);
4017 			if (verify_argop != -1) {
4018 				nfs4args_verify_free(&argop[verify_argop]);
4019 				verify_argop = -1;
4020 			}
4021 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4022 			goto do_again;
4023 		}
4024 	} while (!e.error);
4025 
4026 	if (e.error) {
4027 		/*
4028 		 * If we are here, rfs4call has an irrecoverable error - return
4029 		 */
4030 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4031 		    opsetattr.obj_attributes);
4032 		if (verify_argop != -1) {
4033 			nfs4args_verify_free(&argop[verify_argop]);
4034 			verify_argop = -1;
4035 		}
4036 		if (resp)
4037 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4038 		return (e.error);
4039 	}
4040 
4041 
4042 
4043 	/*
4044 	 * If changing the size of the file, invalidate
4045 	 * any local cached data which is no longer part
4046 	 * of the file.  We also possibly invalidate the
4047 	 * last page in the file.  We could use
4048 	 * pvn_vpzero(), but this would mark the page as
4049 	 * modified and require it to be written back to
4050 	 * the server for no particularly good reason.
4051 	 * This way, if we access it, then we bring it
4052 	 * back in.  A read should be cheaper than a
4053 	 * write.
4054 	 */
4055 	if (mask & AT_SIZE) {
4056 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
4057 	}
4058 
4059 	/* either no error or one of the postop getattr failed */
4060 
4061 	/*
4062 	 * XXX Perform a simplified version of wcc checking. Instead of
4063 	 * have another getattr to get pre-op, just purge cache if
4064 	 * any of the ops prior to and including the getattr failed.
4065 	 * If the getattr succeeded then update the attrcache accordingly.
4066 	 */
4067 
4068 	garp = NULL;
4069 	if (res.status == NFS4_OK) {
4070 		/*
4071 		 * Last getattr
4072 		 */
4073 		resop = &res.array[numops - 1];
4074 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4075 	}
4076 	/*
4077 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
4078 	 * rather than filling it.  See the function itself for details.
4079 	 */
4080 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4081 	if (garp != NULL) {
4082 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
4083 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
4084 			vs_ace4_destroy(&garp->n4g_vsa);
4085 		} else {
4086 			if (vsap != NULL) {
4087 				/*
4088 				 * The ACL was supposed to be set and to be
4089 				 * returned in the last getattr of this
4090 				 * compound, but for some reason the getattr
4091 				 * result doesn't contain the ACL.  In this
4092 				 * case, purge the ACL cache.
4093 				 */
4094 				if (rp->r_secattr != NULL) {
4095 					mutex_enter(&rp->r_statelock);
4096 					vsp = rp->r_secattr;
4097 					rp->r_secattr = NULL;
4098 					mutex_exit(&rp->r_statelock);
4099 					if (vsp != NULL)
4100 						nfs4_acl_free_cache(vsp);
4101 				}
4102 			}
4103 		}
4104 	}
4105 
4106 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4107 		/*
4108 		 * Set the size, rather than relying on getting it updated
4109 		 * via a GETATTR.  With delegations the client tries to
4110 		 * suppress GETATTR calls.
4111 		 */
4112 		mutex_enter(&rp->r_statelock);
4113 		rp->r_size = vap->va_size;
4114 		mutex_exit(&rp->r_statelock);
4115 	}
4116 
4117 	/*
4118 	 * Can free up request args and res
4119 	 */
4120 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4121 	    opsetattr.obj_attributes);
4122 	if (verify_argop != -1) {
4123 		nfs4args_verify_free(&argop[verify_argop]);
4124 		verify_argop = -1;
4125 	}
4126 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4127 
4128 	/*
4129 	 * Some servers will change the mode to clear the setuid
4130 	 * and setgid bits when changing the uid or gid.  The
4131 	 * client needs to compensate appropriately.
4132 	 */
4133 	if (mask & (AT_UID | AT_GID)) {
4134 		int terror, do_setattr;
4135 
4136 		do_setattr = 0;
4137 		va.va_mask = AT_MODE;
4138 		terror = nfs4getattr(vp, &va, cr);
4139 		if (!terror &&
4140 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4141 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4142 			va.va_mask = AT_MODE;
4143 			if (mask & AT_MODE) {
4144 				/*
4145 				 * We asked the mode to be changed and what
4146 				 * we just got from the server in getattr is
4147 				 * not what we wanted it to be, so set it now.
4148 				 */
4149 				va.va_mode = vap->va_mode;
4150 				do_setattr = 1;
4151 			} else {
4152 				/*
4153 				 * We did not ask the mode to be changed,
4154 				 * Check to see that the server just cleared
4155 				 * I_SUID and I_GUID from it. If not then
4156 				 * set mode to omode with UID/GID cleared.
4157 				 */
4158 				if (nfs4_compare_modes(va.va_mode, omode)) {
4159 					omode &= ~(S_ISUID|S_ISGID);
4160 					va.va_mode = omode;
4161 					do_setattr = 1;
4162 				}
4163 			}
4164 
4165 			if (do_setattr)
4166 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4167 		}
4168 	}
4169 
4170 	return (e.error);
4171 }
4172 
4173 /* ARGSUSED */
4174 static int
4175 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr, caller_context_t *ct)
4176 {
4177 	COMPOUND4args_clnt args;
4178 	COMPOUND4res_clnt res;
4179 	int doqueue;
4180 	uint32_t acc, resacc, argacc;
4181 	rnode4_t *rp;
4182 	cred_t *cred, *ncr, *ncrfree = NULL;
4183 	nfs4_access_type_t cacc;
4184 	int num_ops;
4185 	nfs_argop4 argop[3];
4186 	nfs_resop4 *resop;
4187 	bool_t needrecov = FALSE, do_getattr;
4188 	nfs4_recov_state_t recov_state;
4189 	int rpc_error;
4190 	hrtime_t t;
4191 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4192 	mntinfo4_t *mi = VTOMI4(vp);
4193 
4194 	if (nfs_zone() != mi->mi_zone)
4195 		return (EIO);
4196 
4197 	acc = 0;
4198 	if (mode & VREAD)
4199 		acc |= ACCESS4_READ;
4200 	if (mode & VWRITE) {
4201 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4202 			return (EROFS);
4203 		if (vp->v_type == VDIR)
4204 			acc |= ACCESS4_DELETE;
4205 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4206 	}
4207 	if (mode & VEXEC) {
4208 		if (vp->v_type == VDIR)
4209 			acc |= ACCESS4_LOOKUP;
4210 		else
4211 			acc |= ACCESS4_EXECUTE;
4212 	}
4213 
4214 	if (VTOR4(vp)->r_acache != NULL) {
4215 		e.error = nfs4_validate_caches(vp, cr);
4216 		if (e.error)
4217 			return (e.error);
4218 	}
4219 
4220 	rp = VTOR4(vp);
4221 	if (vp->v_type == VDIR)
4222 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4223 		    ACCESS4_EXTEND | ACCESS4_LOOKUP;
4224 	else
4225 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4226 		    ACCESS4_EXECUTE;
4227 	recov_state.rs_flags = 0;
4228 	recov_state.rs_num_retry_despite_err = 0;
4229 
4230 	cred = cr;
4231 	/*
4232 	 * ncr and ncrfree both initially
4233 	 * point to the memory area returned
4234 	 * by crnetadjust();
4235 	 * ncrfree not NULL when exiting means
4236 	 * that we need to release it
4237 	 */
4238 	ncr = crnetadjust(cred);
4239 	ncrfree = ncr;
4240 
4241 tryagain:
4242 	cacc = nfs4_access_check(rp, acc, cred);
4243 	if (cacc == NFS4_ACCESS_ALLOWED) {
4244 		if (ncrfree != NULL)
4245 			crfree(ncrfree);
4246 		return (0);
4247 	}
4248 	if (cacc == NFS4_ACCESS_DENIED) {
4249 		/*
4250 		 * If the cred can be adjusted, try again
4251 		 * with the new cred.
4252 		 */
4253 		if (ncr != NULL) {
4254 			cred = ncr;
4255 			ncr = NULL;
4256 			goto tryagain;
4257 		}
4258 		if (ncrfree != NULL)
4259 			crfree(ncrfree);
4260 		return (EACCES);
4261 	}
4262 
4263 recov_retry:
4264 	/*
4265 	 * Don't take with r_statev4_lock here. r_deleg_type could
4266 	 * change as soon as lock is released.  Since it is an int,
4267 	 * there is no atomicity issue.
4268 	 */
4269 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4270 	num_ops = do_getattr ? 3 : 2;
4271 
4272 	args.ctag = TAG_ACCESS;
4273 
4274 	args.array_len = num_ops;
4275 	args.array = argop;
4276 
4277 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4278 	    &recov_state, NULL)) {
4279 		if (ncrfree != NULL)
4280 			crfree(ncrfree);
4281 		return (e.error);
4282 	}
4283 
4284 	/* putfh target fh */
4285 	argop[0].argop = OP_CPUTFH;
4286 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4287 
4288 	/* access */
4289 	argop[1].argop = OP_ACCESS;
4290 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4291 
4292 	/* getattr */
4293 	if (do_getattr) {
4294 		argop[2].argop = OP_GETATTR;
4295 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4296 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4297 	}
4298 
4299 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4300 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4301 	    rnode4info(VTOR4(vp))));
4302 
4303 	doqueue = 1;
4304 	t = gethrtime();
4305 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4306 	rpc_error = e.error;
4307 
4308 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4309 	if (needrecov) {
4310 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4311 		    "nfs4_access: initiating recovery\n"));
4312 
4313 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4314 		    NULL, OP_ACCESS, NULL) == FALSE) {
4315 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4316 			    &recov_state, needrecov);
4317 			if (!e.error)
4318 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4319 				    (caddr_t)&res);
4320 			goto recov_retry;
4321 		}
4322 	}
4323 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4324 
4325 	if (e.error)
4326 		goto out;
4327 
4328 	if (res.status) {
4329 		e.error = geterrno4(res.status);
4330 		/*
4331 		 * This might generate over the wire calls throught
4332 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4333 		 * here to avoid a deadlock.
4334 		 */
4335 		nfs4_purge_stale_fh(e.error, vp, cr);
4336 		goto out;
4337 	}
4338 	resop = &res.array[1];	/* access res */
4339 
4340 	resacc = resop->nfs_resop4_u.opaccess.access;
4341 
4342 	if (do_getattr) {
4343 		resop++;	/* getattr res */
4344 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4345 		    t, cr, FALSE, NULL);
4346 	}
4347 
4348 	if (!e.error) {
4349 		nfs4_access_cache(rp, argacc, resacc, cred);
4350 		/*
4351 		 * we just cached results with cred; if cred is the
4352 		 * adjusted credentials from crnetadjust, we do not want
4353 		 * to release them before exiting: hence setting ncrfree
4354 		 * to NULL
4355 		 */
4356 		if (cred != cr)
4357 			ncrfree = NULL;
4358 		/* XXX check the supported bits too? */
4359 		if ((acc & resacc) != acc) {
4360 			/*
4361 			 * The following code implements the semantic
4362 			 * that a setuid root program has *at least* the
4363 			 * permissions of the user that is running the
4364 			 * program.  See rfs3call() for more portions
4365 			 * of the implementation of this functionality.
4366 			 */
4367 			/* XXX-LP */
4368 			if (ncr != NULL) {
4369 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4370 				    (caddr_t)&res);
4371 				cred = ncr;
4372 				ncr = NULL;
4373 				goto tryagain;
4374 			}
4375 			e.error = EACCES;
4376 		}
4377 	}
4378 
4379 out:
4380 	if (!rpc_error)
4381 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4382 
4383 	if (ncrfree != NULL)
4384 		crfree(ncrfree);
4385 
4386 	return (e.error);
4387 }
4388 
4389 /* ARGSUSED */
4390 static int
4391 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr, caller_context_t *ct)
4392 {
4393 	COMPOUND4args_clnt args;
4394 	COMPOUND4res_clnt res;
4395 	int doqueue;
4396 	rnode4_t *rp;
4397 	nfs_argop4 argop[3];
4398 	nfs_resop4 *resop;
4399 	READLINK4res *lr_res;
4400 	nfs4_ga_res_t *garp;
4401 	uint_t len;
4402 	char *linkdata;
4403 	bool_t needrecov = FALSE;
4404 	nfs4_recov_state_t recov_state;
4405 	hrtime_t t;
4406 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4407 
4408 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4409 		return (EIO);
4410 	/*
4411 	 * Can't readlink anything other than a symbolic link.
4412 	 */
4413 	if (vp->v_type != VLNK)
4414 		return (EINVAL);
4415 
4416 	rp = VTOR4(vp);
4417 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4418 		e.error = nfs4_validate_caches(vp, cr);
4419 		if (e.error)
4420 			return (e.error);
4421 		mutex_enter(&rp->r_statelock);
4422 		if (rp->r_symlink.contents != NULL) {
4423 			e.error = uiomove(rp->r_symlink.contents,
4424 			    rp->r_symlink.len, UIO_READ, uiop);
4425 			mutex_exit(&rp->r_statelock);
4426 			return (e.error);
4427 		}
4428 		mutex_exit(&rp->r_statelock);
4429 	}
4430 	recov_state.rs_flags = 0;
4431 	recov_state.rs_num_retry_despite_err = 0;
4432 
4433 recov_retry:
4434 	args.array_len = 3;
4435 	args.array = argop;
4436 	args.ctag = TAG_READLINK;
4437 
4438 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4439 	if (e.error) {
4440 		return (e.error);
4441 	}
4442 
4443 	/* 0. putfh symlink fh */
4444 	argop[0].argop = OP_CPUTFH;
4445 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4446 
4447 	/* 1. readlink */
4448 	argop[1].argop = OP_READLINK;
4449 
4450 	/* 2. getattr */
4451 	argop[2].argop = OP_GETATTR;
4452 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4453 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4454 
4455 	doqueue = 1;
4456 
4457 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4458 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4459 	    rnode4info(VTOR4(vp))));
4460 
4461 	t = gethrtime();
4462 
4463 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4464 
4465 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4466 	if (needrecov) {
4467 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4468 		    "nfs4_readlink: initiating recovery\n"));
4469 
4470 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4471 		    NULL, OP_READLINK, NULL) == FALSE) {
4472 			if (!e.error)
4473 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4474 				    (caddr_t)&res);
4475 
4476 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4477 			    needrecov);
4478 			goto recov_retry;
4479 		}
4480 	}
4481 
4482 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4483 
4484 	if (e.error)
4485 		return (e.error);
4486 
4487 	/*
4488 	 * There is an path in the code below which calls
4489 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4490 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4491 	 * here to avoid nfs4_start_op() deadlock.
4492 	 */
4493 
4494 	if (res.status && (res.array_len < args.array_len)) {
4495 		/*
4496 		 * either Putfh or Link failed
4497 		 */
4498 		e.error = geterrno4(res.status);
4499 		nfs4_purge_stale_fh(e.error, vp, cr);
4500 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4501 		return (e.error);
4502 	}
4503 
4504 	resop = &res.array[1];	/* readlink res */
4505 	lr_res = &resop->nfs_resop4_u.opreadlink;
4506 
4507 	/*
4508 	 * treat symlink names as data
4509 	 */
4510 	linkdata = utf8_to_str(&lr_res->link, &len, NULL);
4511 	if (linkdata != NULL) {
4512 		int uio_len = len - 1;
4513 		/* len includes null byte, which we won't uiomove */
4514 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4515 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4516 			mutex_enter(&rp->r_statelock);
4517 			if (rp->r_symlink.contents == NULL) {
4518 				rp->r_symlink.contents = linkdata;
4519 				rp->r_symlink.len = uio_len;
4520 				rp->r_symlink.size = len;
4521 				mutex_exit(&rp->r_statelock);
4522 			} else {
4523 				mutex_exit(&rp->r_statelock);
4524 				kmem_free(linkdata, len);
4525 			}
4526 		} else {
4527 			kmem_free(linkdata, len);
4528 		}
4529 	}
4530 	if (res.status == NFS4_OK) {
4531 		resop++;	/* getattr res */
4532 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4533 	}
4534 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4535 
4536 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4537 
4538 	/*
4539 	 * The over the wire error for attempting to readlink something
4540 	 * other than a symbolic link is ENXIO.  However, we need to
4541 	 * return EINVAL instead of ENXIO, so we map it here.
4542 	 */
4543 	return (e.error == ENXIO ? EINVAL : e.error);
4544 }
4545 
4546 /*
4547  * Flush local dirty pages to stable storage on the server.
4548  *
4549  * If FNODSYNC is specified, then there is nothing to do because
4550  * metadata changes are not cached on the client before being
4551  * sent to the server.
4552  */
4553 /* ARGSUSED */
4554 static int
4555 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
4556 {
4557 	int error;
4558 
4559 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4560 		return (0);
4561 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4562 		return (EIO);
4563 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4564 	if (!error)
4565 		error = VTOR4(vp)->r_error;
4566 	return (error);
4567 }
4568 
4569 /*
4570  * Weirdness: if the file was removed or the target of a rename
4571  * operation while it was open, it got renamed instead.  Here we
4572  * remove the renamed file.
4573  */
4574 /* ARGSUSED */
4575 void
4576 nfs4_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4577 {
4578 	rnode4_t *rp;
4579 
4580 	ASSERT(vp != DNLC_NO_VNODE);
4581 
4582 	rp = VTOR4(vp);
4583 
4584 	if (IS_SHADOW(vp, rp)) {
4585 		sv_inactive(vp);
4586 		return;
4587 	}
4588 
4589 	/*
4590 	 * If this is coming from the wrong zone, we let someone in the right
4591 	 * zone take care of it asynchronously.  We can get here due to
4592 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4593 	 * potentially turn into an expensive no-op if, for instance, v_count
4594 	 * gets incremented in the meantime, but it's still correct.
4595 	 */
4596 	if (nfs_zone() != VTOMI4(vp)->mi_zone) {
4597 		nfs4_async_inactive(vp, cr);
4598 		return;
4599 	}
4600 
4601 	/*
4602 	 * Some of the cleanup steps might require over-the-wire
4603 	 * operations.  Since VOP_INACTIVE can get called as a result of
4604 	 * other over-the-wire operations (e.g., an attribute cache update
4605 	 * can lead to a DNLC purge), doing those steps now would lead to a
4606 	 * nested call to the recovery framework, which can deadlock.  So
4607 	 * do any over-the-wire cleanups asynchronously, in a separate
4608 	 * thread.
4609 	 */
4610 
4611 	mutex_enter(&rp->r_os_lock);
4612 	mutex_enter(&rp->r_statelock);
4613 	mutex_enter(&rp->r_statev4_lock);
4614 
4615 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4616 		mutex_exit(&rp->r_statev4_lock);
4617 		mutex_exit(&rp->r_statelock);
4618 		mutex_exit(&rp->r_os_lock);
4619 		nfs4_async_inactive(vp, cr);
4620 		return;
4621 	}
4622 
4623 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4624 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4625 		mutex_exit(&rp->r_statev4_lock);
4626 		mutex_exit(&rp->r_statelock);
4627 		mutex_exit(&rp->r_os_lock);
4628 		nfs4_async_inactive(vp, cr);
4629 		return;
4630 	}
4631 
4632 	if (rp->r_unldvp != NULL) {
4633 		mutex_exit(&rp->r_statev4_lock);
4634 		mutex_exit(&rp->r_statelock);
4635 		mutex_exit(&rp->r_os_lock);
4636 		nfs4_async_inactive(vp, cr);
4637 		return;
4638 	}
4639 	mutex_exit(&rp->r_statev4_lock);
4640 	mutex_exit(&rp->r_statelock);
4641 	mutex_exit(&rp->r_os_lock);
4642 
4643 	rp4_addfree(rp, cr);
4644 }
4645 
4646 /*
4647  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4648  * various bits of state.  The caller must not refer to vp after this call.
4649  */
4650 
4651 void
4652 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4653 {
4654 	rnode4_t *rp = VTOR4(vp);
4655 	nfs4_recov_state_t recov_state;
4656 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4657 	vnode_t *unldvp;
4658 	char *unlname;
4659 	cred_t *unlcred;
4660 	COMPOUND4args_clnt args;
4661 	COMPOUND4res_clnt res, *resp;
4662 	nfs_argop4 argop[2];
4663 	int doqueue;
4664 #ifdef DEBUG
4665 	char *name;
4666 #endif
4667 
4668 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
4669 	ASSERT(!IS_SHADOW(vp, rp));
4670 
4671 #ifdef DEBUG
4672 	name = fn_name(VTOSV(vp)->sv_name);
4673 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4674 	    "release vnode %s", name));
4675 	kmem_free(name, MAXNAMELEN);
4676 #endif
4677 
4678 	if (vp->v_type == VREG) {
4679 		bool_t recov_failed = FALSE;
4680 
4681 		e.error = nfs4close_all(vp, cr);
4682 		if (e.error) {
4683 			/* Check to see if recovery failed */
4684 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4685 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4686 				recov_failed = TRUE;
4687 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4688 			if (!recov_failed) {
4689 				mutex_enter(&rp->r_statelock);
4690 				if (rp->r_flags & R4RECOVERR)
4691 					recov_failed = TRUE;
4692 				mutex_exit(&rp->r_statelock);
4693 			}
4694 			if (recov_failed) {
4695 				NFS4_DEBUG(nfs4_client_recov_debug,
4696 				    (CE_NOTE, "nfs4_inactive_otw: "
4697 				    "close failed (recovery failure)"));
4698 			}
4699 		}
4700 	}
4701 
4702 redo:
4703 	if (rp->r_unldvp == NULL) {
4704 		rp4_addfree(rp, cr);
4705 		return;
4706 	}
4707 
4708 	/*
4709 	 * Save the vnode pointer for the directory where the
4710 	 * unlinked-open file got renamed, then set it to NULL
4711 	 * to prevent another thread from getting here before
4712 	 * we're done with the remove.  While we have the
4713 	 * statelock, make local copies of the pertinent rnode
4714 	 * fields.  If we weren't to do this in an atomic way, the
4715 	 * the unl* fields could become inconsistent with respect
4716 	 * to each other due to a race condition between this
4717 	 * code and nfs_remove().  See bug report 1034328.
4718 	 */
4719 	mutex_enter(&rp->r_statelock);
4720 	if (rp->r_unldvp == NULL) {
4721 		mutex_exit(&rp->r_statelock);
4722 		rp4_addfree(rp, cr);
4723 		return;
4724 	}
4725 
4726 	unldvp = rp->r_unldvp;
4727 	rp->r_unldvp = NULL;
4728 	unlname = rp->r_unlname;
4729 	rp->r_unlname = NULL;
4730 	unlcred = rp->r_unlcred;
4731 	rp->r_unlcred = NULL;
4732 	mutex_exit(&rp->r_statelock);
4733 
4734 	/*
4735 	 * If there are any dirty pages left, then flush
4736 	 * them.  This is unfortunate because they just
4737 	 * may get thrown away during the remove operation,
4738 	 * but we have to do this for correctness.
4739 	 */
4740 	if (nfs4_has_pages(vp) &&
4741 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4742 		ASSERT(vp->v_type != VCHR);
4743 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, NULL);
4744 		if (e.error) {
4745 			mutex_enter(&rp->r_statelock);
4746 			if (!rp->r_error)
4747 				rp->r_error = e.error;
4748 			mutex_exit(&rp->r_statelock);
4749 		}
4750 	}
4751 
4752 	recov_state.rs_flags = 0;
4753 	recov_state.rs_num_retry_despite_err = 0;
4754 recov_retry_remove:
4755 	/*
4756 	 * Do the remove operation on the renamed file
4757 	 */
4758 	args.ctag = TAG_INACTIVE;
4759 
4760 	/*
4761 	 * Remove ops: putfh dir; remove
4762 	 */
4763 	args.array_len = 2;
4764 	args.array = argop;
4765 
4766 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4767 	if (e.error) {
4768 		kmem_free(unlname, MAXNAMELEN);
4769 		crfree(unlcred);
4770 		VN_RELE(unldvp);
4771 		/*
4772 		 * Try again; this time around r_unldvp will be NULL, so we'll
4773 		 * just call rp4_addfree() and return.
4774 		 */
4775 		goto redo;
4776 	}
4777 
4778 	/* putfh directory */
4779 	argop[0].argop = OP_CPUTFH;
4780 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4781 
4782 	/* remove */
4783 	argop[1].argop = OP_CREMOVE;
4784 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4785 
4786 	doqueue = 1;
4787 	resp = &res;
4788 
4789 #if 0 /* notyet */
4790 	/*
4791 	 * Can't do this yet.  We may be being called from
4792 	 * dnlc_purge_XXX while that routine is holding a
4793 	 * mutex lock to the nc_rele list.  The calls to
4794 	 * nfs3_cache_wcc_data may result in calls to
4795 	 * dnlc_purge_XXX.  This will result in a deadlock.
4796 	 */
4797 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4798 	if (e.error) {
4799 		PURGE_ATTRCACHE4(unldvp);
4800 		resp = NULL;
4801 	} else if (res.status) {
4802 		e.error = geterrno4(res.status);
4803 		PURGE_ATTRCACHE4(unldvp);
4804 		/*
4805 		 * This code is inactive right now
4806 		 * but if made active there should
4807 		 * be a nfs4_end_op() call before
4808 		 * nfs4_purge_stale_fh to avoid start_op()
4809 		 * deadlock. See BugId: 4948726
4810 		 */
4811 		nfs4_purge_stale_fh(error, unldvp, cr);
4812 	} else {
4813 		nfs_resop4 *resop;
4814 		REMOVE4res *rm_res;
4815 
4816 		resop = &res.array[1];
4817 		rm_res = &resop->nfs_resop4_u.opremove;
4818 		/*
4819 		 * Update directory cache attribute,
4820 		 * readdir and dnlc caches.
4821 		 */
4822 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4823 	}
4824 #else
4825 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4826 
4827 	PURGE_ATTRCACHE4(unldvp);
4828 #endif
4829 
4830 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4831 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4832 		    NULL, NULL, OP_REMOVE, NULL) == FALSE) {
4833 			if (!e.error)
4834 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4835 				    (caddr_t)&res);
4836 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4837 			    &recov_state, TRUE);
4838 			goto recov_retry_remove;
4839 		}
4840 	}
4841 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4842 
4843 	/*
4844 	 * Release stuff held for the remove
4845 	 */
4846 	VN_RELE(unldvp);
4847 	if (!e.error && resp)
4848 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4849 
4850 	kmem_free(unlname, MAXNAMELEN);
4851 	crfree(unlcred);
4852 	goto redo;
4853 }
4854 
4855 /*
4856  * Remote file system operations having to do with directory manipulation.
4857  */
4858 /* ARGSUSED3 */
4859 int
4860 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4861     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
4862     int *direntflags, pathname_t *realpnp)
4863 {
4864 	int error;
4865 	vnode_t *vp, *avp = NULL;
4866 	rnode4_t *drp;
4867 
4868 	*vpp = NULL;
4869 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4870 		return (EPERM);
4871 	/*
4872 	 * if LOOKUP_XATTR, must replace dvp (object) with
4873 	 * object's attrdir before continuing with lookup
4874 	 */
4875 	if (flags & LOOKUP_XATTR) {
4876 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4877 		if (error)
4878 			return (error);
4879 
4880 		dvp = avp;
4881 
4882 		/*
4883 		 * If lookup is for "", just return dvp now.  The attrdir
4884 		 * has already been activated (from nfs4lookup_xattr), and
4885 		 * the caller will RELE the original dvp -- not
4886 		 * the attrdir.  So, set vpp and return.
4887 		 * Currently, when the LOOKUP_XATTR flag is
4888 		 * passed to VOP_LOOKUP, the name is always empty, and
4889 		 * shortcircuiting here avoids 3 unneeded lock/unlock
4890 		 * pairs.
4891 		 *
4892 		 * If a non-empty name was provided, then it is the
4893 		 * attribute name, and it will be looked up below.
4894 		 */
4895 		if (*nm == '\0') {
4896 			*vpp = dvp;
4897 			return (0);
4898 		}
4899 
4900 		/*
4901 		 * The vfs layer never sends a name when asking for the
4902 		 * attrdir, so we should never get here (unless of course
4903 		 * name is passed at some time in future -- at which time
4904 		 * we'll blow up here).
4905 		 */
4906 		ASSERT(0);
4907 	}
4908 
4909 	drp = VTOR4(dvp);
4910 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4911 		return (EINTR);
4912 
4913 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
4914 	nfs_rw_exit(&drp->r_rwlock);
4915 
4916 	/*
4917 	 * If vnode is a device, create special vnode.
4918 	 */
4919 	if (!error && ISVDEV((*vpp)->v_type)) {
4920 		vp = *vpp;
4921 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
4922 		VN_RELE(vp);
4923 	}
4924 
4925 	return (error);
4926 }
4927 
4928 /* ARGSUSED */
4929 static int
4930 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
4931 {
4932 	int error;
4933 	rnode4_t *drp;
4934 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
4935 	mntinfo4_t *mi;
4936 
4937 	mi = VTOMI4(dvp);
4938 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR) &&
4939 	    !vfs_has_feature(mi->mi_vfsp, VFSFT_XVATTR))
4940 		return (EINVAL);
4941 
4942 	drp = VTOR4(dvp);
4943 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4944 		return (EINTR);
4945 
4946 	mutex_enter(&drp->r_statelock);
4947 	/*
4948 	 * If the server doesn't support xattrs just return EINVAL
4949 	 */
4950 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
4951 		mutex_exit(&drp->r_statelock);
4952 		nfs_rw_exit(&drp->r_rwlock);
4953 		return (EINVAL);
4954 	}
4955 
4956 	/*
4957 	 * If there is a cached xattr directory entry,
4958 	 * use it as long as the attributes are valid. If the
4959 	 * attributes are not valid, take the simple approach and
4960 	 * free the cached value and re-fetch a new value.
4961 	 *
4962 	 * We don't negative entry cache for now, if we did we
4963 	 * would need to check if the file has changed on every
4964 	 * lookup. But xattrs don't exist very often and failing
4965 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
4966 	 * so do an openattr over the wire for now.
4967 	 */
4968 	if (drp->r_xattr_dir != NULL) {
4969 		if (ATTRCACHE4_VALID(dvp)) {
4970 			VN_HOLD(drp->r_xattr_dir);
4971 			*vpp = drp->r_xattr_dir;
4972 			mutex_exit(&drp->r_statelock);
4973 			nfs_rw_exit(&drp->r_rwlock);
4974 			return (0);
4975 		}
4976 		VN_RELE(drp->r_xattr_dir);
4977 		drp->r_xattr_dir = NULL;
4978 	}
4979 	mutex_exit(&drp->r_statelock);
4980 
4981 	error = nfs4openattr(dvp, vpp, cflag, cr);
4982 
4983 	nfs_rw_exit(&drp->r_rwlock);
4984 
4985 	return (error);
4986 }
4987 
4988 static int
4989 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
4990 {
4991 	int error;
4992 	rnode4_t *drp;
4993 
4994 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
4995 
4996 	/*
4997 	 * If lookup is for "", just return dvp.  Don't need
4998 	 * to send it over the wire, look it up in the dnlc,
4999 	 * or perform any access checks.
5000 	 */
5001 	if (*nm == '\0') {
5002 		VN_HOLD(dvp);
5003 		*vpp = dvp;
5004 		return (0);
5005 	}
5006 
5007 	/*
5008 	 * Can't do lookups in non-directories.
5009 	 */
5010 	if (dvp->v_type != VDIR)
5011 		return (ENOTDIR);
5012 
5013 	/*
5014 	 * If lookup is for ".", just return dvp.  Don't need
5015 	 * to send it over the wire or look it up in the dnlc,
5016 	 * just need to check access.
5017 	 */
5018 	if (nm[0] == '.' && nm[1] == '\0') {
5019 		error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5020 		if (error)
5021 			return (error);
5022 		VN_HOLD(dvp);
5023 		*vpp = dvp;
5024 		return (0);
5025 	}
5026 
5027 	drp = VTOR4(dvp);
5028 	if (!(drp->r_flags & R4LOOKUP)) {
5029 		mutex_enter(&drp->r_statelock);
5030 		drp->r_flags |= R4LOOKUP;
5031 		mutex_exit(&drp->r_statelock);
5032 	}
5033 
5034 	*vpp = NULL;
5035 	/*
5036 	 * Lookup this name in the DNLC.  If there is no entry
5037 	 * lookup over the wire.
5038 	 */
5039 	if (!skipdnlc)
5040 		*vpp = dnlc_lookup(dvp, nm);
5041 	if (*vpp == NULL) {
5042 		/*
5043 		 * We need to go over the wire to lookup the name.
5044 		 */
5045 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
5046 	}
5047 
5048 	/*
5049 	 * We hit on the dnlc
5050 	 */
5051 	if (*vpp != DNLC_NO_VNODE ||
5052 	    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
5053 		/*
5054 		 * But our attrs may not be valid.
5055 		 */
5056 		if (ATTRCACHE4_VALID(dvp)) {
5057 			error = nfs4_waitfor_purge_complete(dvp);
5058 			if (error) {
5059 				VN_RELE(*vpp);
5060 				*vpp = NULL;
5061 				return (error);
5062 			}
5063 
5064 			/*
5065 			 * If after the purge completes, check to make sure
5066 			 * our attrs are still valid.
5067 			 */
5068 			if (ATTRCACHE4_VALID(dvp)) {
5069 				/*
5070 				 * If we waited for a purge we may have
5071 				 * lost our vnode so look it up again.
5072 				 */
5073 				VN_RELE(*vpp);
5074 				*vpp = dnlc_lookup(dvp, nm);
5075 				if (*vpp == NULL)
5076 					return (nfs4lookupnew_otw(dvp,
5077 					    nm, vpp, cr));
5078 
5079 				/*
5080 				 * The access cache should almost always hit
5081 				 */
5082 				error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5083 
5084 				if (error) {
5085 					VN_RELE(*vpp);
5086 					*vpp = NULL;
5087 					return (error);
5088 				}
5089 				if (*vpp == DNLC_NO_VNODE) {
5090 					VN_RELE(*vpp);
5091 					*vpp = NULL;
5092 					return (ENOENT);
5093 				}
5094 				return (0);
5095 			}
5096 		}
5097 	}
5098 
5099 	ASSERT(*vpp != NULL);
5100 
5101 	/*
5102 	 * We may have gotten here we have one of the following cases:
5103 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5104 	 *		need to validate them.
5105 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5106 	 *		must validate.
5107 	 *
5108 	 * Go to the server and check if the directory has changed, if
5109 	 * it hasn't we are done and can use the dnlc entry.
5110 	 */
5111 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5112 }
5113 
5114 /*
5115  * Go to the server and check if the directory has changed, if
5116  * it hasn't we are done and can use the dnlc entry.  If it
5117  * has changed we get a new copy of its attributes and check
5118  * the access for VEXEC, then relookup the filename and
5119  * get its filehandle and attributes.
5120  *
5121  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5122  *	if the NVERIFY failed we must
5123  *		purge the caches
5124  *		cache new attributes (will set r_time_attr_inval)
5125  *		cache new access
5126  *		recheck VEXEC access
5127  *		add name to dnlc, possibly negative
5128  *		if LOOKUP succeeded
5129  *			cache new attributes
5130  *	else
5131  *		set a new r_time_attr_inval for dvp
5132  *		check to make sure we have access
5133  *
5134  * The vpp returned is the vnode passed in if the directory is valid,
5135  * a new vnode if successful lookup, or NULL on error.
5136  */
5137 static int
5138 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5139 {
5140 	COMPOUND4args_clnt args;
5141 	COMPOUND4res_clnt res;
5142 	fattr4 *ver_fattr;
5143 	fattr4_change dchange;
5144 	int32_t *ptr;
5145 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5146 	nfs_argop4 *argop;
5147 	int doqueue;
5148 	mntinfo4_t *mi;
5149 	nfs4_recov_state_t recov_state;
5150 	hrtime_t t;
5151 	int isdotdot;
5152 	vnode_t *nvp;
5153 	nfs_fh4 *fhp;
5154 	nfs4_sharedfh_t *sfhp;
5155 	nfs4_access_type_t cacc;
5156 	rnode4_t *nrp;
5157 	rnode4_t *drp = VTOR4(dvp);
5158 	nfs4_ga_res_t *garp = NULL;
5159 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5160 
5161 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5162 	ASSERT(nm != NULL);
5163 	ASSERT(nm[0] != '\0');
5164 	ASSERT(dvp->v_type == VDIR);
5165 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5166 	ASSERT(*vpp != NULL);
5167 
5168 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5169 		isdotdot = 1;
5170 		args.ctag = TAG_LOOKUP_VPARENT;
5171 	} else {
5172 		/*
5173 		 * If dvp were a stub, it should have triggered and caused
5174 		 * a mount for us to get this far.
5175 		 */
5176 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5177 
5178 		isdotdot = 0;
5179 		args.ctag = TAG_LOOKUP_VALID;
5180 	}
5181 
5182 	mi = VTOMI4(dvp);
5183 	recov_state.rs_flags = 0;
5184 	recov_state.rs_num_retry_despite_err = 0;
5185 
5186 	nvp = NULL;
5187 
5188 	/* Save the original mount point security information */
5189 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5190 
5191 recov_retry:
5192 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5193 	    &recov_state, NULL);
5194 	if (e.error) {
5195 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5196 		VN_RELE(*vpp);
5197 		*vpp = NULL;
5198 		return (e.error);
5199 	}
5200 
5201 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5202 
5203 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5204 	args.array_len = 7;
5205 	args.array = argop;
5206 
5207 	/* 0. putfh file */
5208 	argop[0].argop = OP_CPUTFH;
5209 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5210 
5211 	/* 1. nverify the change info */
5212 	argop[1].argop = OP_NVERIFY;
5213 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5214 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5215 	ver_fattr->attrlist4 = (char *)&dchange;
5216 	ptr = (int32_t *)&dchange;
5217 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5218 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5219 
5220 	/* 2. getattr directory */
5221 	argop[2].argop = OP_GETATTR;
5222 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5223 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5224 
5225 	/* 3. access directory */
5226 	argop[3].argop = OP_ACCESS;
5227 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5228 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5229 
5230 	/* 4. lookup name */
5231 	if (isdotdot) {
5232 		argop[4].argop = OP_LOOKUPP;
5233 	} else {
5234 		argop[4].argop = OP_CLOOKUP;
5235 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5236 	}
5237 
5238 	/* 5. resulting file handle */
5239 	argop[5].argop = OP_GETFH;
5240 
5241 	/* 6. resulting file attributes */
5242 	argop[6].argop = OP_GETATTR;
5243 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5244 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5245 
5246 	doqueue = 1;
5247 	t = gethrtime();
5248 
5249 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5250 
5251 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5252 		/*
5253 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5254 		 * from this thread, do not go thru the recovery thread since
5255 		 * we need the nm information.
5256 		 *
5257 		 * Not doing dotdot case because there is no specification
5258 		 * for (PUTFH, SECINFO "..") yet.
5259 		 */
5260 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5261 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5262 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5263 				    &recov_state, FALSE);
5264 			else
5265 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5266 				    &recov_state, TRUE);
5267 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5268 			kmem_free(argop, argoplist_size);
5269 			if (!e.error)
5270 				goto recov_retry;
5271 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5272 			VN_RELE(*vpp);
5273 			*vpp = NULL;
5274 			return (e.error);
5275 		}
5276 
5277 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5278 		    OP_LOOKUP, NULL) == FALSE) {
5279 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5280 			    &recov_state, TRUE);
5281 
5282 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5283 			kmem_free(argop, argoplist_size);
5284 			goto recov_retry;
5285 		}
5286 	}
5287 
5288 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5289 
5290 	if (e.error || res.array_len == 0) {
5291 		/*
5292 		 * If e.error isn't set, then reply has no ops (or we couldn't
5293 		 * be here).  The only legal way to reply without an op array
5294 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5295 		 * be in the reply for all other status values.
5296 		 *
5297 		 * For valid replies without an ops array, return ENOTSUP
5298 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5299 		 * return EIO -- don't trust status.
5300 		 */
5301 		if (e.error == 0)
5302 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5303 			    ENOTSUP : EIO;
5304 		VN_RELE(*vpp);
5305 		*vpp = NULL;
5306 		kmem_free(argop, argoplist_size);
5307 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5308 		return (e.error);
5309 	}
5310 
5311 	if (res.status != NFS4ERR_SAME) {
5312 		e.error = geterrno4(res.status);
5313 
5314 		/*
5315 		 * The NVERIFY "failed" so the directory has changed
5316 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5317 		 * cleanly.
5318 		 */
5319 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5320 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5321 			nfs4_purge_stale_fh(e.error, dvp, cr);
5322 			VN_RELE(*vpp);
5323 			*vpp = NULL;
5324 			goto exit;
5325 		}
5326 
5327 		/*
5328 		 * We know the NVERIFY "failed" so we must:
5329 		 *	purge the caches (access and indirectly dnlc if needed)
5330 		 */
5331 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5332 
5333 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5334 			nfs4_purge_stale_fh(e.error, dvp, cr);
5335 			VN_RELE(*vpp);
5336 			*vpp = NULL;
5337 			goto exit;
5338 		}
5339 
5340 		/*
5341 		 * Install new cached attributes for the directory
5342 		 */
5343 		nfs4_attr_cache(dvp,
5344 		    &res.array[2].nfs_resop4_u.opgetattr.ga_res,
5345 		    t, cr, FALSE, NULL);
5346 
5347 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5348 			nfs4_purge_stale_fh(e.error, dvp, cr);
5349 			VN_RELE(*vpp);
5350 			*vpp = NULL;
5351 			e.error = geterrno4(res.status);
5352 			goto exit;
5353 		}
5354 
5355 		/*
5356 		 * Now we know the directory is valid,
5357 		 * cache new directory access
5358 		 */
5359 		nfs4_access_cache(drp,
5360 		    args.array[3].nfs_argop4_u.opaccess.access,
5361 		    res.array[3].nfs_resop4_u.opaccess.access, cr);
5362 
5363 		/*
5364 		 * recheck VEXEC access
5365 		 */
5366 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5367 		if (cacc != NFS4_ACCESS_ALLOWED) {
5368 			/*
5369 			 * Directory permissions might have been revoked
5370 			 */
5371 			if (cacc == NFS4_ACCESS_DENIED) {
5372 				e.error = EACCES;
5373 				VN_RELE(*vpp);
5374 				*vpp = NULL;
5375 				goto exit;
5376 			}
5377 
5378 			/*
5379 			 * Somehow we must not have asked for enough
5380 			 * so try a singleton ACCESS, should never happen.
5381 			 */
5382 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5383 			if (e.error) {
5384 				VN_RELE(*vpp);
5385 				*vpp = NULL;
5386 				goto exit;
5387 			}
5388 		}
5389 
5390 		e.error = geterrno4(res.status);
5391 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5392 			/*
5393 			 * The lookup failed, probably no entry
5394 			 */
5395 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5396 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5397 			} else {
5398 				/*
5399 				 * Might be some other error, so remove
5400 				 * the dnlc entry to make sure we start all
5401 				 * over again, next time.
5402 				 */
5403 				dnlc_remove(dvp, nm);
5404 			}
5405 			VN_RELE(*vpp);
5406 			*vpp = NULL;
5407 			goto exit;
5408 		}
5409 
5410 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5411 			/*
5412 			 * The file exists but we can't get its fh for
5413 			 * some unknown reason.  Remove it from the dnlc
5414 			 * and error out to be safe.
5415 			 */
5416 			dnlc_remove(dvp, nm);
5417 			VN_RELE(*vpp);
5418 			*vpp = NULL;
5419 			goto exit;
5420 		}
5421 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5422 		if (fhp->nfs_fh4_len == 0) {
5423 			/*
5424 			 * The file exists but a bogus fh
5425 			 * some unknown reason.  Remove it from the dnlc
5426 			 * and error out to be safe.
5427 			 */
5428 			e.error = ENOENT;
5429 			dnlc_remove(dvp, nm);
5430 			VN_RELE(*vpp);
5431 			*vpp = NULL;
5432 			goto exit;
5433 		}
5434 		sfhp = sfh4_get(fhp, mi);
5435 
5436 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5437 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5438 
5439 		/*
5440 		 * Make the new rnode
5441 		 */
5442 		if (isdotdot) {
5443 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5444 			if (e.error) {
5445 				sfh4_rele(&sfhp);
5446 				VN_RELE(*vpp);
5447 				*vpp = NULL;
5448 				goto exit;
5449 			}
5450 			/*
5451 			 * XXX if nfs4_make_dotdot uses an existing rnode
5452 			 * XXX it doesn't update the attributes.
5453 			 * XXX for now just save them again to save an OTW
5454 			 */
5455 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5456 		} else {
5457 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5458 			    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5459 			/*
5460 			 * If v_type == VNON, then garp was NULL because
5461 			 * the last op in the compound failed and makenfs4node
5462 			 * could not find the vnode for sfhp. It created
5463 			 * a new vnode, so we have nothing to purge here.
5464 			 */
5465 			if (nvp->v_type == VNON) {
5466 				vattr_t vattr;
5467 
5468 				vattr.va_mask = AT_TYPE;
5469 				/*
5470 				 * N.B. We've already called nfs4_end_fop above.
5471 				 */
5472 				e.error = nfs4getattr(nvp, &vattr, cr);
5473 				if (e.error) {
5474 					sfh4_rele(&sfhp);
5475 					VN_RELE(*vpp);
5476 					*vpp = NULL;
5477 					VN_RELE(nvp);
5478 					goto exit;
5479 				}
5480 				nvp->v_type = vattr.va_type;
5481 			}
5482 		}
5483 		sfh4_rele(&sfhp);
5484 
5485 		nrp = VTOR4(nvp);
5486 		mutex_enter(&nrp->r_statev4_lock);
5487 		if (!nrp->created_v4) {
5488 			mutex_exit(&nrp->r_statev4_lock);
5489 			dnlc_update(dvp, nm, nvp);
5490 		} else
5491 			mutex_exit(&nrp->r_statev4_lock);
5492 
5493 		VN_RELE(*vpp);
5494 		*vpp = nvp;
5495 	} else {
5496 		hrtime_t now;
5497 		hrtime_t delta = 0;
5498 
5499 		e.error = 0;
5500 
5501 		/*
5502 		 * Because the NVERIFY "succeeded" we know that the
5503 		 * directory attributes are still valid
5504 		 * so update r_time_attr_inval
5505 		 */
5506 		now = gethrtime();
5507 		mutex_enter(&drp->r_statelock);
5508 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5509 			delta = now - drp->r_time_attr_saved;
5510 			if (delta < mi->mi_acdirmin)
5511 				delta = mi->mi_acdirmin;
5512 			else if (delta > mi->mi_acdirmax)
5513 				delta = mi->mi_acdirmax;
5514 		}
5515 		drp->r_time_attr_inval = now + delta;
5516 		mutex_exit(&drp->r_statelock);
5517 		dnlc_update(dvp, nm, *vpp);
5518 
5519 		/*
5520 		 * Even though we have a valid directory attr cache
5521 		 * and dnlc entry, we may not have access.
5522 		 * This should almost always hit the cache.
5523 		 */
5524 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5525 		if (e.error) {
5526 			VN_RELE(*vpp);
5527 			*vpp = NULL;
5528 		}
5529 
5530 		if (*vpp == DNLC_NO_VNODE) {
5531 			VN_RELE(*vpp);
5532 			*vpp = NULL;
5533 			e.error = ENOENT;
5534 		}
5535 	}
5536 
5537 exit:
5538 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5539 	kmem_free(argop, argoplist_size);
5540 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5541 	return (e.error);
5542 }
5543 
5544 /*
5545  * We need to go over the wire to lookup the name, but
5546  * while we are there verify the directory has not
5547  * changed but if it has, get new attributes and check access
5548  *
5549  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5550  *					NVERIFY GETATTR ACCESS
5551  *
5552  * With the results:
5553  *	if the NVERIFY failed we must purge the caches, add new attributes,
5554  *		and cache new access.
5555  *	set a new r_time_attr_inval
5556  *	add name to dnlc, possibly negative
5557  *	if LOOKUP succeeded
5558  *		cache new attributes
5559  */
5560 static int
5561 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5562 {
5563 	COMPOUND4args_clnt args;
5564 	COMPOUND4res_clnt res;
5565 	fattr4 *ver_fattr;
5566 	fattr4_change dchange;
5567 	int32_t *ptr;
5568 	nfs4_ga_res_t *garp = NULL;
5569 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5570 	nfs_argop4 *argop;
5571 	int doqueue;
5572 	mntinfo4_t *mi;
5573 	nfs4_recov_state_t recov_state;
5574 	hrtime_t t;
5575 	int isdotdot;
5576 	vnode_t *nvp;
5577 	nfs_fh4 *fhp;
5578 	nfs4_sharedfh_t *sfhp;
5579 	nfs4_access_type_t cacc;
5580 	rnode4_t *nrp;
5581 	rnode4_t *drp = VTOR4(dvp);
5582 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5583 
5584 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5585 	ASSERT(nm != NULL);
5586 	ASSERT(nm[0] != '\0');
5587 	ASSERT(dvp->v_type == VDIR);
5588 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5589 	ASSERT(*vpp == NULL);
5590 
5591 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5592 		isdotdot = 1;
5593 		args.ctag = TAG_LOOKUP_PARENT;
5594 	} else {
5595 		/*
5596 		 * If dvp were a stub, it should have triggered and caused
5597 		 * a mount for us to get this far.
5598 		 */
5599 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5600 
5601 		isdotdot = 0;
5602 		args.ctag = TAG_LOOKUP;
5603 	}
5604 
5605 	mi = VTOMI4(dvp);
5606 	recov_state.rs_flags = 0;
5607 	recov_state.rs_num_retry_despite_err = 0;
5608 
5609 	nvp = NULL;
5610 
5611 	/* Save the original mount point security information */
5612 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5613 
5614 recov_retry:
5615 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5616 	    &recov_state, NULL);
5617 	if (e.error) {
5618 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5619 		return (e.error);
5620 	}
5621 
5622 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5623 
5624 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5625 	args.array_len = 9;
5626 	args.array = argop;
5627 
5628 	/* 0. putfh file */
5629 	argop[0].argop = OP_CPUTFH;
5630 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5631 
5632 	/* 1. savefh for the nverify */
5633 	argop[1].argop = OP_SAVEFH;
5634 
5635 	/* 2. lookup name */
5636 	if (isdotdot) {
5637 		argop[2].argop = OP_LOOKUPP;
5638 	} else {
5639 		argop[2].argop = OP_CLOOKUP;
5640 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5641 	}
5642 
5643 	/* 3. resulting file handle */
5644 	argop[3].argop = OP_GETFH;
5645 
5646 	/* 4. resulting file attributes */
5647 	argop[4].argop = OP_GETATTR;
5648 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5649 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5650 
5651 	/* 5. restorefh back the directory for the nverify */
5652 	argop[5].argop = OP_RESTOREFH;
5653 
5654 	/* 6. nverify the change info */
5655 	argop[6].argop = OP_NVERIFY;
5656 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5657 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5658 	ver_fattr->attrlist4 = (char *)&dchange;
5659 	ptr = (int32_t *)&dchange;
5660 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5661 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5662 
5663 	/* 7. getattr directory */
5664 	argop[7].argop = OP_GETATTR;
5665 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5666 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5667 
5668 	/* 8. access directory */
5669 	argop[8].argop = OP_ACCESS;
5670 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5671 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5672 
5673 	doqueue = 1;
5674 	t = gethrtime();
5675 
5676 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5677 
5678 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5679 		/*
5680 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5681 		 * from this thread, do not go thru the recovery thread since
5682 		 * we need the nm information.
5683 		 *
5684 		 * Not doing dotdot case because there is no specification
5685 		 * for (PUTFH, SECINFO "..") yet.
5686 		 */
5687 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5688 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5689 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5690 				    &recov_state, FALSE);
5691 			else
5692 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5693 				    &recov_state, TRUE);
5694 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5695 			kmem_free(argop, argoplist_size);
5696 			if (!e.error)
5697 				goto recov_retry;
5698 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5699 			return (e.error);
5700 		}
5701 
5702 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5703 		    OP_LOOKUP, NULL) == FALSE) {
5704 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5705 			    &recov_state, TRUE);
5706 
5707 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5708 			kmem_free(argop, argoplist_size);
5709 			goto recov_retry;
5710 		}
5711 	}
5712 
5713 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5714 
5715 	if (e.error || res.array_len == 0) {
5716 		/*
5717 		 * If e.error isn't set, then reply has no ops (or we couldn't
5718 		 * be here).  The only legal way to reply without an op array
5719 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5720 		 * be in the reply for all other status values.
5721 		 *
5722 		 * For valid replies without an ops array, return ENOTSUP
5723 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5724 		 * return EIO -- don't trust status.
5725 		 */
5726 		if (e.error == 0)
5727 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5728 			    ENOTSUP : EIO;
5729 
5730 		kmem_free(argop, argoplist_size);
5731 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5732 		return (e.error);
5733 	}
5734 
5735 	e.error = geterrno4(res.status);
5736 
5737 	/*
5738 	 * The PUTFH and SAVEFH may have failed.
5739 	 */
5740 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5741 	    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5742 		nfs4_purge_stale_fh(e.error, dvp, cr);
5743 		goto exit;
5744 	}
5745 
5746 	/*
5747 	 * Check if the file exists, if it does delay entering
5748 	 * into the dnlc until after we update the directory
5749 	 * attributes so we don't cause it to get purged immediately.
5750 	 */
5751 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5752 		/*
5753 		 * The lookup failed, probably no entry
5754 		 */
5755 		if (e.error == ENOENT && nfs4_lookup_neg_cache)
5756 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5757 		goto exit;
5758 	}
5759 
5760 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5761 		/*
5762 		 * The file exists but we can't get its fh for
5763 		 * some unknown reason. Error out to be safe.
5764 		 */
5765 		goto exit;
5766 	}
5767 
5768 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5769 	if (fhp->nfs_fh4_len == 0) {
5770 		/*
5771 		 * The file exists but a bogus fh
5772 		 * some unknown reason.  Error out to be safe.
5773 		 */
5774 		e.error = EIO;
5775 		goto exit;
5776 	}
5777 	sfhp = sfh4_get(fhp, mi);
5778 
5779 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5780 		sfh4_rele(&sfhp);
5781 		e.error = EIO;
5782 		goto exit;
5783 	}
5784 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5785 
5786 	/*
5787 	 * The RESTOREFH may have failed
5788 	 */
5789 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5790 		sfh4_rele(&sfhp);
5791 		e.error = EIO;
5792 		goto exit;
5793 	}
5794 
5795 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5796 		/*
5797 		 * First make sure the NVERIFY failed as we expected,
5798 		 * if it didn't then be conservative and error out
5799 		 * as we can't trust the directory.
5800 		 */
5801 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5802 			sfh4_rele(&sfhp);
5803 			e.error = EIO;
5804 			goto exit;
5805 		}
5806 
5807 		/*
5808 		 * We know the NVERIFY "failed" so the directory has changed,
5809 		 * so we must:
5810 		 *	purge the caches (access and indirectly dnlc if needed)
5811 		 */
5812 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5813 
5814 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5815 			sfh4_rele(&sfhp);
5816 			goto exit;
5817 		}
5818 		nfs4_attr_cache(dvp,
5819 		    &res.array[7].nfs_resop4_u.opgetattr.ga_res,
5820 		    t, cr, FALSE, NULL);
5821 
5822 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5823 			nfs4_purge_stale_fh(e.error, dvp, cr);
5824 			sfh4_rele(&sfhp);
5825 			e.error = geterrno4(res.status);
5826 			goto exit;
5827 		}
5828 
5829 		/*
5830 		 * Now we know the directory is valid,
5831 		 * cache new directory access
5832 		 */
5833 		nfs4_access_cache(drp,
5834 		    args.array[8].nfs_argop4_u.opaccess.access,
5835 		    res.array[8].nfs_resop4_u.opaccess.access, cr);
5836 
5837 		/*
5838 		 * recheck VEXEC access
5839 		 */
5840 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5841 		if (cacc != NFS4_ACCESS_ALLOWED) {
5842 			/*
5843 			 * Directory permissions might have been revoked
5844 			 */
5845 			if (cacc == NFS4_ACCESS_DENIED) {
5846 				sfh4_rele(&sfhp);
5847 				e.error = EACCES;
5848 				goto exit;
5849 			}
5850 
5851 			/*
5852 			 * Somehow we must not have asked for enough
5853 			 * so try a singleton ACCESS should never happen
5854 			 */
5855 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5856 			if (e.error) {
5857 				sfh4_rele(&sfhp);
5858 				goto exit;
5859 			}
5860 		}
5861 
5862 		e.error = geterrno4(res.status);
5863 	} else {
5864 		hrtime_t now;
5865 		hrtime_t delta = 0;
5866 
5867 		e.error = 0;
5868 
5869 		/*
5870 		 * Because the NVERIFY "succeeded" we know that the
5871 		 * directory attributes are still valid
5872 		 * so update r_time_attr_inval
5873 		 */
5874 		now = gethrtime();
5875 		mutex_enter(&drp->r_statelock);
5876 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5877 			delta = now - drp->r_time_attr_saved;
5878 			if (delta < mi->mi_acdirmin)
5879 				delta = mi->mi_acdirmin;
5880 			else if (delta > mi->mi_acdirmax)
5881 				delta = mi->mi_acdirmax;
5882 		}
5883 		drp->r_time_attr_inval = now + delta;
5884 		mutex_exit(&drp->r_statelock);
5885 
5886 		/*
5887 		 * Even though we have a valid directory attr cache,
5888 		 * we may not have access.
5889 		 * This should almost always hit the cache.
5890 		 */
5891 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5892 		if (e.error) {
5893 			sfh4_rele(&sfhp);
5894 			goto exit;
5895 		}
5896 	}
5897 
5898 	/*
5899 	 * Now we have successfully completed the lookup, if the
5900 	 * directory has changed we now have the valid attributes.
5901 	 * We also know we have directory access.
5902 	 * Create the new rnode and insert it in the dnlc.
5903 	 */
5904 	if (isdotdot) {
5905 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5906 		if (e.error) {
5907 			sfh4_rele(&sfhp);
5908 			goto exit;
5909 		}
5910 		/*
5911 		 * XXX if nfs4_make_dotdot uses an existing rnode
5912 		 * XXX it doesn't update the attributes.
5913 		 * XXX for now just save them again to save an OTW
5914 		 */
5915 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5916 	} else {
5917 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5918 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5919 	}
5920 	sfh4_rele(&sfhp);
5921 
5922 	nrp = VTOR4(nvp);
5923 	mutex_enter(&nrp->r_statev4_lock);
5924 	if (!nrp->created_v4) {
5925 		mutex_exit(&nrp->r_statev4_lock);
5926 		dnlc_update(dvp, nm, nvp);
5927 	} else
5928 		mutex_exit(&nrp->r_statev4_lock);
5929 
5930 	*vpp = nvp;
5931 
5932 exit:
5933 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5934 	kmem_free(argop, argoplist_size);
5935 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5936 	return (e.error);
5937 }
5938 
5939 #ifdef DEBUG
5940 void
5941 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
5942 {
5943 	uint_t i, len;
5944 	zoneid_t zoneid = getzoneid();
5945 	char *s;
5946 
5947 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
5948 	for (i = 0; i < argcnt; i++) {
5949 		nfs_argop4 *op = &argbase[i];
5950 		switch (op->argop) {
5951 		case OP_CPUTFH:
5952 		case OP_PUTFH:
5953 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
5954 			break;
5955 		case OP_PUTROOTFH:
5956 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
5957 			break;
5958 		case OP_CLOOKUP:
5959 			s = op->nfs_argop4_u.opclookup.cname;
5960 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5961 			break;
5962 		case OP_LOOKUP:
5963 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
5964 			    &len, NULL);
5965 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5966 			kmem_free(s, len);
5967 			break;
5968 		case OP_LOOKUPP:
5969 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
5970 			break;
5971 		case OP_GETFH:
5972 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
5973 			break;
5974 		case OP_GETATTR:
5975 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
5976 			break;
5977 		case OP_OPENATTR:
5978 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
5979 			break;
5980 		default:
5981 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
5982 			    op->argop);
5983 			break;
5984 		}
5985 	}
5986 }
5987 #endif
5988 
5989 /*
5990  * nfs4lookup_setup - constructs a multi-lookup compound request.
5991  *
5992  * Given the path "nm1/nm2/.../nmn", the following compound requests
5993  * may be created:
5994  *
5995  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
5996  * is faster, for now.
5997  *
5998  * l4_getattrs indicates the type of compound requested.
5999  *
6000  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
6001  *
6002  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
6003  *
6004  *   total number of ops is n + 1.
6005  *
6006  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
6007  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
6008  *      before the last component, and only get attributes
6009  *      for the last component.  Note that the second-to-last
6010  *	pathname component is XATTR_RPATH, which does NOT go
6011  *	over-the-wire as a lookup.
6012  *
6013  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
6014  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
6015  *
6016  *   and total number of ops is n + 5.
6017  *
6018  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
6019  *      attribute directory: create lookups plus an OPENATTR
6020  *	replacing the last lookup.  Note that the last pathname
6021  *	component is XATTR_RPATH, which does NOT go over-the-wire
6022  *	as a lookup.
6023  *
6024  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
6025  *		Openattr; Getfh; Getattr }
6026  *
6027  *   and total number of ops is n + 5.
6028  *
6029  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6030  *	nodes too.
6031  *
6032  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6033  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6034  *
6035  *   and total number of ops is 3*n + 1.
6036  *
6037  * All cases: returns the index in the arg array of the final LOOKUP op, or
6038  * -1 if no LOOKUPs were used.
6039  */
6040 int
6041 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6042 {
6043 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6044 	nfs_argop4 *argbase, *argop;
6045 	int arglen, argcnt;
6046 	int n = 1;	/* number of components */
6047 	int nga = 1;	/* number of Getattr's in request */
6048 	char c = '\0', *s, *p;
6049 	int lookup_idx = -1;
6050 	int argoplist_size;
6051 
6052 	/* set lookuparg response result to 0 */
6053 	lookupargp->resp->status = NFS4_OK;
6054 
6055 	/* skip leading "/" or "." e.g. ".//./" if there is */
6056 	for (; ; nm++) {
6057 		if (*nm != '/' && *nm != '.')
6058 			break;
6059 
6060 		/* ".." is counted as 1 component */
6061 		if (*nm == '.' && *(nm + 1) == '.')
6062 			break;
6063 	}
6064 
6065 	/*
6066 	 * Find n = number of components - nm must be null terminated
6067 	 * Skip "." components.
6068 	 */
6069 	if (*nm != '\0')
6070 		for (n = 1, s = nm; *s != '\0'; s++) {
6071 			if ((*s == '/') && (*(s + 1) != '/') &&
6072 			    (*(s + 1) != '\0') &&
6073 			    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6074 			    *(s + 2) == '\0')))
6075 				n++;
6076 		}
6077 	else
6078 		n = 0;
6079 
6080 	/*
6081 	 * nga is number of components that need Getfh+Getattr
6082 	 */
6083 	switch (l4_getattrs) {
6084 	case LKP4_NO_ATTRIBUTES:
6085 		nga = 0;
6086 		break;
6087 	case LKP4_ALL_ATTRIBUTES:
6088 		nga = n;
6089 		/*
6090 		 * Always have at least 1 getfh, getattr pair
6091 		 */
6092 		if (nga == 0)
6093 			nga++;
6094 		break;
6095 	case LKP4_LAST_ATTRDIR:
6096 	case LKP4_LAST_NAMED_ATTR:
6097 		nga = n+1;
6098 		break;
6099 	}
6100 
6101 	/*
6102 	 * If change to use the filehandle attr instead of getfh
6103 	 * the following line can be deleted.
6104 	 */
6105 	nga *= 2;
6106 
6107 	/*
6108 	 * calculate number of ops in request as
6109 	 * header + trailer + lookups + getattrs
6110 	 */
6111 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6112 
6113 	argoplist_size = arglen * sizeof (nfs_argop4);
6114 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6115 	lookupargp->argsp->array = argop;
6116 
6117 	argcnt = lookupargp->header_len;
6118 	argop += argcnt;
6119 
6120 	/*
6121 	 * loop and create a lookup op and possibly getattr/getfh for
6122 	 * each component. Skip "." components.
6123 	 */
6124 	for (s = nm; *s != '\0'; s = p) {
6125 		/*
6126 		 * Set up a pathname struct for each component if needed
6127 		 */
6128 		while (*s == '/')
6129 			s++;
6130 		if (*s == '\0')
6131 			break;
6132 
6133 		for (p = s; (*p != '/') && (*p != '\0'); p++)
6134 			;
6135 		c = *p;
6136 		*p = '\0';
6137 
6138 		if (s[0] == '.' && s[1] == '\0') {
6139 			*p = c;
6140 			continue;
6141 		}
6142 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6143 		    strcmp(s, XATTR_RPATH) == 0) {
6144 			/* getfh XXX may not be needed in future */
6145 			argop->argop = OP_GETFH;
6146 			argop++;
6147 			argcnt++;
6148 
6149 			/* getattr */
6150 			argop->argop = OP_GETATTR;
6151 			argop->nfs_argop4_u.opgetattr.attr_request =
6152 			    lookupargp->ga_bits;
6153 			argop->nfs_argop4_u.opgetattr.mi =
6154 			    lookupargp->mi;
6155 			argop++;
6156 			argcnt++;
6157 
6158 			/* openattr */
6159 			argop->argop = OP_OPENATTR;
6160 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6161 		    strcmp(s, XATTR_RPATH) == 0) {
6162 			/* openattr */
6163 			argop->argop = OP_OPENATTR;
6164 			argop++;
6165 			argcnt++;
6166 
6167 			/* getfh XXX may not be needed in future */
6168 			argop->argop = OP_GETFH;
6169 			argop++;
6170 			argcnt++;
6171 
6172 			/* getattr */
6173 			argop->argop = OP_GETATTR;
6174 			argop->nfs_argop4_u.opgetattr.attr_request =
6175 			    lookupargp->ga_bits;
6176 			argop->nfs_argop4_u.opgetattr.mi =
6177 			    lookupargp->mi;
6178 			argop++;
6179 			argcnt++;
6180 			*p = c;
6181 			continue;
6182 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6183 			/* lookupp */
6184 			argop->argop = OP_LOOKUPP;
6185 		} else {
6186 			/* lookup */
6187 			argop->argop = OP_LOOKUP;
6188 			(void) str_to_utf8(s,
6189 			    &argop->nfs_argop4_u.oplookup.objname);
6190 		}
6191 		lookup_idx = argcnt;
6192 		argop++;
6193 		argcnt++;
6194 
6195 		*p = c;
6196 
6197 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6198 			/* getfh XXX may not be needed in future */
6199 			argop->argop = OP_GETFH;
6200 			argop++;
6201 			argcnt++;
6202 
6203 			/* getattr */
6204 			argop->argop = OP_GETATTR;
6205 			argop->nfs_argop4_u.opgetattr.attr_request =
6206 			    lookupargp->ga_bits;
6207 			argop->nfs_argop4_u.opgetattr.mi =
6208 			    lookupargp->mi;
6209 			argop++;
6210 			argcnt++;
6211 		}
6212 	}
6213 
6214 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6215 	    ((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6216 		if (needgetfh) {
6217 			/* stick in a post-lookup getfh */
6218 			argop->argop = OP_GETFH;
6219 			argcnt++;
6220 			argop++;
6221 		}
6222 		/* post-lookup getattr */
6223 		argop->argop = OP_GETATTR;
6224 		argop->nfs_argop4_u.opgetattr.attr_request =
6225 		    lookupargp->ga_bits;
6226 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6227 		argcnt++;
6228 	}
6229 	argcnt += lookupargp->trailer_len;	/* actual op count */
6230 	lookupargp->argsp->array_len = argcnt;
6231 	lookupargp->arglen = arglen;
6232 
6233 #ifdef DEBUG
6234 	if (nfs4_client_lookup_debug)
6235 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6236 #endif
6237 
6238 	return (lookup_idx);
6239 }
6240 
6241 static int
6242 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6243 {
6244 	COMPOUND4args_clnt	args;
6245 	COMPOUND4res_clnt	res;
6246 	GETFH4res	*gf_res = NULL;
6247 	nfs_argop4	argop[4];
6248 	nfs_resop4	*resop = NULL;
6249 	nfs4_sharedfh_t *sfhp;
6250 	hrtime_t t;
6251 	nfs4_error_t	e;
6252 
6253 	rnode4_t	*drp;
6254 	int		doqueue = 1;
6255 	vnode_t		*vp;
6256 	int		needrecov = 0;
6257 	nfs4_recov_state_t recov_state;
6258 
6259 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6260 
6261 	*avp = NULL;
6262 	recov_state.rs_flags = 0;
6263 	recov_state.rs_num_retry_despite_err = 0;
6264 
6265 recov_retry:
6266 	/* COMPOUND: putfh, openattr, getfh, getattr */
6267 	args.array_len = 4;
6268 	args.array = argop;
6269 	args.ctag = TAG_OPENATTR;
6270 
6271 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6272 	if (e.error)
6273 		return (e.error);
6274 
6275 	drp = VTOR4(dvp);
6276 
6277 	/* putfh */
6278 	argop[0].argop = OP_CPUTFH;
6279 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6280 
6281 	/* openattr */
6282 	argop[1].argop = OP_OPENATTR;
6283 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6284 
6285 	/* getfh */
6286 	argop[2].argop = OP_GETFH;
6287 
6288 	/* getattr */
6289 	argop[3].argop = OP_GETATTR;
6290 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6291 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6292 
6293 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6294 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6295 	    rnode4info(drp)));
6296 
6297 	t = gethrtime();
6298 
6299 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6300 
6301 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6302 	if (needrecov) {
6303 		bool_t abort;
6304 
6305 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6306 		    "nfs4openattr: initiating recovery\n"));
6307 
6308 		abort = nfs4_start_recovery(&e,
6309 		    VTOMI4(dvp), dvp, NULL, NULL, NULL,
6310 		    OP_OPENATTR, NULL);
6311 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6312 		if (!e.error) {
6313 			e.error = geterrno4(res.status);
6314 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6315 		}
6316 		if (abort == FALSE)
6317 			goto recov_retry;
6318 		return (e.error);
6319 	}
6320 
6321 	if (e.error) {
6322 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6323 		return (e.error);
6324 	}
6325 
6326 	if (res.status) {
6327 		/*
6328 		 * If OTW errro is NOTSUPP, then it should be
6329 		 * translated to EINVAL.  All Solaris file system
6330 		 * implementations return EINVAL to the syscall layer
6331 		 * when the attrdir cannot be created due to an
6332 		 * implementation restriction or noxattr mount option.
6333 		 */
6334 		if (res.status == NFS4ERR_NOTSUPP) {
6335 			mutex_enter(&drp->r_statelock);
6336 			if (drp->r_xattr_dir)
6337 				VN_RELE(drp->r_xattr_dir);
6338 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6339 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6340 			mutex_exit(&drp->r_statelock);
6341 
6342 			e.error = EINVAL;
6343 		} else {
6344 			e.error = geterrno4(res.status);
6345 		}
6346 
6347 		if (e.error) {
6348 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6349 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6350 			    needrecov);
6351 			return (e.error);
6352 		}
6353 	}
6354 
6355 	resop = &res.array[0];  /* putfh res */
6356 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6357 
6358 	resop = &res.array[1];  /* openattr res */
6359 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6360 
6361 	resop = &res.array[2];  /* getfh res */
6362 	gf_res = &resop->nfs_resop4_u.opgetfh;
6363 	if (gf_res->object.nfs_fh4_len == 0) {
6364 		*avp = NULL;
6365 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6366 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6367 		return (ENOENT);
6368 	}
6369 
6370 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6371 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6372 	    dvp->v_vfsp, t, cr, dvp,
6373 	    fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH));
6374 	sfh4_rele(&sfhp);
6375 
6376 	if (e.error)
6377 		PURGE_ATTRCACHE4(vp);
6378 
6379 	mutex_enter(&vp->v_lock);
6380 	vp->v_flag |= V_XATTRDIR;
6381 	mutex_exit(&vp->v_lock);
6382 
6383 	*avp = vp;
6384 
6385 	mutex_enter(&drp->r_statelock);
6386 	if (drp->r_xattr_dir)
6387 		VN_RELE(drp->r_xattr_dir);
6388 	VN_HOLD(vp);
6389 	drp->r_xattr_dir = vp;
6390 
6391 	/*
6392 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6393 	 * NULL.  xattrs could be created at any time, and we have no
6394 	 * way to update pc4_xattr_exists in the base object if/when
6395 	 * it happens.
6396 	 */
6397 	drp->r_pathconf.pc4_xattr_valid = 0;
6398 
6399 	mutex_exit(&drp->r_statelock);
6400 
6401 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6402 
6403 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6404 
6405 	return (0);
6406 }
6407 
6408 /* ARGSUSED */
6409 static int
6410 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6411 	int mode, vnode_t **vpp, cred_t *cr, int flags, caller_context_t *ct,
6412 	vsecattr_t *vsecp)
6413 {
6414 	int error;
6415 	vnode_t *vp = NULL;
6416 	rnode4_t *rp;
6417 	struct vattr vattr;
6418 	rnode4_t *drp;
6419 	vnode_t *tempvp;
6420 	enum createmode4 createmode;
6421 	bool_t must_trunc = FALSE;
6422 	int	truncating = 0;
6423 
6424 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6425 		return (EPERM);
6426 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6427 		return (EINVAL);
6428 	}
6429 
6430 	/* . and .. have special meaning in the protocol, reject them. */
6431 
6432 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6433 		return (EISDIR);
6434 
6435 	drp = VTOR4(dvp);
6436 
6437 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6438 		return (EINTR);
6439 
6440 top:
6441 	/*
6442 	 * We make a copy of the attributes because the caller does not
6443 	 * expect us to change what va points to.
6444 	 */
6445 	vattr = *va;
6446 
6447 	/*
6448 	 * If the pathname is "", then dvp is the root vnode of
6449 	 * a remote file mounted over a local directory.
6450 	 * All that needs to be done is access
6451 	 * checking and truncation.  Note that we avoid doing
6452 	 * open w/ create because the parent directory might
6453 	 * be in pseudo-fs and the open would fail.
6454 	 */
6455 	if (*nm == '\0') {
6456 		error = 0;
6457 		VN_HOLD(dvp);
6458 		vp = dvp;
6459 		must_trunc = TRUE;
6460 	} else {
6461 		/*
6462 		 * We need to go over the wire, just to be sure whether the
6463 		 * file exists or not.  Using the DNLC can be dangerous in
6464 		 * this case when making a decision regarding existence.
6465 		 */
6466 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6467 	}
6468 
6469 	if (exclusive)
6470 		createmode = EXCLUSIVE4;
6471 	else
6472 		createmode = GUARDED4;
6473 
6474 	/*
6475 	 * error would be set if the file does not exist on the
6476 	 * server, so lets go create it.
6477 	 */
6478 	if (error) {
6479 		goto create_otw;
6480 	}
6481 
6482 	/*
6483 	 * File does exist on the server
6484 	 */
6485 	if (exclusive == EXCL)
6486 		error = EEXIST;
6487 	else if (vp->v_type == VDIR && (mode & VWRITE))
6488 		error = EISDIR;
6489 	else {
6490 		/*
6491 		 * If vnode is a device, create special vnode.
6492 		 */
6493 		if (ISVDEV(vp->v_type)) {
6494 			tempvp = vp;
6495 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6496 			VN_RELE(tempvp);
6497 		}
6498 		if (!(error = VOP_ACCESS(vp, mode, 0, cr, ct))) {
6499 			if ((vattr.va_mask & AT_SIZE) &&
6500 			    vp->v_type == VREG) {
6501 				rp = VTOR4(vp);
6502 				/*
6503 				 * Check here for large file handled
6504 				 * by LF-unaware process (as
6505 				 * ufs_create() does)
6506 				 */
6507 				if (!(flags & FOFFMAX)) {
6508 					mutex_enter(&rp->r_statelock);
6509 					if (rp->r_size > MAXOFF32_T)
6510 						error = EOVERFLOW;
6511 					mutex_exit(&rp->r_statelock);
6512 				}
6513 
6514 				/* if error is set then we need to return */
6515 				if (error) {
6516 					nfs_rw_exit(&drp->r_rwlock);
6517 					VN_RELE(vp);
6518 					return (error);
6519 				}
6520 
6521 				if (must_trunc) {
6522 					vattr.va_mask = AT_SIZE;
6523 					error = nfs4setattr(vp, &vattr, 0, cr,
6524 					    NULL);
6525 				} else {
6526 				/*
6527 				 * we know we have a regular file that already
6528 				 * exists and we may end up truncating the file
6529 				 * as a result of the open_otw, so flush out
6530 				 * any dirty pages for this file first.
6531 				 */
6532 					if (nfs4_has_pages(vp) &&
6533 					    ((rp->r_flags & R4DIRTY) ||
6534 					    rp->r_count > 0 ||
6535 					    rp->r_mapcnt > 0)) {
6536 						error = nfs4_putpage(vp,
6537 						    (offset_t)0, 0, 0, cr, ct);
6538 						if (error && (error == ENOSPC ||
6539 						    error == EDQUOT)) {
6540 							mutex_enter(
6541 							    &rp->r_statelock);
6542 							if (!rp->r_error)
6543 								rp->r_error =
6544 								    error;
6545 							mutex_exit(
6546 							    &rp->r_statelock);
6547 						}
6548 					}
6549 					vattr.va_mask = (AT_SIZE |
6550 					    AT_TYPE | AT_MODE);
6551 					vattr.va_type = VREG;
6552 					createmode = UNCHECKED4;
6553 					truncating = 1;
6554 					goto create_otw;
6555 				}
6556 			}
6557 		}
6558 	}
6559 	nfs_rw_exit(&drp->r_rwlock);
6560 	if (error) {
6561 		VN_RELE(vp);
6562 	} else {
6563 		vnode_t *tvp;
6564 		rnode4_t *trp;
6565 		/*
6566 		 * existing file got truncated, notify.
6567 		 */
6568 		tvp = vp;
6569 		if (vp->v_type == VREG) {
6570 			trp = VTOR4(vp);
6571 			if (IS_SHADOW(vp, trp))
6572 				tvp = RTOV4(trp);
6573 		}
6574 		vnevent_create(tvp, ct);
6575 		*vpp = vp;
6576 	}
6577 	return (error);
6578 
6579 create_otw:
6580 	dnlc_remove(dvp, nm);
6581 
6582 	ASSERT(vattr.va_mask & AT_TYPE);
6583 
6584 	/*
6585 	 * If not a regular file let nfs4mknod() handle it.
6586 	 */
6587 	if (vattr.va_type != VREG) {
6588 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6589 		nfs_rw_exit(&drp->r_rwlock);
6590 		return (error);
6591 	}
6592 
6593 	/*
6594 	 * It _is_ a regular file.
6595 	 */
6596 	ASSERT(vattr.va_mask & AT_MODE);
6597 	if (MANDMODE(vattr.va_mode)) {
6598 		nfs_rw_exit(&drp->r_rwlock);
6599 		return (EACCES);
6600 	}
6601 
6602 	/*
6603 	 * If this happens to be a mknod of a regular file, then flags will
6604 	 * have neither FREAD or FWRITE.  However, we must set at least one
6605 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6606 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6607 	 * set (based on openmode specified by app).
6608 	 */
6609 	if ((flags & (FREAD|FWRITE)) == 0)
6610 		flags |= (FREAD|FWRITE);
6611 
6612 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6613 
6614 	if (vp != NULL) {
6615 		/* if create was successful, throw away the file's pages */
6616 		if (!error && (vattr.va_mask & AT_SIZE))
6617 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6618 			    cr);
6619 		/* release the lookup hold */
6620 		VN_RELE(vp);
6621 		vp = NULL;
6622 	}
6623 
6624 	/*
6625 	 * validate that we opened a regular file. This handles a misbehaving
6626 	 * server that returns an incorrect FH.
6627 	 */
6628 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6629 		error = EISDIR;
6630 		VN_RELE(*vpp);
6631 	}
6632 
6633 	/*
6634 	 * If this is not an exclusive create, then the CREATE
6635 	 * request will be made with the GUARDED mode set.  This
6636 	 * means that the server will return EEXIST if the file
6637 	 * exists.  The file could exist because of a retransmitted
6638 	 * request.  In this case, we recover by starting over and
6639 	 * checking to see whether the file exists.  This second
6640 	 * time through it should and a CREATE request will not be
6641 	 * sent.
6642 	 *
6643 	 * This handles the problem of a dangling CREATE request
6644 	 * which contains attributes which indicate that the file
6645 	 * should be truncated.  This retransmitted request could
6646 	 * possibly truncate valid data in the file if not caught
6647 	 * by the duplicate request mechanism on the server or if
6648 	 * not caught by other means.  The scenario is:
6649 	 *
6650 	 * Client transmits CREATE request with size = 0
6651 	 * Client times out, retransmits request.
6652 	 * Response to the first request arrives from the server
6653 	 *  and the client proceeds on.
6654 	 * Client writes data to the file.
6655 	 * The server now processes retransmitted CREATE request
6656 	 *  and truncates file.
6657 	 *
6658 	 * The use of the GUARDED CREATE request prevents this from
6659 	 * happening because the retransmitted CREATE would fail
6660 	 * with EEXIST and would not truncate the file.
6661 	 */
6662 	if (error == EEXIST && exclusive == NONEXCL) {
6663 #ifdef DEBUG
6664 		nfs4_create_misses++;
6665 #endif
6666 		goto top;
6667 	}
6668 	nfs_rw_exit(&drp->r_rwlock);
6669 	if (truncating && !error && *vpp) {
6670 		vnode_t *tvp;
6671 		rnode4_t *trp;
6672 		/*
6673 		 * existing file got truncated, notify.
6674 		 */
6675 		tvp = *vpp;
6676 		trp = VTOR4(tvp);
6677 		if (IS_SHADOW(tvp, trp))
6678 			tvp = RTOV4(trp);
6679 		vnevent_create(tvp, ct);
6680 	}
6681 	return (error);
6682 }
6683 
6684 /*
6685  * Create compound (for mkdir, mknod, symlink):
6686  * { Putfh <dfh>; Create; Getfh; Getattr }
6687  * It's okay if setattr failed to set gid - this is not considered
6688  * an error, but purge attrs in that case.
6689  */
6690 static int
6691 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6692     vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6693 {
6694 	int need_end_op = FALSE;
6695 	COMPOUND4args_clnt args;
6696 	COMPOUND4res_clnt res, *resp = NULL;
6697 	nfs_argop4 *argop;
6698 	nfs_resop4 *resop;
6699 	int doqueue;
6700 	mntinfo4_t *mi;
6701 	rnode4_t *drp = VTOR4(dvp);
6702 	change_info4 *cinfo;
6703 	GETFH4res *gf_res;
6704 	struct vattr vattr;
6705 	vnode_t *vp;
6706 	fattr4 *crattr;
6707 	bool_t needrecov = FALSE;
6708 	nfs4_recov_state_t recov_state;
6709 	nfs4_sharedfh_t *sfhp = NULL;
6710 	hrtime_t t;
6711 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6712 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6713 	dirattr_info_t dinfo, *dinfop;
6714 	servinfo4_t *svp;
6715 	bitmap4 supp_attrs;
6716 
6717 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6718 	    type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6719 
6720 	mi = VTOMI4(dvp);
6721 
6722 	/*
6723 	 * Make sure we properly deal with setting the right gid
6724 	 * on a new directory to reflect the parent's setgid bit
6725 	 */
6726 	setgid_flag = 0;
6727 	if (type == NF4DIR) {
6728 		struct vattr dva;
6729 
6730 		va->va_mode &= ~VSGID;
6731 		dva.va_mask = AT_MODE | AT_GID;
6732 		if (VOP_GETATTR(dvp, &dva, 0, cr, NULL) == 0) {
6733 
6734 			/*
6735 			 * If the parent's directory has the setgid bit set
6736 			 * _and_ the client was able to get a valid mapping
6737 			 * for the parent dir's owner_group, we want to
6738 			 * append NVERIFY(owner_group == dva.va_gid) and
6739 			 * SETTATTR to the CREATE compound.
6740 			 */
6741 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6742 				setgid_flag = 1;
6743 				va->va_mode |= VSGID;
6744 				if (dva.va_gid != GID_NOBODY) {
6745 					va->va_mask |= AT_GID;
6746 					va->va_gid = dva.va_gid;
6747 				}
6748 			}
6749 		}
6750 	}
6751 
6752 	/*
6753 	 * Create ops:
6754 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6755 	 *	5:restorefh(dir) 6:getattr(dir)
6756 	 *
6757 	 * if (setgid)
6758 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6759 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6760 	 *	8:nverify 9:setattr
6761 	 */
6762 	if (setgid_flag) {
6763 		numops = 10;
6764 		idx_create = 1;
6765 		idx_fattr = 3;
6766 	} else {
6767 		numops = 7;
6768 		idx_create = 2;
6769 		idx_fattr = 4;
6770 	}
6771 
6772 	ASSERT(nfs_zone() == mi->mi_zone);
6773 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6774 		return (EINTR);
6775 	}
6776 	recov_state.rs_flags = 0;
6777 	recov_state.rs_num_retry_despite_err = 0;
6778 
6779 	argoplist_size = numops * sizeof (nfs_argop4);
6780 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6781 
6782 recov_retry:
6783 	if (type == NF4LNK)
6784 		args.ctag = TAG_SYMLINK;
6785 	else if (type == NF4DIR)
6786 		args.ctag = TAG_MKDIR;
6787 	else
6788 		args.ctag = TAG_MKNOD;
6789 
6790 	args.array_len = numops;
6791 	args.array = argop;
6792 
6793 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6794 		nfs_rw_exit(&drp->r_rwlock);
6795 		kmem_free(argop, argoplist_size);
6796 		return (e.error);
6797 	}
6798 	need_end_op = TRUE;
6799 
6800 
6801 	/* 0: putfh directory */
6802 	argop[0].argop = OP_CPUTFH;
6803 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6804 
6805 	/* 1/2: Create object */
6806 	argop[idx_create].argop = OP_CCREATE;
6807 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6808 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6809 	if (type == NF4LNK) {
6810 		/*
6811 		 * symlink, treat name as data
6812 		 */
6813 		ASSERT(data != NULL);
6814 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6815 		    (char *)data;
6816 	}
6817 	if (type == NF4BLK || type == NF4CHR) {
6818 		ASSERT(data != NULL);
6819 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6820 		    *((specdata4 *)data);
6821 	}
6822 
6823 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6824 
6825 	svp = drp->r_server;
6826 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6827 	supp_attrs = svp->sv_supp_attrs;
6828 	nfs_rw_exit(&svp->sv_lock);
6829 
6830 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6831 		nfs_rw_exit(&drp->r_rwlock);
6832 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6833 		e.error = EINVAL;
6834 		kmem_free(argop, argoplist_size);
6835 		return (e.error);
6836 	}
6837 
6838 	/* 2/3: getfh fh of created object */
6839 	ASSERT(idx_create + 1 == idx_fattr - 1);
6840 	argop[idx_create + 1].argop = OP_GETFH;
6841 
6842 	/* 3/4: getattr of new object */
6843 	argop[idx_fattr].argop = OP_GETATTR;
6844 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6845 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6846 
6847 	if (setgid_flag) {
6848 		vattr_t	_v;
6849 
6850 		argop[4].argop = OP_SAVEFH;
6851 
6852 		argop[5].argop = OP_CPUTFH;
6853 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6854 
6855 		argop[6].argop = OP_GETATTR;
6856 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6857 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6858 
6859 		argop[7].argop = OP_RESTOREFH;
6860 
6861 		/*
6862 		 * nverify
6863 		 *
6864 		 * XXX - Revisit the last argument to nfs4_end_op()
6865 		 *	 once 5020486 is fixed.
6866 		 */
6867 		_v.va_mask = AT_GID;
6868 		_v.va_gid = va->va_gid;
6869 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6870 		    supp_attrs)) {
6871 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6872 			nfs_rw_exit(&drp->r_rwlock);
6873 			nfs4_fattr4_free(crattr);
6874 			kmem_free(argop, argoplist_size);
6875 			return (e.error);
6876 		}
6877 
6878 		/*
6879 		 * setattr
6880 		 *
6881 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
6882 		 * so no need for stateid or flags. Also we specify NULL
6883 		 * rp since we're only interested in setting owner_group
6884 		 * attributes.
6885 		 */
6886 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
6887 		    &e.error, 0);
6888 
6889 		if (e.error) {
6890 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6891 			nfs_rw_exit(&drp->r_rwlock);
6892 			nfs4_fattr4_free(crattr);
6893 			nfs4args_verify_free(&argop[8]);
6894 			kmem_free(argop, argoplist_size);
6895 			return (e.error);
6896 		}
6897 	} else {
6898 		argop[1].argop = OP_SAVEFH;
6899 
6900 		argop[5].argop = OP_RESTOREFH;
6901 
6902 		argop[6].argop = OP_GETATTR;
6903 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6904 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6905 	}
6906 
6907 	dnlc_remove(dvp, nm);
6908 
6909 	doqueue = 1;
6910 	t = gethrtime();
6911 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
6912 
6913 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
6914 	if (e.error) {
6915 		PURGE_ATTRCACHE4(dvp);
6916 		if (!needrecov)
6917 			goto out;
6918 	}
6919 
6920 	if (needrecov) {
6921 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
6922 		    OP_CREATE, NULL) == FALSE) {
6923 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6924 			    needrecov);
6925 			need_end_op = FALSE;
6926 			nfs4_fattr4_free(crattr);
6927 			if (setgid_flag) {
6928 				nfs4args_verify_free(&argop[8]);
6929 				nfs4args_setattr_free(&argop[9]);
6930 			}
6931 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6932 			goto recov_retry;
6933 		}
6934 	}
6935 
6936 	resp = &res;
6937 
6938 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
6939 
6940 		if (res.status == NFS4ERR_BADOWNER)
6941 			nfs4_log_badowner(mi, OP_CREATE);
6942 
6943 		e.error = geterrno4(res.status);
6944 
6945 		/*
6946 		 * This check is left over from when create was implemented
6947 		 * using a setattr op (instead of createattrs).  If the
6948 		 * putfh/create/getfh failed, the error was returned.  If
6949 		 * setattr/getattr failed, we keep going.
6950 		 *
6951 		 * It might be better to get rid of the GETFH also, and just
6952 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
6953 		 * Then if any of the operations failed, we could return the
6954 		 * error now, and remove much of the error code below.
6955 		 */
6956 		if (res.array_len <= idx_fattr) {
6957 			/*
6958 			 * Either Putfh, Create or Getfh failed.
6959 			 */
6960 			PURGE_ATTRCACHE4(dvp);
6961 			/*
6962 			 * nfs4_purge_stale_fh() may generate otw calls through
6963 			 * nfs4_invalidate_pages. Hence the need to call
6964 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
6965 			 */
6966 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6967 			    needrecov);
6968 			need_end_op = FALSE;
6969 			nfs4_purge_stale_fh(e.error, dvp, cr);
6970 			goto out;
6971 		}
6972 	}
6973 
6974 	resop = &res.array[idx_create];	/* create res */
6975 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
6976 
6977 	resop = &res.array[idx_create + 1]; /* getfh res */
6978 	gf_res = &resop->nfs_resop4_u.opgetfh;
6979 
6980 	sfhp = sfh4_get(&gf_res->object, mi);
6981 	if (e.error) {
6982 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
6983 		    fn_get(VTOSV(dvp)->sv_name, nm));
6984 		if (vp->v_type == VNON) {
6985 			vattr.va_mask = AT_TYPE;
6986 			/*
6987 			 * Need to call nfs4_end_op before nfs4getattr to avoid
6988 			 * potential nfs4_start_op deadlock. See RFE 4777612.
6989 			 */
6990 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6991 			    needrecov);
6992 			need_end_op = FALSE;
6993 			e.error = nfs4getattr(vp, &vattr, cr);
6994 			if (e.error) {
6995 				VN_RELE(vp);
6996 				*vpp = NULL;
6997 				goto out;
6998 			}
6999 			vp->v_type = vattr.va_type;
7000 		}
7001 		e.error = 0;
7002 	} else {
7003 		*vpp = vp = makenfs4node(sfhp,
7004 		    &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
7005 		    dvp->v_vfsp, t, cr,
7006 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
7007 	}
7008 
7009 	/*
7010 	 * If compound succeeded, then update dir attrs
7011 	 */
7012 	if (res.status == NFS4_OK) {
7013 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
7014 		dinfo.di_cred = cr;
7015 		dinfo.di_time_call = t;
7016 		dinfop = &dinfo;
7017 	} else
7018 		dinfop = NULL;
7019 
7020 	/* Update directory cache attribute, readdir and dnlc caches */
7021 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
7022 
7023 out:
7024 	if (sfhp != NULL)
7025 		sfh4_rele(&sfhp);
7026 	nfs_rw_exit(&drp->r_rwlock);
7027 	nfs4_fattr4_free(crattr);
7028 	if (setgid_flag) {
7029 		nfs4args_verify_free(&argop[8]);
7030 		nfs4args_setattr_free(&argop[9]);
7031 	}
7032 	if (resp)
7033 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7034 	if (need_end_op)
7035 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7036 
7037 	kmem_free(argop, argoplist_size);
7038 	return (e.error);
7039 }
7040 
7041 /* ARGSUSED */
7042 static int
7043 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7044     int mode, vnode_t **vpp, cred_t *cr)
7045 {
7046 	int error;
7047 	vnode_t *vp;
7048 	nfs_ftype4 type;
7049 	specdata4 spec, *specp = NULL;
7050 
7051 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7052 
7053 	switch (va->va_type) {
7054 	case VCHR:
7055 	case VBLK:
7056 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7057 		spec.specdata1 = getmajor(va->va_rdev);
7058 		spec.specdata2 = getminor(va->va_rdev);
7059 		specp = &spec;
7060 		break;
7061 
7062 	case VFIFO:
7063 		type = NF4FIFO;
7064 		break;
7065 	case VSOCK:
7066 		type = NF4SOCK;
7067 		break;
7068 
7069 	default:
7070 		return (EINVAL);
7071 	}
7072 
7073 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7074 	if (error) {
7075 		return (error);
7076 	}
7077 
7078 	/*
7079 	 * This might not be needed any more; special case to deal
7080 	 * with problematic v2/v3 servers.  Since create was unable
7081 	 * to set group correctly, not sure what hope setattr has.
7082 	 */
7083 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7084 		va->va_mask = AT_GID;
7085 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7086 	}
7087 
7088 	/*
7089 	 * If vnode is a device create special vnode
7090 	 */
7091 	if (ISVDEV(vp->v_type)) {
7092 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7093 		VN_RELE(vp);
7094 	} else {
7095 		*vpp = vp;
7096 	}
7097 	return (error);
7098 }
7099 
7100 /*
7101  * Remove requires that the current fh be the target directory.
7102  * After the operation, the current fh is unchanged.
7103  * The compound op structure is:
7104  *      PUTFH(targetdir), REMOVE
7105  *
7106  * Weirdness: if the vnode to be removed is open
7107  * we rename it instead of removing it and nfs_inactive
7108  * will remove the new name.
7109  */
7110 /* ARGSUSED */
7111 static int
7112 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr, caller_context_t *ct, int flags)
7113 {
7114 	COMPOUND4args_clnt args;
7115 	COMPOUND4res_clnt res, *resp = NULL;
7116 	REMOVE4res *rm_res;
7117 	nfs_argop4 argop[3];
7118 	nfs_resop4 *resop;
7119 	vnode_t *vp;
7120 	char *tmpname;
7121 	int doqueue;
7122 	mntinfo4_t *mi;
7123 	rnode4_t *rp;
7124 	rnode4_t *drp;
7125 	int needrecov = 0;
7126 	nfs4_recov_state_t recov_state;
7127 	int isopen;
7128 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7129 	dirattr_info_t dinfo;
7130 
7131 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7132 		return (EPERM);
7133 	drp = VTOR4(dvp);
7134 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7135 		return (EINTR);
7136 
7137 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7138 	if (e.error) {
7139 		nfs_rw_exit(&drp->r_rwlock);
7140 		return (e.error);
7141 	}
7142 
7143 	if (vp->v_type == VDIR) {
7144 		VN_RELE(vp);
7145 		nfs_rw_exit(&drp->r_rwlock);
7146 		return (EISDIR);
7147 	}
7148 
7149 	/*
7150 	 * First just remove the entry from the name cache, as it
7151 	 * is most likely the only entry for this vp.
7152 	 */
7153 	dnlc_remove(dvp, nm);
7154 
7155 	rp = VTOR4(vp);
7156 
7157 	/*
7158 	 * For regular file types, check to see if the file is open by looking
7159 	 * at the open streams.
7160 	 * For all other types, check the reference count on the vnode.  Since
7161 	 * they are not opened OTW they never have an open stream.
7162 	 *
7163 	 * If the file is open, rename it to .nfsXXXX.
7164 	 */
7165 	if (vp->v_type != VREG) {
7166 		/*
7167 		 * If the file has a v_count > 1 then there may be more than one
7168 		 * entry in the name cache due multiple links or an open file,
7169 		 * but we don't have the real reference count so flush all
7170 		 * possible entries.
7171 		 */
7172 		if (vp->v_count > 1)
7173 			dnlc_purge_vp(vp);
7174 
7175 		/*
7176 		 * Now we have the real reference count.
7177 		 */
7178 		isopen = vp->v_count > 1;
7179 	} else {
7180 		mutex_enter(&rp->r_os_lock);
7181 		isopen = list_head(&rp->r_open_streams) != NULL;
7182 		mutex_exit(&rp->r_os_lock);
7183 	}
7184 
7185 	mutex_enter(&rp->r_statelock);
7186 	if (isopen &&
7187 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7188 		mutex_exit(&rp->r_statelock);
7189 		tmpname = newname();
7190 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr, ct);
7191 		if (e.error)
7192 			kmem_free(tmpname, MAXNAMELEN);
7193 		else {
7194 			mutex_enter(&rp->r_statelock);
7195 			if (rp->r_unldvp == NULL) {
7196 				VN_HOLD(dvp);
7197 				rp->r_unldvp = dvp;
7198 				if (rp->r_unlcred != NULL)
7199 					crfree(rp->r_unlcred);
7200 				crhold(cr);
7201 				rp->r_unlcred = cr;
7202 				rp->r_unlname = tmpname;
7203 			} else {
7204 				kmem_free(rp->r_unlname, MAXNAMELEN);
7205 				rp->r_unlname = tmpname;
7206 			}
7207 			mutex_exit(&rp->r_statelock);
7208 		}
7209 		VN_RELE(vp);
7210 		nfs_rw_exit(&drp->r_rwlock);
7211 		return (e.error);
7212 	}
7213 	/*
7214 	 * Actually remove the file/dir
7215 	 */
7216 	mutex_exit(&rp->r_statelock);
7217 
7218 	/*
7219 	 * We need to flush any dirty pages which happen to
7220 	 * be hanging around before removing the file.
7221 	 * This shouldn't happen very often since in NFSv4
7222 	 * we should be close to open consistent.
7223 	 */
7224 	if (nfs4_has_pages(vp) &&
7225 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7226 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, ct);
7227 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7228 			mutex_enter(&rp->r_statelock);
7229 			if (!rp->r_error)
7230 				rp->r_error = e.error;
7231 			mutex_exit(&rp->r_statelock);
7232 		}
7233 	}
7234 
7235 	mi = VTOMI4(dvp);
7236 
7237 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7238 	recov_state.rs_flags = 0;
7239 	recov_state.rs_num_retry_despite_err = 0;
7240 
7241 recov_retry:
7242 	/*
7243 	 * Remove ops: putfh dir; remove
7244 	 */
7245 	args.ctag = TAG_REMOVE;
7246 	args.array_len = 3;
7247 	args.array = argop;
7248 
7249 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7250 	if (e.error) {
7251 		nfs_rw_exit(&drp->r_rwlock);
7252 		VN_RELE(vp);
7253 		return (e.error);
7254 	}
7255 
7256 	/* putfh directory */
7257 	argop[0].argop = OP_CPUTFH;
7258 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7259 
7260 	/* remove */
7261 	argop[1].argop = OP_CREMOVE;
7262 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7263 
7264 	/* getattr dir */
7265 	argop[2].argop = OP_GETATTR;
7266 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7267 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7268 
7269 	doqueue = 1;
7270 	dinfo.di_time_call = gethrtime();
7271 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7272 
7273 	PURGE_ATTRCACHE4(vp);
7274 
7275 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7276 	if (e.error)
7277 		PURGE_ATTRCACHE4(dvp);
7278 
7279 	if (needrecov) {
7280 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7281 		    NULL, NULL, NULL, OP_REMOVE, NULL) == FALSE) {
7282 			if (!e.error)
7283 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7284 				    (caddr_t)&res);
7285 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7286 			    needrecov);
7287 			goto recov_retry;
7288 		}
7289 	}
7290 
7291 	/*
7292 	 * Matching nfs4_end_op() for start_op() above.
7293 	 * There is a path in the code below which calls
7294 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7295 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7296 	 * here to avoid nfs4_start_op() deadlock.
7297 	 */
7298 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7299 
7300 	if (!e.error) {
7301 		resp = &res;
7302 
7303 		if (res.status) {
7304 			e.error = geterrno4(res.status);
7305 			PURGE_ATTRCACHE4(dvp);
7306 			nfs4_purge_stale_fh(e.error, dvp, cr);
7307 		} else {
7308 			resop = &res.array[1];	/* remove res */
7309 			rm_res = &resop->nfs_resop4_u.opremove;
7310 
7311 			dinfo.di_garp =
7312 			    &res.array[2].nfs_resop4_u.opgetattr.ga_res;
7313 			dinfo.di_cred = cr;
7314 
7315 			/* Update directory attr, readdir and dnlc caches */
7316 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7317 			    &dinfo);
7318 		}
7319 	}
7320 	nfs_rw_exit(&drp->r_rwlock);
7321 	if (resp)
7322 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7323 
7324 	if (e.error == 0) {
7325 		vnode_t *tvp;
7326 		rnode4_t *trp;
7327 		trp = VTOR4(vp);
7328 		tvp = vp;
7329 		if (IS_SHADOW(vp, trp))
7330 			tvp = RTOV4(trp);
7331 		vnevent_remove(tvp, dvp, nm, ct);
7332 	}
7333 	VN_RELE(vp);
7334 	return (e.error);
7335 }
7336 
7337 /*
7338  * Link requires that the current fh be the target directory and the
7339  * saved fh be the source fh. After the operation, the current fh is unchanged.
7340  * Thus the compound op structure is:
7341  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7342  *	GETATTR(file)
7343  */
7344 /* ARGSUSED */
7345 static int
7346 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr,
7347     caller_context_t *ct, int flags)
7348 {
7349 	COMPOUND4args_clnt args;
7350 	COMPOUND4res_clnt res, *resp = NULL;
7351 	LINK4res *ln_res;
7352 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7353 	nfs_argop4 *argop;
7354 	nfs_resop4 *resop;
7355 	vnode_t *realvp, *nvp;
7356 	int doqueue;
7357 	mntinfo4_t *mi;
7358 	rnode4_t *tdrp;
7359 	bool_t needrecov = FALSE;
7360 	nfs4_recov_state_t recov_state;
7361 	hrtime_t t;
7362 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7363 	dirattr_info_t dinfo;
7364 
7365 	ASSERT(*tnm != '\0');
7366 	ASSERT(tdvp->v_type == VDIR);
7367 	ASSERT(nfs4_consistent_type(tdvp));
7368 	ASSERT(nfs4_consistent_type(svp));
7369 
7370 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7371 		return (EPERM);
7372 	if (VOP_REALVP(svp, &realvp, ct) == 0) {
7373 		svp = realvp;
7374 		ASSERT(nfs4_consistent_type(svp));
7375 	}
7376 
7377 	tdrp = VTOR4(tdvp);
7378 	mi = VTOMI4(svp);
7379 
7380 	if (!(mi->mi_flags & MI4_LINK)) {
7381 		return (EOPNOTSUPP);
7382 	}
7383 	recov_state.rs_flags = 0;
7384 	recov_state.rs_num_retry_despite_err = 0;
7385 
7386 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7387 		return (EINTR);
7388 
7389 recov_retry:
7390 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7391 
7392 	args.ctag = TAG_LINK;
7393 
7394 	/*
7395 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7396 	 * restorefh; getattr(fl)
7397 	 */
7398 	args.array_len = 7;
7399 	args.array = argop;
7400 
7401 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7402 	if (e.error) {
7403 		kmem_free(argop, argoplist_size);
7404 		nfs_rw_exit(&tdrp->r_rwlock);
7405 		return (e.error);
7406 	}
7407 
7408 	/* 0. putfh file */
7409 	argop[0].argop = OP_CPUTFH;
7410 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7411 
7412 	/* 1. save current fh to free up the space for the dir */
7413 	argop[1].argop = OP_SAVEFH;
7414 
7415 	/* 2. putfh targetdir */
7416 	argop[2].argop = OP_CPUTFH;
7417 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7418 
7419 	/* 3. link: current_fh is targetdir, saved_fh is source */
7420 	argop[3].argop = OP_CLINK;
7421 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7422 
7423 	/* 4. Get attributes of dir */
7424 	argop[4].argop = OP_GETATTR;
7425 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7426 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7427 
7428 	/* 5. If link was successful, restore current vp to file */
7429 	argop[5].argop = OP_RESTOREFH;
7430 
7431 	/* 6. Get attributes of linked object */
7432 	argop[6].argop = OP_GETATTR;
7433 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7434 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7435 
7436 	dnlc_remove(tdvp, tnm);
7437 
7438 	doqueue = 1;
7439 	t = gethrtime();
7440 
7441 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7442 
7443 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7444 	if (e.error != 0 && !needrecov) {
7445 		PURGE_ATTRCACHE4(tdvp);
7446 		PURGE_ATTRCACHE4(svp);
7447 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7448 		goto out;
7449 	}
7450 
7451 	if (needrecov) {
7452 		bool_t abort;
7453 
7454 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7455 		    NULL, NULL, OP_LINK, NULL);
7456 		if (abort == FALSE) {
7457 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7458 			    needrecov);
7459 			kmem_free(argop, argoplist_size);
7460 			if (!e.error)
7461 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7462 				    (caddr_t)&res);
7463 			goto recov_retry;
7464 		} else {
7465 			if (e.error != 0) {
7466 				PURGE_ATTRCACHE4(tdvp);
7467 				PURGE_ATTRCACHE4(svp);
7468 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7469 				    &recov_state, needrecov);
7470 				goto out;
7471 			}
7472 			/* fall through for res.status case */
7473 		}
7474 	}
7475 
7476 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7477 
7478 	resp = &res;
7479 	if (res.status) {
7480 		/* If link succeeded, then don't return error */
7481 		e.error = geterrno4(res.status);
7482 		if (res.array_len <= 4) {
7483 			/*
7484 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7485 			 */
7486 			PURGE_ATTRCACHE4(svp);
7487 			PURGE_ATTRCACHE4(tdvp);
7488 			if (e.error == EOPNOTSUPP) {
7489 				mutex_enter(&mi->mi_lock);
7490 				mi->mi_flags &= ~MI4_LINK;
7491 				mutex_exit(&mi->mi_lock);
7492 			}
7493 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7494 			/* XXX-LP */
7495 			if (e.error == EISDIR && crgetuid(cr) != 0)
7496 				e.error = EPERM;
7497 			goto out;
7498 		}
7499 	}
7500 
7501 	/* either no error or one of the postop getattr failed */
7502 
7503 	/*
7504 	 * XXX - if LINK succeeded, but no attrs were returned for link
7505 	 * file, purge its cache.
7506 	 *
7507 	 * XXX Perform a simplified version of wcc checking. Instead of
7508 	 * have another getattr to get pre-op, just purge cache if
7509 	 * any of the ops prior to and including the getattr failed.
7510 	 * If the getattr succeeded then update the attrcache accordingly.
7511 	 */
7512 
7513 	/*
7514 	 * update cache with link file postattrs.
7515 	 * Note: at this point resop points to link res.
7516 	 */
7517 	resop = &res.array[3];	/* link res */
7518 	ln_res = &resop->nfs_resop4_u.oplink;
7519 	if (res.status == NFS4_OK)
7520 		e.error = nfs4_update_attrcache(res.status,
7521 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res,
7522 		    t, svp, cr);
7523 
7524 	/*
7525 	 * Call makenfs4node to create the new shadow vp for tnm.
7526 	 * We pass NULL attrs because we just cached attrs for
7527 	 * the src object.  All we're trying to accomplish is to
7528 	 * to create the new shadow vnode.
7529 	 */
7530 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7531 	    tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm));
7532 
7533 	/* Update target cache attribute, readdir and dnlc caches */
7534 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7535 	dinfo.di_time_call = t;
7536 	dinfo.di_cred = cr;
7537 
7538 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7539 	ASSERT(nfs4_consistent_type(tdvp));
7540 	ASSERT(nfs4_consistent_type(svp));
7541 	ASSERT(nfs4_consistent_type(nvp));
7542 	VN_RELE(nvp);
7543 
7544 	if (!e.error) {
7545 		vnode_t *tvp;
7546 		rnode4_t *trp;
7547 		/*
7548 		 * Notify the source file of this link operation.
7549 		 */
7550 		trp = VTOR4(svp);
7551 		tvp = svp;
7552 		if (IS_SHADOW(svp, trp))
7553 			tvp = RTOV4(trp);
7554 		vnevent_link(tvp, ct);
7555 	}
7556 out:
7557 	kmem_free(argop, argoplist_size);
7558 	if (resp)
7559 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7560 
7561 	nfs_rw_exit(&tdrp->r_rwlock);
7562 
7563 	return (e.error);
7564 }
7565 
7566 /* ARGSUSED */
7567 static int
7568 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7569     caller_context_t *ct, int flags)
7570 {
7571 	vnode_t *realvp;
7572 
7573 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7574 		return (EPERM);
7575 	if (VOP_REALVP(ndvp, &realvp, ct) == 0)
7576 		ndvp = realvp;
7577 
7578 	return (nfs4rename(odvp, onm, ndvp, nnm, cr, ct));
7579 }
7580 
7581 /*
7582  * nfs4rename does the real work of renaming in NFS Version 4.
7583  *
7584  * A file handle is considered volatile for renaming purposes if either
7585  * of the volatile bits are turned on. However, the compound may differ
7586  * based on the likelihood of the filehandle to change during rename.
7587  */
7588 static int
7589 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7590     caller_context_t *ct)
7591 {
7592 	int error;
7593 	mntinfo4_t *mi;
7594 	vnode_t *nvp = NULL;
7595 	vnode_t *ovp = NULL;
7596 	char *tmpname = NULL;
7597 	rnode4_t *rp;
7598 	rnode4_t *odrp;
7599 	rnode4_t *ndrp;
7600 	int did_link = 0;
7601 	int do_link = 1;
7602 	nfsstat4 stat = NFS4_OK;
7603 
7604 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7605 	ASSERT(nfs4_consistent_type(odvp));
7606 	ASSERT(nfs4_consistent_type(ndvp));
7607 
7608 	if (onm[0] == '.' && (onm[1] == '\0' ||
7609 	    (onm[1] == '.' && onm[2] == '\0')))
7610 		return (EINVAL);
7611 
7612 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7613 	    (nnm[1] == '.' && nnm[2] == '\0')))
7614 		return (EINVAL);
7615 
7616 	odrp = VTOR4(odvp);
7617 	ndrp = VTOR4(ndvp);
7618 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7619 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7620 			return (EINTR);
7621 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7622 			nfs_rw_exit(&odrp->r_rwlock);
7623 			return (EINTR);
7624 		}
7625 	} else {
7626 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7627 			return (EINTR);
7628 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7629 			nfs_rw_exit(&ndrp->r_rwlock);
7630 			return (EINTR);
7631 		}
7632 	}
7633 
7634 	/*
7635 	 * Lookup the target file.  If it exists, it needs to be
7636 	 * checked to see whether it is a mount point and whether
7637 	 * it is active (open).
7638 	 */
7639 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7640 	if (!error) {
7641 		int	isactive;
7642 
7643 		ASSERT(nfs4_consistent_type(nvp));
7644 		/*
7645 		 * If this file has been mounted on, then just
7646 		 * return busy because renaming to it would remove
7647 		 * the mounted file system from the name space.
7648 		 */
7649 		if (vn_ismntpt(nvp)) {
7650 			VN_RELE(nvp);
7651 			nfs_rw_exit(&odrp->r_rwlock);
7652 			nfs_rw_exit(&ndrp->r_rwlock);
7653 			return (EBUSY);
7654 		}
7655 
7656 		/*
7657 		 * First just remove the entry from the name cache, as it
7658 		 * is most likely the only entry for this vp.
7659 		 */
7660 		dnlc_remove(ndvp, nnm);
7661 
7662 		rp = VTOR4(nvp);
7663 
7664 		if (nvp->v_type != VREG) {
7665 			/*
7666 			 * Purge the name cache of all references to this vnode
7667 			 * so that we can check the reference count to infer
7668 			 * whether it is active or not.
7669 			 */
7670 			if (nvp->v_count > 1)
7671 				dnlc_purge_vp(nvp);
7672 
7673 			isactive = nvp->v_count > 1;
7674 		} else {
7675 			mutex_enter(&rp->r_os_lock);
7676 			isactive = list_head(&rp->r_open_streams) != NULL;
7677 			mutex_exit(&rp->r_os_lock);
7678 		}
7679 
7680 		/*
7681 		 * If the vnode is active and is not a directory,
7682 		 * arrange to rename it to a
7683 		 * temporary file so that it will continue to be
7684 		 * accessible.  This implements the "unlink-open-file"
7685 		 * semantics for the target of a rename operation.
7686 		 * Before doing this though, make sure that the
7687 		 * source and target files are not already the same.
7688 		 */
7689 		if (isactive && nvp->v_type != VDIR) {
7690 			/*
7691 			 * Lookup the source name.
7692 			 */
7693 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7694 
7695 			/*
7696 			 * The source name *should* already exist.
7697 			 */
7698 			if (error) {
7699 				VN_RELE(nvp);
7700 				nfs_rw_exit(&odrp->r_rwlock);
7701 				nfs_rw_exit(&ndrp->r_rwlock);
7702 				return (error);
7703 			}
7704 
7705 			ASSERT(nfs4_consistent_type(ovp));
7706 
7707 			/*
7708 			 * Compare the two vnodes.  If they are the same,
7709 			 * just release all held vnodes and return success.
7710 			 */
7711 			if (VN_CMP(ovp, nvp)) {
7712 				VN_RELE(ovp);
7713 				VN_RELE(nvp);
7714 				nfs_rw_exit(&odrp->r_rwlock);
7715 				nfs_rw_exit(&ndrp->r_rwlock);
7716 				return (0);
7717 			}
7718 
7719 			/*
7720 			 * Can't mix and match directories and non-
7721 			 * directories in rename operations.  We already
7722 			 * know that the target is not a directory.  If
7723 			 * the source is a directory, return an error.
7724 			 */
7725 			if (ovp->v_type == VDIR) {
7726 				VN_RELE(ovp);
7727 				VN_RELE(nvp);
7728 				nfs_rw_exit(&odrp->r_rwlock);
7729 				nfs_rw_exit(&ndrp->r_rwlock);
7730 				return (ENOTDIR);
7731 			}
7732 link_call:
7733 			/*
7734 			 * The target file exists, is not the same as
7735 			 * the source file, and is active.  We first
7736 			 * try to Link it to a temporary filename to
7737 			 * avoid having the server removing the file
7738 			 * completely (which could cause data loss to
7739 			 * the user's POV in the event the Rename fails
7740 			 * -- see bug 1165874).
7741 			 */
7742 			/*
7743 			 * The do_link and did_link booleans are
7744 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7745 			 * returned for the Rename.  Some servers can
7746 			 * not Rename over an Open file, so they return
7747 			 * this error.  The client needs to Remove the
7748 			 * newly created Link and do two Renames, just
7749 			 * as if the server didn't support LINK.
7750 			 */
7751 			tmpname = newname();
7752 			error = 0;
7753 
7754 			if (do_link) {
7755 				error = nfs4_link(ndvp, nvp, tmpname, cr,
7756 				    NULL, 0);
7757 			}
7758 			if (error == EOPNOTSUPP || !do_link) {
7759 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7760 				    cr, NULL, 0);
7761 				did_link = 0;
7762 			} else {
7763 				did_link = 1;
7764 			}
7765 			if (error) {
7766 				kmem_free(tmpname, MAXNAMELEN);
7767 				VN_RELE(ovp);
7768 				VN_RELE(nvp);
7769 				nfs_rw_exit(&odrp->r_rwlock);
7770 				nfs_rw_exit(&ndrp->r_rwlock);
7771 				return (error);
7772 			}
7773 
7774 			mutex_enter(&rp->r_statelock);
7775 			if (rp->r_unldvp == NULL) {
7776 				VN_HOLD(ndvp);
7777 				rp->r_unldvp = ndvp;
7778 				if (rp->r_unlcred != NULL)
7779 					crfree(rp->r_unlcred);
7780 				crhold(cr);
7781 				rp->r_unlcred = cr;
7782 				rp->r_unlname = tmpname;
7783 			} else {
7784 				if (rp->r_unlname)
7785 					kmem_free(rp->r_unlname, MAXNAMELEN);
7786 				rp->r_unlname = tmpname;
7787 			}
7788 			mutex_exit(&rp->r_statelock);
7789 		}
7790 
7791 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7792 
7793 		ASSERT(nfs4_consistent_type(nvp));
7794 	}
7795 
7796 	if (ovp == NULL) {
7797 		/*
7798 		 * When renaming directories to be a subdirectory of a
7799 		 * different parent, the dnlc entry for ".." will no
7800 		 * longer be valid, so it must be removed.
7801 		 *
7802 		 * We do a lookup here to determine whether we are renaming
7803 		 * a directory and we need to check if we are renaming
7804 		 * an unlinked file.  This might have already been done
7805 		 * in previous code, so we check ovp == NULL to avoid
7806 		 * doing it twice.
7807 		 */
7808 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7809 		/*
7810 		 * The source name *should* already exist.
7811 		 */
7812 		if (error) {
7813 			nfs_rw_exit(&odrp->r_rwlock);
7814 			nfs_rw_exit(&ndrp->r_rwlock);
7815 			if (nvp) {
7816 				VN_RELE(nvp);
7817 			}
7818 			return (error);
7819 		}
7820 		ASSERT(ovp != NULL);
7821 		ASSERT(nfs4_consistent_type(ovp));
7822 	}
7823 
7824 	/*
7825 	 * Is the object being renamed a dir, and if so, is
7826 	 * it being renamed to a child of itself?  The underlying
7827 	 * fs should ultimately return EINVAL for this case;
7828 	 * however, buggy beta non-Solaris NFSv4 servers at
7829 	 * interop testing events have allowed this behavior,
7830 	 * and it caused our client to panic due to a recursive
7831 	 * mutex_enter in fn_move.
7832 	 *
7833 	 * The tedious locking in fn_move could be changed to
7834 	 * deal with this case, and the client could avoid the
7835 	 * panic; however, the client would just confuse itself
7836 	 * later and misbehave.  A better way to handle the broken
7837 	 * server is to detect this condition and return EINVAL
7838 	 * without ever sending the the bogus rename to the server.
7839 	 * We know the rename is invalid -- just fail it now.
7840 	 */
7841 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7842 		VN_RELE(ovp);
7843 		nfs_rw_exit(&odrp->r_rwlock);
7844 		nfs_rw_exit(&ndrp->r_rwlock);
7845 		if (nvp) {
7846 			VN_RELE(nvp);
7847 		}
7848 		return (EINVAL);
7849 	}
7850 
7851 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7852 
7853 	/*
7854 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7855 	 * possible for the filehandle to change due to the rename.
7856 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7857 	 * the fh will not change because of the rename, but we still need
7858 	 * to update its rnode entry with the new name for
7859 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7860 	 * has no effect on these for now, but for future improvements,
7861 	 * we might want to use it too to simplify handling of files
7862 	 * that are open with that flag on. (XXX)
7863 	 */
7864 	mi = VTOMI4(odvp);
7865 	if (NFS4_VOLATILE_FH(mi))
7866 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7867 		    &stat);
7868 	else
7869 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7870 		    &stat);
7871 
7872 	ASSERT(nfs4_consistent_type(odvp));
7873 	ASSERT(nfs4_consistent_type(ndvp));
7874 	ASSERT(nfs4_consistent_type(ovp));
7875 
7876 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
7877 		do_link = 0;
7878 		/*
7879 		 * Before the 'link_call' code, we did a nfs4_lookup
7880 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
7881 		 * call we call VN_RELE to match that hold.  We need
7882 		 * to place an additional VN_HOLD here since we will
7883 		 * be hitting that VN_RELE again.
7884 		 */
7885 		VN_HOLD(nvp);
7886 
7887 		(void) nfs4_remove(ndvp, tmpname, cr, NULL, 0);
7888 
7889 		/* Undo the unlinked file naming stuff we just did */
7890 		mutex_enter(&rp->r_statelock);
7891 		if (rp->r_unldvp) {
7892 			VN_RELE(ndvp);
7893 			rp->r_unldvp = NULL;
7894 			if (rp->r_unlcred != NULL)
7895 				crfree(rp->r_unlcred);
7896 			rp->r_unlcred = NULL;
7897 			/* rp->r_unlanme points to tmpname */
7898 			if (rp->r_unlname)
7899 				kmem_free(rp->r_unlname, MAXNAMELEN);
7900 			rp->r_unlname = NULL;
7901 		}
7902 		mutex_exit(&rp->r_statelock);
7903 
7904 		if (nvp) {
7905 			VN_RELE(nvp);
7906 		}
7907 		goto link_call;
7908 	}
7909 
7910 	if (error) {
7911 		VN_RELE(ovp);
7912 		nfs_rw_exit(&odrp->r_rwlock);
7913 		nfs_rw_exit(&ndrp->r_rwlock);
7914 		if (nvp) {
7915 			VN_RELE(nvp);
7916 		}
7917 		return (error);
7918 	}
7919 
7920 	/*
7921 	 * when renaming directories to be a subdirectory of a
7922 	 * different parent, the dnlc entry for ".." will no
7923 	 * longer be valid, so it must be removed
7924 	 */
7925 	rp = VTOR4(ovp);
7926 	if (ndvp != odvp) {
7927 		if (ovp->v_type == VDIR) {
7928 			dnlc_remove(ovp, "..");
7929 			if (rp->r_dir != NULL)
7930 				nfs4_purge_rddir_cache(ovp);
7931 		}
7932 	}
7933 
7934 	/*
7935 	 * If we are renaming the unlinked file, update the
7936 	 * r_unldvp and r_unlname as needed.
7937 	 */
7938 	mutex_enter(&rp->r_statelock);
7939 	if (rp->r_unldvp != NULL) {
7940 		if (strcmp(rp->r_unlname, onm) == 0) {
7941 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
7942 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
7943 			if (ndvp != rp->r_unldvp) {
7944 				VN_RELE(rp->r_unldvp);
7945 				rp->r_unldvp = ndvp;
7946 				VN_HOLD(ndvp);
7947 			}
7948 		}
7949 	}
7950 	mutex_exit(&rp->r_statelock);
7951 
7952 	/*
7953 	 * Notify the rename vnevents to source vnode, and to the target
7954 	 * vnode if it already existed.
7955 	 */
7956 	if (error == 0) {
7957 		vnode_t *tvp;
7958 		rnode4_t *trp;
7959 		/*
7960 		 * Notify the vnode. Each links is represented by
7961 		 * a different vnode, in nfsv4.
7962 		 */
7963 		if (nvp) {
7964 			trp = VTOR4(nvp);
7965 			tvp = nvp;
7966 			if (IS_SHADOW(nvp, trp))
7967 				tvp = RTOV4(trp);
7968 			vnevent_rename_dest(tvp, ndvp, nnm, ct);
7969 		}
7970 
7971 		/*
7972 		 * if the source and destination directory are not the
7973 		 * same notify the destination directory.
7974 		 */
7975 		if (VTOR4(odvp) != VTOR4(ndvp)) {
7976 			trp = VTOR4(ndvp);
7977 			tvp = ndvp;
7978 			if (IS_SHADOW(ndvp, trp))
7979 				tvp = RTOV4(trp);
7980 			vnevent_rename_dest_dir(tvp, ct);
7981 		}
7982 
7983 		trp = VTOR4(ovp);
7984 		tvp = ovp;
7985 		if (IS_SHADOW(ovp, trp))
7986 			tvp = RTOV4(trp);
7987 		vnevent_rename_src(tvp, odvp, onm, ct);
7988 	}
7989 
7990 	if (nvp) {
7991 		VN_RELE(nvp);
7992 	}
7993 	VN_RELE(ovp);
7994 
7995 	nfs_rw_exit(&odrp->r_rwlock);
7996 	nfs_rw_exit(&ndrp->r_rwlock);
7997 
7998 	return (error);
7999 }
8000 
8001 /*
8002  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
8003  * when it is known that the filehandle is persistent through rename.
8004  *
8005  * Rename requires that the current fh be the target directory and the
8006  * saved fh be the source directory. After the operation, the current fh
8007  * is unchanged.
8008  * The compound op structure for persistent fh rename is:
8009  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
8010  * Rather than bother with the directory postop args, we'll simply
8011  * update that a change occurred in the cache, so no post-op getattrs.
8012  */
8013 static int
8014 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
8015     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8016 {
8017 	COMPOUND4args_clnt args;
8018 	COMPOUND4res_clnt res, *resp = NULL;
8019 	nfs_argop4 *argop;
8020 	nfs_resop4 *resop;
8021 	int doqueue, argoplist_size;
8022 	mntinfo4_t *mi;
8023 	rnode4_t *odrp = VTOR4(odvp);
8024 	rnode4_t *ndrp = VTOR4(ndvp);
8025 	RENAME4res *rn_res;
8026 	bool_t needrecov;
8027 	nfs4_recov_state_t recov_state;
8028 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8029 	dirattr_info_t dinfo, *dinfop;
8030 
8031 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8032 
8033 	recov_state.rs_flags = 0;
8034 	recov_state.rs_num_retry_despite_err = 0;
8035 
8036 	/*
8037 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
8038 	 *
8039 	 * If source/target are different dirs, then append putfh(src); getattr
8040 	 */
8041 	args.array_len = (odvp == ndvp) ? 5 : 7;
8042 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8043 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8044 
8045 recov_retry:
8046 	*statp = NFS4_OK;
8047 
8048 	/* No need to Lookup the file, persistent fh */
8049 	args.ctag = TAG_RENAME;
8050 
8051 	mi = VTOMI4(odvp);
8052 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8053 	if (e.error) {
8054 		kmem_free(argop, argoplist_size);
8055 		return (e.error);
8056 	}
8057 
8058 	/* 0: putfh source directory */
8059 	argop[0].argop = OP_CPUTFH;
8060 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8061 
8062 	/* 1: Save source fh to free up current for target */
8063 	argop[1].argop = OP_SAVEFH;
8064 
8065 	/* 2: putfh targetdir */
8066 	argop[2].argop = OP_CPUTFH;
8067 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8068 
8069 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8070 	argop[3].argop = OP_CRENAME;
8071 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8072 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8073 
8074 	/* 4: getattr (targetdir) */
8075 	argop[4].argop = OP_GETATTR;
8076 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8077 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8078 
8079 	if (ndvp != odvp) {
8080 
8081 		/* 5: putfh (sourcedir) */
8082 		argop[5].argop = OP_CPUTFH;
8083 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8084 
8085 		/* 6: getattr (sourcedir) */
8086 		argop[6].argop = OP_GETATTR;
8087 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8088 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8089 	}
8090 
8091 	dnlc_remove(odvp, onm);
8092 	dnlc_remove(ndvp, nnm);
8093 
8094 	doqueue = 1;
8095 	dinfo.di_time_call = gethrtime();
8096 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8097 
8098 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8099 	if (e.error) {
8100 		PURGE_ATTRCACHE4(odvp);
8101 		PURGE_ATTRCACHE4(ndvp);
8102 	} else {
8103 		*statp = res.status;
8104 	}
8105 
8106 	if (needrecov) {
8107 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8108 		    OP_RENAME, NULL) == FALSE) {
8109 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8110 			if (!e.error)
8111 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8112 				    (caddr_t)&res);
8113 			goto recov_retry;
8114 		}
8115 	}
8116 
8117 	if (!e.error) {
8118 		resp = &res;
8119 		/*
8120 		 * as long as OP_RENAME
8121 		 */
8122 		if (res.status != NFS4_OK && res.array_len <= 4) {
8123 			e.error = geterrno4(res.status);
8124 			PURGE_ATTRCACHE4(odvp);
8125 			PURGE_ATTRCACHE4(ndvp);
8126 			/*
8127 			 * System V defines rename to return EEXIST, not
8128 			 * ENOTEMPTY if the target directory is not empty.
8129 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8130 			 * which geterrno4 maps to ENOTEMPTY.
8131 			 */
8132 			if (e.error == ENOTEMPTY)
8133 				e.error = EEXIST;
8134 		} else {
8135 
8136 			resop = &res.array[3];	/* rename res */
8137 			rn_res = &resop->nfs_resop4_u.oprename;
8138 
8139 			if (res.status == NFS4_OK) {
8140 				/*
8141 				 * Update target attribute, readdir and dnlc
8142 				 * caches.
8143 				 */
8144 				dinfo.di_garp =
8145 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8146 				dinfo.di_cred = cr;
8147 				dinfop = &dinfo;
8148 			} else
8149 				dinfop = NULL;
8150 
8151 			nfs4_update_dircaches(&rn_res->target_cinfo,
8152 			    ndvp, NULL, NULL, dinfop);
8153 
8154 			/*
8155 			 * Update source attribute, readdir and dnlc caches
8156 			 *
8157 			 */
8158 			if (ndvp != odvp) {
8159 				if (dinfop)
8160 					dinfo.di_garp =
8161 					    &(res.array[6].nfs_resop4_u.
8162 					    opgetattr.ga_res);
8163 
8164 				nfs4_update_dircaches(&rn_res->source_cinfo,
8165 				    odvp, NULL, NULL, dinfop);
8166 			}
8167 
8168 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8169 			    nnm);
8170 		}
8171 	}
8172 
8173 	if (resp)
8174 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8175 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8176 	kmem_free(argop, argoplist_size);
8177 
8178 	return (e.error);
8179 }
8180 
8181 /*
8182  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8183  * it is possible for the filehandle to change due to the rename.
8184  *
8185  * The compound req in this case includes a post-rename lookup and getattr
8186  * to ensure that we have the correct fh and attributes for the object.
8187  *
8188  * Rename requires that the current fh be the target directory and the
8189  * saved fh be the source directory. After the operation, the current fh
8190  * is unchanged.
8191  *
8192  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8193  * update the filehandle for the renamed object.  We also get the old
8194  * filehandle for historical reasons; this should be taken out sometime.
8195  * This results in a rather cumbersome compound...
8196  *
8197  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8198  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8199  *
8200  */
8201 static int
8202 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8203     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8204 {
8205 	COMPOUND4args_clnt args;
8206 	COMPOUND4res_clnt res, *resp = NULL;
8207 	int argoplist_size;
8208 	nfs_argop4 *argop;
8209 	nfs_resop4 *resop;
8210 	int doqueue;
8211 	mntinfo4_t *mi;
8212 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8213 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8214 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8215 	RENAME4res *rn_res;
8216 	GETFH4res *ngf_res;
8217 	bool_t needrecov;
8218 	nfs4_recov_state_t recov_state;
8219 	hrtime_t t;
8220 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8221 	dirattr_info_t dinfo, *dinfop = &dinfo;
8222 
8223 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8224 
8225 	recov_state.rs_flags = 0;
8226 	recov_state.rs_num_retry_despite_err = 0;
8227 
8228 recov_retry:
8229 	*statp = NFS4_OK;
8230 
8231 	/*
8232 	 * There is a window between the RPC and updating the path and
8233 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8234 	 * code, so that it doesn't try to use the old path during that
8235 	 * window.
8236 	 */
8237 	mutex_enter(&orp->r_statelock);
8238 	while (orp->r_flags & R4RECEXPFH) {
8239 		klwp_t *lwp = ttolwp(curthread);
8240 
8241 		if (lwp != NULL)
8242 			lwp->lwp_nostop++;
8243 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8244 			mutex_exit(&orp->r_statelock);
8245 			if (lwp != NULL)
8246 				lwp->lwp_nostop--;
8247 			return (EINTR);
8248 		}
8249 		if (lwp != NULL)
8250 			lwp->lwp_nostop--;
8251 	}
8252 	orp->r_flags |= R4RECEXPFH;
8253 	mutex_exit(&orp->r_statelock);
8254 
8255 	mi = VTOMI4(odvp);
8256 
8257 	args.ctag = TAG_RENAME_VFH;
8258 	args.array_len = (odvp == ndvp) ? 10 : 12;
8259 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8260 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8261 
8262 	/*
8263 	 * Rename ops:
8264 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8265 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8266 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8267 	 *
8268 	 *    if (odvp != ndvp)
8269 	 *	add putfh(sourcedir), getattr(sourcedir) }
8270 	 */
8271 	args.array = argop;
8272 
8273 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8274 	    &recov_state, NULL);
8275 	if (e.error) {
8276 		kmem_free(argop, argoplist_size);
8277 		mutex_enter(&orp->r_statelock);
8278 		orp->r_flags &= ~R4RECEXPFH;
8279 		cv_broadcast(&orp->r_cv);
8280 		mutex_exit(&orp->r_statelock);
8281 		return (e.error);
8282 	}
8283 
8284 	/* 0: putfh source directory */
8285 	argop[0].argop = OP_CPUTFH;
8286 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8287 
8288 	/* 1: Save source fh to free up current for target */
8289 	argop[1].argop = OP_SAVEFH;
8290 
8291 	/* 2: Lookup pre-rename fh of renamed object */
8292 	argop[2].argop = OP_CLOOKUP;
8293 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8294 
8295 	/* 3: getfh fh of renamed object (before rename) */
8296 	argop[3].argop = OP_GETFH;
8297 
8298 	/* 4: putfh targetdir */
8299 	argop[4].argop = OP_CPUTFH;
8300 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8301 
8302 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8303 	argop[5].argop = OP_CRENAME;
8304 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8305 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8306 
8307 	/* 6: getattr of target dir (post op attrs) */
8308 	argop[6].argop = OP_GETATTR;
8309 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8310 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8311 
8312 	/* 7: Lookup post-rename fh of renamed object */
8313 	argop[7].argop = OP_CLOOKUP;
8314 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8315 
8316 	/* 8: getfh fh of renamed object (after rename) */
8317 	argop[8].argop = OP_GETFH;
8318 
8319 	/* 9: getattr of renamed object */
8320 	argop[9].argop = OP_GETATTR;
8321 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8322 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8323 
8324 	/*
8325 	 * If source/target dirs are different, then get new post-op
8326 	 * attrs for source dir also.
8327 	 */
8328 	if (ndvp != odvp) {
8329 		/* 10: putfh (sourcedir) */
8330 		argop[10].argop = OP_CPUTFH;
8331 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8332 
8333 		/* 11: getattr (sourcedir) */
8334 		argop[11].argop = OP_GETATTR;
8335 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8336 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8337 	}
8338 
8339 	dnlc_remove(odvp, onm);
8340 	dnlc_remove(ndvp, nnm);
8341 
8342 	doqueue = 1;
8343 	t = gethrtime();
8344 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8345 
8346 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8347 	if (e.error) {
8348 		PURGE_ATTRCACHE4(odvp);
8349 		PURGE_ATTRCACHE4(ndvp);
8350 		if (!needrecov) {
8351 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8352 			    &recov_state, needrecov);
8353 			goto out;
8354 		}
8355 	} else {
8356 		*statp = res.status;
8357 	}
8358 
8359 	if (needrecov) {
8360 		bool_t abort;
8361 
8362 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8363 		    OP_RENAME, NULL);
8364 		if (abort == FALSE) {
8365 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8366 			    &recov_state, needrecov);
8367 			kmem_free(argop, argoplist_size);
8368 			if (!e.error)
8369 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8370 				    (caddr_t)&res);
8371 			mutex_enter(&orp->r_statelock);
8372 			orp->r_flags &= ~R4RECEXPFH;
8373 			cv_broadcast(&orp->r_cv);
8374 			mutex_exit(&orp->r_statelock);
8375 			goto recov_retry;
8376 		} else {
8377 			if (e.error != 0) {
8378 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8379 				    &recov_state, needrecov);
8380 				goto out;
8381 			}
8382 			/* fall through for res.status case */
8383 		}
8384 	}
8385 
8386 	resp = &res;
8387 	/*
8388 	 * If OP_RENAME (or any prev op) failed, then return an error.
8389 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8390 	 */
8391 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8392 		/*
8393 		 * Error in an op other than last Getattr
8394 		 */
8395 		e.error = geterrno4(res.status);
8396 		PURGE_ATTRCACHE4(odvp);
8397 		PURGE_ATTRCACHE4(ndvp);
8398 		/*
8399 		 * System V defines rename to return EEXIST, not
8400 		 * ENOTEMPTY if the target directory is not empty.
8401 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8402 		 * which geterrno4 maps to ENOTEMPTY.
8403 		 */
8404 		if (e.error == ENOTEMPTY)
8405 			e.error = EEXIST;
8406 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8407 		    needrecov);
8408 		goto out;
8409 	}
8410 
8411 	/* rename results */
8412 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8413 
8414 	if (res.status == NFS4_OK) {
8415 		/* Update target attribute, readdir and dnlc caches */
8416 		dinfo.di_garp =
8417 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
8418 		dinfo.di_cred = cr;
8419 		dinfo.di_time_call = t;
8420 	} else
8421 		dinfop = NULL;
8422 
8423 	/* Update source cache attribute, readdir and dnlc caches */
8424 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8425 
8426 	/* Update source cache attribute, readdir and dnlc caches */
8427 	if (ndvp != odvp) {
8428 
8429 		/*
8430 		 * If dinfop is non-NULL, then compound succeded, so
8431 		 * set di_garp to attrs for source dir.  dinfop is only
8432 		 * set to NULL when compound fails.
8433 		 */
8434 		if (dinfop)
8435 			dinfo.di_garp =
8436 			    &res.array[11].nfs_resop4_u.opgetattr.ga_res;
8437 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8438 		    dinfop);
8439 	}
8440 
8441 	/*
8442 	 * Update the rnode with the new component name and args,
8443 	 * and if the file handle changed, also update it with the new fh.
8444 	 * This is only necessary if the target object has an rnode
8445 	 * entry and there is no need to create one for it.
8446 	 */
8447 	resop = &res.array[8];	/* getfh new res */
8448 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8449 
8450 	/*
8451 	 * Update the path and filehandle for the renamed object.
8452 	 */
8453 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8454 
8455 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8456 
8457 	if (res.status == NFS4_OK) {
8458 		resop++;	/* getattr res */
8459 		e.error = nfs4_update_attrcache(res.status,
8460 		    &resop->nfs_resop4_u.opgetattr.ga_res,
8461 		    t, ovp, cr);
8462 	}
8463 
8464 out:
8465 	kmem_free(argop, argoplist_size);
8466 	if (resp)
8467 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8468 	mutex_enter(&orp->r_statelock);
8469 	orp->r_flags &= ~R4RECEXPFH;
8470 	cv_broadcast(&orp->r_cv);
8471 	mutex_exit(&orp->r_statelock);
8472 
8473 	return (e.error);
8474 }
8475 
8476 /* ARGSUSED */
8477 static int
8478 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr,
8479     caller_context_t *ct, int flags, vsecattr_t *vsecp)
8480 {
8481 	int error;
8482 	vnode_t *vp;
8483 
8484 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8485 		return (EPERM);
8486 	/*
8487 	 * As ".." has special meaning and rather than send a mkdir
8488 	 * over the wire to just let the server freak out, we just
8489 	 * short circuit it here and return EEXIST
8490 	 */
8491 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8492 		return (EEXIST);
8493 
8494 	/*
8495 	 * Decision to get the right gid and setgid bit of the
8496 	 * new directory is now made in call_nfs4_create_req.
8497 	 */
8498 	va->va_mask |= AT_MODE;
8499 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8500 	if (error)
8501 		return (error);
8502 
8503 	*vpp = vp;
8504 	return (0);
8505 }
8506 
8507 
8508 /*
8509  * rmdir is using the same remove v4 op as does remove.
8510  * Remove requires that the current fh be the target directory.
8511  * After the operation, the current fh is unchanged.
8512  * The compound op structure is:
8513  *      PUTFH(targetdir), REMOVE
8514  */
8515 /*ARGSUSED4*/
8516 static int
8517 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr,
8518     caller_context_t *ct, int flags)
8519 {
8520 	int need_end_op = FALSE;
8521 	COMPOUND4args_clnt args;
8522 	COMPOUND4res_clnt res, *resp = NULL;
8523 	REMOVE4res *rm_res;
8524 	nfs_argop4 argop[3];
8525 	nfs_resop4 *resop;
8526 	vnode_t *vp;
8527 	int doqueue;
8528 	mntinfo4_t *mi;
8529 	rnode4_t *drp;
8530 	bool_t needrecov = FALSE;
8531 	nfs4_recov_state_t recov_state;
8532 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8533 	dirattr_info_t dinfo, *dinfop;
8534 
8535 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8536 		return (EPERM);
8537 	/*
8538 	 * As ".." has special meaning and rather than send a rmdir
8539 	 * over the wire to just let the server freak out, we just
8540 	 * short circuit it here and return EEXIST
8541 	 */
8542 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8543 		return (EEXIST);
8544 
8545 	drp = VTOR4(dvp);
8546 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8547 		return (EINTR);
8548 
8549 	/*
8550 	 * Attempt to prevent a rmdir(".") from succeeding.
8551 	 */
8552 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8553 	if (e.error) {
8554 		nfs_rw_exit(&drp->r_rwlock);
8555 		return (e.error);
8556 	}
8557 	if (vp == cdir) {
8558 		VN_RELE(vp);
8559 		nfs_rw_exit(&drp->r_rwlock);
8560 		return (EINVAL);
8561 	}
8562 
8563 	/*
8564 	 * Since nfsv4 remove op works on both files and directories,
8565 	 * check that the removed object is indeed a directory.
8566 	 */
8567 	if (vp->v_type != VDIR) {
8568 		VN_RELE(vp);
8569 		nfs_rw_exit(&drp->r_rwlock);
8570 		return (ENOTDIR);
8571 	}
8572 
8573 	/*
8574 	 * First just remove the entry from the name cache, as it
8575 	 * is most likely an entry for this vp.
8576 	 */
8577 	dnlc_remove(dvp, nm);
8578 
8579 	/*
8580 	 * If there vnode reference count is greater than one, then
8581 	 * there may be additional references in the DNLC which will
8582 	 * need to be purged.  First, trying removing the entry for
8583 	 * the parent directory and see if that removes the additional
8584 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8585 	 * to completely remove any references to the directory which
8586 	 * might still exist in the DNLC.
8587 	 */
8588 	if (vp->v_count > 1) {
8589 		dnlc_remove(vp, "..");
8590 		if (vp->v_count > 1)
8591 			dnlc_purge_vp(vp);
8592 	}
8593 
8594 	mi = VTOMI4(dvp);
8595 	recov_state.rs_flags = 0;
8596 	recov_state.rs_num_retry_despite_err = 0;
8597 
8598 recov_retry:
8599 	args.ctag = TAG_RMDIR;
8600 
8601 	/*
8602 	 * Rmdir ops: putfh dir; remove
8603 	 */
8604 	args.array_len = 3;
8605 	args.array = argop;
8606 
8607 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8608 	if (e.error) {
8609 		nfs_rw_exit(&drp->r_rwlock);
8610 		return (e.error);
8611 	}
8612 	need_end_op = TRUE;
8613 
8614 	/* putfh directory */
8615 	argop[0].argop = OP_CPUTFH;
8616 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8617 
8618 	/* remove */
8619 	argop[1].argop = OP_CREMOVE;
8620 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8621 
8622 	/* getattr (postop attrs for dir that contained removed dir) */
8623 	argop[2].argop = OP_GETATTR;
8624 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8625 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8626 
8627 	dinfo.di_time_call = gethrtime();
8628 	doqueue = 1;
8629 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8630 
8631 	PURGE_ATTRCACHE4(vp);
8632 
8633 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8634 	if (e.error) {
8635 		PURGE_ATTRCACHE4(dvp);
8636 	}
8637 
8638 	if (needrecov) {
8639 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8640 		    NULL, OP_REMOVE, NULL) == FALSE) {
8641 			if (!e.error)
8642 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8643 				    (caddr_t)&res);
8644 
8645 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8646 			    needrecov);
8647 			need_end_op = FALSE;
8648 			goto recov_retry;
8649 		}
8650 	}
8651 
8652 	if (!e.error) {
8653 		resp = &res;
8654 
8655 		/*
8656 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8657 		 * failed.
8658 		 */
8659 		if (res.status != NFS4_OK && res.array_len <= 2) {
8660 			e.error = geterrno4(res.status);
8661 			PURGE_ATTRCACHE4(dvp);
8662 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8663 			    &recov_state, needrecov);
8664 			need_end_op = FALSE;
8665 			nfs4_purge_stale_fh(e.error, dvp, cr);
8666 			/*
8667 			 * System V defines rmdir to return EEXIST, not
8668 			 * ENOTEMPTY if the directory is not empty.  Over
8669 			 * the wire, the error is NFSERR_ENOTEMPTY which
8670 			 * geterrno4 maps to ENOTEMPTY.
8671 			 */
8672 			if (e.error == ENOTEMPTY)
8673 				e.error = EEXIST;
8674 		} else {
8675 			resop = &res.array[1];	/* remove res */
8676 			rm_res = &resop->nfs_resop4_u.opremove;
8677 
8678 			if (res.status == NFS4_OK) {
8679 				resop = &res.array[2];	/* dir attrs */
8680 				dinfo.di_garp =
8681 				    &resop->nfs_resop4_u.opgetattr.ga_res;
8682 				dinfo.di_cred = cr;
8683 				dinfop = &dinfo;
8684 			} else
8685 				dinfop = NULL;
8686 
8687 			/* Update dir attribute, readdir and dnlc caches */
8688 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8689 			    dinfop);
8690 
8691 			/* destroy rddir cache for dir that was removed */
8692 			if (VTOR4(vp)->r_dir != NULL)
8693 				nfs4_purge_rddir_cache(vp);
8694 		}
8695 	}
8696 
8697 	if (need_end_op)
8698 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8699 
8700 	nfs_rw_exit(&drp->r_rwlock);
8701 
8702 	if (resp)
8703 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8704 
8705 	if (e.error == 0) {
8706 		vnode_t *tvp;
8707 		rnode4_t *trp;
8708 		trp = VTOR4(vp);
8709 		tvp = vp;
8710 		if (IS_SHADOW(vp, trp))
8711 			tvp = RTOV4(trp);
8712 		vnevent_rmdir(tvp, dvp, nm, ct);
8713 	}
8714 
8715 	VN_RELE(vp);
8716 
8717 	return (e.error);
8718 }
8719 
8720 /* ARGSUSED */
8721 static int
8722 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr,
8723     caller_context_t *ct, int flags)
8724 {
8725 	int error;
8726 	vnode_t *vp;
8727 	rnode4_t *rp;
8728 	char *contents;
8729 	mntinfo4_t *mi = VTOMI4(dvp);
8730 
8731 	if (nfs_zone() != mi->mi_zone)
8732 		return (EPERM);
8733 	if (!(mi->mi_flags & MI4_SYMLINK))
8734 		return (EOPNOTSUPP);
8735 
8736 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8737 	if (error)
8738 		return (error);
8739 
8740 	ASSERT(nfs4_consistent_type(vp));
8741 	rp = VTOR4(vp);
8742 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8743 
8744 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8745 
8746 		if (contents != NULL) {
8747 			mutex_enter(&rp->r_statelock);
8748 			if (rp->r_symlink.contents == NULL) {
8749 				rp->r_symlink.len = strlen(tnm);
8750 				bcopy(tnm, contents, rp->r_symlink.len);
8751 				rp->r_symlink.contents = contents;
8752 				rp->r_symlink.size = MAXPATHLEN;
8753 				mutex_exit(&rp->r_statelock);
8754 			} else {
8755 				mutex_exit(&rp->r_statelock);
8756 				kmem_free((void *)contents, MAXPATHLEN);
8757 			}
8758 		}
8759 	}
8760 	VN_RELE(vp);
8761 
8762 	return (error);
8763 }
8764 
8765 
8766 /*
8767  * Read directory entries.
8768  * There are some weird things to look out for here.  The uio_loffset
8769  * field is either 0 or it is the offset returned from a previous
8770  * readdir.  It is an opaque value used by the server to find the
8771  * correct directory block to read. The count field is the number
8772  * of blocks to read on the server.  This is advisory only, the server
8773  * may return only one block's worth of entries.  Entries may be compressed
8774  * on the server.
8775  */
8776 /* ARGSUSED */
8777 static int
8778 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp,
8779 	caller_context_t *ct, int flags)
8780 {
8781 	int error;
8782 	uint_t count;
8783 	rnode4_t *rp;
8784 	rddir4_cache *rdc;
8785 	rddir4_cache *rrdc;
8786 
8787 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8788 		return (EIO);
8789 	rp = VTOR4(vp);
8790 
8791 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8792 
8793 	/*
8794 	 * Make sure that the directory cache is valid.
8795 	 */
8796 	if (rp->r_dir != NULL) {
8797 		if (nfs_disable_rddir_cache != 0) {
8798 			/*
8799 			 * Setting nfs_disable_rddir_cache in /etc/system
8800 			 * allows interoperability with servers that do not
8801 			 * properly update the attributes of directories.
8802 			 * Any cached information gets purged before an
8803 			 * access is made to it.
8804 			 */
8805 			nfs4_purge_rddir_cache(vp);
8806 		}
8807 
8808 		error = nfs4_validate_caches(vp, cr);
8809 		if (error)
8810 			return (error);
8811 	}
8812 
8813 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8814 
8815 	/*
8816 	 * Short circuit last readdir which always returns 0 bytes.
8817 	 * This can be done after the directory has been read through
8818 	 * completely at least once.  This will set r_direof which
8819 	 * can be used to find the value of the last cookie.
8820 	 */
8821 	mutex_enter(&rp->r_statelock);
8822 	if (rp->r_direof != NULL &&
8823 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8824 		mutex_exit(&rp->r_statelock);
8825 #ifdef DEBUG
8826 		nfs4_readdir_cache_shorts++;
8827 #endif
8828 		if (eofp)
8829 			*eofp = 1;
8830 		return (0);
8831 	}
8832 
8833 	/*
8834 	 * Look for a cache entry.  Cache entries are identified
8835 	 * by the NFS cookie value and the byte count requested.
8836 	 */
8837 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8838 
8839 	/*
8840 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8841 	 */
8842 	if (rdc == NULL) {
8843 		mutex_exit(&rp->r_statelock);
8844 		return (EINTR);
8845 	}
8846 
8847 	/*
8848 	 * Check to see if we need to fill this entry in.
8849 	 */
8850 	if (rdc->flags & RDDIRREQ) {
8851 		rdc->flags &= ~RDDIRREQ;
8852 		rdc->flags |= RDDIR;
8853 		mutex_exit(&rp->r_statelock);
8854 
8855 		/*
8856 		 * Do the readdir.
8857 		 */
8858 		nfs4readdir(vp, rdc, cr);
8859 
8860 		/*
8861 		 * Reacquire the lock, so that we can continue
8862 		 */
8863 		mutex_enter(&rp->r_statelock);
8864 		/*
8865 		 * The entry is now complete
8866 		 */
8867 		rdc->flags &= ~RDDIR;
8868 	}
8869 
8870 	ASSERT(!(rdc->flags & RDDIR));
8871 
8872 	/*
8873 	 * If an error occurred while attempting
8874 	 * to fill the cache entry, mark the entry invalid and
8875 	 * just return the error.
8876 	 */
8877 	if (rdc->error) {
8878 		error = rdc->error;
8879 		rdc->flags |= RDDIRREQ;
8880 		rddir4_cache_rele(rp, rdc);
8881 		mutex_exit(&rp->r_statelock);
8882 		return (error);
8883 	}
8884 
8885 	/*
8886 	 * The cache entry is complete and good,
8887 	 * copyout the dirent structs to the calling
8888 	 * thread.
8889 	 */
8890 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
8891 
8892 	/*
8893 	 * If no error occurred during the copyout,
8894 	 * update the offset in the uio struct to
8895 	 * contain the value of the next NFS 4 cookie
8896 	 * and set the eof value appropriately.
8897 	 */
8898 	if (!error) {
8899 		uiop->uio_loffset = rdc->nfs4_ncookie;
8900 		if (eofp)
8901 			*eofp = rdc->eof;
8902 	}
8903 
8904 	/*
8905 	 * Decide whether to do readahead.  Don't if we
8906 	 * have already read to the end of directory.
8907 	 */
8908 	if (rdc->eof) {
8909 		/*
8910 		 * Make the entry the direof only if it is cached
8911 		 */
8912 		if (rdc->flags & RDDIRCACHED)
8913 			rp->r_direof = rdc;
8914 		rddir4_cache_rele(rp, rdc);
8915 		mutex_exit(&rp->r_statelock);
8916 		return (error);
8917 	}
8918 
8919 	/* Determine if a readdir readahead should be done */
8920 	if (!(rp->r_flags & R4LOOKUP)) {
8921 		rddir4_cache_rele(rp, rdc);
8922 		mutex_exit(&rp->r_statelock);
8923 		return (error);
8924 	}
8925 
8926 	/*
8927 	 * Now look for a readahead entry.
8928 	 *
8929 	 * Check to see whether we found an entry for the readahead.
8930 	 * If so, we don't need to do anything further, so free the new
8931 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
8932 	 * it to the cache, and then initiate an asynchronous readdir
8933 	 * operation to fill it.
8934 	 */
8935 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
8936 
8937 	/*
8938 	 * A readdir cache entry could not be obtained for the readahead.  In
8939 	 * this case we skip the readahead and return.
8940 	 */
8941 	if (rrdc == NULL) {
8942 		rddir4_cache_rele(rp, rdc);
8943 		mutex_exit(&rp->r_statelock);
8944 		return (error);
8945 	}
8946 
8947 	/*
8948 	 * Check to see if we need to fill this entry in.
8949 	 */
8950 	if (rrdc->flags & RDDIRREQ) {
8951 		rrdc->flags &= ~RDDIRREQ;
8952 		rrdc->flags |= RDDIR;
8953 		rddir4_cache_rele(rp, rdc);
8954 		mutex_exit(&rp->r_statelock);
8955 #ifdef DEBUG
8956 		nfs4_readdir_readahead++;
8957 #endif
8958 		/*
8959 		 * Do the readdir.
8960 		 */
8961 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
8962 		return (error);
8963 	}
8964 
8965 	rddir4_cache_rele(rp, rrdc);
8966 	rddir4_cache_rele(rp, rdc);
8967 	mutex_exit(&rp->r_statelock);
8968 	return (error);
8969 }
8970 
8971 static int
8972 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
8973 {
8974 	int error;
8975 	rnode4_t *rp;
8976 
8977 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
8978 
8979 	rp = VTOR4(vp);
8980 
8981 	/*
8982 	 * Obtain the readdir results for the caller.
8983 	 */
8984 	nfs4readdir(vp, rdc, cr);
8985 
8986 	mutex_enter(&rp->r_statelock);
8987 	/*
8988 	 * The entry is now complete
8989 	 */
8990 	rdc->flags &= ~RDDIR;
8991 
8992 	error = rdc->error;
8993 	if (error)
8994 		rdc->flags |= RDDIRREQ;
8995 	rddir4_cache_rele(rp, rdc);
8996 	mutex_exit(&rp->r_statelock);
8997 
8998 	return (error);
8999 }
9000 
9001 /*
9002  * Read directory entries.
9003  * There are some weird things to look out for here.  The uio_loffset
9004  * field is either 0 or it is the offset returned from a previous
9005  * readdir.  It is an opaque value used by the server to find the
9006  * correct directory block to read. The count field is the number
9007  * of blocks to read on the server.  This is advisory only, the server
9008  * may return only one block's worth of entries.  Entries may be compressed
9009  * on the server.
9010  *
9011  * Generates the following compound request:
9012  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9013  *    must include a Lookupp as well. In this case, send:
9014  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9015  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9016  *
9017  * Get complete attributes and filehandles for entries if this is the
9018  * first read of the directory. Otherwise, just get fileid's.
9019  */
9020 static void
9021 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9022 {
9023 	COMPOUND4args_clnt args;
9024 	COMPOUND4res_clnt res;
9025 	READDIR4args *rargs;
9026 	READDIR4res_clnt *rd_res;
9027 	bitmap4 rd_bitsval;
9028 	nfs_argop4 argop[5];
9029 	nfs_resop4 *resop;
9030 	rnode4_t *rp = VTOR4(vp);
9031 	mntinfo4_t *mi = VTOMI4(vp);
9032 	int doqueue;
9033 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9034 	vnode_t *dvp;
9035 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9036 	int num_ops, res_opcnt;
9037 	bool_t needrecov = FALSE;
9038 	nfs4_recov_state_t recov_state;
9039 	hrtime_t t;
9040 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9041 
9042 	ASSERT(nfs_zone() == mi->mi_zone);
9043 	ASSERT(rdc->flags & RDDIR);
9044 	ASSERT(rdc->entries == NULL);
9045 
9046 	/*
9047 	 * If rp were a stub, it should have triggered and caused
9048 	 * a mount for us to get this far.
9049 	 */
9050 	ASSERT(!RP_ISSTUB(rp));
9051 
9052 	num_ops = 2;
9053 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9054 		/*
9055 		 * Since nfsv4 readdir may not return entries for "." and "..",
9056 		 * the client must recreate them:
9057 		 * To find the correct nodeid, do the following:
9058 		 * For current node, get nodeid from dnlc.
9059 		 * - if current node is rootvp, set pnodeid to nodeid.
9060 		 * - else if parent is in the dnlc, get its nodeid from there.
9061 		 * - else add LOOKUPP+GETATTR to compound.
9062 		 */
9063 		nodeid = rp->r_attr.va_nodeid;
9064 		if (vp->v_flag & VROOT) {
9065 			pnodeid = nodeid;	/* root of mount point */
9066 		} else {
9067 			dvp = dnlc_lookup(vp, "..");
9068 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9069 				/* parent in dnlc cache - no need for otw */
9070 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9071 			} else {
9072 				/*
9073 				 * parent not in dnlc cache,
9074 				 * do lookupp to get its id
9075 				 */
9076 				num_ops = 5;
9077 				pnodeid = 0; /* set later by getattr parent */
9078 			}
9079 			if (dvp)
9080 				VN_RELE(dvp);
9081 		}
9082 	}
9083 	recov_state.rs_flags = 0;
9084 	recov_state.rs_num_retry_despite_err = 0;
9085 
9086 	/* Save the original mount point security flavor */
9087 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9088 
9089 recov_retry:
9090 	args.ctag = TAG_READDIR;
9091 
9092 	args.array = argop;
9093 	args.array_len = num_ops;
9094 
9095 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9096 	    &recov_state, NULL)) {
9097 		/*
9098 		 * If readdir a node that is a stub for a crossed mount point,
9099 		 * keep the original secinfo flavor for the current file
9100 		 * system, not the crossed one.
9101 		 */
9102 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9103 		rdc->error = e.error;
9104 		return;
9105 	}
9106 
9107 	/*
9108 	 * Determine which attrs to request for dirents.  This code
9109 	 * must be protected by nfs4_start/end_fop because of r_server
9110 	 * (which will change during failover recovery).
9111 	 *
9112 	 */
9113 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9114 		/*
9115 		 * Get all vattr attrs plus filehandle and rdattr_error
9116 		 */
9117 		rd_bitsval = NFS4_VATTR_MASK |
9118 		    FATTR4_RDATTR_ERROR_MASK |
9119 		    FATTR4_FILEHANDLE_MASK;
9120 
9121 		if (rp->r_flags & R4READDIRWATTR) {
9122 			mutex_enter(&rp->r_statelock);
9123 			rp->r_flags &= ~R4READDIRWATTR;
9124 			mutex_exit(&rp->r_statelock);
9125 		}
9126 	} else {
9127 		servinfo4_t *svp = rp->r_server;
9128 
9129 		/*
9130 		 * Already read directory. Use readdir with
9131 		 * no attrs (except for mounted_on_fileid) for updates.
9132 		 */
9133 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9134 
9135 		/*
9136 		 * request mounted on fileid if supported, else request
9137 		 * fileid.  maybe we should verify that fileid is supported
9138 		 * and request something else if not.
9139 		 */
9140 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9141 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9142 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9143 		nfs_rw_exit(&svp->sv_lock);
9144 	}
9145 
9146 	/* putfh directory fh */
9147 	argop[0].argop = OP_CPUTFH;
9148 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9149 
9150 	argop[1].argop = OP_READDIR;
9151 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9152 	/*
9153 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9154 	 * cookie 0 should be used over-the-wire to start reading at
9155 	 * the beginning of the directory excluding "." and "..".
9156 	 */
9157 	if (rdc->nfs4_cookie == 0 ||
9158 	    rdc->nfs4_cookie == 1 ||
9159 	    rdc->nfs4_cookie == 2) {
9160 		rargs->cookie = (nfs_cookie4)0;
9161 		rargs->cookieverf = 0;
9162 	} else {
9163 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9164 		mutex_enter(&rp->r_statelock);
9165 		rargs->cookieverf = rp->r_cookieverf4;
9166 		mutex_exit(&rp->r_statelock);
9167 	}
9168 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9169 	rargs->maxcount = mi->mi_tsize;
9170 	rargs->attr_request = rd_bitsval;
9171 	rargs->rdc = rdc;
9172 	rargs->dvp = vp;
9173 	rargs->mi = mi;
9174 	rargs->cr = cr;
9175 
9176 
9177 	/*
9178 	 * If count < than the minimum required, we return no entries
9179 	 * and fail with EINVAL
9180 	 */
9181 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9182 		rdc->error = EINVAL;
9183 		goto out;
9184 	}
9185 
9186 	if (args.array_len == 5) {
9187 		/*
9188 		 * Add lookupp and getattr for parent nodeid.
9189 		 */
9190 		argop[2].argop = OP_LOOKUPP;
9191 
9192 		argop[3].argop = OP_GETFH;
9193 
9194 		/* getattr parent */
9195 		argop[4].argop = OP_GETATTR;
9196 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9197 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9198 	}
9199 
9200 	doqueue = 1;
9201 
9202 	if (mi->mi_io_kstats) {
9203 		mutex_enter(&mi->mi_lock);
9204 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9205 		mutex_exit(&mi->mi_lock);
9206 	}
9207 
9208 	/* capture the time of this call */
9209 	rargs->t = t = gethrtime();
9210 
9211 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9212 
9213 	if (mi->mi_io_kstats) {
9214 		mutex_enter(&mi->mi_lock);
9215 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9216 		mutex_exit(&mi->mi_lock);
9217 	}
9218 
9219 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9220 
9221 	/*
9222 	 * If RPC error occurred and it isn't an error that
9223 	 * triggers recovery, then go ahead and fail now.
9224 	 */
9225 	if (e.error != 0 && !needrecov) {
9226 		rdc->error = e.error;
9227 		goto out;
9228 	}
9229 
9230 	if (needrecov) {
9231 		bool_t abort;
9232 
9233 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9234 		    "nfs4readdir: initiating recovery.\n"));
9235 
9236 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9237 		    NULL, OP_READDIR, NULL);
9238 		if (abort == FALSE) {
9239 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9240 			    &recov_state, needrecov);
9241 			if (!e.error)
9242 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9243 				    (caddr_t)&res);
9244 			if (rdc->entries != NULL) {
9245 				kmem_free(rdc->entries, rdc->entlen);
9246 				rdc->entries = NULL;
9247 			}
9248 			goto recov_retry;
9249 		}
9250 
9251 		if (e.error != 0) {
9252 			rdc->error = e.error;
9253 			goto out;
9254 		}
9255 
9256 		/* fall through for res.status case */
9257 	}
9258 
9259 	res_opcnt = res.array_len;
9260 
9261 	/*
9262 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9263 	 * failure here.  Subsequent ops are for filling out dot-dot
9264 	 * dirent, and if they fail, we still want to give the caller
9265 	 * the dirents returned by (the successful) READDIR op, so we need
9266 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9267 	 *
9268 	 * One example where PUTFH+READDIR ops would succeed but
9269 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9270 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9271 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9272 	 * x perm.  We need to come up with a non-vendor-specific way
9273 	 * for a POSIX server to return d_ino from dotdot's dirent if
9274 	 * client only requests mounted_on_fileid, and just say the
9275 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9276 	 * client requested any mandatory attrs, server would be required
9277 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9278 	 * for dotdot.
9279 	 */
9280 
9281 	if (res.status) {
9282 		if (res_opcnt <= 2) {
9283 			e.error = geterrno4(res.status);
9284 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9285 			    &recov_state, needrecov);
9286 			nfs4_purge_stale_fh(e.error, vp, cr);
9287 			rdc->error = e.error;
9288 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9289 			if (rdc->entries != NULL) {
9290 				kmem_free(rdc->entries, rdc->entlen);
9291 				rdc->entries = NULL;
9292 			}
9293 			/*
9294 			 * If readdir a node that is a stub for a
9295 			 * crossed mount point, keep the original
9296 			 * secinfo flavor for the current file system,
9297 			 * not the crossed one.
9298 			 */
9299 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9300 			return;
9301 		}
9302 	}
9303 
9304 	resop = &res.array[1];	/* readdir res */
9305 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9306 
9307 	mutex_enter(&rp->r_statelock);
9308 	rp->r_cookieverf4 = rd_res->cookieverf;
9309 	mutex_exit(&rp->r_statelock);
9310 
9311 	/*
9312 	 * For "." and ".." entries
9313 	 * e.g.
9314 	 *	seek(cookie=0) -> "." entry with d_off = 1
9315 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9316 	 */
9317 	if (cookie == (nfs_cookie4) 0) {
9318 		if (rd_res->dotp)
9319 			rd_res->dotp->d_ino = nodeid;
9320 		if (rd_res->dotdotp)
9321 			rd_res->dotdotp->d_ino = pnodeid;
9322 	}
9323 	if (cookie == (nfs_cookie4) 1) {
9324 		if (rd_res->dotdotp)
9325 			rd_res->dotdotp->d_ino = pnodeid;
9326 	}
9327 
9328 
9329 	/* LOOKUPP+GETATTR attemped */
9330 	if (args.array_len == 5 && rd_res->dotdotp) {
9331 		if (res.status == NFS4_OK && res_opcnt == 5) {
9332 			nfs_fh4 *fhp;
9333 			nfs4_sharedfh_t *sfhp;
9334 			vnode_t *pvp;
9335 			nfs4_ga_res_t *garp;
9336 
9337 			resop++;	/* lookupp */
9338 			resop++;	/* getfh   */
9339 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9340 
9341 			resop++;	/* getattr of parent */
9342 
9343 			/*
9344 			 * First, take care of finishing the
9345 			 * readdir results.
9346 			 */
9347 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9348 			/*
9349 			 * The d_ino of .. must be the inode number
9350 			 * of the mounted filesystem.
9351 			 */
9352 			if (garp->n4g_va.va_mask & AT_NODEID)
9353 				rd_res->dotdotp->d_ino =
9354 				    garp->n4g_va.va_nodeid;
9355 
9356 
9357 			/*
9358 			 * Next, create the ".." dnlc entry
9359 			 */
9360 			sfhp = sfh4_get(fhp, mi);
9361 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9362 				dnlc_update(vp, "..", pvp);
9363 				VN_RELE(pvp);
9364 			}
9365 			sfh4_rele(&sfhp);
9366 		}
9367 	}
9368 
9369 	if (mi->mi_io_kstats) {
9370 		mutex_enter(&mi->mi_lock);
9371 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9372 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9373 		mutex_exit(&mi->mi_lock);
9374 	}
9375 
9376 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9377 
9378 out:
9379 	/*
9380 	 * If readdir a node that is a stub for a crossed mount point,
9381 	 * keep the original secinfo flavor for the current file system,
9382 	 * not the crossed one.
9383 	 */
9384 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9385 
9386 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9387 }
9388 
9389 
9390 static int
9391 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9392 {
9393 	rnode4_t *rp = VTOR4(bp->b_vp);
9394 	int count;
9395 	int error;
9396 	cred_t *cred_otw = NULL;
9397 	offset_t offset;
9398 	nfs4_open_stream_t *osp = NULL;
9399 	bool_t first_time = TRUE;	/* first time getting otw cred */
9400 	bool_t last_time = FALSE;	/* last time getting otw cred */
9401 
9402 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9403 
9404 	DTRACE_IO1(start, struct buf *, bp);
9405 	offset = ldbtob(bp->b_lblkno);
9406 
9407 	if (bp->b_flags & B_READ) {
9408 	read_again:
9409 		/*
9410 		 * Releases the osp, if it is provided.
9411 		 * Puts a hold on the cred_otw and the new osp (if found).
9412 		 */
9413 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9414 		    &first_time, &last_time);
9415 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9416 		    offset, bp->b_bcount, &bp->b_resid, cred_otw,
9417 		    readahead, NULL);
9418 		crfree(cred_otw);
9419 		if (!error) {
9420 			if (bp->b_resid) {
9421 				/*
9422 				 * Didn't get it all because we hit EOF,
9423 				 * zero all the memory beyond the EOF.
9424 				 */
9425 				/* bzero(rdaddr + */
9426 				bzero(bp->b_un.b_addr +
9427 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9428 			}
9429 			mutex_enter(&rp->r_statelock);
9430 			if (bp->b_resid == bp->b_bcount &&
9431 			    offset >= rp->r_size) {
9432 				/*
9433 				 * We didn't read anything at all as we are
9434 				 * past EOF.  Return an error indicator back
9435 				 * but don't destroy the pages (yet).
9436 				 */
9437 				error = NFS_EOF;
9438 			}
9439 			mutex_exit(&rp->r_statelock);
9440 		} else if (error == EACCES && last_time == FALSE) {
9441 				goto read_again;
9442 		}
9443 	} else {
9444 		if (!(rp->r_flags & R4STALE)) {
9445 write_again:
9446 			/*
9447 			 * Releases the osp, if it is provided.
9448 			 * Puts a hold on the cred_otw and the new
9449 			 * osp (if found).
9450 			 */
9451 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9452 			    &first_time, &last_time);
9453 			mutex_enter(&rp->r_statelock);
9454 			count = MIN(bp->b_bcount, rp->r_size - offset);
9455 			mutex_exit(&rp->r_statelock);
9456 			if (count < 0)
9457 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9458 #ifdef DEBUG
9459 			if (count == 0) {
9460 				zoneid_t zoneid = getzoneid();
9461 
9462 				zcmn_err(zoneid, CE_WARN,
9463 				    "nfs4_bio: zero length write at %lld",
9464 				    offset);
9465 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9466 				    "b_bcount=%ld, file size=%lld",
9467 				    rp->r_flags, (long)bp->b_bcount,
9468 				    rp->r_size);
9469 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9470 				if (nfs4_bio_do_stop)
9471 					debug_enter("nfs4_bio");
9472 			}
9473 #endif
9474 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9475 			    count, cred_otw, stab_comm);
9476 			if (error == EACCES && last_time == FALSE) {
9477 				crfree(cred_otw);
9478 				goto write_again;
9479 			}
9480 			bp->b_error = error;
9481 			if (error && error != EINTR &&
9482 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9483 				/*
9484 				 * Don't print EDQUOT errors on the console.
9485 				 * Don't print asynchronous EACCES errors.
9486 				 * Don't print EFBIG errors.
9487 				 * Print all other write errors.
9488 				 */
9489 				if (error != EDQUOT && error != EFBIG &&
9490 				    (error != EACCES ||
9491 				    !(bp->b_flags & B_ASYNC)))
9492 					nfs4_write_error(bp->b_vp,
9493 					    error, cred_otw);
9494 				/*
9495 				 * Update r_error and r_flags as appropriate.
9496 				 * If the error was ESTALE, then mark the
9497 				 * rnode as not being writeable and save
9498 				 * the error status.  Otherwise, save any
9499 				 * errors which occur from asynchronous
9500 				 * page invalidations.  Any errors occurring
9501 				 * from other operations should be saved
9502 				 * by the caller.
9503 				 */
9504 				mutex_enter(&rp->r_statelock);
9505 				if (error == ESTALE) {
9506 					rp->r_flags |= R4STALE;
9507 					if (!rp->r_error)
9508 						rp->r_error = error;
9509 				} else if (!rp->r_error &&
9510 				    (bp->b_flags &
9511 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9512 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9513 					rp->r_error = error;
9514 				}
9515 				mutex_exit(&rp->r_statelock);
9516 			}
9517 			crfree(cred_otw);
9518 		} else
9519 			error = rp->r_error;
9520 	}
9521 
9522 	if (error != 0 && error != NFS_EOF)
9523 		bp->b_flags |= B_ERROR;
9524 
9525 	if (osp)
9526 		open_stream_rele(osp, rp);
9527 
9528 	DTRACE_IO1(done, struct buf *, bp);
9529 
9530 	return (error);
9531 }
9532 
9533 /* ARGSUSED */
9534 int
9535 nfs4_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
9536 {
9537 	return (EREMOTE);
9538 }
9539 
9540 /* ARGSUSED2 */
9541 int
9542 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9543 {
9544 	rnode4_t *rp = VTOR4(vp);
9545 
9546 	if (!write_lock) {
9547 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9548 		return (V_WRITELOCK_FALSE);
9549 	}
9550 
9551 	if ((rp->r_flags & R4DIRECTIO) ||
9552 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9553 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9554 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9555 			return (V_WRITELOCK_FALSE);
9556 		nfs_rw_exit(&rp->r_rwlock);
9557 	}
9558 
9559 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9560 	return (V_WRITELOCK_TRUE);
9561 }
9562 
9563 /* ARGSUSED */
9564 void
9565 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9566 {
9567 	rnode4_t *rp = VTOR4(vp);
9568 
9569 	nfs_rw_exit(&rp->r_rwlock);
9570 }
9571 
9572 /* ARGSUSED */
9573 static int
9574 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp, caller_context_t *ct)
9575 {
9576 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9577 		return (EIO);
9578 
9579 	/*
9580 	 * Because we stuff the readdir cookie into the offset field
9581 	 * someone may attempt to do an lseek with the cookie which
9582 	 * we want to succeed.
9583 	 */
9584 	if (vp->v_type == VDIR)
9585 		return (0);
9586 	if (*noffp < 0)
9587 		return (EINVAL);
9588 	return (0);
9589 }
9590 
9591 
9592 /*
9593  * Return all the pages from [off..off+len) in file
9594  */
9595 /* ARGSUSED */
9596 static int
9597 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9598     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9599 	enum seg_rw rw, cred_t *cr, caller_context_t *ct)
9600 {
9601 	rnode4_t *rp;
9602 	int error;
9603 	mntinfo4_t *mi;
9604 
9605 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9606 		return (EIO);
9607 	rp = VTOR4(vp);
9608 	if (IS_SHADOW(vp, rp))
9609 		vp = RTOV4(rp);
9610 
9611 	if (vp->v_flag & VNOMAP)
9612 		return (ENOSYS);
9613 
9614 	if (protp != NULL)
9615 		*protp = PROT_ALL;
9616 
9617 	/*
9618 	 * Now validate that the caches are up to date.
9619 	 */
9620 	if (error = nfs4_validate_caches(vp, cr))
9621 		return (error);
9622 
9623 	mi = VTOMI4(vp);
9624 retry:
9625 	mutex_enter(&rp->r_statelock);
9626 
9627 	/*
9628 	 * Don't create dirty pages faster than they
9629 	 * can be cleaned so that the system doesn't
9630 	 * get imbalanced.  If the async queue is
9631 	 * maxed out, then wait for it to drain before
9632 	 * creating more dirty pages.  Also, wait for
9633 	 * any threads doing pagewalks in the vop_getattr
9634 	 * entry points so that they don't block for
9635 	 * long periods.
9636 	 */
9637 	if (rw == S_CREATE) {
9638 		while ((mi->mi_max_threads != 0 &&
9639 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
9640 		    rp->r_gcount > 0)
9641 			cv_wait(&rp->r_cv, &rp->r_statelock);
9642 	}
9643 
9644 	/*
9645 	 * If we are getting called as a side effect of an nfs_write()
9646 	 * operation the local file size might not be extended yet.
9647 	 * In this case we want to be able to return pages of zeroes.
9648 	 */
9649 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9650 		NFS4_DEBUG(nfs4_pageio_debug,
9651 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9652 		    "len=%llu, size=%llu, attrsize =%llu", off,
9653 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9654 		mutex_exit(&rp->r_statelock);
9655 		return (EFAULT);		/* beyond EOF */
9656 	}
9657 
9658 	mutex_exit(&rp->r_statelock);
9659 
9660 	if (len <= PAGESIZE) {
9661 		error = nfs4_getapage(vp, off, len, protp, pl, plsz,
9662 		    seg, addr, rw, cr);
9663 		NFS4_DEBUG(nfs4_pageio_debug && error,
9664 		    (CE_NOTE, "getpage error %d; off=%lld, "
9665 		    "len=%lld", error, off, (u_longlong_t)len));
9666 	} else {
9667 		error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9668 		    pl, plsz, seg, addr, rw, cr);
9669 		NFS4_DEBUG(nfs4_pageio_debug && error,
9670 		    (CE_NOTE, "getpages error %d; off=%lld, "
9671 		    "len=%lld", error, off, (u_longlong_t)len));
9672 	}
9673 
9674 	switch (error) {
9675 	case NFS_EOF:
9676 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9677 		goto retry;
9678 	case ESTALE:
9679 		nfs4_purge_stale_fh(error, vp, cr);
9680 	}
9681 
9682 	return (error);
9683 }
9684 
9685 /*
9686  * Called from pvn_getpages or nfs4_getpage to get a particular page.
9687  */
9688 /* ARGSUSED */
9689 static int
9690 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9691     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9692     enum seg_rw rw, cred_t *cr)
9693 {
9694 	rnode4_t *rp;
9695 	uint_t bsize;
9696 	struct buf *bp;
9697 	page_t *pp;
9698 	u_offset_t lbn;
9699 	u_offset_t io_off;
9700 	u_offset_t blkoff;
9701 	u_offset_t rablkoff;
9702 	size_t io_len;
9703 	uint_t blksize;
9704 	int error;
9705 	int readahead;
9706 	int readahead_issued = 0;
9707 	int ra_window; /* readahead window */
9708 	page_t *pagefound;
9709 	page_t *savepp;
9710 
9711 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9712 		return (EIO);
9713 
9714 	rp = VTOR4(vp);
9715 	ASSERT(!IS_SHADOW(vp, rp));
9716 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9717 
9718 reread:
9719 	bp = NULL;
9720 	pp = NULL;
9721 	pagefound = NULL;
9722 
9723 	if (pl != NULL)
9724 		pl[0] = NULL;
9725 
9726 	error = 0;
9727 	lbn = off / bsize;
9728 	blkoff = lbn * bsize;
9729 
9730 	/*
9731 	 * Queueing up the readahead before doing the synchronous read
9732 	 * results in a significant increase in read throughput because
9733 	 * of the increased parallelism between the async threads and
9734 	 * the process context.
9735 	 */
9736 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9737 	    rw != S_CREATE &&
9738 	    !(vp->v_flag & VNOCACHE)) {
9739 		mutex_enter(&rp->r_statelock);
9740 
9741 		/*
9742 		 * Calculate the number of readaheads to do.
9743 		 * a) No readaheads at offset = 0.
9744 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9745 		 *    window is closed.
9746 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9747 		 *    upon how far the readahead window is open or close.
9748 		 * d) No readaheads if rp->r_nextr is not within the scope
9749 		 *    of the readahead window (random i/o).
9750 		 */
9751 
9752 		if (off == 0)
9753 			readahead = 0;
9754 		else if (blkoff == rp->r_nextr)
9755 			readahead = nfs4_nra;
9756 		else if (rp->r_nextr > blkoff &&
9757 		    ((ra_window = (rp->r_nextr - blkoff) / bsize)
9758 		    <= (nfs4_nra - 1)))
9759 			readahead = nfs4_nra - ra_window;
9760 		else
9761 			readahead = 0;
9762 
9763 		rablkoff = rp->r_nextr;
9764 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9765 			mutex_exit(&rp->r_statelock);
9766 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9767 			    addr + (rablkoff + bsize - off),
9768 			    seg, cr, nfs4_readahead) < 0) {
9769 				mutex_enter(&rp->r_statelock);
9770 				break;
9771 			}
9772 			readahead--;
9773 			rablkoff += bsize;
9774 			/*
9775 			 * Indicate that we did a readahead so
9776 			 * readahead offset is not updated
9777 			 * by the synchronous read below.
9778 			 */
9779 			readahead_issued = 1;
9780 			mutex_enter(&rp->r_statelock);
9781 			/*
9782 			 * set readahead offset to
9783 			 * offset of last async readahead
9784 			 * request.
9785 			 */
9786 			rp->r_nextr = rablkoff;
9787 		}
9788 		mutex_exit(&rp->r_statelock);
9789 	}
9790 
9791 again:
9792 	if ((pagefound = page_exists(vp, off)) == NULL) {
9793 		if (pl == NULL) {
9794 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9795 			    nfs4_readahead);
9796 		} else if (rw == S_CREATE) {
9797 			/*
9798 			 * Block for this page is not allocated, or the offset
9799 			 * is beyond the current allocation size, or we're
9800 			 * allocating a swap slot and the page was not found,
9801 			 * so allocate it and return a zero page.
9802 			 */
9803 			if ((pp = page_create_va(vp, off,
9804 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9805 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9806 			io_len = PAGESIZE;
9807 			mutex_enter(&rp->r_statelock);
9808 			rp->r_nextr = off + PAGESIZE;
9809 			mutex_exit(&rp->r_statelock);
9810 		} else {
9811 			/*
9812 			 * Need to go to server to get a block
9813 			 */
9814 			mutex_enter(&rp->r_statelock);
9815 			if (blkoff < rp->r_size &&
9816 			    blkoff + bsize > rp->r_size) {
9817 				/*
9818 				 * If less than a block left in
9819 				 * file read less than a block.
9820 				 */
9821 				if (rp->r_size <= off) {
9822 					/*
9823 					 * Trying to access beyond EOF,
9824 					 * set up to get at least one page.
9825 					 */
9826 					blksize = off + PAGESIZE - blkoff;
9827 				} else
9828 					blksize = rp->r_size - blkoff;
9829 			} else if ((off == 0) ||
9830 			    (off != rp->r_nextr && !readahead_issued)) {
9831 				blksize = PAGESIZE;
9832 				blkoff = off; /* block = page here */
9833 			} else
9834 				blksize = bsize;
9835 			mutex_exit(&rp->r_statelock);
9836 
9837 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9838 			    &io_len, blkoff, blksize, 0);
9839 
9840 			/*
9841 			 * Some other thread has entered the page,
9842 			 * so just use it.
9843 			 */
9844 			if (pp == NULL)
9845 				goto again;
9846 
9847 			/*
9848 			 * Now round the request size up to page boundaries.
9849 			 * This ensures that the entire page will be
9850 			 * initialized to zeroes if EOF is encountered.
9851 			 */
9852 			io_len = ptob(btopr(io_len));
9853 
9854 			bp = pageio_setup(pp, io_len, vp, B_READ);
9855 			ASSERT(bp != NULL);
9856 
9857 			/*
9858 			 * pageio_setup should have set b_addr to 0.  This
9859 			 * is correct since we want to do I/O on a page
9860 			 * boundary.  bp_mapin will use this addr to calculate
9861 			 * an offset, and then set b_addr to the kernel virtual
9862 			 * address it allocated for us.
9863 			 */
9864 			ASSERT(bp->b_un.b_addr == 0);
9865 
9866 			bp->b_edev = 0;
9867 			bp->b_dev = 0;
9868 			bp->b_lblkno = lbtodb(io_off);
9869 			bp->b_file = vp;
9870 			bp->b_offset = (offset_t)off;
9871 			bp_mapin(bp);
9872 
9873 			/*
9874 			 * If doing a write beyond what we believe is EOF,
9875 			 * don't bother trying to read the pages from the
9876 			 * server, we'll just zero the pages here.  We
9877 			 * don't check that the rw flag is S_WRITE here
9878 			 * because some implementations may attempt a
9879 			 * read access to the buffer before copying data.
9880 			 */
9881 			mutex_enter(&rp->r_statelock);
9882 			if (io_off >= rp->r_size && seg == segkmap) {
9883 				mutex_exit(&rp->r_statelock);
9884 				bzero(bp->b_un.b_addr, io_len);
9885 			} else {
9886 				mutex_exit(&rp->r_statelock);
9887 				error = nfs4_bio(bp, NULL, cr, FALSE);
9888 			}
9889 
9890 			/*
9891 			 * Unmap the buffer before freeing it.
9892 			 */
9893 			bp_mapout(bp);
9894 			pageio_done(bp);
9895 
9896 			savepp = pp;
9897 			do {
9898 				pp->p_fsdata = C_NOCOMMIT;
9899 			} while ((pp = pp->p_next) != savepp);
9900 
9901 			if (error == NFS_EOF) {
9902 				/*
9903 				 * If doing a write system call just return
9904 				 * zeroed pages, else user tried to get pages
9905 				 * beyond EOF, return error.  We don't check
9906 				 * that the rw flag is S_WRITE here because
9907 				 * some implementations may attempt a read
9908 				 * access to the buffer before copying data.
9909 				 */
9910 				if (seg == segkmap)
9911 					error = 0;
9912 				else
9913 					error = EFAULT;
9914 			}
9915 
9916 			if (!readahead_issued && !error) {
9917 				mutex_enter(&rp->r_statelock);
9918 				rp->r_nextr = io_off + io_len;
9919 				mutex_exit(&rp->r_statelock);
9920 			}
9921 		}
9922 	}
9923 
9924 out:
9925 	if (pl == NULL)
9926 		return (error);
9927 
9928 	if (error) {
9929 		if (pp != NULL)
9930 			pvn_read_done(pp, B_ERROR);
9931 		return (error);
9932 	}
9933 
9934 	if (pagefound) {
9935 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
9936 
9937 		/*
9938 		 * Page exists in the cache, acquire the appropriate lock.
9939 		 * If this fails, start all over again.
9940 		 */
9941 		if ((pp = page_lookup(vp, off, se)) == NULL) {
9942 #ifdef DEBUG
9943 			nfs4_lostpage++;
9944 #endif
9945 			goto reread;
9946 		}
9947 		pl[0] = pp;
9948 		pl[1] = NULL;
9949 		return (0);
9950 	}
9951 
9952 	if (pp != NULL)
9953 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
9954 
9955 	return (error);
9956 }
9957 
9958 static void
9959 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
9960     cred_t *cr)
9961 {
9962 	int error;
9963 	page_t *pp;
9964 	u_offset_t io_off;
9965 	size_t io_len;
9966 	struct buf *bp;
9967 	uint_t bsize, blksize;
9968 	rnode4_t *rp = VTOR4(vp);
9969 	page_t *savepp;
9970 
9971 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9972 
9973 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9974 
9975 	mutex_enter(&rp->r_statelock);
9976 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
9977 		/*
9978 		 * If less than a block left in file read less
9979 		 * than a block.
9980 		 */
9981 		blksize = rp->r_size - blkoff;
9982 	} else
9983 		blksize = bsize;
9984 	mutex_exit(&rp->r_statelock);
9985 
9986 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
9987 	    &io_off, &io_len, blkoff, blksize, 1);
9988 	/*
9989 	 * The isra flag passed to the kluster function is 1, we may have
9990 	 * gotten a return value of NULL for a variety of reasons (# of free
9991 	 * pages < minfree, someone entered the page on the vnode etc). In all
9992 	 * cases, we want to punt on the readahead.
9993 	 */
9994 	if (pp == NULL)
9995 		return;
9996 
9997 	/*
9998 	 * Now round the request size up to page boundaries.
9999 	 * This ensures that the entire page will be
10000 	 * initialized to zeroes if EOF is encountered.
10001 	 */
10002 	io_len = ptob(btopr(io_len));
10003 
10004 	bp = pageio_setup(pp, io_len, vp, B_READ);
10005 	ASSERT(bp != NULL);
10006 
10007 	/*
10008 	 * pageio_setup should have set b_addr to 0.  This is correct since
10009 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10010 	 * to calculate an offset, and then set b_addr to the kernel virtual
10011 	 * address it allocated for us.
10012 	 */
10013 	ASSERT(bp->b_un.b_addr == 0);
10014 
10015 	bp->b_edev = 0;
10016 	bp->b_dev = 0;
10017 	bp->b_lblkno = lbtodb(io_off);
10018 	bp->b_file = vp;
10019 	bp->b_offset = (offset_t)blkoff;
10020 	bp_mapin(bp);
10021 
10022 	/*
10023 	 * If doing a write beyond what we believe is EOF, don't bother trying
10024 	 * to read the pages from the server, we'll just zero the pages here.
10025 	 * We don't check that the rw flag is S_WRITE here because some
10026 	 * implementations may attempt a read access to the buffer before
10027 	 * copying data.
10028 	 */
10029 	mutex_enter(&rp->r_statelock);
10030 	if (io_off >= rp->r_size && seg == segkmap) {
10031 		mutex_exit(&rp->r_statelock);
10032 		bzero(bp->b_un.b_addr, io_len);
10033 		error = 0;
10034 	} else {
10035 		mutex_exit(&rp->r_statelock);
10036 		error = nfs4_bio(bp, NULL, cr, TRUE);
10037 		if (error == NFS_EOF)
10038 			error = 0;
10039 	}
10040 
10041 	/*
10042 	 * Unmap the buffer before freeing it.
10043 	 */
10044 	bp_mapout(bp);
10045 	pageio_done(bp);
10046 
10047 	savepp = pp;
10048 	do {
10049 		pp->p_fsdata = C_NOCOMMIT;
10050 	} while ((pp = pp->p_next) != savepp);
10051 
10052 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10053 
10054 	/*
10055 	 * In case of error set readahead offset
10056 	 * to the lowest offset.
10057 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10058 	 */
10059 	if (error && rp->r_nextr > io_off) {
10060 		mutex_enter(&rp->r_statelock);
10061 		if (rp->r_nextr > io_off)
10062 			rp->r_nextr = io_off;
10063 		mutex_exit(&rp->r_statelock);
10064 	}
10065 }
10066 
10067 /*
10068  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10069  * If len == 0, do from off to EOF.
10070  *
10071  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10072  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10073  * (from pageout).
10074  */
10075 /* ARGSUSED */
10076 static int
10077 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
10078 	caller_context_t *ct)
10079 {
10080 	int error;
10081 	rnode4_t *rp;
10082 
10083 	ASSERT(cr != NULL);
10084 
10085 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10086 		return (EIO);
10087 
10088 	rp = VTOR4(vp);
10089 	if (IS_SHADOW(vp, rp))
10090 		vp = RTOV4(rp);
10091 
10092 	/*
10093 	 * XXX - Why should this check be made here?
10094 	 */
10095 	if (vp->v_flag & VNOMAP)
10096 		return (ENOSYS);
10097 
10098 	if (len == 0 && !(flags & B_INVAL) &&
10099 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10100 		return (0);
10101 
10102 	mutex_enter(&rp->r_statelock);
10103 	rp->r_count++;
10104 	mutex_exit(&rp->r_statelock);
10105 	error = nfs4_putpages(vp, off, len, flags, cr);
10106 	mutex_enter(&rp->r_statelock);
10107 	rp->r_count--;
10108 	cv_broadcast(&rp->r_cv);
10109 	mutex_exit(&rp->r_statelock);
10110 
10111 	return (error);
10112 }
10113 
10114 /*
10115  * Write out a single page, possibly klustering adjacent dirty pages.
10116  */
10117 int
10118 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10119     int flags, cred_t *cr)
10120 {
10121 	u_offset_t io_off;
10122 	u_offset_t lbn_off;
10123 	u_offset_t lbn;
10124 	size_t io_len;
10125 	uint_t bsize;
10126 	int error;
10127 	rnode4_t *rp;
10128 
10129 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10130 	ASSERT(pp != NULL);
10131 	ASSERT(cr != NULL);
10132 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10133 
10134 	rp = VTOR4(vp);
10135 	ASSERT(rp->r_count > 0);
10136 	ASSERT(!IS_SHADOW(vp, rp));
10137 
10138 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10139 	lbn = pp->p_offset / bsize;
10140 	lbn_off = lbn * bsize;
10141 
10142 	/*
10143 	 * Find a kluster that fits in one block, or in
10144 	 * one page if pages are bigger than blocks.  If
10145 	 * there is less file space allocated than a whole
10146 	 * page, we'll shorten the i/o request below.
10147 	 */
10148 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10149 	    roundup(bsize, PAGESIZE), flags);
10150 
10151 	/*
10152 	 * pvn_write_kluster shouldn't have returned a page with offset
10153 	 * behind the original page we were given.  Verify that.
10154 	 */
10155 	ASSERT((pp->p_offset / bsize) >= lbn);
10156 
10157 	/*
10158 	 * Now pp will have the list of kept dirty pages marked for
10159 	 * write back.  It will also handle invalidation and freeing
10160 	 * of pages that are not dirty.  Check for page length rounding
10161 	 * problems.
10162 	 */
10163 	if (io_off + io_len > lbn_off + bsize) {
10164 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10165 		io_len = lbn_off + bsize - io_off;
10166 	}
10167 	/*
10168 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10169 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10170 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10171 	 * progress and the r_size has not been made consistent with the
10172 	 * new size of the file. When the uiomove() completes the r_size is
10173 	 * updated and the R4MODINPROGRESS flag is cleared.
10174 	 *
10175 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10176 	 * consistent value of r_size. Without this handshaking, it is
10177 	 * possible that nfs4_bio() picks  up the old value of r_size
10178 	 * before the uiomove() in writerp4() completes. This will result
10179 	 * in the write through nfs4_bio() being dropped.
10180 	 *
10181 	 * More precisely, there is a window between the time the uiomove()
10182 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10183 	 * operation intervenes in this window, the page will be picked up,
10184 	 * because it is dirty (it will be unlocked, unless it was
10185 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10186 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10187 	 * checked. This will still be the old size. Therefore the page will
10188 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10189 	 * the page will be found to be clean and the write will be dropped.
10190 	 */
10191 	if (rp->r_flags & R4MODINPROGRESS) {
10192 		mutex_enter(&rp->r_statelock);
10193 		if ((rp->r_flags & R4MODINPROGRESS) &&
10194 		    rp->r_modaddr + MAXBSIZE > io_off &&
10195 		    rp->r_modaddr < io_off + io_len) {
10196 			page_t *plist;
10197 			/*
10198 			 * A write is in progress for this region of the file.
10199 			 * If we did not detect R4MODINPROGRESS here then this
10200 			 * path through nfs_putapage() would eventually go to
10201 			 * nfs4_bio() and may not write out all of the data
10202 			 * in the pages. We end up losing data. So we decide
10203 			 * to set the modified bit on each page in the page
10204 			 * list and mark the rnode with R4DIRTY. This write
10205 			 * will be restarted at some later time.
10206 			 */
10207 			plist = pp;
10208 			while (plist != NULL) {
10209 				pp = plist;
10210 				page_sub(&plist, pp);
10211 				hat_setmod(pp);
10212 				page_io_unlock(pp);
10213 				page_unlock(pp);
10214 			}
10215 			rp->r_flags |= R4DIRTY;
10216 			mutex_exit(&rp->r_statelock);
10217 			if (offp)
10218 				*offp = io_off;
10219 			if (lenp)
10220 				*lenp = io_len;
10221 			return (0);
10222 		}
10223 		mutex_exit(&rp->r_statelock);
10224 	}
10225 
10226 	if (flags & B_ASYNC) {
10227 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10228 		    nfs4_sync_putapage);
10229 	} else
10230 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10231 
10232 	if (offp)
10233 		*offp = io_off;
10234 	if (lenp)
10235 		*lenp = io_len;
10236 	return (error);
10237 }
10238 
10239 static int
10240 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10241     int flags, cred_t *cr)
10242 {
10243 	int error;
10244 	rnode4_t *rp;
10245 
10246 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10247 
10248 	flags |= B_WRITE;
10249 
10250 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10251 
10252 	rp = VTOR4(vp);
10253 
10254 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10255 	    error == EACCES) &&
10256 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10257 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10258 			mutex_enter(&rp->r_statelock);
10259 			rp->r_flags |= R4OUTOFSPACE;
10260 			mutex_exit(&rp->r_statelock);
10261 		}
10262 		flags |= B_ERROR;
10263 		pvn_write_done(pp, flags);
10264 		/*
10265 		 * If this was not an async thread, then try again to
10266 		 * write out the pages, but this time, also destroy
10267 		 * them whether or not the write is successful.  This
10268 		 * will prevent memory from filling up with these
10269 		 * pages and destroying them is the only alternative
10270 		 * if they can't be written out.
10271 		 *
10272 		 * Don't do this if this is an async thread because
10273 		 * when the pages are unlocked in pvn_write_done,
10274 		 * some other thread could have come along, locked
10275 		 * them, and queued for an async thread.  It would be
10276 		 * possible for all of the async threads to be tied
10277 		 * up waiting to lock the pages again and they would
10278 		 * all already be locked and waiting for an async
10279 		 * thread to handle them.  Deadlock.
10280 		 */
10281 		if (!(flags & B_ASYNC)) {
10282 			error = nfs4_putpage(vp, io_off, io_len,
10283 			    B_INVAL | B_FORCE, cr, NULL);
10284 		}
10285 	} else {
10286 		if (error)
10287 			flags |= B_ERROR;
10288 		else if (rp->r_flags & R4OUTOFSPACE) {
10289 			mutex_enter(&rp->r_statelock);
10290 			rp->r_flags &= ~R4OUTOFSPACE;
10291 			mutex_exit(&rp->r_statelock);
10292 		}
10293 		pvn_write_done(pp, flags);
10294 		if (freemem < desfree)
10295 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10296 			    NFS4_WRITE_NOWAIT);
10297 	}
10298 
10299 	return (error);
10300 }
10301 
10302 #ifdef DEBUG
10303 int nfs4_force_open_before_mmap = 0;
10304 #endif
10305 
10306 /* ARGSUSED */
10307 static int
10308 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10309     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10310     caller_context_t *ct)
10311 {
10312 	struct segvn_crargs vn_a;
10313 	int error = 0;
10314 	rnode4_t *rp = VTOR4(vp);
10315 	mntinfo4_t *mi = VTOMI4(vp);
10316 
10317 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10318 		return (EIO);
10319 
10320 	if (vp->v_flag & VNOMAP)
10321 		return (ENOSYS);
10322 
10323 	if (off < 0 || (off + len) < 0)
10324 		return (ENXIO);
10325 
10326 	if (vp->v_type != VREG)
10327 		return (ENODEV);
10328 
10329 	/*
10330 	 * If the file is delegated to the client don't do anything.
10331 	 * If the file is not delegated, then validate the data cache.
10332 	 */
10333 	mutex_enter(&rp->r_statev4_lock);
10334 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10335 		mutex_exit(&rp->r_statev4_lock);
10336 		error = nfs4_validate_caches(vp, cr);
10337 		if (error)
10338 			return (error);
10339 	} else {
10340 		mutex_exit(&rp->r_statev4_lock);
10341 	}
10342 
10343 	/*
10344 	 * Check to see if the vnode is currently marked as not cachable.
10345 	 * This means portions of the file are locked (through VOP_FRLOCK).
10346 	 * In this case the map request must be refused.  We use
10347 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10348 	 */
10349 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
10350 		return (EINTR);
10351 
10352 	if (vp->v_flag & VNOCACHE) {
10353 		error = EAGAIN;
10354 		goto done;
10355 	}
10356 
10357 	/*
10358 	 * Don't allow concurrent locks and mapping if mandatory locking is
10359 	 * enabled.
10360 	 */
10361 	if (flk_has_remote_locks(vp)) {
10362 		struct vattr va;
10363 		va.va_mask = AT_MODE;
10364 		error = nfs4getattr(vp, &va, cr);
10365 		if (error != 0)
10366 			goto done;
10367 		if (MANDLOCK(vp, va.va_mode)) {
10368 			error = EAGAIN;
10369 			goto done;
10370 		}
10371 	}
10372 
10373 	/*
10374 	 * It is possible that the rnode has a lost lock request that we
10375 	 * are still trying to recover, and that the request conflicts with
10376 	 * this map request.
10377 	 *
10378 	 * An alternative approach would be for nfs4_safemap() to consider
10379 	 * queued lock requests when deciding whether to set or clear
10380 	 * VNOCACHE.  This would require the frlock code path to call
10381 	 * nfs4_safemap() after enqueing a lost request.
10382 	 */
10383 	if (nfs4_map_lost_lock_conflict(vp)) {
10384 		error = EAGAIN;
10385 		goto done;
10386 	}
10387 
10388 	as_rangelock(as);
10389 	if (!(flags & MAP_FIXED)) {
10390 		map_addr(addrp, len, off, 1, flags);
10391 		if (*addrp == NULL) {
10392 			as_rangeunlock(as);
10393 			error = ENOMEM;
10394 			goto done;
10395 		}
10396 	} else {
10397 		/*
10398 		 * User specified address - blow away any previous mappings
10399 		 */
10400 		(void) as_unmap(as, *addrp, len);
10401 	}
10402 
10403 	if (vp->v_type == VREG) {
10404 		/*
10405 		 * We need to retrieve the open stream
10406 		 */
10407 		nfs4_open_stream_t	*osp = NULL;
10408 		nfs4_open_owner_t	*oop = NULL;
10409 
10410 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10411 		if (oop != NULL) {
10412 			/* returns with 'os_sync_lock' held */
10413 			osp = find_open_stream(oop, rp);
10414 			open_owner_rele(oop);
10415 		}
10416 		if (osp == NULL) {
10417 #ifdef DEBUG
10418 			if (nfs4_force_open_before_mmap) {
10419 				error = EIO;
10420 				goto done;
10421 			}
10422 #endif
10423 			/* returns with 'os_sync_lock' held */
10424 			error = open_and_get_osp(vp, cr, &osp);
10425 			if (osp == NULL) {
10426 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10427 				    "nfs4_map: we tried to OPEN the file "
10428 				    "but again no osp, so fail with EIO"));
10429 				goto done;
10430 			}
10431 		}
10432 
10433 		if (osp->os_failed_reopen) {
10434 			mutex_exit(&osp->os_sync_lock);
10435 			open_stream_rele(osp, rp);
10436 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10437 			    "nfs4_map: os_failed_reopen set on "
10438 			    "osp %p, cr %p, rp %s", (void *)osp,
10439 			    (void *)cr, rnode4info(rp)));
10440 			error = EIO;
10441 			goto done;
10442 		}
10443 		mutex_exit(&osp->os_sync_lock);
10444 		open_stream_rele(osp, rp);
10445 	}
10446 
10447 	vn_a.vp = vp;
10448 	vn_a.offset = off;
10449 	vn_a.type = (flags & MAP_TYPE);
10450 	vn_a.prot = (uchar_t)prot;
10451 	vn_a.maxprot = (uchar_t)maxprot;
10452 	vn_a.flags = (flags & ~MAP_TYPE);
10453 	vn_a.cred = cr;
10454 	vn_a.amp = NULL;
10455 	vn_a.szc = 0;
10456 	vn_a.lgrp_mem_policy_flags = 0;
10457 
10458 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10459 	as_rangeunlock(as);
10460 
10461 done:
10462 	nfs_rw_exit(&rp->r_lkserlock);
10463 	return (error);
10464 }
10465 
10466 /*
10467  * We're most likely dealing with a kernel module that likes to READ
10468  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10469  * officially OPEN the file to create the necessary client state
10470  * for bookkeeping of os_mmap_read/write counts.
10471  *
10472  * Since VOP_MAP only passes in a pointer to the vnode rather than
10473  * a double pointer, we can't handle the case where nfs4open_otw()
10474  * returns a different vnode than the one passed into VOP_MAP (since
10475  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10476  * we return NULL and let nfs4_map() fail.  Note: the only case where
10477  * this should happen is if the file got removed and replaced with the
10478  * same name on the server (in addition to the fact that we're trying
10479  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10480  */
10481 static int
10482 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10483 {
10484 	rnode4_t		*rp, *drp;
10485 	vnode_t			*dvp, *open_vp;
10486 	char			file_name[MAXNAMELEN];
10487 	int			just_created;
10488 	nfs4_open_stream_t	*osp;
10489 	nfs4_open_owner_t	*oop;
10490 	int			error;
10491 
10492 	*ospp = NULL;
10493 	open_vp = map_vp;
10494 
10495 	rp = VTOR4(open_vp);
10496 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10497 		return (error);
10498 	drp = VTOR4(dvp);
10499 
10500 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10501 		VN_RELE(dvp);
10502 		return (EINTR);
10503 	}
10504 
10505 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10506 		nfs_rw_exit(&drp->r_rwlock);
10507 		VN_RELE(dvp);
10508 		return (error);
10509 	}
10510 
10511 	mutex_enter(&rp->r_statev4_lock);
10512 	if (rp->created_v4) {
10513 		rp->created_v4 = 0;
10514 		mutex_exit(&rp->r_statev4_lock);
10515 
10516 		dnlc_update(dvp, file_name, open_vp);
10517 		/* This is needed so we don't bump the open ref count */
10518 		just_created = 1;
10519 	} else {
10520 		mutex_exit(&rp->r_statev4_lock);
10521 		just_created = 0;
10522 	}
10523 
10524 	VN_HOLD(map_vp);
10525 
10526 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10527 	    just_created);
10528 	if (error) {
10529 		nfs_rw_exit(&drp->r_rwlock);
10530 		VN_RELE(dvp);
10531 		VN_RELE(map_vp);
10532 		return (error);
10533 	}
10534 
10535 	nfs_rw_exit(&drp->r_rwlock);
10536 	VN_RELE(dvp);
10537 
10538 	/*
10539 	 * If nfs4open_otw() returned a different vnode then "undo"
10540 	 * the open and return failure to the caller.
10541 	 */
10542 	if (!VN_CMP(open_vp, map_vp)) {
10543 		nfs4_error_t e;
10544 
10545 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10546 		    "open returned a different vnode"));
10547 		/*
10548 		 * If there's an error, ignore it,
10549 		 * and let VOP_INACTIVE handle it.
10550 		 */
10551 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10552 		    CLOSE_NORM, 0, 0, 0);
10553 		VN_RELE(map_vp);
10554 		return (EIO);
10555 	}
10556 
10557 	VN_RELE(map_vp);
10558 
10559 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10560 	if (!oop) {
10561 		nfs4_error_t e;
10562 
10563 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10564 		    "no open owner"));
10565 		/*
10566 		 * If there's an error, ignore it,
10567 		 * and let VOP_INACTIVE handle it.
10568 		 */
10569 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10570 		    CLOSE_NORM, 0, 0, 0);
10571 		return (EIO);
10572 	}
10573 	osp = find_open_stream(oop, rp);
10574 	open_owner_rele(oop);
10575 	*ospp = osp;
10576 	return (0);
10577 }
10578 
10579 /*
10580  * Please be aware that when this function is called, the address space write
10581  * a_lock is held.  Do not put over the wire calls in this function.
10582  */
10583 /* ARGSUSED */
10584 static int
10585 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10586     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10587     caller_context_t *ct)
10588 {
10589 	rnode4_t		*rp;
10590 	int			error = 0;
10591 	mntinfo4_t		*mi;
10592 
10593 	mi = VTOMI4(vp);
10594 	rp = VTOR4(vp);
10595 
10596 	if (nfs_zone() != mi->mi_zone)
10597 		return (EIO);
10598 	if (vp->v_flag & VNOMAP)
10599 		return (ENOSYS);
10600 
10601 	/*
10602 	 * Need to hold rwlock while incrementing the mapcnt so that
10603 	 * mmap'ing can be serialized with writes so that the caching
10604 	 * can be handled correctly.
10605 	 *
10606 	 * Don't need to update the open stream first, since this
10607 	 * mmap can't add any additional share access that isn't
10608 	 * already contained in the open stream (for the case where we
10609 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10610 	 * take into account os_mmap_read[write] counts).
10611 	 */
10612 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR(vp)))
10613 		return (EINTR);
10614 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10615 	nfs_rw_exit(&rp->r_rwlock);
10616 
10617 	if (vp->v_type == VREG) {
10618 		/*
10619 		 * We need to retrieve the open stream and update the counts.
10620 		 * If there is no open stream here, something is wrong.
10621 		 */
10622 		nfs4_open_stream_t	*osp = NULL;
10623 		nfs4_open_owner_t	*oop = NULL;
10624 
10625 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10626 		if (oop != NULL) {
10627 			/* returns with 'os_sync_lock' held */
10628 			osp = find_open_stream(oop, rp);
10629 			open_owner_rele(oop);
10630 		}
10631 		if (osp == NULL) {
10632 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10633 			    "nfs4_addmap: we should have an osp"
10634 			    "but we don't, so fail with EIO"));
10635 			error = EIO;
10636 			goto out;
10637 		}
10638 
10639 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10640 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10641 
10642 		/*
10643 		 * Update the map count in the open stream.
10644 		 * This is necessary in the case where we
10645 		 * open/mmap/close/, then the server reboots, and we
10646 		 * attempt to reopen.  If the mmap doesn't add share
10647 		 * access then we send an invalid reopen with
10648 		 * access = NONE.
10649 		 *
10650 		 * We need to specifically check each PROT_* so a mmap
10651 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10652 		 * read and write access.  A simple comparison of prot
10653 		 * to ~PROT_WRITE to determine read access is insufficient
10654 		 * since prot can be |= with PROT_USER, etc.
10655 		 */
10656 
10657 		/*
10658 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10659 		 */
10660 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10661 			osp->os_mmap_write += btopr(len);
10662 		if (maxprot & PROT_READ)
10663 			osp->os_mmap_read += btopr(len);
10664 		if (maxprot & PROT_EXEC)
10665 			osp->os_mmap_read += btopr(len);
10666 		/*
10667 		 * Ensure that os_mmap_read gets incremented, even if
10668 		 * maxprot were to look like PROT_NONE.
10669 		 */
10670 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10671 		    !(maxprot & PROT_EXEC))
10672 			osp->os_mmap_read += btopr(len);
10673 		osp->os_mapcnt += btopr(len);
10674 		mutex_exit(&osp->os_sync_lock);
10675 		open_stream_rele(osp, rp);
10676 	}
10677 
10678 out:
10679 	/*
10680 	 * If we got an error, then undo our
10681 	 * incrementing of 'r_mapcnt'.
10682 	 */
10683 
10684 	if (error) {
10685 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10686 		ASSERT(rp->r_mapcnt >= 0);
10687 	}
10688 	return (error);
10689 }
10690 
10691 /* ARGSUSED */
10692 static int
10693 nfs4_cmp(vnode_t *vp1, vnode_t *vp2, caller_context_t *ct)
10694 {
10695 
10696 	return (VTOR4(vp1) == VTOR4(vp2));
10697 }
10698 
10699 /* ARGSUSED */
10700 static int
10701 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10702     offset_t offset, struct flk_callback *flk_cbp, cred_t *cr,
10703     caller_context_t *ct)
10704 {
10705 	int rc;
10706 	u_offset_t start, end;
10707 	rnode4_t *rp;
10708 	int error = 0, intr = INTR4(vp);
10709 	nfs4_error_t e;
10710 
10711 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10712 		return (EIO);
10713 
10714 	/* check for valid cmd parameter */
10715 	if (cmd != F_GETLK && cmd != F_SETLK && cmd != F_SETLKW)
10716 		return (EINVAL);
10717 
10718 	/* Verify l_type. */
10719 	switch (bfp->l_type) {
10720 	case F_RDLCK:
10721 		if (cmd != F_GETLK && !(flag & FREAD))
10722 			return (EBADF);
10723 		break;
10724 	case F_WRLCK:
10725 		if (cmd != F_GETLK && !(flag & FWRITE))
10726 			return (EBADF);
10727 		break;
10728 	case F_UNLCK:
10729 		intr = 0;
10730 		break;
10731 
10732 	default:
10733 		return (EINVAL);
10734 	}
10735 
10736 	/* check the validity of the lock range */
10737 	if (rc = flk_convert_lock_data(vp, bfp, &start, &end, offset))
10738 		return (rc);
10739 	if (rc = flk_check_lock_data(start, end, MAXEND))
10740 		return (rc);
10741 
10742 	/*
10743 	 * If the filesystem is mounted using local locking, pass the
10744 	 * request off to the local locking code.
10745 	 */
10746 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10747 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10748 			/*
10749 			 * For complete safety, we should be holding
10750 			 * r_lkserlock.  However, we can't call
10751 			 * nfs4_safelock and then fs_frlock while
10752 			 * holding r_lkserlock, so just invoke
10753 			 * nfs4_safelock and expect that this will
10754 			 * catch enough of the cases.
10755 			 */
10756 			if (!nfs4_safelock(vp, bfp, cr))
10757 				return (EAGAIN);
10758 		}
10759 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
10760 	}
10761 
10762 	rp = VTOR4(vp);
10763 
10764 	/*
10765 	 * Check whether the given lock request can proceed, given the
10766 	 * current file mappings.
10767 	 */
10768 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr))
10769 		return (EINTR);
10770 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10771 		if (!nfs4_safelock(vp, bfp, cr)) {
10772 			rc = EAGAIN;
10773 			goto done;
10774 		}
10775 	}
10776 
10777 	/*
10778 	 * Flush the cache after waiting for async I/O to finish.  For new
10779 	 * locks, this is so that the process gets the latest bits from the
10780 	 * server.  For unlocks, this is so that other clients see the
10781 	 * latest bits once the file has been unlocked.  If currently dirty
10782 	 * pages can't be flushed, then don't allow a lock to be set.  But
10783 	 * allow unlocks to succeed, to avoid having orphan locks on the
10784 	 * server.
10785 	 */
10786 	if (cmd != F_GETLK) {
10787 		mutex_enter(&rp->r_statelock);
10788 		while (rp->r_count > 0) {
10789 			if (intr) {
10790 				klwp_t *lwp = ttolwp(curthread);
10791 
10792 				if (lwp != NULL)
10793 					lwp->lwp_nostop++;
10794 				if (cv_wait_sig(&rp->r_cv,
10795 				    &rp->r_statelock) == 0) {
10796 					if (lwp != NULL)
10797 						lwp->lwp_nostop--;
10798 					rc = EINTR;
10799 					break;
10800 				}
10801 				if (lwp != NULL)
10802 					lwp->lwp_nostop--;
10803 				} else
10804 					cv_wait(&rp->r_cv, &rp->r_statelock);
10805 		}
10806 		mutex_exit(&rp->r_statelock);
10807 		if (rc != 0)
10808 			goto done;
10809 		error = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr, ct);
10810 		if (error) {
10811 			if (error == ENOSPC || error == EDQUOT) {
10812 				mutex_enter(&rp->r_statelock);
10813 				if (!rp->r_error)
10814 					rp->r_error = error;
10815 				mutex_exit(&rp->r_statelock);
10816 			}
10817 			if (bfp->l_type != F_UNLCK) {
10818 				rc = ENOLCK;
10819 				goto done;
10820 			}
10821 		}
10822 	}
10823 
10824 	/*
10825 	 * Call the lock manager to do the real work of contacting
10826 	 * the server and obtaining the lock.
10827 	 */
10828 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, flag, offset,
10829 	    cr, &e, NULL, NULL);
10830 	rc = e.error;
10831 
10832 	if (rc == 0)
10833 		nfs4_lockcompletion(vp, cmd);
10834 
10835 done:
10836 	nfs_rw_exit(&rp->r_lkserlock);
10837 
10838 	return (rc);
10839 }
10840 
10841 /*
10842  * Free storage space associated with the specified vnode.  The portion
10843  * to be freed is specified by bfp->l_start and bfp->l_len (already
10844  * normalized to a "whence" of 0).
10845  *
10846  * This is an experimental facility whose continued existence is not
10847  * guaranteed.  Currently, we only support the special case
10848  * of l_len == 0, meaning free to end of file.
10849  */
10850 /* ARGSUSED */
10851 static int
10852 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10853     offset_t offset, cred_t *cr, caller_context_t *ct)
10854 {
10855 	int error;
10856 
10857 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10858 		return (EIO);
10859 	ASSERT(vp->v_type == VREG);
10860 	if (cmd != F_FREESP)
10861 		return (EINVAL);
10862 
10863 	error = convoff(vp, bfp, 0, offset);
10864 	if (!error) {
10865 		ASSERT(bfp->l_start >= 0);
10866 		if (bfp->l_len == 0) {
10867 			struct vattr va;
10868 
10869 			va.va_mask = AT_SIZE;
10870 			va.va_size = bfp->l_start;
10871 			error = nfs4setattr(vp, &va, 0, cr, NULL);
10872 		} else
10873 			error = EINVAL;
10874 	}
10875 
10876 	return (error);
10877 }
10878 
10879 /* ARGSUSED */
10880 int
10881 nfs4_realvp(vnode_t *vp, vnode_t **vpp, caller_context_t *ct)
10882 {
10883 	rnode4_t *rp;
10884 	rp = VTOR4(vp);
10885 
10886 	if (vp->v_type == VREG && IS_SHADOW(vp, rp)) {
10887 		vp = RTOV4(rp);
10888 	}
10889 	*vpp = vp;
10890 	return (0);
10891 }
10892 
10893 /*
10894  * Setup and add an address space callback to do the work of the delmap call.
10895  * The callback will (and must be) deleted in the actual callback function.
10896  *
10897  * This is done in order to take care of the problem that we have with holding
10898  * the address space's a_lock for a long period of time (e.g. if the NFS server
10899  * is down).  Callbacks will be executed in the address space code while the
10900  * a_lock is not held.  Holding the address space's a_lock causes things such
10901  * as ps and fork to hang because they are trying to acquire this lock as well.
10902  */
10903 /* ARGSUSED */
10904 static int
10905 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10906     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
10907     caller_context_t *ct)
10908 {
10909 	int			caller_found;
10910 	int			error;
10911 	rnode4_t		*rp;
10912 	nfs4_delmap_args_t	*dmapp;
10913 	nfs4_delmapcall_t	*delmap_call;
10914 
10915 	if (vp->v_flag & VNOMAP)
10916 		return (ENOSYS);
10917 
10918 	/*
10919 	 * A process may not change zones if it has NFS pages mmap'ed
10920 	 * in, so we can't legitimately get here from the wrong zone.
10921 	 */
10922 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10923 
10924 	rp = VTOR4(vp);
10925 
10926 	/*
10927 	 * The way that the address space of this process deletes its mapping
10928 	 * of this file is via the following call chains:
10929 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10930 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10931 	 *
10932 	 * With the use of address space callbacks we are allowed to drop the
10933 	 * address space lock, a_lock, while executing the NFS operations that
10934 	 * need to go over the wire.  Returning EAGAIN to the caller of this
10935 	 * function is what drives the execution of the callback that we add
10936 	 * below.  The callback will be executed by the address space code
10937 	 * after dropping the a_lock.  When the callback is finished, since
10938 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
10939 	 * is called again on the same segment to finish the rest of the work
10940 	 * that needs to happen during unmapping.
10941 	 *
10942 	 * This action of calling back into the segment driver causes
10943 	 * nfs4_delmap() to get called again, but since the callback was
10944 	 * already executed at this point, it already did the work and there
10945 	 * is nothing left for us to do.
10946 	 *
10947 	 * To Summarize:
10948 	 * - The first time nfs4_delmap is called by the current thread is when
10949 	 * we add the caller associated with this delmap to the delmap caller
10950 	 * list, add the callback, and return EAGAIN.
10951 	 * - The second time in this call chain when nfs4_delmap is called we
10952 	 * will find this caller in the delmap caller list and realize there
10953 	 * is no more work to do thus removing this caller from the list and
10954 	 * returning the error that was set in the callback execution.
10955 	 */
10956 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
10957 	if (caller_found) {
10958 		/*
10959 		 * 'error' is from the actual delmap operations.  To avoid
10960 		 * hangs, we need to handle the return of EAGAIN differently
10961 		 * since this is what drives the callback execution.
10962 		 * In this case, we don't want to return EAGAIN and do the
10963 		 * callback execution because there are none to execute.
10964 		 */
10965 		if (error == EAGAIN)
10966 			return (0);
10967 		else
10968 			return (error);
10969 	}
10970 
10971 	/* current caller was not in the list */
10972 	delmap_call = nfs4_init_delmapcall();
10973 
10974 	mutex_enter(&rp->r_statelock);
10975 	list_insert_tail(&rp->r_indelmap, delmap_call);
10976 	mutex_exit(&rp->r_statelock);
10977 
10978 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
10979 
10980 	dmapp->vp = vp;
10981 	dmapp->off = off;
10982 	dmapp->addr = addr;
10983 	dmapp->len = len;
10984 	dmapp->prot = prot;
10985 	dmapp->maxprot = maxprot;
10986 	dmapp->flags = flags;
10987 	dmapp->cr = cr;
10988 	dmapp->caller = delmap_call;
10989 
10990 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
10991 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
10992 
10993 	return (error ? error : EAGAIN);
10994 }
10995 
10996 static nfs4_delmapcall_t *
10997 nfs4_init_delmapcall()
10998 {
10999 	nfs4_delmapcall_t	*delmap_call;
11000 
11001 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
11002 	delmap_call->call_id = curthread;
11003 	delmap_call->error = 0;
11004 
11005 	return (delmap_call);
11006 }
11007 
11008 static void
11009 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11010 {
11011 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11012 }
11013 
11014 /*
11015  * Searches for the current delmap caller (based on curthread) in the list of
11016  * callers.  If it is found, we remove it and free the delmap caller.
11017  * Returns:
11018  *      0 if the caller wasn't found
11019  *      1 if the caller was found, removed and freed.  *errp will be set
11020  *	to what the result of the delmap was.
11021  */
11022 static int
11023 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11024 {
11025 	nfs4_delmapcall_t	*delmap_call;
11026 
11027 	/*
11028 	 * If the list doesn't exist yet, we create it and return
11029 	 * that the caller wasn't found.  No list = no callers.
11030 	 */
11031 	mutex_enter(&rp->r_statelock);
11032 	if (!(rp->r_flags & R4DELMAPLIST)) {
11033 		/* The list does not exist */
11034 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11035 		    offsetof(nfs4_delmapcall_t, call_node));
11036 		rp->r_flags |= R4DELMAPLIST;
11037 		mutex_exit(&rp->r_statelock);
11038 		return (0);
11039 	} else {
11040 		/* The list exists so search it */
11041 		for (delmap_call = list_head(&rp->r_indelmap);
11042 		    delmap_call != NULL;
11043 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11044 			if (delmap_call->call_id == curthread) {
11045 				/* current caller is in the list */
11046 				*errp = delmap_call->error;
11047 				list_remove(&rp->r_indelmap, delmap_call);
11048 				mutex_exit(&rp->r_statelock);
11049 				nfs4_free_delmapcall(delmap_call);
11050 				return (1);
11051 			}
11052 		}
11053 	}
11054 	mutex_exit(&rp->r_statelock);
11055 	return (0);
11056 }
11057 
11058 /*
11059  * Remove some pages from an mmap'd vnode.  Just update the
11060  * count of pages.  If doing close-to-open, then flush and
11061  * commit all of the pages associated with this file.
11062  * Otherwise, start an asynchronous page flush to write out
11063  * any dirty pages.  This will also associate a credential
11064  * with the rnode which can be used to write the pages.
11065  */
11066 /* ARGSUSED */
11067 static void
11068 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11069 {
11070 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11071 	rnode4_t		*rp;
11072 	mntinfo4_t		*mi;
11073 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11074 
11075 	rp = VTOR4(dmapp->vp);
11076 	mi = VTOMI4(dmapp->vp);
11077 
11078 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11079 	ASSERT(rp->r_mapcnt >= 0);
11080 
11081 	/*
11082 	 * Initiate a page flush and potential commit if there are
11083 	 * pages, the file system was not mounted readonly, the segment
11084 	 * was mapped shared, and the pages themselves were writeable.
11085 	 */
11086 	if (nfs4_has_pages(dmapp->vp) &&
11087 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11088 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11089 		mutex_enter(&rp->r_statelock);
11090 		rp->r_flags |= R4DIRTY;
11091 		mutex_exit(&rp->r_statelock);
11092 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11093 		    dmapp->len, dmapp->cr);
11094 		if (!e.error) {
11095 			mutex_enter(&rp->r_statelock);
11096 			e.error = rp->r_error;
11097 			rp->r_error = 0;
11098 			mutex_exit(&rp->r_statelock);
11099 		}
11100 	} else
11101 		e.error = 0;
11102 
11103 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11104 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11105 		    B_INVAL, dmapp->cr, NULL);
11106 
11107 	if (e.error) {
11108 		e.stat = puterrno4(e.error);
11109 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11110 		    OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11111 		dmapp->caller->error = e.error;
11112 	}
11113 
11114 	/* Check to see if we need to close the file */
11115 
11116 	if (dmapp->vp->v_type == VREG) {
11117 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11118 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11119 
11120 		if (e.error != 0 || e.stat != NFS4_OK) {
11121 			/*
11122 			 * Since it is possible that e.error == 0 and
11123 			 * e.stat != NFS4_OK (and vice versa),
11124 			 * we do the proper checking in order to get both
11125 			 * e.error and e.stat reporting the correct info.
11126 			 */
11127 			if (e.stat == NFS4_OK)
11128 				e.stat = puterrno4(e.error);
11129 			if (e.error == 0)
11130 				e.error = geterrno4(e.stat);
11131 
11132 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11133 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11134 			dmapp->caller->error = e.error;
11135 		}
11136 	}
11137 
11138 	(void) as_delete_callback(as, arg);
11139 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11140 }
11141 
11142 
11143 static uint_t
11144 fattr4_maxfilesize_to_bits(uint64_t ll)
11145 {
11146 	uint_t l = 1;
11147 
11148 	if (ll == 0) {
11149 		return (0);
11150 	}
11151 
11152 	if (ll & 0xffffffff00000000) {
11153 		l += 32; ll >>= 32;
11154 	}
11155 	if (ll & 0xffff0000) {
11156 		l += 16; ll >>= 16;
11157 	}
11158 	if (ll & 0xff00) {
11159 		l += 8; ll >>= 8;
11160 	}
11161 	if (ll & 0xf0) {
11162 		l += 4; ll >>= 4;
11163 	}
11164 	if (ll & 0xc) {
11165 		l += 2; ll >>= 2;
11166 	}
11167 	if (ll & 0x2) {
11168 		l += 1;
11169 	}
11170 	return (l);
11171 }
11172 
11173 /* ARGSUSED */
11174 int
11175 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
11176 	caller_context_t *ct)
11177 {
11178 	int error;
11179 	hrtime_t t;
11180 	rnode4_t *rp;
11181 	nfs4_ga_res_t gar;
11182 	nfs4_ga_ext_res_t ger;
11183 
11184 	gar.n4g_ext_res = &ger;
11185 
11186 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11187 		return (EIO);
11188 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11189 		*valp = MAXPATHLEN;
11190 		return (0);
11191 	}
11192 	if (cmd == _PC_ACL_ENABLED) {
11193 		*valp = _ACL_ACE_ENABLED;
11194 		return (0);
11195 	}
11196 
11197 	rp = VTOR4(vp);
11198 	if (cmd == _PC_XATTR_EXISTS) {
11199 		/*
11200 		 * Eventually should attempt small client readdir before
11201 		 * going otw with GETATTR(FATTR4_NAMED_ATTR).  For now
11202 		 * just drive the OTW getattr.  This is required because
11203 		 * _PC_XATTR_EXISTS can only return true if attributes
11204 		 * exist -- simply checking for existence of the attrdir
11205 		 * is not sufficient.
11206 		 *
11207 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11208 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11209 		 * and we don't have any way to update the "base" object's
11210 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11211 		 * could help out.
11212 		 */
11213 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11214 		    rp->r_xattr_dir == NULL) {
11215 			*valp = rp->r_pathconf.pc4_xattr_exists;
11216 			return (0);
11217 		}
11218 	} else {  /* OLD CODE */
11219 		if (ATTRCACHE4_VALID(vp)) {
11220 			mutex_enter(&rp->r_statelock);
11221 			if (rp->r_pathconf.pc4_cache_valid) {
11222 				error = 0;
11223 				switch (cmd) {
11224 				case _PC_FILESIZEBITS:
11225 					*valp =
11226 					    rp->r_pathconf.pc4_filesizebits;
11227 					break;
11228 				case _PC_LINK_MAX:
11229 					*valp =
11230 					    rp->r_pathconf.pc4_link_max;
11231 					break;
11232 				case _PC_NAME_MAX:
11233 					*valp =
11234 					    rp->r_pathconf.pc4_name_max;
11235 					break;
11236 				case _PC_CHOWN_RESTRICTED:
11237 					*valp =
11238 					    rp->r_pathconf.pc4_chown_restricted;
11239 					break;
11240 				case _PC_NO_TRUNC:
11241 					*valp =
11242 					    rp->r_pathconf.pc4_no_trunc;
11243 					break;
11244 				default:
11245 					error = EINVAL;
11246 					break;
11247 				}
11248 				mutex_exit(&rp->r_statelock);
11249 #ifdef DEBUG
11250 				nfs4_pathconf_cache_hits++;
11251 #endif
11252 				return (error);
11253 			}
11254 			mutex_exit(&rp->r_statelock);
11255 		}
11256 	}
11257 #ifdef DEBUG
11258 	nfs4_pathconf_cache_misses++;
11259 #endif
11260 
11261 	t = gethrtime();
11262 
11263 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11264 
11265 	if (error) {
11266 		mutex_enter(&rp->r_statelock);
11267 		rp->r_pathconf.pc4_cache_valid = FALSE;
11268 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11269 		mutex_exit(&rp->r_statelock);
11270 		return (error);
11271 	}
11272 
11273 	/* interpret the max filesize */
11274 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11275 	    fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11276 
11277 	/* Store the attributes we just received */
11278 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11279 
11280 	switch (cmd) {
11281 	case _PC_FILESIZEBITS:
11282 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11283 		break;
11284 	case _PC_LINK_MAX:
11285 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11286 		break;
11287 	case _PC_NAME_MAX:
11288 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11289 		break;
11290 	case _PC_CHOWN_RESTRICTED:
11291 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11292 		break;
11293 	case _PC_NO_TRUNC:
11294 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11295 		break;
11296 	case _PC_XATTR_EXISTS:
11297 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists;
11298 		break;
11299 	default:
11300 		return (EINVAL);
11301 	}
11302 
11303 	return (0);
11304 }
11305 
11306 /*
11307  * Called by async thread to do synchronous pageio. Do the i/o, wait
11308  * for it to complete, and cleanup the page list when done.
11309  */
11310 static int
11311 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11312     int flags, cred_t *cr)
11313 {
11314 	int error;
11315 
11316 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11317 
11318 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11319 	if (flags & B_READ)
11320 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11321 	else
11322 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11323 	return (error);
11324 }
11325 
11326 /* ARGSUSED */
11327 static int
11328 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11329 	int flags, cred_t *cr, caller_context_t *ct)
11330 {
11331 	int error;
11332 	rnode4_t *rp;
11333 
11334 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11335 		return (EIO);
11336 
11337 	if (pp == NULL)
11338 		return (EINVAL);
11339 
11340 	rp = VTOR4(vp);
11341 	mutex_enter(&rp->r_statelock);
11342 	rp->r_count++;
11343 	mutex_exit(&rp->r_statelock);
11344 
11345 	if (flags & B_ASYNC) {
11346 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11347 		    nfs4_sync_pageio);
11348 	} else
11349 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11350 	mutex_enter(&rp->r_statelock);
11351 	rp->r_count--;
11352 	cv_broadcast(&rp->r_cv);
11353 	mutex_exit(&rp->r_statelock);
11354 	return (error);
11355 }
11356 
11357 /* ARGSUSED */
11358 static void
11359 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr,
11360 	caller_context_t *ct)
11361 {
11362 	int error;
11363 	rnode4_t *rp;
11364 	page_t *plist;
11365 	page_t *pptr;
11366 	offset3 offset;
11367 	count3 len;
11368 	k_sigset_t smask;
11369 
11370 	/*
11371 	 * We should get called with fl equal to either B_FREE or
11372 	 * B_INVAL.  Any other value is illegal.
11373 	 *
11374 	 * The page that we are either supposed to free or destroy
11375 	 * should be exclusive locked and its io lock should not
11376 	 * be held.
11377 	 */
11378 	ASSERT(fl == B_FREE || fl == B_INVAL);
11379 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11380 
11381 	rp = VTOR4(vp);
11382 
11383 	/*
11384 	 * If the page doesn't need to be committed or we shouldn't
11385 	 * even bother attempting to commit it, then just make sure
11386 	 * that the p_fsdata byte is clear and then either free or
11387 	 * destroy the page as appropriate.
11388 	 */
11389 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11390 		pp->p_fsdata = C_NOCOMMIT;
11391 		if (fl == B_FREE)
11392 			page_free(pp, dn);
11393 		else
11394 			page_destroy(pp, dn);
11395 		return;
11396 	}
11397 
11398 	/*
11399 	 * If there is a page invalidation operation going on, then
11400 	 * if this is one of the pages being destroyed, then just
11401 	 * clear the p_fsdata byte and then either free or destroy
11402 	 * the page as appropriate.
11403 	 */
11404 	mutex_enter(&rp->r_statelock);
11405 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11406 		mutex_exit(&rp->r_statelock);
11407 		pp->p_fsdata = C_NOCOMMIT;
11408 		if (fl == B_FREE)
11409 			page_free(pp, dn);
11410 		else
11411 			page_destroy(pp, dn);
11412 		return;
11413 	}
11414 
11415 	/*
11416 	 * If we are freeing this page and someone else is already
11417 	 * waiting to do a commit, then just unlock the page and
11418 	 * return.  That other thread will take care of commiting
11419 	 * this page.  The page can be freed sometime after the
11420 	 * commit has finished.  Otherwise, if the page is marked
11421 	 * as delay commit, then we may be getting called from
11422 	 * pvn_write_done, one page at a time.   This could result
11423 	 * in one commit per page, so we end up doing lots of small
11424 	 * commits instead of fewer larger commits.  This is bad,
11425 	 * we want do as few commits as possible.
11426 	 */
11427 	if (fl == B_FREE) {
11428 		if (rp->r_flags & R4COMMITWAIT) {
11429 			page_unlock(pp);
11430 			mutex_exit(&rp->r_statelock);
11431 			return;
11432 		}
11433 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11434 			pp->p_fsdata = C_COMMIT;
11435 			page_unlock(pp);
11436 			mutex_exit(&rp->r_statelock);
11437 			return;
11438 		}
11439 	}
11440 
11441 	/*
11442 	 * Check to see if there is a signal which would prevent an
11443 	 * attempt to commit the pages from being successful.  If so,
11444 	 * then don't bother with all of the work to gather pages and
11445 	 * generate the unsuccessful RPC.  Just return from here and
11446 	 * let the page be committed at some later time.
11447 	 */
11448 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11449 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11450 		sigunintr(&smask);
11451 		page_unlock(pp);
11452 		mutex_exit(&rp->r_statelock);
11453 		return;
11454 	}
11455 	sigunintr(&smask);
11456 
11457 	/*
11458 	 * We are starting to need to commit pages, so let's try
11459 	 * to commit as many as possible at once to reduce the
11460 	 * overhead.
11461 	 *
11462 	 * Set the `commit inprogress' state bit.  We must
11463 	 * first wait until any current one finishes.  Then
11464 	 * we initialize the c_pages list with this page.
11465 	 */
11466 	while (rp->r_flags & R4COMMIT) {
11467 		rp->r_flags |= R4COMMITWAIT;
11468 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11469 		rp->r_flags &= ~R4COMMITWAIT;
11470 	}
11471 	rp->r_flags |= R4COMMIT;
11472 	mutex_exit(&rp->r_statelock);
11473 	ASSERT(rp->r_commit.c_pages == NULL);
11474 	rp->r_commit.c_pages = pp;
11475 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11476 	rp->r_commit.c_commlen = PAGESIZE;
11477 
11478 	/*
11479 	 * Gather together all other pages which can be committed.
11480 	 * They will all be chained off r_commit.c_pages.
11481 	 */
11482 	nfs4_get_commit(vp);
11483 
11484 	/*
11485 	 * Clear the `commit inprogress' status and disconnect
11486 	 * the list of pages to be committed from the rnode.
11487 	 * At this same time, we also save the starting offset
11488 	 * and length of data to be committed on the server.
11489 	 */
11490 	plist = rp->r_commit.c_pages;
11491 	rp->r_commit.c_pages = NULL;
11492 	offset = rp->r_commit.c_commbase;
11493 	len = rp->r_commit.c_commlen;
11494 	mutex_enter(&rp->r_statelock);
11495 	rp->r_flags &= ~R4COMMIT;
11496 	cv_broadcast(&rp->r_commit.c_cv);
11497 	mutex_exit(&rp->r_statelock);
11498 
11499 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11500 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11501 		nfs4_async_commit(vp, plist, offset, len,
11502 		    cr, do_nfs4_async_commit);
11503 		return;
11504 	}
11505 
11506 	/*
11507 	 * Actually generate the COMMIT op over the wire operation.
11508 	 */
11509 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11510 
11511 	/*
11512 	 * If we got an error during the commit, just unlock all
11513 	 * of the pages.  The pages will get retransmitted to the
11514 	 * server during a putpage operation.
11515 	 */
11516 	if (error) {
11517 		while (plist != NULL) {
11518 			pptr = plist;
11519 			page_sub(&plist, pptr);
11520 			page_unlock(pptr);
11521 		}
11522 		return;
11523 	}
11524 
11525 	/*
11526 	 * We've tried as hard as we can to commit the data to stable
11527 	 * storage on the server.  We just unlock the rest of the pages
11528 	 * and clear the commit required state.  They will be put
11529 	 * onto the tail of the cachelist if they are nolonger
11530 	 * mapped.
11531 	 */
11532 	while (plist != pp) {
11533 		pptr = plist;
11534 		page_sub(&plist, pptr);
11535 		pptr->p_fsdata = C_NOCOMMIT;
11536 		page_unlock(pptr);
11537 	}
11538 
11539 	/*
11540 	 * It is possible that nfs4_commit didn't return error but
11541 	 * some other thread has modified the page we are going
11542 	 * to free/destroy.
11543 	 *    In this case we need to rewrite the page. Do an explicit check
11544 	 * before attempting to free/destroy the page. If modified, needs to
11545 	 * be rewritten so unlock the page and return.
11546 	 */
11547 	if (hat_ismod(pp)) {
11548 		pp->p_fsdata = C_NOCOMMIT;
11549 		page_unlock(pp);
11550 		return;
11551 	}
11552 
11553 	/*
11554 	 * Now, as appropriate, either free or destroy the page
11555 	 * that we were called with.
11556 	 */
11557 	pp->p_fsdata = C_NOCOMMIT;
11558 	if (fl == B_FREE)
11559 		page_free(pp, dn);
11560 	else
11561 		page_destroy(pp, dn);
11562 }
11563 
11564 /*
11565  * Commit requires that the current fh be the file written to.
11566  * The compound op structure is:
11567  *      PUTFH(file), COMMIT
11568  */
11569 static int
11570 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11571 {
11572 	COMPOUND4args_clnt args;
11573 	COMPOUND4res_clnt res;
11574 	COMMIT4res *cm_res;
11575 	nfs_argop4 argop[2];
11576 	nfs_resop4 *resop;
11577 	int doqueue;
11578 	mntinfo4_t *mi;
11579 	rnode4_t *rp;
11580 	cred_t *cred_otw = NULL;
11581 	bool_t needrecov = FALSE;
11582 	nfs4_recov_state_t recov_state;
11583 	nfs4_open_stream_t *osp = NULL;
11584 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11585 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11586 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11587 
11588 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11589 
11590 	rp = VTOR4(vp);
11591 
11592 	mi = VTOMI4(vp);
11593 	recov_state.rs_flags = 0;
11594 	recov_state.rs_num_retry_despite_err = 0;
11595 get_commit_cred:
11596 	/*
11597 	 * Releases the osp, if a valid open stream is provided.
11598 	 * Puts a hold on the cred_otw and the new osp (if found).
11599 	 */
11600 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11601 	    &first_time, &last_time);
11602 	args.ctag = TAG_COMMIT;
11603 recov_retry:
11604 	/*
11605 	 * Commit ops: putfh file; commit
11606 	 */
11607 	args.array_len = 2;
11608 	args.array = argop;
11609 
11610 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11611 	    &recov_state, NULL);
11612 	if (e.error) {
11613 		crfree(cred_otw);
11614 		if (osp != NULL)
11615 			open_stream_rele(osp, rp);
11616 		return (e.error);
11617 	}
11618 
11619 	/* putfh directory */
11620 	argop[0].argop = OP_CPUTFH;
11621 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11622 
11623 	/* commit */
11624 	argop[1].argop = OP_COMMIT;
11625 	argop[1].nfs_argop4_u.opcommit.offset = offset;
11626 	argop[1].nfs_argop4_u.opcommit.count = count;
11627 
11628 	doqueue = 1;
11629 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
11630 
11631 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
11632 	if (!needrecov && e.error) {
11633 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
11634 		    needrecov);
11635 		crfree(cred_otw);
11636 		if (e.error == EACCES && last_time == FALSE)
11637 			goto get_commit_cred;
11638 		if (osp != NULL)
11639 			open_stream_rele(osp, rp);
11640 		return (e.error);
11641 	}
11642 
11643 	if (needrecov) {
11644 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
11645 		    NULL, OP_COMMIT, NULL) == FALSE) {
11646 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11647 			    &recov_state, needrecov);
11648 			if (!e.error)
11649 				(void) xdr_free(xdr_COMPOUND4res_clnt,
11650 				    (caddr_t)&res);
11651 			goto recov_retry;
11652 		}
11653 		if (e.error) {
11654 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11655 			    &recov_state, needrecov);
11656 			crfree(cred_otw);
11657 			if (osp != NULL)
11658 				open_stream_rele(osp, rp);
11659 			return (e.error);
11660 		}
11661 		/* fall through for res.status case */
11662 	}
11663 
11664 	if (res.status) {
11665 		e.error = geterrno4(res.status);
11666 		if (e.error == EACCES && last_time == FALSE) {
11667 			crfree(cred_otw);
11668 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11669 			    &recov_state, needrecov);
11670 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11671 			goto get_commit_cred;
11672 		}
11673 		/*
11674 		 * Can't do a nfs4_purge_stale_fh here because this
11675 		 * can cause a deadlock.  nfs4_commit can
11676 		 * be called from nfs4_dispose which can be called
11677 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
11678 		 * can call back to pvn_vplist_dirty.
11679 		 */
11680 		if (e.error == ESTALE) {
11681 			mutex_enter(&rp->r_statelock);
11682 			rp->r_flags |= R4STALE;
11683 			if (!rp->r_error)
11684 				rp->r_error = e.error;
11685 			mutex_exit(&rp->r_statelock);
11686 			PURGE_ATTRCACHE4(vp);
11687 		} else {
11688 			mutex_enter(&rp->r_statelock);
11689 			if (!rp->r_error)
11690 				rp->r_error = e.error;
11691 			mutex_exit(&rp->r_statelock);
11692 		}
11693 	} else {
11694 		ASSERT(rp->r_flags & R4HAVEVERF);
11695 		resop = &res.array[1];	/* commit res */
11696 		cm_res = &resop->nfs_resop4_u.opcommit;
11697 		mutex_enter(&rp->r_statelock);
11698 		if (cm_res->writeverf == rp->r_writeverf) {
11699 			mutex_exit(&rp->r_statelock);
11700 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11701 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11702 			    &recov_state, needrecov);
11703 			crfree(cred_otw);
11704 			if (osp != NULL)
11705 				open_stream_rele(osp, rp);
11706 			return (0);
11707 		}
11708 		nfs4_set_mod(vp);
11709 		rp->r_writeverf = cm_res->writeverf;
11710 		mutex_exit(&rp->r_statelock);
11711 		e.error = NFS_VERF_MISMATCH;
11712 	}
11713 
11714 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11715 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
11716 	crfree(cred_otw);
11717 	if (osp != NULL)
11718 		open_stream_rele(osp, rp);
11719 
11720 	return (e.error);
11721 }
11722 
11723 static void
11724 nfs4_set_mod(vnode_t *vp)
11725 {
11726 	page_t *pp;
11727 	kmutex_t *vphm;
11728 	rnode4_t *rp;
11729 
11730 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11731 
11732 	/* make sure we're looking at the master vnode, not a shadow */
11733 
11734 	rp = VTOR4(vp);
11735 	if (IS_SHADOW(vp, rp))
11736 		vp = RTOV4(rp);
11737 
11738 	vphm = page_vnode_mutex(vp);
11739 	mutex_enter(vphm);
11740 	/*
11741 	 * If there are no pages associated with this vnode, then
11742 	 * just return.
11743 	 */
11744 	if ((pp = vp->v_pages) == NULL) {
11745 		mutex_exit(vphm);
11746 		return;
11747 	}
11748 
11749 	do {
11750 		if (pp->p_fsdata != C_NOCOMMIT) {
11751 			hat_setmod(pp);
11752 			pp->p_fsdata = C_NOCOMMIT;
11753 		}
11754 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11755 	mutex_exit(vphm);
11756 }
11757 
11758 /*
11759  * This function is used to gather a page list of the pages which
11760  * can be committed on the server.
11761  *
11762  * The calling thread must have set R4COMMIT.  This bit is used to
11763  * serialize access to the commit structure in the rnode.  As long
11764  * as the thread has set R4COMMIT, then it can manipulate the commit
11765  * structure without requiring any other locks.
11766  *
11767  * When this function is called from nfs4_dispose() the page passed
11768  * into nfs4_dispose() will be SE_EXCL locked, and so this function
11769  * will skip it. This is not a problem since we initially add the
11770  * page to the r_commit page list.
11771  *
11772  */
11773 static void
11774 nfs4_get_commit(vnode_t *vp)
11775 {
11776 	rnode4_t *rp;
11777 	page_t *pp;
11778 	kmutex_t *vphm;
11779 
11780 	rp = VTOR4(vp);
11781 
11782 	ASSERT(rp->r_flags & R4COMMIT);
11783 
11784 	/* make sure we're looking at the master vnode, not a shadow */
11785 
11786 	if (IS_SHADOW(vp, rp))
11787 		vp = RTOV4(rp);
11788 
11789 	vphm = page_vnode_mutex(vp);
11790 	mutex_enter(vphm);
11791 
11792 	/*
11793 	 * If there are no pages associated with this vnode, then
11794 	 * just return.
11795 	 */
11796 	if ((pp = vp->v_pages) == NULL) {
11797 		mutex_exit(vphm);
11798 		return;
11799 	}
11800 
11801 	/*
11802 	 * Step through all of the pages associated with this vnode
11803 	 * looking for pages which need to be committed.
11804 	 */
11805 	do {
11806 		/*
11807 		 * First short-cut everything (without the page_lock)
11808 		 * and see if this page does not need to be committed
11809 		 * or is modified if so then we'll just skip it.
11810 		 */
11811 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
11812 			continue;
11813 
11814 		/*
11815 		 * Attempt to lock the page.  If we can't, then
11816 		 * someone else is messing with it or we have been
11817 		 * called from nfs4_dispose and this is the page that
11818 		 * nfs4_dispose was called with.. anyway just skip it.
11819 		 */
11820 		if (!page_trylock(pp, SE_EXCL))
11821 			continue;
11822 
11823 		/*
11824 		 * Lets check again now that we have the page lock.
11825 		 */
11826 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11827 			page_unlock(pp);
11828 			continue;
11829 		}
11830 
11831 		/* this had better not be a free page */
11832 		ASSERT(PP_ISFREE(pp) == 0);
11833 
11834 		/*
11835 		 * The page needs to be committed and we locked it.
11836 		 * Update the base and length parameters and add it
11837 		 * to r_pages.
11838 		 */
11839 		if (rp->r_commit.c_pages == NULL) {
11840 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11841 			rp->r_commit.c_commlen = PAGESIZE;
11842 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
11843 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
11844 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
11845 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11846 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
11847 		    <= pp->p_offset) {
11848 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11849 			    rp->r_commit.c_commbase + PAGESIZE;
11850 		}
11851 		page_add(&rp->r_commit.c_pages, pp);
11852 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11853 
11854 	mutex_exit(vphm);
11855 }
11856 
11857 /*
11858  * This routine is used to gather together a page list of the pages
11859  * which are to be committed on the server.  This routine must not
11860  * be called if the calling thread holds any locked pages.
11861  *
11862  * The calling thread must have set R4COMMIT.  This bit is used to
11863  * serialize access to the commit structure in the rnode.  As long
11864  * as the thread has set R4COMMIT, then it can manipulate the commit
11865  * structure without requiring any other locks.
11866  */
11867 static void
11868 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
11869 {
11870 
11871 	rnode4_t *rp;
11872 	page_t *pp;
11873 	u_offset_t end;
11874 	u_offset_t off;
11875 	ASSERT(len != 0);
11876 	rp = VTOR4(vp);
11877 	ASSERT(rp->r_flags & R4COMMIT);
11878 
11879 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11880 
11881 	/* make sure we're looking at the master vnode, not a shadow */
11882 
11883 	if (IS_SHADOW(vp, rp))
11884 		vp = RTOV4(rp);
11885 
11886 	/*
11887 	 * If there are no pages associated with this vnode, then
11888 	 * just return.
11889 	 */
11890 	if ((pp = vp->v_pages) == NULL)
11891 		return;
11892 	/*
11893 	 * Calculate the ending offset.
11894 	 */
11895 	end = soff + len;
11896 	for (off = soff; off < end; off += PAGESIZE) {
11897 		/*
11898 		 * Lookup each page by vp, offset.
11899 		 */
11900 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
11901 			continue;
11902 		/*
11903 		 * If this page does not need to be committed or is
11904 		 * modified, then just skip it.
11905 		 */
11906 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11907 			page_unlock(pp);
11908 			continue;
11909 		}
11910 
11911 		ASSERT(PP_ISFREE(pp) == 0);
11912 		/*
11913 		 * The page needs to be committed and we locked it.
11914 		 * Update the base and length parameters and add it
11915 		 * to r_pages.
11916 		 */
11917 		if (rp->r_commit.c_pages == NULL) {
11918 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11919 			rp->r_commit.c_commlen = PAGESIZE;
11920 		} else {
11921 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11922 			    rp->r_commit.c_commbase + PAGESIZE;
11923 		}
11924 		page_add(&rp->r_commit.c_pages, pp);
11925 	}
11926 }
11927 
11928 /*
11929  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
11930  * Flushes and commits data to the server.
11931  */
11932 static int
11933 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
11934 {
11935 	int error;
11936 	verifier4 write_verf;
11937 	rnode4_t *rp = VTOR4(vp);
11938 
11939 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11940 
11941 	/*
11942 	 * Flush the data portion of the file and then commit any
11943 	 * portions which need to be committed.  This may need to
11944 	 * be done twice if the server has changed state since
11945 	 * data was last written.  The data will need to be
11946 	 * rewritten to the server and then a new commit done.
11947 	 *
11948 	 * In fact, this may need to be done several times if the
11949 	 * server is having problems and crashing while we are
11950 	 * attempting to do this.
11951 	 */
11952 
11953 top:
11954 	/*
11955 	 * Do a flush based on the poff and plen arguments.  This
11956 	 * will synchronously write out any modified pages in the
11957 	 * range specified by (poff, plen). This starts all of the
11958 	 * i/o operations which will be waited for in the next
11959 	 * call to nfs4_putpage
11960 	 */
11961 
11962 	mutex_enter(&rp->r_statelock);
11963 	write_verf = rp->r_writeverf;
11964 	mutex_exit(&rp->r_statelock);
11965 
11966 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr, NULL);
11967 	if (error == EAGAIN)
11968 		error = 0;
11969 
11970 	/*
11971 	 * Do a flush based on the poff and plen arguments.  This
11972 	 * will synchronously write out any modified pages in the
11973 	 * range specified by (poff, plen) and wait until all of
11974 	 * the asynchronous i/o's in that range are done as well.
11975 	 */
11976 	if (!error)
11977 		error = nfs4_putpage(vp, poff, plen, 0, cr, NULL);
11978 
11979 	if (error)
11980 		return (error);
11981 
11982 	mutex_enter(&rp->r_statelock);
11983 	if (rp->r_writeverf != write_verf) {
11984 		mutex_exit(&rp->r_statelock);
11985 		goto top;
11986 	}
11987 	mutex_exit(&rp->r_statelock);
11988 
11989 	/*
11990 	 * Now commit any pages which might need to be committed.
11991 	 * If the error, NFS_VERF_MISMATCH, is returned, then
11992 	 * start over with the flush operation.
11993 	 */
11994 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
11995 
11996 	if (error == NFS_VERF_MISMATCH)
11997 		goto top;
11998 
11999 	return (error);
12000 }
12001 
12002 /*
12003  * nfs4_commit_vp()  will wait for other pending commits and
12004  * will either commit the whole file or a range, plen dictates
12005  * if we commit whole file. a value of zero indicates the whole
12006  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
12007  */
12008 static int
12009 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12010     cred_t *cr, int wait_on_writes)
12011 {
12012 	rnode4_t *rp;
12013 	page_t *plist;
12014 	offset3 offset;
12015 	count3 len;
12016 
12017 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12018 
12019 	rp = VTOR4(vp);
12020 
12021 	/*
12022 	 *  before we gather commitable pages make
12023 	 *  sure there are no outstanding async writes
12024 	 */
12025 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12026 		mutex_enter(&rp->r_statelock);
12027 		while (rp->r_count > 0) {
12028 			cv_wait(&rp->r_cv, &rp->r_statelock);
12029 		}
12030 		mutex_exit(&rp->r_statelock);
12031 	}
12032 
12033 	/*
12034 	 * Set the `commit inprogress' state bit.  We must
12035 	 * first wait until any current one finishes.
12036 	 */
12037 	mutex_enter(&rp->r_statelock);
12038 	while (rp->r_flags & R4COMMIT) {
12039 		rp->r_flags |= R4COMMITWAIT;
12040 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12041 		rp->r_flags &= ~R4COMMITWAIT;
12042 	}
12043 	rp->r_flags |= R4COMMIT;
12044 	mutex_exit(&rp->r_statelock);
12045 
12046 	/*
12047 	 * Gather all of the pages which need to be
12048 	 * committed.
12049 	 */
12050 	if (plen == 0)
12051 		nfs4_get_commit(vp);
12052 	else
12053 		nfs4_get_commit_range(vp, poff, plen);
12054 
12055 	/*
12056 	 * Clear the `commit inprogress' bit and disconnect the
12057 	 * page list which was gathered by nfs4_get_commit.
12058 	 */
12059 	plist = rp->r_commit.c_pages;
12060 	rp->r_commit.c_pages = NULL;
12061 	offset = rp->r_commit.c_commbase;
12062 	len = rp->r_commit.c_commlen;
12063 	mutex_enter(&rp->r_statelock);
12064 	rp->r_flags &= ~R4COMMIT;
12065 	cv_broadcast(&rp->r_commit.c_cv);
12066 	mutex_exit(&rp->r_statelock);
12067 
12068 	/*
12069 	 * If any pages need to be committed, commit them and
12070 	 * then unlock them so that they can be freed some
12071 	 * time later.
12072 	 */
12073 	if (plist == NULL)
12074 		return (0);
12075 
12076 	/*
12077 	 * No error occurred during the flush portion
12078 	 * of this operation, so now attempt to commit
12079 	 * the data to stable storage on the server.
12080 	 *
12081 	 * This will unlock all of the pages on the list.
12082 	 */
12083 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12084 }
12085 
12086 static int
12087 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12088     cred_t *cr)
12089 {
12090 	int error;
12091 	page_t *pp;
12092 
12093 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12094 
12095 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12096 
12097 	/*
12098 	 * If we got an error, then just unlock all of the pages
12099 	 * on the list.
12100 	 */
12101 	if (error) {
12102 		while (plist != NULL) {
12103 			pp = plist;
12104 			page_sub(&plist, pp);
12105 			page_unlock(pp);
12106 		}
12107 		return (error);
12108 	}
12109 	/*
12110 	 * We've tried as hard as we can to commit the data to stable
12111 	 * storage on the server.  We just unlock the pages and clear
12112 	 * the commit required state.  They will get freed later.
12113 	 */
12114 	while (plist != NULL) {
12115 		pp = plist;
12116 		page_sub(&plist, pp);
12117 		pp->p_fsdata = C_NOCOMMIT;
12118 		page_unlock(pp);
12119 	}
12120 
12121 	return (error);
12122 }
12123 
12124 static void
12125 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12126     cred_t *cr)
12127 {
12128 
12129 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12130 }
12131 
12132 /*ARGSUSED*/
12133 static int
12134 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12135 	caller_context_t *ct)
12136 {
12137 	int		error = 0;
12138 	mntinfo4_t	*mi;
12139 	vattr_t		va;
12140 	vsecattr_t	nfsace4_vsap;
12141 
12142 	mi = VTOMI4(vp);
12143 	if (nfs_zone() != mi->mi_zone)
12144 		return (EIO);
12145 	if (mi->mi_flags & MI4_ACL) {
12146 		/* if we have a delegation, return it */
12147 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12148 			(void) nfs4delegreturn(VTOR4(vp),
12149 			    NFS4_DR_REOPEN|NFS4_DR_PUSH);
12150 
12151 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12152 		    NFS4_ACL_SET);
12153 		if (error) /* EINVAL */
12154 			return (error);
12155 
12156 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12157 			/*
12158 			 * These are aclent_t type entries.
12159 			 */
12160 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12161 			    vp->v_type == VDIR, FALSE);
12162 			if (error)
12163 				return (error);
12164 		} else {
12165 			/*
12166 			 * These are ace_t type entries.
12167 			 */
12168 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12169 			    FALSE);
12170 			if (error)
12171 				return (error);
12172 		}
12173 		bzero(&va, sizeof (va));
12174 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12175 		vs_ace4_destroy(&nfsace4_vsap);
12176 		return (error);
12177 	}
12178 	return (ENOSYS);
12179 }
12180 
12181 /* ARGSUSED */
12182 int
12183 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12184 	caller_context_t *ct)
12185 {
12186 	int		error;
12187 	mntinfo4_t	*mi;
12188 	nfs4_ga_res_t	gar;
12189 	rnode4_t	*rp = VTOR4(vp);
12190 
12191 	mi = VTOMI4(vp);
12192 	if (nfs_zone() != mi->mi_zone)
12193 		return (EIO);
12194 
12195 	bzero(&gar, sizeof (gar));
12196 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12197 
12198 	/*
12199 	 * vsecattr->vsa_mask holds the original acl request mask.
12200 	 * This is needed when determining what to return.
12201 	 * (See: nfs4_create_getsecattr_return())
12202 	 */
12203 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12204 	if (error) /* EINVAL */
12205 		return (error);
12206 
12207 	if (mi->mi_flags & MI4_ACL) {
12208 		/*
12209 		 * Check if the data is cached and the cache is valid.  If it
12210 		 * is we don't go over the wire.
12211 		 */
12212 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12213 			mutex_enter(&rp->r_statelock);
12214 			if (rp->r_secattr != NULL) {
12215 				error = nfs4_create_getsecattr_return(
12216 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12217 				    rp->r_attr.va_gid,
12218 				    vp->v_type == VDIR);
12219 				if (!error) { /* error == 0 - Success! */
12220 					mutex_exit(&rp->r_statelock);
12221 					return (error);
12222 				}
12223 			}
12224 			mutex_exit(&rp->r_statelock);
12225 		}
12226 
12227 		/*
12228 		 * The getattr otw call will always get both the acl, in
12229 		 * the form of a list of nfsace4's, and the number of acl
12230 		 * entries; independent of the value of gar.n4g_vsa.vsa_mask.
12231 		 */
12232 		gar.n4g_va.va_mask = AT_ALL;
12233 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12234 		if (error) {
12235 			vs_ace4_destroy(&gar.n4g_vsa);
12236 			if (error == ENOTSUP || error == EOPNOTSUPP)
12237 				error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12238 			return (error);
12239 		}
12240 
12241 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12242 			/*
12243 			 * No error was returned, but according to the response
12244 			 * bitmap, neither was an acl.
12245 			 */
12246 			vs_ace4_destroy(&gar.n4g_vsa);
12247 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12248 			return (error);
12249 		}
12250 
12251 		/*
12252 		 * Update the cache with the ACL.
12253 		 */
12254 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12255 
12256 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12257 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12258 		    vp->v_type == VDIR);
12259 		vs_ace4_destroy(&gar.n4g_vsa);
12260 		if ((error) && (vsecattr->vsa_mask &
12261 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12262 		    (error != EACCES)) {
12263 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12264 		}
12265 		return (error);
12266 	}
12267 	error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12268 	return (error);
12269 }
12270 
12271 /*
12272  * The function returns:
12273  * 	- 0 (zero) if the passed in "acl_mask" is a valid request.
12274  * 	- EINVAL if the passed in "acl_mask" is an invalid request.
12275  *
12276  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12277  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12278  *
12279  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12280  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12281  * - We have a count field set without the corresponding acl field set. (e.g. -
12282  * VSA_ACECNT is set, but VSA_ACE is not)
12283  */
12284 static int
12285 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12286 {
12287 	/* Shortcut the masks that are always valid. */
12288 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12289 		return (0);
12290 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12291 		return (0);
12292 
12293 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12294 		/*
12295 		 * We can't have any VSA_ACL type stuff in the mask now.
12296 		 */
12297 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12298 		    VSA_DFACLCNT))
12299 			return (EINVAL);
12300 
12301 		if (op == NFS4_ACL_SET) {
12302 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12303 				return (EINVAL);
12304 		}
12305 	}
12306 
12307 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12308 		/*
12309 		 * We can't have any VSA_ACE type stuff in the mask now.
12310 		 */
12311 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12312 			return (EINVAL);
12313 
12314 		if (op == NFS4_ACL_SET) {
12315 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12316 				return (EINVAL);
12317 
12318 			if ((acl_mask & VSA_DFACLCNT) &&
12319 			    !(acl_mask & VSA_DFACL))
12320 				return (EINVAL);
12321 		}
12322 	}
12323 	return (0);
12324 }
12325 
12326 /*
12327  * The theory behind creating the correct getsecattr return is simply this:
12328  * "Don't return anything that the caller is not expecting to have to free."
12329  */
12330 static int
12331 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12332     uid_t uid, gid_t gid, int isdir)
12333 {
12334 	int error = 0;
12335 	/* Save the mask since the translators modify it. */
12336 	uint_t	orig_mask = vsap->vsa_mask;
12337 
12338 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12339 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid,
12340 		    FALSE, ((orig_mask & VSA_ACE) ? FALSE : TRUE));
12341 
12342 		if (error)
12343 			return (error);
12344 
12345 		/*
12346 		 * If the caller only asked for the ace count (VSA_ACECNT)
12347 		 * don't give them the full acl (VSA_ACE), free it.
12348 		 */
12349 		if (!orig_mask & VSA_ACE) {
12350 			if (vsap->vsa_aclentp != NULL) {
12351 				kmem_free(vsap->vsa_aclentp,
12352 				    vsap->vsa_aclcnt * sizeof (ace_t));
12353 				vsap->vsa_aclentp = NULL;
12354 			}
12355 		}
12356 		vsap->vsa_mask = orig_mask;
12357 
12358 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12359 	    VSA_DFACLCNT)) {
12360 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12361 		    isdir, FALSE,
12362 		    ((orig_mask & (VSA_ACL | VSA_DFACL)) ? FALSE : TRUE));
12363 
12364 		if (error)
12365 			return (error);
12366 
12367 		/*
12368 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12369 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12370 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12371 		 */
12372 		if (!orig_mask & VSA_ACL) {
12373 			if (vsap->vsa_aclentp != NULL) {
12374 				kmem_free(vsap->vsa_aclentp,
12375 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12376 				vsap->vsa_aclentp = NULL;
12377 			}
12378 		}
12379 
12380 		if (!orig_mask & VSA_DFACL) {
12381 			if (vsap->vsa_dfaclentp != NULL) {
12382 				kmem_free(vsap->vsa_dfaclentp,
12383 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12384 				vsap->vsa_dfaclentp = NULL;
12385 			}
12386 		}
12387 		vsap->vsa_mask = orig_mask;
12388 	}
12389 	return (0);
12390 }
12391 
12392 /* ARGSUSED */
12393 int
12394 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr,
12395     caller_context_t *ct)
12396 {
12397 	int error;
12398 
12399 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12400 		return (EIO);
12401 	/*
12402 	 * check for valid cmd parameter
12403 	 */
12404 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12405 		return (EINVAL);
12406 
12407 	/*
12408 	 * Check access permissions
12409 	 */
12410 	if ((cmd & F_SHARE) &&
12411 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12412 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12413 		return (EBADF);
12414 
12415 	/*
12416 	 * If the filesystem is mounted using local locking, pass the
12417 	 * request off to the local share code.
12418 	 */
12419 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12420 		return (fs_shrlock(vp, cmd, shr, flag, cr, ct));
12421 
12422 	switch (cmd) {
12423 	case F_SHARE:
12424 	case F_UNSHARE:
12425 		/*
12426 		 * This will be properly implemented later,
12427 		 * see RFE: 4823948 .
12428 		 */
12429 		error = EAGAIN;
12430 		break;
12431 
12432 	case F_HASREMOTELOCKS:
12433 		/*
12434 		 * NFS client can't store remote locks itself
12435 		 */
12436 		shr->s_access = 0;
12437 		error = 0;
12438 		break;
12439 
12440 	default:
12441 		error = EINVAL;
12442 		break;
12443 	}
12444 
12445 	return (error);
12446 }
12447 
12448 /*
12449  * Common code called by directory ops to update the attrcache
12450  */
12451 static int
12452 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12453     hrtime_t t, vnode_t *vp, cred_t *cr)
12454 {
12455 	int error = 0;
12456 
12457 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12458 
12459 	if (status != NFS4_OK) {
12460 		/* getattr not done or failed */
12461 		PURGE_ATTRCACHE4(vp);
12462 		return (error);
12463 	}
12464 
12465 	if (garp) {
12466 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12467 	} else {
12468 		PURGE_ATTRCACHE4(vp);
12469 	}
12470 	return (error);
12471 }
12472 
12473 /*
12474  * Update directory caches for directory modification ops (link, rename, etc.)
12475  * When dinfo is NULL, manage dircaches in the old way.
12476  */
12477 static void
12478 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12479     dirattr_info_t *dinfo)
12480 {
12481 	rnode4_t	*drp = VTOR4(dvp);
12482 
12483 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12484 
12485 	/* Purge rddir cache for dir since it changed */
12486 	if (drp->r_dir != NULL)
12487 		nfs4_purge_rddir_cache(dvp);
12488 
12489 	/*
12490 	 * If caller provided dinfo, then use it to manage dir caches.
12491 	 */
12492 	if (dinfo != NULL) {
12493 		if (vp != NULL) {
12494 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12495 			if (!VTOR4(vp)->created_v4) {
12496 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12497 				dnlc_update(dvp, nm, vp);
12498 			} else {
12499 				/*
12500 				 * XXX don't update if the created_v4 flag is
12501 				 * set
12502 				 */
12503 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12504 				NFS4_DEBUG(nfs4_client_state_debug,
12505 				    (CE_NOTE, "nfs4_update_dircaches: "
12506 				    "don't update dnlc: created_v4 flag"));
12507 			}
12508 		}
12509 
12510 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12511 		    dinfo->di_cred, FALSE, cinfo);
12512 
12513 		return;
12514 	}
12515 
12516 	/*
12517 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12518 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12519 	 * attrs, the dir's attrs must be purged.
12520 	 *
12521 	 * XXX this check and dnlc update/purge should really be atomic,
12522 	 * XXX but can't use rnode statelock because it'll deadlock in
12523 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12524 	 * XXX does occur.
12525 	 *
12526 	 * XXX We also may want to check that atomic is true in the
12527 	 * XXX change_info struct. If it is not, the change_info may
12528 	 * XXX reflect changes by more than one clients which means that
12529 	 * XXX our cache may not be valid.
12530 	 */
12531 	PURGE_ATTRCACHE4(dvp);
12532 	if (drp->r_change == cinfo->before) {
12533 		/* no changes took place in the directory prior to our link */
12534 		if (vp != NULL) {
12535 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12536 			if (!VTOR4(vp)->created_v4) {
12537 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12538 				dnlc_update(dvp, nm, vp);
12539 			} else {
12540 				/*
12541 				 * XXX dont' update if the created_v4 flag
12542 				 * is set
12543 				 */
12544 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12545 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12546 				    "nfs4_update_dircaches: don't"
12547 				    " update dnlc: created_v4 flag"));
12548 			}
12549 		}
12550 	} else {
12551 		/* Another client modified directory - purge its dnlc cache */
12552 		dnlc_purge_vp(dvp);
12553 	}
12554 }
12555 
12556 /*
12557  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12558  * file.
12559  *
12560  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12561  * file (ie: client recovery) and otherwise set to FALSE.
12562  *
12563  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12564  * initiated) calling functions.
12565  *
12566  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12567  * of resending a 'lost' open request.
12568  *
12569  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12570  * server that hands out BAD_SEQID on open confirm.
12571  *
12572  * Errors are returned via the nfs4_error_t parameter.
12573  */
12574 void
12575 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12576     bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12577     bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12578 {
12579 	COMPOUND4args_clnt args;
12580 	COMPOUND4res_clnt res;
12581 	nfs_argop4 argop[2];
12582 	nfs_resop4 *resop;
12583 	int doqueue = 1;
12584 	mntinfo4_t *mi;
12585 	OPEN_CONFIRM4args *open_confirm_args;
12586 	int needrecov;
12587 
12588 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12589 #if DEBUG
12590 	mutex_enter(&oop->oo_lock);
12591 	ASSERT(oop->oo_seqid_inuse);
12592 	mutex_exit(&oop->oo_lock);
12593 #endif
12594 
12595 recov_retry_confirm:
12596 	nfs4_error_zinit(ep);
12597 	*retry_open = FALSE;
12598 
12599 	if (resend)
12600 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12601 	else
12602 		args.ctag = TAG_OPEN_CONFIRM;
12603 
12604 	args.array_len = 2;
12605 	args.array = argop;
12606 
12607 	/* putfh target fh */
12608 	argop[0].argop = OP_CPUTFH;
12609 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12610 
12611 	argop[1].argop = OP_OPEN_CONFIRM;
12612 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12613 
12614 	(*seqid) += 1;
12615 	open_confirm_args->seqid = *seqid;
12616 	open_confirm_args->open_stateid = *stateid;
12617 
12618 	mi = VTOMI4(vp);
12619 
12620 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12621 
12622 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12623 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12624 	}
12625 
12626 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12627 	if (!needrecov && ep->error)
12628 		return;
12629 
12630 	if (needrecov) {
12631 		bool_t abort = FALSE;
12632 
12633 		if (reopening_file == FALSE) {
12634 			nfs4_bseqid_entry_t *bsep = NULL;
12635 
12636 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12637 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12638 				    vp, 0, args.ctag,
12639 				    open_confirm_args->seqid);
12640 
12641 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp,
12642 			    NULL, NULL, NULL, OP_OPEN_CONFIRM, bsep);
12643 			if (bsep) {
12644 				kmem_free(bsep, sizeof (*bsep));
12645 				if (num_bseqid_retryp &&
12646 				    --(*num_bseqid_retryp) == 0)
12647 					abort = TRUE;
12648 			}
12649 		}
12650 		if ((ep->error == ETIMEDOUT ||
12651 		    res.status == NFS4ERR_RESOURCE) &&
12652 		    abort == FALSE && resend == FALSE) {
12653 			if (!ep->error)
12654 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12655 				    (caddr_t)&res);
12656 
12657 			delay(SEC_TO_TICK(confirm_retry_sec));
12658 			goto recov_retry_confirm;
12659 		}
12660 		/* State may have changed so retry the entire OPEN op */
12661 		if (abort == FALSE)
12662 			*retry_open = TRUE;
12663 		else
12664 			*retry_open = FALSE;
12665 		if (!ep->error)
12666 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12667 		return;
12668 	}
12669 
12670 	if (res.status) {
12671 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12672 		return;
12673 	}
12674 
12675 	resop = &res.array[1];  /* open confirm res */
12676 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
12677 	    stateid, sizeof (*stateid));
12678 
12679 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12680 }
12681 
12682 /*
12683  * Return the credentials associated with a client state object.  The
12684  * caller is responsible for freeing the credentials.
12685  */
12686 
12687 static cred_t *
12688 state_to_cred(nfs4_open_stream_t *osp)
12689 {
12690 	cred_t *cr;
12691 
12692 	/*
12693 	 * It's ok to not lock the open stream and open owner to get
12694 	 * the oo_cred since this is only written once (upon creation)
12695 	 * and will not change.
12696 	 */
12697 	cr = osp->os_open_owner->oo_cred;
12698 	crhold(cr);
12699 
12700 	return (cr);
12701 }
12702 
12703 /*
12704  * nfs4_find_sysid
12705  *
12706  * Find the sysid for the knetconfig associated with the given mi.
12707  */
12708 static struct lm_sysid *
12709 nfs4_find_sysid(mntinfo4_t *mi)
12710 {
12711 	ASSERT(nfs_zone() == mi->mi_zone);
12712 
12713 	/*
12714 	 * Switch from RDMA knconf to original mount knconf
12715 	 */
12716 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
12717 	    mi->mi_curr_serv->sv_hostname, NULL));
12718 }
12719 
12720 #ifdef DEBUG
12721 /*
12722  * Return a string version of the call type for easy reading.
12723  */
12724 static char *
12725 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
12726 {
12727 	switch (ctype) {
12728 	case NFS4_LCK_CTYPE_NORM:
12729 		return ("NORMAL");
12730 	case NFS4_LCK_CTYPE_RECLAIM:
12731 		return ("RECLAIM");
12732 	case NFS4_LCK_CTYPE_RESEND:
12733 		return ("RESEND");
12734 	case NFS4_LCK_CTYPE_REINSTATE:
12735 		return ("REINSTATE");
12736 	default:
12737 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
12738 		    "type %d", ctype);
12739 		return ("");
12740 	}
12741 }
12742 #endif
12743 
12744 /*
12745  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
12746  * Unlock requests don't have an over-the-wire locktype, so we just return
12747  * something non-threatening.
12748  */
12749 
12750 static nfs_lock_type4
12751 flk_to_locktype(int cmd, int l_type)
12752 {
12753 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
12754 
12755 	switch (l_type) {
12756 	case F_UNLCK:
12757 		return (READ_LT);
12758 	case F_RDLCK:
12759 		if (cmd == F_SETLK)
12760 			return (READ_LT);
12761 		else
12762 			return (READW_LT);
12763 	case F_WRLCK:
12764 		if (cmd == F_SETLK)
12765 			return (WRITE_LT);
12766 		else
12767 			return (WRITEW_LT);
12768 	}
12769 	panic("flk_to_locktype");
12770 	/*NOTREACHED*/
12771 }
12772 
12773 /*
12774  * Do some preliminary checks for nfs4frlock.
12775  */
12776 static int
12777 nfs4frlock_validate_args(int cmd, flock64_t *flk, int flag, vnode_t *vp,
12778     u_offset_t offset)
12779 {
12780 	int error = 0;
12781 
12782 	/*
12783 	 * If we are setting a lock, check that the file is opened
12784 	 * with the correct mode.
12785 	 */
12786 	if (cmd == F_SETLK || cmd == F_SETLKW) {
12787 		if ((flk->l_type == F_RDLCK && (flag & FREAD) == 0) ||
12788 		    (flk->l_type == F_WRLCK && (flag & FWRITE) == 0)) {
12789 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12790 			    "nfs4frlock_validate_args: file was opened with "
12791 			    "incorrect mode"));
12792 			return (EBADF);
12793 		}
12794 	}
12795 
12796 	/* Convert the offset. It may need to be restored before returning. */
12797 	if (error = convoff(vp, flk, 0, offset)) {
12798 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12799 		    "nfs4frlock_validate_args: convoff  =>  error= %d\n",
12800 		    error));
12801 		return (error);
12802 	}
12803 
12804 	return (error);
12805 }
12806 
12807 /*
12808  * Set the flock64's lm_sysid for nfs4frlock.
12809  */
12810 static int
12811 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
12812 {
12813 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12814 
12815 	/* Find the lm_sysid */
12816 	*lspp = nfs4_find_sysid(VTOMI4(vp));
12817 
12818 	if (*lspp == NULL) {
12819 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12820 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
12821 		return (ENOLCK);
12822 	}
12823 
12824 	flk->l_sysid = lm_sysidt(*lspp);
12825 
12826 	return (0);
12827 }
12828 
12829 /*
12830  * Do the remaining preliminary setup for nfs4frlock.
12831  */
12832 static void
12833 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
12834     flock64_t *flk, short *whencep, vnode_t *vp, cred_t *search_cr,
12835     cred_t **cred_otw)
12836 {
12837 	/*
12838 	 * set tick_delay to the base delay time.
12839 	 * (NFS4_BASE_WAIT_TIME is in secs)
12840 	 */
12841 
12842 	*tick_delayp = drv_usectohz(NFS4_BASE_WAIT_TIME * 1000 * 1000);
12843 
12844 	/*
12845 	 * If lock is relative to EOF, we need the newest length of the
12846 	 * file. Therefore invalidate the ATTR_CACHE.
12847 	 */
12848 
12849 	*whencep = flk->l_whence;
12850 
12851 	if (*whencep == 2)		/* SEEK_END */
12852 		PURGE_ATTRCACHE4(vp);
12853 
12854 	recov_statep->rs_flags = 0;
12855 	recov_statep->rs_num_retry_despite_err = 0;
12856 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
12857 }
12858 
12859 /*
12860  * Initialize and allocate the data structures necessary for
12861  * the nfs4frlock call.
12862  * Allocates argsp's op array, frees up the saved_rqstpp if there is one.
12863  */
12864 static void
12865 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
12866     nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
12867     bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
12868     bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
12869 {
12870 	int		argoplist_size;
12871 	int		num_ops = 2;
12872 
12873 	*retry = FALSE;
12874 	*did_start_fop = FALSE;
12875 	*skip_get_err = FALSE;
12876 	lost_rqstp->lr_op = 0;
12877 	argoplist_size  = num_ops * sizeof (nfs_argop4);
12878 	/* fill array with zero */
12879 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
12880 
12881 	*argspp = argsp;
12882 	*respp = NULL;
12883 
12884 	argsp->array_len = num_ops;
12885 	argsp->array = *argopp;
12886 
12887 	/* initialize in case of error; will get real value down below */
12888 	argsp->ctag = TAG_NONE;
12889 
12890 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
12891 		*op_hintp = OH_LOCKU;
12892 	else
12893 		*op_hintp = OH_OTHER;
12894 }
12895 
12896 /*
12897  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
12898  * the proper nfs4_server_t for this instance of nfs4frlock.
12899  * Returns 0 (success) or an errno value.
12900  */
12901 static int
12902 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
12903     nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
12904     bool_t *did_start_fop, bool_t *startrecovp)
12905 {
12906 	int error = 0;
12907 	rnode4_t *rp;
12908 
12909 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12910 
12911 	if (ctype == NFS4_LCK_CTYPE_NORM) {
12912 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
12913 		    recov_statep, startrecovp);
12914 		if (error)
12915 			return (error);
12916 		*did_start_fop = TRUE;
12917 	} else {
12918 		*did_start_fop = FALSE;
12919 		*startrecovp = FALSE;
12920 	}
12921 
12922 	if (!error) {
12923 		rp = VTOR4(vp);
12924 
12925 		/* If the file failed recovery, just quit. */
12926 		mutex_enter(&rp->r_statelock);
12927 		if (rp->r_flags & R4RECOVERR) {
12928 			error = EIO;
12929 		}
12930 		mutex_exit(&rp->r_statelock);
12931 	}
12932 
12933 	return (error);
12934 }
12935 
12936 /*
12937  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
12938  * resend nfs4frlock call is initiated by the recovery framework.
12939  * Acquires the lop and oop seqid synchronization.
12940  */
12941 static void
12942 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
12943     COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
12944     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
12945     LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
12946 {
12947 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
12948 	int error;
12949 
12950 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
12951 	    (CE_NOTE,
12952 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
12953 	ASSERT(resend_rqstp != NULL);
12954 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
12955 	    resend_rqstp->lr_op == OP_LOCKU);
12956 
12957 	*oopp = resend_rqstp->lr_oop;
12958 	if (resend_rqstp->lr_oop) {
12959 		open_owner_hold(resend_rqstp->lr_oop);
12960 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
12961 		ASSERT(error == 0);	/* recov thread always succeeds */
12962 	}
12963 
12964 	/* Must resend this lost lock/locku request. */
12965 	ASSERT(resend_rqstp->lr_lop != NULL);
12966 	*lopp = resend_rqstp->lr_lop;
12967 	lock_owner_hold(resend_rqstp->lr_lop);
12968 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
12969 	ASSERT(error == 0);	/* recov thread always succeeds */
12970 
12971 	*ospp = resend_rqstp->lr_osp;
12972 	if (*ospp)
12973 		open_stream_hold(resend_rqstp->lr_osp);
12974 
12975 	if (resend_rqstp->lr_op == OP_LOCK) {
12976 		LOCK4args *lock_args;
12977 
12978 		argop->argop = OP_LOCK;
12979 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
12980 		lock_args->locktype = resend_rqstp->lr_locktype;
12981 		lock_args->reclaim =
12982 		    (resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
12983 		lock_args->offset = resend_rqstp->lr_flk->l_start;
12984 		lock_args->length = resend_rqstp->lr_flk->l_len;
12985 		if (lock_args->length == 0)
12986 			lock_args->length = ~lock_args->length;
12987 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
12988 		    mi2clientid(mi), &lock_args->locker);
12989 
12990 		switch (resend_rqstp->lr_ctype) {
12991 		case NFS4_LCK_CTYPE_RESEND:
12992 			argsp->ctag = TAG_LOCK_RESEND;
12993 			break;
12994 		case NFS4_LCK_CTYPE_REINSTATE:
12995 			argsp->ctag = TAG_LOCK_REINSTATE;
12996 			break;
12997 		case NFS4_LCK_CTYPE_RECLAIM:
12998 			argsp->ctag = TAG_LOCK_RECLAIM;
12999 			break;
13000 		default:
13001 			argsp->ctag = TAG_LOCK_UNKNOWN;
13002 			break;
13003 		}
13004 	} else {
13005 		LOCKU4args *locku_args;
13006 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
13007 
13008 		argop->argop = OP_LOCKU;
13009 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
13010 		locku_args->locktype = READ_LT;
13011 		locku_args->seqid = lop->lock_seqid + 1;
13012 		mutex_enter(&lop->lo_lock);
13013 		locku_args->lock_stateid = lop->lock_stateid;
13014 		mutex_exit(&lop->lo_lock);
13015 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13016 		locku_args->length = resend_rqstp->lr_flk->l_len;
13017 		if (locku_args->length == 0)
13018 			locku_args->length = ~locku_args->length;
13019 
13020 		switch (resend_rqstp->lr_ctype) {
13021 		case NFS4_LCK_CTYPE_RESEND:
13022 			argsp->ctag = TAG_LOCKU_RESEND;
13023 			break;
13024 		case NFS4_LCK_CTYPE_REINSTATE:
13025 			argsp->ctag = TAG_LOCKU_REINSTATE;
13026 			break;
13027 		default:
13028 			argsp->ctag = TAG_LOCK_UNKNOWN;
13029 			break;
13030 		}
13031 	}
13032 }
13033 
13034 /*
13035  * Setup the LOCKT4 arguments.
13036  */
13037 static void
13038 nfs4frlock_setup_lockt_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13039     LOCKT4args **lockt_argsp, COMPOUND4args_clnt *argsp, flock64_t *flk,
13040     rnode4_t *rp)
13041 {
13042 	LOCKT4args *lockt_args;
13043 
13044 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13045 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13046 	argop->argop = OP_LOCKT;
13047 	argsp->ctag = TAG_LOCKT;
13048 	lockt_args = &argop->nfs_argop4_u.oplockt;
13049 
13050 	/*
13051 	 * The locktype will be READ_LT unless it's
13052 	 * a write lock. We do this because the Solaris
13053 	 * system call allows the combination of
13054 	 * F_UNLCK and F_GETLK* and so in that case the
13055 	 * unlock is mapped to a read.
13056 	 */
13057 	if (flk->l_type == F_WRLCK)
13058 		lockt_args->locktype = WRITE_LT;
13059 	else
13060 		lockt_args->locktype = READ_LT;
13061 
13062 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13063 	/* set the lock owner4 args */
13064 	nfs4_setlockowner_args(&lockt_args->owner, rp,
13065 	    ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13066 	    flk->l_pid);
13067 	lockt_args->offset = flk->l_start;
13068 	lockt_args->length = flk->l_len;
13069 	if (flk->l_len == 0)
13070 		lockt_args->length = ~lockt_args->length;
13071 
13072 	*lockt_argsp = lockt_args;
13073 }
13074 
13075 /*
13076  * If the client is holding a delegation, and the open stream to be used
13077  * with this lock request is a delegation open stream, then re-open the stream.
13078  * Sets the nfs4_error_t to all zeros unless the open stream has already
13079  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13080  * means the caller should retry (like a recovery retry).
13081  */
13082 static void
13083 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13084 {
13085 	open_delegation_type4	dt;
13086 	bool_t			reopen_needed, force;
13087 	nfs4_open_stream_t	*osp;
13088 	open_claim_type4 	oclaim;
13089 	rnode4_t		*rp = VTOR4(vp);
13090 	mntinfo4_t		*mi = VTOMI4(vp);
13091 
13092 	ASSERT(nfs_zone() == mi->mi_zone);
13093 
13094 	nfs4_error_zinit(ep);
13095 
13096 	mutex_enter(&rp->r_statev4_lock);
13097 	dt = rp->r_deleg_type;
13098 	mutex_exit(&rp->r_statev4_lock);
13099 
13100 	if (dt != OPEN_DELEGATE_NONE) {
13101 		nfs4_open_owner_t	*oop;
13102 
13103 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13104 		if (!oop) {
13105 			ep->stat = NFS4ERR_IO;
13106 			return;
13107 		}
13108 		/* returns with 'os_sync_lock' held */
13109 		osp = find_open_stream(oop, rp);
13110 		if (!osp) {
13111 			open_owner_rele(oop);
13112 			ep->stat = NFS4ERR_IO;
13113 			return;
13114 		}
13115 
13116 		if (osp->os_failed_reopen) {
13117 			NFS4_DEBUG((nfs4_open_stream_debug ||
13118 			    nfs4_client_lock_debug), (CE_NOTE,
13119 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13120 			    "for osp %p, cr %p, rp %s", (void *)osp,
13121 			    (void *)cr, rnode4info(rp)));
13122 			mutex_exit(&osp->os_sync_lock);
13123 			open_stream_rele(osp, rp);
13124 			open_owner_rele(oop);
13125 			ep->stat = NFS4ERR_IO;
13126 			return;
13127 		}
13128 
13129 		/*
13130 		 * Determine whether a reopen is needed.  If this
13131 		 * is a delegation open stream, then send the open
13132 		 * to the server to give visibility to the open owner.
13133 		 * Even if it isn't a delegation open stream, we need
13134 		 * to check if the previous open CLAIM_DELEGATE_CUR
13135 		 * was sufficient.
13136 		 */
13137 
13138 		reopen_needed = osp->os_delegation ||
13139 		    ((lt == F_RDLCK &&
13140 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13141 		    (lt == F_WRLCK &&
13142 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13143 
13144 		mutex_exit(&osp->os_sync_lock);
13145 		open_owner_rele(oop);
13146 
13147 		if (reopen_needed) {
13148 			/*
13149 			 * Always use CLAIM_PREVIOUS after server reboot.
13150 			 * The server will reject CLAIM_DELEGATE_CUR if
13151 			 * it is used during the grace period.
13152 			 */
13153 			mutex_enter(&mi->mi_lock);
13154 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13155 				oclaim = CLAIM_PREVIOUS;
13156 				force = TRUE;
13157 			} else {
13158 				oclaim = CLAIM_DELEGATE_CUR;
13159 				force = FALSE;
13160 			}
13161 			mutex_exit(&mi->mi_lock);
13162 
13163 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13164 			if (ep->error == EAGAIN) {
13165 				nfs4_error_zinit(ep);
13166 				ep->stat = NFS4ERR_DELAY;
13167 			}
13168 		}
13169 		open_stream_rele(osp, rp);
13170 		osp = NULL;
13171 	}
13172 }
13173 
13174 /*
13175  * Setup the LOCKU4 arguments.
13176  * Returns errors via the nfs4_error_t.
13177  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13178  *			over-the-wire.  The caller must release the
13179  *			reference on *lopp.
13180  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13181  * (other)		unrecoverable error.
13182  */
13183 static void
13184 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13185     LOCKU4args **locku_argsp, flock64_t *flk,
13186     nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13187     vnode_t *vp, int flag, u_offset_t offset, cred_t *cr,
13188     bool_t *skip_get_err, bool_t *go_otwp)
13189 {
13190 	nfs4_lock_owner_t	*lop = NULL;
13191 	LOCKU4args		*locku_args;
13192 	pid_t			pid;
13193 	bool_t			is_spec = FALSE;
13194 	rnode4_t		*rp = VTOR4(vp);
13195 
13196 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13197 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13198 
13199 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13200 	if (ep->error || ep->stat)
13201 		return;
13202 
13203 	argop->argop = OP_LOCKU;
13204 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13205 		argsp->ctag = TAG_LOCKU_REINSTATE;
13206 	else
13207 		argsp->ctag = TAG_LOCKU;
13208 	locku_args = &argop->nfs_argop4_u.oplocku;
13209 	*locku_argsp = locku_args;
13210 
13211 	/*
13212 	 * XXX what should locku_args->locktype be?
13213 	 * setting to ALWAYS be READ_LT so at least
13214 	 * it is a valid locktype.
13215 	 */
13216 
13217 	locku_args->locktype = READ_LT;
13218 
13219 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13220 	    flk->l_pid;
13221 
13222 	/*
13223 	 * Get the lock owner stateid.  If no lock owner
13224 	 * exists, return success.
13225 	 */
13226 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13227 	*lopp = lop;
13228 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13229 		is_spec = TRUE;
13230 	if (!lop || is_spec) {
13231 		/*
13232 		 * No lock owner so no locks to unlock.
13233 		 * Return success.  If there was a failed
13234 		 * reclaim earlier, the lock might still be
13235 		 * registered with the local locking code,
13236 		 * so notify it of the unlock.
13237 		 *
13238 		 * If the lockowner is using a special stateid,
13239 		 * then the original lock request (that created
13240 		 * this lockowner) was never successful, so we
13241 		 * have no lock to undo OTW.
13242 		 */
13243 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13244 		    "nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13245 		    "(%ld) so return success", (long)pid));
13246 
13247 		if (ctype == NFS4_LCK_CTYPE_NORM)
13248 			flk->l_pid = curproc->p_pid;
13249 		nfs4_register_lock_locally(vp, flk, flag, offset);
13250 		/*
13251 		 * Release our hold and NULL out so final_cleanup
13252 		 * doesn't try to end a lock seqid sync we
13253 		 * never started.
13254 		 */
13255 		if (is_spec) {
13256 			lock_owner_rele(lop);
13257 			*lopp = NULL;
13258 		}
13259 		*skip_get_err = TRUE;
13260 		*go_otwp = FALSE;
13261 		return;
13262 	}
13263 
13264 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13265 	if (ep->error == EAGAIN) {
13266 		lock_owner_rele(lop);
13267 		*lopp = NULL;
13268 		return;
13269 	}
13270 
13271 	mutex_enter(&lop->lo_lock);
13272 	locku_args->lock_stateid = lop->lock_stateid;
13273 	mutex_exit(&lop->lo_lock);
13274 	locku_args->seqid = lop->lock_seqid + 1;
13275 
13276 	/* leave the ref count on lop, rele after RPC call */
13277 
13278 	locku_args->offset = flk->l_start;
13279 	locku_args->length = flk->l_len;
13280 	if (flk->l_len == 0)
13281 		locku_args->length = ~locku_args->length;
13282 
13283 	*go_otwp = TRUE;
13284 }
13285 
13286 /*
13287  * Setup the LOCK4 arguments.
13288  *
13289  * Returns errors via the nfs4_error_t.
13290  * NFS4_OK		no problems
13291  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13292  * (other)		unrecoverable error
13293  */
13294 static void
13295 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13296     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13297     nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13298     flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13299 {
13300 	LOCK4args		*lock_args;
13301 	nfs4_open_owner_t	*oop = NULL;
13302 	nfs4_open_stream_t	*osp = NULL;
13303 	nfs4_lock_owner_t	*lop = NULL;
13304 	pid_t			pid;
13305 	rnode4_t		*rp = VTOR4(vp);
13306 
13307 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13308 
13309 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13310 	if (ep->error || ep->stat != NFS4_OK)
13311 		return;
13312 
13313 	argop->argop = OP_LOCK;
13314 	if (ctype == NFS4_LCK_CTYPE_NORM)
13315 		argsp->ctag = TAG_LOCK;
13316 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13317 		argsp->ctag = TAG_RELOCK;
13318 	else
13319 		argsp->ctag = TAG_LOCK_REINSTATE;
13320 	lock_args = &argop->nfs_argop4_u.oplock;
13321 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13322 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13323 	/*
13324 	 * Get the lock owner.  If no lock owner exists,
13325 	 * create a 'temporary' one and grab the open seqid
13326 	 * synchronization (which puts a hold on the open
13327 	 * owner and open stream).
13328 	 * This also grabs the lock seqid synchronization.
13329 	 */
13330 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid : flk->l_pid;
13331 	ep->stat =
13332 	    nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13333 
13334 	if (ep->stat != NFS4_OK)
13335 		goto out;
13336 
13337 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13338 	    &lock_args->locker);
13339 
13340 	lock_args->offset = flk->l_start;
13341 	lock_args->length = flk->l_len;
13342 	if (flk->l_len == 0)
13343 		lock_args->length = ~lock_args->length;
13344 	*lock_argsp = lock_args;
13345 out:
13346 	*oopp = oop;
13347 	*ospp = osp;
13348 	*lopp = lop;
13349 }
13350 
13351 /*
13352  * After we get the reply from the server, record the proper information
13353  * for possible resend lock requests.
13354  *
13355  * Allocates memory for the saved_rqstp if we have a lost lock to save.
13356  */
13357 static void
13358 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13359     nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13360     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13361     nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13362 {
13363 	bool_t unlock = (flk->l_type == F_UNLCK);
13364 
13365 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13366 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13367 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13368 
13369 	if (error != 0 && !unlock) {
13370 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13371 		    nfs4_client_lock_debug), (CE_NOTE,
13372 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13373 		    " for lop %p", (void *)lop));
13374 		ASSERT(lop != NULL);
13375 		mutex_enter(&lop->lo_lock);
13376 		lop->lo_pending_rqsts = 1;
13377 		mutex_exit(&lop->lo_lock);
13378 	}
13379 
13380 	lost_rqstp->lr_putfirst = FALSE;
13381 	lost_rqstp->lr_op = 0;
13382 
13383 	/*
13384 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13385 	 * recovery purposes so that the lock request that was sent
13386 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13387 	 * unmount.  This is done to have the client's local locking state
13388 	 * match the v4 server's state; that is, the request was
13389 	 * potentially received and accepted by the server but the client
13390 	 * thinks it was not.
13391 	 */
13392 	if (error == ETIMEDOUT || error == EINTR ||
13393 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13394 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13395 		    nfs4_client_lock_debug), (CE_NOTE,
13396 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13397 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13398 		    (void *)lop, (void *)oop, (void *)osp));
13399 		if (unlock)
13400 			lost_rqstp->lr_op = OP_LOCKU;
13401 		else {
13402 			lost_rqstp->lr_op = OP_LOCK;
13403 			lost_rqstp->lr_locktype = locktype;
13404 		}
13405 		/*
13406 		 * Objects are held and rele'd via the recovery code.
13407 		 * See nfs4_save_lost_rqst.
13408 		 */
13409 		lost_rqstp->lr_vp = vp;
13410 		lost_rqstp->lr_dvp = NULL;
13411 		lost_rqstp->lr_oop = oop;
13412 		lost_rqstp->lr_osp = osp;
13413 		lost_rqstp->lr_lop = lop;
13414 		lost_rqstp->lr_cr = cr;
13415 		switch (ctype) {
13416 		case NFS4_LCK_CTYPE_NORM:
13417 			flk->l_pid = ttoproc(curthread)->p_pid;
13418 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13419 			break;
13420 		case NFS4_LCK_CTYPE_REINSTATE:
13421 			lost_rqstp->lr_putfirst = TRUE;
13422 			lost_rqstp->lr_ctype = ctype;
13423 			break;
13424 		default:
13425 			break;
13426 		}
13427 		lost_rqstp->lr_flk = flk;
13428 	}
13429 }
13430 
13431 /*
13432  * Update lop's seqid.  Also update the seqid stored in a resend request,
13433  * if any.  (Some recovery errors increment the seqid, and we may have to
13434  * send the resend request again.)
13435  */
13436 
13437 static void
13438 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13439     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13440 {
13441 	if (lock_args) {
13442 		if (lock_args->locker.new_lock_owner == TRUE)
13443 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13444 		else {
13445 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13446 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13447 		}
13448 	} else if (locku_args) {
13449 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13450 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13451 	}
13452 }
13453 
13454 /*
13455  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13456  * COMPOUND4 args/res for calls that need to retry.
13457  * Switches the *cred_otwp to base_cr.
13458  */
13459 static void
13460 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13461     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13462     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13463     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13464     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13465 {
13466 	nfs4_open_owner_t	*oop = *oopp;
13467 	nfs4_open_stream_t	*osp = *ospp;
13468 	nfs4_lock_owner_t	*lop = *lopp;
13469 	nfs_argop4		*argop = (*argspp)->array;
13470 
13471 	if (*did_start_fop) {
13472 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13473 		    needrecov);
13474 		*did_start_fop = FALSE;
13475 	}
13476 	ASSERT((*argspp)->array_len == 2);
13477 	if (argop[1].argop == OP_LOCK)
13478 		nfs4args_lock_free(&argop[1]);
13479 	else if (argop[1].argop == OP_LOCKT)
13480 		nfs4args_lockt_free(&argop[1]);
13481 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13482 	if (!error)
13483 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13484 	*argspp = NULL;
13485 	*respp = NULL;
13486 
13487 	if (lop) {
13488 		nfs4_end_lock_seqid_sync(lop);
13489 		lock_owner_rele(lop);
13490 		*lopp = NULL;
13491 	}
13492 
13493 	/* need to free up the reference on osp for lock args */
13494 	if (osp != NULL) {
13495 		open_stream_rele(osp, VTOR4(vp));
13496 		*ospp = NULL;
13497 	}
13498 
13499 	/* need to free up the reference on oop for lock args */
13500 	if (oop != NULL) {
13501 		nfs4_end_open_seqid_sync(oop);
13502 		open_owner_rele(oop);
13503 		*oopp = NULL;
13504 	}
13505 
13506 	crfree(*cred_otwp);
13507 	*cred_otwp = base_cr;
13508 	crhold(*cred_otwp);
13509 }
13510 
13511 /*
13512  * Function to process the client's recovery for nfs4frlock.
13513  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13514  *
13515  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13516  * COMPOUND4 args/res for calls that need to retry.
13517  *
13518  * Note: the rp's r_lkserlock is *not* dropped during this path.
13519  */
13520 static bool_t
13521 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13522     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13523     LOCK4args *lock_args, LOCKU4args *locku_args,
13524     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13525     nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13526     nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13527     bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13528 {
13529 	nfs4_open_owner_t	*oop = *oopp;
13530 	nfs4_open_stream_t	*osp = *ospp;
13531 	nfs4_lock_owner_t	*lop = *lopp;
13532 
13533 	bool_t abort, retry;
13534 
13535 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13536 	ASSERT((*argspp) != NULL);
13537 	ASSERT((*respp) != NULL);
13538 	if (lock_args || locku_args)
13539 		ASSERT(lop != NULL);
13540 
13541 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13542 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13543 
13544 	retry = TRUE;
13545 	abort = FALSE;
13546 	if (needrecov) {
13547 		nfs4_bseqid_entry_t *bsep = NULL;
13548 		nfs_opnum4 op;
13549 
13550 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13551 
13552 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13553 			seqid4 seqid;
13554 
13555 			if (lock_args) {
13556 				if (lock_args->locker.new_lock_owner == TRUE)
13557 					seqid = lock_args->locker.locker4_u.
13558 					    open_owner.open_seqid;
13559 				else
13560 					seqid = lock_args->locker.locker4_u.
13561 					    lock_owner.lock_seqid;
13562 			} else if (locku_args) {
13563 				seqid = locku_args->seqid;
13564 			} else {
13565 				seqid = 0;
13566 			}
13567 
13568 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13569 			    flk->l_pid, (*argspp)->ctag, seqid);
13570 		}
13571 
13572 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13573 		    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13574 		    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13575 		    NULL, op, bsep);
13576 
13577 		if (bsep)
13578 			kmem_free(bsep, sizeof (*bsep));
13579 	}
13580 
13581 	/*
13582 	 * Return that we do not want to retry the request for 3 cases:
13583 	 * 1. If we received EINTR or are bailing out because of a forced
13584 	 *    unmount, we came into this code path just for the sake of
13585 	 *    initiating recovery, we now need to return the error.
13586 	 * 2. If we have aborted recovery.
13587 	 * 3. We received NFS4ERR_BAD_SEQID.
13588 	 */
13589 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13590 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13591 		retry = FALSE;
13592 
13593 	if (*did_start_fop == TRUE) {
13594 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13595 		    needrecov);
13596 		*did_start_fop = FALSE;
13597 	}
13598 
13599 	if (retry == TRUE) {
13600 		nfs_argop4	*argop;
13601 
13602 		argop = (*argspp)->array;
13603 		ASSERT((*argspp)->array_len == 2);
13604 
13605 		if (argop[1].argop == OP_LOCK)
13606 			nfs4args_lock_free(&argop[1]);
13607 		else if (argop[1].argop == OP_LOCKT)
13608 			nfs4args_lockt_free(&argop[1]);
13609 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13610 		if (!ep->error)
13611 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13612 		*respp = NULL;
13613 		*argspp = NULL;
13614 	}
13615 
13616 	if (lop != NULL) {
13617 		nfs4_end_lock_seqid_sync(lop);
13618 		lock_owner_rele(lop);
13619 	}
13620 
13621 	*lopp = NULL;
13622 
13623 	/* need to free up the reference on osp for lock args */
13624 	if (osp != NULL) {
13625 		open_stream_rele(osp, rp);
13626 		*ospp = NULL;
13627 	}
13628 
13629 	/* need to free up the reference on oop for lock args */
13630 	if (oop != NULL) {
13631 		nfs4_end_open_seqid_sync(oop);
13632 		open_owner_rele(oop);
13633 		*oopp = NULL;
13634 	}
13635 
13636 	return (retry);
13637 }
13638 
13639 /*
13640  * Handles the successful reply from the server for nfs4frlock.
13641  */
13642 static void
13643 nfs4frlock_results_ok(nfs4_lock_call_type_t ctype, int cmd, flock64_t *flk,
13644     vnode_t *vp, int flag, u_offset_t offset,
13645     nfs4_lost_rqst_t *resend_rqstp)
13646 {
13647 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13648 	if ((cmd == F_SETLK || cmd == F_SETLKW) &&
13649 	    (flk->l_type == F_RDLCK || flk->l_type == F_WRLCK)) {
13650 		if (ctype == NFS4_LCK_CTYPE_NORM) {
13651 			flk->l_pid = ttoproc(curthread)->p_pid;
13652 			/*
13653 			 * We do not register lost locks locally in
13654 			 * the 'resend' case since the user/application
13655 			 * doesn't think we have the lock.
13656 			 */
13657 			ASSERT(!resend_rqstp);
13658 			nfs4_register_lock_locally(vp, flk, flag, offset);
13659 		}
13660 	}
13661 }
13662 
13663 /*
13664  * Handle the DENIED reply from the server for nfs4frlock.
13665  * Returns TRUE if we should retry the request; FALSE otherwise.
13666  *
13667  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13668  * COMPOUND4 args/res for calls that need to retry.  Can also
13669  * drop and regrab the r_lkserlock.
13670  */
13671 static bool_t
13672 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13673     LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13674     nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13675     vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13676     nfs4_recov_state_t *recov_statep, int needrecov,
13677     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13678     clock_t *tick_delayp, short *whencep, int *errorp,
13679     nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13680     bool_t *skip_get_err)
13681 {
13682 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13683 
13684 	if (lock_args) {
13685 		nfs4_open_owner_t	*oop = *oopp;
13686 		nfs4_open_stream_t	*osp = *ospp;
13687 		nfs4_lock_owner_t	*lop = *lopp;
13688 		int			intr;
13689 
13690 		/*
13691 		 * Blocking lock needs to sleep and retry from the request.
13692 		 *
13693 		 * Do not block and wait for 'resend' or 'reinstate'
13694 		 * lock requests, just return the error.
13695 		 *
13696 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13697 		 */
13698 		if (cmd == F_SETLKW) {
13699 			rnode4_t *rp = VTOR4(vp);
13700 			nfs_argop4 *argop = (*argspp)->array;
13701 
13702 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13703 
13704 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13705 			    recov_statep, needrecov);
13706 			*did_start_fop = FALSE;
13707 			ASSERT((*argspp)->array_len == 2);
13708 			if (argop[1].argop == OP_LOCK)
13709 				nfs4args_lock_free(&argop[1]);
13710 			else if (argop[1].argop == OP_LOCKT)
13711 				nfs4args_lockt_free(&argop[1]);
13712 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13713 			if (*respp)
13714 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13715 				    (caddr_t)*respp);
13716 			*argspp = NULL;
13717 			*respp = NULL;
13718 			nfs4_end_lock_seqid_sync(lop);
13719 			lock_owner_rele(lop);
13720 			*lopp = NULL;
13721 			if (osp != NULL) {
13722 				open_stream_rele(osp, rp);
13723 				*ospp = NULL;
13724 			}
13725 			if (oop != NULL) {
13726 				nfs4_end_open_seqid_sync(oop);
13727 				open_owner_rele(oop);
13728 				*oopp = NULL;
13729 			}
13730 
13731 			nfs_rw_exit(&rp->r_lkserlock);
13732 
13733 			intr = nfs4_block_and_wait(tick_delayp, rp);
13734 
13735 			if (intr) {
13736 				(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13737 				    RW_WRITER, FALSE);
13738 				*errorp = EINTR;
13739 				return (FALSE);
13740 			}
13741 
13742 			(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13743 			    RW_WRITER, FALSE);
13744 
13745 			/*
13746 			 * Make sure we are still safe to lock with
13747 			 * regards to mmapping.
13748 			 */
13749 			if (!nfs4_safelock(vp, flk, cr)) {
13750 				*errorp = EAGAIN;
13751 				return (FALSE);
13752 			}
13753 
13754 			return (TRUE);
13755 		}
13756 		if (ctype == NFS4_LCK_CTYPE_NORM)
13757 			*errorp = EAGAIN;
13758 		*skip_get_err = TRUE;
13759 		flk->l_whence = 0;
13760 		*whencep = 0;
13761 		return (FALSE);
13762 	} else if (lockt_args) {
13763 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13764 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
13765 
13766 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
13767 		    flk, lockt_args);
13768 
13769 		/* according to NLM code */
13770 		*errorp = 0;
13771 		*whencep = 0;
13772 		*skip_get_err = TRUE;
13773 		return (FALSE);
13774 	}
13775 	return (FALSE);
13776 }
13777 
13778 /*
13779  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
13780  */
13781 static void
13782 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
13783 {
13784 	switch (resp->status) {
13785 	case NFS4ERR_ACCESS:
13786 	case NFS4ERR_ADMIN_REVOKED:
13787 	case NFS4ERR_BADHANDLE:
13788 	case NFS4ERR_BAD_RANGE:
13789 	case NFS4ERR_BAD_SEQID:
13790 	case NFS4ERR_BAD_STATEID:
13791 	case NFS4ERR_BADXDR:
13792 	case NFS4ERR_DEADLOCK:
13793 	case NFS4ERR_DELAY:
13794 	case NFS4ERR_EXPIRED:
13795 	case NFS4ERR_FHEXPIRED:
13796 	case NFS4ERR_GRACE:
13797 	case NFS4ERR_INVAL:
13798 	case NFS4ERR_ISDIR:
13799 	case NFS4ERR_LEASE_MOVED:
13800 	case NFS4ERR_LOCK_NOTSUPP:
13801 	case NFS4ERR_LOCK_RANGE:
13802 	case NFS4ERR_MOVED:
13803 	case NFS4ERR_NOFILEHANDLE:
13804 	case NFS4ERR_NO_GRACE:
13805 	case NFS4ERR_OLD_STATEID:
13806 	case NFS4ERR_OPENMODE:
13807 	case NFS4ERR_RECLAIM_BAD:
13808 	case NFS4ERR_RECLAIM_CONFLICT:
13809 	case NFS4ERR_RESOURCE:
13810 	case NFS4ERR_SERVERFAULT:
13811 	case NFS4ERR_STALE:
13812 	case NFS4ERR_STALE_CLIENTID:
13813 	case NFS4ERR_STALE_STATEID:
13814 		return;
13815 	default:
13816 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13817 		    "nfs4frlock_results_default: got unrecognizable "
13818 		    "res.status %d", resp->status));
13819 		*errorp = NFS4ERR_INVAL;
13820 	}
13821 }
13822 
13823 /*
13824  * The lock request was successful, so update the client's state.
13825  */
13826 static void
13827 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
13828     LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
13829     vnode_t *vp, flock64_t *flk, cred_t *cr,
13830     nfs4_lost_rqst_t *resend_rqstp)
13831 {
13832 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13833 
13834 	if (lock_args) {
13835 		LOCK4res *lock_res;
13836 
13837 		lock_res = &resop->nfs_resop4_u.oplock;
13838 		/* update the stateid with server's response */
13839 
13840 		if (lock_args->locker.new_lock_owner == TRUE) {
13841 			mutex_enter(&lop->lo_lock);
13842 			lop->lo_just_created = NFS4_PERM_CREATED;
13843 			mutex_exit(&lop->lo_lock);
13844 		}
13845 
13846 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
13847 
13848 		/*
13849 		 * If the lock was the result of a resending a lost
13850 		 * request, we've synched up the stateid and seqid
13851 		 * with the server, but now the server might be out of sync
13852 		 * with what the application thinks it has for locks.
13853 		 * Clean that up here.  It's unclear whether we should do
13854 		 * this even if the filesystem has been forcibly unmounted.
13855 		 * For most servers, it's probably wasted effort, but
13856 		 * RFC3530 lets servers require that unlocks exactly match
13857 		 * the locks that are held.
13858 		 */
13859 		if (resend_rqstp != NULL &&
13860 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
13861 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
13862 		} else {
13863 			flk->l_whence = 0;
13864 		}
13865 	} else if (locku_args) {
13866 		LOCKU4res *locku_res;
13867 
13868 		locku_res = &resop->nfs_resop4_u.oplocku;
13869 
13870 		/* Update the stateid with the server's response */
13871 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
13872 	} else if (lockt_args) {
13873 		/* Switch the lock type to express success, see fcntl */
13874 		flk->l_type = F_UNLCK;
13875 		flk->l_whence = 0;
13876 	}
13877 }
13878 
13879 /*
13880  * Do final cleanup before exiting nfs4frlock.
13881  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13882  * COMPOUND4 args/res for calls that haven't already.
13883  */
13884 static void
13885 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
13886     COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
13887     nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
13888     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13889     short whence, u_offset_t offset, struct lm_sysid *ls,
13890     int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
13891     bool_t did_start_fop, bool_t skip_get_err,
13892     cred_t *cred_otw, cred_t *cred)
13893 {
13894 	mntinfo4_t	*mi = VTOMI4(vp);
13895 	rnode4_t	*rp = VTOR4(vp);
13896 	int		error = *errorp;
13897 	nfs_argop4	*argop;
13898 
13899 	ASSERT(nfs_zone() == mi->mi_zone);
13900 	/*
13901 	 * The client recovery code wants the raw status information,
13902 	 * so don't map the NFS status code to an errno value for
13903 	 * non-normal call types.
13904 	 */
13905 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13906 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
13907 			*errorp = geterrno4(resp->status);
13908 		if (did_start_fop == TRUE)
13909 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
13910 			    needrecov);
13911 
13912 		/*
13913 		 * We've established a new lock on the server, so invalidate
13914 		 * the pages associated with the vnode to get the most up to
13915 		 * date pages from the server after acquiring the lock. We
13916 		 * want to be sure that the read operation gets the newest data.
13917 		 * N.B.
13918 		 * We used to do this in nfs4frlock_results_ok but that doesn't
13919 		 * work since VOP_PUTPAGE can call nfs4_commit which calls
13920 		 * nfs4_start_fop. We flush the pages below after calling
13921 		 * nfs4_end_fop above
13922 		 */
13923 		if (!error && resp && resp->status == NFS4_OK) {
13924 			int error;
13925 
13926 			error = VOP_PUTPAGE(vp, (u_offset_t)0,
13927 			    0, B_INVAL, cred, NULL);
13928 
13929 			if (error && (error == ENOSPC || error == EDQUOT)) {
13930 				rnode4_t *rp = VTOR4(vp);
13931 
13932 				mutex_enter(&rp->r_statelock);
13933 				if (!rp->r_error)
13934 					rp->r_error = error;
13935 				mutex_exit(&rp->r_statelock);
13936 			}
13937 		}
13938 	}
13939 	if (argsp) {
13940 		ASSERT(argsp->array_len == 2);
13941 		argop = argsp->array;
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 		if (resp)
13948 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
13949 	}
13950 
13951 	/* free the reference on the lock owner */
13952 	if (lop != NULL) {
13953 		nfs4_end_lock_seqid_sync(lop);
13954 		lock_owner_rele(lop);
13955 	}
13956 
13957 	/* need to free up the reference on osp for lock args */
13958 	if (osp != NULL)
13959 		open_stream_rele(osp, rp);
13960 
13961 	/* need to free up the reference on oop for lock args */
13962 	if (oop != NULL) {
13963 		nfs4_end_open_seqid_sync(oop);
13964 		open_owner_rele(oop);
13965 	}
13966 
13967 	(void) convoff(vp, flk, whence, offset);
13968 
13969 	lm_rel_sysid(ls);
13970 
13971 	/*
13972 	 * Record debug information in the event we get EINVAL.
13973 	 */
13974 	mutex_enter(&mi->mi_lock);
13975 	if (*errorp == EINVAL && (lock_args || locku_args) &&
13976 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
13977 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
13978 			zcmn_err(getzoneid(), CE_NOTE,
13979 			    "%s operation failed with "
13980 			    "EINVAL probably since the server, %s,"
13981 			    " doesn't support POSIX style locking",
13982 			    lock_args ? "LOCK" : "LOCKU",
13983 			    mi->mi_curr_serv->sv_hostname);
13984 			mi->mi_flags |= MI4_LOCK_DEBUG;
13985 		}
13986 	}
13987 	mutex_exit(&mi->mi_lock);
13988 
13989 	if (cred_otw)
13990 		crfree(cred_otw);
13991 }
13992 
13993 /*
13994  * This calls the server and the local locking code.
13995  *
13996  * Client locks are registerred locally by oring the sysid with
13997  * LM_SYSID_CLIENT. The server registers locks locally using just the sysid.
13998  * We need to distinguish between the two to avoid collision in case one
13999  * machine is used as both client and server.
14000  *
14001  * Blocking lock requests will continually retry to acquire the lock
14002  * forever.
14003  *
14004  * The ctype is defined as follows:
14005  * NFS4_LCK_CTYPE_NORM: normal lock request.
14006  *
14007  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
14008  * recovery, get the pid from flk instead of curproc, and don't reregister
14009  * the lock locally.
14010  *
14011  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
14012  * that we will use the information passed in via resend_rqstp to setup the
14013  * lock/locku request.  This resend is the exact same request as the 'lost
14014  * lock', and is initiated by the recovery framework. A successful resend
14015  * request can initiate one or more reinstate requests.
14016  *
14017  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14018  * does not trigger additional reinstate requests.  This lock call type is
14019  * set for setting the v4 server's locking state back to match what the
14020  * client's local locking state is in the event of a received 'lost lock'.
14021  *
14022  * Errors are returned via the nfs4_error_t parameter.
14023  */
14024 void
14025 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14026     int flag, u_offset_t offset, cred_t *cr, nfs4_error_t *ep,
14027     nfs4_lost_rqst_t *resend_rqstp, int *did_reclaimp)
14028 {
14029 	COMPOUND4args_clnt	args, *argsp = NULL;
14030 	COMPOUND4res_clnt	res, *resp = NULL;
14031 	nfs_argop4	*argop;
14032 	nfs_resop4	*resop;
14033 	rnode4_t	*rp;
14034 	int		doqueue = 1;
14035 	clock_t		tick_delay;  /* delay in clock ticks */
14036 	struct lm_sysid	*ls;
14037 	LOCK4args	*lock_args = NULL;
14038 	LOCKU4args	*locku_args = NULL;
14039 	LOCKT4args	*lockt_args = NULL;
14040 	nfs4_open_owner_t *oop = NULL;
14041 	nfs4_open_stream_t *osp = NULL;
14042 	nfs4_lock_owner_t *lop = NULL;
14043 	bool_t		needrecov = FALSE;
14044 	nfs4_recov_state_t recov_state;
14045 	short		whence;
14046 	nfs4_op_hint_t	op_hint;
14047 	nfs4_lost_rqst_t lost_rqst;
14048 	bool_t		retry = FALSE;
14049 	bool_t		did_start_fop = FALSE;
14050 	bool_t		skip_get_err = FALSE;
14051 	cred_t		*cred_otw = NULL;
14052 	bool_t		recovonly;	/* just queue request */
14053 	int		frc_no_reclaim = 0;
14054 #ifdef DEBUG
14055 	char *name;
14056 #endif
14057 
14058 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14059 
14060 #ifdef DEBUG
14061 	name = fn_name(VTOSV(vp)->sv_name);
14062 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14063 	    "%s: cmd %d, type %d, offset %llu, start %"PRIx64", "
14064 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14065 	    "resend request %s", name, cmd, flk->l_type, offset, flk->l_start,
14066 	    flk->l_len, ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid :
14067 	    flk->l_pid, flk->l_sysid, nfs4frlock_get_call_type(ctype),
14068 	    resend_rqstp ? "TRUE" : "FALSE"));
14069 	kmem_free(name, MAXNAMELEN);
14070 #endif
14071 
14072 	nfs4_error_zinit(ep);
14073 	ep->error = nfs4frlock_validate_args(cmd, flk, flag, vp, offset);
14074 	if (ep->error)
14075 		return;
14076 	ep->error = nfs4frlock_get_sysid(&ls, vp, flk);
14077 	if (ep->error)
14078 		return;
14079 	nfs4frlock_pre_setup(&tick_delay, &recov_state, flk, &whence,
14080 	    vp, cr, &cred_otw);
14081 
14082 recov_retry:
14083 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14084 	    &retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14085 	rp = VTOR4(vp);
14086 
14087 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14088 	    &did_start_fop, &recovonly);
14089 
14090 	if (ep->error)
14091 		goto out;
14092 
14093 	if (recovonly) {
14094 		/*
14095 		 * Leave the request for the recovery system to deal with.
14096 		 */
14097 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14098 		ASSERT(cmd != F_GETLK);
14099 		ASSERT(flk->l_type == F_UNLCK);
14100 
14101 		nfs4_error_init(ep, EINTR);
14102 		needrecov = TRUE;
14103 		lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14104 		if (lop != NULL) {
14105 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14106 			    NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14107 			(void) nfs4_start_recovery(ep,
14108 			    VTOMI4(vp), vp, NULL, NULL,
14109 			    (lost_rqst.lr_op == OP_LOCK ||
14110 			    lost_rqst.lr_op == OP_LOCKU) ?
14111 			    &lost_rqst : NULL, OP_LOCKU, NULL);
14112 			lock_owner_rele(lop);
14113 			lop = NULL;
14114 		}
14115 		flk->l_pid = curproc->p_pid;
14116 		nfs4_register_lock_locally(vp, flk, flag, offset);
14117 		goto out;
14118 	}
14119 
14120 	/* putfh directory fh */
14121 	argop[0].argop = OP_CPUTFH;
14122 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14123 
14124 	/*
14125 	 * Set up the over-the-wire arguments and get references to the
14126 	 * open owner, etc.
14127 	 */
14128 
14129 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14130 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14131 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14132 		    &argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14133 	} else {
14134 		bool_t go_otw = TRUE;
14135 
14136 		ASSERT(resend_rqstp == NULL);
14137 
14138 		switch (cmd) {
14139 		case F_GETLK:
14140 		case F_O_GETLK:
14141 			nfs4frlock_setup_lockt_args(ctype, &argop[1],
14142 			    &lockt_args, argsp, flk, rp);
14143 			break;
14144 		case F_SETLKW:
14145 		case F_SETLK:
14146 			if (flk->l_type == F_UNLCK)
14147 				nfs4frlock_setup_locku_args(ctype,
14148 				    &argop[1], &locku_args, flk,
14149 				    &lop, ep, argsp,
14150 				    vp, flag, offset, cr,
14151 				    &skip_get_err, &go_otw);
14152 			else
14153 				nfs4frlock_setup_lock_args(ctype,
14154 				    &lock_args, &oop, &osp, &lop, &argop[1],
14155 				    argsp, flk, cmd, vp, cr, ep);
14156 
14157 			if (ep->error)
14158 				goto out;
14159 
14160 			switch (ep->stat) {
14161 			case NFS4_OK:
14162 				break;
14163 			case NFS4ERR_DELAY:
14164 				/* recov thread never gets this error */
14165 				ASSERT(resend_rqstp == NULL);
14166 				ASSERT(did_start_fop);
14167 
14168 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14169 				    &recov_state, TRUE);
14170 				did_start_fop = FALSE;
14171 				if (argop[1].argop == OP_LOCK)
14172 					nfs4args_lock_free(&argop[1]);
14173 				else if (argop[1].argop == OP_LOCKT)
14174 					nfs4args_lockt_free(&argop[1]);
14175 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14176 				argsp = NULL;
14177 				goto recov_retry;
14178 			default:
14179 				ep->error = EIO;
14180 				goto out;
14181 			}
14182 			break;
14183 		default:
14184 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14185 			    "nfs4_frlock: invalid cmd %d", cmd));
14186 			ep->error = EINVAL;
14187 			goto out;
14188 		}
14189 
14190 		if (!go_otw)
14191 			goto out;
14192 	}
14193 
14194 	/* XXX should we use the local reclock as a cache ? */
14195 	/*
14196 	 * Unregister the lock with the local locking code before
14197 	 * contacting the server.  This avoids a potential race where
14198 	 * another process gets notified that it has been granted a lock
14199 	 * before we can unregister ourselves locally.
14200 	 */
14201 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK) {
14202 		if (ctype == NFS4_LCK_CTYPE_NORM)
14203 			flk->l_pid = ttoproc(curthread)->p_pid;
14204 		nfs4_register_lock_locally(vp, flk, flag, offset);
14205 	}
14206 
14207 	/*
14208 	 * Send the server the lock request.  Continually loop with a delay
14209 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14210 	 */
14211 	resp = &res;
14212 
14213 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14214 	    (CE_NOTE,
14215 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14216 	    rnode4info(rp)));
14217 
14218 	if (lock_args && frc_no_reclaim) {
14219 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14220 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14221 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14222 		lock_args->reclaim = FALSE;
14223 		if (did_reclaimp)
14224 			*did_reclaimp = 0;
14225 	}
14226 
14227 	/*
14228 	 * Do the OTW call.
14229 	 */
14230 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14231 
14232 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14233 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14234 
14235 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14236 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14237 	    "nfs4frlock: needrecov %d", needrecov));
14238 
14239 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14240 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14241 		    args.ctag);
14242 
14243 	/*
14244 	 * Check if one of these mutually exclusive error cases has
14245 	 * happened:
14246 	 *   need to swap credentials due to access error
14247 	 *   recovery is needed
14248 	 *   different error (only known case is missing Kerberos ticket)
14249 	 */
14250 
14251 	if ((ep->error == EACCES ||
14252 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14253 	    cred_otw != cr) {
14254 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14255 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14256 		    cr, &cred_otw);
14257 		goto recov_retry;
14258 	}
14259 
14260 	if (needrecov) {
14261 		/*
14262 		 * LOCKT requests don't need to recover from lost
14263 		 * requests since they don't create/modify state.
14264 		 */
14265 		if ((ep->error == EINTR ||
14266 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14267 		    lockt_args)
14268 			goto out;
14269 		/*
14270 		 * Do not attempt recovery for requests initiated by
14271 		 * the recovery framework.  Let the framework redrive them.
14272 		 */
14273 		if (ctype != NFS4_LCK_CTYPE_NORM)
14274 			goto out;
14275 		else {
14276 			ASSERT(resend_rqstp == NULL);
14277 		}
14278 
14279 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14280 		    flk_to_locktype(cmd, flk->l_type),
14281 		    oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14282 
14283 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14284 		    &resp, lock_args, locku_args, &oop, &osp, &lop,
14285 		    rp, vp, &recov_state, op_hint, &did_start_fop,
14286 		    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14287 
14288 		if (retry) {
14289 			ASSERT(oop == NULL);
14290 			ASSERT(osp == NULL);
14291 			ASSERT(lop == NULL);
14292 			goto recov_retry;
14293 		}
14294 		goto out;
14295 	}
14296 
14297 	/*
14298 	 * Bail out if have reached this point with ep->error set. Can
14299 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14300 	 * This happens if Kerberos ticket has expired or has been
14301 	 * destroyed.
14302 	 */
14303 	if (ep->error != 0)
14304 		goto out;
14305 
14306 	/*
14307 	 * Process the reply.
14308 	 */
14309 	switch (resp->status) {
14310 	case NFS4_OK:
14311 		resop = &resp->array[1];
14312 		nfs4frlock_results_ok(ctype, cmd, flk, vp, flag, offset,
14313 		    resend_rqstp);
14314 		/*
14315 		 * Have a successful lock operation, now update state.
14316 		 */
14317 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14318 		    resop, lop, vp, flk, cr, resend_rqstp);
14319 		break;
14320 
14321 	case NFS4ERR_DENIED:
14322 		resop = &resp->array[1];
14323 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14324 		    &oop, &osp, &lop, cmd, vp, flk, op_hint,
14325 		    &recov_state, needrecov, &argsp, &resp,
14326 		    &tick_delay, &whence, &ep->error, resop, cr,
14327 		    &did_start_fop, &skip_get_err);
14328 
14329 		if (retry) {
14330 			ASSERT(oop == NULL);
14331 			ASSERT(osp == NULL);
14332 			ASSERT(lop == NULL);
14333 			goto recov_retry;
14334 		}
14335 		break;
14336 	/*
14337 	 * If the server won't let us reclaim, fall-back to trying to lock
14338 	 * the file from scratch. Code elsewhere will check the changeinfo
14339 	 * to ensure the file hasn't been changed.
14340 	 */
14341 	case NFS4ERR_NO_GRACE:
14342 		if (lock_args && lock_args->reclaim == TRUE) {
14343 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14344 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14345 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14346 			frc_no_reclaim = 1;
14347 			/* clean up before retrying */
14348 			needrecov = 0;
14349 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14350 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14351 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14352 			goto recov_retry;
14353 		}
14354 		/* FALLTHROUGH */
14355 
14356 	default:
14357 		nfs4frlock_results_default(resp, &ep->error);
14358 		break;
14359 	}
14360 out:
14361 	/*
14362 	 * Process and cleanup from error.  Make interrupted unlock
14363 	 * requests look successful, since they will be handled by the
14364 	 * client recovery code.
14365 	 */
14366 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14367 	    needrecov, oop, osp, lop, flk, whence, offset, ls, &ep->error,
14368 	    lock_args, locku_args, did_start_fop,
14369 	    skip_get_err, cred_otw, cr);
14370 
14371 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14372 	    (cmd == F_SETLK || cmd == F_SETLKW))
14373 		ep->error = 0;
14374 }
14375 
14376 /*
14377  * nfs4_safelock:
14378  *
14379  * Return non-zero if the given lock request can be handled without
14380  * violating the constraints on concurrent mapping and locking.
14381  */
14382 
14383 static int
14384 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14385 {
14386 	rnode4_t *rp = VTOR4(vp);
14387 	struct vattr va;
14388 	int error;
14389 
14390 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14391 	ASSERT(rp->r_mapcnt >= 0);
14392 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14393 	    "(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14394 	    "write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14395 	    bfp->l_start, bfp->l_len, rp->r_mapcnt));
14396 
14397 	if (rp->r_mapcnt == 0)
14398 		return (1);		/* always safe if not mapped */
14399 
14400 	/*
14401 	 * If the file is already mapped and there are locks, then they
14402 	 * should be all safe locks.  So adding or removing a lock is safe
14403 	 * as long as the new request is safe (i.e., whole-file, meaning
14404 	 * length and starting offset are both zero).
14405 	 */
14406 
14407 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14408 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14409 		    "cannot lock a memory mapped file unless locking the "
14410 		    "entire file: start %"PRIx64", len %"PRIx64,
14411 		    bfp->l_start, bfp->l_len));
14412 		return (0);
14413 	}
14414 
14415 	/* mandatory locking and mapping don't mix */
14416 	va.va_mask = AT_MODE;
14417 	error = VOP_GETATTR(vp, &va, 0, cr, NULL);
14418 	if (error != 0) {
14419 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14420 		    "getattr error %d", error));
14421 		return (0);		/* treat errors conservatively */
14422 	}
14423 	if (MANDLOCK(vp, va.va_mode)) {
14424 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14425 		    "cannot mandatory lock and mmap a file"));
14426 		return (0);
14427 	}
14428 
14429 	return (1);
14430 }
14431 
14432 
14433 /*
14434  * Register the lock locally within Solaris.
14435  * As the client, we "or" the sysid with LM_SYSID_CLIENT when
14436  * recording locks locally.
14437  *
14438  * This should handle conflicts/cooperation with NFS v2/v3 since all locks
14439  * are registered locally.
14440  */
14441 void
14442 nfs4_register_lock_locally(vnode_t *vp, struct flock64 *flk, int flag,
14443     u_offset_t offset)
14444 {
14445 	int oldsysid;
14446 	int error;
14447 #ifdef DEBUG
14448 	char *name;
14449 #endif
14450 
14451 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14452 
14453 #ifdef DEBUG
14454 	name = fn_name(VTOSV(vp)->sv_name);
14455 	NFS4_DEBUG(nfs4_client_lock_debug,
14456 	    (CE_NOTE, "nfs4_register_lock_locally: %s: type %d, "
14457 	    "start %"PRIx64", length %"PRIx64", pid %ld, sysid %d",
14458 	    name, flk->l_type, flk->l_start, flk->l_len, (long)flk->l_pid,
14459 	    flk->l_sysid));
14460 	kmem_free(name, MAXNAMELEN);
14461 #endif
14462 
14463 	/* register the lock with local locking */
14464 	oldsysid = flk->l_sysid;
14465 	flk->l_sysid |= LM_SYSID_CLIENT;
14466 	error = reclock(vp, flk, SETFLCK, flag, offset, NULL);
14467 #ifdef DEBUG
14468 	if (error != 0) {
14469 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14470 		    "nfs4_register_lock_locally: could not register with"
14471 		    " local locking"));
14472 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14473 		    "error %d, vp 0x%p, pid %d, sysid 0x%x",
14474 		    error, (void *)vp, flk->l_pid, flk->l_sysid));
14475 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14476 		    "type %d off 0x%" PRIx64 " len 0x%" PRIx64,
14477 		    flk->l_type, flk->l_start, flk->l_len));
14478 		(void) reclock(vp, flk, 0, flag, offset, NULL);
14479 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14480 		    "blocked by pid %d sysid 0x%x type %d "
14481 		    "off 0x%" PRIx64 " len 0x%" PRIx64,
14482 		    flk->l_pid, flk->l_sysid, flk->l_type, flk->l_start,
14483 		    flk->l_len));
14484 	}
14485 #endif
14486 	flk->l_sysid = oldsysid;
14487 }
14488 
14489 /*
14490  * nfs4_lockrelease:
14491  *
14492  * Release any locks on the given vnode that are held by the current
14493  * process.  Also removes the lock owner (if one exists) from the rnode's
14494  * list.
14495  */
14496 static int
14497 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14498 {
14499 	flock64_t ld;
14500 	int ret, error;
14501 	rnode4_t *rp;
14502 	nfs4_lock_owner_t *lop;
14503 	nfs4_recov_state_t recov_state;
14504 	mntinfo4_t *mi;
14505 	bool_t possible_orphan = FALSE;
14506 	bool_t recovonly;
14507 
14508 	ASSERT((uintptr_t)vp > KERNELBASE);
14509 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14510 
14511 	rp = VTOR4(vp);
14512 	mi = VTOMI4(vp);
14513 
14514 	/*
14515 	 * If we have not locked anything then we can
14516 	 * just return since we have no work to do.
14517 	 */
14518 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14519 		return (0);
14520 	}
14521 
14522 	/*
14523 	 * We need to comprehend that another thread may
14524 	 * kick off recovery and the lock_owner we have stashed
14525 	 * in lop might be invalid so we should NOT cache it
14526 	 * locally!
14527 	 */
14528 	recov_state.rs_flags = 0;
14529 	recov_state.rs_num_retry_despite_err = 0;
14530 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14531 	    &recovonly);
14532 	if (error) {
14533 		mutex_enter(&rp->r_statelock);
14534 		rp->r_flags |= R4LODANGLERS;
14535 		mutex_exit(&rp->r_statelock);
14536 		return (error);
14537 	}
14538 
14539 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14540 
14541 	/*
14542 	 * Check if the lock owner might have a lock (request was sent but
14543 	 * no response was received).  Also check if there are any remote
14544 	 * locks on the file.  (In theory we shouldn't have to make this
14545 	 * second check if there's no lock owner, but for now we'll be
14546 	 * conservative and do it anyway.)  If either condition is true,
14547 	 * send an unlock for the entire file to the server.
14548 	 *
14549 	 * Note that no explicit synchronization is needed here.  At worst,
14550 	 * flk_has_remote_locks() will return a false positive, in which case
14551 	 * the unlock call wastes time but doesn't harm correctness.
14552 	 */
14553 
14554 	if (lop) {
14555 		mutex_enter(&lop->lo_lock);
14556 		possible_orphan = lop->lo_pending_rqsts;
14557 		mutex_exit(&lop->lo_lock);
14558 		lock_owner_rele(lop);
14559 	}
14560 
14561 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14562 
14563 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14564 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14565 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14566 	    (void *)lop));
14567 
14568 	if (possible_orphan || flk_has_remote_locks(vp)) {
14569 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14570 		ld.l_whence = 0;	/* unlock from start of file */
14571 		ld.l_start = 0;
14572 		ld.l_len = 0;		/* do entire file */
14573 
14574 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL,
14575 		    cr, NULL);
14576 
14577 		if (ret != 0) {
14578 			/*
14579 			 * If VOP_FRLOCK fails, make sure we unregister
14580 			 * local locks before we continue.
14581 			 */
14582 			ld.l_pid = ttoproc(curthread)->p_pid;
14583 			nfs4_register_lock_locally(vp, &ld, flag, offset);
14584 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14585 			    "nfs4_lockrelease: lock release error on vp"
14586 			    " %p: error %d.\n", (void *)vp, ret));
14587 		}
14588 	}
14589 
14590 	recov_state.rs_flags = 0;
14591 	recov_state.rs_num_retry_despite_err = 0;
14592 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14593 	    &recovonly);
14594 	if (error) {
14595 		mutex_enter(&rp->r_statelock);
14596 		rp->r_flags |= R4LODANGLERS;
14597 		mutex_exit(&rp->r_statelock);
14598 		return (error);
14599 	}
14600 
14601 	/*
14602 	 * So, here we're going to need to retrieve the lock-owner
14603 	 * again (in case recovery has done a switch-a-roo) and
14604 	 * remove it because we can.
14605 	 */
14606 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14607 
14608 	if (lop) {
14609 		nfs4_rnode_remove_lock_owner(rp, lop);
14610 		lock_owner_rele(lop);
14611 	}
14612 
14613 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14614 	return (0);
14615 }
14616 
14617 /*
14618  * Wait for 'tick_delay' clock ticks.
14619  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14620  * NOTE: lock_lease_time is in seconds.
14621  *
14622  * XXX For future improvements, should implement a waiting queue scheme.
14623  */
14624 static int
14625 nfs4_block_and_wait(clock_t *tick_delay, rnode4_t *rp)
14626 {
14627 	long milliseconds_delay;
14628 	time_t lock_lease_time;
14629 
14630 	/* wait tick_delay clock ticks or siginteruptus */
14631 	if (delay_sig(*tick_delay)) {
14632 		return (EINTR);
14633 	}
14634 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14635 	    "reissue the lock request: blocked for %ld clock ticks: %ld "
14636 	    "milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14637 
14638 	/* get the lease time */
14639 	lock_lease_time = r2lease_time(rp);
14640 
14641 	/* drv_hztousec converts ticks to microseconds */
14642 	milliseconds_delay = drv_hztousec(*tick_delay) / 1000;
14643 	if (milliseconds_delay < lock_lease_time * 1000) {
14644 		*tick_delay = 2 * *tick_delay;
14645 		if (drv_hztousec(*tick_delay) > lock_lease_time * 1000 * 1000)
14646 			*tick_delay = drv_usectohz(lock_lease_time*1000*1000);
14647 	}
14648 	return (0);
14649 }
14650 
14651 
14652 void
14653 nfs4_vnops_init(void)
14654 {
14655 }
14656 
14657 void
14658 nfs4_vnops_fini(void)
14659 {
14660 }
14661 
14662 /*
14663  * Return a reference to the directory (parent) vnode for a given vnode,
14664  * using the saved pathname information and the directory file handle.  The
14665  * caller is responsible for disposing of the reference.
14666  * Returns zero or an errno value.
14667  *
14668  * Caller should set need_start_op to FALSE if it is the recovery
14669  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14670  */
14671 int
14672 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14673 {
14674 	svnode_t *svnp;
14675 	vnode_t *dvp = NULL;
14676 	servinfo4_t *svp;
14677 	nfs4_fname_t *mfname;
14678 	int error;
14679 
14680 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14681 
14682 	if (vp->v_flag & VROOT) {
14683 		nfs4_sharedfh_t *sfh;
14684 		nfs_fh4 fh;
14685 		mntinfo4_t *mi;
14686 
14687 		ASSERT(vp->v_type == VREG);
14688 
14689 		mi = VTOMI4(vp);
14690 		svp = mi->mi_curr_serv;
14691 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14692 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14693 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14694 		sfh = sfh4_get(&fh, VTOMI4(vp));
14695 		nfs_rw_exit(&svp->sv_lock);
14696 		mfname = mi->mi_fname;
14697 		fn_hold(mfname);
14698 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14699 		sfh4_rele(&sfh);
14700 
14701 		if (dvp->v_type == VNON)
14702 			dvp->v_type = VDIR;
14703 		*dvpp = dvp;
14704 		return (0);
14705 	}
14706 
14707 	svnp = VTOSV(vp);
14708 
14709 	if (svnp == NULL) {
14710 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14711 		    "shadow node is NULL"));
14712 		return (EINVAL);
14713 	}
14714 
14715 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14716 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14717 		    "shadow node name or dfh val == NULL"));
14718 		return (EINVAL);
14719 	}
14720 
14721 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14722 	    (int)need_start_op);
14723 	if (error != 0) {
14724 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14725 		    "nfs4_make_dotdot returned %d", error));
14726 		return (error);
14727 	}
14728 	if (!dvp) {
14729 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14730 		    "nfs4_make_dotdot returned a NULL dvp"));
14731 		return (EIO);
14732 	}
14733 	if (dvp->v_type == VNON)
14734 		dvp->v_type = VDIR;
14735 	ASSERT(dvp->v_type == VDIR);
14736 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14737 		mutex_enter(&dvp->v_lock);
14738 		dvp->v_flag |= V_XATTRDIR;
14739 		mutex_exit(&dvp->v_lock);
14740 	}
14741 	*dvpp = dvp;
14742 	return (0);
14743 }
14744 
14745 /*
14746  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14747  * length that fnamep can accept, including the trailing null.
14748  * Returns 0 if okay, returns an errno value if there was a problem.
14749  */
14750 
14751 int
14752 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14753 {
14754 	char *fn;
14755 	int err = 0;
14756 	servinfo4_t *svp;
14757 	svnode_t *shvp;
14758 
14759 	/*
14760 	 * If the file being opened has VROOT set, then this is
14761 	 * a "file" mount.  sv_name will not be interesting, so
14762 	 * go back to the servinfo4 to get the original mount
14763 	 * path and strip off all but the final edge.  Otherwise
14764 	 * just return the name from the shadow vnode.
14765 	 */
14766 
14767 	if (vp->v_flag & VROOT) {
14768 
14769 		svp = VTOMI4(vp)->mi_curr_serv;
14770 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14771 
14772 		fn = strrchr(svp->sv_path, '/');
14773 		if (fn == NULL)
14774 			err = EINVAL;
14775 		else
14776 			fn++;
14777 	} else {
14778 		shvp = VTOSV(vp);
14779 		fn = fn_name(shvp->sv_name);
14780 	}
14781 
14782 	if (err == 0)
14783 		if (strlen(fn) < maxlen)
14784 			(void) strcpy(fnamep, fn);
14785 		else
14786 			err = ENAMETOOLONG;
14787 
14788 	if (vp->v_flag & VROOT)
14789 		nfs_rw_exit(&svp->sv_lock);
14790 	else
14791 		kmem_free(fn, MAXNAMELEN);
14792 
14793 	return (err);
14794 }
14795 
14796 /*
14797  * Bookkeeping for a close that doesn't need to go over the wire.
14798  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14799  * it is left at 1.
14800  */
14801 void
14802 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14803 {
14804 	rnode4_t		*rp;
14805 	mntinfo4_t		*mi;
14806 
14807 	mi = VTOMI4(vp);
14808 	rp = VTOR4(vp);
14809 
14810 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14811 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14812 	ASSERT(nfs_zone() == mi->mi_zone);
14813 	ASSERT(mutex_owned(&osp->os_sync_lock));
14814 	ASSERT(*have_lockp);
14815 
14816 	if (!osp->os_valid ||
14817 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14818 		return;
14819 	}
14820 
14821 	/*
14822 	 * This removes the reference obtained at OPEN; ie,
14823 	 * when the open stream structure was created.
14824 	 *
14825 	 * We don't have to worry about calling 'open_stream_rele'
14826 	 * since we our currently holding a reference to this
14827 	 * open stream which means the count can not go to 0 with
14828 	 * this decrement.
14829 	 */
14830 	ASSERT(osp->os_ref_count >= 2);
14831 	osp->os_ref_count--;
14832 	osp->os_valid = 0;
14833 	mutex_exit(&osp->os_sync_lock);
14834 	*have_lockp = 0;
14835 
14836 	nfs4_dec_state_ref_count(mi);
14837 }
14838 
14839 /*
14840  * Close all remaining open streams on the rnode.  These open streams
14841  * could be here because:
14842  * - The close attempted at either close or delmap failed
14843  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
14844  * - Someone did mknod on a regular file but never opened it
14845  */
14846 int
14847 nfs4close_all(vnode_t *vp, cred_t *cr)
14848 {
14849 	nfs4_open_stream_t *osp;
14850 	int error;
14851 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
14852 	rnode4_t *rp;
14853 
14854 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14855 
14856 	error = 0;
14857 	rp = VTOR4(vp);
14858 
14859 	/*
14860 	 * At this point, all we know is that the last time
14861 	 * someone called vn_rele, the count was 1.  Since then,
14862 	 * the vnode could have been re-activated.  We want to
14863 	 * loop through the open streams and close each one, but
14864 	 * we have to be careful since once we release the rnode
14865 	 * hash bucket lock, someone else is free to come in and
14866 	 * re-activate the rnode and add new open streams.  The
14867 	 * strategy is take the rnode hash bucket lock, verify that
14868 	 * the count is still 1, grab the open stream off the
14869 	 * head of the list and mark it invalid, then release the
14870 	 * rnode hash bucket lock and proceed with that open stream.
14871 	 * This is ok because nfs4close_one() will acquire the proper
14872 	 * open/create to close/destroy synchronization for open
14873 	 * streams, and will ensure that if someone has reopened
14874 	 * the open stream after we've dropped the hash bucket lock
14875 	 * then we'll just simply return without destroying the
14876 	 * open stream.
14877 	 * Repeat until the list is empty.
14878 	 */
14879 
14880 	for (;;) {
14881 
14882 		/* make sure vnode hasn't been reactivated */
14883 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
14884 		mutex_enter(&vp->v_lock);
14885 		if (vp->v_count > 1) {
14886 			mutex_exit(&vp->v_lock);
14887 			rw_exit(&rp->r_hashq->r_lock);
14888 			break;
14889 		}
14890 		/*
14891 		 * Grabbing r_os_lock before releasing v_lock prevents
14892 		 * a window where the rnode/open stream could get
14893 		 * reactivated (and os_force_close set to 0) before we
14894 		 * had a chance to set os_force_close to 1.
14895 		 */
14896 		mutex_enter(&rp->r_os_lock);
14897 		mutex_exit(&vp->v_lock);
14898 
14899 		osp = list_head(&rp->r_open_streams);
14900 		if (!osp) {
14901 			/* nothing left to CLOSE OTW, so return */
14902 			mutex_exit(&rp->r_os_lock);
14903 			rw_exit(&rp->r_hashq->r_lock);
14904 			break;
14905 		}
14906 
14907 		mutex_enter(&rp->r_statev4_lock);
14908 		/* the file can't still be mem mapped */
14909 		ASSERT(rp->r_mapcnt == 0);
14910 		if (rp->created_v4)
14911 			rp->created_v4 = 0;
14912 		mutex_exit(&rp->r_statev4_lock);
14913 
14914 		/*
14915 		 * Grab a ref on this open stream; nfs4close_one
14916 		 * will mark it as invalid
14917 		 */
14918 		mutex_enter(&osp->os_sync_lock);
14919 		osp->os_ref_count++;
14920 		osp->os_force_close = 1;
14921 		mutex_exit(&osp->os_sync_lock);
14922 		mutex_exit(&rp->r_os_lock);
14923 		rw_exit(&rp->r_hashq->r_lock);
14924 
14925 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
14926 
14927 		/* Update error if it isn't already non-zero */
14928 		if (error == 0) {
14929 			if (e.error)
14930 				error = e.error;
14931 			else if (e.stat)
14932 				error = geterrno4(e.stat);
14933 		}
14934 
14935 #ifdef	DEBUG
14936 		nfs4close_all_cnt++;
14937 #endif
14938 		/* Release the ref on osp acquired above. */
14939 		open_stream_rele(osp, rp);
14940 
14941 		/* Proceed to the next open stream, if any */
14942 	}
14943 	return (error);
14944 }
14945 
14946 /*
14947  * nfs4close_one - close one open stream for a file if needed.
14948  *
14949  * "close_type" indicates which close path this is:
14950  * CLOSE_NORM: close initiated via VOP_CLOSE.
14951  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
14952  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
14953  *	the close and release of client state for this open stream
14954  *	(unless someone else has the open stream open).
14955  * CLOSE_RESEND: indicates the request is a replay of an earlier request
14956  *	(e.g., due to abort because of a signal).
14957  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
14958  *
14959  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
14960  * recovery.  Instead, the caller is expected to deal with retries.
14961  *
14962  * The caller can either pass in the osp ('provided_osp') or not.
14963  *
14964  * 'access_bits' represents the access we are closing/downgrading.
14965  *
14966  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
14967  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
14968  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
14969  *
14970  * Errors are returned via the nfs4_error_t.
14971  */
14972 void
14973 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
14974     int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
14975     nfs4_close_type_t close_type, size_t len, uint_t maxprot,
14976     uint_t mmap_flags)
14977 {
14978 	nfs4_open_owner_t *oop;
14979 	nfs4_open_stream_t *osp = NULL;
14980 	int retry = 0;
14981 	int num_retries = NFS4_NUM_RECOV_RETRIES;
14982 	rnode4_t *rp;
14983 	mntinfo4_t *mi;
14984 	nfs4_recov_state_t recov_state;
14985 	cred_t *cred_otw = NULL;
14986 	bool_t recovonly = FALSE;
14987 	int isrecov;
14988 	int force_close;
14989 	int close_failed = 0;
14990 	int did_dec_count = 0;
14991 	int did_start_op = 0;
14992 	int did_force_recovlock = 0;
14993 	int did_start_seqid_sync = 0;
14994 	int have_sync_lock = 0;
14995 
14996 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14997 
14998 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
14999 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
15000 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
15001 	    len, maxprot, mmap_flags, access_bits));
15002 
15003 	nfs4_error_zinit(ep);
15004 	rp = VTOR4(vp);
15005 	mi = VTOMI4(vp);
15006 	isrecov = (close_type == CLOSE_RESEND ||
15007 	    close_type == CLOSE_AFTER_RESEND);
15008 
15009 	/*
15010 	 * First get the open owner.
15011 	 */
15012 	if (!provided_osp) {
15013 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
15014 	} else {
15015 		oop = provided_osp->os_open_owner;
15016 		ASSERT(oop != NULL);
15017 		open_owner_hold(oop);
15018 	}
15019 
15020 	if (!oop) {
15021 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15022 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15023 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15024 		    (void *)provided_osp, close_type));
15025 		ep->error = EIO;
15026 		goto out;
15027 	}
15028 
15029 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15030 recov_retry:
15031 	osp = NULL;
15032 	close_failed = 0;
15033 	force_close = (close_type == CLOSE_FORCE);
15034 	retry = 0;
15035 	did_start_op = 0;
15036 	did_force_recovlock = 0;
15037 	did_start_seqid_sync = 0;
15038 	have_sync_lock = 0;
15039 	recovonly = FALSE;
15040 	recov_state.rs_flags = 0;
15041 	recov_state.rs_num_retry_despite_err = 0;
15042 
15043 	/*
15044 	 * Second synchronize with recovery.
15045 	 */
15046 	if (!isrecov) {
15047 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15048 		    &recov_state, &recovonly);
15049 		if (!ep->error) {
15050 			did_start_op = 1;
15051 		} else {
15052 			close_failed = 1;
15053 			/*
15054 			 * If we couldn't get start_fop, but have to
15055 			 * cleanup state, then at least acquire the
15056 			 * mi_recovlock so we can synchronize with
15057 			 * recovery.
15058 			 */
15059 			if (close_type == CLOSE_FORCE) {
15060 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15061 				    RW_READER, FALSE);
15062 				did_force_recovlock = 1;
15063 			} else
15064 				goto out;
15065 		}
15066 	}
15067 
15068 	/*
15069 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15070 	 * set 'recovonly' to TRUE since most likely this is due to
15071 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15072 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15073 	 * to retry, causing us to loop until recovery finishes.  Plus we
15074 	 * don't need protection over the open seqid since we're not going
15075 	 * OTW, hence don't need to use the seqid.
15076 	 */
15077 	if (recovonly == FALSE) {
15078 		/* need to grab the open owner sync before 'os_sync_lock' */
15079 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15080 		if (ep->error == EAGAIN) {
15081 			ASSERT(!isrecov);
15082 			if (did_start_op)
15083 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15084 				    &recov_state, TRUE);
15085 			if (did_force_recovlock)
15086 				nfs_rw_exit(&mi->mi_recovlock);
15087 			goto recov_retry;
15088 		}
15089 		did_start_seqid_sync = 1;
15090 	}
15091 
15092 	/*
15093 	 * Third get an open stream and acquire 'os_sync_lock' to
15094 	 * sychronize the opening/creating of an open stream with the
15095 	 * closing/destroying of an open stream.
15096 	 */
15097 	if (!provided_osp) {
15098 		/* returns with 'os_sync_lock' held */
15099 		osp = find_open_stream(oop, rp);
15100 		if (!osp) {
15101 			ep->error = EIO;
15102 			goto out;
15103 		}
15104 	} else {
15105 		osp = provided_osp;
15106 		open_stream_hold(osp);
15107 		mutex_enter(&osp->os_sync_lock);
15108 	}
15109 	have_sync_lock = 1;
15110 
15111 	ASSERT(oop == osp->os_open_owner);
15112 
15113 	/*
15114 	 * Fourth, do any special pre-OTW CLOSE processing
15115 	 * based on the specific close type.
15116 	 */
15117 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15118 	    !did_dec_count) {
15119 		ASSERT(osp->os_open_ref_count > 0);
15120 		osp->os_open_ref_count--;
15121 		did_dec_count = 1;
15122 		if (osp->os_open_ref_count == 0)
15123 			osp->os_final_close = 1;
15124 	}
15125 
15126 	if (close_type == CLOSE_FORCE) {
15127 		/* see if somebody reopened the open stream. */
15128 		if (!osp->os_force_close) {
15129 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15130 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15131 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15132 			ep->error = 0;
15133 			ep->stat = NFS4_OK;
15134 			goto out;
15135 		}
15136 
15137 		if (!osp->os_final_close && !did_dec_count) {
15138 			osp->os_open_ref_count--;
15139 			did_dec_count = 1;
15140 		}
15141 
15142 		/*
15143 		 * We can't depend on os_open_ref_count being 0 due to the
15144 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15145 		 */
15146 #ifdef	NOTYET
15147 		ASSERT(osp->os_open_ref_count == 0);
15148 #endif
15149 		if (osp->os_open_ref_count != 0) {
15150 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15151 			    "nfs4close_one: should panic here on an "
15152 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15153 			    "since this is probably the exec problem."));
15154 
15155 			osp->os_open_ref_count = 0;
15156 		}
15157 
15158 		/*
15159 		 * There is the possibility that nfs4close_one()
15160 		 * for close_type == CLOSE_DELMAP couldn't find the
15161 		 * open stream, thus couldn't decrement its os_mapcnt;
15162 		 * therefore we can't use this ASSERT yet.
15163 		 */
15164 #ifdef	NOTYET
15165 		ASSERT(osp->os_mapcnt == 0);
15166 #endif
15167 		osp->os_mapcnt = 0;
15168 	}
15169 
15170 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15171 		ASSERT(osp->os_mapcnt >= btopr(len));
15172 
15173 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15174 			osp->os_mmap_write -= btopr(len);
15175 		if (maxprot & PROT_READ)
15176 			osp->os_mmap_read -= btopr(len);
15177 		if (maxprot & PROT_EXEC)
15178 			osp->os_mmap_read -= btopr(len);
15179 		/* mirror the PROT_NONE check in nfs4_addmap() */
15180 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15181 		    !(maxprot & PROT_EXEC))
15182 			osp->os_mmap_read -= btopr(len);
15183 		osp->os_mapcnt -= btopr(len);
15184 		did_dec_count = 1;
15185 	}
15186 
15187 	if (recovonly) {
15188 		nfs4_lost_rqst_t lost_rqst;
15189 
15190 		/* request should not already be in recovery queue */
15191 		ASSERT(lrp == NULL);
15192 		nfs4_error_init(ep, EINTR);
15193 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15194 		    osp, cred_otw, vp);
15195 		mutex_exit(&osp->os_sync_lock);
15196 		have_sync_lock = 0;
15197 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15198 		    lost_rqst.lr_op == OP_CLOSE ?
15199 		    &lost_rqst : NULL, OP_CLOSE, NULL);
15200 		close_failed = 1;
15201 		force_close = 0;
15202 		goto close_cleanup;
15203 	}
15204 
15205 	/*
15206 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15207 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15208 	 * space, which means we stopped operating on the open stream
15209 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15210 	 * stateid could be stale, potentially triggering a false
15211 	 * setclientid), and just clean up the client's internal state.
15212 	 */
15213 	if (osp->os_orig_oo_name != oop->oo_name) {
15214 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15215 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15216 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15217 		    "oo_name %" PRIx64")",
15218 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15219 		    oop->oo_name));
15220 		close_failed = 1;
15221 	}
15222 
15223 	/* If the file failed recovery, just quit. */
15224 	mutex_enter(&rp->r_statelock);
15225 	if (rp->r_flags & R4RECOVERR) {
15226 		close_failed = 1;
15227 	}
15228 	mutex_exit(&rp->r_statelock);
15229 
15230 	/*
15231 	 * If the force close path failed to obtain start_fop
15232 	 * then skip the OTW close and just remove the state.
15233 	 */
15234 	if (close_failed)
15235 		goto close_cleanup;
15236 
15237 	/*
15238 	 * Fifth, check to see if there are still mapped pages or other
15239 	 * opens using this open stream.  If there are then we can't
15240 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15241 	 */
15242 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15243 		nfs4_lost_rqst_t	new_lost_rqst;
15244 		bool_t			needrecov = FALSE;
15245 		cred_t			*odg_cred_otw = NULL;
15246 		seqid4			open_dg_seqid = 0;
15247 
15248 		if (osp->os_delegation) {
15249 			/*
15250 			 * If this open stream was never OPENed OTW then we
15251 			 * surely can't DOWNGRADE it (especially since the
15252 			 * osp->open_stateid is really a delegation stateid
15253 			 * when os_delegation is 1).
15254 			 */
15255 			if (access_bits & FREAD)
15256 				osp->os_share_acc_read--;
15257 			if (access_bits & FWRITE)
15258 				osp->os_share_acc_write--;
15259 			osp->os_share_deny_none--;
15260 			nfs4_error_zinit(ep);
15261 			goto out;
15262 		}
15263 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15264 		    lrp, ep, &odg_cred_otw, &open_dg_seqid);
15265 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15266 		if (needrecov && !isrecov) {
15267 			bool_t abort;
15268 			nfs4_bseqid_entry_t *bsep = NULL;
15269 
15270 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15271 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15272 				    vp, 0,
15273 				    lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15274 				    open_dg_seqid);
15275 
15276 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15277 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15278 			mutex_exit(&osp->os_sync_lock);
15279 			have_sync_lock = 0;
15280 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15281 			    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15282 			    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15283 			    bsep);
15284 			if (odg_cred_otw)
15285 				crfree(odg_cred_otw);
15286 			if (bsep)
15287 				kmem_free(bsep, sizeof (*bsep));
15288 
15289 			if (abort == TRUE)
15290 				goto out;
15291 
15292 			if (did_start_seqid_sync) {
15293 				nfs4_end_open_seqid_sync(oop);
15294 				did_start_seqid_sync = 0;
15295 			}
15296 			open_stream_rele(osp, rp);
15297 
15298 			if (did_start_op)
15299 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15300 				    &recov_state, FALSE);
15301 			if (did_force_recovlock)
15302 				nfs_rw_exit(&mi->mi_recovlock);
15303 
15304 			goto recov_retry;
15305 		} else {
15306 			if (odg_cred_otw)
15307 				crfree(odg_cred_otw);
15308 		}
15309 		goto out;
15310 	}
15311 
15312 	/*
15313 	 * If this open stream was created as the results of an open
15314 	 * while holding a delegation, then just release it; no need
15315 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15316 	 */
15317 	if (osp->os_delegation) {
15318 		nfs4close_notw(vp, osp, &have_sync_lock);
15319 		nfs4_error_zinit(ep);
15320 		goto out;
15321 	}
15322 
15323 	/*
15324 	 * If this stream is not valid, we're done.
15325 	 */
15326 	if (!osp->os_valid) {
15327 		nfs4_error_zinit(ep);
15328 		goto out;
15329 	}
15330 
15331 	/*
15332 	 * Last open or mmap ref has vanished, need to do an OTW close.
15333 	 * First check to see if a close is still necessary.
15334 	 */
15335 	if (osp->os_failed_reopen) {
15336 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15337 		    "don't close OTW osp %p since reopen failed.",
15338 		    (void *)osp));
15339 		/*
15340 		 * Reopen of the open stream failed, hence the
15341 		 * stateid of the open stream is invalid/stale, and
15342 		 * sending this OTW would incorrectly cause another
15343 		 * round of recovery.  In this case, we need to set
15344 		 * the 'os_valid' bit to 0 so another thread doesn't
15345 		 * come in and re-open this open stream before
15346 		 * this "closing" thread cleans up state (decrementing
15347 		 * the nfs4_server_t's state_ref_count and decrementing
15348 		 * the os_ref_count).
15349 		 */
15350 		osp->os_valid = 0;
15351 		/*
15352 		 * This removes the reference obtained at OPEN; ie,
15353 		 * when the open stream structure was created.
15354 		 *
15355 		 * We don't have to worry about calling 'open_stream_rele'
15356 		 * since we our currently holding a reference to this
15357 		 * open stream which means the count can not go to 0 with
15358 		 * this decrement.
15359 		 */
15360 		ASSERT(osp->os_ref_count >= 2);
15361 		osp->os_ref_count--;
15362 		nfs4_error_zinit(ep);
15363 		close_failed = 0;
15364 		goto close_cleanup;
15365 	}
15366 
15367 	ASSERT(osp->os_ref_count > 1);
15368 
15369 	/*
15370 	 * Sixth, try the CLOSE OTW.
15371 	 */
15372 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15373 	    close_type, ep, &have_sync_lock);
15374 
15375 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15376 		/*
15377 		 * Let the recovery thread be responsible for
15378 		 * removing the state for CLOSE.
15379 		 */
15380 		close_failed = 1;
15381 		force_close = 0;
15382 		retry = 0;
15383 	}
15384 
15385 	/* See if we need to retry with a different cred */
15386 	if ((ep->error == EACCES ||
15387 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15388 	    cred_otw != cr) {
15389 		crfree(cred_otw);
15390 		cred_otw = cr;
15391 		crhold(cred_otw);
15392 		retry = 1;
15393 	}
15394 
15395 	if (ep->error || ep->stat)
15396 		close_failed = 1;
15397 
15398 	if (retry && !isrecov && num_retries-- > 0) {
15399 		if (have_sync_lock) {
15400 			mutex_exit(&osp->os_sync_lock);
15401 			have_sync_lock = 0;
15402 		}
15403 		if (did_start_seqid_sync) {
15404 			nfs4_end_open_seqid_sync(oop);
15405 			did_start_seqid_sync = 0;
15406 		}
15407 		open_stream_rele(osp, rp);
15408 
15409 		if (did_start_op)
15410 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15411 			    &recov_state, FALSE);
15412 		if (did_force_recovlock)
15413 			nfs_rw_exit(&mi->mi_recovlock);
15414 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15415 		    "nfs4close_one: need to retry the close "
15416 		    "operation"));
15417 		goto recov_retry;
15418 	}
15419 close_cleanup:
15420 	/*
15421 	 * Seventh and lastly, process our results.
15422 	 */
15423 	if (close_failed && force_close) {
15424 		/*
15425 		 * It's ok to drop and regrab the 'os_sync_lock' since
15426 		 * nfs4close_notw() will recheck to make sure the
15427 		 * "close"/removal of state should happen.
15428 		 */
15429 		if (!have_sync_lock) {
15430 			mutex_enter(&osp->os_sync_lock);
15431 			have_sync_lock = 1;
15432 		}
15433 		/*
15434 		 * This is last call, remove the ref on the open
15435 		 * stream created by open and clean everything up.
15436 		 */
15437 		osp->os_pending_close = 0;
15438 		nfs4close_notw(vp, osp, &have_sync_lock);
15439 		nfs4_error_zinit(ep);
15440 	}
15441 
15442 	if (!close_failed) {
15443 		if (have_sync_lock) {
15444 			osp->os_pending_close = 0;
15445 			mutex_exit(&osp->os_sync_lock);
15446 			have_sync_lock = 0;
15447 		} else {
15448 			mutex_enter(&osp->os_sync_lock);
15449 			osp->os_pending_close = 0;
15450 			mutex_exit(&osp->os_sync_lock);
15451 		}
15452 		if (did_start_op && recov_state.rs_sp != NULL) {
15453 			mutex_enter(&recov_state.rs_sp->s_lock);
15454 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15455 			mutex_exit(&recov_state.rs_sp->s_lock);
15456 		} else {
15457 			nfs4_dec_state_ref_count(mi);
15458 		}
15459 		nfs4_error_zinit(ep);
15460 	}
15461 
15462 out:
15463 	if (have_sync_lock)
15464 		mutex_exit(&osp->os_sync_lock);
15465 	if (did_start_op)
15466 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15467 		    recovonly ? TRUE : FALSE);
15468 	if (did_force_recovlock)
15469 		nfs_rw_exit(&mi->mi_recovlock);
15470 	if (cred_otw)
15471 		crfree(cred_otw);
15472 	if (osp)
15473 		open_stream_rele(osp, rp);
15474 	if (oop) {
15475 		if (did_start_seqid_sync)
15476 			nfs4_end_open_seqid_sync(oop);
15477 		open_owner_rele(oop);
15478 	}
15479 }
15480 
15481 /*
15482  * Convert information returned by the server in the LOCK4denied
15483  * structure to the form required by fcntl.
15484  */
15485 static void
15486 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15487 {
15488 	nfs4_lo_name_t *lo;
15489 
15490 #ifdef	DEBUG
15491 	if (denied_to_flk_debug) {
15492 		lockt_denied_debug = lockt_denied;
15493 		debug_enter("lockt_denied");
15494 	}
15495 #endif
15496 
15497 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15498 	flk->l_whence = 0;	/* aka SEEK_SET */
15499 	flk->l_start = lockt_denied->offset;
15500 	flk->l_len = lockt_denied->length;
15501 
15502 	/*
15503 	 * If the blocking clientid matches our client id, then we can
15504 	 * interpret the lockowner (since we built it).  If not, then
15505 	 * fabricate a sysid and pid.  Note that the l_sysid field
15506 	 * in *flk already has the local sysid.
15507 	 */
15508 
15509 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15510 
15511 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15512 			lo = (nfs4_lo_name_t *)
15513 			    lockt_denied->owner.owner_val;
15514 
15515 			flk->l_pid = lo->ln_pid;
15516 		} else {
15517 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15518 			    "denied_to_flk: bad lock owner length\n"));
15519 
15520 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15521 		}
15522 	} else {
15523 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15524 		"denied_to_flk: foreign clientid\n"));
15525 
15526 		/*
15527 		 * Construct a new sysid which should be different from
15528 		 * sysids of other systems.
15529 		 */
15530 
15531 		flk->l_sysid++;
15532 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15533 	}
15534 }
15535 
15536 static pid_t
15537 lo_to_pid(lock_owner4 *lop)
15538 {
15539 	pid_t pid = 0;
15540 	uchar_t *cp;
15541 	int i;
15542 
15543 	cp = (uchar_t *)&lop->clientid;
15544 
15545 	for (i = 0; i < sizeof (lop->clientid); i++)
15546 		pid += (pid_t)*cp++;
15547 
15548 	cp = (uchar_t *)lop->owner_val;
15549 
15550 	for (i = 0; i < lop->owner_len; i++)
15551 		pid += (pid_t)*cp++;
15552 
15553 	return (pid);
15554 }
15555 
15556 /*
15557  * Given a lock pointer, returns the length of that lock.
15558  * "end" is the last locked offset the "l_len" covers from
15559  * the start of the lock.
15560  */
15561 static off64_t
15562 lock_to_end(flock64_t *lock)
15563 {
15564 	off64_t lock_end;
15565 
15566 	if (lock->l_len == 0)
15567 		lock_end = (off64_t)MAXEND;
15568 	else
15569 		lock_end = lock->l_start + lock->l_len - 1;
15570 
15571 	return (lock_end);
15572 }
15573 
15574 /*
15575  * Given the end of a lock, it will return you the length "l_len" for that lock.
15576  */
15577 static off64_t
15578 end_to_len(off64_t start, off64_t end)
15579 {
15580 	off64_t lock_len;
15581 
15582 	ASSERT(end >= start);
15583 	if (end == MAXEND)
15584 		lock_len = 0;
15585 	else
15586 		lock_len = end - start + 1;
15587 
15588 	return (lock_len);
15589 }
15590 
15591 /*
15592  * On given end for a lock it determines if it is the last locked offset
15593  * or not, if so keeps it as is, else adds one to return the length for
15594  * valid start.
15595  */
15596 static off64_t
15597 start_check(off64_t x)
15598 {
15599 	if (x == MAXEND)
15600 		return (x);
15601 	else
15602 		return (x + 1);
15603 }
15604 
15605 /*
15606  * See if these two locks overlap, and if so return 1;
15607  * otherwise, return 0.
15608  */
15609 static int
15610 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15611 {
15612 	off64_t llfp_end, curfp_end;
15613 
15614 	llfp_end = lock_to_end(llfp);
15615 	curfp_end = lock_to_end(curfp);
15616 
15617 	if (((llfp_end >= curfp->l_start) &&
15618 	    (llfp->l_start <= curfp->l_start)) ||
15619 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15620 		return (1);
15621 	return (0);
15622 }
15623 
15624 /*
15625  * Determine what the intersecting lock region is, and add that to the
15626  * 'nl_llpp' locklist in increasing order (by l_start).
15627  */
15628 static void
15629 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15630     locklist_t **nl_llpp, vnode_t *vp)
15631 {
15632 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15633 	off64_t lost_flp_end, local_flp_end, len, start;
15634 
15635 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15636 
15637 	if (!locks_intersect(lost_flp, local_flp))
15638 		return;
15639 
15640 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15641 	    "locks intersect"));
15642 
15643 	lost_flp_end = lock_to_end(lost_flp);
15644 	local_flp_end = lock_to_end(local_flp);
15645 
15646 	/* Find the starting point of the intersecting region */
15647 	if (local_flp->l_start > lost_flp->l_start)
15648 		start = local_flp->l_start;
15649 	else
15650 		start = lost_flp->l_start;
15651 
15652 	/* Find the lenght of the intersecting region */
15653 	if (lost_flp_end < local_flp_end)
15654 		len = end_to_len(start, lost_flp_end);
15655 	else
15656 		len = end_to_len(start, local_flp_end);
15657 
15658 	/*
15659 	 * Prepare the flock structure for the intersection found and insert
15660 	 * it into the new list in increasing l_start order. This list contains
15661 	 * intersections of locks registered by the client with the local host
15662 	 * and the lost lock.
15663 	 * The lock type of this lock is the same as that of the local_flp.
15664 	 */
15665 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15666 	intersect_llp->ll_flock.l_start = start;
15667 	intersect_llp->ll_flock.l_len = len;
15668 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15669 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15670 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15671 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15672 	intersect_llp->ll_vp = vp;
15673 
15674 	tmp_fllp = *nl_llpp;
15675 	cur_fllp = NULL;
15676 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15677 	    intersect_llp->ll_flock.l_start) {
15678 			cur_fllp = tmp_fllp;
15679 			tmp_fllp = tmp_fllp->ll_next;
15680 	}
15681 	if (cur_fllp == NULL) {
15682 		/* first on the list */
15683 		intersect_llp->ll_next = *nl_llpp;
15684 		*nl_llpp = intersect_llp;
15685 	} else {
15686 		intersect_llp->ll_next = cur_fllp->ll_next;
15687 		cur_fllp->ll_next = intersect_llp;
15688 	}
15689 
15690 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15691 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15692 	    intersect_llp->ll_flock.l_start,
15693 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15694 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15695 }
15696 
15697 /*
15698  * Our local locking current state is potentially different than
15699  * what the NFSv4 server thinks we have due to a lost lock that was
15700  * resent and then received.  We need to reset our "NFSv4" locking
15701  * state to match the current local locking state for this pid since
15702  * that is what the user/application sees as what the world is.
15703  *
15704  * We cannot afford to drop the open/lock seqid sync since then we can
15705  * get confused about what the current local locking state "is" versus
15706  * "was".
15707  *
15708  * If we are unable to fix up the locks, we send SIGLOST to the affected
15709  * process.  This is not done if the filesystem has been forcibly
15710  * unmounted, in case the process has already exited and a new process
15711  * exists with the same pid.
15712  */
15713 static void
15714 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15715     nfs4_lock_owner_t *lop)
15716 {
15717 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15718 	mntinfo4_t *mi = VTOMI4(vp);
15719 	const int cmd = F_SETLK;
15720 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15721 	flock64_t ul_fl;
15722 
15723 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15724 	    "nfs4_reinstitute_local_lock_state"));
15725 
15726 	/*
15727 	 * Find active locks for this vp from the local locking code.
15728 	 * Scan through this list and find out the locks that intersect with
15729 	 * the lost lock. Once we find the lock that intersects, add the
15730 	 * intersection area as a new lock to a new list "ri_llp". The lock
15731 	 * type of the intersection region lock added to ri_llp is the same
15732 	 * as that found in the active lock list, "list". The intersecting
15733 	 * region locks are added to ri_llp in increasing l_start order.
15734 	 */
15735 	ASSERT(nfs_zone() == mi->mi_zone);
15736 
15737 	locks = flk_active_locks_for_vp(vp);
15738 	ri_llp = NULL;
15739 
15740 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15741 		ASSERT(llp->ll_vp == vp);
15742 		/*
15743 		 * Pick locks that belong to this pid/lockowner
15744 		 */
15745 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15746 			continue;
15747 
15748 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15749 	}
15750 
15751 	/*
15752 	 * Now we have the list of intersections with the lost lock. These are
15753 	 * the locks that were/are active before the server replied to the
15754 	 * last/lost lock. Issue these locks to the server here. Playing these
15755 	 * locks to the server will re-establish aur current local locking state
15756 	 * with the v4 server.
15757 	 * If we get an error, send SIGLOST to the application for that lock.
15758 	 */
15759 
15760 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15761 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15762 		    "nfs4_reinstitute_local_lock_state: need to issue "
15763 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15764 		    llp->ll_flock.l_start,
15765 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15766 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15767 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15768 		/*
15769 		 * No need to relock what we already have
15770 		 */
15771 		if (llp->ll_flock.l_type == lost_flp->l_type)
15772 			continue;
15773 
15774 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15775 	}
15776 
15777 	/*
15778 	 * Now keeping the start of the lost lock as our reference parse the
15779 	 * newly created ri_llp locklist to find the ranges that we have locked
15780 	 * with the v4 server but not in the current local locking. We need
15781 	 * to unlock these ranges.
15782 	 * These ranges can also be reffered to as those ranges, where the lost
15783 	 * lock does not overlap with the locks in the ri_llp but are locked
15784 	 * since the server replied to the lost lock.
15785 	 */
15786 	cur_start = lost_flp->l_start;
15787 	lost_flp_end = lock_to_end(lost_flp);
15788 
15789 	ul_fl.l_type = F_UNLCK;
15790 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15791 	ul_fl.l_sysid = lost_flp->l_sysid;
15792 	ul_fl.l_pid = lost_flp->l_pid;
15793 
15794 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15795 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15796 
15797 		if (llp->ll_flock.l_start <= cur_start) {
15798 			cur_start = start_check(llp_ll_flock_end);
15799 			continue;
15800 		}
15801 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15802 		    "nfs4_reinstitute_local_lock_state: "
15803 		    "UNLOCK [%"PRIx64" - %"PRIx64"]",
15804 		    cur_start, llp->ll_flock.l_start));
15805 
15806 		ul_fl.l_start = cur_start;
15807 		ul_fl.l_len = end_to_len(cur_start,
15808 		    (llp->ll_flock.l_start - 1));
15809 
15810 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15811 		cur_start = start_check(llp_ll_flock_end);
15812 	}
15813 
15814 	/*
15815 	 * In the case where the lost lock ends after all intersecting locks,
15816 	 * unlock the last part of the lost lock range.
15817 	 */
15818 	if (cur_start != start_check(lost_flp_end)) {
15819 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15820 		    "nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15821 		    "lost lock region [%"PRIx64" - %"PRIx64"]",
15822 		    cur_start, lost_flp->l_start + lost_flp->l_len));
15823 
15824 		ul_fl.l_start = cur_start;
15825 		/*
15826 		 * Is it an to-EOF lock? if so unlock till the end
15827 		 */
15828 		if (lost_flp->l_len == 0)
15829 			ul_fl.l_len = 0;
15830 		else
15831 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15832 
15833 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15834 	}
15835 
15836 	if (locks != NULL)
15837 		flk_free_locklist(locks);
15838 
15839 	/* Free up our newly created locklist */
15840 	for (llp = ri_llp; llp != NULL; ) {
15841 		tmp_llp = llp->ll_next;
15842 		kmem_free(llp, sizeof (locklist_t));
15843 		llp = tmp_llp;
15844 	}
15845 
15846 	/*
15847 	 * Now return back to the original calling nfs4frlock()
15848 	 * and let us naturally drop our seqid syncs.
15849 	 */
15850 }
15851 
15852 /*
15853  * Create a lost state record for the given lock reinstantiation request
15854  * and push it onto the lost state queue.
15855  */
15856 static void
15857 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
15858     nfs4_lock_owner_t *lop)
15859 {
15860 	nfs4_lost_rqst_t req;
15861 	nfs_lock_type4 locktype;
15862 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
15863 
15864 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15865 
15866 	locktype = flk_to_locktype(cmd, flk->l_type);
15867 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
15868 	    NULL, NULL, lop, flk, &req, cr, vp);
15869 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
15870 	    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
15871 	    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
15872 	    NULL);
15873 }
15874