xref: /titanic_52/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision 1c2187e7a735b31a46941879f0bd124e0aa325a3)
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 struct lm_sysid *nfs4_find_sysid(mntinfo4_t *mi);
107 
108 static void	nfs4_update_dircaches(change_info4 *, vnode_t *, vnode_t *,
109 			char *, dirattr_info_t *);
110 
111 static void	nfs4close_otw(rnode4_t *, cred_t *, nfs4_open_owner_t *,
112 		    nfs4_open_stream_t *, int *, int *, nfs4_close_type_t,
113 		    nfs4_error_t *, int *);
114 static int	nfs4_rdwrlbn(vnode_t *, page_t *, u_offset_t, size_t, int,
115 			cred_t *);
116 static int	nfs4write(vnode_t *, caddr_t, u_offset_t, int, cred_t *,
117 			stable_how4 *);
118 static int	nfs4read(vnode_t *, caddr_t, offset_t, int, size_t *,
119 			cred_t *, bool_t, struct uio *);
120 static int	nfs4setattr(vnode_t *, struct vattr *, int, cred_t *,
121 			vsecattr_t *);
122 static int	nfs4openattr(vnode_t *, vnode_t **, int, cred_t *);
123 static int	nfs4lookup(vnode_t *, char *, vnode_t **, cred_t *, int);
124 static int	nfs4lookup_xattr(vnode_t *, char *, vnode_t **, int, cred_t *);
125 static int	nfs4lookupvalidate_otw(vnode_t *, char *, vnode_t **, cred_t *);
126 static int	nfs4lookupnew_otw(vnode_t *, char *, vnode_t **, cred_t *);
127 static int	nfs4mknod(vnode_t *, char *, struct vattr *, enum vcexcl,
128 			int, vnode_t **, cred_t *);
129 static int	nfs4open_otw(vnode_t *, char *, struct vattr *, vnode_t **,
130 			cred_t *, int, int, enum createmode4, int);
131 static int	nfs4rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
132 			caller_context_t *);
133 static int	nfs4rename_persistent_fh(vnode_t *, char *, vnode_t *,
134 			vnode_t *, char *, cred_t *, nfsstat4 *);
135 static int	nfs4rename_volatile_fh(vnode_t *, char *, vnode_t *,
136 			vnode_t *, char *, cred_t *, nfsstat4 *);
137 static int	do_nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
138 static void	nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
139 static int	nfs4_bio(struct buf *, stable_how4 *, cred_t *, bool_t);
140 static int	nfs4_getapage(vnode_t *, u_offset_t, size_t, uint_t *,
141 			page_t *[], size_t, struct seg *, caddr_t,
142 			enum seg_rw, cred_t *);
143 static void	nfs4_readahead(vnode_t *, u_offset_t, caddr_t, struct seg *,
144 			cred_t *);
145 static int	nfs4_sync_putapage(vnode_t *, page_t *, u_offset_t, size_t,
146 			int, cred_t *);
147 static int	nfs4_sync_pageio(vnode_t *, page_t *, u_offset_t, size_t,
148 			int, cred_t *);
149 static int	nfs4_commit(vnode_t *, offset4, count4, cred_t *);
150 static void	nfs4_set_mod(vnode_t *);
151 static void	nfs4_get_commit(vnode_t *);
152 static void	nfs4_get_commit_range(vnode_t *, u_offset_t, size_t);
153 static int	nfs4_putpage_commit(vnode_t *, offset_t, size_t, cred_t *);
154 static int	nfs4_commit_vp(vnode_t *, u_offset_t, size_t, cred_t *, int);
155 static int	nfs4_sync_commit(vnode_t *, page_t *, offset3, count3,
156 			cred_t *);
157 static void	do_nfs4_async_commit(vnode_t *, page_t *, offset3, count3,
158 			cred_t *);
159 static int	nfs4_update_attrcache(nfsstat4, nfs4_ga_res_t *,
160 			hrtime_t, vnode_t *, cred_t *);
161 static int	nfs4_open_non_reg_file(vnode_t **, int, cred_t *);
162 static int	nfs4_safelock(vnode_t *, const struct flock64 *, cred_t *);
163 static void	nfs4_register_lock_locally(vnode_t *, struct flock64 *, int,
164 			u_offset_t);
165 static int 	nfs4_lockrelease(vnode_t *, int, offset_t, cred_t *);
166 static int	nfs4_block_and_wait(clock_t *, rnode4_t *);
167 static cred_t  *state_to_cred(nfs4_open_stream_t *);
168 static int	vtoname(vnode_t *, char *, ssize_t);
169 static void	denied_to_flk(LOCK4denied *, flock64_t *, LOCKT4args *);
170 static pid_t	lo_to_pid(lock_owner4 *);
171 static void	nfs4_reinstitute_local_lock_state(vnode_t *, flock64_t *,
172 			cred_t *, nfs4_lock_owner_t *);
173 static void	push_reinstate(vnode_t *, int, flock64_t *, cred_t *,
174 			nfs4_lock_owner_t *);
175 static int 	open_and_get_osp(vnode_t *, cred_t *, nfs4_open_stream_t **);
176 static void	nfs4_delmap_callback(struct as *, void *, uint_t);
177 static void	nfs4_free_delmapcall(nfs4_delmapcall_t *);
178 static nfs4_delmapcall_t	*nfs4_init_delmapcall();
179 static int	nfs4_find_and_delete_delmapcall(rnode4_t *, int *);
180 static int	nfs4_is_acl_mask_valid(uint_t, nfs4_acl_op_t);
181 static int	nfs4_create_getsecattr_return(vsecattr_t *, vsecattr_t *,
182 			uid_t, gid_t, int);
183 
184 /*
185  * Routines that implement the setting of v4 args for the misc. ops
186  */
187 static void	nfs4args_lock_free(nfs_argop4 *);
188 static void	nfs4args_lockt_free(nfs_argop4 *);
189 static void	nfs4args_setattr(nfs_argop4 *, vattr_t *, vsecattr_t *,
190 			int, rnode4_t *, cred_t *, bitmap4, int *,
191 			nfs4_stateid_types_t *);
192 static void	nfs4args_setattr_free(nfs_argop4 *);
193 static int	nfs4args_verify(nfs_argop4 *, vattr_t *, enum nfs_opnum4,
194 			bitmap4);
195 static void	nfs4args_verify_free(nfs_argop4 *);
196 static void	nfs4args_write(nfs_argop4 *, stable_how4, rnode4_t *, cred_t *,
197 			WRITE4args **, nfs4_stateid_types_t *);
198 
199 /*
200  * These are the vnode ops functions that implement the vnode interface to
201  * the networked file system.  See more comments below at nfs4_vnodeops.
202  */
203 static int	nfs4_open(vnode_t **, int, cred_t *, caller_context_t *);
204 static int	nfs4_close(vnode_t *, int, int, offset_t, cred_t *,
205 			caller_context_t *);
206 static int	nfs4_read(vnode_t *, struct uio *, int, cred_t *,
207 			caller_context_t *);
208 static int	nfs4_write(vnode_t *, struct uio *, int, cred_t *,
209 			caller_context_t *);
210 static int	nfs4_ioctl(vnode_t *, int, intptr_t, int, cred_t *, int *,
211 			caller_context_t *);
212 static int	nfs4_setattr(vnode_t *, struct vattr *, int, cred_t *,
213 			caller_context_t *);
214 static int	nfs4_access(vnode_t *, int, int, cred_t *, caller_context_t *);
215 static int	nfs4_readlink(vnode_t *, struct uio *, cred_t *,
216 			caller_context_t *);
217 static int	nfs4_fsync(vnode_t *, int, cred_t *, caller_context_t *);
218 static int	nfs4_create(vnode_t *, char *, struct vattr *, enum vcexcl,
219 			int, vnode_t **, cred_t *, int, caller_context_t *,
220 			vsecattr_t *);
221 static int	nfs4_remove(vnode_t *, char *, cred_t *, caller_context_t *,
222 			int);
223 static int	nfs4_link(vnode_t *, vnode_t *, char *, cred_t *,
224 			caller_context_t *, int);
225 static int	nfs4_rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
226 			caller_context_t *, int);
227 static int	nfs4_mkdir(vnode_t *, char *, struct vattr *, vnode_t **,
228 			cred_t *, caller_context_t *, int, vsecattr_t *);
229 static int	nfs4_rmdir(vnode_t *, char *, vnode_t *, cred_t *,
230 			caller_context_t *, int);
231 static int	nfs4_symlink(vnode_t *, char *, struct vattr *, char *,
232 			cred_t *, caller_context_t *, int);
233 static int	nfs4_readdir(vnode_t *, struct uio *, cred_t *, int *,
234 			caller_context_t *, int);
235 static int	nfs4_seek(vnode_t *, offset_t, offset_t *, caller_context_t *);
236 static int	nfs4_getpage(vnode_t *, offset_t, size_t, uint_t *,
237 			page_t *[], size_t, struct seg *, caddr_t,
238 			enum seg_rw, cred_t *, caller_context_t *);
239 static int	nfs4_putpage(vnode_t *, offset_t, size_t, int, cred_t *,
240 			caller_context_t *);
241 static int	nfs4_map(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_addmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
244 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
245 static int	nfs4_cmp(vnode_t *, vnode_t *, caller_context_t *);
246 static int	nfs4_frlock(vnode_t *, int, struct flock64 *, int, offset_t,
247 			struct flk_callback *, cred_t *, caller_context_t *);
248 static int	nfs4_space(vnode_t *, int, struct flock64 *, int, offset_t,
249 			cred_t *, caller_context_t *);
250 static int	nfs4_delmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
251 			uint_t, uint_t, uint_t, cred_t *, caller_context_t *);
252 static int	nfs4_pageio(vnode_t *, page_t *, u_offset_t, size_t, int,
253 			cred_t *, caller_context_t *);
254 static void	nfs4_dispose(vnode_t *, page_t *, int, int, cred_t *,
255 			caller_context_t *);
256 static int	nfs4_setsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
257 			caller_context_t *);
258 /*
259  * These vnode ops are required to be called from outside this source file,
260  * e.g. by ephemeral mount stub vnode ops, and so may not be declared
261  * as static.
262  */
263 int	nfs4_getattr(vnode_t *, struct vattr *, int, cred_t *,
264 	    caller_context_t *);
265 void	nfs4_inactive(vnode_t *, cred_t *, caller_context_t *);
266 int	nfs4_lookup(vnode_t *, char *, vnode_t **,
267 	    struct pathname *, int, vnode_t *, cred_t *,
268 	    caller_context_t *, int *, pathname_t *);
269 int	nfs4_fid(vnode_t *, fid_t *, caller_context_t *);
270 int	nfs4_rwlock(vnode_t *, int, caller_context_t *);
271 void	nfs4_rwunlock(vnode_t *, int, caller_context_t *);
272 int	nfs4_realvp(vnode_t *, vnode_t **, caller_context_t *);
273 int	nfs4_pathconf(vnode_t *, int, ulong_t *, cred_t *,
274 	    caller_context_t *);
275 int	nfs4_getsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
276 	    caller_context_t *);
277 int	nfs4_shrlock(vnode_t *, int, struct shrlock *, int, cred_t *,
278 	    caller_context_t *);
279 
280 /*
281  * Used for nfs4_commit_vp() to indicate if we should
282  * wait on pending writes.
283  */
284 #define	NFS4_WRITE_NOWAIT	0
285 #define	NFS4_WRITE_WAIT		1
286 
287 #define	NFS4_BASE_WAIT_TIME 1	/* 1 second */
288 
289 /*
290  * Error flags used to pass information about certain special errors
291  * which need to be handled specially.
292  */
293 #define	NFS_EOF			-98
294 #define	NFS_VERF_MISMATCH	-97
295 
296 /*
297  * Flags used to differentiate between which operation drove the
298  * potential CLOSE OTW. (see nfs4_close_otw_if_necessary)
299  */
300 #define	NFS4_CLOSE_OP		0x1
301 #define	NFS4_DELMAP_OP		0x2
302 #define	NFS4_INACTIVE_OP	0x3
303 
304 #define	ISVDEV(t) ((t == VBLK) || (t == VCHR) || (t == VFIFO))
305 
306 /* ALIGN64 aligns the given buffer and adjust buffer size to 64 bit */
307 #define	ALIGN64(x, ptr, sz)						\
308 	x = ((uintptr_t)(ptr)) & (sizeof (uint64_t) - 1);		\
309 	if (x) {							\
310 		x = sizeof (uint64_t) - (x);				\
311 		sz -= (x);						\
312 		ptr += (x);						\
313 	}
314 
315 #ifdef DEBUG
316 int nfs4_client_attr_debug = 0;
317 int nfs4_client_state_debug = 0;
318 int nfs4_client_shadow_debug = 0;
319 int nfs4_client_lock_debug = 0;
320 int nfs4_seqid_sync = 0;
321 int nfs4_client_map_debug = 0;
322 static int nfs4_pageio_debug = 0;
323 int nfs4_client_inactive_debug = 0;
324 int nfs4_client_recov_debug = 0;
325 int nfs4_client_failover_debug = 0;
326 int nfs4_client_call_debug = 0;
327 int nfs4_client_lookup_debug = 0;
328 int nfs4_client_zone_debug = 0;
329 int nfs4_lost_rqst_debug = 0;
330 int nfs4_rdattrerr_debug = 0;
331 int nfs4_open_stream_debug = 0;
332 
333 int nfs4read_error_inject;
334 
335 static int nfs4_create_misses = 0;
336 
337 static int nfs4_readdir_cache_shorts = 0;
338 static int nfs4_readdir_readahead = 0;
339 
340 static int nfs4_bio_do_stop = 0;
341 
342 static int nfs4_lostpage = 0;	/* number of times we lost original page */
343 
344 int nfs4_mmap_debug = 0;
345 
346 static int nfs4_pathconf_cache_hits = 0;
347 static int nfs4_pathconf_cache_misses = 0;
348 
349 int nfs4close_all_cnt;
350 int nfs4close_one_debug = 0;
351 int nfs4close_notw_debug = 0;
352 
353 int denied_to_flk_debug = 0;
354 void *lockt_denied_debug;
355 
356 #endif
357 
358 /*
359  * How long to wait before trying again if OPEN_CONFIRM gets ETIMEDOUT
360  * or NFS4ERR_RESOURCE.
361  */
362 static int confirm_retry_sec = 30;
363 
364 static int nfs4_lookup_neg_cache = 1;
365 
366 /*
367  * number of pages to read ahead
368  * optimized for 100 base-T.
369  */
370 static int nfs4_nra = 4;
371 
372 static int nfs4_do_symlink_cache = 1;
373 
374 static int nfs4_pathconf_disable_cache = 0;
375 
376 /*
377  * These are the vnode ops routines which implement the vnode interface to
378  * the networked file system.  These routines just take their parameters,
379  * make them look networkish by putting the right info into interface structs,
380  * and then calling the appropriate remote routine(s) to do the work.
381  *
382  * Note on directory name lookup cacheing:  If we detect a stale fhandle,
383  * we purge the directory cache relative to that vnode.  This way, the
384  * user won't get burned by the cache repeatedly.  See <nfs/rnode4.h> for
385  * more details on rnode locking.
386  */
387 
388 struct vnodeops *nfs4_vnodeops;
389 
390 const fs_operation_def_t nfs4_vnodeops_template[] = {
391 	VOPNAME_OPEN,		{ .vop_open = nfs4_open },
392 	VOPNAME_CLOSE,		{ .vop_close = nfs4_close },
393 	VOPNAME_READ,		{ .vop_read = nfs4_read },
394 	VOPNAME_WRITE,		{ .vop_write = nfs4_write },
395 	VOPNAME_IOCTL,		{ .vop_ioctl = nfs4_ioctl },
396 	VOPNAME_GETATTR,	{ .vop_getattr = nfs4_getattr },
397 	VOPNAME_SETATTR,	{ .vop_setattr = nfs4_setattr },
398 	VOPNAME_ACCESS,		{ .vop_access = nfs4_access },
399 	VOPNAME_LOOKUP,		{ .vop_lookup = nfs4_lookup },
400 	VOPNAME_CREATE,		{ .vop_create = nfs4_create },
401 	VOPNAME_REMOVE,		{ .vop_remove = nfs4_remove },
402 	VOPNAME_LINK,		{ .vop_link = nfs4_link },
403 	VOPNAME_RENAME,		{ .vop_rename = nfs4_rename },
404 	VOPNAME_MKDIR,		{ .vop_mkdir = nfs4_mkdir },
405 	VOPNAME_RMDIR,		{ .vop_rmdir = nfs4_rmdir },
406 	VOPNAME_READDIR,	{ .vop_readdir = nfs4_readdir },
407 	VOPNAME_SYMLINK,	{ .vop_symlink = nfs4_symlink },
408 	VOPNAME_READLINK,	{ .vop_readlink = nfs4_readlink },
409 	VOPNAME_FSYNC,		{ .vop_fsync = nfs4_fsync },
410 	VOPNAME_INACTIVE,	{ .vop_inactive = nfs4_inactive },
411 	VOPNAME_FID,		{ .vop_fid = nfs4_fid },
412 	VOPNAME_RWLOCK,		{ .vop_rwlock = nfs4_rwlock },
413 	VOPNAME_RWUNLOCK,	{ .vop_rwunlock = nfs4_rwunlock },
414 	VOPNAME_SEEK,		{ .vop_seek = nfs4_seek },
415 	VOPNAME_FRLOCK,		{ .vop_frlock = nfs4_frlock },
416 	VOPNAME_SPACE,		{ .vop_space = nfs4_space },
417 	VOPNAME_REALVP,		{ .vop_realvp = nfs4_realvp },
418 	VOPNAME_GETPAGE,	{ .vop_getpage = nfs4_getpage },
419 	VOPNAME_PUTPAGE,	{ .vop_putpage = nfs4_putpage },
420 	VOPNAME_MAP,		{ .vop_map = nfs4_map },
421 	VOPNAME_ADDMAP,		{ .vop_addmap = nfs4_addmap },
422 	VOPNAME_DELMAP,		{ .vop_delmap = nfs4_delmap },
423 	/* no separate nfs4_dump */
424 	VOPNAME_DUMP,		{ .vop_dump = nfs_dump },
425 	VOPNAME_PATHCONF,	{ .vop_pathconf = nfs4_pathconf },
426 	VOPNAME_PAGEIO,		{ .vop_pageio = nfs4_pageio },
427 	VOPNAME_DISPOSE,	{ .vop_dispose = nfs4_dispose },
428 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = nfs4_setsecattr },
429 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = nfs4_getsecattr },
430 	VOPNAME_SHRLOCK,	{ .vop_shrlock = nfs4_shrlock },
431 	VOPNAME_VNEVENT, 	{ .vop_vnevent = fs_vnevent_support },
432 	NULL,			NULL
433 };
434 
435 /*
436  * The following are subroutines and definitions to set args or get res
437  * for the different nfsv4 ops
438  */
439 
440 void
441 nfs4args_lookup_free(nfs_argop4 *argop, int arglen)
442 {
443 	int		i;
444 
445 	for (i = 0; i < arglen; i++) {
446 		if (argop[i].argop == OP_LOOKUP) {
447 			kmem_free(
448 			    argop[i].nfs_argop4_u.oplookup.
449 			    objname.utf8string_val,
450 			    argop[i].nfs_argop4_u.oplookup.
451 			    objname.utf8string_len);
452 		}
453 	}
454 }
455 
456 static void
457 nfs4args_lock_free(nfs_argop4 *argop)
458 {
459 	locker4 *locker = &argop->nfs_argop4_u.oplock.locker;
460 
461 	if (locker->new_lock_owner == TRUE) {
462 		open_to_lock_owner4 *open_owner;
463 
464 		open_owner = &locker->locker4_u.open_owner;
465 		if (open_owner->lock_owner.owner_val != NULL) {
466 			kmem_free(open_owner->lock_owner.owner_val,
467 			    open_owner->lock_owner.owner_len);
468 		}
469 	}
470 }
471 
472 static void
473 nfs4args_lockt_free(nfs_argop4 *argop)
474 {
475 	lock_owner4 *lowner = &argop->nfs_argop4_u.oplockt.owner;
476 
477 	if (lowner->owner_val != NULL) {
478 		kmem_free(lowner->owner_val, lowner->owner_len);
479 	}
480 }
481 
482 static void
483 nfs4args_setattr(nfs_argop4 *argop, vattr_t *vap, vsecattr_t *vsap, int flags,
484     rnode4_t *rp, cred_t *cr, bitmap4 supp, int *error,
485     nfs4_stateid_types_t *sid_types)
486 {
487 	fattr4		*attr = &argop->nfs_argop4_u.opsetattr.obj_attributes;
488 	mntinfo4_t	*mi;
489 
490 	argop->argop = OP_SETATTR;
491 	/*
492 	 * The stateid is set to 0 if client is not modifying the size
493 	 * and otherwise to whatever nfs4_get_stateid() returns.
494 	 *
495 	 * XXX Note: nfs4_get_stateid() returns 0 if no lockowner and/or no
496 	 * state struct could be found for the process/file pair.  We may
497 	 * want to change this in the future (by OPENing the file).  See
498 	 * bug # 4474852.
499 	 */
500 	if (vap->va_mask & AT_SIZE) {
501 
502 		ASSERT(rp != NULL);
503 		mi = VTOMI4(RTOV4(rp));
504 
505 		argop->nfs_argop4_u.opsetattr.stateid =
506 		    nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
507 		    OP_SETATTR, sid_types, FALSE);
508 	} else {
509 		bzero(&argop->nfs_argop4_u.opsetattr.stateid,
510 		    sizeof (stateid4));
511 	}
512 
513 	*error = vattr_to_fattr4(vap, vsap, attr, flags, OP_SETATTR, supp);
514 	if (*error)
515 		bzero(attr, sizeof (*attr));
516 }
517 
518 static void
519 nfs4args_setattr_free(nfs_argop4 *argop)
520 {
521 	nfs4_fattr4_free(&argop->nfs_argop4_u.opsetattr.obj_attributes);
522 }
523 
524 static int
525 nfs4args_verify(nfs_argop4 *argop, vattr_t *vap, enum nfs_opnum4 op,
526     bitmap4 supp)
527 {
528 	fattr4 *attr;
529 	int error = 0;
530 
531 	argop->argop = op;
532 	switch (op) {
533 	case OP_VERIFY:
534 		attr = &argop->nfs_argop4_u.opverify.obj_attributes;
535 		break;
536 	case OP_NVERIFY:
537 		attr = &argop->nfs_argop4_u.opnverify.obj_attributes;
538 		break;
539 	default:
540 		return (EINVAL);
541 	}
542 	if (!error)
543 		error = vattr_to_fattr4(vap, NULL, attr, 0, op, supp);
544 	if (error)
545 		bzero(attr, sizeof (*attr));
546 	return (error);
547 }
548 
549 static void
550 nfs4args_verify_free(nfs_argop4 *argop)
551 {
552 	switch (argop->argop) {
553 	case OP_VERIFY:
554 		nfs4_fattr4_free(&argop->nfs_argop4_u.opverify.obj_attributes);
555 		break;
556 	case OP_NVERIFY:
557 		nfs4_fattr4_free(&argop->nfs_argop4_u.opnverify.obj_attributes);
558 		break;
559 	default:
560 		break;
561 	}
562 }
563 
564 static void
565 nfs4args_write(nfs_argop4 *argop, stable_how4 stable, rnode4_t *rp, cred_t *cr,
566     WRITE4args **wargs_pp, nfs4_stateid_types_t *sid_tp)
567 {
568 	WRITE4args *wargs = &argop->nfs_argop4_u.opwrite;
569 	mntinfo4_t *mi = VTOMI4(RTOV4(rp));
570 
571 	argop->argop = OP_WRITE;
572 	wargs->stable = stable;
573 	wargs->stateid = nfs4_get_w_stateid(cr, rp, curproc->p_pidp->pid_id,
574 	    mi, OP_WRITE, sid_tp);
575 	wargs->mblk = NULL;
576 	*wargs_pp = wargs;
577 }
578 
579 void
580 nfs4args_copen_free(OPEN4cargs *open_args)
581 {
582 	if (open_args->owner.owner_val) {
583 		kmem_free(open_args->owner.owner_val,
584 		    open_args->owner.owner_len);
585 	}
586 	if ((open_args->opentype == OPEN4_CREATE) &&
587 	    (open_args->mode != EXCLUSIVE4)) {
588 		nfs4_fattr4_free(&open_args->createhow4_u.createattrs);
589 	}
590 }
591 
592 /*
593  * XXX:  This is referenced in modstubs.s
594  */
595 struct vnodeops *
596 nfs4_getvnodeops(void)
597 {
598 	return (nfs4_vnodeops);
599 }
600 
601 /*
602  * The OPEN operation opens a regular file.
603  */
604 /*ARGSUSED3*/
605 static int
606 nfs4_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
607 {
608 	vnode_t *dvp = NULL;
609 	rnode4_t *rp, *drp;
610 	int error;
611 	int just_been_created;
612 	char fn[MAXNAMELEN];
613 
614 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4_open: "));
615 	if (nfs_zone() != VTOMI4(*vpp)->mi_zone)
616 		return (EIO);
617 	rp = VTOR4(*vpp);
618 
619 	/*
620 	 * Check to see if opening something besides a regular file;
621 	 * if so skip the OTW call
622 	 */
623 	if ((*vpp)->v_type != VREG) {
624 		error = nfs4_open_non_reg_file(vpp, flag, cr);
625 		return (error);
626 	}
627 
628 	/*
629 	 * XXX - would like a check right here to know if the file is
630 	 * executable or not, so as to skip OTW
631 	 */
632 
633 	if ((error = vtodv(*vpp, &dvp, cr, TRUE)) != 0)
634 		return (error);
635 
636 	drp = VTOR4(dvp);
637 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
638 		return (EINTR);
639 
640 	if ((error = vtoname(*vpp, fn, MAXNAMELEN)) != 0) {
641 		nfs_rw_exit(&drp->r_rwlock);
642 		return (error);
643 	}
644 
645 	/*
646 	 * See if this file has just been CREATEd.
647 	 * If so, clear the flag and update the dnlc, which was previously
648 	 * skipped in nfs4_create.
649 	 * XXX need better serilization on this.
650 	 * XXX move this into the nf4open_otw call, after we have
651 	 * XXX acquired the open owner seqid sync.
652 	 */
653 	mutex_enter(&rp->r_statev4_lock);
654 	if (rp->created_v4) {
655 		rp->created_v4 = 0;
656 		mutex_exit(&rp->r_statev4_lock);
657 
658 		dnlc_update(dvp, fn, *vpp);
659 		/* This is needed so we don't bump the open ref count */
660 		just_been_created = 1;
661 	} else {
662 		mutex_exit(&rp->r_statev4_lock);
663 		just_been_created = 0;
664 	}
665 
666 	/*
667 	 * If caller specified O_TRUNC/FTRUNC, then be sure to set
668 	 * FWRITE (to drive successful setattr(size=0) after open)
669 	 */
670 	if (flag & FTRUNC)
671 		flag |= FWRITE;
672 
673 	error = nfs4open_otw(dvp, fn, NULL, vpp, cr, 0, flag, 0,
674 	    just_been_created);
675 
676 	if (!error && !((*vpp)->v_flag & VROOT))
677 		dnlc_update(dvp, fn, *vpp);
678 
679 	nfs_rw_exit(&drp->r_rwlock);
680 
681 	/* release the hold from vtodv */
682 	VN_RELE(dvp);
683 
684 	/* exchange the shadow for the master vnode, if needed */
685 
686 	if (error == 0 && IS_SHADOW(*vpp, rp))
687 		sv_exchange(vpp);
688 
689 	return (error);
690 }
691 
692 /*
693  * See if there's a "lost open" request to be saved and recovered.
694  */
695 static void
696 nfs4open_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
697     nfs4_open_owner_t *oop, cred_t *cr, vnode_t *vp,
698     vnode_t *dvp, OPEN4cargs *open_args)
699 {
700 	vfs_t *vfsp;
701 	char *srccfp;
702 
703 	vfsp = (dvp ? dvp->v_vfsp : vp->v_vfsp);
704 
705 	if (error != ETIMEDOUT && error != EINTR &&
706 	    !NFS4_FRC_UNMT_ERR(error, vfsp)) {
707 		lost_rqstp->lr_op = 0;
708 		return;
709 	}
710 
711 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
712 	    "nfs4open_save_lost_rqst: error %d", error));
713 
714 	lost_rqstp->lr_op = OP_OPEN;
715 
716 	/*
717 	 * The vp (if it is not NULL) and dvp are held and rele'd via
718 	 * the recovery code.  See nfs4_save_lost_rqst.
719 	 */
720 	lost_rqstp->lr_vp = vp;
721 	lost_rqstp->lr_dvp = dvp;
722 	lost_rqstp->lr_oop = oop;
723 	lost_rqstp->lr_osp = NULL;
724 	lost_rqstp->lr_lop = NULL;
725 	lost_rqstp->lr_cr = cr;
726 	lost_rqstp->lr_flk = NULL;
727 	lost_rqstp->lr_oacc = open_args->share_access;
728 	lost_rqstp->lr_odeny = open_args->share_deny;
729 	lost_rqstp->lr_oclaim = open_args->claim;
730 	if (open_args->claim == CLAIM_DELEGATE_CUR) {
731 		lost_rqstp->lr_ostateid =
732 		    open_args->open_claim4_u.delegate_cur_info.delegate_stateid;
733 		srccfp = open_args->open_claim4_u.delegate_cur_info.cfile;
734 	} else {
735 		srccfp = open_args->open_claim4_u.cfile;
736 	}
737 	lost_rqstp->lr_ofile.utf8string_len = 0;
738 	lost_rqstp->lr_ofile.utf8string_val = NULL;
739 	(void) str_to_utf8(srccfp, &lost_rqstp->lr_ofile);
740 	lost_rqstp->lr_putfirst = FALSE;
741 }
742 
743 struct nfs4_excl_time {
744 	uint32 seconds;
745 	uint32 nseconds;
746 };
747 
748 /*
749  * The OPEN operation creates and/or opens a regular file
750  *
751  * ARGSUSED
752  */
753 static int
754 nfs4open_otw(vnode_t *dvp, char *file_name, struct vattr *in_va,
755     vnode_t **vpp, cred_t *cr, int create_flag, int open_flag,
756     enum createmode4 createmode, int file_just_been_created)
757 {
758 	rnode4_t *rp;
759 	rnode4_t *drp = VTOR4(dvp);
760 	vnode_t *vp = NULL;
761 	vnode_t *vpi = *vpp;
762 	bool_t needrecov = FALSE;
763 
764 	int doqueue = 1;
765 
766 	COMPOUND4args_clnt args;
767 	COMPOUND4res_clnt res;
768 	nfs_argop4 *argop;
769 	nfs_resop4 *resop;
770 	int argoplist_size;
771 	int idx_open, idx_fattr;
772 
773 	GETFH4res *gf_res = NULL;
774 	OPEN4res *op_res = NULL;
775 	nfs4_ga_res_t *garp;
776 	fattr4 *attr = NULL;
777 	struct nfs4_excl_time verf;
778 	bool_t did_excl_setup = FALSE;
779 	int created_osp;
780 
781 	OPEN4cargs *open_args;
782 	nfs4_open_owner_t	*oop = NULL;
783 	nfs4_open_stream_t	*osp = NULL;
784 	seqid4 seqid = 0;
785 	bool_t retry_open = FALSE;
786 	nfs4_recov_state_t recov_state;
787 	nfs4_lost_rqst_t lost_rqst;
788 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
789 	hrtime_t t;
790 	int acc = 0;
791 	cred_t *cred_otw = NULL;	/* cred used to do the RPC call */
792 	cred_t *ncr = NULL;
793 
794 	nfs4_sharedfh_t *otw_sfh;
795 	nfs4_sharedfh_t *orig_sfh;
796 	int fh_differs = 0;
797 	int numops, setgid_flag;
798 	int num_bseqid_retry = NFS4_NUM_RETRY_BAD_SEQID + 1;
799 
800 	/*
801 	 * Make sure we properly deal with setting the right gid on
802 	 * a newly created file to reflect the parent's setgid bit
803 	 */
804 	setgid_flag = 0;
805 	if (create_flag && in_va) {
806 
807 		/*
808 		 * If the parent's directory has the setgid bit set
809 		 * _and_ the client was able to get a valid mapping
810 		 * for the parent dir's owner_group, we want to
811 		 * append NVERIFY(owner_group == dva.va_gid) and
812 		 * SETATTR to the CREATE compound.
813 		 */
814 		mutex_enter(&drp->r_statelock);
815 		if (drp->r_attr.va_mode & VSGID &&
816 		    drp->r_attr.va_gid != GID_NOBODY) {
817 			in_va->va_gid = drp->r_attr.va_gid;
818 			setgid_flag = 1;
819 		}
820 		mutex_exit(&drp->r_statelock);
821 	}
822 
823 	/*
824 	 * Normal/non-create compound:
825 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new)
826 	 *
827 	 * Open(create) compound no setgid:
828 	 * PUTFH(dfh) + SAVEFH + OPEN(create) + GETFH + GETATTR(new) +
829 	 * RESTOREFH + GETATTR
830 	 *
831 	 * Open(create) setgid:
832 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new) +
833 	 * SAVEFH + PUTFH(dfh) + GETATTR(dvp) + RESTOREFH +
834 	 * NVERIFY(grp) + SETATTR
835 	 */
836 	if (setgid_flag) {
837 		numops = 10;
838 		idx_open = 1;
839 		idx_fattr = 3;
840 	} else if (create_flag) {
841 		numops = 7;
842 		idx_open = 2;
843 		idx_fattr = 4;
844 	} else {
845 		numops = 4;
846 		idx_open = 1;
847 		idx_fattr = 3;
848 	}
849 
850 	args.array_len = numops;
851 	argoplist_size = numops * sizeof (nfs_argop4);
852 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
853 
854 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw: "
855 	    "open %s open flag 0x%x cred %p", file_name, open_flag,
856 	    (void *)cr));
857 
858 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
859 	if (create_flag) {
860 		/*
861 		 * We are to create a file.  Initialize the passed in vnode
862 		 * pointer.
863 		 */
864 		vpi = NULL;
865 	} else {
866 		/*
867 		 * Check to see if the client owns a read delegation and is
868 		 * trying to open for write.  If so, then return the delegation
869 		 * to avoid the server doing a cb_recall and returning DELAY.
870 		 * NB - we don't use the statev4_lock here because we'd have
871 		 * to drop the lock anyway and the result would be stale.
872 		 */
873 		if ((open_flag & FWRITE) &&
874 		    VTOR4(vpi)->r_deleg_type == OPEN_DELEGATE_READ)
875 			(void) nfs4delegreturn(VTOR4(vpi), NFS4_DR_REOPEN);
876 
877 		/*
878 		 * If the file has a delegation, then do an access check up
879 		 * front.  This avoids having to an access check later after
880 		 * we've already done start_op, which could deadlock.
881 		 */
882 		if (VTOR4(vpi)->r_deleg_type != OPEN_DELEGATE_NONE) {
883 			if (open_flag & FREAD &&
884 			    nfs4_access(vpi, VREAD, 0, cr, NULL) == 0)
885 				acc |= VREAD;
886 			if (open_flag & FWRITE &&
887 			    nfs4_access(vpi, VWRITE, 0, cr, NULL) == 0)
888 				acc |= VWRITE;
889 		}
890 	}
891 
892 	drp = VTOR4(dvp);
893 
894 	recov_state.rs_flags = 0;
895 	recov_state.rs_num_retry_despite_err = 0;
896 	cred_otw = cr;
897 
898 recov_retry:
899 	fh_differs = 0;
900 	nfs4_error_zinit(&e);
901 
902 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, vpi, &recov_state);
903 	if (e.error) {
904 		if (ncr != NULL)
905 			crfree(ncr);
906 		kmem_free(argop, argoplist_size);
907 		return (e.error);
908 	}
909 
910 	args.ctag = TAG_OPEN;
911 	args.array_len = numops;
912 	args.array = argop;
913 
914 	/* putfh directory fh */
915 	argop[0].argop = OP_CPUTFH;
916 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
917 
918 	/* OPEN: either op 1 or op 2 depending upon create/setgid flags */
919 	argop[idx_open].argop = OP_COPEN;
920 	open_args = &argop[idx_open].nfs_argop4_u.opcopen;
921 	open_args->claim = CLAIM_NULL;
922 
923 	/* name of file */
924 	open_args->open_claim4_u.cfile = file_name;
925 	open_args->owner.owner_len = 0;
926 	open_args->owner.owner_val = NULL;
927 
928 	if (create_flag) {
929 		/* CREATE a file */
930 		open_args->opentype = OPEN4_CREATE;
931 		open_args->mode = createmode;
932 		if (createmode == EXCLUSIVE4) {
933 			if (did_excl_setup == FALSE) {
934 				verf.seconds = nfs_atoi(hw_serial);
935 				if (verf.seconds != 0)
936 					verf.nseconds = newnum();
937 				else {
938 					timestruc_t now;
939 
940 					gethrestime(&now);
941 					verf.seconds = now.tv_sec;
942 					verf.nseconds = now.tv_nsec;
943 				}
944 				/*
945 				 * Since the server will use this value for the
946 				 * mtime, make sure that it can't overflow. Zero
947 				 * out the MSB. The actual value does not matter
948 				 * here, only its uniqeness.
949 				 */
950 				verf.seconds &= INT32_MAX;
951 				did_excl_setup = TRUE;
952 			}
953 
954 			/* Now copy over verifier to OPEN4args. */
955 			open_args->createhow4_u.createverf = *(uint64_t *)&verf;
956 		} else {
957 			int v_error;
958 			bitmap4 supp_attrs;
959 			servinfo4_t *svp;
960 
961 			attr = &open_args->createhow4_u.createattrs;
962 
963 			svp = drp->r_server;
964 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
965 			supp_attrs = svp->sv_supp_attrs;
966 			nfs_rw_exit(&svp->sv_lock);
967 
968 			/* GUARDED4 or UNCHECKED4 */
969 			v_error = vattr_to_fattr4(in_va, NULL, attr, 0, OP_OPEN,
970 			    supp_attrs);
971 			if (v_error) {
972 				bzero(attr, sizeof (*attr));
973 				nfs4args_copen_free(open_args);
974 				nfs4_end_op(VTOMI4(dvp), dvp, vpi,
975 				    &recov_state, FALSE);
976 				if (ncr != NULL)
977 					crfree(ncr);
978 				kmem_free(argop, argoplist_size);
979 				return (v_error);
980 			}
981 		}
982 	} else {
983 		/* NO CREATE */
984 		open_args->opentype = OPEN4_NOCREATE;
985 	}
986 
987 	if (recov_state.rs_sp != NULL) {
988 		mutex_enter(&recov_state.rs_sp->s_lock);
989 		open_args->owner.clientid = recov_state.rs_sp->clientid;
990 		mutex_exit(&recov_state.rs_sp->s_lock);
991 	} else {
992 		/* XXX should we just fail here? */
993 		open_args->owner.clientid = 0;
994 	}
995 
996 	/*
997 	 * This increments oop's ref count or creates a temporary 'just_created'
998 	 * open owner that will become valid when this OPEN/OPEN_CONFIRM call
999 	 * completes.
1000 	 */
1001 	mutex_enter(&VTOMI4(dvp)->mi_lock);
1002 
1003 	/* See if a permanent or just created open owner exists */
1004 	oop = find_open_owner_nolock(cr, NFS4_JUST_CREATED, VTOMI4(dvp));
1005 	if (!oop) {
1006 		/*
1007 		 * This open owner does not exist so create a temporary
1008 		 * just created one.
1009 		 */
1010 		oop = create_open_owner(cr, VTOMI4(dvp));
1011 		ASSERT(oop != NULL);
1012 	}
1013 	mutex_exit(&VTOMI4(dvp)->mi_lock);
1014 
1015 	/* this length never changes, do alloc before seqid sync */
1016 	open_args->owner.owner_len = sizeof (oop->oo_name);
1017 	open_args->owner.owner_val =
1018 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1019 
1020 	e.error = nfs4_start_open_seqid_sync(oop, VTOMI4(dvp));
1021 	if (e.error == EAGAIN) {
1022 		open_owner_rele(oop);
1023 		nfs4args_copen_free(open_args);
1024 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1025 		if (ncr != NULL) {
1026 			crfree(ncr);
1027 			ncr = NULL;
1028 		}
1029 		goto recov_retry;
1030 	}
1031 
1032 	/* Check to see if we need to do the OTW call */
1033 	if (!create_flag) {
1034 		if (!nfs4_is_otw_open_necessary(oop, open_flag, vpi,
1035 		    file_just_been_created, &e.error, acc, &recov_state)) {
1036 
1037 			/*
1038 			 * The OTW open is not necessary.  Either
1039 			 * the open can succeed without it (eg.
1040 			 * delegation, error == 0) or the open
1041 			 * must fail due to an access failure
1042 			 * (error != 0).  In either case, tidy
1043 			 * up and return.
1044 			 */
1045 
1046 			nfs4_end_open_seqid_sync(oop);
1047 			open_owner_rele(oop);
1048 			nfs4args_copen_free(open_args);
1049 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, FALSE);
1050 			if (ncr != NULL)
1051 				crfree(ncr);
1052 			kmem_free(argop, argoplist_size);
1053 			return (e.error);
1054 		}
1055 	}
1056 
1057 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1058 	    open_args->owner.owner_len);
1059 
1060 	seqid = nfs4_get_open_seqid(oop) + 1;
1061 	open_args->seqid = seqid;
1062 	open_args->share_access = 0;
1063 	if (open_flag & FREAD)
1064 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1065 	if (open_flag & FWRITE)
1066 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1067 	open_args->share_deny = OPEN4_SHARE_DENY_NONE;
1068 
1069 
1070 
1071 	/*
1072 	 * getfh w/sanity check for idx_open/idx_fattr
1073 	 */
1074 	ASSERT((idx_open + 1) == (idx_fattr - 1));
1075 	argop[idx_open + 1].argop = OP_GETFH;
1076 
1077 	/* getattr */
1078 	argop[idx_fattr].argop = OP_GETATTR;
1079 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1080 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1081 
1082 	if (setgid_flag) {
1083 		vattr_t	_v;
1084 		servinfo4_t *svp;
1085 		bitmap4	supp_attrs;
1086 
1087 		svp = drp->r_server;
1088 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1089 		supp_attrs = svp->sv_supp_attrs;
1090 		nfs_rw_exit(&svp->sv_lock);
1091 
1092 		/*
1093 		 * For setgid case, we need to:
1094 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1095 		 */
1096 		argop[4].argop = OP_SAVEFH;
1097 
1098 		argop[5].argop = OP_CPUTFH;
1099 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
1100 
1101 		argop[6].argop = OP_GETATTR;
1102 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1103 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1104 
1105 		argop[7].argop = OP_RESTOREFH;
1106 
1107 		/*
1108 		 * nverify
1109 		 */
1110 		_v.va_mask = AT_GID;
1111 		_v.va_gid = in_va->va_gid;
1112 		if (!(e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
1113 		    supp_attrs))) {
1114 
1115 			/*
1116 			 * setattr
1117 			 *
1118 			 * We _know_ we're not messing with AT_SIZE or
1119 			 * AT_XTIME, so no need for stateid or flags.
1120 			 * Also we specify NULL rp since we're only
1121 			 * interested in setting owner_group attributes.
1122 			 */
1123 			nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr,
1124 			    supp_attrs, &e.error, 0);
1125 			if (e.error)
1126 				nfs4args_verify_free(&argop[8]);
1127 		}
1128 
1129 		if (e.error) {
1130 			/*
1131 			 * XXX - Revisit the last argument to nfs4_end_op()
1132 			 *	 once 5020486 is fixed.
1133 			 */
1134 			nfs4_end_open_seqid_sync(oop);
1135 			open_owner_rele(oop);
1136 			nfs4args_copen_free(open_args);
1137 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1138 			if (ncr != NULL)
1139 				crfree(ncr);
1140 			kmem_free(argop, argoplist_size);
1141 			return (e.error);
1142 		}
1143 	} else if (create_flag) {
1144 		/*
1145 		 * For setgid case, we need to:
1146 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1147 		 */
1148 		argop[1].argop = OP_SAVEFH;
1149 
1150 		argop[5].argop = OP_RESTOREFH;
1151 
1152 		argop[6].argop = OP_GETATTR;
1153 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1154 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1155 	}
1156 
1157 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1158 	    "nfs4open_otw: %s call, nm %s, rp %s",
1159 	    needrecov ? "recov" : "first", file_name,
1160 	    rnode4info(VTOR4(dvp))));
1161 
1162 	t = gethrtime();
1163 
1164 	rfs4call(VTOMI4(dvp), &args, &res, cred_otw, &doqueue, 0, &e);
1165 
1166 	if (!e.error && nfs4_need_to_bump_seqid(&res))
1167 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1168 
1169 	needrecov = nfs4_needs_recovery(&e, TRUE, dvp->v_vfsp);
1170 
1171 	if (e.error || needrecov) {
1172 		bool_t abort = FALSE;
1173 
1174 		if (needrecov) {
1175 			nfs4_bseqid_entry_t *bsep = NULL;
1176 
1177 			nfs4open_save_lost_rqst(e.error, &lost_rqst, oop,
1178 			    cred_otw, vpi, dvp, open_args);
1179 
1180 			if (!e.error && res.status == NFS4ERR_BAD_SEQID) {
1181 				bsep = nfs4_create_bseqid_entry(oop, NULL,
1182 				    vpi, 0, args.ctag, open_args->seqid);
1183 				num_bseqid_retry--;
1184 			}
1185 
1186 			abort = nfs4_start_recovery(&e, VTOMI4(dvp), dvp, vpi,
1187 			    NULL, lost_rqst.lr_op == OP_OPEN ?
1188 			    &lost_rqst : NULL, OP_OPEN, bsep);
1189 
1190 			if (bsep)
1191 				kmem_free(bsep, sizeof (*bsep));
1192 			/* give up if we keep getting BAD_SEQID */
1193 			if (num_bseqid_retry == 0)
1194 				abort = TRUE;
1195 			if (abort == TRUE && e.error == 0)
1196 				e.error = geterrno4(res.status);
1197 		}
1198 		nfs4_end_open_seqid_sync(oop);
1199 		open_owner_rele(oop);
1200 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1201 		nfs4args_copen_free(open_args);
1202 		if (setgid_flag) {
1203 			nfs4args_verify_free(&argop[8]);
1204 			nfs4args_setattr_free(&argop[9]);
1205 		}
1206 		if (!e.error)
1207 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1208 		if (ncr != NULL) {
1209 			crfree(ncr);
1210 			ncr = NULL;
1211 		}
1212 		if (!needrecov || abort == TRUE || e.error == EINTR ||
1213 		    NFS4_FRC_UNMT_ERR(e.error, dvp->v_vfsp)) {
1214 			kmem_free(argop, argoplist_size);
1215 			return (e.error);
1216 		}
1217 		goto recov_retry;
1218 	}
1219 
1220 	/*
1221 	 * Will check and update lease after checking the rflag for
1222 	 * OPEN_CONFIRM in the successful OPEN call.
1223 	 */
1224 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
1225 
1226 		/*
1227 		 * XXX what if we're crossing mount points from server1:/drp
1228 		 * to server2:/drp/rp.
1229 		 */
1230 
1231 		/* Signal our end of use of the open seqid */
1232 		nfs4_end_open_seqid_sync(oop);
1233 
1234 		/*
1235 		 * This will destroy the open owner if it was just created,
1236 		 * and no one else has put a reference on it.
1237 		 */
1238 		open_owner_rele(oop);
1239 		if (create_flag && (createmode != EXCLUSIVE4) &&
1240 		    res.status == NFS4ERR_BADOWNER)
1241 			nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1242 
1243 		e.error = geterrno4(res.status);
1244 		nfs4args_copen_free(open_args);
1245 		if (setgid_flag) {
1246 			nfs4args_verify_free(&argop[8]);
1247 			nfs4args_setattr_free(&argop[9]);
1248 		}
1249 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1250 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1251 		/*
1252 		 * If the reply is NFS4ERR_ACCESS, it may be because
1253 		 * we are root (no root net access).  If the real uid
1254 		 * is not root, then retry with the real uid instead.
1255 		 */
1256 		if (ncr != NULL) {
1257 			crfree(ncr);
1258 			ncr = NULL;
1259 		}
1260 		if (res.status == NFS4ERR_ACCESS &&
1261 		    (ncr = crnetadjust(cred_otw)) != NULL) {
1262 			cred_otw = ncr;
1263 			goto recov_retry;
1264 		}
1265 		kmem_free(argop, argoplist_size);
1266 		return (e.error);
1267 	}
1268 
1269 	resop = &res.array[idx_open];  /* open res */
1270 	op_res = &resop->nfs_resop4_u.opopen;
1271 
1272 #ifdef DEBUG
1273 	/*
1274 	 * verify attrset bitmap
1275 	 */
1276 	if (create_flag &&
1277 	    (createmode == UNCHECKED4 || createmode == GUARDED4)) {
1278 		/* make sure attrset returned is what we asked for */
1279 		/* XXX Ignore this 'error' for now */
1280 		if (attr->attrmask != op_res->attrset)
1281 			/* EMPTY */;
1282 	}
1283 #endif
1284 
1285 	if (op_res->rflags & OPEN4_RESULT_LOCKTYPE_POSIX) {
1286 		mutex_enter(&VTOMI4(dvp)->mi_lock);
1287 		VTOMI4(dvp)->mi_flags |= MI4_POSIX_LOCK;
1288 		mutex_exit(&VTOMI4(dvp)->mi_lock);
1289 	}
1290 
1291 	resop = &res.array[idx_open + 1];  /* getfh res */
1292 	gf_res = &resop->nfs_resop4_u.opgetfh;
1293 
1294 	otw_sfh = sfh4_get(&gf_res->object, VTOMI4(dvp));
1295 
1296 	/*
1297 	 * The open stateid has been updated on the server but not
1298 	 * on the client yet.  There is a path: makenfs4node->nfs4_attr_cache->
1299 	 * flush_pages->VOP_PUTPAGE->...->nfs4write where we will issue an OTW
1300 	 * WRITE call.  That, however, will use the old stateid, so go ahead
1301 	 * and upate the open stateid now, before any call to makenfs4node.
1302 	 */
1303 	if (vpi) {
1304 		nfs4_open_stream_t	*tmp_osp;
1305 		rnode4_t		*tmp_rp = VTOR4(vpi);
1306 
1307 		tmp_osp = find_open_stream(oop, tmp_rp);
1308 		if (tmp_osp) {
1309 			tmp_osp->open_stateid = op_res->stateid;
1310 			mutex_exit(&tmp_osp->os_sync_lock);
1311 			open_stream_rele(tmp_osp, tmp_rp);
1312 		}
1313 
1314 		/*
1315 		 * We must determine if the file handle given by the otw open
1316 		 * is the same as the file handle which was passed in with
1317 		 * *vpp.  This case can be reached if the file we are trying
1318 		 * to open has been removed and another file has been created
1319 		 * having the same file name.  The passed in vnode is released
1320 		 * later.
1321 		 */
1322 		orig_sfh = VTOR4(vpi)->r_fh;
1323 		fh_differs = nfs4cmpfh(&orig_sfh->sfh_fh, &otw_sfh->sfh_fh);
1324 	}
1325 
1326 	garp = &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res;
1327 
1328 	if (create_flag || fh_differs) {
1329 		int rnode_err = 0;
1330 
1331 		vp = makenfs4node(otw_sfh, garp, dvp->v_vfsp, t, cr,
1332 		    dvp, fn_get(VTOSV(dvp)->sv_name, file_name));
1333 
1334 		if (e.error)
1335 			PURGE_ATTRCACHE4(vp);
1336 		/*
1337 		 * For the newly created vp case, make sure the rnode
1338 		 * isn't bad before using it.
1339 		 */
1340 		mutex_enter(&(VTOR4(vp))->r_statelock);
1341 		if (VTOR4(vp)->r_flags & R4RECOVERR)
1342 			rnode_err = EIO;
1343 		mutex_exit(&(VTOR4(vp))->r_statelock);
1344 
1345 		if (rnode_err) {
1346 			nfs4_end_open_seqid_sync(oop);
1347 			nfs4args_copen_free(open_args);
1348 			if (setgid_flag) {
1349 				nfs4args_verify_free(&argop[8]);
1350 				nfs4args_setattr_free(&argop[9]);
1351 			}
1352 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1353 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1354 			    needrecov);
1355 			open_owner_rele(oop);
1356 			VN_RELE(vp);
1357 			if (ncr != NULL)
1358 				crfree(ncr);
1359 			sfh4_rele(&otw_sfh);
1360 			kmem_free(argop, argoplist_size);
1361 			return (EIO);
1362 		}
1363 	} else {
1364 		vp = vpi;
1365 	}
1366 	sfh4_rele(&otw_sfh);
1367 
1368 	/*
1369 	 * It seems odd to get a full set of attrs and then not update
1370 	 * the object's attrcache in the non-create case.  Create case uses
1371 	 * the attrs since makenfs4node checks to see if the attrs need to
1372 	 * be updated (and then updates them).  The non-create case should
1373 	 * update attrs also.
1374 	 */
1375 	if (! create_flag && ! fh_differs && !e.error) {
1376 		nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
1377 	}
1378 
1379 	nfs4_error_zinit(&e);
1380 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
1381 		/* This does not do recovery for vp explicitly. */
1382 		nfs4open_confirm(vp, &seqid, &op_res->stateid, cred_otw, FALSE,
1383 		    &retry_open, oop, FALSE, &e, &num_bseqid_retry);
1384 
1385 		if (e.error || e.stat) {
1386 			nfs4_end_open_seqid_sync(oop);
1387 			nfs4args_copen_free(open_args);
1388 			if (setgid_flag) {
1389 				nfs4args_verify_free(&argop[8]);
1390 				nfs4args_setattr_free(&argop[9]);
1391 			}
1392 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1393 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1394 			    needrecov);
1395 			open_owner_rele(oop);
1396 			if (create_flag || fh_differs) {
1397 				/* rele the makenfs4node */
1398 				VN_RELE(vp);
1399 			}
1400 			if (ncr != NULL) {
1401 				crfree(ncr);
1402 				ncr = NULL;
1403 			}
1404 			if (retry_open == TRUE) {
1405 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1406 				    "nfs4open_otw: retry the open since OPEN "
1407 				    "CONFIRM failed with error %d stat %d",
1408 				    e.error, e.stat));
1409 				if (create_flag && createmode == GUARDED4) {
1410 					NFS4_DEBUG(nfs4_client_recov_debug,
1411 					    (CE_NOTE, "nfs4open_otw: switch "
1412 					    "createmode from GUARDED4 to "
1413 					    "UNCHECKED4"));
1414 					createmode = UNCHECKED4;
1415 				}
1416 				goto recov_retry;
1417 			}
1418 			if (!e.error) {
1419 				if (create_flag && (createmode != EXCLUSIVE4) &&
1420 				    e.stat == NFS4ERR_BADOWNER)
1421 					nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1422 
1423 				e.error = geterrno4(e.stat);
1424 			}
1425 			kmem_free(argop, argoplist_size);
1426 			return (e.error);
1427 		}
1428 	}
1429 
1430 	rp = VTOR4(vp);
1431 
1432 	mutex_enter(&rp->r_statev4_lock);
1433 	if (create_flag)
1434 		rp->created_v4 = 1;
1435 	mutex_exit(&rp->r_statev4_lock);
1436 
1437 	mutex_enter(&oop->oo_lock);
1438 	/* Doesn't matter if 'oo_just_created' already was set as this */
1439 	oop->oo_just_created = NFS4_PERM_CREATED;
1440 	if (oop->oo_cred_otw)
1441 		crfree(oop->oo_cred_otw);
1442 	oop->oo_cred_otw = cred_otw;
1443 	crhold(oop->oo_cred_otw);
1444 	mutex_exit(&oop->oo_lock);
1445 
1446 	/* returns with 'os_sync_lock' held */
1447 	osp = find_or_create_open_stream(oop, rp, &created_osp);
1448 	if (!osp) {
1449 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1450 		    "nfs4open_otw: failed to create an open stream"));
1451 		NFS4_DEBUG(nfs4_seqid_sync, (CE_NOTE, "nfs4open_otw: "
1452 		    "signal our end of use of the open seqid"));
1453 
1454 		nfs4_end_open_seqid_sync(oop);
1455 		open_owner_rele(oop);
1456 		nfs4args_copen_free(open_args);
1457 		if (setgid_flag) {
1458 			nfs4args_verify_free(&argop[8]);
1459 			nfs4args_setattr_free(&argop[9]);
1460 		}
1461 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1462 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1463 		if (create_flag || fh_differs)
1464 			VN_RELE(vp);
1465 		if (ncr != NULL)
1466 			crfree(ncr);
1467 
1468 		kmem_free(argop, argoplist_size);
1469 		return (EINVAL);
1470 
1471 	}
1472 
1473 	osp->open_stateid = op_res->stateid;
1474 
1475 	if (open_flag & FREAD)
1476 		osp->os_share_acc_read++;
1477 	if (open_flag & FWRITE)
1478 		osp->os_share_acc_write++;
1479 	osp->os_share_deny_none++;
1480 
1481 	/*
1482 	 * Need to reset this bitfield for the possible case where we were
1483 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
1484 	 * we could retry the CLOSE, OPENed the file again.
1485 	 */
1486 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
1487 	osp->os_final_close = 0;
1488 	osp->os_force_close = 0;
1489 #ifdef DEBUG
1490 	if (osp->os_failed_reopen)
1491 		NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE, "nfs4open_otw:"
1492 		    " clearing os_failed_reopen for osp %p, cr %p, rp %s",
1493 		    (void *)osp, (void *)cr, rnode4info(rp)));
1494 #endif
1495 	osp->os_failed_reopen = 0;
1496 
1497 	mutex_exit(&osp->os_sync_lock);
1498 
1499 	nfs4_end_open_seqid_sync(oop);
1500 
1501 	if (created_osp && recov_state.rs_sp != NULL) {
1502 		mutex_enter(&recov_state.rs_sp->s_lock);
1503 		nfs4_inc_state_ref_count_nolock(recov_state.rs_sp, VTOMI4(dvp));
1504 		mutex_exit(&recov_state.rs_sp->s_lock);
1505 	}
1506 
1507 	/* get rid of our reference to find oop */
1508 	open_owner_rele(oop);
1509 
1510 	open_stream_rele(osp, rp);
1511 
1512 	/* accept delegation, if any */
1513 	nfs4_delegation_accept(rp, CLAIM_NULL, op_res, garp, cred_otw);
1514 
1515 	nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1516 
1517 	if (createmode == EXCLUSIVE4 &&
1518 	    (in_va->va_mask & ~(AT_GID | AT_SIZE))) {
1519 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw:"
1520 		    " EXCLUSIVE4: sending a SETATTR"));
1521 		/*
1522 		 * If doing an exclusive create, then generate
1523 		 * a SETATTR to set the initial attributes.
1524 		 * Try to set the mtime and the atime to the
1525 		 * server's current time.  It is somewhat
1526 		 * expected that these fields will be used to
1527 		 * store the exclusive create cookie.  If not,
1528 		 * server implementors will need to know that
1529 		 * a SETATTR will follow an exclusive create
1530 		 * and the cookie should be destroyed if
1531 		 * appropriate.
1532 		 *
1533 		 * The AT_GID and AT_SIZE bits are turned off
1534 		 * so that the SETATTR request will not attempt
1535 		 * to process these.  The gid will be set
1536 		 * separately if appropriate.  The size is turned
1537 		 * off because it is assumed that a new file will
1538 		 * be created empty and if the file wasn't empty,
1539 		 * then the exclusive create will have failed
1540 		 * because the file must have existed already.
1541 		 * Therefore, no truncate operation is needed.
1542 		 */
1543 		in_va->va_mask &= ~(AT_GID | AT_SIZE);
1544 		in_va->va_mask |= (AT_MTIME | AT_ATIME);
1545 
1546 		e.error = nfs4setattr(vp, in_va, 0, cr, NULL);
1547 		if (e.error) {
1548 			/*
1549 			 * Couldn't correct the attributes of
1550 			 * the newly created file and the
1551 			 * attributes are wrong.  Remove the
1552 			 * file and return an error to the
1553 			 * application.
1554 			 */
1555 			/* XXX will this take care of client state ? */
1556 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1557 			    "nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1558 			    " remove file", e.error));
1559 			VN_RELE(vp);
1560 			(void) nfs4_remove(dvp, file_name, cr, NULL, 0);
1561 			/*
1562 			 * Since we've reled the vnode and removed
1563 			 * the file we now need to return the error.
1564 			 * At this point we don't want to update the
1565 			 * dircaches, call nfs4_waitfor_purge_complete
1566 			 * or set vpp to vp so we need to skip these
1567 			 * as well.
1568 			 */
1569 			goto skip_update_dircaches;
1570 		}
1571 	}
1572 
1573 	/*
1574 	 * If we created or found the correct vnode, due to create_flag or
1575 	 * fh_differs being set, then update directory cache attribute, readdir
1576 	 * and dnlc caches.
1577 	 */
1578 	if (create_flag || fh_differs) {
1579 		dirattr_info_t dinfo, *dinfop;
1580 
1581 		/*
1582 		 * Make sure getattr succeeded before using results.
1583 		 * note: op 7 is getattr(dir) for both flavors of
1584 		 * open(create).
1585 		 */
1586 		if (create_flag && res.status == NFS4_OK) {
1587 			dinfo.di_time_call = t;
1588 			dinfo.di_cred = cr;
1589 			dinfo.di_garp =
1590 			    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
1591 			dinfop = &dinfo;
1592 		} else {
1593 			dinfop = NULL;
1594 		}
1595 
1596 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1597 		    dinfop);
1598 	}
1599 
1600 	/*
1601 	 * If the page cache for this file was flushed from actions
1602 	 * above, it was done asynchronously and if that is true,
1603 	 * there is a need to wait here for it to complete.  This must
1604 	 * be done outside of start_fop/end_fop.
1605 	 */
1606 	(void) nfs4_waitfor_purge_complete(vp);
1607 
1608 	/*
1609 	 * It is implicit that we are in the open case (create_flag == 0) since
1610 	 * fh_differs can only be set to a non-zero value in the open case.
1611 	 */
1612 	if (fh_differs != 0 && vpi != NULL)
1613 		VN_RELE(vpi);
1614 
1615 	/*
1616 	 * Be sure to set *vpp to the correct value before returning.
1617 	 */
1618 	*vpp = vp;
1619 
1620 skip_update_dircaches:
1621 
1622 	nfs4args_copen_free(open_args);
1623 	if (setgid_flag) {
1624 		nfs4args_verify_free(&argop[8]);
1625 		nfs4args_setattr_free(&argop[9]);
1626 	}
1627 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1628 
1629 	if (ncr)
1630 		crfree(ncr);
1631 	kmem_free(argop, argoplist_size);
1632 	return (e.error);
1633 }
1634 
1635 /*
1636  * Reopen an open instance.  cf. nfs4open_otw().
1637  *
1638  * Errors are returned by the nfs4_error_t parameter.
1639  * - ep->error contains an errno value or zero.
1640  * - if it is zero, ep->stat is set to an NFS status code, if any.
1641  *   If the file could not be reopened, but the caller should continue, the
1642  *   file is marked dead and no error values are returned.  If the caller
1643  *   should stop recovering open files and start over, either the ep->error
1644  *   value or ep->stat will indicate an error (either something that requires
1645  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1646  *   filehandles) may be handled silently by this routine.
1647  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1648  *   will be started, so the caller should not do it.
1649  *
1650  * Gotos:
1651  * - kill_file : reopen failed in such a fashion to constitute marking the
1652  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1653  *   is for cases where recovery is not possible.
1654  * - failed_reopen : same as above, except that the file has already been
1655  *   marked dead, so no need to do it again.
1656  * - bailout : reopen failed but we are able to recover and retry the reopen -
1657  *   either within this function immediately or via the calling function.
1658  */
1659 
1660 void
1661 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1662     open_claim_type4 claim, bool_t frc_use_claim_previous,
1663     bool_t is_recov)
1664 {
1665 	COMPOUND4args_clnt args;
1666 	COMPOUND4res_clnt res;
1667 	nfs_argop4 argop[4];
1668 	nfs_resop4 *resop;
1669 	OPEN4res *op_res = NULL;
1670 	OPEN4cargs *open_args;
1671 	GETFH4res *gf_res;
1672 	rnode4_t *rp = VTOR4(vp);
1673 	int doqueue = 1;
1674 	cred_t *cr = NULL, *cred_otw = NULL;
1675 	nfs4_open_owner_t *oop = NULL;
1676 	seqid4 seqid;
1677 	nfs4_ga_res_t *garp;
1678 	char fn[MAXNAMELEN];
1679 	nfs4_recov_state_t recov = {NULL, 0};
1680 	nfs4_lost_rqst_t lost_rqst;
1681 	mntinfo4_t *mi = VTOMI4(vp);
1682 	bool_t abort;
1683 	char *failed_msg = "";
1684 	int fh_different;
1685 	hrtime_t t;
1686 	nfs4_bseqid_entry_t *bsep = NULL;
1687 
1688 	ASSERT(nfs4_consistent_type(vp));
1689 	ASSERT(nfs_zone() == mi->mi_zone);
1690 
1691 	nfs4_error_zinit(ep);
1692 
1693 	/* this is the cred used to find the open owner */
1694 	cr = state_to_cred(osp);
1695 	if (cr == NULL) {
1696 		failed_msg = "Couldn't reopen: no cred";
1697 		goto kill_file;
1698 	}
1699 	/* use this cred for OTW operations */
1700 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1701 
1702 top:
1703 	nfs4_error_zinit(ep);
1704 
1705 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1706 		/* File system has been unmounted, quit */
1707 		ep->error = EIO;
1708 		failed_msg = "Couldn't reopen: file system has been unmounted";
1709 		goto kill_file;
1710 	}
1711 
1712 	oop = osp->os_open_owner;
1713 
1714 	ASSERT(oop != NULL);
1715 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1716 		failed_msg = "can't reopen: no open owner";
1717 		goto kill_file;
1718 	}
1719 	open_owner_hold(oop);
1720 
1721 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1722 	if (ep->error) {
1723 		open_owner_rele(oop);
1724 		oop = NULL;
1725 		goto bailout;
1726 	}
1727 
1728 	/*
1729 	 * If the rnode has a delegation and the delegation has been
1730 	 * recovered and the server didn't request a recall and the caller
1731 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1732 	 * recovery) and the rnode hasn't been marked dead, then install
1733 	 * the delegation stateid in the open stream.  Otherwise, proceed
1734 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1735 	 */
1736 	mutex_enter(&rp->r_statev4_lock);
1737 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1738 	    !rp->r_deleg_return_pending &&
1739 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1740 	    !rp->r_deleg_needs_recall &&
1741 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1742 	    !(rp->r_flags & R4RECOVERR)) {
1743 		mutex_enter(&osp->os_sync_lock);
1744 		osp->os_delegation = 1;
1745 		osp->open_stateid = rp->r_deleg_stateid;
1746 		mutex_exit(&osp->os_sync_lock);
1747 		mutex_exit(&rp->r_statev4_lock);
1748 		goto bailout;
1749 	}
1750 	mutex_exit(&rp->r_statev4_lock);
1751 
1752 	/*
1753 	 * If the file failed recovery, just quit.  This failure need not
1754 	 * affect other reopens, so don't return an error.
1755 	 */
1756 	mutex_enter(&rp->r_statelock);
1757 	if (rp->r_flags & R4RECOVERR) {
1758 		mutex_exit(&rp->r_statelock);
1759 		ep->error = 0;
1760 		goto failed_reopen;
1761 	}
1762 	mutex_exit(&rp->r_statelock);
1763 
1764 	/*
1765 	 * argop is empty here
1766 	 *
1767 	 * PUTFH, OPEN, GETATTR
1768 	 */
1769 	args.ctag = TAG_REOPEN;
1770 	args.array_len = 4;
1771 	args.array = argop;
1772 
1773 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1774 	    "nfs4_reopen: file is type %d, id %s",
1775 	    vp->v_type, rnode4info(VTOR4(vp))));
1776 
1777 	argop[0].argop = OP_CPUTFH;
1778 
1779 	if (claim != CLAIM_PREVIOUS) {
1780 		/*
1781 		 * if this is a file mount then
1782 		 * use the mntinfo parentfh
1783 		 */
1784 		argop[0].nfs_argop4_u.opcputfh.sfh =
1785 		    (vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1786 		    VTOSV(vp)->sv_dfh;
1787 	} else {
1788 		/* putfh fh to reopen */
1789 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1790 	}
1791 
1792 	argop[1].argop = OP_COPEN;
1793 	open_args = &argop[1].nfs_argop4_u.opcopen;
1794 	open_args->claim = claim;
1795 
1796 	if (claim == CLAIM_NULL) {
1797 
1798 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1799 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1800 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1801 			    (void *)vp);
1802 			failed_msg = "Couldn't reopen: vtoname failed for "
1803 			    "CLAIM_NULL";
1804 			/* nothing allocated yet */
1805 			goto kill_file;
1806 		}
1807 
1808 		open_args->open_claim4_u.cfile = fn;
1809 	} else if (claim == CLAIM_PREVIOUS) {
1810 
1811 		/*
1812 		 * We have two cases to deal with here:
1813 		 * 1) We're being called to reopen files in order to satisfy
1814 		 *    a lock operation request which requires us to explicitly
1815 		 *    reopen files which were opened under a delegation.  If
1816 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1817 		 *    that case, frc_use_claim_previous is TRUE and we must
1818 		 *    use the rnode's current delegation type (r_deleg_type).
1819 		 * 2) We're reopening files during some form of recovery.
1820 		 *    In this case, frc_use_claim_previous is FALSE and we
1821 		 *    use the delegation type appropriate for recovery
1822 		 *    (r_deleg_needs_recovery).
1823 		 */
1824 		mutex_enter(&rp->r_statev4_lock);
1825 		open_args->open_claim4_u.delegate_type =
1826 		    frc_use_claim_previous ?
1827 		    rp->r_deleg_type :
1828 		    rp->r_deleg_needs_recovery;
1829 		mutex_exit(&rp->r_statev4_lock);
1830 
1831 	} else if (claim == CLAIM_DELEGATE_CUR) {
1832 
1833 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1834 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1835 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1836 			    "with %m", (void *)vp);
1837 			failed_msg = "Couldn't reopen: vtoname failed for "
1838 			    "CLAIM_DELEGATE_CUR";
1839 			/* nothing allocated yet */
1840 			goto kill_file;
1841 		}
1842 
1843 		mutex_enter(&rp->r_statev4_lock);
1844 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1845 		    rp->r_deleg_stateid;
1846 		mutex_exit(&rp->r_statev4_lock);
1847 
1848 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1849 	}
1850 	open_args->opentype = OPEN4_NOCREATE;
1851 	open_args->owner.clientid = mi2clientid(mi);
1852 	open_args->owner.owner_len = sizeof (oop->oo_name);
1853 	open_args->owner.owner_val =
1854 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1855 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1856 	    open_args->owner.owner_len);
1857 	open_args->share_access = 0;
1858 	open_args->share_deny = 0;
1859 
1860 	mutex_enter(&osp->os_sync_lock);
1861 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1862 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1863 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1864 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1865 	    osp->os_share_acc_write, osp->os_open_ref_count,
1866 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1867 
1868 	if (osp->os_share_acc_read || osp->os_mmap_read)
1869 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1870 	if (osp->os_share_acc_write || osp->os_mmap_write)
1871 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1872 	if (osp->os_share_deny_read)
1873 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1874 	if (osp->os_share_deny_write)
1875 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1876 	mutex_exit(&osp->os_sync_lock);
1877 
1878 	seqid = nfs4_get_open_seqid(oop) + 1;
1879 	open_args->seqid = seqid;
1880 
1881 	/* Construct the getfh part of the compound */
1882 	argop[2].argop = OP_GETFH;
1883 
1884 	/* Construct the getattr part of the compound */
1885 	argop[3].argop = OP_GETATTR;
1886 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1887 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1888 
1889 	t = gethrtime();
1890 
1891 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1892 
1893 	if (ep->error) {
1894 		if (!is_recov && !frc_use_claim_previous &&
1895 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1896 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1897 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1898 			    cred_otw, vp, NULL, open_args);
1899 			abort = nfs4_start_recovery(ep,
1900 			    VTOMI4(vp), vp, NULL, NULL,
1901 			    lost_rqst.lr_op == OP_OPEN ?
1902 			    &lost_rqst : NULL, OP_OPEN, NULL);
1903 			nfs4args_copen_free(open_args);
1904 			goto bailout;
1905 		}
1906 
1907 		nfs4args_copen_free(open_args);
1908 
1909 		if (ep->error == EACCES && cred_otw != cr) {
1910 			crfree(cred_otw);
1911 			cred_otw = cr;
1912 			crhold(cred_otw);
1913 			nfs4_end_open_seqid_sync(oop);
1914 			open_owner_rele(oop);
1915 			oop = NULL;
1916 			goto top;
1917 		}
1918 		if (ep->error == ETIMEDOUT)
1919 			goto bailout;
1920 		failed_msg = "Couldn't reopen: rpc error";
1921 		goto kill_file;
1922 	}
1923 
1924 	if (nfs4_need_to_bump_seqid(&res))
1925 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1926 
1927 	switch (res.status) {
1928 	case NFS4_OK:
1929 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1930 			mutex_enter(&rp->r_statelock);
1931 			rp->r_delay_interval = 0;
1932 			mutex_exit(&rp->r_statelock);
1933 		}
1934 		break;
1935 	case NFS4ERR_BAD_SEQID:
1936 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1937 		    args.ctag, open_args->seqid);
1938 
1939 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1940 		    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1941 		    NULL, OP_OPEN, bsep);
1942 
1943 		nfs4args_copen_free(open_args);
1944 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1945 		nfs4_end_open_seqid_sync(oop);
1946 		open_owner_rele(oop);
1947 		oop = NULL;
1948 		kmem_free(bsep, sizeof (*bsep));
1949 
1950 		goto kill_file;
1951 	case NFS4ERR_NO_GRACE:
1952 		nfs4args_copen_free(open_args);
1953 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1954 		nfs4_end_open_seqid_sync(oop);
1955 		open_owner_rele(oop);
1956 		oop = NULL;
1957 		if (claim == CLAIM_PREVIOUS) {
1958 			/*
1959 			 * Retry as a plain open. We don't need to worry about
1960 			 * checking the changeinfo: it is acceptable for a
1961 			 * client to re-open a file and continue processing
1962 			 * (in the absence of locks).
1963 			 */
1964 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1965 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1966 			    "will retry as CLAIM_NULL"));
1967 			claim = CLAIM_NULL;
1968 			nfs4_mi_kstat_inc_no_grace(mi);
1969 			goto top;
1970 		}
1971 		failed_msg =
1972 		    "Couldn't reopen: tried reclaim outside grace period. ";
1973 		goto kill_file;
1974 	case NFS4ERR_GRACE:
1975 		nfs4_set_grace_wait(mi);
1976 		nfs4args_copen_free(open_args);
1977 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1978 		nfs4_end_open_seqid_sync(oop);
1979 		open_owner_rele(oop);
1980 		oop = NULL;
1981 		ep->error = nfs4_wait_for_grace(mi, &recov);
1982 		if (ep->error != 0)
1983 			goto bailout;
1984 		goto top;
1985 	case NFS4ERR_DELAY:
1986 		nfs4_set_delay_wait(vp);
1987 		nfs4args_copen_free(open_args);
1988 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1989 		nfs4_end_open_seqid_sync(oop);
1990 		open_owner_rele(oop);
1991 		oop = NULL;
1992 		ep->error = nfs4_wait_for_delay(vp, &recov);
1993 		nfs4_mi_kstat_inc_delay(mi);
1994 		if (ep->error != 0)
1995 			goto bailout;
1996 		goto top;
1997 	case NFS4ERR_FHEXPIRED:
1998 		/* recover filehandle and retry */
1999 		abort = nfs4_start_recovery(ep,
2000 		    mi, vp, NULL, NULL, NULL, OP_OPEN, NULL);
2001 		nfs4args_copen_free(open_args);
2002 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2003 		nfs4_end_open_seqid_sync(oop);
2004 		open_owner_rele(oop);
2005 		oop = NULL;
2006 		if (abort == FALSE)
2007 			goto top;
2008 		failed_msg = "Couldn't reopen: recovery aborted";
2009 		goto kill_file;
2010 	case NFS4ERR_RESOURCE:
2011 	case NFS4ERR_STALE_CLIENTID:
2012 	case NFS4ERR_WRONGSEC:
2013 	case NFS4ERR_EXPIRED:
2014 		/*
2015 		 * Do not mark the file dead and let the calling
2016 		 * function initiate recovery.
2017 		 */
2018 		nfs4args_copen_free(open_args);
2019 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2020 		nfs4_end_open_seqid_sync(oop);
2021 		open_owner_rele(oop);
2022 		oop = NULL;
2023 		goto bailout;
2024 	case NFS4ERR_ACCESS:
2025 		if (cred_otw != cr) {
2026 			crfree(cred_otw);
2027 			cred_otw = cr;
2028 			crhold(cred_otw);
2029 			nfs4args_copen_free(open_args);
2030 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2031 			nfs4_end_open_seqid_sync(oop);
2032 			open_owner_rele(oop);
2033 			oop = NULL;
2034 			goto top;
2035 		}
2036 		/* fall through */
2037 	default:
2038 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2039 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2040 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2041 		    rnode4info(VTOR4(vp))));
2042 		failed_msg = "Couldn't reopen: NFSv4 error";
2043 		nfs4args_copen_free(open_args);
2044 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2045 		goto kill_file;
2046 	}
2047 
2048 	resop = &res.array[1];  /* open res */
2049 	op_res = &resop->nfs_resop4_u.opopen;
2050 
2051 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2052 
2053 	/*
2054 	 * Check if the path we reopened really is the same
2055 	 * file. We could end up in a situation where the file
2056 	 * was removed and a new file created with the same name.
2057 	 */
2058 	resop = &res.array[2];
2059 	gf_res = &resop->nfs_resop4_u.opgetfh;
2060 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2061 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2062 	if (fh_different) {
2063 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2064 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2065 			/* Oops, we don't have the same file */
2066 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2067 				failed_msg = "Couldn't reopen: Persistent "
2068 				    "file handle changed";
2069 			else
2070 				failed_msg = "Couldn't reopen: Volatile "
2071 				    "(no expire on open) file handle changed";
2072 
2073 			nfs4args_copen_free(open_args);
2074 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2075 			nfs_rw_exit(&mi->mi_fh_lock);
2076 			goto kill_file;
2077 
2078 		} else {
2079 			/*
2080 			 * We have volatile file handles that don't compare.
2081 			 * If the fids are the same then we assume that the
2082 			 * file handle expired but the rnode still refers to
2083 			 * the same file object.
2084 			 *
2085 			 * First check that we have fids or not.
2086 			 * If we don't we have a dumb server so we will
2087 			 * just assume every thing is ok for now.
2088 			 */
2089 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2090 			    rp->r_attr.va_mask & AT_NODEID &&
2091 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2092 				/*
2093 				 * We have fids, but they don't
2094 				 * compare. So kill the file.
2095 				 */
2096 				failed_msg =
2097 				    "Couldn't reopen: file handle changed"
2098 				    " due to mismatched fids";
2099 				nfs4args_copen_free(open_args);
2100 				(void) xdr_free(xdr_COMPOUND4res_clnt,
2101 				    (caddr_t)&res);
2102 				nfs_rw_exit(&mi->mi_fh_lock);
2103 				goto kill_file;
2104 			} else {
2105 				/*
2106 				 * We have volatile file handles that refers
2107 				 * to the same file (at least they have the
2108 				 * same fid) or we don't have fids so we
2109 				 * can't tell. :(. We'll be a kind and accepting
2110 				 * client so we'll update the rnode's file
2111 				 * handle with the otw handle.
2112 				 *
2113 				 * We need to drop mi->mi_fh_lock since
2114 				 * sh4_update acquires it. Since there is
2115 				 * only one recovery thread there is no
2116 				 * race.
2117 				 */
2118 				nfs_rw_exit(&mi->mi_fh_lock);
2119 				sfh4_update(rp->r_fh, &gf_res->object);
2120 			}
2121 		}
2122 	} else {
2123 		nfs_rw_exit(&mi->mi_fh_lock);
2124 	}
2125 
2126 	ASSERT(nfs4_consistent_type(vp));
2127 
2128 	/*
2129 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2130 	 * over.  Presumably if there is a persistent error it will show up
2131 	 * when we resend the OPEN.
2132 	 */
2133 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2134 		bool_t retry_open = FALSE;
2135 
2136 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2137 		    cred_otw, is_recov, &retry_open,
2138 		    oop, FALSE, ep, NULL);
2139 		if (ep->error || ep->stat) {
2140 			nfs4args_copen_free(open_args);
2141 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2142 			nfs4_end_open_seqid_sync(oop);
2143 			open_owner_rele(oop);
2144 			oop = NULL;
2145 			goto top;
2146 		}
2147 	}
2148 
2149 	mutex_enter(&osp->os_sync_lock);
2150 	osp->open_stateid = op_res->stateid;
2151 	osp->os_delegation = 0;
2152 	/*
2153 	 * Need to reset this bitfield for the possible case where we were
2154 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2155 	 * we could retry the CLOSE, OPENed the file again.
2156 	 */
2157 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2158 	osp->os_final_close = 0;
2159 	osp->os_force_close = 0;
2160 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2161 		osp->os_dc_openacc = open_args->share_access;
2162 	mutex_exit(&osp->os_sync_lock);
2163 
2164 	nfs4_end_open_seqid_sync(oop);
2165 
2166 	/* accept delegation, if any */
2167 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2168 
2169 	nfs4args_copen_free(open_args);
2170 
2171 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2172 
2173 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2174 
2175 	ASSERT(nfs4_consistent_type(vp));
2176 
2177 	open_owner_rele(oop);
2178 	crfree(cr);
2179 	crfree(cred_otw);
2180 	return;
2181 
2182 kill_file:
2183 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2184 failed_reopen:
2185 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2186 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2187 	    (void *)osp, (void *)cr, rnode4info(rp)));
2188 	mutex_enter(&osp->os_sync_lock);
2189 	osp->os_failed_reopen = 1;
2190 	mutex_exit(&osp->os_sync_lock);
2191 bailout:
2192 	if (oop != NULL) {
2193 		nfs4_end_open_seqid_sync(oop);
2194 		open_owner_rele(oop);
2195 	}
2196 	if (cr != NULL)
2197 		crfree(cr);
2198 	if (cred_otw != NULL)
2199 		crfree(cred_otw);
2200 }
2201 
2202 /* for . and .. OPENs */
2203 /* ARGSUSED */
2204 static int
2205 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2206 {
2207 	rnode4_t *rp;
2208 	nfs4_ga_res_t gar;
2209 
2210 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2211 
2212 	/*
2213 	 * If close-to-open consistency checking is turned off or
2214 	 * if there is no cached data, we can avoid
2215 	 * the over the wire getattr.  Otherwise, force a
2216 	 * call to the server to get fresh attributes and to
2217 	 * check caches. This is required for close-to-open
2218 	 * consistency.
2219 	 */
2220 	rp = VTOR4(*vpp);
2221 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2222 	    (rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2223 		return (0);
2224 
2225 	gar.n4g_va.va_mask = AT_ALL;
2226 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2227 }
2228 
2229 /*
2230  * CLOSE a file
2231  */
2232 /* ARGSUSED */
2233 static int
2234 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
2235 	caller_context_t *ct)
2236 {
2237 	rnode4_t	*rp;
2238 	int		 error = 0;
2239 	int		 r_error = 0;
2240 	int		 n4error = 0;
2241 	nfs4_error_t	 e = { 0, NFS4_OK, RPC_SUCCESS };
2242 
2243 	/*
2244 	 * Remove client state for this (lockowner, file) pair.
2245 	 * Issue otw v4 call to have the server do the same.
2246 	 */
2247 
2248 	rp = VTOR4(vp);
2249 
2250 	/*
2251 	 * zone_enter(2) prevents processes from changing zones with NFS files
2252 	 * open; if we happen to get here from the wrong zone we can't do
2253 	 * anything over the wire.
2254 	 */
2255 	if (VTOMI4(vp)->mi_zone != nfs_zone()) {
2256 		/*
2257 		 * We could attempt to clean up locks, except we're sure
2258 		 * that the current process didn't acquire any locks on
2259 		 * the file: any attempt to lock a file belong to another zone
2260 		 * will fail, and one can't lock an NFS file and then change
2261 		 * zones, as that fails too.
2262 		 *
2263 		 * Returning an error here is the sane thing to do.  A
2264 		 * subsequent call to VN_RELE() which translates to a
2265 		 * nfs4_inactive() will clean up state: if the zone of the
2266 		 * vnode's origin is still alive and kicking, the inactive
2267 		 * thread will handle the request (from the correct zone), and
2268 		 * everything (minus the OTW close call) should be OK.  If the
2269 		 * zone is going away nfs4_async_inactive() will throw away
2270 		 * delegations, open streams and cached pages inline.
2271 		 */
2272 		return (EIO);
2273 	}
2274 
2275 	/*
2276 	 * If we are using local locking for this filesystem, then
2277 	 * release all of the SYSV style record locks.  Otherwise,
2278 	 * we are doing network locking and we need to release all
2279 	 * of the network locks.  All of the locks held by this
2280 	 * process on this file are released no matter what the
2281 	 * incoming reference count is.
2282 	 */
2283 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK) {
2284 		cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
2285 		cleanshares(vp, ttoproc(curthread)->p_pid);
2286 	} else
2287 		e.error = nfs4_lockrelease(vp, flag, offset, cr);
2288 
2289 	if (e.error) {
2290 		struct lm_sysid *lmsid;
2291 		lmsid = nfs4_find_sysid(VTOMI4(vp));
2292 		if (lmsid == NULL) {
2293 			DTRACE_PROBE2(unknown__sysid, int, e.error,
2294 			    vnode_t *, vp);
2295 		} else {
2296 			cleanlocks(vp, ttoproc(curthread)->p_pid,
2297 			    (lm_sysidt(lmsid) | LM_SYSID_CLIENT));
2298 		}
2299 		return (e.error);
2300 	}
2301 
2302 	if (count > 1)
2303 		return (0);
2304 
2305 	/*
2306 	 * If the file has been `unlinked', then purge the
2307 	 * DNLC so that this vnode will get reycled quicker
2308 	 * and the .nfs* file on the server will get removed.
2309 	 */
2310 	if (rp->r_unldvp != NULL)
2311 		dnlc_purge_vp(vp);
2312 
2313 	/*
2314 	 * If the file was open for write and there are pages,
2315 	 * do a synchronous flush and commit of all of the
2316 	 * dirty and uncommitted pages.
2317 	 */
2318 	ASSERT(!e.error);
2319 	if ((flag & FWRITE) && nfs4_has_pages(vp))
2320 		error = nfs4_putpage_commit(vp, 0, 0, cr);
2321 
2322 	mutex_enter(&rp->r_statelock);
2323 	r_error = rp->r_error;
2324 	rp->r_error = 0;
2325 	mutex_exit(&rp->r_statelock);
2326 
2327 	/*
2328 	 * If this file type is one for which no explicit 'open' was
2329 	 * done, then bail now (ie. no need for protocol 'close'). If
2330 	 * there was an error w/the vm subsystem, return _that_ error,
2331 	 * otherwise, return any errors that may've been reported via
2332 	 * the rnode.
2333 	 */
2334 	if (vp->v_type != VREG)
2335 		return (error ? error : r_error);
2336 
2337 	/*
2338 	 * The sync putpage commit may have failed above, but since
2339 	 * we're working w/a regular file, we need to do the protocol
2340 	 * 'close' (nfs4close_one will figure out if an otw close is
2341 	 * needed or not). Report any errors _after_ doing the protocol
2342 	 * 'close'.
2343 	 */
2344 	nfs4close_one(vp, NULL, cr, flag, NULL, &e, CLOSE_NORM, 0, 0, 0);
2345 	n4error = e.error ? e.error : geterrno4(e.stat);
2346 
2347 	/*
2348 	 * Error reporting prio (Hi -> Lo)
2349 	 *
2350 	 *   i) nfs4_putpage_commit (error)
2351 	 *  ii) rnode's (r_error)
2352 	 * iii) nfs4close_one (n4error)
2353 	 */
2354 	return (error ? error : (r_error ? r_error : n4error));
2355 }
2356 
2357 /*
2358  * Initialize *lost_rqstp.
2359  */
2360 
2361 static void
2362 nfs4close_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
2363     nfs4_open_owner_t *oop, nfs4_open_stream_t *osp, cred_t *cr,
2364     vnode_t *vp)
2365 {
2366 	if (error != ETIMEDOUT && error != EINTR &&
2367 	    !NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
2368 		lost_rqstp->lr_op = 0;
2369 		return;
2370 	}
2371 
2372 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
2373 	    "nfs4close_save_lost_rqst: error %d", error));
2374 
2375 	lost_rqstp->lr_op = OP_CLOSE;
2376 	/*
2377 	 * The vp is held and rele'd via the recovery code.
2378 	 * See nfs4_save_lost_rqst.
2379 	 */
2380 	lost_rqstp->lr_vp = vp;
2381 	lost_rqstp->lr_dvp = NULL;
2382 	lost_rqstp->lr_oop = oop;
2383 	lost_rqstp->lr_osp = osp;
2384 	ASSERT(osp != NULL);
2385 	ASSERT(mutex_owned(&osp->os_sync_lock));
2386 	osp->os_pending_close = 1;
2387 	lost_rqstp->lr_lop = NULL;
2388 	lost_rqstp->lr_cr = cr;
2389 	lost_rqstp->lr_flk = NULL;
2390 	lost_rqstp->lr_putfirst = FALSE;
2391 }
2392 
2393 /*
2394  * Assumes you already have the open seqid sync grabbed as well as the
2395  * 'os_sync_lock'.  Note: this will release the open seqid sync and
2396  * 'os_sync_lock' if client recovery starts.  Calling functions have to
2397  * be prepared to handle this.
2398  *
2399  * 'recov' is returned as 1 if the CLOSE operation detected client recovery
2400  * was needed and was started, and that the calling function should retry
2401  * this function; otherwise it is returned as 0.
2402  *
2403  * Errors are returned via the nfs4_error_t parameter.
2404  */
2405 static void
2406 nfs4close_otw(rnode4_t *rp, cred_t *cred_otw, nfs4_open_owner_t *oop,
2407     nfs4_open_stream_t *osp, int *recov, int *did_start_seqid_syncp,
2408     nfs4_close_type_t close_type, nfs4_error_t *ep, int *have_sync_lockp)
2409 {
2410 	COMPOUND4args_clnt args;
2411 	COMPOUND4res_clnt res;
2412 	CLOSE4args *close_args;
2413 	nfs_resop4 *resop;
2414 	nfs_argop4 argop[3];
2415 	int doqueue = 1;
2416 	mntinfo4_t *mi;
2417 	seqid4 seqid;
2418 	vnode_t *vp;
2419 	bool_t needrecov = FALSE;
2420 	nfs4_lost_rqst_t lost_rqst;
2421 	hrtime_t t;
2422 
2423 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
2424 
2425 	ASSERT(MUTEX_HELD(&osp->os_sync_lock));
2426 
2427 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw"));
2428 
2429 	/* Only set this to 1 if recovery is started */
2430 	*recov = 0;
2431 
2432 	/* do the OTW call to close the file */
2433 
2434 	if (close_type == CLOSE_RESEND)
2435 		args.ctag = TAG_CLOSE_LOST;
2436 	else if (close_type == CLOSE_AFTER_RESEND)
2437 		args.ctag = TAG_CLOSE_UNDO;
2438 	else
2439 		args.ctag = TAG_CLOSE;
2440 
2441 	args.array_len = 3;
2442 	args.array = argop;
2443 
2444 	vp = RTOV4(rp);
2445 
2446 	mi = VTOMI4(vp);
2447 
2448 	/* putfh target fh */
2449 	argop[0].argop = OP_CPUTFH;
2450 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
2451 
2452 	argop[1].argop = OP_GETATTR;
2453 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
2454 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
2455 
2456 	argop[2].argop = OP_CLOSE;
2457 	close_args = &argop[2].nfs_argop4_u.opclose;
2458 
2459 	seqid = nfs4_get_open_seqid(oop) + 1;
2460 
2461 	close_args->seqid = seqid;
2462 	close_args->open_stateid = osp->open_stateid;
2463 
2464 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
2465 	    "nfs4close_otw: %s call, rp %s", needrecov ? "recov" : "first",
2466 	    rnode4info(rp)));
2467 
2468 	t = gethrtime();
2469 
2470 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
2471 
2472 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
2473 		nfs4_set_open_seqid(seqid, oop, args.ctag);
2474 	}
2475 
2476 	needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
2477 	if (ep->error && !needrecov) {
2478 		/*
2479 		 * if there was an error and no recovery is to be done
2480 		 * then then set up the file to flush its cache if
2481 		 * needed for the next caller.
2482 		 */
2483 		mutex_enter(&rp->r_statelock);
2484 		PURGE_ATTRCACHE4_LOCKED(rp);
2485 		rp->r_flags &= ~R4WRITEMODIFIED;
2486 		mutex_exit(&rp->r_statelock);
2487 		return;
2488 	}
2489 
2490 	if (needrecov) {
2491 		bool_t abort;
2492 		nfs4_bseqid_entry_t *bsep = NULL;
2493 
2494 		if (close_type != CLOSE_RESEND)
2495 			nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
2496 			    osp, cred_otw, vp);
2497 
2498 		if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
2499 			bsep = nfs4_create_bseqid_entry(oop, NULL, vp,
2500 			    0, args.ctag, close_args->seqid);
2501 
2502 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
2503 		    "nfs4close_otw: initiating recovery. error %d "
2504 		    "res.status %d", ep->error, res.status));
2505 
2506 		/*
2507 		 * Drop the 'os_sync_lock' here so we don't hit
2508 		 * a potential recursive mutex_enter via an
2509 		 * 'open_stream_hold()'.
2510 		 */
2511 		mutex_exit(&osp->os_sync_lock);
2512 		*have_sync_lockp = 0;
2513 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
2514 		    (close_type != CLOSE_RESEND &&
2515 		    lost_rqst.lr_op == OP_CLOSE) ? &lost_rqst : NULL,
2516 		    OP_CLOSE, bsep);
2517 
2518 		/* drop open seq sync, and let the calling function regrab it */
2519 		nfs4_end_open_seqid_sync(oop);
2520 		*did_start_seqid_syncp = 0;
2521 
2522 		if (bsep)
2523 			kmem_free(bsep, sizeof (*bsep));
2524 		/*
2525 		 * For signals, the caller wants to quit, so don't say to
2526 		 * retry.  For forced unmount, if it's a user thread, it
2527 		 * wants to quit.  If it's a recovery thread, the retry
2528 		 * will happen higher-up on the call stack.  Either way,
2529 		 * don't say to retry.
2530 		 */
2531 		if (abort == FALSE && ep->error != EINTR &&
2532 		    !NFS4_FRC_UNMT_ERR(ep->error, mi->mi_vfsp) &&
2533 		    close_type != CLOSE_RESEND &&
2534 		    close_type != CLOSE_AFTER_RESEND)
2535 			*recov = 1;
2536 		else
2537 			*recov = 0;
2538 
2539 		if (!ep->error)
2540 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2541 		return;
2542 	}
2543 
2544 	if (res.status) {
2545 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2546 		return;
2547 	}
2548 
2549 	mutex_enter(&rp->r_statev4_lock);
2550 	rp->created_v4 = 0;
2551 	mutex_exit(&rp->r_statev4_lock);
2552 
2553 	resop = &res.array[2];
2554 	osp->open_stateid = resop->nfs_resop4_u.opclose.open_stateid;
2555 	osp->os_valid = 0;
2556 
2557 	/*
2558 	 * This removes the reference obtained at OPEN; ie, when the
2559 	 * open stream structure was created.
2560 	 *
2561 	 * We don't have to worry about calling 'open_stream_rele'
2562 	 * since we our currently holding a reference to the open
2563 	 * stream which means the count cannot go to 0 with this
2564 	 * decrement.
2565 	 */
2566 	ASSERT(osp->os_ref_count >= 2);
2567 	osp->os_ref_count--;
2568 
2569 	if (!ep->error)
2570 		nfs4_attr_cache(vp,
2571 		    &res.array[1].nfs_resop4_u.opgetattr.ga_res,
2572 		    t, cred_otw, TRUE, NULL);
2573 
2574 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw:"
2575 	    " returning %d", ep->error));
2576 
2577 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2578 }
2579 
2580 /* ARGSUSED */
2581 static int
2582 nfs4_read(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2583     caller_context_t *ct)
2584 {
2585 	rnode4_t *rp;
2586 	u_offset_t off;
2587 	offset_t diff;
2588 	uint_t on;
2589 	uint_t n;
2590 	caddr_t base;
2591 	uint_t flags;
2592 	int error;
2593 	mntinfo4_t *mi;
2594 
2595 	rp = VTOR4(vp);
2596 
2597 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2598 
2599 	if (IS_SHADOW(vp, rp))
2600 		vp = RTOV4(rp);
2601 
2602 	if (vp->v_type != VREG)
2603 		return (EISDIR);
2604 
2605 	mi = VTOMI4(vp);
2606 
2607 	if (nfs_zone() != mi->mi_zone)
2608 		return (EIO);
2609 
2610 	if (uiop->uio_resid == 0)
2611 		return (0);
2612 
2613 	if (uiop->uio_loffset < 0 || uiop->uio_loffset + uiop->uio_resid < 0)
2614 		return (EINVAL);
2615 
2616 	mutex_enter(&rp->r_statelock);
2617 	if (rp->r_flags & R4RECOVERRP)
2618 		error = (rp->r_error ? rp->r_error : EIO);
2619 	else
2620 		error = 0;
2621 	mutex_exit(&rp->r_statelock);
2622 	if (error)
2623 		return (error);
2624 
2625 	/*
2626 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2627 	 * using client-side direct I/O and the file is not mmap'd and
2628 	 * there are no cached pages.
2629 	 */
2630 	if ((vp->v_flag & VNOCACHE) ||
2631 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2632 	    rp->r_mapcnt == 0 && !nfs4_has_pages(vp))) {
2633 		size_t resid = 0;
2634 
2635 		return (nfs4read(vp, NULL, uiop->uio_loffset,
2636 		    uiop->uio_resid, &resid, cr, FALSE, uiop));
2637 	}
2638 
2639 	error = 0;
2640 
2641 	do {
2642 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2643 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2644 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2645 
2646 		if (error = nfs4_validate_caches(vp, cr))
2647 			break;
2648 
2649 		mutex_enter(&rp->r_statelock);
2650 		while (rp->r_flags & R4INCACHEPURGE) {
2651 			if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2652 				mutex_exit(&rp->r_statelock);
2653 				return (EINTR);
2654 			}
2655 		}
2656 		diff = rp->r_size - uiop->uio_loffset;
2657 		mutex_exit(&rp->r_statelock);
2658 		if (diff <= 0)
2659 			break;
2660 		if (diff < n)
2661 			n = (uint_t)diff;
2662 
2663 		if (vpm_enable) {
2664 			/*
2665 			 * Copy data.
2666 			 */
2667 			error = vpm_data_copy(vp, off + on, n, uiop,
2668 			    1, NULL, 0, S_READ);
2669 		} else {
2670 			base = segmap_getmapflt(segkmap, vp, off + on, n, 1,
2671 			    S_READ);
2672 
2673 			error = uiomove(base + on, n, UIO_READ, uiop);
2674 		}
2675 
2676 		if (!error) {
2677 			/*
2678 			 * If read a whole block or read to eof,
2679 			 * won't need this buffer again soon.
2680 			 */
2681 			mutex_enter(&rp->r_statelock);
2682 			if (n + on == MAXBSIZE ||
2683 			    uiop->uio_loffset == rp->r_size)
2684 				flags = SM_DONTNEED;
2685 			else
2686 				flags = 0;
2687 			mutex_exit(&rp->r_statelock);
2688 			if (vpm_enable) {
2689 				error = vpm_sync_pages(vp, off, n, flags);
2690 			} else {
2691 				error = segmap_release(segkmap, base, flags);
2692 			}
2693 		} else {
2694 			if (vpm_enable) {
2695 				(void) vpm_sync_pages(vp, off, n, 0);
2696 			} else {
2697 				(void) segmap_release(segkmap, base, 0);
2698 			}
2699 		}
2700 	} while (!error && uiop->uio_resid > 0);
2701 
2702 	return (error);
2703 }
2704 
2705 /* ARGSUSED */
2706 static int
2707 nfs4_write(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2708     caller_context_t *ct)
2709 {
2710 	rlim64_t limit = uiop->uio_llimit;
2711 	rnode4_t *rp;
2712 	u_offset_t off;
2713 	caddr_t base;
2714 	uint_t flags;
2715 	int remainder;
2716 	size_t n;
2717 	int on;
2718 	int error;
2719 	int resid;
2720 	u_offset_t offset;
2721 	mntinfo4_t *mi;
2722 	uint_t bsize;
2723 
2724 	rp = VTOR4(vp);
2725 
2726 	if (IS_SHADOW(vp, rp))
2727 		vp = RTOV4(rp);
2728 
2729 	if (vp->v_type != VREG)
2730 		return (EISDIR);
2731 
2732 	mi = VTOMI4(vp);
2733 
2734 	if (nfs_zone() != mi->mi_zone)
2735 		return (EIO);
2736 
2737 	if (uiop->uio_resid == 0)
2738 		return (0);
2739 
2740 	mutex_enter(&rp->r_statelock);
2741 	if (rp->r_flags & R4RECOVERRP)
2742 		error = (rp->r_error ? rp->r_error : EIO);
2743 	else
2744 		error = 0;
2745 	mutex_exit(&rp->r_statelock);
2746 	if (error)
2747 		return (error);
2748 
2749 	if (ioflag & FAPPEND) {
2750 		struct vattr va;
2751 
2752 		/*
2753 		 * Must serialize if appending.
2754 		 */
2755 		if (nfs_rw_lock_held(&rp->r_rwlock, RW_READER)) {
2756 			nfs_rw_exit(&rp->r_rwlock);
2757 			if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER,
2758 			    INTR(vp)))
2759 				return (EINTR);
2760 		}
2761 
2762 		va.va_mask = AT_SIZE;
2763 		error = nfs4getattr(vp, &va, cr);
2764 		if (error)
2765 			return (error);
2766 		uiop->uio_loffset = va.va_size;
2767 	}
2768 
2769 	offset = uiop->uio_loffset + uiop->uio_resid;
2770 
2771 	if (uiop->uio_loffset < (offset_t)0 || offset < 0)
2772 		return (EINVAL);
2773 
2774 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
2775 		limit = MAXOFFSET_T;
2776 
2777 	/*
2778 	 * Check to make sure that the process will not exceed
2779 	 * its limit on file size.  It is okay to write up to
2780 	 * the limit, but not beyond.  Thus, the write which
2781 	 * reaches the limit will be short and the next write
2782 	 * will return an error.
2783 	 */
2784 	remainder = 0;
2785 	if (offset > uiop->uio_llimit) {
2786 		remainder = offset - uiop->uio_llimit;
2787 		uiop->uio_resid = uiop->uio_llimit - uiop->uio_loffset;
2788 		if (uiop->uio_resid <= 0) {
2789 			proc_t *p = ttoproc(curthread);
2790 
2791 			uiop->uio_resid += remainder;
2792 			mutex_enter(&p->p_lock);
2793 			(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE],
2794 			    p->p_rctls, p, RCA_UNSAFE_SIGINFO);
2795 			mutex_exit(&p->p_lock);
2796 			return (EFBIG);
2797 		}
2798 	}
2799 
2800 	/* update the change attribute, if we have a write delegation */
2801 
2802 	mutex_enter(&rp->r_statev4_lock);
2803 	if (rp->r_deleg_type == OPEN_DELEGATE_WRITE)
2804 		rp->r_deleg_change++;
2805 
2806 	mutex_exit(&rp->r_statev4_lock);
2807 
2808 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
2809 		return (EINTR);
2810 
2811 	/*
2812 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2813 	 * using client-side direct I/O and the file is not mmap'd and
2814 	 * there are no cached pages.
2815 	 */
2816 	if ((vp->v_flag & VNOCACHE) ||
2817 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2818 	    rp->r_mapcnt == 0 && !nfs4_has_pages(vp))) {
2819 		size_t bufsize;
2820 		int count;
2821 		u_offset_t org_offset;
2822 		stable_how4 stab_comm;
2823 nfs4_fwrite:
2824 		if (rp->r_flags & R4STALE) {
2825 			resid = uiop->uio_resid;
2826 			offset = uiop->uio_loffset;
2827 			error = rp->r_error;
2828 			goto bottom;
2829 		}
2830 
2831 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2832 		base = kmem_alloc(bufsize, KM_SLEEP);
2833 		do {
2834 			if (ioflag & FDSYNC)
2835 				stab_comm = DATA_SYNC4;
2836 			else
2837 				stab_comm = FILE_SYNC4;
2838 			resid = uiop->uio_resid;
2839 			offset = uiop->uio_loffset;
2840 			count = MIN(uiop->uio_resid, bufsize);
2841 			org_offset = uiop->uio_loffset;
2842 			error = uiomove(base, count, UIO_WRITE, uiop);
2843 			if (!error) {
2844 				error = nfs4write(vp, base, org_offset,
2845 				    count, cr, &stab_comm);
2846 				if (!error) {
2847 					mutex_enter(&rp->r_statelock);
2848 					if (rp->r_size < uiop->uio_loffset)
2849 						rp->r_size = uiop->uio_loffset;
2850 					mutex_exit(&rp->r_statelock);
2851 				}
2852 			}
2853 		} while (!error && uiop->uio_resid > 0);
2854 		kmem_free(base, bufsize);
2855 		goto bottom;
2856 	}
2857 
2858 	bsize = vp->v_vfsp->vfs_bsize;
2859 
2860 	do {
2861 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2862 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2863 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2864 
2865 		resid = uiop->uio_resid;
2866 		offset = uiop->uio_loffset;
2867 
2868 		if (rp->r_flags & R4STALE) {
2869 			error = rp->r_error;
2870 			break;
2871 		}
2872 
2873 		/*
2874 		 * Don't create dirty pages faster than they
2875 		 * can be cleaned so that the system doesn't
2876 		 * get imbalanced.  If the async queue is
2877 		 * maxed out, then wait for it to drain before
2878 		 * creating more dirty pages.  Also, wait for
2879 		 * any threads doing pagewalks in the vop_getattr
2880 		 * entry points so that they don't block for
2881 		 * long periods.
2882 		 */
2883 		mutex_enter(&rp->r_statelock);
2884 		while ((mi->mi_max_threads != 0 &&
2885 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2886 		    rp->r_gcount > 0)
2887 			cv_wait(&rp->r_cv, &rp->r_statelock);
2888 		mutex_exit(&rp->r_statelock);
2889 
2890 		if (vpm_enable) {
2891 			/*
2892 			 * It will use kpm mappings, so no need to
2893 			 * pass an address.
2894 			 */
2895 			error = writerp4(rp, NULL, n, uiop, 0);
2896 		} else  {
2897 			if (segmap_kpm) {
2898 				int pon = uiop->uio_loffset & PAGEOFFSET;
2899 				size_t pn = MIN(PAGESIZE - pon,
2900 				    uiop->uio_resid);
2901 				int pagecreate;
2902 
2903 				mutex_enter(&rp->r_statelock);
2904 				pagecreate = (pon == 0) && (pn == PAGESIZE ||
2905 				    uiop->uio_loffset + pn >= rp->r_size);
2906 				mutex_exit(&rp->r_statelock);
2907 
2908 				base = segmap_getmapflt(segkmap, vp, off + on,
2909 				    pn, !pagecreate, S_WRITE);
2910 
2911 				error = writerp4(rp, base + pon, n, uiop,
2912 				    pagecreate);
2913 
2914 			} else {
2915 				base = segmap_getmapflt(segkmap, vp, off + on,
2916 				    n, 0, S_READ);
2917 				error = writerp4(rp, base + on, n, uiop, 0);
2918 			}
2919 		}
2920 
2921 		if (!error) {
2922 			if (mi->mi_flags & MI4_NOAC)
2923 				flags = SM_WRITE;
2924 			else if ((uiop->uio_loffset % bsize) == 0 ||
2925 			    IS_SWAPVP(vp)) {
2926 				/*
2927 				 * Have written a whole block.
2928 				 * Start an asynchronous write
2929 				 * and mark the buffer to
2930 				 * indicate that it won't be
2931 				 * needed again soon.
2932 				 */
2933 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
2934 			} else
2935 				flags = 0;
2936 			if ((ioflag & (FSYNC|FDSYNC)) ||
2937 			    (rp->r_flags & R4OUTOFSPACE)) {
2938 				flags &= ~SM_ASYNC;
2939 				flags |= SM_WRITE;
2940 			}
2941 			if (vpm_enable) {
2942 				error = vpm_sync_pages(vp, off, n, flags);
2943 			} else {
2944 				error = segmap_release(segkmap, base, flags);
2945 			}
2946 		} else {
2947 			if (vpm_enable) {
2948 				(void) vpm_sync_pages(vp, off, n, 0);
2949 			} else {
2950 				(void) segmap_release(segkmap, base, 0);
2951 			}
2952 			/*
2953 			 * In the event that we got an access error while
2954 			 * faulting in a page for a write-only file just
2955 			 * force a write.
2956 			 */
2957 			if (error == EACCES)
2958 				goto nfs4_fwrite;
2959 		}
2960 	} while (!error && uiop->uio_resid > 0);
2961 
2962 bottom:
2963 	if (error) {
2964 		uiop->uio_resid = resid + remainder;
2965 		uiop->uio_loffset = offset;
2966 	} else {
2967 		uiop->uio_resid += remainder;
2968 
2969 		mutex_enter(&rp->r_statev4_lock);
2970 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
2971 			gethrestime(&rp->r_attr.va_mtime);
2972 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
2973 		}
2974 		mutex_exit(&rp->r_statev4_lock);
2975 	}
2976 
2977 	nfs_rw_exit(&rp->r_lkserlock);
2978 
2979 	return (error);
2980 }
2981 
2982 /*
2983  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
2984  */
2985 static int
2986 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
2987     int flags, cred_t *cr)
2988 {
2989 	struct buf *bp;
2990 	int error;
2991 	page_t *savepp;
2992 	uchar_t fsdata;
2993 	stable_how4 stab_comm;
2994 
2995 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
2996 	bp = pageio_setup(pp, len, vp, flags);
2997 	ASSERT(bp != NULL);
2998 
2999 	/*
3000 	 * pageio_setup should have set b_addr to 0.  This
3001 	 * is correct since we want to do I/O on a page
3002 	 * boundary.  bp_mapin will use this addr to calculate
3003 	 * an offset, and then set b_addr to the kernel virtual
3004 	 * address it allocated for us.
3005 	 */
3006 	ASSERT(bp->b_un.b_addr == 0);
3007 
3008 	bp->b_edev = 0;
3009 	bp->b_dev = 0;
3010 	bp->b_lblkno = lbtodb(off);
3011 	bp->b_file = vp;
3012 	bp->b_offset = (offset_t)off;
3013 	bp_mapin(bp);
3014 
3015 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
3016 	    freemem > desfree)
3017 		stab_comm = UNSTABLE4;
3018 	else
3019 		stab_comm = FILE_SYNC4;
3020 
3021 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
3022 
3023 	bp_mapout(bp);
3024 	pageio_done(bp);
3025 
3026 	if (stab_comm == UNSTABLE4)
3027 		fsdata = C_DELAYCOMMIT;
3028 	else
3029 		fsdata = C_NOCOMMIT;
3030 
3031 	savepp = pp;
3032 	do {
3033 		pp->p_fsdata = fsdata;
3034 	} while ((pp = pp->p_next) != savepp);
3035 
3036 	return (error);
3037 }
3038 
3039 /*
3040  */
3041 static int
3042 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
3043 {
3044 	nfs4_open_owner_t	*oop;
3045 	nfs4_open_stream_t	*osp;
3046 	rnode4_t		*rp = VTOR4(vp);
3047 	mntinfo4_t 		*mi = VTOMI4(vp);
3048 	int 			reopen_needed;
3049 
3050 	ASSERT(nfs_zone() == mi->mi_zone);
3051 
3052 
3053 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
3054 	if (!oop)
3055 		return (EIO);
3056 
3057 	/* returns with 'os_sync_lock' held */
3058 	osp = find_open_stream(oop, rp);
3059 	if (!osp) {
3060 		open_owner_rele(oop);
3061 		return (EIO);
3062 	}
3063 
3064 	if (osp->os_failed_reopen) {
3065 		mutex_exit(&osp->os_sync_lock);
3066 		open_stream_rele(osp, rp);
3067 		open_owner_rele(oop);
3068 		return (EIO);
3069 	}
3070 
3071 	/*
3072 	 * Determine whether a reopen is needed.  If this
3073 	 * is a delegation open stream, then the os_delegation bit
3074 	 * should be set.
3075 	 */
3076 
3077 	reopen_needed = osp->os_delegation;
3078 
3079 	mutex_exit(&osp->os_sync_lock);
3080 	open_owner_rele(oop);
3081 
3082 	if (reopen_needed) {
3083 		nfs4_error_zinit(ep);
3084 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
3085 		mutex_enter(&osp->os_sync_lock);
3086 		if (ep->error || ep->stat || osp->os_failed_reopen) {
3087 			mutex_exit(&osp->os_sync_lock);
3088 			open_stream_rele(osp, rp);
3089 			return (EIO);
3090 		}
3091 		mutex_exit(&osp->os_sync_lock);
3092 	}
3093 	open_stream_rele(osp, rp);
3094 
3095 	return (0);
3096 }
3097 
3098 /*
3099  * Write to file.  Writes to remote server in largest size
3100  * chunks that the server can handle.  Write is synchronous.
3101  */
3102 static int
3103 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3104     stable_how4 *stab_comm)
3105 {
3106 	mntinfo4_t *mi;
3107 	COMPOUND4args_clnt args;
3108 	COMPOUND4res_clnt res;
3109 	WRITE4args *wargs;
3110 	WRITE4res *wres;
3111 	nfs_argop4 argop[2];
3112 	nfs_resop4 *resop;
3113 	int tsize;
3114 	stable_how4 stable;
3115 	rnode4_t *rp;
3116 	int doqueue = 1;
3117 	bool_t needrecov;
3118 	nfs4_recov_state_t recov_state;
3119 	nfs4_stateid_types_t sid_types;
3120 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3121 
3122 	rp = VTOR4(vp);
3123 	mi = VTOMI4(vp);
3124 
3125 	ASSERT(nfs_zone() == mi->mi_zone);
3126 
3127 	stable = *stab_comm;
3128 	*stab_comm = FILE_SYNC4;
3129 
3130 	needrecov = FALSE;
3131 	recov_state.rs_flags = 0;
3132 	recov_state.rs_num_retry_despite_err = 0;
3133 	nfs4_init_stateid_types(&sid_types);
3134 
3135 recov_retry:
3136 	args.ctag = TAG_WRITE;
3137 	args.array_len = 2;
3138 	args.array = argop;
3139 
3140 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3141 	    &recov_state, NULL);
3142 	if (e.error)
3143 		return (e.error);
3144 
3145 	/* 0. putfh target fh */
3146 	argop[0].argop = OP_CPUTFH;
3147 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3148 
3149 	/* 1. write */
3150 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3151 
3152 	do {
3153 
3154 		wargs->offset = (offset4)offset;
3155 		wargs->data_val = base;
3156 
3157 		if (mi->mi_io_kstats) {
3158 			mutex_enter(&mi->mi_lock);
3159 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3160 			mutex_exit(&mi->mi_lock);
3161 		}
3162 
3163 		if ((vp->v_flag & VNOCACHE) ||
3164 		    (rp->r_flags & R4DIRECTIO) ||
3165 		    (mi->mi_flags & MI4_DIRECTIO))
3166 			tsize = MIN(mi->mi_stsize, count);
3167 		else
3168 			tsize = MIN(mi->mi_curwrite, count);
3169 		wargs->data_len = (uint_t)tsize;
3170 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3171 
3172 		if (mi->mi_io_kstats) {
3173 			mutex_enter(&mi->mi_lock);
3174 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3175 			mutex_exit(&mi->mi_lock);
3176 		}
3177 
3178 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3179 		if (e.error && !needrecov) {
3180 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3181 			    &recov_state, needrecov);
3182 			return (e.error);
3183 		}
3184 
3185 
3186 		/*
3187 		 * Do handling of OLD_STATEID outside
3188 		 * of the normal recovery framework.
3189 		 *
3190 		 * If write receives a BAD stateid error while using a
3191 		 * delegation stateid, retry using the open stateid (if it
3192 		 * exists).  If it doesn't have an open stateid, reopen the
3193 		 * file first, then retry.
3194 		 */
3195 		if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3196 		    sid_types.cur_sid_type != SPEC_SID) {
3197 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3198 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3199 			    &recov_state, needrecov);
3200 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3201 			goto recov_retry;
3202 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3203 		    sid_types.cur_sid_type == DEL_SID) {
3204 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3205 			mutex_enter(&rp->r_statev4_lock);
3206 			rp->r_deleg_return_pending = TRUE;
3207 			mutex_exit(&rp->r_statev4_lock);
3208 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3209 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3210 				    &recov_state, needrecov);
3211 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3212 				    (caddr_t)&res);
3213 				return (EIO);
3214 			}
3215 			nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3216 			    &recov_state, needrecov);
3217 			/* hold needed for nfs4delegreturn_thread */
3218 			VN_HOLD(vp);
3219 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3220 			    NFS4_DR_DISCARD), FALSE);
3221 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3222 			goto recov_retry;
3223 		}
3224 
3225 		if (needrecov) {
3226 			bool_t abort;
3227 
3228 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3229 			    "nfs4write: client got error %d, res.status %d"
3230 			    ", so start recovery", e.error, res.status));
3231 
3232 			abort = nfs4_start_recovery(&e,
3233 			    VTOMI4(vp), vp, NULL, &wargs->stateid,
3234 			    NULL, OP_WRITE, NULL);
3235 			if (!e.error) {
3236 				e.error = geterrno4(res.status);
3237 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3238 				    (caddr_t)&res);
3239 			}
3240 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3241 			    &recov_state, needrecov);
3242 			if (abort == FALSE)
3243 				goto recov_retry;
3244 			return (e.error);
3245 		}
3246 
3247 		if (res.status) {
3248 			e.error = geterrno4(res.status);
3249 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3250 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3251 			    &recov_state, needrecov);
3252 			return (e.error);
3253 		}
3254 
3255 		resop = &res.array[1];	/* write res */
3256 		wres = &resop->nfs_resop4_u.opwrite;
3257 
3258 		if ((int)wres->count > tsize) {
3259 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3260 
3261 			zcmn_err(getzoneid(), CE_WARN,
3262 			    "nfs4write: server wrote %u, requested was %u",
3263 			    (int)wres->count, tsize);
3264 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3265 			    &recov_state, needrecov);
3266 			return (EIO);
3267 		}
3268 		if (wres->committed == UNSTABLE4) {
3269 			*stab_comm = UNSTABLE4;
3270 			if (wargs->stable == DATA_SYNC4 ||
3271 			    wargs->stable == FILE_SYNC4) {
3272 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3273 				    (caddr_t)&res);
3274 				zcmn_err(getzoneid(), CE_WARN,
3275 				    "nfs4write: server %s did not commit "
3276 				    "to stable storage",
3277 				    rp->r_server->sv_hostname);
3278 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3279 				    &recov_state, needrecov);
3280 				return (EIO);
3281 			}
3282 		}
3283 
3284 		tsize = (int)wres->count;
3285 		count -= tsize;
3286 		base += tsize;
3287 		offset += tsize;
3288 		if (mi->mi_io_kstats) {
3289 			mutex_enter(&mi->mi_lock);
3290 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3291 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3292 			    tsize;
3293 			mutex_exit(&mi->mi_lock);
3294 		}
3295 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3296 		mutex_enter(&rp->r_statelock);
3297 		if (rp->r_flags & R4HAVEVERF) {
3298 			if (rp->r_writeverf != wres->writeverf) {
3299 				nfs4_set_mod(vp);
3300 				rp->r_writeverf = wres->writeverf;
3301 			}
3302 		} else {
3303 			rp->r_writeverf = wres->writeverf;
3304 			rp->r_flags |= R4HAVEVERF;
3305 		}
3306 		PURGE_ATTRCACHE4_LOCKED(rp);
3307 		rp->r_flags |= R4WRITEMODIFIED;
3308 		gethrestime(&rp->r_attr.va_mtime);
3309 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3310 		mutex_exit(&rp->r_statelock);
3311 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3312 	} while (count);
3313 
3314 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state, needrecov);
3315 
3316 	return (e.error);
3317 }
3318 
3319 /*
3320  * Read from a file.  Reads data in largest chunks our interface can handle.
3321  */
3322 static int
3323 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3324     size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3325 {
3326 	mntinfo4_t *mi;
3327 	COMPOUND4args_clnt args;
3328 	COMPOUND4res_clnt res;
3329 	READ4args *rargs;
3330 	nfs_argop4 argop[2];
3331 	int tsize;
3332 	int doqueue;
3333 	rnode4_t *rp;
3334 	int data_len;
3335 	bool_t is_eof;
3336 	bool_t needrecov = FALSE;
3337 	nfs4_recov_state_t recov_state;
3338 	nfs4_stateid_types_t sid_types;
3339 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3340 
3341 	rp = VTOR4(vp);
3342 	mi = VTOMI4(vp);
3343 	doqueue = 1;
3344 
3345 	ASSERT(nfs_zone() == mi->mi_zone);
3346 
3347 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3348 
3349 	args.array_len = 2;
3350 	args.array = argop;
3351 
3352 	nfs4_init_stateid_types(&sid_types);
3353 
3354 	recov_state.rs_flags = 0;
3355 	recov_state.rs_num_retry_despite_err = 0;
3356 
3357 recov_retry:
3358 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3359 	    &recov_state, NULL);
3360 	if (e.error)
3361 		return (e.error);
3362 
3363 	/* putfh target fh */
3364 	argop[0].argop = OP_CPUTFH;
3365 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3366 
3367 	/* read */
3368 	argop[1].argop = OP_READ;
3369 	rargs = &argop[1].nfs_argop4_u.opread;
3370 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3371 	    OP_READ, &sid_types, async);
3372 
3373 	do {
3374 		if (mi->mi_io_kstats) {
3375 			mutex_enter(&mi->mi_lock);
3376 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3377 			mutex_exit(&mi->mi_lock);
3378 		}
3379 
3380 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3381 		    "nfs4read: %s call, rp %s",
3382 		    needrecov ? "recov" : "first",
3383 		    rnode4info(rp)));
3384 
3385 		if ((vp->v_flag & VNOCACHE) ||
3386 		    (rp->r_flags & R4DIRECTIO) ||
3387 		    (mi->mi_flags & MI4_DIRECTIO))
3388 			tsize = MIN(mi->mi_tsize, count);
3389 		else
3390 			tsize = MIN(mi->mi_curread, count);
3391 		rargs->offset = (offset4)offset;
3392 		rargs->count = (count4)tsize;
3393 		rargs->res_data_val_alt = NULL;
3394 		rargs->res_mblk = NULL;
3395 		rargs->res_uiop = NULL;
3396 		rargs->res_maxsize = 0;
3397 		if (uiop)
3398 			rargs->res_uiop = uiop;
3399 		else
3400 			rargs->res_data_val_alt = base;
3401 		rargs->res_maxsize = tsize;
3402 
3403 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3404 #ifdef	DEBUG
3405 		if (nfs4read_error_inject) {
3406 			res.status = nfs4read_error_inject;
3407 			nfs4read_error_inject = 0;
3408 		}
3409 #endif
3410 
3411 		if (mi->mi_io_kstats) {
3412 			mutex_enter(&mi->mi_lock);
3413 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3414 			mutex_exit(&mi->mi_lock);
3415 		}
3416 
3417 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3418 		if (e.error != 0 && !needrecov) {
3419 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3420 			    &recov_state, needrecov);
3421 			return (e.error);
3422 		}
3423 
3424 		/*
3425 		 * Do proper retry for OLD and BAD stateid errors outside
3426 		 * of the normal recovery framework.  There are two differences
3427 		 * between async and sync reads.  The first is that we allow
3428 		 * retry on BAD_STATEID for async reads, but not sync reads.
3429 		 * The second is that we mark the file dead for a failed
3430 		 * attempt with a special stateid for sync reads, but just
3431 		 * return EIO for async reads.
3432 		 *
3433 		 * If a sync read receives a BAD stateid error while using a
3434 		 * delegation stateid, retry using the open stateid (if it
3435 		 * exists).  If it doesn't have an open stateid, reopen the
3436 		 * file first, then retry.
3437 		 */
3438 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3439 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3440 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3441 			    &recov_state, needrecov);
3442 			if (sid_types.cur_sid_type == SPEC_SID) {
3443 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3444 				    (caddr_t)&res);
3445 				return (EIO);
3446 			}
3447 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3448 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3449 			goto recov_retry;
3450 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3451 		    !async && sid_types.cur_sid_type != SPEC_SID) {
3452 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3453 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3454 			    &recov_state, needrecov);
3455 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3456 			goto recov_retry;
3457 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3458 		    sid_types.cur_sid_type == DEL_SID) {
3459 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3460 			mutex_enter(&rp->r_statev4_lock);
3461 			rp->r_deleg_return_pending = TRUE;
3462 			mutex_exit(&rp->r_statev4_lock);
3463 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3464 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3465 				    &recov_state, needrecov);
3466 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3467 				    (caddr_t)&res);
3468 				return (EIO);
3469 			}
3470 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3471 			    &recov_state, needrecov);
3472 			/* hold needed for nfs4delegreturn_thread */
3473 			VN_HOLD(vp);
3474 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3475 			    NFS4_DR_DISCARD), FALSE);
3476 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3477 			goto recov_retry;
3478 		}
3479 		if (needrecov) {
3480 			bool_t abort;
3481 
3482 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3483 			    "nfs4read: initiating recovery\n"));
3484 
3485 			abort = nfs4_start_recovery(&e,
3486 			    mi, vp, NULL, &rargs->stateid,
3487 			    NULL, OP_READ, NULL);
3488 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3489 			    &recov_state, needrecov);
3490 			/*
3491 			 * Do not retry if we got OLD_STATEID using a special
3492 			 * stateid.  This avoids looping with a broken server.
3493 			 */
3494 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3495 			    sid_types.cur_sid_type == SPEC_SID)
3496 				abort = TRUE;
3497 
3498 			if (abort == FALSE) {
3499 				/*
3500 				 * Need to retry all possible stateids in
3501 				 * case the recovery error wasn't stateid
3502 				 * related or the stateids have become
3503 				 * stale (server reboot).
3504 				 */
3505 				nfs4_init_stateid_types(&sid_types);
3506 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3507 				    (caddr_t)&res);
3508 				goto recov_retry;
3509 			}
3510 
3511 			if (!e.error) {
3512 				e.error = geterrno4(res.status);
3513 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3514 				    (caddr_t)&res);
3515 			}
3516 			return (e.error);
3517 		}
3518 
3519 		if (res.status) {
3520 			e.error = geterrno4(res.status);
3521 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3522 			    &recov_state, needrecov);
3523 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3524 			return (e.error);
3525 		}
3526 
3527 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3528 		count -= data_len;
3529 		if (base)
3530 			base += data_len;
3531 		offset += data_len;
3532 		if (mi->mi_io_kstats) {
3533 			mutex_enter(&mi->mi_lock);
3534 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3535 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3536 			mutex_exit(&mi->mi_lock);
3537 		}
3538 		lwp_stat_update(LWP_STAT_INBLK, 1);
3539 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3540 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3541 
3542 	} while (count && !is_eof);
3543 
3544 	*residp = count;
3545 
3546 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3547 
3548 	return (e.error);
3549 }
3550 
3551 /* ARGSUSED */
3552 static int
3553 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp,
3554 	caller_context_t *ct)
3555 {
3556 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3557 		return (EIO);
3558 	switch (cmd) {
3559 		case _FIODIRECTIO:
3560 			return (nfs4_directio(vp, (int)arg, cr));
3561 		default:
3562 			return (ENOTTY);
3563 	}
3564 }
3565 
3566 /* ARGSUSED */
3567 int
3568 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3569     caller_context_t *ct)
3570 {
3571 	int error;
3572 	rnode4_t *rp = VTOR4(vp);
3573 
3574 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3575 		return (EIO);
3576 	/*
3577 	 * If it has been specified that the return value will
3578 	 * just be used as a hint, and we are only being asked
3579 	 * for size, fsid or rdevid, then return the client's
3580 	 * notion of these values without checking to make sure
3581 	 * that the attribute cache is up to date.
3582 	 * The whole point is to avoid an over the wire GETATTR
3583 	 * call.
3584 	 */
3585 	if (flags & ATTR_HINT) {
3586 		if (vap->va_mask ==
3587 		    (vap->va_mask & (AT_SIZE | AT_FSID | AT_RDEV))) {
3588 			mutex_enter(&rp->r_statelock);
3589 			if (vap->va_mask | AT_SIZE)
3590 				vap->va_size = rp->r_size;
3591 			if (vap->va_mask | AT_FSID)
3592 				vap->va_fsid = rp->r_attr.va_fsid;
3593 			if (vap->va_mask | AT_RDEV)
3594 				vap->va_rdev = rp->r_attr.va_rdev;
3595 			mutex_exit(&rp->r_statelock);
3596 			return (0);
3597 		}
3598 	}
3599 
3600 	/*
3601 	 * Only need to flush pages if asking for the mtime
3602 	 * and if there any dirty pages or any outstanding
3603 	 * asynchronous (write) requests for this file.
3604 	 */
3605 	if (vap->va_mask & AT_MTIME) {
3606 		rp = VTOR4(vp);
3607 		if (nfs4_has_pages(vp)) {
3608 			mutex_enter(&rp->r_statev4_lock);
3609 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3610 				mutex_exit(&rp->r_statev4_lock);
3611 				if (rp->r_flags & R4DIRTY ||
3612 				    rp->r_awcount > 0) {
3613 					mutex_enter(&rp->r_statelock);
3614 					rp->r_gcount++;
3615 					mutex_exit(&rp->r_statelock);
3616 					error =
3617 					    nfs4_putpage(vp, (u_offset_t)0,
3618 					    0, 0, cr, NULL);
3619 					mutex_enter(&rp->r_statelock);
3620 					if (error && (error == ENOSPC ||
3621 					    error == EDQUOT)) {
3622 						if (!rp->r_error)
3623 							rp->r_error = error;
3624 					}
3625 					if (--rp->r_gcount == 0)
3626 						cv_broadcast(&rp->r_cv);
3627 					mutex_exit(&rp->r_statelock);
3628 				}
3629 			} else {
3630 				mutex_exit(&rp->r_statev4_lock);
3631 			}
3632 		}
3633 	}
3634 	return (nfs4getattr(vp, vap, cr));
3635 }
3636 
3637 int
3638 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3639 {
3640 	/*
3641 	 * If these are the only two bits cleared
3642 	 * on the server then return 0 (OK) else
3643 	 * return 1 (BAD).
3644 	 */
3645 	on_client &= ~(S_ISUID|S_ISGID);
3646 	if (on_client == from_server)
3647 		return (0);
3648 	else
3649 		return (1);
3650 }
3651 
3652 /*ARGSUSED4*/
3653 static int
3654 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3655     caller_context_t *ct)
3656 {
3657 	if (vap->va_mask & AT_NOSET)
3658 		return (EINVAL);
3659 
3660 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3661 		return (EIO);
3662 
3663 	/*
3664 	 * Don't call secpolicy_vnode_setattr, the client cannot
3665 	 * use its cached attributes to make security decisions
3666 	 * as the server may be faking mode bits or mapping uid/gid.
3667 	 * Always just let the server to the checking.
3668 	 * If we provide the ability to remove basic priviledges
3669 	 * to setattr (e.g. basic without chmod) then we will
3670 	 * need to add a check here before calling the server.
3671 	 */
3672 
3673 	return (nfs4setattr(vp, vap, flags, cr, NULL));
3674 }
3675 
3676 /*
3677  * To replace the "guarded" version 3 setattr, we use two types of compound
3678  * setattr requests:
3679  * 1. The "normal" setattr, used when the size of the file isn't being
3680  *    changed - { Putfh <fh>; Setattr; Getattr }/
3681  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3682  *    with only ctime as the argument. If the server ctime differs from
3683  *    what is cached on the client, the verify will fail, but we would
3684  *    already have the ctime from the preceding getattr, so just set it
3685  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3686  *	Setattr; Getattr }.
3687  *
3688  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3689  * this setattr and NULL if they are not.
3690  */
3691 static int
3692 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3693     vsecattr_t *vsap)
3694 {
3695 	COMPOUND4args_clnt args;
3696 	COMPOUND4res_clnt res, *resp = NULL;
3697 	nfs4_ga_res_t *garp = NULL;
3698 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3699 	nfs_argop4 argop[5];
3700 	int verify_argop = -1;
3701 	int setattr_argop = 1;
3702 	nfs_resop4 *resop;
3703 	vattr_t va;
3704 	rnode4_t *rp;
3705 	int doqueue = 1;
3706 	uint_t mask = vap->va_mask;
3707 	mode_t omode;
3708 	vsecattr_t *vsp;
3709 	timestruc_t ctime;
3710 	bool_t needrecov = FALSE;
3711 	nfs4_recov_state_t recov_state;
3712 	nfs4_stateid_types_t sid_types;
3713 	stateid4 stateid;
3714 	hrtime_t t;
3715 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3716 	servinfo4_t *svp;
3717 	bitmap4 supp_attrs;
3718 
3719 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3720 	rp = VTOR4(vp);
3721 	nfs4_init_stateid_types(&sid_types);
3722 
3723 	/*
3724 	 * Only need to flush pages if there are any pages and
3725 	 * if the file is marked as dirty in some fashion.  The
3726 	 * file must be flushed so that we can accurately
3727 	 * determine the size of the file and the cached data
3728 	 * after the SETATTR returns.  A file is considered to
3729 	 * be dirty if it is either marked with R4DIRTY, has
3730 	 * outstanding i/o's active, or is mmap'd.  In this
3731 	 * last case, we can't tell whether there are dirty
3732 	 * pages, so we flush just to be sure.
3733 	 */
3734 	if (nfs4_has_pages(vp) &&
3735 	    ((rp->r_flags & R4DIRTY) ||
3736 	    rp->r_count > 0 ||
3737 	    rp->r_mapcnt > 0)) {
3738 		ASSERT(vp->v_type != VCHR);
3739 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr, NULL);
3740 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3741 			mutex_enter(&rp->r_statelock);
3742 			if (!rp->r_error)
3743 				rp->r_error = e.error;
3744 			mutex_exit(&rp->r_statelock);
3745 		}
3746 	}
3747 
3748 	if (mask & AT_SIZE) {
3749 		/*
3750 		 * Verification setattr compound for non-deleg AT_SIZE:
3751 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3752 		 * Set ctime local here (outside the do_again label)
3753 		 * so that subsequent retries (after failed VERIFY)
3754 		 * will use ctime from GETATTR results (from failed
3755 		 * verify compound) as VERIFY arg.
3756 		 * If file has delegation, then VERIFY(time_metadata)
3757 		 * is of little added value, so don't bother.
3758 		 */
3759 		mutex_enter(&rp->r_statev4_lock);
3760 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3761 		    rp->r_deleg_return_pending) {
3762 			numops = 5;
3763 			ctime = rp->r_attr.va_ctime;
3764 		}
3765 		mutex_exit(&rp->r_statev4_lock);
3766 	}
3767 
3768 	recov_state.rs_flags = 0;
3769 	recov_state.rs_num_retry_despite_err = 0;
3770 
3771 	args.ctag = TAG_SETATTR;
3772 do_again:
3773 recov_retry:
3774 	setattr_argop = numops - 2;
3775 
3776 	args.array = argop;
3777 	args.array_len = numops;
3778 
3779 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3780 	if (e.error)
3781 		return (e.error);
3782 
3783 
3784 	/* putfh target fh */
3785 	argop[0].argop = OP_CPUTFH;
3786 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3787 
3788 	if (numops == 5) {
3789 		/*
3790 		 * We only care about the ctime, but need to get mtime
3791 		 * and size for proper cache update.
3792 		 */
3793 		/* getattr */
3794 		argop[1].argop = OP_GETATTR;
3795 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3796 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3797 
3798 		/* verify - set later in loop */
3799 		verify_argop = 2;
3800 	}
3801 
3802 	/* setattr */
3803 	svp = rp->r_server;
3804 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3805 	supp_attrs = svp->sv_supp_attrs;
3806 	nfs_rw_exit(&svp->sv_lock);
3807 
3808 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3809 	    supp_attrs, &e.error, &sid_types);
3810 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3811 	if (e.error) {
3812 		/* req time field(s) overflow - return immediately */
3813 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3814 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3815 		    opsetattr.obj_attributes);
3816 		return (e.error);
3817 	}
3818 	omode = rp->r_attr.va_mode;
3819 
3820 	/* getattr */
3821 	argop[numops-1].argop = OP_GETATTR;
3822 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3823 	/*
3824 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3825 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3826 	 * used in updating the ACL cache.
3827 	 */
3828 	if (vsap != NULL)
3829 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3830 		    FATTR4_ACL_MASK;
3831 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3832 
3833 	/*
3834 	 * setattr iterates if the object size is set and the cached ctime
3835 	 * does not match the file ctime. In that case, verify the ctime first.
3836 	 */
3837 
3838 	do {
3839 		if (verify_argop != -1) {
3840 			/*
3841 			 * Verify that the ctime match before doing setattr.
3842 			 */
3843 			va.va_mask = AT_CTIME;
3844 			va.va_ctime = ctime;
3845 			svp = rp->r_server;
3846 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3847 			supp_attrs = svp->sv_supp_attrs;
3848 			nfs_rw_exit(&svp->sv_lock);
3849 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3850 			    OP_VERIFY, supp_attrs);
3851 			if (e.error) {
3852 				/* req time field(s) overflow - return */
3853 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3854 				    needrecov);
3855 				break;
3856 			}
3857 		}
3858 
3859 		doqueue = 1;
3860 
3861 		t = gethrtime();
3862 
3863 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3864 
3865 		/*
3866 		 * Purge the access cache and ACL cache if changing either the
3867 		 * owner of the file, the group owner, or the mode.  These may
3868 		 * change the access permissions of the file, so purge old
3869 		 * information and start over again.
3870 		 */
3871 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3872 			(void) nfs4_access_purge_rp(rp);
3873 			if (rp->r_secattr != NULL) {
3874 				mutex_enter(&rp->r_statelock);
3875 				vsp = rp->r_secattr;
3876 				rp->r_secattr = NULL;
3877 				mutex_exit(&rp->r_statelock);
3878 				if (vsp != NULL)
3879 					nfs4_acl_free_cache(vsp);
3880 			}
3881 		}
3882 
3883 		/*
3884 		 * If res.array_len == numops, then everything succeeded,
3885 		 * except for possibly the final getattr.  If only the
3886 		 * last getattr failed, give up, and don't try recovery.
3887 		 */
3888 		if (res.array_len == numops) {
3889 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3890 			    needrecov);
3891 			if (! e.error)
3892 				resp = &res;
3893 			break;
3894 		}
3895 
3896 		/*
3897 		 * if either rpc call failed or completely succeeded - done
3898 		 */
3899 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
3900 		if (e.error) {
3901 			PURGE_ATTRCACHE4(vp);
3902 			if (!needrecov) {
3903 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3904 				    needrecov);
3905 				break;
3906 			}
3907 		}
3908 
3909 		/*
3910 		 * Do proper retry for OLD_STATEID outside of the normal
3911 		 * recovery framework.
3912 		 */
3913 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3914 		    sid_types.cur_sid_type != SPEC_SID &&
3915 		    sid_types.cur_sid_type != NO_SID) {
3916 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3917 			    needrecov);
3918 			nfs4_save_stateid(&stateid, &sid_types);
3919 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3920 			    opsetattr.obj_attributes);
3921 			if (verify_argop != -1) {
3922 				nfs4args_verify_free(&argop[verify_argop]);
3923 				verify_argop = -1;
3924 			}
3925 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3926 			goto recov_retry;
3927 		}
3928 
3929 		if (needrecov) {
3930 			bool_t abort;
3931 
3932 			abort = nfs4_start_recovery(&e,
3933 			    VTOMI4(vp), vp, NULL, NULL, NULL,
3934 			    OP_SETATTR, NULL);
3935 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3936 			    needrecov);
3937 			/*
3938 			 * Do not retry if we failed with OLD_STATEID using
3939 			 * a special stateid.  This is done to avoid looping
3940 			 * with a broken server.
3941 			 */
3942 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3943 			    (sid_types.cur_sid_type == SPEC_SID ||
3944 			    sid_types.cur_sid_type == NO_SID))
3945 				abort = TRUE;
3946 			if (!e.error) {
3947 				if (res.status == NFS4ERR_BADOWNER)
3948 					nfs4_log_badowner(VTOMI4(vp),
3949 					    OP_SETATTR);
3950 
3951 				e.error = geterrno4(res.status);
3952 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3953 				    (caddr_t)&res);
3954 			}
3955 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3956 			    opsetattr.obj_attributes);
3957 			if (verify_argop != -1) {
3958 				nfs4args_verify_free(&argop[verify_argop]);
3959 				verify_argop = -1;
3960 			}
3961 			if (abort == FALSE) {
3962 				/*
3963 				 * Need to retry all possible stateids in
3964 				 * case the recovery error wasn't stateid
3965 				 * related or the stateids have become
3966 				 * stale (server reboot).
3967 				 */
3968 				nfs4_init_stateid_types(&sid_types);
3969 				goto recov_retry;
3970 			}
3971 			return (e.error);
3972 		}
3973 
3974 		/*
3975 		 * Need to call nfs4_end_op before nfs4getattr to
3976 		 * avoid potential nfs4_start_op deadlock. See RFE
3977 		 * 4777612.  Calls to nfs4_invalidate_pages() and
3978 		 * nfs4_purge_stale_fh() might also generate over the
3979 		 * wire calls which my cause nfs4_start_op() deadlock.
3980 		 */
3981 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3982 
3983 		/*
3984 		 * Check to update lease.
3985 		 */
3986 		resp = &res;
3987 		if (res.status == NFS4_OK) {
3988 			break;
3989 		}
3990 
3991 		/*
3992 		 * Check if verify failed to see if try again
3993 		 */
3994 		if ((verify_argop == -1) || (res.array_len != 3)) {
3995 			/*
3996 			 * can't continue...
3997 			 */
3998 			if (res.status == NFS4ERR_BADOWNER)
3999 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
4000 
4001 			e.error = geterrno4(res.status);
4002 		} else {
4003 			/*
4004 			 * When the verify request fails, the client ctime is
4005 			 * not in sync with the server. This is the same as
4006 			 * the version 3 "not synchronized" error, and we
4007 			 * handle it in a similar manner (XXX do we need to???).
4008 			 * Use the ctime returned in the first getattr for
4009 			 * the input to the next verify.
4010 			 * If we couldn't get the attributes, then we give up
4011 			 * because we can't complete the operation as required.
4012 			 */
4013 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
4014 		}
4015 		if (e.error) {
4016 			PURGE_ATTRCACHE4(vp);
4017 			nfs4_purge_stale_fh(e.error, vp, cr);
4018 		} else {
4019 			/*
4020 			 * retry with a new verify value
4021 			 */
4022 			ctime = garp->n4g_va.va_ctime;
4023 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4024 			resp = NULL;
4025 		}
4026 		if (!e.error) {
4027 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4028 			    opsetattr.obj_attributes);
4029 			if (verify_argop != -1) {
4030 				nfs4args_verify_free(&argop[verify_argop]);
4031 				verify_argop = -1;
4032 			}
4033 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4034 			goto do_again;
4035 		}
4036 	} while (!e.error);
4037 
4038 	if (e.error) {
4039 		/*
4040 		 * If we are here, rfs4call has an irrecoverable error - return
4041 		 */
4042 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4043 		    opsetattr.obj_attributes);
4044 		if (verify_argop != -1) {
4045 			nfs4args_verify_free(&argop[verify_argop]);
4046 			verify_argop = -1;
4047 		}
4048 		if (resp)
4049 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4050 		return (e.error);
4051 	}
4052 
4053 
4054 
4055 	/*
4056 	 * If changing the size of the file, invalidate
4057 	 * any local cached data which is no longer part
4058 	 * of the file.  We also possibly invalidate the
4059 	 * last page in the file.  We could use
4060 	 * pvn_vpzero(), but this would mark the page as
4061 	 * modified and require it to be written back to
4062 	 * the server for no particularly good reason.
4063 	 * This way, if we access it, then we bring it
4064 	 * back in.  A read should be cheaper than a
4065 	 * write.
4066 	 */
4067 	if (mask & AT_SIZE) {
4068 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
4069 	}
4070 
4071 	/* either no error or one of the postop getattr failed */
4072 
4073 	/*
4074 	 * XXX Perform a simplified version of wcc checking. Instead of
4075 	 * have another getattr to get pre-op, just purge cache if
4076 	 * any of the ops prior to and including the getattr failed.
4077 	 * If the getattr succeeded then update the attrcache accordingly.
4078 	 */
4079 
4080 	garp = NULL;
4081 	if (res.status == NFS4_OK) {
4082 		/*
4083 		 * Last getattr
4084 		 */
4085 		resop = &res.array[numops - 1];
4086 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4087 	}
4088 	/*
4089 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
4090 	 * rather than filling it.  See the function itself for details.
4091 	 */
4092 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4093 	if (garp != NULL) {
4094 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
4095 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
4096 			vs_ace4_destroy(&garp->n4g_vsa);
4097 		} else {
4098 			if (vsap != NULL) {
4099 				/*
4100 				 * The ACL was supposed to be set and to be
4101 				 * returned in the last getattr of this
4102 				 * compound, but for some reason the getattr
4103 				 * result doesn't contain the ACL.  In this
4104 				 * case, purge the ACL cache.
4105 				 */
4106 				if (rp->r_secattr != NULL) {
4107 					mutex_enter(&rp->r_statelock);
4108 					vsp = rp->r_secattr;
4109 					rp->r_secattr = NULL;
4110 					mutex_exit(&rp->r_statelock);
4111 					if (vsp != NULL)
4112 						nfs4_acl_free_cache(vsp);
4113 				}
4114 			}
4115 		}
4116 	}
4117 
4118 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4119 		/*
4120 		 * Set the size, rather than relying on getting it updated
4121 		 * via a GETATTR.  With delegations the client tries to
4122 		 * suppress GETATTR calls.
4123 		 */
4124 		mutex_enter(&rp->r_statelock);
4125 		rp->r_size = vap->va_size;
4126 		mutex_exit(&rp->r_statelock);
4127 	}
4128 
4129 	/*
4130 	 * Can free up request args and res
4131 	 */
4132 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4133 	    opsetattr.obj_attributes);
4134 	if (verify_argop != -1) {
4135 		nfs4args_verify_free(&argop[verify_argop]);
4136 		verify_argop = -1;
4137 	}
4138 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4139 
4140 	/*
4141 	 * Some servers will change the mode to clear the setuid
4142 	 * and setgid bits when changing the uid or gid.  The
4143 	 * client needs to compensate appropriately.
4144 	 */
4145 	if (mask & (AT_UID | AT_GID)) {
4146 		int terror, do_setattr;
4147 
4148 		do_setattr = 0;
4149 		va.va_mask = AT_MODE;
4150 		terror = nfs4getattr(vp, &va, cr);
4151 		if (!terror &&
4152 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4153 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4154 			va.va_mask = AT_MODE;
4155 			if (mask & AT_MODE) {
4156 				/*
4157 				 * We asked the mode to be changed and what
4158 				 * we just got from the server in getattr is
4159 				 * not what we wanted it to be, so set it now.
4160 				 */
4161 				va.va_mode = vap->va_mode;
4162 				do_setattr = 1;
4163 			} else {
4164 				/*
4165 				 * We did not ask the mode to be changed,
4166 				 * Check to see that the server just cleared
4167 				 * I_SUID and I_GUID from it. If not then
4168 				 * set mode to omode with UID/GID cleared.
4169 				 */
4170 				if (nfs4_compare_modes(va.va_mode, omode)) {
4171 					omode &= ~(S_ISUID|S_ISGID);
4172 					va.va_mode = omode;
4173 					do_setattr = 1;
4174 				}
4175 			}
4176 
4177 			if (do_setattr)
4178 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4179 		}
4180 	}
4181 
4182 	return (e.error);
4183 }
4184 
4185 /* ARGSUSED */
4186 static int
4187 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr, caller_context_t *ct)
4188 {
4189 	COMPOUND4args_clnt args;
4190 	COMPOUND4res_clnt res;
4191 	int doqueue;
4192 	uint32_t acc, resacc, argacc;
4193 	rnode4_t *rp;
4194 	cred_t *cred, *ncr, *ncrfree = NULL;
4195 	nfs4_access_type_t cacc;
4196 	int num_ops;
4197 	nfs_argop4 argop[3];
4198 	nfs_resop4 *resop;
4199 	bool_t needrecov = FALSE, do_getattr;
4200 	nfs4_recov_state_t recov_state;
4201 	int rpc_error;
4202 	hrtime_t t;
4203 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4204 	mntinfo4_t *mi = VTOMI4(vp);
4205 
4206 	if (nfs_zone() != mi->mi_zone)
4207 		return (EIO);
4208 
4209 	acc = 0;
4210 	if (mode & VREAD)
4211 		acc |= ACCESS4_READ;
4212 	if (mode & VWRITE) {
4213 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4214 			return (EROFS);
4215 		if (vp->v_type == VDIR)
4216 			acc |= ACCESS4_DELETE;
4217 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4218 	}
4219 	if (mode & VEXEC) {
4220 		if (vp->v_type == VDIR)
4221 			acc |= ACCESS4_LOOKUP;
4222 		else
4223 			acc |= ACCESS4_EXECUTE;
4224 	}
4225 
4226 	if (VTOR4(vp)->r_acache != NULL) {
4227 		e.error = nfs4_validate_caches(vp, cr);
4228 		if (e.error)
4229 			return (e.error);
4230 	}
4231 
4232 	rp = VTOR4(vp);
4233 	if (vp->v_type == VDIR)
4234 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4235 		    ACCESS4_EXTEND | ACCESS4_LOOKUP;
4236 	else
4237 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4238 		    ACCESS4_EXECUTE;
4239 	recov_state.rs_flags = 0;
4240 	recov_state.rs_num_retry_despite_err = 0;
4241 
4242 	cred = cr;
4243 	/*
4244 	 * ncr and ncrfree both initially
4245 	 * point to the memory area returned
4246 	 * by crnetadjust();
4247 	 * ncrfree not NULL when exiting means
4248 	 * that we need to release it
4249 	 */
4250 	ncr = crnetadjust(cred);
4251 	ncrfree = ncr;
4252 
4253 tryagain:
4254 	cacc = nfs4_access_check(rp, acc, cred);
4255 	if (cacc == NFS4_ACCESS_ALLOWED) {
4256 		if (ncrfree != NULL)
4257 			crfree(ncrfree);
4258 		return (0);
4259 	}
4260 	if (cacc == NFS4_ACCESS_DENIED) {
4261 		/*
4262 		 * If the cred can be adjusted, try again
4263 		 * with the new cred.
4264 		 */
4265 		if (ncr != NULL) {
4266 			cred = ncr;
4267 			ncr = NULL;
4268 			goto tryagain;
4269 		}
4270 		if (ncrfree != NULL)
4271 			crfree(ncrfree);
4272 		return (EACCES);
4273 	}
4274 
4275 recov_retry:
4276 	/*
4277 	 * Don't take with r_statev4_lock here. r_deleg_type could
4278 	 * change as soon as lock is released.  Since it is an int,
4279 	 * there is no atomicity issue.
4280 	 */
4281 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4282 	num_ops = do_getattr ? 3 : 2;
4283 
4284 	args.ctag = TAG_ACCESS;
4285 
4286 	args.array_len = num_ops;
4287 	args.array = argop;
4288 
4289 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4290 	    &recov_state, NULL)) {
4291 		if (ncrfree != NULL)
4292 			crfree(ncrfree);
4293 		return (e.error);
4294 	}
4295 
4296 	/* putfh target fh */
4297 	argop[0].argop = OP_CPUTFH;
4298 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4299 
4300 	/* access */
4301 	argop[1].argop = OP_ACCESS;
4302 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4303 
4304 	/* getattr */
4305 	if (do_getattr) {
4306 		argop[2].argop = OP_GETATTR;
4307 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4308 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4309 	}
4310 
4311 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4312 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4313 	    rnode4info(VTOR4(vp))));
4314 
4315 	doqueue = 1;
4316 	t = gethrtime();
4317 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4318 	rpc_error = e.error;
4319 
4320 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4321 	if (needrecov) {
4322 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4323 		    "nfs4_access: initiating recovery\n"));
4324 
4325 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4326 		    NULL, OP_ACCESS, NULL) == FALSE) {
4327 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4328 			    &recov_state, needrecov);
4329 			if (!e.error)
4330 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4331 				    (caddr_t)&res);
4332 			goto recov_retry;
4333 		}
4334 	}
4335 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4336 
4337 	if (e.error)
4338 		goto out;
4339 
4340 	if (res.status) {
4341 		e.error = geterrno4(res.status);
4342 		/*
4343 		 * This might generate over the wire calls throught
4344 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4345 		 * here to avoid a deadlock.
4346 		 */
4347 		nfs4_purge_stale_fh(e.error, vp, cr);
4348 		goto out;
4349 	}
4350 	resop = &res.array[1];	/* access res */
4351 
4352 	resacc = resop->nfs_resop4_u.opaccess.access;
4353 
4354 	if (do_getattr) {
4355 		resop++;	/* getattr res */
4356 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4357 		    t, cr, FALSE, NULL);
4358 	}
4359 
4360 	if (!e.error) {
4361 		nfs4_access_cache(rp, argacc, resacc, cred);
4362 		/*
4363 		 * we just cached results with cred; if cred is the
4364 		 * adjusted credentials from crnetadjust, we do not want
4365 		 * to release them before exiting: hence setting ncrfree
4366 		 * to NULL
4367 		 */
4368 		if (cred != cr)
4369 			ncrfree = NULL;
4370 		/* XXX check the supported bits too? */
4371 		if ((acc & resacc) != acc) {
4372 			/*
4373 			 * The following code implements the semantic
4374 			 * that a setuid root program has *at least* the
4375 			 * permissions of the user that is running the
4376 			 * program.  See rfs3call() for more portions
4377 			 * of the implementation of this functionality.
4378 			 */
4379 			/* XXX-LP */
4380 			if (ncr != NULL) {
4381 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4382 				    (caddr_t)&res);
4383 				cred = ncr;
4384 				ncr = NULL;
4385 				goto tryagain;
4386 			}
4387 			e.error = EACCES;
4388 		}
4389 	}
4390 
4391 out:
4392 	if (!rpc_error)
4393 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4394 
4395 	if (ncrfree != NULL)
4396 		crfree(ncrfree);
4397 
4398 	return (e.error);
4399 }
4400 
4401 /* ARGSUSED */
4402 static int
4403 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr, caller_context_t *ct)
4404 {
4405 	COMPOUND4args_clnt args;
4406 	COMPOUND4res_clnt res;
4407 	int doqueue;
4408 	rnode4_t *rp;
4409 	nfs_argop4 argop[3];
4410 	nfs_resop4 *resop;
4411 	READLINK4res *lr_res;
4412 	nfs4_ga_res_t *garp;
4413 	uint_t len;
4414 	char *linkdata;
4415 	bool_t needrecov = FALSE;
4416 	nfs4_recov_state_t recov_state;
4417 	hrtime_t t;
4418 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4419 
4420 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4421 		return (EIO);
4422 	/*
4423 	 * Can't readlink anything other than a symbolic link.
4424 	 */
4425 	if (vp->v_type != VLNK)
4426 		return (EINVAL);
4427 
4428 	rp = VTOR4(vp);
4429 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4430 		e.error = nfs4_validate_caches(vp, cr);
4431 		if (e.error)
4432 			return (e.error);
4433 		mutex_enter(&rp->r_statelock);
4434 		if (rp->r_symlink.contents != NULL) {
4435 			e.error = uiomove(rp->r_symlink.contents,
4436 			    rp->r_symlink.len, UIO_READ, uiop);
4437 			mutex_exit(&rp->r_statelock);
4438 			return (e.error);
4439 		}
4440 		mutex_exit(&rp->r_statelock);
4441 	}
4442 	recov_state.rs_flags = 0;
4443 	recov_state.rs_num_retry_despite_err = 0;
4444 
4445 recov_retry:
4446 	args.array_len = 3;
4447 	args.array = argop;
4448 	args.ctag = TAG_READLINK;
4449 
4450 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4451 	if (e.error) {
4452 		return (e.error);
4453 	}
4454 
4455 	/* 0. putfh symlink fh */
4456 	argop[0].argop = OP_CPUTFH;
4457 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4458 
4459 	/* 1. readlink */
4460 	argop[1].argop = OP_READLINK;
4461 
4462 	/* 2. getattr */
4463 	argop[2].argop = OP_GETATTR;
4464 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4465 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4466 
4467 	doqueue = 1;
4468 
4469 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4470 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4471 	    rnode4info(VTOR4(vp))));
4472 
4473 	t = gethrtime();
4474 
4475 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4476 
4477 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4478 	if (needrecov) {
4479 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4480 		    "nfs4_readlink: initiating recovery\n"));
4481 
4482 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4483 		    NULL, OP_READLINK, NULL) == FALSE) {
4484 			if (!e.error)
4485 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4486 				    (caddr_t)&res);
4487 
4488 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4489 			    needrecov);
4490 			goto recov_retry;
4491 		}
4492 	}
4493 
4494 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4495 
4496 	if (e.error)
4497 		return (e.error);
4498 
4499 	/*
4500 	 * There is an path in the code below which calls
4501 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4502 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4503 	 * here to avoid nfs4_start_op() deadlock.
4504 	 */
4505 
4506 	if (res.status && (res.array_len < args.array_len)) {
4507 		/*
4508 		 * either Putfh or Link failed
4509 		 */
4510 		e.error = geterrno4(res.status);
4511 		nfs4_purge_stale_fh(e.error, vp, cr);
4512 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4513 		return (e.error);
4514 	}
4515 
4516 	resop = &res.array[1];	/* readlink res */
4517 	lr_res = &resop->nfs_resop4_u.opreadlink;
4518 
4519 	/*
4520 	 * treat symlink names as data
4521 	 */
4522 	linkdata = utf8_to_str(&lr_res->link, &len, NULL);
4523 	if (linkdata != NULL) {
4524 		int uio_len = len - 1;
4525 		/* len includes null byte, which we won't uiomove */
4526 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4527 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4528 			mutex_enter(&rp->r_statelock);
4529 			if (rp->r_symlink.contents == NULL) {
4530 				rp->r_symlink.contents = linkdata;
4531 				rp->r_symlink.len = uio_len;
4532 				rp->r_symlink.size = len;
4533 				mutex_exit(&rp->r_statelock);
4534 			} else {
4535 				mutex_exit(&rp->r_statelock);
4536 				kmem_free(linkdata, len);
4537 			}
4538 		} else {
4539 			kmem_free(linkdata, len);
4540 		}
4541 	}
4542 	if (res.status == NFS4_OK) {
4543 		resop++;	/* getattr res */
4544 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4545 	}
4546 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4547 
4548 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4549 
4550 	/*
4551 	 * The over the wire error for attempting to readlink something
4552 	 * other than a symbolic link is ENXIO.  However, we need to
4553 	 * return EINVAL instead of ENXIO, so we map it here.
4554 	 */
4555 	return (e.error == ENXIO ? EINVAL : e.error);
4556 }
4557 
4558 /*
4559  * Flush local dirty pages to stable storage on the server.
4560  *
4561  * If FNODSYNC is specified, then there is nothing to do because
4562  * metadata changes are not cached on the client before being
4563  * sent to the server.
4564  */
4565 /* ARGSUSED */
4566 static int
4567 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
4568 {
4569 	int error;
4570 
4571 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4572 		return (0);
4573 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4574 		return (EIO);
4575 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4576 	if (!error)
4577 		error = VTOR4(vp)->r_error;
4578 	return (error);
4579 }
4580 
4581 /*
4582  * Weirdness: if the file was removed or the target of a rename
4583  * operation while it was open, it got renamed instead.  Here we
4584  * remove the renamed file.
4585  */
4586 /* ARGSUSED */
4587 void
4588 nfs4_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4589 {
4590 	rnode4_t *rp;
4591 
4592 	ASSERT(vp != DNLC_NO_VNODE);
4593 
4594 	rp = VTOR4(vp);
4595 
4596 	if (IS_SHADOW(vp, rp)) {
4597 		sv_inactive(vp);
4598 		return;
4599 	}
4600 
4601 	/*
4602 	 * If this is coming from the wrong zone, we let someone in the right
4603 	 * zone take care of it asynchronously.  We can get here due to
4604 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4605 	 * potentially turn into an expensive no-op if, for instance, v_count
4606 	 * gets incremented in the meantime, but it's still correct.
4607 	 */
4608 	if (nfs_zone() != VTOMI4(vp)->mi_zone) {
4609 		nfs4_async_inactive(vp, cr);
4610 		return;
4611 	}
4612 
4613 	/*
4614 	 * Some of the cleanup steps might require over-the-wire
4615 	 * operations.  Since VOP_INACTIVE can get called as a result of
4616 	 * other over-the-wire operations (e.g., an attribute cache update
4617 	 * can lead to a DNLC purge), doing those steps now would lead to a
4618 	 * nested call to the recovery framework, which can deadlock.  So
4619 	 * do any over-the-wire cleanups asynchronously, in a separate
4620 	 * thread.
4621 	 */
4622 
4623 	mutex_enter(&rp->r_os_lock);
4624 	mutex_enter(&rp->r_statelock);
4625 	mutex_enter(&rp->r_statev4_lock);
4626 
4627 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4628 		mutex_exit(&rp->r_statev4_lock);
4629 		mutex_exit(&rp->r_statelock);
4630 		mutex_exit(&rp->r_os_lock);
4631 		nfs4_async_inactive(vp, cr);
4632 		return;
4633 	}
4634 
4635 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4636 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4637 		mutex_exit(&rp->r_statev4_lock);
4638 		mutex_exit(&rp->r_statelock);
4639 		mutex_exit(&rp->r_os_lock);
4640 		nfs4_async_inactive(vp, cr);
4641 		return;
4642 	}
4643 
4644 	if (rp->r_unldvp != NULL) {
4645 		mutex_exit(&rp->r_statev4_lock);
4646 		mutex_exit(&rp->r_statelock);
4647 		mutex_exit(&rp->r_os_lock);
4648 		nfs4_async_inactive(vp, cr);
4649 		return;
4650 	}
4651 	mutex_exit(&rp->r_statev4_lock);
4652 	mutex_exit(&rp->r_statelock);
4653 	mutex_exit(&rp->r_os_lock);
4654 
4655 	rp4_addfree(rp, cr);
4656 }
4657 
4658 /*
4659  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4660  * various bits of state.  The caller must not refer to vp after this call.
4661  */
4662 
4663 void
4664 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4665 {
4666 	rnode4_t *rp = VTOR4(vp);
4667 	nfs4_recov_state_t recov_state;
4668 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4669 	vnode_t *unldvp;
4670 	char *unlname;
4671 	cred_t *unlcred;
4672 	COMPOUND4args_clnt args;
4673 	COMPOUND4res_clnt res, *resp;
4674 	nfs_argop4 argop[2];
4675 	int doqueue;
4676 #ifdef DEBUG
4677 	char *name;
4678 #endif
4679 
4680 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
4681 	ASSERT(!IS_SHADOW(vp, rp));
4682 
4683 #ifdef DEBUG
4684 	name = fn_name(VTOSV(vp)->sv_name);
4685 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4686 	    "release vnode %s", name));
4687 	kmem_free(name, MAXNAMELEN);
4688 #endif
4689 
4690 	if (vp->v_type == VREG) {
4691 		bool_t recov_failed = FALSE;
4692 
4693 		e.error = nfs4close_all(vp, cr);
4694 		if (e.error) {
4695 			/* Check to see if recovery failed */
4696 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4697 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4698 				recov_failed = TRUE;
4699 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4700 			if (!recov_failed) {
4701 				mutex_enter(&rp->r_statelock);
4702 				if (rp->r_flags & R4RECOVERR)
4703 					recov_failed = TRUE;
4704 				mutex_exit(&rp->r_statelock);
4705 			}
4706 			if (recov_failed) {
4707 				NFS4_DEBUG(nfs4_client_recov_debug,
4708 				    (CE_NOTE, "nfs4_inactive_otw: "
4709 				    "close failed (recovery failure)"));
4710 			}
4711 		}
4712 	}
4713 
4714 redo:
4715 	if (rp->r_unldvp == NULL) {
4716 		rp4_addfree(rp, cr);
4717 		return;
4718 	}
4719 
4720 	/*
4721 	 * Save the vnode pointer for the directory where the
4722 	 * unlinked-open file got renamed, then set it to NULL
4723 	 * to prevent another thread from getting here before
4724 	 * we're done with the remove.  While we have the
4725 	 * statelock, make local copies of the pertinent rnode
4726 	 * fields.  If we weren't to do this in an atomic way, the
4727 	 * the unl* fields could become inconsistent with respect
4728 	 * to each other due to a race condition between this
4729 	 * code and nfs_remove().  See bug report 1034328.
4730 	 */
4731 	mutex_enter(&rp->r_statelock);
4732 	if (rp->r_unldvp == NULL) {
4733 		mutex_exit(&rp->r_statelock);
4734 		rp4_addfree(rp, cr);
4735 		return;
4736 	}
4737 
4738 	unldvp = rp->r_unldvp;
4739 	rp->r_unldvp = NULL;
4740 	unlname = rp->r_unlname;
4741 	rp->r_unlname = NULL;
4742 	unlcred = rp->r_unlcred;
4743 	rp->r_unlcred = NULL;
4744 	mutex_exit(&rp->r_statelock);
4745 
4746 	/*
4747 	 * If there are any dirty pages left, then flush
4748 	 * them.  This is unfortunate because they just
4749 	 * may get thrown away during the remove operation,
4750 	 * but we have to do this for correctness.
4751 	 */
4752 	if (nfs4_has_pages(vp) &&
4753 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4754 		ASSERT(vp->v_type != VCHR);
4755 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, NULL);
4756 		if (e.error) {
4757 			mutex_enter(&rp->r_statelock);
4758 			if (!rp->r_error)
4759 				rp->r_error = e.error;
4760 			mutex_exit(&rp->r_statelock);
4761 		}
4762 	}
4763 
4764 	recov_state.rs_flags = 0;
4765 	recov_state.rs_num_retry_despite_err = 0;
4766 recov_retry_remove:
4767 	/*
4768 	 * Do the remove operation on the renamed file
4769 	 */
4770 	args.ctag = TAG_INACTIVE;
4771 
4772 	/*
4773 	 * Remove ops: putfh dir; remove
4774 	 */
4775 	args.array_len = 2;
4776 	args.array = argop;
4777 
4778 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4779 	if (e.error) {
4780 		kmem_free(unlname, MAXNAMELEN);
4781 		crfree(unlcred);
4782 		VN_RELE(unldvp);
4783 		/*
4784 		 * Try again; this time around r_unldvp will be NULL, so we'll
4785 		 * just call rp4_addfree() and return.
4786 		 */
4787 		goto redo;
4788 	}
4789 
4790 	/* putfh directory */
4791 	argop[0].argop = OP_CPUTFH;
4792 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4793 
4794 	/* remove */
4795 	argop[1].argop = OP_CREMOVE;
4796 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4797 
4798 	doqueue = 1;
4799 	resp = &res;
4800 
4801 #if 0 /* notyet */
4802 	/*
4803 	 * Can't do this yet.  We may be being called from
4804 	 * dnlc_purge_XXX while that routine is holding a
4805 	 * mutex lock to the nc_rele list.  The calls to
4806 	 * nfs3_cache_wcc_data may result in calls to
4807 	 * dnlc_purge_XXX.  This will result in a deadlock.
4808 	 */
4809 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4810 	if (e.error) {
4811 		PURGE_ATTRCACHE4(unldvp);
4812 		resp = NULL;
4813 	} else if (res.status) {
4814 		e.error = geterrno4(res.status);
4815 		PURGE_ATTRCACHE4(unldvp);
4816 		/*
4817 		 * This code is inactive right now
4818 		 * but if made active there should
4819 		 * be a nfs4_end_op() call before
4820 		 * nfs4_purge_stale_fh to avoid start_op()
4821 		 * deadlock. See BugId: 4948726
4822 		 */
4823 		nfs4_purge_stale_fh(error, unldvp, cr);
4824 	} else {
4825 		nfs_resop4 *resop;
4826 		REMOVE4res *rm_res;
4827 
4828 		resop = &res.array[1];
4829 		rm_res = &resop->nfs_resop4_u.opremove;
4830 		/*
4831 		 * Update directory cache attribute,
4832 		 * readdir and dnlc caches.
4833 		 */
4834 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4835 	}
4836 #else
4837 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4838 
4839 	PURGE_ATTRCACHE4(unldvp);
4840 #endif
4841 
4842 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4843 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4844 		    NULL, NULL, OP_REMOVE, NULL) == FALSE) {
4845 			if (!e.error)
4846 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4847 				    (caddr_t)&res);
4848 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4849 			    &recov_state, TRUE);
4850 			goto recov_retry_remove;
4851 		}
4852 	}
4853 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4854 
4855 	/*
4856 	 * Release stuff held for the remove
4857 	 */
4858 	VN_RELE(unldvp);
4859 	if (!e.error && resp)
4860 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4861 
4862 	kmem_free(unlname, MAXNAMELEN);
4863 	crfree(unlcred);
4864 	goto redo;
4865 }
4866 
4867 /*
4868  * Remote file system operations having to do with directory manipulation.
4869  */
4870 /* ARGSUSED3 */
4871 int
4872 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4873     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
4874     int *direntflags, pathname_t *realpnp)
4875 {
4876 	int error;
4877 	vnode_t *vp, *avp = NULL;
4878 	rnode4_t *drp;
4879 
4880 	*vpp = NULL;
4881 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4882 		return (EPERM);
4883 	/*
4884 	 * if LOOKUP_XATTR, must replace dvp (object) with
4885 	 * object's attrdir before continuing with lookup
4886 	 */
4887 	if (flags & LOOKUP_XATTR) {
4888 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4889 		if (error)
4890 			return (error);
4891 
4892 		dvp = avp;
4893 
4894 		/*
4895 		 * If lookup is for "", just return dvp now.  The attrdir
4896 		 * has already been activated (from nfs4lookup_xattr), and
4897 		 * the caller will RELE the original dvp -- not
4898 		 * the attrdir.  So, set vpp and return.
4899 		 * Currently, when the LOOKUP_XATTR flag is
4900 		 * passed to VOP_LOOKUP, the name is always empty, and
4901 		 * shortcircuiting here avoids 3 unneeded lock/unlock
4902 		 * pairs.
4903 		 *
4904 		 * If a non-empty name was provided, then it is the
4905 		 * attribute name, and it will be looked up below.
4906 		 */
4907 		if (*nm == '\0') {
4908 			*vpp = dvp;
4909 			return (0);
4910 		}
4911 
4912 		/*
4913 		 * The vfs layer never sends a name when asking for the
4914 		 * attrdir, so we should never get here (unless of course
4915 		 * name is passed at some time in future -- at which time
4916 		 * we'll blow up here).
4917 		 */
4918 		ASSERT(0);
4919 	}
4920 
4921 	drp = VTOR4(dvp);
4922 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4923 		return (EINTR);
4924 
4925 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
4926 	nfs_rw_exit(&drp->r_rwlock);
4927 
4928 	/*
4929 	 * If vnode is a device, create special vnode.
4930 	 */
4931 	if (!error && ISVDEV((*vpp)->v_type)) {
4932 		vp = *vpp;
4933 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
4934 		VN_RELE(vp);
4935 	}
4936 
4937 	return (error);
4938 }
4939 
4940 /* ARGSUSED */
4941 static int
4942 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
4943 {
4944 	int error;
4945 	rnode4_t *drp;
4946 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
4947 	mntinfo4_t *mi;
4948 
4949 	mi = VTOMI4(dvp);
4950 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR) &&
4951 	    !vfs_has_feature(mi->mi_vfsp, VFSFT_XVATTR))
4952 		return (EINVAL);
4953 
4954 	drp = VTOR4(dvp);
4955 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4956 		return (EINTR);
4957 
4958 	mutex_enter(&drp->r_statelock);
4959 	/*
4960 	 * If the server doesn't support xattrs just return EINVAL
4961 	 */
4962 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
4963 		mutex_exit(&drp->r_statelock);
4964 		nfs_rw_exit(&drp->r_rwlock);
4965 		return (EINVAL);
4966 	}
4967 
4968 	/*
4969 	 * If there is a cached xattr directory entry,
4970 	 * use it as long as the attributes are valid. If the
4971 	 * attributes are not valid, take the simple approach and
4972 	 * free the cached value and re-fetch a new value.
4973 	 *
4974 	 * We don't negative entry cache for now, if we did we
4975 	 * would need to check if the file has changed on every
4976 	 * lookup. But xattrs don't exist very often and failing
4977 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
4978 	 * so do an openattr over the wire for now.
4979 	 */
4980 	if (drp->r_xattr_dir != NULL) {
4981 		if (ATTRCACHE4_VALID(dvp)) {
4982 			VN_HOLD(drp->r_xattr_dir);
4983 			*vpp = drp->r_xattr_dir;
4984 			mutex_exit(&drp->r_statelock);
4985 			nfs_rw_exit(&drp->r_rwlock);
4986 			return (0);
4987 		}
4988 		VN_RELE(drp->r_xattr_dir);
4989 		drp->r_xattr_dir = NULL;
4990 	}
4991 	mutex_exit(&drp->r_statelock);
4992 
4993 	error = nfs4openattr(dvp, vpp, cflag, cr);
4994 
4995 	nfs_rw_exit(&drp->r_rwlock);
4996 
4997 	return (error);
4998 }
4999 
5000 static int
5001 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
5002 {
5003 	int error;
5004 	rnode4_t *drp;
5005 
5006 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5007 
5008 	/*
5009 	 * If lookup is for "", just return dvp.  Don't need
5010 	 * to send it over the wire, look it up in the dnlc,
5011 	 * or perform any access checks.
5012 	 */
5013 	if (*nm == '\0') {
5014 		VN_HOLD(dvp);
5015 		*vpp = dvp;
5016 		return (0);
5017 	}
5018 
5019 	/*
5020 	 * Can't do lookups in non-directories.
5021 	 */
5022 	if (dvp->v_type != VDIR)
5023 		return (ENOTDIR);
5024 
5025 	/*
5026 	 * If lookup is for ".", just return dvp.  Don't need
5027 	 * to send it over the wire or look it up in the dnlc,
5028 	 * just need to check access.
5029 	 */
5030 	if (nm[0] == '.' && nm[1] == '\0') {
5031 		error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5032 		if (error)
5033 			return (error);
5034 		VN_HOLD(dvp);
5035 		*vpp = dvp;
5036 		return (0);
5037 	}
5038 
5039 	drp = VTOR4(dvp);
5040 	if (!(drp->r_flags & R4LOOKUP)) {
5041 		mutex_enter(&drp->r_statelock);
5042 		drp->r_flags |= R4LOOKUP;
5043 		mutex_exit(&drp->r_statelock);
5044 	}
5045 
5046 	*vpp = NULL;
5047 	/*
5048 	 * Lookup this name in the DNLC.  If there is no entry
5049 	 * lookup over the wire.
5050 	 */
5051 	if (!skipdnlc)
5052 		*vpp = dnlc_lookup(dvp, nm);
5053 	if (*vpp == NULL) {
5054 		/*
5055 		 * We need to go over the wire to lookup the name.
5056 		 */
5057 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
5058 	}
5059 
5060 	/*
5061 	 * We hit on the dnlc
5062 	 */
5063 	if (*vpp != DNLC_NO_VNODE ||
5064 	    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
5065 		/*
5066 		 * But our attrs may not be valid.
5067 		 */
5068 		if (ATTRCACHE4_VALID(dvp)) {
5069 			error = nfs4_waitfor_purge_complete(dvp);
5070 			if (error) {
5071 				VN_RELE(*vpp);
5072 				*vpp = NULL;
5073 				return (error);
5074 			}
5075 
5076 			/*
5077 			 * If after the purge completes, check to make sure
5078 			 * our attrs are still valid.
5079 			 */
5080 			if (ATTRCACHE4_VALID(dvp)) {
5081 				/*
5082 				 * If we waited for a purge we may have
5083 				 * lost our vnode so look it up again.
5084 				 */
5085 				VN_RELE(*vpp);
5086 				*vpp = dnlc_lookup(dvp, nm);
5087 				if (*vpp == NULL)
5088 					return (nfs4lookupnew_otw(dvp,
5089 					    nm, vpp, cr));
5090 
5091 				/*
5092 				 * The access cache should almost always hit
5093 				 */
5094 				error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5095 
5096 				if (error) {
5097 					VN_RELE(*vpp);
5098 					*vpp = NULL;
5099 					return (error);
5100 				}
5101 				if (*vpp == DNLC_NO_VNODE) {
5102 					VN_RELE(*vpp);
5103 					*vpp = NULL;
5104 					return (ENOENT);
5105 				}
5106 				return (0);
5107 			}
5108 		}
5109 	}
5110 
5111 	ASSERT(*vpp != NULL);
5112 
5113 	/*
5114 	 * We may have gotten here we have one of the following cases:
5115 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5116 	 *		need to validate them.
5117 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5118 	 *		must validate.
5119 	 *
5120 	 * Go to the server and check if the directory has changed, if
5121 	 * it hasn't we are done and can use the dnlc entry.
5122 	 */
5123 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5124 }
5125 
5126 /*
5127  * Go to the server and check if the directory has changed, if
5128  * it hasn't we are done and can use the dnlc entry.  If it
5129  * has changed we get a new copy of its attributes and check
5130  * the access for VEXEC, then relookup the filename and
5131  * get its filehandle and attributes.
5132  *
5133  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5134  *	if the NVERIFY failed we must
5135  *		purge the caches
5136  *		cache new attributes (will set r_time_attr_inval)
5137  *		cache new access
5138  *		recheck VEXEC access
5139  *		add name to dnlc, possibly negative
5140  *		if LOOKUP succeeded
5141  *			cache new attributes
5142  *	else
5143  *		set a new r_time_attr_inval for dvp
5144  *		check to make sure we have access
5145  *
5146  * The vpp returned is the vnode passed in if the directory is valid,
5147  * a new vnode if successful lookup, or NULL on error.
5148  */
5149 static int
5150 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5151 {
5152 	COMPOUND4args_clnt args;
5153 	COMPOUND4res_clnt res;
5154 	fattr4 *ver_fattr;
5155 	fattr4_change dchange;
5156 	int32_t *ptr;
5157 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5158 	nfs_argop4 *argop;
5159 	int doqueue;
5160 	mntinfo4_t *mi;
5161 	nfs4_recov_state_t recov_state;
5162 	hrtime_t t;
5163 	int isdotdot;
5164 	vnode_t *nvp;
5165 	nfs_fh4 *fhp;
5166 	nfs4_sharedfh_t *sfhp;
5167 	nfs4_access_type_t cacc;
5168 	rnode4_t *nrp;
5169 	rnode4_t *drp = VTOR4(dvp);
5170 	nfs4_ga_res_t *garp = NULL;
5171 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5172 
5173 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5174 	ASSERT(nm != NULL);
5175 	ASSERT(nm[0] != '\0');
5176 	ASSERT(dvp->v_type == VDIR);
5177 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5178 	ASSERT(*vpp != NULL);
5179 
5180 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5181 		isdotdot = 1;
5182 		args.ctag = TAG_LOOKUP_VPARENT;
5183 	} else {
5184 		/*
5185 		 * If dvp were a stub, it should have triggered and caused
5186 		 * a mount for us to get this far.
5187 		 */
5188 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5189 
5190 		isdotdot = 0;
5191 		args.ctag = TAG_LOOKUP_VALID;
5192 	}
5193 
5194 	mi = VTOMI4(dvp);
5195 	recov_state.rs_flags = 0;
5196 	recov_state.rs_num_retry_despite_err = 0;
5197 
5198 	nvp = NULL;
5199 
5200 	/* Save the original mount point security information */
5201 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5202 
5203 recov_retry:
5204 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5205 	    &recov_state, NULL);
5206 	if (e.error) {
5207 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5208 		VN_RELE(*vpp);
5209 		*vpp = NULL;
5210 		return (e.error);
5211 	}
5212 
5213 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5214 
5215 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5216 	args.array_len = 7;
5217 	args.array = argop;
5218 
5219 	/* 0. putfh file */
5220 	argop[0].argop = OP_CPUTFH;
5221 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5222 
5223 	/* 1. nverify the change info */
5224 	argop[1].argop = OP_NVERIFY;
5225 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5226 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5227 	ver_fattr->attrlist4 = (char *)&dchange;
5228 	ptr = (int32_t *)&dchange;
5229 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5230 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5231 
5232 	/* 2. getattr directory */
5233 	argop[2].argop = OP_GETATTR;
5234 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5235 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5236 
5237 	/* 3. access directory */
5238 	argop[3].argop = OP_ACCESS;
5239 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5240 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5241 
5242 	/* 4. lookup name */
5243 	if (isdotdot) {
5244 		argop[4].argop = OP_LOOKUPP;
5245 	} else {
5246 		argop[4].argop = OP_CLOOKUP;
5247 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5248 	}
5249 
5250 	/* 5. resulting file handle */
5251 	argop[5].argop = OP_GETFH;
5252 
5253 	/* 6. resulting file attributes */
5254 	argop[6].argop = OP_GETATTR;
5255 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5256 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5257 
5258 	doqueue = 1;
5259 	t = gethrtime();
5260 
5261 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5262 
5263 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5264 		/*
5265 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5266 		 * from this thread, do not go thru the recovery thread since
5267 		 * we need the nm information.
5268 		 *
5269 		 * Not doing dotdot case because there is no specification
5270 		 * for (PUTFH, SECINFO "..") yet.
5271 		 */
5272 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5273 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5274 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5275 				    &recov_state, FALSE);
5276 			else
5277 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5278 				    &recov_state, TRUE);
5279 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5280 			kmem_free(argop, argoplist_size);
5281 			if (!e.error)
5282 				goto recov_retry;
5283 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5284 			VN_RELE(*vpp);
5285 			*vpp = NULL;
5286 			return (e.error);
5287 		}
5288 
5289 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5290 		    OP_LOOKUP, NULL) == FALSE) {
5291 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5292 			    &recov_state, TRUE);
5293 
5294 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5295 			kmem_free(argop, argoplist_size);
5296 			goto recov_retry;
5297 		}
5298 	}
5299 
5300 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5301 
5302 	if (e.error || res.array_len == 0) {
5303 		/*
5304 		 * If e.error isn't set, then reply has no ops (or we couldn't
5305 		 * be here).  The only legal way to reply without an op array
5306 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5307 		 * be in the reply for all other status values.
5308 		 *
5309 		 * For valid replies without an ops array, return ENOTSUP
5310 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5311 		 * return EIO -- don't trust status.
5312 		 */
5313 		if (e.error == 0)
5314 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5315 			    ENOTSUP : EIO;
5316 		VN_RELE(*vpp);
5317 		*vpp = NULL;
5318 		kmem_free(argop, argoplist_size);
5319 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5320 		return (e.error);
5321 	}
5322 
5323 	if (res.status != NFS4ERR_SAME) {
5324 		e.error = geterrno4(res.status);
5325 
5326 		/*
5327 		 * The NVERIFY "failed" so the directory has changed
5328 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5329 		 * cleanly.
5330 		 */
5331 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5332 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5333 			nfs4_purge_stale_fh(e.error, dvp, cr);
5334 			VN_RELE(*vpp);
5335 			*vpp = NULL;
5336 			goto exit;
5337 		}
5338 
5339 		/*
5340 		 * We know the NVERIFY "failed" so we must:
5341 		 *	purge the caches (access and indirectly dnlc if needed)
5342 		 */
5343 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5344 
5345 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5346 			nfs4_purge_stale_fh(e.error, dvp, cr);
5347 			VN_RELE(*vpp);
5348 			*vpp = NULL;
5349 			goto exit;
5350 		}
5351 
5352 		/*
5353 		 * Install new cached attributes for the directory
5354 		 */
5355 		nfs4_attr_cache(dvp,
5356 		    &res.array[2].nfs_resop4_u.opgetattr.ga_res,
5357 		    t, cr, FALSE, NULL);
5358 
5359 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5360 			nfs4_purge_stale_fh(e.error, dvp, cr);
5361 			VN_RELE(*vpp);
5362 			*vpp = NULL;
5363 			e.error = geterrno4(res.status);
5364 			goto exit;
5365 		}
5366 
5367 		/*
5368 		 * Now we know the directory is valid,
5369 		 * cache new directory access
5370 		 */
5371 		nfs4_access_cache(drp,
5372 		    args.array[3].nfs_argop4_u.opaccess.access,
5373 		    res.array[3].nfs_resop4_u.opaccess.access, cr);
5374 
5375 		/*
5376 		 * recheck VEXEC access
5377 		 */
5378 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5379 		if (cacc != NFS4_ACCESS_ALLOWED) {
5380 			/*
5381 			 * Directory permissions might have been revoked
5382 			 */
5383 			if (cacc == NFS4_ACCESS_DENIED) {
5384 				e.error = EACCES;
5385 				VN_RELE(*vpp);
5386 				*vpp = NULL;
5387 				goto exit;
5388 			}
5389 
5390 			/*
5391 			 * Somehow we must not have asked for enough
5392 			 * so try a singleton ACCESS, should never happen.
5393 			 */
5394 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5395 			if (e.error) {
5396 				VN_RELE(*vpp);
5397 				*vpp = NULL;
5398 				goto exit;
5399 			}
5400 		}
5401 
5402 		e.error = geterrno4(res.status);
5403 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5404 			/*
5405 			 * The lookup failed, probably no entry
5406 			 */
5407 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5408 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5409 			} else {
5410 				/*
5411 				 * Might be some other error, so remove
5412 				 * the dnlc entry to make sure we start all
5413 				 * over again, next time.
5414 				 */
5415 				dnlc_remove(dvp, nm);
5416 			}
5417 			VN_RELE(*vpp);
5418 			*vpp = NULL;
5419 			goto exit;
5420 		}
5421 
5422 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5423 			/*
5424 			 * The file exists but we can't get its fh for
5425 			 * some unknown reason.  Remove it from the dnlc
5426 			 * and error out to be safe.
5427 			 */
5428 			dnlc_remove(dvp, nm);
5429 			VN_RELE(*vpp);
5430 			*vpp = NULL;
5431 			goto exit;
5432 		}
5433 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5434 		if (fhp->nfs_fh4_len == 0) {
5435 			/*
5436 			 * The file exists but a bogus fh
5437 			 * some unknown reason.  Remove it from the dnlc
5438 			 * and error out to be safe.
5439 			 */
5440 			e.error = ENOENT;
5441 			dnlc_remove(dvp, nm);
5442 			VN_RELE(*vpp);
5443 			*vpp = NULL;
5444 			goto exit;
5445 		}
5446 		sfhp = sfh4_get(fhp, mi);
5447 
5448 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5449 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5450 
5451 		/*
5452 		 * Make the new rnode
5453 		 */
5454 		if (isdotdot) {
5455 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5456 			if (e.error) {
5457 				sfh4_rele(&sfhp);
5458 				VN_RELE(*vpp);
5459 				*vpp = NULL;
5460 				goto exit;
5461 			}
5462 			/*
5463 			 * XXX if nfs4_make_dotdot uses an existing rnode
5464 			 * XXX it doesn't update the attributes.
5465 			 * XXX for now just save them again to save an OTW
5466 			 */
5467 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5468 		} else {
5469 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5470 			    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5471 			/*
5472 			 * If v_type == VNON, then garp was NULL because
5473 			 * the last op in the compound failed and makenfs4node
5474 			 * could not find the vnode for sfhp. It created
5475 			 * a new vnode, so we have nothing to purge here.
5476 			 */
5477 			if (nvp->v_type == VNON) {
5478 				vattr_t vattr;
5479 
5480 				vattr.va_mask = AT_TYPE;
5481 				/*
5482 				 * N.B. We've already called nfs4_end_fop above.
5483 				 */
5484 				e.error = nfs4getattr(nvp, &vattr, cr);
5485 				if (e.error) {
5486 					sfh4_rele(&sfhp);
5487 					VN_RELE(*vpp);
5488 					*vpp = NULL;
5489 					VN_RELE(nvp);
5490 					goto exit;
5491 				}
5492 				nvp->v_type = vattr.va_type;
5493 			}
5494 		}
5495 		sfh4_rele(&sfhp);
5496 
5497 		nrp = VTOR4(nvp);
5498 		mutex_enter(&nrp->r_statev4_lock);
5499 		if (!nrp->created_v4) {
5500 			mutex_exit(&nrp->r_statev4_lock);
5501 			dnlc_update(dvp, nm, nvp);
5502 		} else
5503 			mutex_exit(&nrp->r_statev4_lock);
5504 
5505 		VN_RELE(*vpp);
5506 		*vpp = nvp;
5507 	} else {
5508 		hrtime_t now;
5509 		hrtime_t delta = 0;
5510 
5511 		e.error = 0;
5512 
5513 		/*
5514 		 * Because the NVERIFY "succeeded" we know that the
5515 		 * directory attributes are still valid
5516 		 * so update r_time_attr_inval
5517 		 */
5518 		now = gethrtime();
5519 		mutex_enter(&drp->r_statelock);
5520 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5521 			delta = now - drp->r_time_attr_saved;
5522 			if (delta < mi->mi_acdirmin)
5523 				delta = mi->mi_acdirmin;
5524 			else if (delta > mi->mi_acdirmax)
5525 				delta = mi->mi_acdirmax;
5526 		}
5527 		drp->r_time_attr_inval = now + delta;
5528 		mutex_exit(&drp->r_statelock);
5529 		dnlc_update(dvp, nm, *vpp);
5530 
5531 		/*
5532 		 * Even though we have a valid directory attr cache
5533 		 * and dnlc entry, we may not have access.
5534 		 * This should almost always hit the cache.
5535 		 */
5536 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5537 		if (e.error) {
5538 			VN_RELE(*vpp);
5539 			*vpp = NULL;
5540 		}
5541 
5542 		if (*vpp == DNLC_NO_VNODE) {
5543 			VN_RELE(*vpp);
5544 			*vpp = NULL;
5545 			e.error = ENOENT;
5546 		}
5547 	}
5548 
5549 exit:
5550 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5551 	kmem_free(argop, argoplist_size);
5552 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5553 	return (e.error);
5554 }
5555 
5556 /*
5557  * We need to go over the wire to lookup the name, but
5558  * while we are there verify the directory has not
5559  * changed but if it has, get new attributes and check access
5560  *
5561  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5562  *					NVERIFY GETATTR ACCESS
5563  *
5564  * With the results:
5565  *	if the NVERIFY failed we must purge the caches, add new attributes,
5566  *		and cache new access.
5567  *	set a new r_time_attr_inval
5568  *	add name to dnlc, possibly negative
5569  *	if LOOKUP succeeded
5570  *		cache new attributes
5571  */
5572 static int
5573 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5574 {
5575 	COMPOUND4args_clnt args;
5576 	COMPOUND4res_clnt res;
5577 	fattr4 *ver_fattr;
5578 	fattr4_change dchange;
5579 	int32_t *ptr;
5580 	nfs4_ga_res_t *garp = NULL;
5581 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5582 	nfs_argop4 *argop;
5583 	int doqueue;
5584 	mntinfo4_t *mi;
5585 	nfs4_recov_state_t recov_state;
5586 	hrtime_t t;
5587 	int isdotdot;
5588 	vnode_t *nvp;
5589 	nfs_fh4 *fhp;
5590 	nfs4_sharedfh_t *sfhp;
5591 	nfs4_access_type_t cacc;
5592 	rnode4_t *nrp;
5593 	rnode4_t *drp = VTOR4(dvp);
5594 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5595 
5596 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5597 	ASSERT(nm != NULL);
5598 	ASSERT(nm[0] != '\0');
5599 	ASSERT(dvp->v_type == VDIR);
5600 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5601 	ASSERT(*vpp == NULL);
5602 
5603 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5604 		isdotdot = 1;
5605 		args.ctag = TAG_LOOKUP_PARENT;
5606 	} else {
5607 		/*
5608 		 * If dvp were a stub, it should have triggered and caused
5609 		 * a mount for us to get this far.
5610 		 */
5611 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5612 
5613 		isdotdot = 0;
5614 		args.ctag = TAG_LOOKUP;
5615 	}
5616 
5617 	mi = VTOMI4(dvp);
5618 	recov_state.rs_flags = 0;
5619 	recov_state.rs_num_retry_despite_err = 0;
5620 
5621 	nvp = NULL;
5622 
5623 	/* Save the original mount point security information */
5624 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5625 
5626 recov_retry:
5627 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5628 	    &recov_state, NULL);
5629 	if (e.error) {
5630 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5631 		return (e.error);
5632 	}
5633 
5634 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5635 
5636 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5637 	args.array_len = 9;
5638 	args.array = argop;
5639 
5640 	/* 0. putfh file */
5641 	argop[0].argop = OP_CPUTFH;
5642 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5643 
5644 	/* 1. savefh for the nverify */
5645 	argop[1].argop = OP_SAVEFH;
5646 
5647 	/* 2. lookup name */
5648 	if (isdotdot) {
5649 		argop[2].argop = OP_LOOKUPP;
5650 	} else {
5651 		argop[2].argop = OP_CLOOKUP;
5652 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5653 	}
5654 
5655 	/* 3. resulting file handle */
5656 	argop[3].argop = OP_GETFH;
5657 
5658 	/* 4. resulting file attributes */
5659 	argop[4].argop = OP_GETATTR;
5660 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5661 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5662 
5663 	/* 5. restorefh back the directory for the nverify */
5664 	argop[5].argop = OP_RESTOREFH;
5665 
5666 	/* 6. nverify the change info */
5667 	argop[6].argop = OP_NVERIFY;
5668 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5669 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5670 	ver_fattr->attrlist4 = (char *)&dchange;
5671 	ptr = (int32_t *)&dchange;
5672 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5673 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5674 
5675 	/* 7. getattr directory */
5676 	argop[7].argop = OP_GETATTR;
5677 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5678 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5679 
5680 	/* 8. access directory */
5681 	argop[8].argop = OP_ACCESS;
5682 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5683 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5684 
5685 	doqueue = 1;
5686 	t = gethrtime();
5687 
5688 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5689 
5690 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5691 		/*
5692 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5693 		 * from this thread, do not go thru the recovery thread since
5694 		 * we need the nm information.
5695 		 *
5696 		 * Not doing dotdot case because there is no specification
5697 		 * for (PUTFH, SECINFO "..") yet.
5698 		 */
5699 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5700 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5701 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5702 				    &recov_state, FALSE);
5703 			else
5704 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5705 				    &recov_state, TRUE);
5706 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5707 			kmem_free(argop, argoplist_size);
5708 			if (!e.error)
5709 				goto recov_retry;
5710 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5711 			return (e.error);
5712 		}
5713 
5714 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5715 		    OP_LOOKUP, NULL) == FALSE) {
5716 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5717 			    &recov_state, TRUE);
5718 
5719 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5720 			kmem_free(argop, argoplist_size);
5721 			goto recov_retry;
5722 		}
5723 	}
5724 
5725 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5726 
5727 	if (e.error || res.array_len == 0) {
5728 		/*
5729 		 * If e.error isn't set, then reply has no ops (or we couldn't
5730 		 * be here).  The only legal way to reply without an op array
5731 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5732 		 * be in the reply for all other status values.
5733 		 *
5734 		 * For valid replies without an ops array, return ENOTSUP
5735 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5736 		 * return EIO -- don't trust status.
5737 		 */
5738 		if (e.error == 0)
5739 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5740 			    ENOTSUP : EIO;
5741 
5742 		kmem_free(argop, argoplist_size);
5743 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5744 		return (e.error);
5745 	}
5746 
5747 	e.error = geterrno4(res.status);
5748 
5749 	/*
5750 	 * The PUTFH and SAVEFH may have failed.
5751 	 */
5752 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5753 	    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5754 		nfs4_purge_stale_fh(e.error, dvp, cr);
5755 		goto exit;
5756 	}
5757 
5758 	/*
5759 	 * Check if the file exists, if it does delay entering
5760 	 * into the dnlc until after we update the directory
5761 	 * attributes so we don't cause it to get purged immediately.
5762 	 */
5763 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5764 		/*
5765 		 * The lookup failed, probably no entry
5766 		 */
5767 		if (e.error == ENOENT && nfs4_lookup_neg_cache)
5768 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5769 		goto exit;
5770 	}
5771 
5772 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5773 		/*
5774 		 * The file exists but we can't get its fh for
5775 		 * some unknown reason. Error out to be safe.
5776 		 */
5777 		goto exit;
5778 	}
5779 
5780 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5781 	if (fhp->nfs_fh4_len == 0) {
5782 		/*
5783 		 * The file exists but a bogus fh
5784 		 * some unknown reason.  Error out to be safe.
5785 		 */
5786 		e.error = EIO;
5787 		goto exit;
5788 	}
5789 	sfhp = sfh4_get(fhp, mi);
5790 
5791 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5792 		sfh4_rele(&sfhp);
5793 		e.error = EIO;
5794 		goto exit;
5795 	}
5796 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5797 
5798 	/*
5799 	 * The RESTOREFH may have failed
5800 	 */
5801 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5802 		sfh4_rele(&sfhp);
5803 		e.error = EIO;
5804 		goto exit;
5805 	}
5806 
5807 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5808 		/*
5809 		 * First make sure the NVERIFY failed as we expected,
5810 		 * if it didn't then be conservative and error out
5811 		 * as we can't trust the directory.
5812 		 */
5813 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5814 			sfh4_rele(&sfhp);
5815 			e.error = EIO;
5816 			goto exit;
5817 		}
5818 
5819 		/*
5820 		 * We know the NVERIFY "failed" so the directory has changed,
5821 		 * so we must:
5822 		 *	purge the caches (access and indirectly dnlc if needed)
5823 		 */
5824 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5825 
5826 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5827 			sfh4_rele(&sfhp);
5828 			goto exit;
5829 		}
5830 		nfs4_attr_cache(dvp,
5831 		    &res.array[7].nfs_resop4_u.opgetattr.ga_res,
5832 		    t, cr, FALSE, NULL);
5833 
5834 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5835 			nfs4_purge_stale_fh(e.error, dvp, cr);
5836 			sfh4_rele(&sfhp);
5837 			e.error = geterrno4(res.status);
5838 			goto exit;
5839 		}
5840 
5841 		/*
5842 		 * Now we know the directory is valid,
5843 		 * cache new directory access
5844 		 */
5845 		nfs4_access_cache(drp,
5846 		    args.array[8].nfs_argop4_u.opaccess.access,
5847 		    res.array[8].nfs_resop4_u.opaccess.access, cr);
5848 
5849 		/*
5850 		 * recheck VEXEC access
5851 		 */
5852 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5853 		if (cacc != NFS4_ACCESS_ALLOWED) {
5854 			/*
5855 			 * Directory permissions might have been revoked
5856 			 */
5857 			if (cacc == NFS4_ACCESS_DENIED) {
5858 				sfh4_rele(&sfhp);
5859 				e.error = EACCES;
5860 				goto exit;
5861 			}
5862 
5863 			/*
5864 			 * Somehow we must not have asked for enough
5865 			 * so try a singleton ACCESS should never happen
5866 			 */
5867 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5868 			if (e.error) {
5869 				sfh4_rele(&sfhp);
5870 				goto exit;
5871 			}
5872 		}
5873 
5874 		e.error = geterrno4(res.status);
5875 	} else {
5876 		hrtime_t now;
5877 		hrtime_t delta = 0;
5878 
5879 		e.error = 0;
5880 
5881 		/*
5882 		 * Because the NVERIFY "succeeded" we know that the
5883 		 * directory attributes are still valid
5884 		 * so update r_time_attr_inval
5885 		 */
5886 		now = gethrtime();
5887 		mutex_enter(&drp->r_statelock);
5888 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5889 			delta = now - drp->r_time_attr_saved;
5890 			if (delta < mi->mi_acdirmin)
5891 				delta = mi->mi_acdirmin;
5892 			else if (delta > mi->mi_acdirmax)
5893 				delta = mi->mi_acdirmax;
5894 		}
5895 		drp->r_time_attr_inval = now + delta;
5896 		mutex_exit(&drp->r_statelock);
5897 
5898 		/*
5899 		 * Even though we have a valid directory attr cache,
5900 		 * we may not have access.
5901 		 * This should almost always hit the cache.
5902 		 */
5903 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5904 		if (e.error) {
5905 			sfh4_rele(&sfhp);
5906 			goto exit;
5907 		}
5908 	}
5909 
5910 	/*
5911 	 * Now we have successfully completed the lookup, if the
5912 	 * directory has changed we now have the valid attributes.
5913 	 * We also know we have directory access.
5914 	 * Create the new rnode and insert it in the dnlc.
5915 	 */
5916 	if (isdotdot) {
5917 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5918 		if (e.error) {
5919 			sfh4_rele(&sfhp);
5920 			goto exit;
5921 		}
5922 		/*
5923 		 * XXX if nfs4_make_dotdot uses an existing rnode
5924 		 * XXX it doesn't update the attributes.
5925 		 * XXX for now just save them again to save an OTW
5926 		 */
5927 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5928 	} else {
5929 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5930 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5931 	}
5932 	sfh4_rele(&sfhp);
5933 
5934 	nrp = VTOR4(nvp);
5935 	mutex_enter(&nrp->r_statev4_lock);
5936 	if (!nrp->created_v4) {
5937 		mutex_exit(&nrp->r_statev4_lock);
5938 		dnlc_update(dvp, nm, nvp);
5939 	} else
5940 		mutex_exit(&nrp->r_statev4_lock);
5941 
5942 	*vpp = nvp;
5943 
5944 exit:
5945 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5946 	kmem_free(argop, argoplist_size);
5947 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5948 	return (e.error);
5949 }
5950 
5951 #ifdef DEBUG
5952 void
5953 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
5954 {
5955 	uint_t i, len;
5956 	zoneid_t zoneid = getzoneid();
5957 	char *s;
5958 
5959 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
5960 	for (i = 0; i < argcnt; i++) {
5961 		nfs_argop4 *op = &argbase[i];
5962 		switch (op->argop) {
5963 		case OP_CPUTFH:
5964 		case OP_PUTFH:
5965 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
5966 			break;
5967 		case OP_PUTROOTFH:
5968 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
5969 			break;
5970 		case OP_CLOOKUP:
5971 			s = op->nfs_argop4_u.opclookup.cname;
5972 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5973 			break;
5974 		case OP_LOOKUP:
5975 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
5976 			    &len, NULL);
5977 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5978 			kmem_free(s, len);
5979 			break;
5980 		case OP_LOOKUPP:
5981 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
5982 			break;
5983 		case OP_GETFH:
5984 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
5985 			break;
5986 		case OP_GETATTR:
5987 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
5988 			break;
5989 		case OP_OPENATTR:
5990 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
5991 			break;
5992 		default:
5993 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
5994 			    op->argop);
5995 			break;
5996 		}
5997 	}
5998 }
5999 #endif
6000 
6001 /*
6002  * nfs4lookup_setup - constructs a multi-lookup compound request.
6003  *
6004  * Given the path "nm1/nm2/.../nmn", the following compound requests
6005  * may be created:
6006  *
6007  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
6008  * is faster, for now.
6009  *
6010  * l4_getattrs indicates the type of compound requested.
6011  *
6012  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
6013  *
6014  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
6015  *
6016  *   total number of ops is n + 1.
6017  *
6018  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
6019  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
6020  *      before the last component, and only get attributes
6021  *      for the last component.  Note that the second-to-last
6022  *	pathname component is XATTR_RPATH, which does NOT go
6023  *	over-the-wire as a lookup.
6024  *
6025  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
6026  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
6027  *
6028  *   and total number of ops is n + 5.
6029  *
6030  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
6031  *      attribute directory: create lookups plus an OPENATTR
6032  *	replacing the last lookup.  Note that the last pathname
6033  *	component is XATTR_RPATH, which does NOT go over-the-wire
6034  *	as a lookup.
6035  *
6036  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
6037  *		Openattr; Getfh; Getattr }
6038  *
6039  *   and total number of ops is n + 5.
6040  *
6041  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6042  *	nodes too.
6043  *
6044  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6045  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6046  *
6047  *   and total number of ops is 3*n + 1.
6048  *
6049  * All cases: returns the index in the arg array of the final LOOKUP op, or
6050  * -1 if no LOOKUPs were used.
6051  */
6052 int
6053 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6054 {
6055 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6056 	nfs_argop4 *argbase, *argop;
6057 	int arglen, argcnt;
6058 	int n = 1;	/* number of components */
6059 	int nga = 1;	/* number of Getattr's in request */
6060 	char c = '\0', *s, *p;
6061 	int lookup_idx = -1;
6062 	int argoplist_size;
6063 
6064 	/* set lookuparg response result to 0 */
6065 	lookupargp->resp->status = NFS4_OK;
6066 
6067 	/* skip leading "/" or "." e.g. ".//./" if there is */
6068 	for (; ; nm++) {
6069 		if (*nm != '/' && *nm != '.')
6070 			break;
6071 
6072 		/* ".." is counted as 1 component */
6073 		if (*nm == '.' && *(nm + 1) == '.')
6074 			break;
6075 	}
6076 
6077 	/*
6078 	 * Find n = number of components - nm must be null terminated
6079 	 * Skip "." components.
6080 	 */
6081 	if (*nm != '\0')
6082 		for (n = 1, s = nm; *s != '\0'; s++) {
6083 			if ((*s == '/') && (*(s + 1) != '/') &&
6084 			    (*(s + 1) != '\0') &&
6085 			    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6086 			    *(s + 2) == '\0')))
6087 				n++;
6088 		}
6089 	else
6090 		n = 0;
6091 
6092 	/*
6093 	 * nga is number of components that need Getfh+Getattr
6094 	 */
6095 	switch (l4_getattrs) {
6096 	case LKP4_NO_ATTRIBUTES:
6097 		nga = 0;
6098 		break;
6099 	case LKP4_ALL_ATTRIBUTES:
6100 		nga = n;
6101 		/*
6102 		 * Always have at least 1 getfh, getattr pair
6103 		 */
6104 		if (nga == 0)
6105 			nga++;
6106 		break;
6107 	case LKP4_LAST_ATTRDIR:
6108 	case LKP4_LAST_NAMED_ATTR:
6109 		nga = n+1;
6110 		break;
6111 	}
6112 
6113 	/*
6114 	 * If change to use the filehandle attr instead of getfh
6115 	 * the following line can be deleted.
6116 	 */
6117 	nga *= 2;
6118 
6119 	/*
6120 	 * calculate number of ops in request as
6121 	 * header + trailer + lookups + getattrs
6122 	 */
6123 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6124 
6125 	argoplist_size = arglen * sizeof (nfs_argop4);
6126 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6127 	lookupargp->argsp->array = argop;
6128 
6129 	argcnt = lookupargp->header_len;
6130 	argop += argcnt;
6131 
6132 	/*
6133 	 * loop and create a lookup op and possibly getattr/getfh for
6134 	 * each component. Skip "." components.
6135 	 */
6136 	for (s = nm; *s != '\0'; s = p) {
6137 		/*
6138 		 * Set up a pathname struct for each component if needed
6139 		 */
6140 		while (*s == '/')
6141 			s++;
6142 		if (*s == '\0')
6143 			break;
6144 
6145 		for (p = s; (*p != '/') && (*p != '\0'); p++)
6146 			;
6147 		c = *p;
6148 		*p = '\0';
6149 
6150 		if (s[0] == '.' && s[1] == '\0') {
6151 			*p = c;
6152 			continue;
6153 		}
6154 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6155 		    strcmp(s, XATTR_RPATH) == 0) {
6156 			/* getfh XXX may not be needed in future */
6157 			argop->argop = OP_GETFH;
6158 			argop++;
6159 			argcnt++;
6160 
6161 			/* getattr */
6162 			argop->argop = OP_GETATTR;
6163 			argop->nfs_argop4_u.opgetattr.attr_request =
6164 			    lookupargp->ga_bits;
6165 			argop->nfs_argop4_u.opgetattr.mi =
6166 			    lookupargp->mi;
6167 			argop++;
6168 			argcnt++;
6169 
6170 			/* openattr */
6171 			argop->argop = OP_OPENATTR;
6172 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6173 		    strcmp(s, XATTR_RPATH) == 0) {
6174 			/* openattr */
6175 			argop->argop = OP_OPENATTR;
6176 			argop++;
6177 			argcnt++;
6178 
6179 			/* getfh XXX may not be needed in future */
6180 			argop->argop = OP_GETFH;
6181 			argop++;
6182 			argcnt++;
6183 
6184 			/* getattr */
6185 			argop->argop = OP_GETATTR;
6186 			argop->nfs_argop4_u.opgetattr.attr_request =
6187 			    lookupargp->ga_bits;
6188 			argop->nfs_argop4_u.opgetattr.mi =
6189 			    lookupargp->mi;
6190 			argop++;
6191 			argcnt++;
6192 			*p = c;
6193 			continue;
6194 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6195 			/* lookupp */
6196 			argop->argop = OP_LOOKUPP;
6197 		} else {
6198 			/* lookup */
6199 			argop->argop = OP_LOOKUP;
6200 			(void) str_to_utf8(s,
6201 			    &argop->nfs_argop4_u.oplookup.objname);
6202 		}
6203 		lookup_idx = argcnt;
6204 		argop++;
6205 		argcnt++;
6206 
6207 		*p = c;
6208 
6209 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6210 			/* getfh XXX may not be needed in future */
6211 			argop->argop = OP_GETFH;
6212 			argop++;
6213 			argcnt++;
6214 
6215 			/* getattr */
6216 			argop->argop = OP_GETATTR;
6217 			argop->nfs_argop4_u.opgetattr.attr_request =
6218 			    lookupargp->ga_bits;
6219 			argop->nfs_argop4_u.opgetattr.mi =
6220 			    lookupargp->mi;
6221 			argop++;
6222 			argcnt++;
6223 		}
6224 	}
6225 
6226 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6227 	    ((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6228 		if (needgetfh) {
6229 			/* stick in a post-lookup getfh */
6230 			argop->argop = OP_GETFH;
6231 			argcnt++;
6232 			argop++;
6233 		}
6234 		/* post-lookup getattr */
6235 		argop->argop = OP_GETATTR;
6236 		argop->nfs_argop4_u.opgetattr.attr_request =
6237 		    lookupargp->ga_bits;
6238 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6239 		argcnt++;
6240 	}
6241 	argcnt += lookupargp->trailer_len;	/* actual op count */
6242 	lookupargp->argsp->array_len = argcnt;
6243 	lookupargp->arglen = arglen;
6244 
6245 #ifdef DEBUG
6246 	if (nfs4_client_lookup_debug)
6247 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6248 #endif
6249 
6250 	return (lookup_idx);
6251 }
6252 
6253 static int
6254 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6255 {
6256 	COMPOUND4args_clnt	args;
6257 	COMPOUND4res_clnt	res;
6258 	GETFH4res	*gf_res = NULL;
6259 	nfs_argop4	argop[4];
6260 	nfs_resop4	*resop = NULL;
6261 	nfs4_sharedfh_t *sfhp;
6262 	hrtime_t t;
6263 	nfs4_error_t	e;
6264 
6265 	rnode4_t	*drp;
6266 	int		doqueue = 1;
6267 	vnode_t		*vp;
6268 	int		needrecov = 0;
6269 	nfs4_recov_state_t recov_state;
6270 
6271 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6272 
6273 	*avp = NULL;
6274 	recov_state.rs_flags = 0;
6275 	recov_state.rs_num_retry_despite_err = 0;
6276 
6277 recov_retry:
6278 	/* COMPOUND: putfh, openattr, getfh, getattr */
6279 	args.array_len = 4;
6280 	args.array = argop;
6281 	args.ctag = TAG_OPENATTR;
6282 
6283 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6284 	if (e.error)
6285 		return (e.error);
6286 
6287 	drp = VTOR4(dvp);
6288 
6289 	/* putfh */
6290 	argop[0].argop = OP_CPUTFH;
6291 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6292 
6293 	/* openattr */
6294 	argop[1].argop = OP_OPENATTR;
6295 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6296 
6297 	/* getfh */
6298 	argop[2].argop = OP_GETFH;
6299 
6300 	/* getattr */
6301 	argop[3].argop = OP_GETATTR;
6302 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6303 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6304 
6305 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6306 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6307 	    rnode4info(drp)));
6308 
6309 	t = gethrtime();
6310 
6311 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6312 
6313 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6314 	if (needrecov) {
6315 		bool_t abort;
6316 
6317 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6318 		    "nfs4openattr: initiating recovery\n"));
6319 
6320 		abort = nfs4_start_recovery(&e,
6321 		    VTOMI4(dvp), dvp, NULL, NULL, NULL,
6322 		    OP_OPENATTR, NULL);
6323 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6324 		if (!e.error) {
6325 			e.error = geterrno4(res.status);
6326 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6327 		}
6328 		if (abort == FALSE)
6329 			goto recov_retry;
6330 		return (e.error);
6331 	}
6332 
6333 	if (e.error) {
6334 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6335 		return (e.error);
6336 	}
6337 
6338 	if (res.status) {
6339 		/*
6340 		 * If OTW errro is NOTSUPP, then it should be
6341 		 * translated to EINVAL.  All Solaris file system
6342 		 * implementations return EINVAL to the syscall layer
6343 		 * when the attrdir cannot be created due to an
6344 		 * implementation restriction or noxattr mount option.
6345 		 */
6346 		if (res.status == NFS4ERR_NOTSUPP) {
6347 			mutex_enter(&drp->r_statelock);
6348 			if (drp->r_xattr_dir)
6349 				VN_RELE(drp->r_xattr_dir);
6350 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6351 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6352 			mutex_exit(&drp->r_statelock);
6353 
6354 			e.error = EINVAL;
6355 		} else {
6356 			e.error = geterrno4(res.status);
6357 		}
6358 
6359 		if (e.error) {
6360 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6361 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6362 			    needrecov);
6363 			return (e.error);
6364 		}
6365 	}
6366 
6367 	resop = &res.array[0];  /* putfh res */
6368 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6369 
6370 	resop = &res.array[1];  /* openattr res */
6371 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6372 
6373 	resop = &res.array[2];  /* getfh res */
6374 	gf_res = &resop->nfs_resop4_u.opgetfh;
6375 	if (gf_res->object.nfs_fh4_len == 0) {
6376 		*avp = NULL;
6377 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6378 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6379 		return (ENOENT);
6380 	}
6381 
6382 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6383 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6384 	    dvp->v_vfsp, t, cr, dvp,
6385 	    fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH));
6386 	sfh4_rele(&sfhp);
6387 
6388 	if (e.error)
6389 		PURGE_ATTRCACHE4(vp);
6390 
6391 	mutex_enter(&vp->v_lock);
6392 	vp->v_flag |= V_XATTRDIR;
6393 	mutex_exit(&vp->v_lock);
6394 
6395 	*avp = vp;
6396 
6397 	mutex_enter(&drp->r_statelock);
6398 	if (drp->r_xattr_dir)
6399 		VN_RELE(drp->r_xattr_dir);
6400 	VN_HOLD(vp);
6401 	drp->r_xattr_dir = vp;
6402 
6403 	/*
6404 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6405 	 * NULL.  xattrs could be created at any time, and we have no
6406 	 * way to update pc4_xattr_exists in the base object if/when
6407 	 * it happens.
6408 	 */
6409 	drp->r_pathconf.pc4_xattr_valid = 0;
6410 
6411 	mutex_exit(&drp->r_statelock);
6412 
6413 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6414 
6415 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6416 
6417 	return (0);
6418 }
6419 
6420 /* ARGSUSED */
6421 static int
6422 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6423 	int mode, vnode_t **vpp, cred_t *cr, int flags, caller_context_t *ct,
6424 	vsecattr_t *vsecp)
6425 {
6426 	int error;
6427 	vnode_t *vp = NULL;
6428 	rnode4_t *rp;
6429 	struct vattr vattr;
6430 	rnode4_t *drp;
6431 	vnode_t *tempvp;
6432 	enum createmode4 createmode;
6433 	bool_t must_trunc = FALSE;
6434 	int	truncating = 0;
6435 
6436 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6437 		return (EPERM);
6438 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6439 		return (EINVAL);
6440 	}
6441 
6442 	/* . and .. have special meaning in the protocol, reject them. */
6443 
6444 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6445 		return (EISDIR);
6446 
6447 	drp = VTOR4(dvp);
6448 
6449 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6450 		return (EINTR);
6451 
6452 top:
6453 	/*
6454 	 * We make a copy of the attributes because the caller does not
6455 	 * expect us to change what va points to.
6456 	 */
6457 	vattr = *va;
6458 
6459 	/*
6460 	 * If the pathname is "", then dvp is the root vnode of
6461 	 * a remote file mounted over a local directory.
6462 	 * All that needs to be done is access
6463 	 * checking and truncation.  Note that we avoid doing
6464 	 * open w/ create because the parent directory might
6465 	 * be in pseudo-fs and the open would fail.
6466 	 */
6467 	if (*nm == '\0') {
6468 		error = 0;
6469 		VN_HOLD(dvp);
6470 		vp = dvp;
6471 		must_trunc = TRUE;
6472 	} else {
6473 		/*
6474 		 * We need to go over the wire, just to be sure whether the
6475 		 * file exists or not.  Using the DNLC can be dangerous in
6476 		 * this case when making a decision regarding existence.
6477 		 */
6478 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6479 	}
6480 
6481 	if (exclusive)
6482 		createmode = EXCLUSIVE4;
6483 	else
6484 		createmode = GUARDED4;
6485 
6486 	/*
6487 	 * error would be set if the file does not exist on the
6488 	 * server, so lets go create it.
6489 	 */
6490 	if (error) {
6491 		goto create_otw;
6492 	}
6493 
6494 	/*
6495 	 * File does exist on the server
6496 	 */
6497 	if (exclusive == EXCL)
6498 		error = EEXIST;
6499 	else if (vp->v_type == VDIR && (mode & VWRITE))
6500 		error = EISDIR;
6501 	else {
6502 		/*
6503 		 * If vnode is a device, create special vnode.
6504 		 */
6505 		if (ISVDEV(vp->v_type)) {
6506 			tempvp = vp;
6507 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6508 			VN_RELE(tempvp);
6509 		}
6510 		if (!(error = VOP_ACCESS(vp, mode, 0, cr, ct))) {
6511 			if ((vattr.va_mask & AT_SIZE) &&
6512 			    vp->v_type == VREG) {
6513 				rp = VTOR4(vp);
6514 				/*
6515 				 * Check here for large file handled
6516 				 * by LF-unaware process (as
6517 				 * ufs_create() does)
6518 				 */
6519 				if (!(flags & FOFFMAX)) {
6520 					mutex_enter(&rp->r_statelock);
6521 					if (rp->r_size > MAXOFF32_T)
6522 						error = EOVERFLOW;
6523 					mutex_exit(&rp->r_statelock);
6524 				}
6525 
6526 				/* if error is set then we need to return */
6527 				if (error) {
6528 					nfs_rw_exit(&drp->r_rwlock);
6529 					VN_RELE(vp);
6530 					return (error);
6531 				}
6532 
6533 				if (must_trunc) {
6534 					vattr.va_mask = AT_SIZE;
6535 					error = nfs4setattr(vp, &vattr, 0, cr,
6536 					    NULL);
6537 				} else {
6538 				/*
6539 				 * we know we have a regular file that already
6540 				 * exists and we may end up truncating the file
6541 				 * as a result of the open_otw, so flush out
6542 				 * any dirty pages for this file first.
6543 				 */
6544 					if (nfs4_has_pages(vp) &&
6545 					    ((rp->r_flags & R4DIRTY) ||
6546 					    rp->r_count > 0 ||
6547 					    rp->r_mapcnt > 0)) {
6548 						error = nfs4_putpage(vp,
6549 						    (offset_t)0, 0, 0, cr, ct);
6550 						if (error && (error == ENOSPC ||
6551 						    error == EDQUOT)) {
6552 							mutex_enter(
6553 							    &rp->r_statelock);
6554 							if (!rp->r_error)
6555 								rp->r_error =
6556 								    error;
6557 							mutex_exit(
6558 							    &rp->r_statelock);
6559 						}
6560 					}
6561 					vattr.va_mask = (AT_SIZE |
6562 					    AT_TYPE | AT_MODE);
6563 					vattr.va_type = VREG;
6564 					createmode = UNCHECKED4;
6565 					truncating = 1;
6566 					goto create_otw;
6567 				}
6568 			}
6569 		}
6570 	}
6571 	nfs_rw_exit(&drp->r_rwlock);
6572 	if (error) {
6573 		VN_RELE(vp);
6574 	} else {
6575 		vnode_t *tvp;
6576 		rnode4_t *trp;
6577 		/*
6578 		 * existing file got truncated, notify.
6579 		 */
6580 		tvp = vp;
6581 		if (vp->v_type == VREG) {
6582 			trp = VTOR4(vp);
6583 			if (IS_SHADOW(vp, trp))
6584 				tvp = RTOV4(trp);
6585 		}
6586 		vnevent_create(tvp, ct);
6587 		*vpp = vp;
6588 	}
6589 	return (error);
6590 
6591 create_otw:
6592 	dnlc_remove(dvp, nm);
6593 
6594 	ASSERT(vattr.va_mask & AT_TYPE);
6595 
6596 	/*
6597 	 * If not a regular file let nfs4mknod() handle it.
6598 	 */
6599 	if (vattr.va_type != VREG) {
6600 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6601 		nfs_rw_exit(&drp->r_rwlock);
6602 		return (error);
6603 	}
6604 
6605 	/*
6606 	 * It _is_ a regular file.
6607 	 */
6608 	ASSERT(vattr.va_mask & AT_MODE);
6609 	if (MANDMODE(vattr.va_mode)) {
6610 		nfs_rw_exit(&drp->r_rwlock);
6611 		return (EACCES);
6612 	}
6613 
6614 	/*
6615 	 * If this happens to be a mknod of a regular file, then flags will
6616 	 * have neither FREAD or FWRITE.  However, we must set at least one
6617 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6618 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6619 	 * set (based on openmode specified by app).
6620 	 */
6621 	if ((flags & (FREAD|FWRITE)) == 0)
6622 		flags |= (FREAD|FWRITE);
6623 
6624 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6625 
6626 	if (vp != NULL) {
6627 		/* if create was successful, throw away the file's pages */
6628 		if (!error && (vattr.va_mask & AT_SIZE))
6629 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6630 			    cr);
6631 		/* release the lookup hold */
6632 		VN_RELE(vp);
6633 		vp = NULL;
6634 	}
6635 
6636 	/*
6637 	 * validate that we opened a regular file. This handles a misbehaving
6638 	 * server that returns an incorrect FH.
6639 	 */
6640 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6641 		error = EISDIR;
6642 		VN_RELE(*vpp);
6643 	}
6644 
6645 	/*
6646 	 * If this is not an exclusive create, then the CREATE
6647 	 * request will be made with the GUARDED mode set.  This
6648 	 * means that the server will return EEXIST if the file
6649 	 * exists.  The file could exist because of a retransmitted
6650 	 * request.  In this case, we recover by starting over and
6651 	 * checking to see whether the file exists.  This second
6652 	 * time through it should and a CREATE request will not be
6653 	 * sent.
6654 	 *
6655 	 * This handles the problem of a dangling CREATE request
6656 	 * which contains attributes which indicate that the file
6657 	 * should be truncated.  This retransmitted request could
6658 	 * possibly truncate valid data in the file if not caught
6659 	 * by the duplicate request mechanism on the server or if
6660 	 * not caught by other means.  The scenario is:
6661 	 *
6662 	 * Client transmits CREATE request with size = 0
6663 	 * Client times out, retransmits request.
6664 	 * Response to the first request arrives from the server
6665 	 *  and the client proceeds on.
6666 	 * Client writes data to the file.
6667 	 * The server now processes retransmitted CREATE request
6668 	 *  and truncates file.
6669 	 *
6670 	 * The use of the GUARDED CREATE request prevents this from
6671 	 * happening because the retransmitted CREATE would fail
6672 	 * with EEXIST and would not truncate the file.
6673 	 */
6674 	if (error == EEXIST && exclusive == NONEXCL) {
6675 #ifdef DEBUG
6676 		nfs4_create_misses++;
6677 #endif
6678 		goto top;
6679 	}
6680 	nfs_rw_exit(&drp->r_rwlock);
6681 	if (truncating && !error && *vpp) {
6682 		vnode_t *tvp;
6683 		rnode4_t *trp;
6684 		/*
6685 		 * existing file got truncated, notify.
6686 		 */
6687 		tvp = *vpp;
6688 		trp = VTOR4(tvp);
6689 		if (IS_SHADOW(tvp, trp))
6690 			tvp = RTOV4(trp);
6691 		vnevent_create(tvp, ct);
6692 	}
6693 	return (error);
6694 }
6695 
6696 /*
6697  * Create compound (for mkdir, mknod, symlink):
6698  * { Putfh <dfh>; Create; Getfh; Getattr }
6699  * It's okay if setattr failed to set gid - this is not considered
6700  * an error, but purge attrs in that case.
6701  */
6702 static int
6703 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6704     vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6705 {
6706 	int need_end_op = FALSE;
6707 	COMPOUND4args_clnt args;
6708 	COMPOUND4res_clnt res, *resp = NULL;
6709 	nfs_argop4 *argop;
6710 	nfs_resop4 *resop;
6711 	int doqueue;
6712 	mntinfo4_t *mi;
6713 	rnode4_t *drp = VTOR4(dvp);
6714 	change_info4 *cinfo;
6715 	GETFH4res *gf_res;
6716 	struct vattr vattr;
6717 	vnode_t *vp;
6718 	fattr4 *crattr;
6719 	bool_t needrecov = FALSE;
6720 	nfs4_recov_state_t recov_state;
6721 	nfs4_sharedfh_t *sfhp = NULL;
6722 	hrtime_t t;
6723 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6724 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6725 	dirattr_info_t dinfo, *dinfop;
6726 	servinfo4_t *svp;
6727 	bitmap4 supp_attrs;
6728 
6729 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6730 	    type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6731 
6732 	mi = VTOMI4(dvp);
6733 
6734 	/*
6735 	 * Make sure we properly deal with setting the right gid
6736 	 * on a new directory to reflect the parent's setgid bit
6737 	 */
6738 	setgid_flag = 0;
6739 	if (type == NF4DIR) {
6740 		struct vattr dva;
6741 
6742 		va->va_mode &= ~VSGID;
6743 		dva.va_mask = AT_MODE | AT_GID;
6744 		if (VOP_GETATTR(dvp, &dva, 0, cr, NULL) == 0) {
6745 
6746 			/*
6747 			 * If the parent's directory has the setgid bit set
6748 			 * _and_ the client was able to get a valid mapping
6749 			 * for the parent dir's owner_group, we want to
6750 			 * append NVERIFY(owner_group == dva.va_gid) and
6751 			 * SETTATTR to the CREATE compound.
6752 			 */
6753 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6754 				setgid_flag = 1;
6755 				va->va_mode |= VSGID;
6756 				if (dva.va_gid != GID_NOBODY) {
6757 					va->va_mask |= AT_GID;
6758 					va->va_gid = dva.va_gid;
6759 				}
6760 			}
6761 		}
6762 	}
6763 
6764 	/*
6765 	 * Create ops:
6766 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6767 	 *	5:restorefh(dir) 6:getattr(dir)
6768 	 *
6769 	 * if (setgid)
6770 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6771 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6772 	 *	8:nverify 9:setattr
6773 	 */
6774 	if (setgid_flag) {
6775 		numops = 10;
6776 		idx_create = 1;
6777 		idx_fattr = 3;
6778 	} else {
6779 		numops = 7;
6780 		idx_create = 2;
6781 		idx_fattr = 4;
6782 	}
6783 
6784 	ASSERT(nfs_zone() == mi->mi_zone);
6785 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6786 		return (EINTR);
6787 	}
6788 	recov_state.rs_flags = 0;
6789 	recov_state.rs_num_retry_despite_err = 0;
6790 
6791 	argoplist_size = numops * sizeof (nfs_argop4);
6792 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6793 
6794 recov_retry:
6795 	if (type == NF4LNK)
6796 		args.ctag = TAG_SYMLINK;
6797 	else if (type == NF4DIR)
6798 		args.ctag = TAG_MKDIR;
6799 	else
6800 		args.ctag = TAG_MKNOD;
6801 
6802 	args.array_len = numops;
6803 	args.array = argop;
6804 
6805 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6806 		nfs_rw_exit(&drp->r_rwlock);
6807 		kmem_free(argop, argoplist_size);
6808 		return (e.error);
6809 	}
6810 	need_end_op = TRUE;
6811 
6812 
6813 	/* 0: putfh directory */
6814 	argop[0].argop = OP_CPUTFH;
6815 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6816 
6817 	/* 1/2: Create object */
6818 	argop[idx_create].argop = OP_CCREATE;
6819 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6820 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6821 	if (type == NF4LNK) {
6822 		/*
6823 		 * symlink, treat name as data
6824 		 */
6825 		ASSERT(data != NULL);
6826 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6827 		    (char *)data;
6828 	}
6829 	if (type == NF4BLK || type == NF4CHR) {
6830 		ASSERT(data != NULL);
6831 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6832 		    *((specdata4 *)data);
6833 	}
6834 
6835 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6836 
6837 	svp = drp->r_server;
6838 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6839 	supp_attrs = svp->sv_supp_attrs;
6840 	nfs_rw_exit(&svp->sv_lock);
6841 
6842 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6843 		nfs_rw_exit(&drp->r_rwlock);
6844 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6845 		e.error = EINVAL;
6846 		kmem_free(argop, argoplist_size);
6847 		return (e.error);
6848 	}
6849 
6850 	/* 2/3: getfh fh of created object */
6851 	ASSERT(idx_create + 1 == idx_fattr - 1);
6852 	argop[idx_create + 1].argop = OP_GETFH;
6853 
6854 	/* 3/4: getattr of new object */
6855 	argop[idx_fattr].argop = OP_GETATTR;
6856 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6857 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6858 
6859 	if (setgid_flag) {
6860 		vattr_t	_v;
6861 
6862 		argop[4].argop = OP_SAVEFH;
6863 
6864 		argop[5].argop = OP_CPUTFH;
6865 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6866 
6867 		argop[6].argop = OP_GETATTR;
6868 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6869 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6870 
6871 		argop[7].argop = OP_RESTOREFH;
6872 
6873 		/*
6874 		 * nverify
6875 		 *
6876 		 * XXX - Revisit the last argument to nfs4_end_op()
6877 		 *	 once 5020486 is fixed.
6878 		 */
6879 		_v.va_mask = AT_GID;
6880 		_v.va_gid = va->va_gid;
6881 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6882 		    supp_attrs)) {
6883 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6884 			nfs_rw_exit(&drp->r_rwlock);
6885 			nfs4_fattr4_free(crattr);
6886 			kmem_free(argop, argoplist_size);
6887 			return (e.error);
6888 		}
6889 
6890 		/*
6891 		 * setattr
6892 		 *
6893 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
6894 		 * so no need for stateid or flags. Also we specify NULL
6895 		 * rp since we're only interested in setting owner_group
6896 		 * attributes.
6897 		 */
6898 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
6899 		    &e.error, 0);
6900 
6901 		if (e.error) {
6902 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6903 			nfs_rw_exit(&drp->r_rwlock);
6904 			nfs4_fattr4_free(crattr);
6905 			nfs4args_verify_free(&argop[8]);
6906 			kmem_free(argop, argoplist_size);
6907 			return (e.error);
6908 		}
6909 	} else {
6910 		argop[1].argop = OP_SAVEFH;
6911 
6912 		argop[5].argop = OP_RESTOREFH;
6913 
6914 		argop[6].argop = OP_GETATTR;
6915 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6916 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6917 	}
6918 
6919 	dnlc_remove(dvp, nm);
6920 
6921 	doqueue = 1;
6922 	t = gethrtime();
6923 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
6924 
6925 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
6926 	if (e.error) {
6927 		PURGE_ATTRCACHE4(dvp);
6928 		if (!needrecov)
6929 			goto out;
6930 	}
6931 
6932 	if (needrecov) {
6933 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
6934 		    OP_CREATE, NULL) == FALSE) {
6935 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6936 			    needrecov);
6937 			need_end_op = FALSE;
6938 			nfs4_fattr4_free(crattr);
6939 			if (setgid_flag) {
6940 				nfs4args_verify_free(&argop[8]);
6941 				nfs4args_setattr_free(&argop[9]);
6942 			}
6943 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6944 			goto recov_retry;
6945 		}
6946 	}
6947 
6948 	resp = &res;
6949 
6950 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
6951 
6952 		if (res.status == NFS4ERR_BADOWNER)
6953 			nfs4_log_badowner(mi, OP_CREATE);
6954 
6955 		e.error = geterrno4(res.status);
6956 
6957 		/*
6958 		 * This check is left over from when create was implemented
6959 		 * using a setattr op (instead of createattrs).  If the
6960 		 * putfh/create/getfh failed, the error was returned.  If
6961 		 * setattr/getattr failed, we keep going.
6962 		 *
6963 		 * It might be better to get rid of the GETFH also, and just
6964 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
6965 		 * Then if any of the operations failed, we could return the
6966 		 * error now, and remove much of the error code below.
6967 		 */
6968 		if (res.array_len <= idx_fattr) {
6969 			/*
6970 			 * Either Putfh, Create or Getfh failed.
6971 			 */
6972 			PURGE_ATTRCACHE4(dvp);
6973 			/*
6974 			 * nfs4_purge_stale_fh() may generate otw calls through
6975 			 * nfs4_invalidate_pages. Hence the need to call
6976 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
6977 			 */
6978 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6979 			    needrecov);
6980 			need_end_op = FALSE;
6981 			nfs4_purge_stale_fh(e.error, dvp, cr);
6982 			goto out;
6983 		}
6984 	}
6985 
6986 	resop = &res.array[idx_create];	/* create res */
6987 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
6988 
6989 	resop = &res.array[idx_create + 1]; /* getfh res */
6990 	gf_res = &resop->nfs_resop4_u.opgetfh;
6991 
6992 	sfhp = sfh4_get(&gf_res->object, mi);
6993 	if (e.error) {
6994 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
6995 		    fn_get(VTOSV(dvp)->sv_name, nm));
6996 		if (vp->v_type == VNON) {
6997 			vattr.va_mask = AT_TYPE;
6998 			/*
6999 			 * Need to call nfs4_end_op before nfs4getattr to avoid
7000 			 * potential nfs4_start_op deadlock. See RFE 4777612.
7001 			 */
7002 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7003 			    needrecov);
7004 			need_end_op = FALSE;
7005 			e.error = nfs4getattr(vp, &vattr, cr);
7006 			if (e.error) {
7007 				VN_RELE(vp);
7008 				*vpp = NULL;
7009 				goto out;
7010 			}
7011 			vp->v_type = vattr.va_type;
7012 		}
7013 		e.error = 0;
7014 	} else {
7015 		*vpp = vp = makenfs4node(sfhp,
7016 		    &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
7017 		    dvp->v_vfsp, t, cr,
7018 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
7019 	}
7020 
7021 	/*
7022 	 * If compound succeeded, then update dir attrs
7023 	 */
7024 	if (res.status == NFS4_OK) {
7025 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
7026 		dinfo.di_cred = cr;
7027 		dinfo.di_time_call = t;
7028 		dinfop = &dinfo;
7029 	} else
7030 		dinfop = NULL;
7031 
7032 	/* Update directory cache attribute, readdir and dnlc caches */
7033 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
7034 
7035 out:
7036 	if (sfhp != NULL)
7037 		sfh4_rele(&sfhp);
7038 	nfs_rw_exit(&drp->r_rwlock);
7039 	nfs4_fattr4_free(crattr);
7040 	if (setgid_flag) {
7041 		nfs4args_verify_free(&argop[8]);
7042 		nfs4args_setattr_free(&argop[9]);
7043 	}
7044 	if (resp)
7045 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7046 	if (need_end_op)
7047 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7048 
7049 	kmem_free(argop, argoplist_size);
7050 	return (e.error);
7051 }
7052 
7053 /* ARGSUSED */
7054 static int
7055 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7056     int mode, vnode_t **vpp, cred_t *cr)
7057 {
7058 	int error;
7059 	vnode_t *vp;
7060 	nfs_ftype4 type;
7061 	specdata4 spec, *specp = NULL;
7062 
7063 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7064 
7065 	switch (va->va_type) {
7066 	case VCHR:
7067 	case VBLK:
7068 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7069 		spec.specdata1 = getmajor(va->va_rdev);
7070 		spec.specdata2 = getminor(va->va_rdev);
7071 		specp = &spec;
7072 		break;
7073 
7074 	case VFIFO:
7075 		type = NF4FIFO;
7076 		break;
7077 	case VSOCK:
7078 		type = NF4SOCK;
7079 		break;
7080 
7081 	default:
7082 		return (EINVAL);
7083 	}
7084 
7085 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7086 	if (error) {
7087 		return (error);
7088 	}
7089 
7090 	/*
7091 	 * This might not be needed any more; special case to deal
7092 	 * with problematic v2/v3 servers.  Since create was unable
7093 	 * to set group correctly, not sure what hope setattr has.
7094 	 */
7095 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7096 		va->va_mask = AT_GID;
7097 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7098 	}
7099 
7100 	/*
7101 	 * If vnode is a device create special vnode
7102 	 */
7103 	if (ISVDEV(vp->v_type)) {
7104 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7105 		VN_RELE(vp);
7106 	} else {
7107 		*vpp = vp;
7108 	}
7109 	return (error);
7110 }
7111 
7112 /*
7113  * Remove requires that the current fh be the target directory.
7114  * After the operation, the current fh is unchanged.
7115  * The compound op structure is:
7116  *      PUTFH(targetdir), REMOVE
7117  *
7118  * Weirdness: if the vnode to be removed is open
7119  * we rename it instead of removing it and nfs_inactive
7120  * will remove the new name.
7121  */
7122 /* ARGSUSED */
7123 static int
7124 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr, caller_context_t *ct, int flags)
7125 {
7126 	COMPOUND4args_clnt args;
7127 	COMPOUND4res_clnt res, *resp = NULL;
7128 	REMOVE4res *rm_res;
7129 	nfs_argop4 argop[3];
7130 	nfs_resop4 *resop;
7131 	vnode_t *vp;
7132 	char *tmpname;
7133 	int doqueue;
7134 	mntinfo4_t *mi;
7135 	rnode4_t *rp;
7136 	rnode4_t *drp;
7137 	int needrecov = 0;
7138 	nfs4_recov_state_t recov_state;
7139 	int isopen;
7140 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7141 	dirattr_info_t dinfo;
7142 
7143 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7144 		return (EPERM);
7145 	drp = VTOR4(dvp);
7146 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7147 		return (EINTR);
7148 
7149 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7150 	if (e.error) {
7151 		nfs_rw_exit(&drp->r_rwlock);
7152 		return (e.error);
7153 	}
7154 
7155 	if (vp->v_type == VDIR) {
7156 		VN_RELE(vp);
7157 		nfs_rw_exit(&drp->r_rwlock);
7158 		return (EISDIR);
7159 	}
7160 
7161 	/*
7162 	 * First just remove the entry from the name cache, as it
7163 	 * is most likely the only entry for this vp.
7164 	 */
7165 	dnlc_remove(dvp, nm);
7166 
7167 	rp = VTOR4(vp);
7168 
7169 	/*
7170 	 * For regular file types, check to see if the file is open by looking
7171 	 * at the open streams.
7172 	 * For all other types, check the reference count on the vnode.  Since
7173 	 * they are not opened OTW they never have an open stream.
7174 	 *
7175 	 * If the file is open, rename it to .nfsXXXX.
7176 	 */
7177 	if (vp->v_type != VREG) {
7178 		/*
7179 		 * If the file has a v_count > 1 then there may be more than one
7180 		 * entry in the name cache due multiple links or an open file,
7181 		 * but we don't have the real reference count so flush all
7182 		 * possible entries.
7183 		 */
7184 		if (vp->v_count > 1)
7185 			dnlc_purge_vp(vp);
7186 
7187 		/*
7188 		 * Now we have the real reference count.
7189 		 */
7190 		isopen = vp->v_count > 1;
7191 	} else {
7192 		mutex_enter(&rp->r_os_lock);
7193 		isopen = list_head(&rp->r_open_streams) != NULL;
7194 		mutex_exit(&rp->r_os_lock);
7195 	}
7196 
7197 	mutex_enter(&rp->r_statelock);
7198 	if (isopen &&
7199 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7200 		mutex_exit(&rp->r_statelock);
7201 		tmpname = newname();
7202 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr, ct);
7203 		if (e.error)
7204 			kmem_free(tmpname, MAXNAMELEN);
7205 		else {
7206 			mutex_enter(&rp->r_statelock);
7207 			if (rp->r_unldvp == NULL) {
7208 				VN_HOLD(dvp);
7209 				rp->r_unldvp = dvp;
7210 				if (rp->r_unlcred != NULL)
7211 					crfree(rp->r_unlcred);
7212 				crhold(cr);
7213 				rp->r_unlcred = cr;
7214 				rp->r_unlname = tmpname;
7215 			} else {
7216 				kmem_free(rp->r_unlname, MAXNAMELEN);
7217 				rp->r_unlname = tmpname;
7218 			}
7219 			mutex_exit(&rp->r_statelock);
7220 		}
7221 		VN_RELE(vp);
7222 		nfs_rw_exit(&drp->r_rwlock);
7223 		return (e.error);
7224 	}
7225 	/*
7226 	 * Actually remove the file/dir
7227 	 */
7228 	mutex_exit(&rp->r_statelock);
7229 
7230 	/*
7231 	 * We need to flush any dirty pages which happen to
7232 	 * be hanging around before removing the file.
7233 	 * This shouldn't happen very often since in NFSv4
7234 	 * we should be close to open consistent.
7235 	 */
7236 	if (nfs4_has_pages(vp) &&
7237 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7238 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, ct);
7239 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7240 			mutex_enter(&rp->r_statelock);
7241 			if (!rp->r_error)
7242 				rp->r_error = e.error;
7243 			mutex_exit(&rp->r_statelock);
7244 		}
7245 	}
7246 
7247 	mi = VTOMI4(dvp);
7248 
7249 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7250 	recov_state.rs_flags = 0;
7251 	recov_state.rs_num_retry_despite_err = 0;
7252 
7253 recov_retry:
7254 	/*
7255 	 * Remove ops: putfh dir; remove
7256 	 */
7257 	args.ctag = TAG_REMOVE;
7258 	args.array_len = 3;
7259 	args.array = argop;
7260 
7261 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7262 	if (e.error) {
7263 		nfs_rw_exit(&drp->r_rwlock);
7264 		VN_RELE(vp);
7265 		return (e.error);
7266 	}
7267 
7268 	/* putfh directory */
7269 	argop[0].argop = OP_CPUTFH;
7270 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7271 
7272 	/* remove */
7273 	argop[1].argop = OP_CREMOVE;
7274 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7275 
7276 	/* getattr dir */
7277 	argop[2].argop = OP_GETATTR;
7278 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7279 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7280 
7281 	doqueue = 1;
7282 	dinfo.di_time_call = gethrtime();
7283 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7284 
7285 	PURGE_ATTRCACHE4(vp);
7286 
7287 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7288 	if (e.error)
7289 		PURGE_ATTRCACHE4(dvp);
7290 
7291 	if (needrecov) {
7292 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7293 		    NULL, NULL, NULL, OP_REMOVE, NULL) == FALSE) {
7294 			if (!e.error)
7295 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7296 				    (caddr_t)&res);
7297 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7298 			    needrecov);
7299 			goto recov_retry;
7300 		}
7301 	}
7302 
7303 	/*
7304 	 * Matching nfs4_end_op() for start_op() above.
7305 	 * There is a path in the code below which calls
7306 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7307 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7308 	 * here to avoid nfs4_start_op() deadlock.
7309 	 */
7310 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7311 
7312 	if (!e.error) {
7313 		resp = &res;
7314 
7315 		if (res.status) {
7316 			e.error = geterrno4(res.status);
7317 			PURGE_ATTRCACHE4(dvp);
7318 			nfs4_purge_stale_fh(e.error, dvp, cr);
7319 		} else {
7320 			resop = &res.array[1];	/* remove res */
7321 			rm_res = &resop->nfs_resop4_u.opremove;
7322 
7323 			dinfo.di_garp =
7324 			    &res.array[2].nfs_resop4_u.opgetattr.ga_res;
7325 			dinfo.di_cred = cr;
7326 
7327 			/* Update directory attr, readdir and dnlc caches */
7328 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7329 			    &dinfo);
7330 		}
7331 	}
7332 	nfs_rw_exit(&drp->r_rwlock);
7333 	if (resp)
7334 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7335 
7336 	if (e.error == 0) {
7337 		vnode_t *tvp;
7338 		rnode4_t *trp;
7339 		trp = VTOR4(vp);
7340 		tvp = vp;
7341 		if (IS_SHADOW(vp, trp))
7342 			tvp = RTOV4(trp);
7343 		vnevent_remove(tvp, dvp, nm, ct);
7344 	}
7345 	VN_RELE(vp);
7346 	return (e.error);
7347 }
7348 
7349 /*
7350  * Link requires that the current fh be the target directory and the
7351  * saved fh be the source fh. After the operation, the current fh is unchanged.
7352  * Thus the compound op structure is:
7353  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7354  *	GETATTR(file)
7355  */
7356 /* ARGSUSED */
7357 static int
7358 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr,
7359     caller_context_t *ct, int flags)
7360 {
7361 	COMPOUND4args_clnt args;
7362 	COMPOUND4res_clnt res, *resp = NULL;
7363 	LINK4res *ln_res;
7364 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7365 	nfs_argop4 *argop;
7366 	nfs_resop4 *resop;
7367 	vnode_t *realvp, *nvp;
7368 	int doqueue;
7369 	mntinfo4_t *mi;
7370 	rnode4_t *tdrp;
7371 	bool_t needrecov = FALSE;
7372 	nfs4_recov_state_t recov_state;
7373 	hrtime_t t;
7374 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7375 	dirattr_info_t dinfo;
7376 
7377 	ASSERT(*tnm != '\0');
7378 	ASSERT(tdvp->v_type == VDIR);
7379 	ASSERT(nfs4_consistent_type(tdvp));
7380 	ASSERT(nfs4_consistent_type(svp));
7381 
7382 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7383 		return (EPERM);
7384 	if (VOP_REALVP(svp, &realvp, ct) == 0) {
7385 		svp = realvp;
7386 		ASSERT(nfs4_consistent_type(svp));
7387 	}
7388 
7389 	tdrp = VTOR4(tdvp);
7390 	mi = VTOMI4(svp);
7391 
7392 	if (!(mi->mi_flags & MI4_LINK)) {
7393 		return (EOPNOTSUPP);
7394 	}
7395 	recov_state.rs_flags = 0;
7396 	recov_state.rs_num_retry_despite_err = 0;
7397 
7398 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7399 		return (EINTR);
7400 
7401 recov_retry:
7402 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7403 
7404 	args.ctag = TAG_LINK;
7405 
7406 	/*
7407 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7408 	 * restorefh; getattr(fl)
7409 	 */
7410 	args.array_len = 7;
7411 	args.array = argop;
7412 
7413 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7414 	if (e.error) {
7415 		kmem_free(argop, argoplist_size);
7416 		nfs_rw_exit(&tdrp->r_rwlock);
7417 		return (e.error);
7418 	}
7419 
7420 	/* 0. putfh file */
7421 	argop[0].argop = OP_CPUTFH;
7422 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7423 
7424 	/* 1. save current fh to free up the space for the dir */
7425 	argop[1].argop = OP_SAVEFH;
7426 
7427 	/* 2. putfh targetdir */
7428 	argop[2].argop = OP_CPUTFH;
7429 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7430 
7431 	/* 3. link: current_fh is targetdir, saved_fh is source */
7432 	argop[3].argop = OP_CLINK;
7433 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7434 
7435 	/* 4. Get attributes of dir */
7436 	argop[4].argop = OP_GETATTR;
7437 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7438 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7439 
7440 	/* 5. If link was successful, restore current vp to file */
7441 	argop[5].argop = OP_RESTOREFH;
7442 
7443 	/* 6. Get attributes of linked object */
7444 	argop[6].argop = OP_GETATTR;
7445 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7446 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7447 
7448 	dnlc_remove(tdvp, tnm);
7449 
7450 	doqueue = 1;
7451 	t = gethrtime();
7452 
7453 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7454 
7455 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7456 	if (e.error != 0 && !needrecov) {
7457 		PURGE_ATTRCACHE4(tdvp);
7458 		PURGE_ATTRCACHE4(svp);
7459 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7460 		goto out;
7461 	}
7462 
7463 	if (needrecov) {
7464 		bool_t abort;
7465 
7466 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7467 		    NULL, NULL, OP_LINK, NULL);
7468 		if (abort == FALSE) {
7469 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7470 			    needrecov);
7471 			kmem_free(argop, argoplist_size);
7472 			if (!e.error)
7473 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7474 				    (caddr_t)&res);
7475 			goto recov_retry;
7476 		} else {
7477 			if (e.error != 0) {
7478 				PURGE_ATTRCACHE4(tdvp);
7479 				PURGE_ATTRCACHE4(svp);
7480 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7481 				    &recov_state, needrecov);
7482 				goto out;
7483 			}
7484 			/* fall through for res.status case */
7485 		}
7486 	}
7487 
7488 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7489 
7490 	resp = &res;
7491 	if (res.status) {
7492 		/* If link succeeded, then don't return error */
7493 		e.error = geterrno4(res.status);
7494 		if (res.array_len <= 4) {
7495 			/*
7496 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7497 			 */
7498 			PURGE_ATTRCACHE4(svp);
7499 			PURGE_ATTRCACHE4(tdvp);
7500 			if (e.error == EOPNOTSUPP) {
7501 				mutex_enter(&mi->mi_lock);
7502 				mi->mi_flags &= ~MI4_LINK;
7503 				mutex_exit(&mi->mi_lock);
7504 			}
7505 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7506 			/* XXX-LP */
7507 			if (e.error == EISDIR && crgetuid(cr) != 0)
7508 				e.error = EPERM;
7509 			goto out;
7510 		}
7511 	}
7512 
7513 	/* either no error or one of the postop getattr failed */
7514 
7515 	/*
7516 	 * XXX - if LINK succeeded, but no attrs were returned for link
7517 	 * file, purge its cache.
7518 	 *
7519 	 * XXX Perform a simplified version of wcc checking. Instead of
7520 	 * have another getattr to get pre-op, just purge cache if
7521 	 * any of the ops prior to and including the getattr failed.
7522 	 * If the getattr succeeded then update the attrcache accordingly.
7523 	 */
7524 
7525 	/*
7526 	 * update cache with link file postattrs.
7527 	 * Note: at this point resop points to link res.
7528 	 */
7529 	resop = &res.array[3];	/* link res */
7530 	ln_res = &resop->nfs_resop4_u.oplink;
7531 	if (res.status == NFS4_OK)
7532 		e.error = nfs4_update_attrcache(res.status,
7533 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res,
7534 		    t, svp, cr);
7535 
7536 	/*
7537 	 * Call makenfs4node to create the new shadow vp for tnm.
7538 	 * We pass NULL attrs because we just cached attrs for
7539 	 * the src object.  All we're trying to accomplish is to
7540 	 * to create the new shadow vnode.
7541 	 */
7542 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7543 	    tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm));
7544 
7545 	/* Update target cache attribute, readdir and dnlc caches */
7546 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7547 	dinfo.di_time_call = t;
7548 	dinfo.di_cred = cr;
7549 
7550 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7551 	ASSERT(nfs4_consistent_type(tdvp));
7552 	ASSERT(nfs4_consistent_type(svp));
7553 	ASSERT(nfs4_consistent_type(nvp));
7554 	VN_RELE(nvp);
7555 
7556 	if (!e.error) {
7557 		vnode_t *tvp;
7558 		rnode4_t *trp;
7559 		/*
7560 		 * Notify the source file of this link operation.
7561 		 */
7562 		trp = VTOR4(svp);
7563 		tvp = svp;
7564 		if (IS_SHADOW(svp, trp))
7565 			tvp = RTOV4(trp);
7566 		vnevent_link(tvp, ct);
7567 	}
7568 out:
7569 	kmem_free(argop, argoplist_size);
7570 	if (resp)
7571 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7572 
7573 	nfs_rw_exit(&tdrp->r_rwlock);
7574 
7575 	return (e.error);
7576 }
7577 
7578 /* ARGSUSED */
7579 static int
7580 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7581     caller_context_t *ct, int flags)
7582 {
7583 	vnode_t *realvp;
7584 
7585 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7586 		return (EPERM);
7587 	if (VOP_REALVP(ndvp, &realvp, ct) == 0)
7588 		ndvp = realvp;
7589 
7590 	return (nfs4rename(odvp, onm, ndvp, nnm, cr, ct));
7591 }
7592 
7593 /*
7594  * nfs4rename does the real work of renaming in NFS Version 4.
7595  *
7596  * A file handle is considered volatile for renaming purposes if either
7597  * of the volatile bits are turned on. However, the compound may differ
7598  * based on the likelihood of the filehandle to change during rename.
7599  */
7600 static int
7601 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7602     caller_context_t *ct)
7603 {
7604 	int error;
7605 	mntinfo4_t *mi;
7606 	vnode_t *nvp = NULL;
7607 	vnode_t *ovp = NULL;
7608 	char *tmpname = NULL;
7609 	rnode4_t *rp;
7610 	rnode4_t *odrp;
7611 	rnode4_t *ndrp;
7612 	int did_link = 0;
7613 	int do_link = 1;
7614 	nfsstat4 stat = NFS4_OK;
7615 
7616 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7617 	ASSERT(nfs4_consistent_type(odvp));
7618 	ASSERT(nfs4_consistent_type(ndvp));
7619 
7620 	if (onm[0] == '.' && (onm[1] == '\0' ||
7621 	    (onm[1] == '.' && onm[2] == '\0')))
7622 		return (EINVAL);
7623 
7624 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7625 	    (nnm[1] == '.' && nnm[2] == '\0')))
7626 		return (EINVAL);
7627 
7628 	odrp = VTOR4(odvp);
7629 	ndrp = VTOR4(ndvp);
7630 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7631 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7632 			return (EINTR);
7633 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7634 			nfs_rw_exit(&odrp->r_rwlock);
7635 			return (EINTR);
7636 		}
7637 	} else {
7638 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7639 			return (EINTR);
7640 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7641 			nfs_rw_exit(&ndrp->r_rwlock);
7642 			return (EINTR);
7643 		}
7644 	}
7645 
7646 	/*
7647 	 * Lookup the target file.  If it exists, it needs to be
7648 	 * checked to see whether it is a mount point and whether
7649 	 * it is active (open).
7650 	 */
7651 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7652 	if (!error) {
7653 		int	isactive;
7654 
7655 		ASSERT(nfs4_consistent_type(nvp));
7656 		/*
7657 		 * If this file has been mounted on, then just
7658 		 * return busy because renaming to it would remove
7659 		 * the mounted file system from the name space.
7660 		 */
7661 		if (vn_ismntpt(nvp)) {
7662 			VN_RELE(nvp);
7663 			nfs_rw_exit(&odrp->r_rwlock);
7664 			nfs_rw_exit(&ndrp->r_rwlock);
7665 			return (EBUSY);
7666 		}
7667 
7668 		/*
7669 		 * First just remove the entry from the name cache, as it
7670 		 * is most likely the only entry for this vp.
7671 		 */
7672 		dnlc_remove(ndvp, nnm);
7673 
7674 		rp = VTOR4(nvp);
7675 
7676 		if (nvp->v_type != VREG) {
7677 			/*
7678 			 * Purge the name cache of all references to this vnode
7679 			 * so that we can check the reference count to infer
7680 			 * whether it is active or not.
7681 			 */
7682 			if (nvp->v_count > 1)
7683 				dnlc_purge_vp(nvp);
7684 
7685 			isactive = nvp->v_count > 1;
7686 		} else {
7687 			mutex_enter(&rp->r_os_lock);
7688 			isactive = list_head(&rp->r_open_streams) != NULL;
7689 			mutex_exit(&rp->r_os_lock);
7690 		}
7691 
7692 		/*
7693 		 * If the vnode is active and is not a directory,
7694 		 * arrange to rename it to a
7695 		 * temporary file so that it will continue to be
7696 		 * accessible.  This implements the "unlink-open-file"
7697 		 * semantics for the target of a rename operation.
7698 		 * Before doing this though, make sure that the
7699 		 * source and target files are not already the same.
7700 		 */
7701 		if (isactive && nvp->v_type != VDIR) {
7702 			/*
7703 			 * Lookup the source name.
7704 			 */
7705 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7706 
7707 			/*
7708 			 * The source name *should* already exist.
7709 			 */
7710 			if (error) {
7711 				VN_RELE(nvp);
7712 				nfs_rw_exit(&odrp->r_rwlock);
7713 				nfs_rw_exit(&ndrp->r_rwlock);
7714 				return (error);
7715 			}
7716 
7717 			ASSERT(nfs4_consistent_type(ovp));
7718 
7719 			/*
7720 			 * Compare the two vnodes.  If they are the same,
7721 			 * just release all held vnodes and return success.
7722 			 */
7723 			if (VN_CMP(ovp, nvp)) {
7724 				VN_RELE(ovp);
7725 				VN_RELE(nvp);
7726 				nfs_rw_exit(&odrp->r_rwlock);
7727 				nfs_rw_exit(&ndrp->r_rwlock);
7728 				return (0);
7729 			}
7730 
7731 			/*
7732 			 * Can't mix and match directories and non-
7733 			 * directories in rename operations.  We already
7734 			 * know that the target is not a directory.  If
7735 			 * the source is a directory, return an error.
7736 			 */
7737 			if (ovp->v_type == VDIR) {
7738 				VN_RELE(ovp);
7739 				VN_RELE(nvp);
7740 				nfs_rw_exit(&odrp->r_rwlock);
7741 				nfs_rw_exit(&ndrp->r_rwlock);
7742 				return (ENOTDIR);
7743 			}
7744 link_call:
7745 			/*
7746 			 * The target file exists, is not the same as
7747 			 * the source file, and is active.  We first
7748 			 * try to Link it to a temporary filename to
7749 			 * avoid having the server removing the file
7750 			 * completely (which could cause data loss to
7751 			 * the user's POV in the event the Rename fails
7752 			 * -- see bug 1165874).
7753 			 */
7754 			/*
7755 			 * The do_link and did_link booleans are
7756 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7757 			 * returned for the Rename.  Some servers can
7758 			 * not Rename over an Open file, so they return
7759 			 * this error.  The client needs to Remove the
7760 			 * newly created Link and do two Renames, just
7761 			 * as if the server didn't support LINK.
7762 			 */
7763 			tmpname = newname();
7764 			error = 0;
7765 
7766 			if (do_link) {
7767 				error = nfs4_link(ndvp, nvp, tmpname, cr,
7768 				    NULL, 0);
7769 			}
7770 			if (error == EOPNOTSUPP || !do_link) {
7771 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7772 				    cr, NULL, 0);
7773 				did_link = 0;
7774 			} else {
7775 				did_link = 1;
7776 			}
7777 			if (error) {
7778 				kmem_free(tmpname, MAXNAMELEN);
7779 				VN_RELE(ovp);
7780 				VN_RELE(nvp);
7781 				nfs_rw_exit(&odrp->r_rwlock);
7782 				nfs_rw_exit(&ndrp->r_rwlock);
7783 				return (error);
7784 			}
7785 
7786 			mutex_enter(&rp->r_statelock);
7787 			if (rp->r_unldvp == NULL) {
7788 				VN_HOLD(ndvp);
7789 				rp->r_unldvp = ndvp;
7790 				if (rp->r_unlcred != NULL)
7791 					crfree(rp->r_unlcred);
7792 				crhold(cr);
7793 				rp->r_unlcred = cr;
7794 				rp->r_unlname = tmpname;
7795 			} else {
7796 				if (rp->r_unlname)
7797 					kmem_free(rp->r_unlname, MAXNAMELEN);
7798 				rp->r_unlname = tmpname;
7799 			}
7800 			mutex_exit(&rp->r_statelock);
7801 		}
7802 
7803 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7804 
7805 		ASSERT(nfs4_consistent_type(nvp));
7806 	}
7807 
7808 	if (ovp == NULL) {
7809 		/*
7810 		 * When renaming directories to be a subdirectory of a
7811 		 * different parent, the dnlc entry for ".." will no
7812 		 * longer be valid, so it must be removed.
7813 		 *
7814 		 * We do a lookup here to determine whether we are renaming
7815 		 * a directory and we need to check if we are renaming
7816 		 * an unlinked file.  This might have already been done
7817 		 * in previous code, so we check ovp == NULL to avoid
7818 		 * doing it twice.
7819 		 */
7820 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7821 		/*
7822 		 * The source name *should* already exist.
7823 		 */
7824 		if (error) {
7825 			nfs_rw_exit(&odrp->r_rwlock);
7826 			nfs_rw_exit(&ndrp->r_rwlock);
7827 			if (nvp) {
7828 				VN_RELE(nvp);
7829 			}
7830 			return (error);
7831 		}
7832 		ASSERT(ovp != NULL);
7833 		ASSERT(nfs4_consistent_type(ovp));
7834 	}
7835 
7836 	/*
7837 	 * Is the object being renamed a dir, and if so, is
7838 	 * it being renamed to a child of itself?  The underlying
7839 	 * fs should ultimately return EINVAL for this case;
7840 	 * however, buggy beta non-Solaris NFSv4 servers at
7841 	 * interop testing events have allowed this behavior,
7842 	 * and it caused our client to panic due to a recursive
7843 	 * mutex_enter in fn_move.
7844 	 *
7845 	 * The tedious locking in fn_move could be changed to
7846 	 * deal with this case, and the client could avoid the
7847 	 * panic; however, the client would just confuse itself
7848 	 * later and misbehave.  A better way to handle the broken
7849 	 * server is to detect this condition and return EINVAL
7850 	 * without ever sending the the bogus rename to the server.
7851 	 * We know the rename is invalid -- just fail it now.
7852 	 */
7853 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7854 		VN_RELE(ovp);
7855 		nfs_rw_exit(&odrp->r_rwlock);
7856 		nfs_rw_exit(&ndrp->r_rwlock);
7857 		if (nvp) {
7858 			VN_RELE(nvp);
7859 		}
7860 		return (EINVAL);
7861 	}
7862 
7863 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7864 
7865 	/*
7866 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7867 	 * possible for the filehandle to change due to the rename.
7868 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7869 	 * the fh will not change because of the rename, but we still need
7870 	 * to update its rnode entry with the new name for
7871 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7872 	 * has no effect on these for now, but for future improvements,
7873 	 * we might want to use it too to simplify handling of files
7874 	 * that are open with that flag on. (XXX)
7875 	 */
7876 	mi = VTOMI4(odvp);
7877 	if (NFS4_VOLATILE_FH(mi))
7878 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7879 		    &stat);
7880 	else
7881 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7882 		    &stat);
7883 
7884 	ASSERT(nfs4_consistent_type(odvp));
7885 	ASSERT(nfs4_consistent_type(ndvp));
7886 	ASSERT(nfs4_consistent_type(ovp));
7887 
7888 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
7889 		do_link = 0;
7890 		/*
7891 		 * Before the 'link_call' code, we did a nfs4_lookup
7892 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
7893 		 * call we call VN_RELE to match that hold.  We need
7894 		 * to place an additional VN_HOLD here since we will
7895 		 * be hitting that VN_RELE again.
7896 		 */
7897 		VN_HOLD(nvp);
7898 
7899 		(void) nfs4_remove(ndvp, tmpname, cr, NULL, 0);
7900 
7901 		/* Undo the unlinked file naming stuff we just did */
7902 		mutex_enter(&rp->r_statelock);
7903 		if (rp->r_unldvp) {
7904 			VN_RELE(ndvp);
7905 			rp->r_unldvp = NULL;
7906 			if (rp->r_unlcred != NULL)
7907 				crfree(rp->r_unlcred);
7908 			rp->r_unlcred = NULL;
7909 			/* rp->r_unlanme points to tmpname */
7910 			if (rp->r_unlname)
7911 				kmem_free(rp->r_unlname, MAXNAMELEN);
7912 			rp->r_unlname = NULL;
7913 		}
7914 		mutex_exit(&rp->r_statelock);
7915 
7916 		if (nvp) {
7917 			VN_RELE(nvp);
7918 		}
7919 		goto link_call;
7920 	}
7921 
7922 	if (error) {
7923 		VN_RELE(ovp);
7924 		nfs_rw_exit(&odrp->r_rwlock);
7925 		nfs_rw_exit(&ndrp->r_rwlock);
7926 		if (nvp) {
7927 			VN_RELE(nvp);
7928 		}
7929 		return (error);
7930 	}
7931 
7932 	/*
7933 	 * when renaming directories to be a subdirectory of a
7934 	 * different parent, the dnlc entry for ".." will no
7935 	 * longer be valid, so it must be removed
7936 	 */
7937 	rp = VTOR4(ovp);
7938 	if (ndvp != odvp) {
7939 		if (ovp->v_type == VDIR) {
7940 			dnlc_remove(ovp, "..");
7941 			if (rp->r_dir != NULL)
7942 				nfs4_purge_rddir_cache(ovp);
7943 		}
7944 	}
7945 
7946 	/*
7947 	 * If we are renaming the unlinked file, update the
7948 	 * r_unldvp and r_unlname as needed.
7949 	 */
7950 	mutex_enter(&rp->r_statelock);
7951 	if (rp->r_unldvp != NULL) {
7952 		if (strcmp(rp->r_unlname, onm) == 0) {
7953 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
7954 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
7955 			if (ndvp != rp->r_unldvp) {
7956 				VN_RELE(rp->r_unldvp);
7957 				rp->r_unldvp = ndvp;
7958 				VN_HOLD(ndvp);
7959 			}
7960 		}
7961 	}
7962 	mutex_exit(&rp->r_statelock);
7963 
7964 	/*
7965 	 * Notify the rename vnevents to source vnode, and to the target
7966 	 * vnode if it already existed.
7967 	 */
7968 	if (error == 0) {
7969 		vnode_t *tvp;
7970 		rnode4_t *trp;
7971 		/*
7972 		 * Notify the vnode. Each links is represented by
7973 		 * a different vnode, in nfsv4.
7974 		 */
7975 		if (nvp) {
7976 			trp = VTOR4(nvp);
7977 			tvp = nvp;
7978 			if (IS_SHADOW(nvp, trp))
7979 				tvp = RTOV4(trp);
7980 			vnevent_rename_dest(tvp, ndvp, nnm, ct);
7981 		}
7982 
7983 		/*
7984 		 * if the source and destination directory are not the
7985 		 * same notify the destination directory.
7986 		 */
7987 		if (VTOR4(odvp) != VTOR4(ndvp)) {
7988 			trp = VTOR4(ndvp);
7989 			tvp = ndvp;
7990 			if (IS_SHADOW(ndvp, trp))
7991 				tvp = RTOV4(trp);
7992 			vnevent_rename_dest_dir(tvp, ct);
7993 		}
7994 
7995 		trp = VTOR4(ovp);
7996 		tvp = ovp;
7997 		if (IS_SHADOW(ovp, trp))
7998 			tvp = RTOV4(trp);
7999 		vnevent_rename_src(tvp, odvp, onm, ct);
8000 	}
8001 
8002 	if (nvp) {
8003 		VN_RELE(nvp);
8004 	}
8005 	VN_RELE(ovp);
8006 
8007 	nfs_rw_exit(&odrp->r_rwlock);
8008 	nfs_rw_exit(&ndrp->r_rwlock);
8009 
8010 	return (error);
8011 }
8012 
8013 /*
8014  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
8015  * when it is known that the filehandle is persistent through rename.
8016  *
8017  * Rename requires that the current fh be the target directory and the
8018  * saved fh be the source directory. After the operation, the current fh
8019  * is unchanged.
8020  * The compound op structure for persistent fh rename is:
8021  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
8022  * Rather than bother with the directory postop args, we'll simply
8023  * update that a change occurred in the cache, so no post-op getattrs.
8024  */
8025 static int
8026 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
8027     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8028 {
8029 	COMPOUND4args_clnt args;
8030 	COMPOUND4res_clnt res, *resp = NULL;
8031 	nfs_argop4 *argop;
8032 	nfs_resop4 *resop;
8033 	int doqueue, argoplist_size;
8034 	mntinfo4_t *mi;
8035 	rnode4_t *odrp = VTOR4(odvp);
8036 	rnode4_t *ndrp = VTOR4(ndvp);
8037 	RENAME4res *rn_res;
8038 	bool_t needrecov;
8039 	nfs4_recov_state_t recov_state;
8040 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8041 	dirattr_info_t dinfo, *dinfop;
8042 
8043 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8044 
8045 	recov_state.rs_flags = 0;
8046 	recov_state.rs_num_retry_despite_err = 0;
8047 
8048 	/*
8049 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
8050 	 *
8051 	 * If source/target are different dirs, then append putfh(src); getattr
8052 	 */
8053 	args.array_len = (odvp == ndvp) ? 5 : 7;
8054 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8055 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8056 
8057 recov_retry:
8058 	*statp = NFS4_OK;
8059 
8060 	/* No need to Lookup the file, persistent fh */
8061 	args.ctag = TAG_RENAME;
8062 
8063 	mi = VTOMI4(odvp);
8064 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8065 	if (e.error) {
8066 		kmem_free(argop, argoplist_size);
8067 		return (e.error);
8068 	}
8069 
8070 	/* 0: putfh source directory */
8071 	argop[0].argop = OP_CPUTFH;
8072 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8073 
8074 	/* 1: Save source fh to free up current for target */
8075 	argop[1].argop = OP_SAVEFH;
8076 
8077 	/* 2: putfh targetdir */
8078 	argop[2].argop = OP_CPUTFH;
8079 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8080 
8081 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8082 	argop[3].argop = OP_CRENAME;
8083 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8084 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8085 
8086 	/* 4: getattr (targetdir) */
8087 	argop[4].argop = OP_GETATTR;
8088 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8089 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8090 
8091 	if (ndvp != odvp) {
8092 
8093 		/* 5: putfh (sourcedir) */
8094 		argop[5].argop = OP_CPUTFH;
8095 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8096 
8097 		/* 6: getattr (sourcedir) */
8098 		argop[6].argop = OP_GETATTR;
8099 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8100 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8101 	}
8102 
8103 	dnlc_remove(odvp, onm);
8104 	dnlc_remove(ndvp, nnm);
8105 
8106 	doqueue = 1;
8107 	dinfo.di_time_call = gethrtime();
8108 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8109 
8110 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8111 	if (e.error) {
8112 		PURGE_ATTRCACHE4(odvp);
8113 		PURGE_ATTRCACHE4(ndvp);
8114 	} else {
8115 		*statp = res.status;
8116 	}
8117 
8118 	if (needrecov) {
8119 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8120 		    OP_RENAME, NULL) == FALSE) {
8121 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8122 			if (!e.error)
8123 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8124 				    (caddr_t)&res);
8125 			goto recov_retry;
8126 		}
8127 	}
8128 
8129 	if (!e.error) {
8130 		resp = &res;
8131 		/*
8132 		 * as long as OP_RENAME
8133 		 */
8134 		if (res.status != NFS4_OK && res.array_len <= 4) {
8135 			e.error = geterrno4(res.status);
8136 			PURGE_ATTRCACHE4(odvp);
8137 			PURGE_ATTRCACHE4(ndvp);
8138 			/*
8139 			 * System V defines rename to return EEXIST, not
8140 			 * ENOTEMPTY if the target directory is not empty.
8141 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8142 			 * which geterrno4 maps to ENOTEMPTY.
8143 			 */
8144 			if (e.error == ENOTEMPTY)
8145 				e.error = EEXIST;
8146 		} else {
8147 
8148 			resop = &res.array[3];	/* rename res */
8149 			rn_res = &resop->nfs_resop4_u.oprename;
8150 
8151 			if (res.status == NFS4_OK) {
8152 				/*
8153 				 * Update target attribute, readdir and dnlc
8154 				 * caches.
8155 				 */
8156 				dinfo.di_garp =
8157 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8158 				dinfo.di_cred = cr;
8159 				dinfop = &dinfo;
8160 			} else
8161 				dinfop = NULL;
8162 
8163 			nfs4_update_dircaches(&rn_res->target_cinfo,
8164 			    ndvp, NULL, NULL, dinfop);
8165 
8166 			/*
8167 			 * Update source attribute, readdir and dnlc caches
8168 			 *
8169 			 */
8170 			if (ndvp != odvp) {
8171 				if (dinfop)
8172 					dinfo.di_garp =
8173 					    &(res.array[6].nfs_resop4_u.
8174 					    opgetattr.ga_res);
8175 
8176 				nfs4_update_dircaches(&rn_res->source_cinfo,
8177 				    odvp, NULL, NULL, dinfop);
8178 			}
8179 
8180 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8181 			    nnm);
8182 		}
8183 	}
8184 
8185 	if (resp)
8186 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8187 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8188 	kmem_free(argop, argoplist_size);
8189 
8190 	return (e.error);
8191 }
8192 
8193 /*
8194  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8195  * it is possible for the filehandle to change due to the rename.
8196  *
8197  * The compound req in this case includes a post-rename lookup and getattr
8198  * to ensure that we have the correct fh and attributes for the object.
8199  *
8200  * Rename requires that the current fh be the target directory and the
8201  * saved fh be the source directory. After the operation, the current fh
8202  * is unchanged.
8203  *
8204  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8205  * update the filehandle for the renamed object.  We also get the old
8206  * filehandle for historical reasons; this should be taken out sometime.
8207  * This results in a rather cumbersome compound...
8208  *
8209  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8210  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8211  *
8212  */
8213 static int
8214 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8215     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8216 {
8217 	COMPOUND4args_clnt args;
8218 	COMPOUND4res_clnt res, *resp = NULL;
8219 	int argoplist_size;
8220 	nfs_argop4 *argop;
8221 	nfs_resop4 *resop;
8222 	int doqueue;
8223 	mntinfo4_t *mi;
8224 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8225 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8226 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8227 	RENAME4res *rn_res;
8228 	GETFH4res *ngf_res;
8229 	bool_t needrecov;
8230 	nfs4_recov_state_t recov_state;
8231 	hrtime_t t;
8232 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8233 	dirattr_info_t dinfo, *dinfop = &dinfo;
8234 
8235 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8236 
8237 	recov_state.rs_flags = 0;
8238 	recov_state.rs_num_retry_despite_err = 0;
8239 
8240 recov_retry:
8241 	*statp = NFS4_OK;
8242 
8243 	/*
8244 	 * There is a window between the RPC and updating the path and
8245 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8246 	 * code, so that it doesn't try to use the old path during that
8247 	 * window.
8248 	 */
8249 	mutex_enter(&orp->r_statelock);
8250 	while (orp->r_flags & R4RECEXPFH) {
8251 		klwp_t *lwp = ttolwp(curthread);
8252 
8253 		if (lwp != NULL)
8254 			lwp->lwp_nostop++;
8255 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8256 			mutex_exit(&orp->r_statelock);
8257 			if (lwp != NULL)
8258 				lwp->lwp_nostop--;
8259 			return (EINTR);
8260 		}
8261 		if (lwp != NULL)
8262 			lwp->lwp_nostop--;
8263 	}
8264 	orp->r_flags |= R4RECEXPFH;
8265 	mutex_exit(&orp->r_statelock);
8266 
8267 	mi = VTOMI4(odvp);
8268 
8269 	args.ctag = TAG_RENAME_VFH;
8270 	args.array_len = (odvp == ndvp) ? 10 : 12;
8271 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8272 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8273 
8274 	/*
8275 	 * Rename ops:
8276 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8277 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8278 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8279 	 *
8280 	 *    if (odvp != ndvp)
8281 	 *	add putfh(sourcedir), getattr(sourcedir) }
8282 	 */
8283 	args.array = argop;
8284 
8285 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8286 	    &recov_state, NULL);
8287 	if (e.error) {
8288 		kmem_free(argop, argoplist_size);
8289 		mutex_enter(&orp->r_statelock);
8290 		orp->r_flags &= ~R4RECEXPFH;
8291 		cv_broadcast(&orp->r_cv);
8292 		mutex_exit(&orp->r_statelock);
8293 		return (e.error);
8294 	}
8295 
8296 	/* 0: putfh source directory */
8297 	argop[0].argop = OP_CPUTFH;
8298 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8299 
8300 	/* 1: Save source fh to free up current for target */
8301 	argop[1].argop = OP_SAVEFH;
8302 
8303 	/* 2: Lookup pre-rename fh of renamed object */
8304 	argop[2].argop = OP_CLOOKUP;
8305 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8306 
8307 	/* 3: getfh fh of renamed object (before rename) */
8308 	argop[3].argop = OP_GETFH;
8309 
8310 	/* 4: putfh targetdir */
8311 	argop[4].argop = OP_CPUTFH;
8312 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8313 
8314 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8315 	argop[5].argop = OP_CRENAME;
8316 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8317 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8318 
8319 	/* 6: getattr of target dir (post op attrs) */
8320 	argop[6].argop = OP_GETATTR;
8321 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8322 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8323 
8324 	/* 7: Lookup post-rename fh of renamed object */
8325 	argop[7].argop = OP_CLOOKUP;
8326 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8327 
8328 	/* 8: getfh fh of renamed object (after rename) */
8329 	argop[8].argop = OP_GETFH;
8330 
8331 	/* 9: getattr of renamed object */
8332 	argop[9].argop = OP_GETATTR;
8333 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8334 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8335 
8336 	/*
8337 	 * If source/target dirs are different, then get new post-op
8338 	 * attrs for source dir also.
8339 	 */
8340 	if (ndvp != odvp) {
8341 		/* 10: putfh (sourcedir) */
8342 		argop[10].argop = OP_CPUTFH;
8343 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8344 
8345 		/* 11: getattr (sourcedir) */
8346 		argop[11].argop = OP_GETATTR;
8347 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8348 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8349 	}
8350 
8351 	dnlc_remove(odvp, onm);
8352 	dnlc_remove(ndvp, nnm);
8353 
8354 	doqueue = 1;
8355 	t = gethrtime();
8356 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8357 
8358 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8359 	if (e.error) {
8360 		PURGE_ATTRCACHE4(odvp);
8361 		PURGE_ATTRCACHE4(ndvp);
8362 		if (!needrecov) {
8363 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8364 			    &recov_state, needrecov);
8365 			goto out;
8366 		}
8367 	} else {
8368 		*statp = res.status;
8369 	}
8370 
8371 	if (needrecov) {
8372 		bool_t abort;
8373 
8374 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8375 		    OP_RENAME, NULL);
8376 		if (abort == FALSE) {
8377 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8378 			    &recov_state, needrecov);
8379 			kmem_free(argop, argoplist_size);
8380 			if (!e.error)
8381 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8382 				    (caddr_t)&res);
8383 			mutex_enter(&orp->r_statelock);
8384 			orp->r_flags &= ~R4RECEXPFH;
8385 			cv_broadcast(&orp->r_cv);
8386 			mutex_exit(&orp->r_statelock);
8387 			goto recov_retry;
8388 		} else {
8389 			if (e.error != 0) {
8390 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8391 				    &recov_state, needrecov);
8392 				goto out;
8393 			}
8394 			/* fall through for res.status case */
8395 		}
8396 	}
8397 
8398 	resp = &res;
8399 	/*
8400 	 * If OP_RENAME (or any prev op) failed, then return an error.
8401 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8402 	 */
8403 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8404 		/*
8405 		 * Error in an op other than last Getattr
8406 		 */
8407 		e.error = geterrno4(res.status);
8408 		PURGE_ATTRCACHE4(odvp);
8409 		PURGE_ATTRCACHE4(ndvp);
8410 		/*
8411 		 * System V defines rename to return EEXIST, not
8412 		 * ENOTEMPTY if the target directory is not empty.
8413 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8414 		 * which geterrno4 maps to ENOTEMPTY.
8415 		 */
8416 		if (e.error == ENOTEMPTY)
8417 			e.error = EEXIST;
8418 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8419 		    needrecov);
8420 		goto out;
8421 	}
8422 
8423 	/* rename results */
8424 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8425 
8426 	if (res.status == NFS4_OK) {
8427 		/* Update target attribute, readdir and dnlc caches */
8428 		dinfo.di_garp =
8429 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
8430 		dinfo.di_cred = cr;
8431 		dinfo.di_time_call = t;
8432 	} else
8433 		dinfop = NULL;
8434 
8435 	/* Update source cache attribute, readdir and dnlc caches */
8436 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8437 
8438 	/* Update source cache attribute, readdir and dnlc caches */
8439 	if (ndvp != odvp) {
8440 
8441 		/*
8442 		 * If dinfop is non-NULL, then compound succeded, so
8443 		 * set di_garp to attrs for source dir.  dinfop is only
8444 		 * set to NULL when compound fails.
8445 		 */
8446 		if (dinfop)
8447 			dinfo.di_garp =
8448 			    &res.array[11].nfs_resop4_u.opgetattr.ga_res;
8449 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8450 		    dinfop);
8451 	}
8452 
8453 	/*
8454 	 * Update the rnode with the new component name and args,
8455 	 * and if the file handle changed, also update it with the new fh.
8456 	 * This is only necessary if the target object has an rnode
8457 	 * entry and there is no need to create one for it.
8458 	 */
8459 	resop = &res.array[8];	/* getfh new res */
8460 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8461 
8462 	/*
8463 	 * Update the path and filehandle for the renamed object.
8464 	 */
8465 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8466 
8467 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8468 
8469 	if (res.status == NFS4_OK) {
8470 		resop++;	/* getattr res */
8471 		e.error = nfs4_update_attrcache(res.status,
8472 		    &resop->nfs_resop4_u.opgetattr.ga_res,
8473 		    t, ovp, cr);
8474 	}
8475 
8476 out:
8477 	kmem_free(argop, argoplist_size);
8478 	if (resp)
8479 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8480 	mutex_enter(&orp->r_statelock);
8481 	orp->r_flags &= ~R4RECEXPFH;
8482 	cv_broadcast(&orp->r_cv);
8483 	mutex_exit(&orp->r_statelock);
8484 
8485 	return (e.error);
8486 }
8487 
8488 /* ARGSUSED */
8489 static int
8490 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr,
8491     caller_context_t *ct, int flags, vsecattr_t *vsecp)
8492 {
8493 	int error;
8494 	vnode_t *vp;
8495 
8496 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8497 		return (EPERM);
8498 	/*
8499 	 * As ".." has special meaning and rather than send a mkdir
8500 	 * over the wire to just let the server freak out, we just
8501 	 * short circuit it here and return EEXIST
8502 	 */
8503 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8504 		return (EEXIST);
8505 
8506 	/*
8507 	 * Decision to get the right gid and setgid bit of the
8508 	 * new directory is now made in call_nfs4_create_req.
8509 	 */
8510 	va->va_mask |= AT_MODE;
8511 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8512 	if (error)
8513 		return (error);
8514 
8515 	*vpp = vp;
8516 	return (0);
8517 }
8518 
8519 
8520 /*
8521  * rmdir is using the same remove v4 op as does remove.
8522  * Remove requires that the current fh be the target directory.
8523  * After the operation, the current fh is unchanged.
8524  * The compound op structure is:
8525  *      PUTFH(targetdir), REMOVE
8526  */
8527 /*ARGSUSED4*/
8528 static int
8529 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr,
8530     caller_context_t *ct, int flags)
8531 {
8532 	int need_end_op = FALSE;
8533 	COMPOUND4args_clnt args;
8534 	COMPOUND4res_clnt res, *resp = NULL;
8535 	REMOVE4res *rm_res;
8536 	nfs_argop4 argop[3];
8537 	nfs_resop4 *resop;
8538 	vnode_t *vp;
8539 	int doqueue;
8540 	mntinfo4_t *mi;
8541 	rnode4_t *drp;
8542 	bool_t needrecov = FALSE;
8543 	nfs4_recov_state_t recov_state;
8544 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8545 	dirattr_info_t dinfo, *dinfop;
8546 
8547 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8548 		return (EPERM);
8549 	/*
8550 	 * As ".." has special meaning and rather than send a rmdir
8551 	 * over the wire to just let the server freak out, we just
8552 	 * short circuit it here and return EEXIST
8553 	 */
8554 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8555 		return (EEXIST);
8556 
8557 	drp = VTOR4(dvp);
8558 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8559 		return (EINTR);
8560 
8561 	/*
8562 	 * Attempt to prevent a rmdir(".") from succeeding.
8563 	 */
8564 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8565 	if (e.error) {
8566 		nfs_rw_exit(&drp->r_rwlock);
8567 		return (e.error);
8568 	}
8569 	if (vp == cdir) {
8570 		VN_RELE(vp);
8571 		nfs_rw_exit(&drp->r_rwlock);
8572 		return (EINVAL);
8573 	}
8574 
8575 	/*
8576 	 * Since nfsv4 remove op works on both files and directories,
8577 	 * check that the removed object is indeed a directory.
8578 	 */
8579 	if (vp->v_type != VDIR) {
8580 		VN_RELE(vp);
8581 		nfs_rw_exit(&drp->r_rwlock);
8582 		return (ENOTDIR);
8583 	}
8584 
8585 	/*
8586 	 * First just remove the entry from the name cache, as it
8587 	 * is most likely an entry for this vp.
8588 	 */
8589 	dnlc_remove(dvp, nm);
8590 
8591 	/*
8592 	 * If there vnode reference count is greater than one, then
8593 	 * there may be additional references in the DNLC which will
8594 	 * need to be purged.  First, trying removing the entry for
8595 	 * the parent directory and see if that removes the additional
8596 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8597 	 * to completely remove any references to the directory which
8598 	 * might still exist in the DNLC.
8599 	 */
8600 	if (vp->v_count > 1) {
8601 		dnlc_remove(vp, "..");
8602 		if (vp->v_count > 1)
8603 			dnlc_purge_vp(vp);
8604 	}
8605 
8606 	mi = VTOMI4(dvp);
8607 	recov_state.rs_flags = 0;
8608 	recov_state.rs_num_retry_despite_err = 0;
8609 
8610 recov_retry:
8611 	args.ctag = TAG_RMDIR;
8612 
8613 	/*
8614 	 * Rmdir ops: putfh dir; remove
8615 	 */
8616 	args.array_len = 3;
8617 	args.array = argop;
8618 
8619 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8620 	if (e.error) {
8621 		nfs_rw_exit(&drp->r_rwlock);
8622 		return (e.error);
8623 	}
8624 	need_end_op = TRUE;
8625 
8626 	/* putfh directory */
8627 	argop[0].argop = OP_CPUTFH;
8628 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8629 
8630 	/* remove */
8631 	argop[1].argop = OP_CREMOVE;
8632 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8633 
8634 	/* getattr (postop attrs for dir that contained removed dir) */
8635 	argop[2].argop = OP_GETATTR;
8636 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8637 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8638 
8639 	dinfo.di_time_call = gethrtime();
8640 	doqueue = 1;
8641 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8642 
8643 	PURGE_ATTRCACHE4(vp);
8644 
8645 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8646 	if (e.error) {
8647 		PURGE_ATTRCACHE4(dvp);
8648 	}
8649 
8650 	if (needrecov) {
8651 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8652 		    NULL, OP_REMOVE, NULL) == FALSE) {
8653 			if (!e.error)
8654 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8655 				    (caddr_t)&res);
8656 
8657 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8658 			    needrecov);
8659 			need_end_op = FALSE;
8660 			goto recov_retry;
8661 		}
8662 	}
8663 
8664 	if (!e.error) {
8665 		resp = &res;
8666 
8667 		/*
8668 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8669 		 * failed.
8670 		 */
8671 		if (res.status != NFS4_OK && res.array_len <= 2) {
8672 			e.error = geterrno4(res.status);
8673 			PURGE_ATTRCACHE4(dvp);
8674 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8675 			    &recov_state, needrecov);
8676 			need_end_op = FALSE;
8677 			nfs4_purge_stale_fh(e.error, dvp, cr);
8678 			/*
8679 			 * System V defines rmdir to return EEXIST, not
8680 			 * ENOTEMPTY if the directory is not empty.  Over
8681 			 * the wire, the error is NFSERR_ENOTEMPTY which
8682 			 * geterrno4 maps to ENOTEMPTY.
8683 			 */
8684 			if (e.error == ENOTEMPTY)
8685 				e.error = EEXIST;
8686 		} else {
8687 			resop = &res.array[1];	/* remove res */
8688 			rm_res = &resop->nfs_resop4_u.opremove;
8689 
8690 			if (res.status == NFS4_OK) {
8691 				resop = &res.array[2];	/* dir attrs */
8692 				dinfo.di_garp =
8693 				    &resop->nfs_resop4_u.opgetattr.ga_res;
8694 				dinfo.di_cred = cr;
8695 				dinfop = &dinfo;
8696 			} else
8697 				dinfop = NULL;
8698 
8699 			/* Update dir attribute, readdir and dnlc caches */
8700 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8701 			    dinfop);
8702 
8703 			/* destroy rddir cache for dir that was removed */
8704 			if (VTOR4(vp)->r_dir != NULL)
8705 				nfs4_purge_rddir_cache(vp);
8706 		}
8707 	}
8708 
8709 	if (need_end_op)
8710 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8711 
8712 	nfs_rw_exit(&drp->r_rwlock);
8713 
8714 	if (resp)
8715 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8716 
8717 	if (e.error == 0) {
8718 		vnode_t *tvp;
8719 		rnode4_t *trp;
8720 		trp = VTOR4(vp);
8721 		tvp = vp;
8722 		if (IS_SHADOW(vp, trp))
8723 			tvp = RTOV4(trp);
8724 		vnevent_rmdir(tvp, dvp, nm, ct);
8725 	}
8726 
8727 	VN_RELE(vp);
8728 
8729 	return (e.error);
8730 }
8731 
8732 /* ARGSUSED */
8733 static int
8734 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr,
8735     caller_context_t *ct, int flags)
8736 {
8737 	int error;
8738 	vnode_t *vp;
8739 	rnode4_t *rp;
8740 	char *contents;
8741 	mntinfo4_t *mi = VTOMI4(dvp);
8742 
8743 	if (nfs_zone() != mi->mi_zone)
8744 		return (EPERM);
8745 	if (!(mi->mi_flags & MI4_SYMLINK))
8746 		return (EOPNOTSUPP);
8747 
8748 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8749 	if (error)
8750 		return (error);
8751 
8752 	ASSERT(nfs4_consistent_type(vp));
8753 	rp = VTOR4(vp);
8754 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8755 
8756 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8757 
8758 		if (contents != NULL) {
8759 			mutex_enter(&rp->r_statelock);
8760 			if (rp->r_symlink.contents == NULL) {
8761 				rp->r_symlink.len = strlen(tnm);
8762 				bcopy(tnm, contents, rp->r_symlink.len);
8763 				rp->r_symlink.contents = contents;
8764 				rp->r_symlink.size = MAXPATHLEN;
8765 				mutex_exit(&rp->r_statelock);
8766 			} else {
8767 				mutex_exit(&rp->r_statelock);
8768 				kmem_free((void *)contents, MAXPATHLEN);
8769 			}
8770 		}
8771 	}
8772 	VN_RELE(vp);
8773 
8774 	return (error);
8775 }
8776 
8777 
8778 /*
8779  * Read directory entries.
8780  * There are some weird things to look out for here.  The uio_loffset
8781  * field is either 0 or it is the offset returned from a previous
8782  * readdir.  It is an opaque value used by the server to find the
8783  * correct directory block to read. The count field is the number
8784  * of blocks to read on the server.  This is advisory only, the server
8785  * may return only one block's worth of entries.  Entries may be compressed
8786  * on the server.
8787  */
8788 /* ARGSUSED */
8789 static int
8790 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp,
8791 	caller_context_t *ct, int flags)
8792 {
8793 	int error;
8794 	uint_t count;
8795 	rnode4_t *rp;
8796 	rddir4_cache *rdc;
8797 	rddir4_cache *rrdc;
8798 
8799 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8800 		return (EIO);
8801 	rp = VTOR4(vp);
8802 
8803 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8804 
8805 	/*
8806 	 * Make sure that the directory cache is valid.
8807 	 */
8808 	if (rp->r_dir != NULL) {
8809 		if (nfs_disable_rddir_cache != 0) {
8810 			/*
8811 			 * Setting nfs_disable_rddir_cache in /etc/system
8812 			 * allows interoperability with servers that do not
8813 			 * properly update the attributes of directories.
8814 			 * Any cached information gets purged before an
8815 			 * access is made to it.
8816 			 */
8817 			nfs4_purge_rddir_cache(vp);
8818 		}
8819 
8820 		error = nfs4_validate_caches(vp, cr);
8821 		if (error)
8822 			return (error);
8823 	}
8824 
8825 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8826 
8827 	/*
8828 	 * Short circuit last readdir which always returns 0 bytes.
8829 	 * This can be done after the directory has been read through
8830 	 * completely at least once.  This will set r_direof which
8831 	 * can be used to find the value of the last cookie.
8832 	 */
8833 	mutex_enter(&rp->r_statelock);
8834 	if (rp->r_direof != NULL &&
8835 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8836 		mutex_exit(&rp->r_statelock);
8837 #ifdef DEBUG
8838 		nfs4_readdir_cache_shorts++;
8839 #endif
8840 		if (eofp)
8841 			*eofp = 1;
8842 		return (0);
8843 	}
8844 
8845 	/*
8846 	 * Look for a cache entry.  Cache entries are identified
8847 	 * by the NFS cookie value and the byte count requested.
8848 	 */
8849 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8850 
8851 	/*
8852 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8853 	 */
8854 	if (rdc == NULL) {
8855 		mutex_exit(&rp->r_statelock);
8856 		return (EINTR);
8857 	}
8858 
8859 	/*
8860 	 * Check to see if we need to fill this entry in.
8861 	 */
8862 	if (rdc->flags & RDDIRREQ) {
8863 		rdc->flags &= ~RDDIRREQ;
8864 		rdc->flags |= RDDIR;
8865 		mutex_exit(&rp->r_statelock);
8866 
8867 		/*
8868 		 * Do the readdir.
8869 		 */
8870 		nfs4readdir(vp, rdc, cr);
8871 
8872 		/*
8873 		 * Reacquire the lock, so that we can continue
8874 		 */
8875 		mutex_enter(&rp->r_statelock);
8876 		/*
8877 		 * The entry is now complete
8878 		 */
8879 		rdc->flags &= ~RDDIR;
8880 	}
8881 
8882 	ASSERT(!(rdc->flags & RDDIR));
8883 
8884 	/*
8885 	 * If an error occurred while attempting
8886 	 * to fill the cache entry, mark the entry invalid and
8887 	 * just return the error.
8888 	 */
8889 	if (rdc->error) {
8890 		error = rdc->error;
8891 		rdc->flags |= RDDIRREQ;
8892 		rddir4_cache_rele(rp, rdc);
8893 		mutex_exit(&rp->r_statelock);
8894 		return (error);
8895 	}
8896 
8897 	/*
8898 	 * The cache entry is complete and good,
8899 	 * copyout the dirent structs to the calling
8900 	 * thread.
8901 	 */
8902 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
8903 
8904 	/*
8905 	 * If no error occurred during the copyout,
8906 	 * update the offset in the uio struct to
8907 	 * contain the value of the next NFS 4 cookie
8908 	 * and set the eof value appropriately.
8909 	 */
8910 	if (!error) {
8911 		uiop->uio_loffset = rdc->nfs4_ncookie;
8912 		if (eofp)
8913 			*eofp = rdc->eof;
8914 	}
8915 
8916 	/*
8917 	 * Decide whether to do readahead.  Don't if we
8918 	 * have already read to the end of directory.
8919 	 */
8920 	if (rdc->eof) {
8921 		/*
8922 		 * Make the entry the direof only if it is cached
8923 		 */
8924 		if (rdc->flags & RDDIRCACHED)
8925 			rp->r_direof = rdc;
8926 		rddir4_cache_rele(rp, rdc);
8927 		mutex_exit(&rp->r_statelock);
8928 		return (error);
8929 	}
8930 
8931 	/* Determine if a readdir readahead should be done */
8932 	if (!(rp->r_flags & R4LOOKUP)) {
8933 		rddir4_cache_rele(rp, rdc);
8934 		mutex_exit(&rp->r_statelock);
8935 		return (error);
8936 	}
8937 
8938 	/*
8939 	 * Now look for a readahead entry.
8940 	 *
8941 	 * Check to see whether we found an entry for the readahead.
8942 	 * If so, we don't need to do anything further, so free the new
8943 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
8944 	 * it to the cache, and then initiate an asynchronous readdir
8945 	 * operation to fill it.
8946 	 */
8947 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
8948 
8949 	/*
8950 	 * A readdir cache entry could not be obtained for the readahead.  In
8951 	 * this case we skip the readahead and return.
8952 	 */
8953 	if (rrdc == NULL) {
8954 		rddir4_cache_rele(rp, rdc);
8955 		mutex_exit(&rp->r_statelock);
8956 		return (error);
8957 	}
8958 
8959 	/*
8960 	 * Check to see if we need to fill this entry in.
8961 	 */
8962 	if (rrdc->flags & RDDIRREQ) {
8963 		rrdc->flags &= ~RDDIRREQ;
8964 		rrdc->flags |= RDDIR;
8965 		rddir4_cache_rele(rp, rdc);
8966 		mutex_exit(&rp->r_statelock);
8967 #ifdef DEBUG
8968 		nfs4_readdir_readahead++;
8969 #endif
8970 		/*
8971 		 * Do the readdir.
8972 		 */
8973 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
8974 		return (error);
8975 	}
8976 
8977 	rddir4_cache_rele(rp, rrdc);
8978 	rddir4_cache_rele(rp, rdc);
8979 	mutex_exit(&rp->r_statelock);
8980 	return (error);
8981 }
8982 
8983 static int
8984 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
8985 {
8986 	int error;
8987 	rnode4_t *rp;
8988 
8989 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
8990 
8991 	rp = VTOR4(vp);
8992 
8993 	/*
8994 	 * Obtain the readdir results for the caller.
8995 	 */
8996 	nfs4readdir(vp, rdc, cr);
8997 
8998 	mutex_enter(&rp->r_statelock);
8999 	/*
9000 	 * The entry is now complete
9001 	 */
9002 	rdc->flags &= ~RDDIR;
9003 
9004 	error = rdc->error;
9005 	if (error)
9006 		rdc->flags |= RDDIRREQ;
9007 	rddir4_cache_rele(rp, rdc);
9008 	mutex_exit(&rp->r_statelock);
9009 
9010 	return (error);
9011 }
9012 
9013 /*
9014  * Read directory entries.
9015  * There are some weird things to look out for here.  The uio_loffset
9016  * field is either 0 or it is the offset returned from a previous
9017  * readdir.  It is an opaque value used by the server to find the
9018  * correct directory block to read. The count field is the number
9019  * of blocks to read on the server.  This is advisory only, the server
9020  * may return only one block's worth of entries.  Entries may be compressed
9021  * on the server.
9022  *
9023  * Generates the following compound request:
9024  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9025  *    must include a Lookupp as well. In this case, send:
9026  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9027  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9028  *
9029  * Get complete attributes and filehandles for entries if this is the
9030  * first read of the directory. Otherwise, just get fileid's.
9031  */
9032 static void
9033 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9034 {
9035 	COMPOUND4args_clnt args;
9036 	COMPOUND4res_clnt res;
9037 	READDIR4args *rargs;
9038 	READDIR4res_clnt *rd_res;
9039 	bitmap4 rd_bitsval;
9040 	nfs_argop4 argop[5];
9041 	nfs_resop4 *resop;
9042 	rnode4_t *rp = VTOR4(vp);
9043 	mntinfo4_t *mi = VTOMI4(vp);
9044 	int doqueue;
9045 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9046 	vnode_t *dvp;
9047 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9048 	int num_ops, res_opcnt;
9049 	bool_t needrecov = FALSE;
9050 	nfs4_recov_state_t recov_state;
9051 	hrtime_t t;
9052 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9053 
9054 	ASSERT(nfs_zone() == mi->mi_zone);
9055 	ASSERT(rdc->flags & RDDIR);
9056 	ASSERT(rdc->entries == NULL);
9057 
9058 	/*
9059 	 * If rp were a stub, it should have triggered and caused
9060 	 * a mount for us to get this far.
9061 	 */
9062 	ASSERT(!RP_ISSTUB(rp));
9063 
9064 	num_ops = 2;
9065 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9066 		/*
9067 		 * Since nfsv4 readdir may not return entries for "." and "..",
9068 		 * the client must recreate them:
9069 		 * To find the correct nodeid, do the following:
9070 		 * For current node, get nodeid from dnlc.
9071 		 * - if current node is rootvp, set pnodeid to nodeid.
9072 		 * - else if parent is in the dnlc, get its nodeid from there.
9073 		 * - else add LOOKUPP+GETATTR to compound.
9074 		 */
9075 		nodeid = rp->r_attr.va_nodeid;
9076 		if (vp->v_flag & VROOT) {
9077 			pnodeid = nodeid;	/* root of mount point */
9078 		} else {
9079 			dvp = dnlc_lookup(vp, "..");
9080 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9081 				/* parent in dnlc cache - no need for otw */
9082 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9083 			} else {
9084 				/*
9085 				 * parent not in dnlc cache,
9086 				 * do lookupp to get its id
9087 				 */
9088 				num_ops = 5;
9089 				pnodeid = 0; /* set later by getattr parent */
9090 			}
9091 			if (dvp)
9092 				VN_RELE(dvp);
9093 		}
9094 	}
9095 	recov_state.rs_flags = 0;
9096 	recov_state.rs_num_retry_despite_err = 0;
9097 
9098 	/* Save the original mount point security flavor */
9099 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9100 
9101 recov_retry:
9102 	args.ctag = TAG_READDIR;
9103 
9104 	args.array = argop;
9105 	args.array_len = num_ops;
9106 
9107 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9108 	    &recov_state, NULL)) {
9109 		/*
9110 		 * If readdir a node that is a stub for a crossed mount point,
9111 		 * keep the original secinfo flavor for the current file
9112 		 * system, not the crossed one.
9113 		 */
9114 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9115 		rdc->error = e.error;
9116 		return;
9117 	}
9118 
9119 	/*
9120 	 * Determine which attrs to request for dirents.  This code
9121 	 * must be protected by nfs4_start/end_fop because of r_server
9122 	 * (which will change during failover recovery).
9123 	 *
9124 	 */
9125 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9126 		/*
9127 		 * Get all vattr attrs plus filehandle and rdattr_error
9128 		 */
9129 		rd_bitsval = NFS4_VATTR_MASK |
9130 		    FATTR4_RDATTR_ERROR_MASK |
9131 		    FATTR4_FILEHANDLE_MASK;
9132 
9133 		if (rp->r_flags & R4READDIRWATTR) {
9134 			mutex_enter(&rp->r_statelock);
9135 			rp->r_flags &= ~R4READDIRWATTR;
9136 			mutex_exit(&rp->r_statelock);
9137 		}
9138 	} else {
9139 		servinfo4_t *svp = rp->r_server;
9140 
9141 		/*
9142 		 * Already read directory. Use readdir with
9143 		 * no attrs (except for mounted_on_fileid) for updates.
9144 		 */
9145 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9146 
9147 		/*
9148 		 * request mounted on fileid if supported, else request
9149 		 * fileid.  maybe we should verify that fileid is supported
9150 		 * and request something else if not.
9151 		 */
9152 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9153 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9154 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9155 		nfs_rw_exit(&svp->sv_lock);
9156 	}
9157 
9158 	/* putfh directory fh */
9159 	argop[0].argop = OP_CPUTFH;
9160 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9161 
9162 	argop[1].argop = OP_READDIR;
9163 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9164 	/*
9165 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9166 	 * cookie 0 should be used over-the-wire to start reading at
9167 	 * the beginning of the directory excluding "." and "..".
9168 	 */
9169 	if (rdc->nfs4_cookie == 0 ||
9170 	    rdc->nfs4_cookie == 1 ||
9171 	    rdc->nfs4_cookie == 2) {
9172 		rargs->cookie = (nfs_cookie4)0;
9173 		rargs->cookieverf = 0;
9174 	} else {
9175 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9176 		mutex_enter(&rp->r_statelock);
9177 		rargs->cookieverf = rp->r_cookieverf4;
9178 		mutex_exit(&rp->r_statelock);
9179 	}
9180 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9181 	rargs->maxcount = mi->mi_tsize;
9182 	rargs->attr_request = rd_bitsval;
9183 	rargs->rdc = rdc;
9184 	rargs->dvp = vp;
9185 	rargs->mi = mi;
9186 	rargs->cr = cr;
9187 
9188 
9189 	/*
9190 	 * If count < than the minimum required, we return no entries
9191 	 * and fail with EINVAL
9192 	 */
9193 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9194 		rdc->error = EINVAL;
9195 		goto out;
9196 	}
9197 
9198 	if (args.array_len == 5) {
9199 		/*
9200 		 * Add lookupp and getattr for parent nodeid.
9201 		 */
9202 		argop[2].argop = OP_LOOKUPP;
9203 
9204 		argop[3].argop = OP_GETFH;
9205 
9206 		/* getattr parent */
9207 		argop[4].argop = OP_GETATTR;
9208 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9209 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9210 	}
9211 
9212 	doqueue = 1;
9213 
9214 	if (mi->mi_io_kstats) {
9215 		mutex_enter(&mi->mi_lock);
9216 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9217 		mutex_exit(&mi->mi_lock);
9218 	}
9219 
9220 	/* capture the time of this call */
9221 	rargs->t = t = gethrtime();
9222 
9223 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9224 
9225 	if (mi->mi_io_kstats) {
9226 		mutex_enter(&mi->mi_lock);
9227 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9228 		mutex_exit(&mi->mi_lock);
9229 	}
9230 
9231 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9232 
9233 	/*
9234 	 * If RPC error occurred and it isn't an error that
9235 	 * triggers recovery, then go ahead and fail now.
9236 	 */
9237 	if (e.error != 0 && !needrecov) {
9238 		rdc->error = e.error;
9239 		goto out;
9240 	}
9241 
9242 	if (needrecov) {
9243 		bool_t abort;
9244 
9245 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9246 		    "nfs4readdir: initiating recovery.\n"));
9247 
9248 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9249 		    NULL, OP_READDIR, NULL);
9250 		if (abort == FALSE) {
9251 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9252 			    &recov_state, needrecov);
9253 			if (!e.error)
9254 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9255 				    (caddr_t)&res);
9256 			if (rdc->entries != NULL) {
9257 				kmem_free(rdc->entries, rdc->entlen);
9258 				rdc->entries = NULL;
9259 			}
9260 			goto recov_retry;
9261 		}
9262 
9263 		if (e.error != 0) {
9264 			rdc->error = e.error;
9265 			goto out;
9266 		}
9267 
9268 		/* fall through for res.status case */
9269 	}
9270 
9271 	res_opcnt = res.array_len;
9272 
9273 	/*
9274 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9275 	 * failure here.  Subsequent ops are for filling out dot-dot
9276 	 * dirent, and if they fail, we still want to give the caller
9277 	 * the dirents returned by (the successful) READDIR op, so we need
9278 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9279 	 *
9280 	 * One example where PUTFH+READDIR ops would succeed but
9281 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9282 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9283 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9284 	 * x perm.  We need to come up with a non-vendor-specific way
9285 	 * for a POSIX server to return d_ino from dotdot's dirent if
9286 	 * client only requests mounted_on_fileid, and just say the
9287 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9288 	 * client requested any mandatory attrs, server would be required
9289 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9290 	 * for dotdot.
9291 	 */
9292 
9293 	if (res.status) {
9294 		if (res_opcnt <= 2) {
9295 			e.error = geterrno4(res.status);
9296 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9297 			    &recov_state, needrecov);
9298 			nfs4_purge_stale_fh(e.error, vp, cr);
9299 			rdc->error = e.error;
9300 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9301 			if (rdc->entries != NULL) {
9302 				kmem_free(rdc->entries, rdc->entlen);
9303 				rdc->entries = NULL;
9304 			}
9305 			/*
9306 			 * If readdir a node that is a stub for a
9307 			 * crossed mount point, keep the original
9308 			 * secinfo flavor for the current file system,
9309 			 * not the crossed one.
9310 			 */
9311 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9312 			return;
9313 		}
9314 	}
9315 
9316 	resop = &res.array[1];	/* readdir res */
9317 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9318 
9319 	mutex_enter(&rp->r_statelock);
9320 	rp->r_cookieverf4 = rd_res->cookieverf;
9321 	mutex_exit(&rp->r_statelock);
9322 
9323 	/*
9324 	 * For "." and ".." entries
9325 	 * e.g.
9326 	 *	seek(cookie=0) -> "." entry with d_off = 1
9327 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9328 	 */
9329 	if (cookie == (nfs_cookie4) 0) {
9330 		if (rd_res->dotp)
9331 			rd_res->dotp->d_ino = nodeid;
9332 		if (rd_res->dotdotp)
9333 			rd_res->dotdotp->d_ino = pnodeid;
9334 	}
9335 	if (cookie == (nfs_cookie4) 1) {
9336 		if (rd_res->dotdotp)
9337 			rd_res->dotdotp->d_ino = pnodeid;
9338 	}
9339 
9340 
9341 	/* LOOKUPP+GETATTR attemped */
9342 	if (args.array_len == 5 && rd_res->dotdotp) {
9343 		if (res.status == NFS4_OK && res_opcnt == 5) {
9344 			nfs_fh4 *fhp;
9345 			nfs4_sharedfh_t *sfhp;
9346 			vnode_t *pvp;
9347 			nfs4_ga_res_t *garp;
9348 
9349 			resop++;	/* lookupp */
9350 			resop++;	/* getfh   */
9351 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9352 
9353 			resop++;	/* getattr of parent */
9354 
9355 			/*
9356 			 * First, take care of finishing the
9357 			 * readdir results.
9358 			 */
9359 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9360 			/*
9361 			 * The d_ino of .. must be the inode number
9362 			 * of the mounted filesystem.
9363 			 */
9364 			if (garp->n4g_va.va_mask & AT_NODEID)
9365 				rd_res->dotdotp->d_ino =
9366 				    garp->n4g_va.va_nodeid;
9367 
9368 
9369 			/*
9370 			 * Next, create the ".." dnlc entry
9371 			 */
9372 			sfhp = sfh4_get(fhp, mi);
9373 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9374 				dnlc_update(vp, "..", pvp);
9375 				VN_RELE(pvp);
9376 			}
9377 			sfh4_rele(&sfhp);
9378 		}
9379 	}
9380 
9381 	if (mi->mi_io_kstats) {
9382 		mutex_enter(&mi->mi_lock);
9383 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9384 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9385 		mutex_exit(&mi->mi_lock);
9386 	}
9387 
9388 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9389 
9390 out:
9391 	/*
9392 	 * If readdir a node that is a stub for a crossed mount point,
9393 	 * keep the original secinfo flavor for the current file system,
9394 	 * not the crossed one.
9395 	 */
9396 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9397 
9398 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9399 }
9400 
9401 
9402 static int
9403 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9404 {
9405 	rnode4_t *rp = VTOR4(bp->b_vp);
9406 	int count;
9407 	int error;
9408 	cred_t *cred_otw = NULL;
9409 	offset_t offset;
9410 	nfs4_open_stream_t *osp = NULL;
9411 	bool_t first_time = TRUE;	/* first time getting otw cred */
9412 	bool_t last_time = FALSE;	/* last time getting otw cred */
9413 
9414 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9415 
9416 	DTRACE_IO1(start, struct buf *, bp);
9417 	offset = ldbtob(bp->b_lblkno);
9418 
9419 	if (bp->b_flags & B_READ) {
9420 	read_again:
9421 		/*
9422 		 * Releases the osp, if it is provided.
9423 		 * Puts a hold on the cred_otw and the new osp (if found).
9424 		 */
9425 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9426 		    &first_time, &last_time);
9427 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9428 		    offset, bp->b_bcount, &bp->b_resid, cred_otw,
9429 		    readahead, NULL);
9430 		crfree(cred_otw);
9431 		if (!error) {
9432 			if (bp->b_resid) {
9433 				/*
9434 				 * Didn't get it all because we hit EOF,
9435 				 * zero all the memory beyond the EOF.
9436 				 */
9437 				/* bzero(rdaddr + */
9438 				bzero(bp->b_un.b_addr +
9439 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9440 			}
9441 			mutex_enter(&rp->r_statelock);
9442 			if (bp->b_resid == bp->b_bcount &&
9443 			    offset >= rp->r_size) {
9444 				/*
9445 				 * We didn't read anything at all as we are
9446 				 * past EOF.  Return an error indicator back
9447 				 * but don't destroy the pages (yet).
9448 				 */
9449 				error = NFS_EOF;
9450 			}
9451 			mutex_exit(&rp->r_statelock);
9452 		} else if (error == EACCES && last_time == FALSE) {
9453 				goto read_again;
9454 		}
9455 	} else {
9456 		if (!(rp->r_flags & R4STALE)) {
9457 write_again:
9458 			/*
9459 			 * Releases the osp, if it is provided.
9460 			 * Puts a hold on the cred_otw and the new
9461 			 * osp (if found).
9462 			 */
9463 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9464 			    &first_time, &last_time);
9465 			mutex_enter(&rp->r_statelock);
9466 			count = MIN(bp->b_bcount, rp->r_size - offset);
9467 			mutex_exit(&rp->r_statelock);
9468 			if (count < 0)
9469 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9470 #ifdef DEBUG
9471 			if (count == 0) {
9472 				zoneid_t zoneid = getzoneid();
9473 
9474 				zcmn_err(zoneid, CE_WARN,
9475 				    "nfs4_bio: zero length write at %lld",
9476 				    offset);
9477 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9478 				    "b_bcount=%ld, file size=%lld",
9479 				    rp->r_flags, (long)bp->b_bcount,
9480 				    rp->r_size);
9481 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9482 				if (nfs4_bio_do_stop)
9483 					debug_enter("nfs4_bio");
9484 			}
9485 #endif
9486 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9487 			    count, cred_otw, stab_comm);
9488 			if (error == EACCES && last_time == FALSE) {
9489 				crfree(cred_otw);
9490 				goto write_again;
9491 			}
9492 			bp->b_error = error;
9493 			if (error && error != EINTR &&
9494 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9495 				/*
9496 				 * Don't print EDQUOT errors on the console.
9497 				 * Don't print asynchronous EACCES errors.
9498 				 * Don't print EFBIG errors.
9499 				 * Print all other write errors.
9500 				 */
9501 				if (error != EDQUOT && error != EFBIG &&
9502 				    (error != EACCES ||
9503 				    !(bp->b_flags & B_ASYNC)))
9504 					nfs4_write_error(bp->b_vp,
9505 					    error, cred_otw);
9506 				/*
9507 				 * Update r_error and r_flags as appropriate.
9508 				 * If the error was ESTALE, then mark the
9509 				 * rnode as not being writeable and save
9510 				 * the error status.  Otherwise, save any
9511 				 * errors which occur from asynchronous
9512 				 * page invalidations.  Any errors occurring
9513 				 * from other operations should be saved
9514 				 * by the caller.
9515 				 */
9516 				mutex_enter(&rp->r_statelock);
9517 				if (error == ESTALE) {
9518 					rp->r_flags |= R4STALE;
9519 					if (!rp->r_error)
9520 						rp->r_error = error;
9521 				} else if (!rp->r_error &&
9522 				    (bp->b_flags &
9523 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9524 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9525 					rp->r_error = error;
9526 				}
9527 				mutex_exit(&rp->r_statelock);
9528 			}
9529 			crfree(cred_otw);
9530 		} else
9531 			error = rp->r_error;
9532 	}
9533 
9534 	if (error != 0 && error != NFS_EOF)
9535 		bp->b_flags |= B_ERROR;
9536 
9537 	if (osp)
9538 		open_stream_rele(osp, rp);
9539 
9540 	DTRACE_IO1(done, struct buf *, bp);
9541 
9542 	return (error);
9543 }
9544 
9545 /* ARGSUSED */
9546 int
9547 nfs4_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
9548 {
9549 	return (EREMOTE);
9550 }
9551 
9552 /* ARGSUSED2 */
9553 int
9554 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9555 {
9556 	rnode4_t *rp = VTOR4(vp);
9557 
9558 	if (!write_lock) {
9559 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9560 		return (V_WRITELOCK_FALSE);
9561 	}
9562 
9563 	if ((rp->r_flags & R4DIRECTIO) ||
9564 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9565 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9566 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9567 			return (V_WRITELOCK_FALSE);
9568 		nfs_rw_exit(&rp->r_rwlock);
9569 	}
9570 
9571 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9572 	return (V_WRITELOCK_TRUE);
9573 }
9574 
9575 /* ARGSUSED */
9576 void
9577 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9578 {
9579 	rnode4_t *rp = VTOR4(vp);
9580 
9581 	nfs_rw_exit(&rp->r_rwlock);
9582 }
9583 
9584 /* ARGSUSED */
9585 static int
9586 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp, caller_context_t *ct)
9587 {
9588 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9589 		return (EIO);
9590 
9591 	/*
9592 	 * Because we stuff the readdir cookie into the offset field
9593 	 * someone may attempt to do an lseek with the cookie which
9594 	 * we want to succeed.
9595 	 */
9596 	if (vp->v_type == VDIR)
9597 		return (0);
9598 	if (*noffp < 0)
9599 		return (EINVAL);
9600 	return (0);
9601 }
9602 
9603 
9604 /*
9605  * Return all the pages from [off..off+len) in file
9606  */
9607 /* ARGSUSED */
9608 static int
9609 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9610     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9611 	enum seg_rw rw, cred_t *cr, caller_context_t *ct)
9612 {
9613 	rnode4_t *rp;
9614 	int error;
9615 	mntinfo4_t *mi;
9616 
9617 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9618 		return (EIO);
9619 	rp = VTOR4(vp);
9620 	if (IS_SHADOW(vp, rp))
9621 		vp = RTOV4(rp);
9622 
9623 	if (vp->v_flag & VNOMAP)
9624 		return (ENOSYS);
9625 
9626 	if (protp != NULL)
9627 		*protp = PROT_ALL;
9628 
9629 	/*
9630 	 * Now validate that the caches are up to date.
9631 	 */
9632 	if (error = nfs4_validate_caches(vp, cr))
9633 		return (error);
9634 
9635 	mi = VTOMI4(vp);
9636 retry:
9637 	mutex_enter(&rp->r_statelock);
9638 
9639 	/*
9640 	 * Don't create dirty pages faster than they
9641 	 * can be cleaned so that the system doesn't
9642 	 * get imbalanced.  If the async queue is
9643 	 * maxed out, then wait for it to drain before
9644 	 * creating more dirty pages.  Also, wait for
9645 	 * any threads doing pagewalks in the vop_getattr
9646 	 * entry points so that they don't block for
9647 	 * long periods.
9648 	 */
9649 	if (rw == S_CREATE) {
9650 		while ((mi->mi_max_threads != 0 &&
9651 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
9652 		    rp->r_gcount > 0)
9653 			cv_wait(&rp->r_cv, &rp->r_statelock);
9654 	}
9655 
9656 	/*
9657 	 * If we are getting called as a side effect of an nfs_write()
9658 	 * operation the local file size might not be extended yet.
9659 	 * In this case we want to be able to return pages of zeroes.
9660 	 */
9661 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9662 		NFS4_DEBUG(nfs4_pageio_debug,
9663 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9664 		    "len=%llu, size=%llu, attrsize =%llu", off,
9665 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9666 		mutex_exit(&rp->r_statelock);
9667 		return (EFAULT);		/* beyond EOF */
9668 	}
9669 
9670 	mutex_exit(&rp->r_statelock);
9671 
9672 	if (len <= PAGESIZE) {
9673 		error = nfs4_getapage(vp, off, len, protp, pl, plsz,
9674 		    seg, addr, rw, cr);
9675 		NFS4_DEBUG(nfs4_pageio_debug && error,
9676 		    (CE_NOTE, "getpage error %d; off=%lld, "
9677 		    "len=%lld", error, off, (u_longlong_t)len));
9678 	} else {
9679 		error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9680 		    pl, plsz, seg, addr, rw, cr);
9681 		NFS4_DEBUG(nfs4_pageio_debug && error,
9682 		    (CE_NOTE, "getpages error %d; off=%lld, "
9683 		    "len=%lld", error, off, (u_longlong_t)len));
9684 	}
9685 
9686 	switch (error) {
9687 	case NFS_EOF:
9688 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9689 		goto retry;
9690 	case ESTALE:
9691 		nfs4_purge_stale_fh(error, vp, cr);
9692 	}
9693 
9694 	return (error);
9695 }
9696 
9697 /*
9698  * Called from pvn_getpages or nfs4_getpage to get a particular page.
9699  */
9700 /* ARGSUSED */
9701 static int
9702 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9703     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9704     enum seg_rw rw, cred_t *cr)
9705 {
9706 	rnode4_t *rp;
9707 	uint_t bsize;
9708 	struct buf *bp;
9709 	page_t *pp;
9710 	u_offset_t lbn;
9711 	u_offset_t io_off;
9712 	u_offset_t blkoff;
9713 	u_offset_t rablkoff;
9714 	size_t io_len;
9715 	uint_t blksize;
9716 	int error;
9717 	int readahead;
9718 	int readahead_issued = 0;
9719 	int ra_window; /* readahead window */
9720 	page_t *pagefound;
9721 	page_t *savepp;
9722 
9723 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9724 		return (EIO);
9725 
9726 	rp = VTOR4(vp);
9727 	ASSERT(!IS_SHADOW(vp, rp));
9728 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9729 
9730 reread:
9731 	bp = NULL;
9732 	pp = NULL;
9733 	pagefound = NULL;
9734 
9735 	if (pl != NULL)
9736 		pl[0] = NULL;
9737 
9738 	error = 0;
9739 	lbn = off / bsize;
9740 	blkoff = lbn * bsize;
9741 
9742 	/*
9743 	 * Queueing up the readahead before doing the synchronous read
9744 	 * results in a significant increase in read throughput because
9745 	 * of the increased parallelism between the async threads and
9746 	 * the process context.
9747 	 */
9748 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9749 	    rw != S_CREATE &&
9750 	    !(vp->v_flag & VNOCACHE)) {
9751 		mutex_enter(&rp->r_statelock);
9752 
9753 		/*
9754 		 * Calculate the number of readaheads to do.
9755 		 * a) No readaheads at offset = 0.
9756 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9757 		 *    window is closed.
9758 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9759 		 *    upon how far the readahead window is open or close.
9760 		 * d) No readaheads if rp->r_nextr is not within the scope
9761 		 *    of the readahead window (random i/o).
9762 		 */
9763 
9764 		if (off == 0)
9765 			readahead = 0;
9766 		else if (blkoff == rp->r_nextr)
9767 			readahead = nfs4_nra;
9768 		else if (rp->r_nextr > blkoff &&
9769 		    ((ra_window = (rp->r_nextr - blkoff) / bsize)
9770 		    <= (nfs4_nra - 1)))
9771 			readahead = nfs4_nra - ra_window;
9772 		else
9773 			readahead = 0;
9774 
9775 		rablkoff = rp->r_nextr;
9776 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9777 			mutex_exit(&rp->r_statelock);
9778 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9779 			    addr + (rablkoff + bsize - off),
9780 			    seg, cr, nfs4_readahead) < 0) {
9781 				mutex_enter(&rp->r_statelock);
9782 				break;
9783 			}
9784 			readahead--;
9785 			rablkoff += bsize;
9786 			/*
9787 			 * Indicate that we did a readahead so
9788 			 * readahead offset is not updated
9789 			 * by the synchronous read below.
9790 			 */
9791 			readahead_issued = 1;
9792 			mutex_enter(&rp->r_statelock);
9793 			/*
9794 			 * set readahead offset to
9795 			 * offset of last async readahead
9796 			 * request.
9797 			 */
9798 			rp->r_nextr = rablkoff;
9799 		}
9800 		mutex_exit(&rp->r_statelock);
9801 	}
9802 
9803 again:
9804 	if ((pagefound = page_exists(vp, off)) == NULL) {
9805 		if (pl == NULL) {
9806 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9807 			    nfs4_readahead);
9808 		} else if (rw == S_CREATE) {
9809 			/*
9810 			 * Block for this page is not allocated, or the offset
9811 			 * is beyond the current allocation size, or we're
9812 			 * allocating a swap slot and the page was not found,
9813 			 * so allocate it and return a zero page.
9814 			 */
9815 			if ((pp = page_create_va(vp, off,
9816 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9817 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9818 			io_len = PAGESIZE;
9819 			mutex_enter(&rp->r_statelock);
9820 			rp->r_nextr = off + PAGESIZE;
9821 			mutex_exit(&rp->r_statelock);
9822 		} else {
9823 			/*
9824 			 * Need to go to server to get a block
9825 			 */
9826 			mutex_enter(&rp->r_statelock);
9827 			if (blkoff < rp->r_size &&
9828 			    blkoff + bsize > rp->r_size) {
9829 				/*
9830 				 * If less than a block left in
9831 				 * file read less than a block.
9832 				 */
9833 				if (rp->r_size <= off) {
9834 					/*
9835 					 * Trying to access beyond EOF,
9836 					 * set up to get at least one page.
9837 					 */
9838 					blksize = off + PAGESIZE - blkoff;
9839 				} else
9840 					blksize = rp->r_size - blkoff;
9841 			} else if ((off == 0) ||
9842 			    (off != rp->r_nextr && !readahead_issued)) {
9843 				blksize = PAGESIZE;
9844 				blkoff = off; /* block = page here */
9845 			} else
9846 				blksize = bsize;
9847 			mutex_exit(&rp->r_statelock);
9848 
9849 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9850 			    &io_len, blkoff, blksize, 0);
9851 
9852 			/*
9853 			 * Some other thread has entered the page,
9854 			 * so just use it.
9855 			 */
9856 			if (pp == NULL)
9857 				goto again;
9858 
9859 			/*
9860 			 * Now round the request size up to page boundaries.
9861 			 * This ensures that the entire page will be
9862 			 * initialized to zeroes if EOF is encountered.
9863 			 */
9864 			io_len = ptob(btopr(io_len));
9865 
9866 			bp = pageio_setup(pp, io_len, vp, B_READ);
9867 			ASSERT(bp != NULL);
9868 
9869 			/*
9870 			 * pageio_setup should have set b_addr to 0.  This
9871 			 * is correct since we want to do I/O on a page
9872 			 * boundary.  bp_mapin will use this addr to calculate
9873 			 * an offset, and then set b_addr to the kernel virtual
9874 			 * address it allocated for us.
9875 			 */
9876 			ASSERT(bp->b_un.b_addr == 0);
9877 
9878 			bp->b_edev = 0;
9879 			bp->b_dev = 0;
9880 			bp->b_lblkno = lbtodb(io_off);
9881 			bp->b_file = vp;
9882 			bp->b_offset = (offset_t)off;
9883 			bp_mapin(bp);
9884 
9885 			/*
9886 			 * If doing a write beyond what we believe is EOF,
9887 			 * don't bother trying to read the pages from the
9888 			 * server, we'll just zero the pages here.  We
9889 			 * don't check that the rw flag is S_WRITE here
9890 			 * because some implementations may attempt a
9891 			 * read access to the buffer before copying data.
9892 			 */
9893 			mutex_enter(&rp->r_statelock);
9894 			if (io_off >= rp->r_size && seg == segkmap) {
9895 				mutex_exit(&rp->r_statelock);
9896 				bzero(bp->b_un.b_addr, io_len);
9897 			} else {
9898 				mutex_exit(&rp->r_statelock);
9899 				error = nfs4_bio(bp, NULL, cr, FALSE);
9900 			}
9901 
9902 			/*
9903 			 * Unmap the buffer before freeing it.
9904 			 */
9905 			bp_mapout(bp);
9906 			pageio_done(bp);
9907 
9908 			savepp = pp;
9909 			do {
9910 				pp->p_fsdata = C_NOCOMMIT;
9911 			} while ((pp = pp->p_next) != savepp);
9912 
9913 			if (error == NFS_EOF) {
9914 				/*
9915 				 * If doing a write system call just return
9916 				 * zeroed pages, else user tried to get pages
9917 				 * beyond EOF, return error.  We don't check
9918 				 * that the rw flag is S_WRITE here because
9919 				 * some implementations may attempt a read
9920 				 * access to the buffer before copying data.
9921 				 */
9922 				if (seg == segkmap)
9923 					error = 0;
9924 				else
9925 					error = EFAULT;
9926 			}
9927 
9928 			if (!readahead_issued && !error) {
9929 				mutex_enter(&rp->r_statelock);
9930 				rp->r_nextr = io_off + io_len;
9931 				mutex_exit(&rp->r_statelock);
9932 			}
9933 		}
9934 	}
9935 
9936 out:
9937 	if (pl == NULL)
9938 		return (error);
9939 
9940 	if (error) {
9941 		if (pp != NULL)
9942 			pvn_read_done(pp, B_ERROR);
9943 		return (error);
9944 	}
9945 
9946 	if (pagefound) {
9947 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
9948 
9949 		/*
9950 		 * Page exists in the cache, acquire the appropriate lock.
9951 		 * If this fails, start all over again.
9952 		 */
9953 		if ((pp = page_lookup(vp, off, se)) == NULL) {
9954 #ifdef DEBUG
9955 			nfs4_lostpage++;
9956 #endif
9957 			goto reread;
9958 		}
9959 		pl[0] = pp;
9960 		pl[1] = NULL;
9961 		return (0);
9962 	}
9963 
9964 	if (pp != NULL)
9965 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
9966 
9967 	return (error);
9968 }
9969 
9970 static void
9971 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
9972     cred_t *cr)
9973 {
9974 	int error;
9975 	page_t *pp;
9976 	u_offset_t io_off;
9977 	size_t io_len;
9978 	struct buf *bp;
9979 	uint_t bsize, blksize;
9980 	rnode4_t *rp = VTOR4(vp);
9981 	page_t *savepp;
9982 
9983 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9984 
9985 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9986 
9987 	mutex_enter(&rp->r_statelock);
9988 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
9989 		/*
9990 		 * If less than a block left in file read less
9991 		 * than a block.
9992 		 */
9993 		blksize = rp->r_size - blkoff;
9994 	} else
9995 		blksize = bsize;
9996 	mutex_exit(&rp->r_statelock);
9997 
9998 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
9999 	    &io_off, &io_len, blkoff, blksize, 1);
10000 	/*
10001 	 * The isra flag passed to the kluster function is 1, we may have
10002 	 * gotten a return value of NULL for a variety of reasons (# of free
10003 	 * pages < minfree, someone entered the page on the vnode etc). In all
10004 	 * cases, we want to punt on the readahead.
10005 	 */
10006 	if (pp == NULL)
10007 		return;
10008 
10009 	/*
10010 	 * Now round the request size up to page boundaries.
10011 	 * This ensures that the entire page will be
10012 	 * initialized to zeroes if EOF is encountered.
10013 	 */
10014 	io_len = ptob(btopr(io_len));
10015 
10016 	bp = pageio_setup(pp, io_len, vp, B_READ);
10017 	ASSERT(bp != NULL);
10018 
10019 	/*
10020 	 * pageio_setup should have set b_addr to 0.  This is correct since
10021 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10022 	 * to calculate an offset, and then set b_addr to the kernel virtual
10023 	 * address it allocated for us.
10024 	 */
10025 	ASSERT(bp->b_un.b_addr == 0);
10026 
10027 	bp->b_edev = 0;
10028 	bp->b_dev = 0;
10029 	bp->b_lblkno = lbtodb(io_off);
10030 	bp->b_file = vp;
10031 	bp->b_offset = (offset_t)blkoff;
10032 	bp_mapin(bp);
10033 
10034 	/*
10035 	 * If doing a write beyond what we believe is EOF, don't bother trying
10036 	 * to read the pages from the server, we'll just zero the pages here.
10037 	 * We don't check that the rw flag is S_WRITE here because some
10038 	 * implementations may attempt a read access to the buffer before
10039 	 * copying data.
10040 	 */
10041 	mutex_enter(&rp->r_statelock);
10042 	if (io_off >= rp->r_size && seg == segkmap) {
10043 		mutex_exit(&rp->r_statelock);
10044 		bzero(bp->b_un.b_addr, io_len);
10045 		error = 0;
10046 	} else {
10047 		mutex_exit(&rp->r_statelock);
10048 		error = nfs4_bio(bp, NULL, cr, TRUE);
10049 		if (error == NFS_EOF)
10050 			error = 0;
10051 	}
10052 
10053 	/*
10054 	 * Unmap the buffer before freeing it.
10055 	 */
10056 	bp_mapout(bp);
10057 	pageio_done(bp);
10058 
10059 	savepp = pp;
10060 	do {
10061 		pp->p_fsdata = C_NOCOMMIT;
10062 	} while ((pp = pp->p_next) != savepp);
10063 
10064 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10065 
10066 	/*
10067 	 * In case of error set readahead offset
10068 	 * to the lowest offset.
10069 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10070 	 */
10071 	if (error && rp->r_nextr > io_off) {
10072 		mutex_enter(&rp->r_statelock);
10073 		if (rp->r_nextr > io_off)
10074 			rp->r_nextr = io_off;
10075 		mutex_exit(&rp->r_statelock);
10076 	}
10077 }
10078 
10079 /*
10080  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10081  * If len == 0, do from off to EOF.
10082  *
10083  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10084  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10085  * (from pageout).
10086  */
10087 /* ARGSUSED */
10088 static int
10089 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
10090 	caller_context_t *ct)
10091 {
10092 	int error;
10093 	rnode4_t *rp;
10094 
10095 	ASSERT(cr != NULL);
10096 
10097 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10098 		return (EIO);
10099 
10100 	rp = VTOR4(vp);
10101 	if (IS_SHADOW(vp, rp))
10102 		vp = RTOV4(rp);
10103 
10104 	/*
10105 	 * XXX - Why should this check be made here?
10106 	 */
10107 	if (vp->v_flag & VNOMAP)
10108 		return (ENOSYS);
10109 
10110 	if (len == 0 && !(flags & B_INVAL) &&
10111 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10112 		return (0);
10113 
10114 	mutex_enter(&rp->r_statelock);
10115 	rp->r_count++;
10116 	mutex_exit(&rp->r_statelock);
10117 	error = nfs4_putpages(vp, off, len, flags, cr);
10118 	mutex_enter(&rp->r_statelock);
10119 	rp->r_count--;
10120 	cv_broadcast(&rp->r_cv);
10121 	mutex_exit(&rp->r_statelock);
10122 
10123 	return (error);
10124 }
10125 
10126 /*
10127  * Write out a single page, possibly klustering adjacent dirty pages.
10128  */
10129 int
10130 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10131     int flags, cred_t *cr)
10132 {
10133 	u_offset_t io_off;
10134 	u_offset_t lbn_off;
10135 	u_offset_t lbn;
10136 	size_t io_len;
10137 	uint_t bsize;
10138 	int error;
10139 	rnode4_t *rp;
10140 
10141 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10142 	ASSERT(pp != NULL);
10143 	ASSERT(cr != NULL);
10144 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10145 
10146 	rp = VTOR4(vp);
10147 	ASSERT(rp->r_count > 0);
10148 	ASSERT(!IS_SHADOW(vp, rp));
10149 
10150 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10151 	lbn = pp->p_offset / bsize;
10152 	lbn_off = lbn * bsize;
10153 
10154 	/*
10155 	 * Find a kluster that fits in one block, or in
10156 	 * one page if pages are bigger than blocks.  If
10157 	 * there is less file space allocated than a whole
10158 	 * page, we'll shorten the i/o request below.
10159 	 */
10160 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10161 	    roundup(bsize, PAGESIZE), flags);
10162 
10163 	/*
10164 	 * pvn_write_kluster shouldn't have returned a page with offset
10165 	 * behind the original page we were given.  Verify that.
10166 	 */
10167 	ASSERT((pp->p_offset / bsize) >= lbn);
10168 
10169 	/*
10170 	 * Now pp will have the list of kept dirty pages marked for
10171 	 * write back.  It will also handle invalidation and freeing
10172 	 * of pages that are not dirty.  Check for page length rounding
10173 	 * problems.
10174 	 */
10175 	if (io_off + io_len > lbn_off + bsize) {
10176 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10177 		io_len = lbn_off + bsize - io_off;
10178 	}
10179 	/*
10180 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10181 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10182 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10183 	 * progress and the r_size has not been made consistent with the
10184 	 * new size of the file. When the uiomove() completes the r_size is
10185 	 * updated and the R4MODINPROGRESS flag is cleared.
10186 	 *
10187 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10188 	 * consistent value of r_size. Without this handshaking, it is
10189 	 * possible that nfs4_bio() picks  up the old value of r_size
10190 	 * before the uiomove() in writerp4() completes. This will result
10191 	 * in the write through nfs4_bio() being dropped.
10192 	 *
10193 	 * More precisely, there is a window between the time the uiomove()
10194 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10195 	 * operation intervenes in this window, the page will be picked up,
10196 	 * because it is dirty (it will be unlocked, unless it was
10197 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10198 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10199 	 * checked. This will still be the old size. Therefore the page will
10200 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10201 	 * the page will be found to be clean and the write will be dropped.
10202 	 */
10203 	if (rp->r_flags & R4MODINPROGRESS) {
10204 		mutex_enter(&rp->r_statelock);
10205 		if ((rp->r_flags & R4MODINPROGRESS) &&
10206 		    rp->r_modaddr + MAXBSIZE > io_off &&
10207 		    rp->r_modaddr < io_off + io_len) {
10208 			page_t *plist;
10209 			/*
10210 			 * A write is in progress for this region of the file.
10211 			 * If we did not detect R4MODINPROGRESS here then this
10212 			 * path through nfs_putapage() would eventually go to
10213 			 * nfs4_bio() and may not write out all of the data
10214 			 * in the pages. We end up losing data. So we decide
10215 			 * to set the modified bit on each page in the page
10216 			 * list and mark the rnode with R4DIRTY. This write
10217 			 * will be restarted at some later time.
10218 			 */
10219 			plist = pp;
10220 			while (plist != NULL) {
10221 				pp = plist;
10222 				page_sub(&plist, pp);
10223 				hat_setmod(pp);
10224 				page_io_unlock(pp);
10225 				page_unlock(pp);
10226 			}
10227 			rp->r_flags |= R4DIRTY;
10228 			mutex_exit(&rp->r_statelock);
10229 			if (offp)
10230 				*offp = io_off;
10231 			if (lenp)
10232 				*lenp = io_len;
10233 			return (0);
10234 		}
10235 		mutex_exit(&rp->r_statelock);
10236 	}
10237 
10238 	if (flags & B_ASYNC) {
10239 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10240 		    nfs4_sync_putapage);
10241 	} else
10242 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10243 
10244 	if (offp)
10245 		*offp = io_off;
10246 	if (lenp)
10247 		*lenp = io_len;
10248 	return (error);
10249 }
10250 
10251 static int
10252 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10253     int flags, cred_t *cr)
10254 {
10255 	int error;
10256 	rnode4_t *rp;
10257 
10258 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10259 
10260 	flags |= B_WRITE;
10261 
10262 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10263 
10264 	rp = VTOR4(vp);
10265 
10266 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10267 	    error == EACCES) &&
10268 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10269 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10270 			mutex_enter(&rp->r_statelock);
10271 			rp->r_flags |= R4OUTOFSPACE;
10272 			mutex_exit(&rp->r_statelock);
10273 		}
10274 		flags |= B_ERROR;
10275 		pvn_write_done(pp, flags);
10276 		/*
10277 		 * If this was not an async thread, then try again to
10278 		 * write out the pages, but this time, also destroy
10279 		 * them whether or not the write is successful.  This
10280 		 * will prevent memory from filling up with these
10281 		 * pages and destroying them is the only alternative
10282 		 * if they can't be written out.
10283 		 *
10284 		 * Don't do this if this is an async thread because
10285 		 * when the pages are unlocked in pvn_write_done,
10286 		 * some other thread could have come along, locked
10287 		 * them, and queued for an async thread.  It would be
10288 		 * possible for all of the async threads to be tied
10289 		 * up waiting to lock the pages again and they would
10290 		 * all already be locked and waiting for an async
10291 		 * thread to handle them.  Deadlock.
10292 		 */
10293 		if (!(flags & B_ASYNC)) {
10294 			error = nfs4_putpage(vp, io_off, io_len,
10295 			    B_INVAL | B_FORCE, cr, NULL);
10296 		}
10297 	} else {
10298 		if (error)
10299 			flags |= B_ERROR;
10300 		else if (rp->r_flags & R4OUTOFSPACE) {
10301 			mutex_enter(&rp->r_statelock);
10302 			rp->r_flags &= ~R4OUTOFSPACE;
10303 			mutex_exit(&rp->r_statelock);
10304 		}
10305 		pvn_write_done(pp, flags);
10306 		if (freemem < desfree)
10307 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10308 			    NFS4_WRITE_NOWAIT);
10309 	}
10310 
10311 	return (error);
10312 }
10313 
10314 #ifdef DEBUG
10315 int nfs4_force_open_before_mmap = 0;
10316 #endif
10317 
10318 /* ARGSUSED */
10319 static int
10320 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10321     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10322     caller_context_t *ct)
10323 {
10324 	struct segvn_crargs vn_a;
10325 	int error = 0;
10326 	rnode4_t *rp = VTOR4(vp);
10327 	mntinfo4_t *mi = VTOMI4(vp);
10328 
10329 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10330 		return (EIO);
10331 
10332 	if (vp->v_flag & VNOMAP)
10333 		return (ENOSYS);
10334 
10335 	if (off < 0 || (off + len) < 0)
10336 		return (ENXIO);
10337 
10338 	if (vp->v_type != VREG)
10339 		return (ENODEV);
10340 
10341 	/*
10342 	 * If the file is delegated to the client don't do anything.
10343 	 * If the file is not delegated, then validate the data cache.
10344 	 */
10345 	mutex_enter(&rp->r_statev4_lock);
10346 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10347 		mutex_exit(&rp->r_statev4_lock);
10348 		error = nfs4_validate_caches(vp, cr);
10349 		if (error)
10350 			return (error);
10351 	} else {
10352 		mutex_exit(&rp->r_statev4_lock);
10353 	}
10354 
10355 	/*
10356 	 * Check to see if the vnode is currently marked as not cachable.
10357 	 * This means portions of the file are locked (through VOP_FRLOCK).
10358 	 * In this case the map request must be refused.  We use
10359 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10360 	 */
10361 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
10362 		return (EINTR);
10363 
10364 	if (vp->v_flag & VNOCACHE) {
10365 		error = EAGAIN;
10366 		goto done;
10367 	}
10368 
10369 	/*
10370 	 * Don't allow concurrent locks and mapping if mandatory locking is
10371 	 * enabled.
10372 	 */
10373 	if (flk_has_remote_locks(vp)) {
10374 		struct vattr va;
10375 		va.va_mask = AT_MODE;
10376 		error = nfs4getattr(vp, &va, cr);
10377 		if (error != 0)
10378 			goto done;
10379 		if (MANDLOCK(vp, va.va_mode)) {
10380 			error = EAGAIN;
10381 			goto done;
10382 		}
10383 	}
10384 
10385 	/*
10386 	 * It is possible that the rnode has a lost lock request that we
10387 	 * are still trying to recover, and that the request conflicts with
10388 	 * this map request.
10389 	 *
10390 	 * An alternative approach would be for nfs4_safemap() to consider
10391 	 * queued lock requests when deciding whether to set or clear
10392 	 * VNOCACHE.  This would require the frlock code path to call
10393 	 * nfs4_safemap() after enqueing a lost request.
10394 	 */
10395 	if (nfs4_map_lost_lock_conflict(vp)) {
10396 		error = EAGAIN;
10397 		goto done;
10398 	}
10399 
10400 	as_rangelock(as);
10401 	if (!(flags & MAP_FIXED)) {
10402 		map_addr(addrp, len, off, 1, flags);
10403 		if (*addrp == NULL) {
10404 			as_rangeunlock(as);
10405 			error = ENOMEM;
10406 			goto done;
10407 		}
10408 	} else {
10409 		/*
10410 		 * User specified address - blow away any previous mappings
10411 		 */
10412 		(void) as_unmap(as, *addrp, len);
10413 	}
10414 
10415 	if (vp->v_type == VREG) {
10416 		/*
10417 		 * We need to retrieve the open stream
10418 		 */
10419 		nfs4_open_stream_t	*osp = NULL;
10420 		nfs4_open_owner_t	*oop = NULL;
10421 
10422 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10423 		if (oop != NULL) {
10424 			/* returns with 'os_sync_lock' held */
10425 			osp = find_open_stream(oop, rp);
10426 			open_owner_rele(oop);
10427 		}
10428 		if (osp == NULL) {
10429 #ifdef DEBUG
10430 			if (nfs4_force_open_before_mmap) {
10431 				error = EIO;
10432 				goto done;
10433 			}
10434 #endif
10435 			/* returns with 'os_sync_lock' held */
10436 			error = open_and_get_osp(vp, cr, &osp);
10437 			if (osp == NULL) {
10438 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10439 				    "nfs4_map: we tried to OPEN the file "
10440 				    "but again no osp, so fail with EIO"));
10441 				goto done;
10442 			}
10443 		}
10444 
10445 		if (osp->os_failed_reopen) {
10446 			mutex_exit(&osp->os_sync_lock);
10447 			open_stream_rele(osp, rp);
10448 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10449 			    "nfs4_map: os_failed_reopen set on "
10450 			    "osp %p, cr %p, rp %s", (void *)osp,
10451 			    (void *)cr, rnode4info(rp)));
10452 			error = EIO;
10453 			goto done;
10454 		}
10455 		mutex_exit(&osp->os_sync_lock);
10456 		open_stream_rele(osp, rp);
10457 	}
10458 
10459 	vn_a.vp = vp;
10460 	vn_a.offset = off;
10461 	vn_a.type = (flags & MAP_TYPE);
10462 	vn_a.prot = (uchar_t)prot;
10463 	vn_a.maxprot = (uchar_t)maxprot;
10464 	vn_a.flags = (flags & ~MAP_TYPE);
10465 	vn_a.cred = cr;
10466 	vn_a.amp = NULL;
10467 	vn_a.szc = 0;
10468 	vn_a.lgrp_mem_policy_flags = 0;
10469 
10470 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10471 	as_rangeunlock(as);
10472 
10473 done:
10474 	nfs_rw_exit(&rp->r_lkserlock);
10475 	return (error);
10476 }
10477 
10478 /*
10479  * We're most likely dealing with a kernel module that likes to READ
10480  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10481  * officially OPEN the file to create the necessary client state
10482  * for bookkeeping of os_mmap_read/write counts.
10483  *
10484  * Since VOP_MAP only passes in a pointer to the vnode rather than
10485  * a double pointer, we can't handle the case where nfs4open_otw()
10486  * returns a different vnode than the one passed into VOP_MAP (since
10487  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10488  * we return NULL and let nfs4_map() fail.  Note: the only case where
10489  * this should happen is if the file got removed and replaced with the
10490  * same name on the server (in addition to the fact that we're trying
10491  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10492  */
10493 static int
10494 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10495 {
10496 	rnode4_t		*rp, *drp;
10497 	vnode_t			*dvp, *open_vp;
10498 	char			file_name[MAXNAMELEN];
10499 	int			just_created;
10500 	nfs4_open_stream_t	*osp;
10501 	nfs4_open_owner_t	*oop;
10502 	int			error;
10503 
10504 	*ospp = NULL;
10505 	open_vp = map_vp;
10506 
10507 	rp = VTOR4(open_vp);
10508 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10509 		return (error);
10510 	drp = VTOR4(dvp);
10511 
10512 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10513 		VN_RELE(dvp);
10514 		return (EINTR);
10515 	}
10516 
10517 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10518 		nfs_rw_exit(&drp->r_rwlock);
10519 		VN_RELE(dvp);
10520 		return (error);
10521 	}
10522 
10523 	mutex_enter(&rp->r_statev4_lock);
10524 	if (rp->created_v4) {
10525 		rp->created_v4 = 0;
10526 		mutex_exit(&rp->r_statev4_lock);
10527 
10528 		dnlc_update(dvp, file_name, open_vp);
10529 		/* This is needed so we don't bump the open ref count */
10530 		just_created = 1;
10531 	} else {
10532 		mutex_exit(&rp->r_statev4_lock);
10533 		just_created = 0;
10534 	}
10535 
10536 	VN_HOLD(map_vp);
10537 
10538 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10539 	    just_created);
10540 	if (error) {
10541 		nfs_rw_exit(&drp->r_rwlock);
10542 		VN_RELE(dvp);
10543 		VN_RELE(map_vp);
10544 		return (error);
10545 	}
10546 
10547 	nfs_rw_exit(&drp->r_rwlock);
10548 	VN_RELE(dvp);
10549 
10550 	/*
10551 	 * If nfs4open_otw() returned a different vnode then "undo"
10552 	 * the open and return failure to the caller.
10553 	 */
10554 	if (!VN_CMP(open_vp, map_vp)) {
10555 		nfs4_error_t e;
10556 
10557 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10558 		    "open returned a different vnode"));
10559 		/*
10560 		 * If there's an error, ignore it,
10561 		 * and let VOP_INACTIVE handle it.
10562 		 */
10563 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10564 		    CLOSE_NORM, 0, 0, 0);
10565 		VN_RELE(map_vp);
10566 		return (EIO);
10567 	}
10568 
10569 	VN_RELE(map_vp);
10570 
10571 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10572 	if (!oop) {
10573 		nfs4_error_t e;
10574 
10575 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10576 		    "no open owner"));
10577 		/*
10578 		 * If there's an error, ignore it,
10579 		 * and let VOP_INACTIVE handle it.
10580 		 */
10581 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10582 		    CLOSE_NORM, 0, 0, 0);
10583 		return (EIO);
10584 	}
10585 	osp = find_open_stream(oop, rp);
10586 	open_owner_rele(oop);
10587 	*ospp = osp;
10588 	return (0);
10589 }
10590 
10591 /*
10592  * Please be aware that when this function is called, the address space write
10593  * a_lock is held.  Do not put over the wire calls in this function.
10594  */
10595 /* ARGSUSED */
10596 static int
10597 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10598     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10599     caller_context_t *ct)
10600 {
10601 	rnode4_t		*rp;
10602 	int			error = 0;
10603 	mntinfo4_t		*mi;
10604 
10605 	mi = VTOMI4(vp);
10606 	rp = VTOR4(vp);
10607 
10608 	if (nfs_zone() != mi->mi_zone)
10609 		return (EIO);
10610 	if (vp->v_flag & VNOMAP)
10611 		return (ENOSYS);
10612 
10613 	/*
10614 	 * Need to hold rwlock while incrementing the mapcnt so that
10615 	 * mmap'ing can be serialized with writes so that the caching
10616 	 * can be handled correctly.
10617 	 *
10618 	 * Don't need to update the open stream first, since this
10619 	 * mmap can't add any additional share access that isn't
10620 	 * already contained in the open stream (for the case where we
10621 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10622 	 * take into account os_mmap_read[write] counts).
10623 	 */
10624 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR(vp)))
10625 		return (EINTR);
10626 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10627 	nfs_rw_exit(&rp->r_rwlock);
10628 
10629 	if (vp->v_type == VREG) {
10630 		/*
10631 		 * We need to retrieve the open stream and update the counts.
10632 		 * If there is no open stream here, something is wrong.
10633 		 */
10634 		nfs4_open_stream_t	*osp = NULL;
10635 		nfs4_open_owner_t	*oop = NULL;
10636 
10637 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10638 		if (oop != NULL) {
10639 			/* returns with 'os_sync_lock' held */
10640 			osp = find_open_stream(oop, rp);
10641 			open_owner_rele(oop);
10642 		}
10643 		if (osp == NULL) {
10644 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10645 			    "nfs4_addmap: we should have an osp"
10646 			    "but we don't, so fail with EIO"));
10647 			error = EIO;
10648 			goto out;
10649 		}
10650 
10651 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10652 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10653 
10654 		/*
10655 		 * Update the map count in the open stream.
10656 		 * This is necessary in the case where we
10657 		 * open/mmap/close/, then the server reboots, and we
10658 		 * attempt to reopen.  If the mmap doesn't add share
10659 		 * access then we send an invalid reopen with
10660 		 * access = NONE.
10661 		 *
10662 		 * We need to specifically check each PROT_* so a mmap
10663 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10664 		 * read and write access.  A simple comparison of prot
10665 		 * to ~PROT_WRITE to determine read access is insufficient
10666 		 * since prot can be |= with PROT_USER, etc.
10667 		 */
10668 
10669 		/*
10670 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10671 		 */
10672 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10673 			osp->os_mmap_write += btopr(len);
10674 		if (maxprot & PROT_READ)
10675 			osp->os_mmap_read += btopr(len);
10676 		if (maxprot & PROT_EXEC)
10677 			osp->os_mmap_read += btopr(len);
10678 		/*
10679 		 * Ensure that os_mmap_read gets incremented, even if
10680 		 * maxprot were to look like PROT_NONE.
10681 		 */
10682 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10683 		    !(maxprot & PROT_EXEC))
10684 			osp->os_mmap_read += btopr(len);
10685 		osp->os_mapcnt += btopr(len);
10686 		mutex_exit(&osp->os_sync_lock);
10687 		open_stream_rele(osp, rp);
10688 	}
10689 
10690 out:
10691 	/*
10692 	 * If we got an error, then undo our
10693 	 * incrementing of 'r_mapcnt'.
10694 	 */
10695 
10696 	if (error) {
10697 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10698 		ASSERT(rp->r_mapcnt >= 0);
10699 	}
10700 	return (error);
10701 }
10702 
10703 /* ARGSUSED */
10704 static int
10705 nfs4_cmp(vnode_t *vp1, vnode_t *vp2, caller_context_t *ct)
10706 {
10707 
10708 	return (VTOR4(vp1) == VTOR4(vp2));
10709 }
10710 
10711 /* ARGSUSED */
10712 static int
10713 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10714     offset_t offset, struct flk_callback *flk_cbp, cred_t *cr,
10715     caller_context_t *ct)
10716 {
10717 	int rc;
10718 	u_offset_t start, end;
10719 	rnode4_t *rp;
10720 	int error = 0, intr = INTR4(vp);
10721 	nfs4_error_t e;
10722 
10723 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10724 		return (EIO);
10725 
10726 	/* check for valid cmd parameter */
10727 	if (cmd != F_GETLK && cmd != F_SETLK && cmd != F_SETLKW)
10728 		return (EINVAL);
10729 
10730 	/* Verify l_type. */
10731 	switch (bfp->l_type) {
10732 	case F_RDLCK:
10733 		if (cmd != F_GETLK && !(flag & FREAD))
10734 			return (EBADF);
10735 		break;
10736 	case F_WRLCK:
10737 		if (cmd != F_GETLK && !(flag & FWRITE))
10738 			return (EBADF);
10739 		break;
10740 	case F_UNLCK:
10741 		intr = 0;
10742 		break;
10743 
10744 	default:
10745 		return (EINVAL);
10746 	}
10747 
10748 	/* check the validity of the lock range */
10749 	if (rc = flk_convert_lock_data(vp, bfp, &start, &end, offset))
10750 		return (rc);
10751 	if (rc = flk_check_lock_data(start, end, MAXEND))
10752 		return (rc);
10753 
10754 	/*
10755 	 * If the filesystem is mounted using local locking, pass the
10756 	 * request off to the local locking code.
10757 	 */
10758 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10759 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10760 			/*
10761 			 * For complete safety, we should be holding
10762 			 * r_lkserlock.  However, we can't call
10763 			 * nfs4_safelock and then fs_frlock while
10764 			 * holding r_lkserlock, so just invoke
10765 			 * nfs4_safelock and expect that this will
10766 			 * catch enough of the cases.
10767 			 */
10768 			if (!nfs4_safelock(vp, bfp, cr))
10769 				return (EAGAIN);
10770 		}
10771 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
10772 	}
10773 
10774 	rp = VTOR4(vp);
10775 
10776 	/*
10777 	 * Check whether the given lock request can proceed, given the
10778 	 * current file mappings.
10779 	 */
10780 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr))
10781 		return (EINTR);
10782 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10783 		if (!nfs4_safelock(vp, bfp, cr)) {
10784 			rc = EAGAIN;
10785 			goto done;
10786 		}
10787 	}
10788 
10789 	/*
10790 	 * Flush the cache after waiting for async I/O to finish.  For new
10791 	 * locks, this is so that the process gets the latest bits from the
10792 	 * server.  For unlocks, this is so that other clients see the
10793 	 * latest bits once the file has been unlocked.  If currently dirty
10794 	 * pages can't be flushed, then don't allow a lock to be set.  But
10795 	 * allow unlocks to succeed, to avoid having orphan locks on the
10796 	 * server.
10797 	 */
10798 	if (cmd != F_GETLK) {
10799 		mutex_enter(&rp->r_statelock);
10800 		while (rp->r_count > 0) {
10801 			if (intr) {
10802 				klwp_t *lwp = ttolwp(curthread);
10803 
10804 				if (lwp != NULL)
10805 					lwp->lwp_nostop++;
10806 				if (cv_wait_sig(&rp->r_cv,
10807 				    &rp->r_statelock) == 0) {
10808 					if (lwp != NULL)
10809 						lwp->lwp_nostop--;
10810 					rc = EINTR;
10811 					break;
10812 				}
10813 				if (lwp != NULL)
10814 					lwp->lwp_nostop--;
10815 				} else
10816 					cv_wait(&rp->r_cv, &rp->r_statelock);
10817 		}
10818 		mutex_exit(&rp->r_statelock);
10819 		if (rc != 0)
10820 			goto done;
10821 		error = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr, ct);
10822 		if (error) {
10823 			if (error == ENOSPC || error == EDQUOT) {
10824 				mutex_enter(&rp->r_statelock);
10825 				if (!rp->r_error)
10826 					rp->r_error = error;
10827 				mutex_exit(&rp->r_statelock);
10828 			}
10829 			if (bfp->l_type != F_UNLCK) {
10830 				rc = ENOLCK;
10831 				goto done;
10832 			}
10833 		}
10834 	}
10835 
10836 	/*
10837 	 * Call the lock manager to do the real work of contacting
10838 	 * the server and obtaining the lock.
10839 	 */
10840 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, flag, offset,
10841 	    cr, &e, NULL, NULL);
10842 	rc = e.error;
10843 
10844 	if (rc == 0)
10845 		nfs4_lockcompletion(vp, cmd);
10846 
10847 done:
10848 	nfs_rw_exit(&rp->r_lkserlock);
10849 
10850 	return (rc);
10851 }
10852 
10853 /*
10854  * Free storage space associated with the specified vnode.  The portion
10855  * to be freed is specified by bfp->l_start and bfp->l_len (already
10856  * normalized to a "whence" of 0).
10857  *
10858  * This is an experimental facility whose continued existence is not
10859  * guaranteed.  Currently, we only support the special case
10860  * of l_len == 0, meaning free to end of file.
10861  */
10862 /* ARGSUSED */
10863 static int
10864 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10865     offset_t offset, cred_t *cr, caller_context_t *ct)
10866 {
10867 	int error;
10868 
10869 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10870 		return (EIO);
10871 	ASSERT(vp->v_type == VREG);
10872 	if (cmd != F_FREESP)
10873 		return (EINVAL);
10874 
10875 	error = convoff(vp, bfp, 0, offset);
10876 	if (!error) {
10877 		ASSERT(bfp->l_start >= 0);
10878 		if (bfp->l_len == 0) {
10879 			struct vattr va;
10880 
10881 			va.va_mask = AT_SIZE;
10882 			va.va_size = bfp->l_start;
10883 			error = nfs4setattr(vp, &va, 0, cr, NULL);
10884 		} else
10885 			error = EINVAL;
10886 	}
10887 
10888 	return (error);
10889 }
10890 
10891 /* ARGSUSED */
10892 int
10893 nfs4_realvp(vnode_t *vp, vnode_t **vpp, caller_context_t *ct)
10894 {
10895 	rnode4_t *rp;
10896 	rp = VTOR4(vp);
10897 
10898 	if (vp->v_type == VREG && IS_SHADOW(vp, rp)) {
10899 		vp = RTOV4(rp);
10900 	}
10901 	*vpp = vp;
10902 	return (0);
10903 }
10904 
10905 /*
10906  * Setup and add an address space callback to do the work of the delmap call.
10907  * The callback will (and must be) deleted in the actual callback function.
10908  *
10909  * This is done in order to take care of the problem that we have with holding
10910  * the address space's a_lock for a long period of time (e.g. if the NFS server
10911  * is down).  Callbacks will be executed in the address space code while the
10912  * a_lock is not held.  Holding the address space's a_lock causes things such
10913  * as ps and fork to hang because they are trying to acquire this lock as well.
10914  */
10915 /* ARGSUSED */
10916 static int
10917 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10918     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
10919     caller_context_t *ct)
10920 {
10921 	int			caller_found;
10922 	int			error;
10923 	rnode4_t		*rp;
10924 	nfs4_delmap_args_t	*dmapp;
10925 	nfs4_delmapcall_t	*delmap_call;
10926 
10927 	if (vp->v_flag & VNOMAP)
10928 		return (ENOSYS);
10929 
10930 	/*
10931 	 * A process may not change zones if it has NFS pages mmap'ed
10932 	 * in, so we can't legitimately get here from the wrong zone.
10933 	 */
10934 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10935 
10936 	rp = VTOR4(vp);
10937 
10938 	/*
10939 	 * The way that the address space of this process deletes its mapping
10940 	 * of this file is via the following call chains:
10941 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10942 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10943 	 *
10944 	 * With the use of address space callbacks we are allowed to drop the
10945 	 * address space lock, a_lock, while executing the NFS operations that
10946 	 * need to go over the wire.  Returning EAGAIN to the caller of this
10947 	 * function is what drives the execution of the callback that we add
10948 	 * below.  The callback will be executed by the address space code
10949 	 * after dropping the a_lock.  When the callback is finished, since
10950 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
10951 	 * is called again on the same segment to finish the rest of the work
10952 	 * that needs to happen during unmapping.
10953 	 *
10954 	 * This action of calling back into the segment driver causes
10955 	 * nfs4_delmap() to get called again, but since the callback was
10956 	 * already executed at this point, it already did the work and there
10957 	 * is nothing left for us to do.
10958 	 *
10959 	 * To Summarize:
10960 	 * - The first time nfs4_delmap is called by the current thread is when
10961 	 * we add the caller associated with this delmap to the delmap caller
10962 	 * list, add the callback, and return EAGAIN.
10963 	 * - The second time in this call chain when nfs4_delmap is called we
10964 	 * will find this caller in the delmap caller list and realize there
10965 	 * is no more work to do thus removing this caller from the list and
10966 	 * returning the error that was set in the callback execution.
10967 	 */
10968 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
10969 	if (caller_found) {
10970 		/*
10971 		 * 'error' is from the actual delmap operations.  To avoid
10972 		 * hangs, we need to handle the return of EAGAIN differently
10973 		 * since this is what drives the callback execution.
10974 		 * In this case, we don't want to return EAGAIN and do the
10975 		 * callback execution because there are none to execute.
10976 		 */
10977 		if (error == EAGAIN)
10978 			return (0);
10979 		else
10980 			return (error);
10981 	}
10982 
10983 	/* current caller was not in the list */
10984 	delmap_call = nfs4_init_delmapcall();
10985 
10986 	mutex_enter(&rp->r_statelock);
10987 	list_insert_tail(&rp->r_indelmap, delmap_call);
10988 	mutex_exit(&rp->r_statelock);
10989 
10990 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
10991 
10992 	dmapp->vp = vp;
10993 	dmapp->off = off;
10994 	dmapp->addr = addr;
10995 	dmapp->len = len;
10996 	dmapp->prot = prot;
10997 	dmapp->maxprot = maxprot;
10998 	dmapp->flags = flags;
10999 	dmapp->cr = cr;
11000 	dmapp->caller = delmap_call;
11001 
11002 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
11003 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
11004 
11005 	return (error ? error : EAGAIN);
11006 }
11007 
11008 static nfs4_delmapcall_t *
11009 nfs4_init_delmapcall()
11010 {
11011 	nfs4_delmapcall_t	*delmap_call;
11012 
11013 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
11014 	delmap_call->call_id = curthread;
11015 	delmap_call->error = 0;
11016 
11017 	return (delmap_call);
11018 }
11019 
11020 static void
11021 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11022 {
11023 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11024 }
11025 
11026 /*
11027  * Searches for the current delmap caller (based on curthread) in the list of
11028  * callers.  If it is found, we remove it and free the delmap caller.
11029  * Returns:
11030  *      0 if the caller wasn't found
11031  *      1 if the caller was found, removed and freed.  *errp will be set
11032  *	to what the result of the delmap was.
11033  */
11034 static int
11035 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11036 {
11037 	nfs4_delmapcall_t	*delmap_call;
11038 
11039 	/*
11040 	 * If the list doesn't exist yet, we create it and return
11041 	 * that the caller wasn't found.  No list = no callers.
11042 	 */
11043 	mutex_enter(&rp->r_statelock);
11044 	if (!(rp->r_flags & R4DELMAPLIST)) {
11045 		/* The list does not exist */
11046 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11047 		    offsetof(nfs4_delmapcall_t, call_node));
11048 		rp->r_flags |= R4DELMAPLIST;
11049 		mutex_exit(&rp->r_statelock);
11050 		return (0);
11051 	} else {
11052 		/* The list exists so search it */
11053 		for (delmap_call = list_head(&rp->r_indelmap);
11054 		    delmap_call != NULL;
11055 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11056 			if (delmap_call->call_id == curthread) {
11057 				/* current caller is in the list */
11058 				*errp = delmap_call->error;
11059 				list_remove(&rp->r_indelmap, delmap_call);
11060 				mutex_exit(&rp->r_statelock);
11061 				nfs4_free_delmapcall(delmap_call);
11062 				return (1);
11063 			}
11064 		}
11065 	}
11066 	mutex_exit(&rp->r_statelock);
11067 	return (0);
11068 }
11069 
11070 /*
11071  * Remove some pages from an mmap'd vnode.  Just update the
11072  * count of pages.  If doing close-to-open, then flush and
11073  * commit all of the pages associated with this file.
11074  * Otherwise, start an asynchronous page flush to write out
11075  * any dirty pages.  This will also associate a credential
11076  * with the rnode which can be used to write the pages.
11077  */
11078 /* ARGSUSED */
11079 static void
11080 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11081 {
11082 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11083 	rnode4_t		*rp;
11084 	mntinfo4_t		*mi;
11085 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11086 
11087 	rp = VTOR4(dmapp->vp);
11088 	mi = VTOMI4(dmapp->vp);
11089 
11090 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11091 	ASSERT(rp->r_mapcnt >= 0);
11092 
11093 	/*
11094 	 * Initiate a page flush and potential commit if there are
11095 	 * pages, the file system was not mounted readonly, the segment
11096 	 * was mapped shared, and the pages themselves were writeable.
11097 	 */
11098 	if (nfs4_has_pages(dmapp->vp) &&
11099 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11100 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11101 		mutex_enter(&rp->r_statelock);
11102 		rp->r_flags |= R4DIRTY;
11103 		mutex_exit(&rp->r_statelock);
11104 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11105 		    dmapp->len, dmapp->cr);
11106 		if (!e.error) {
11107 			mutex_enter(&rp->r_statelock);
11108 			e.error = rp->r_error;
11109 			rp->r_error = 0;
11110 			mutex_exit(&rp->r_statelock);
11111 		}
11112 	} else
11113 		e.error = 0;
11114 
11115 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11116 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11117 		    B_INVAL, dmapp->cr, NULL);
11118 
11119 	if (e.error) {
11120 		e.stat = puterrno4(e.error);
11121 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11122 		    OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11123 		dmapp->caller->error = e.error;
11124 	}
11125 
11126 	/* Check to see if we need to close the file */
11127 
11128 	if (dmapp->vp->v_type == VREG) {
11129 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11130 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11131 
11132 		if (e.error != 0 || e.stat != NFS4_OK) {
11133 			/*
11134 			 * Since it is possible that e.error == 0 and
11135 			 * e.stat != NFS4_OK (and vice versa),
11136 			 * we do the proper checking in order to get both
11137 			 * e.error and e.stat reporting the correct info.
11138 			 */
11139 			if (e.stat == NFS4_OK)
11140 				e.stat = puterrno4(e.error);
11141 			if (e.error == 0)
11142 				e.error = geterrno4(e.stat);
11143 
11144 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11145 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11146 			dmapp->caller->error = e.error;
11147 		}
11148 	}
11149 
11150 	(void) as_delete_callback(as, arg);
11151 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11152 }
11153 
11154 
11155 static uint_t
11156 fattr4_maxfilesize_to_bits(uint64_t ll)
11157 {
11158 	uint_t l = 1;
11159 
11160 	if (ll == 0) {
11161 		return (0);
11162 	}
11163 
11164 	if (ll & 0xffffffff00000000) {
11165 		l += 32; ll >>= 32;
11166 	}
11167 	if (ll & 0xffff0000) {
11168 		l += 16; ll >>= 16;
11169 	}
11170 	if (ll & 0xff00) {
11171 		l += 8; ll >>= 8;
11172 	}
11173 	if (ll & 0xf0) {
11174 		l += 4; ll >>= 4;
11175 	}
11176 	if (ll & 0xc) {
11177 		l += 2; ll >>= 2;
11178 	}
11179 	if (ll & 0x2) {
11180 		l += 1;
11181 	}
11182 	return (l);
11183 }
11184 
11185 /* ARGSUSED */
11186 int
11187 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
11188 	caller_context_t *ct)
11189 {
11190 	int error;
11191 	hrtime_t t;
11192 	rnode4_t *rp;
11193 	nfs4_ga_res_t gar;
11194 	nfs4_ga_ext_res_t ger;
11195 
11196 	gar.n4g_ext_res = &ger;
11197 
11198 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11199 		return (EIO);
11200 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11201 		*valp = MAXPATHLEN;
11202 		return (0);
11203 	}
11204 	if (cmd == _PC_ACL_ENABLED) {
11205 		*valp = _ACL_ACE_ENABLED;
11206 		return (0);
11207 	}
11208 
11209 	rp = VTOR4(vp);
11210 	if (cmd == _PC_XATTR_EXISTS) {
11211 		/*
11212 		 * Eventually should attempt small client readdir before
11213 		 * going otw with GETATTR(FATTR4_NAMED_ATTR).  For now
11214 		 * just drive the OTW getattr.  This is required because
11215 		 * _PC_XATTR_EXISTS can only return true if attributes
11216 		 * exist -- simply checking for existence of the attrdir
11217 		 * is not sufficient.
11218 		 *
11219 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11220 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11221 		 * and we don't have any way to update the "base" object's
11222 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11223 		 * could help out.
11224 		 */
11225 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11226 		    rp->r_xattr_dir == NULL) {
11227 			*valp = rp->r_pathconf.pc4_xattr_exists;
11228 			return (0);
11229 		}
11230 	} else {  /* OLD CODE */
11231 		if (ATTRCACHE4_VALID(vp)) {
11232 			mutex_enter(&rp->r_statelock);
11233 			if (rp->r_pathconf.pc4_cache_valid) {
11234 				error = 0;
11235 				switch (cmd) {
11236 				case _PC_FILESIZEBITS:
11237 					*valp =
11238 					    rp->r_pathconf.pc4_filesizebits;
11239 					break;
11240 				case _PC_LINK_MAX:
11241 					*valp =
11242 					    rp->r_pathconf.pc4_link_max;
11243 					break;
11244 				case _PC_NAME_MAX:
11245 					*valp =
11246 					    rp->r_pathconf.pc4_name_max;
11247 					break;
11248 				case _PC_CHOWN_RESTRICTED:
11249 					*valp =
11250 					    rp->r_pathconf.pc4_chown_restricted;
11251 					break;
11252 				case _PC_NO_TRUNC:
11253 					*valp =
11254 					    rp->r_pathconf.pc4_no_trunc;
11255 					break;
11256 				default:
11257 					error = EINVAL;
11258 					break;
11259 				}
11260 				mutex_exit(&rp->r_statelock);
11261 #ifdef DEBUG
11262 				nfs4_pathconf_cache_hits++;
11263 #endif
11264 				return (error);
11265 			}
11266 			mutex_exit(&rp->r_statelock);
11267 		}
11268 	}
11269 #ifdef DEBUG
11270 	nfs4_pathconf_cache_misses++;
11271 #endif
11272 
11273 	t = gethrtime();
11274 
11275 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11276 
11277 	if (error) {
11278 		mutex_enter(&rp->r_statelock);
11279 		rp->r_pathconf.pc4_cache_valid = FALSE;
11280 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11281 		mutex_exit(&rp->r_statelock);
11282 		return (error);
11283 	}
11284 
11285 	/* interpret the max filesize */
11286 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11287 	    fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11288 
11289 	/* Store the attributes we just received */
11290 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11291 
11292 	switch (cmd) {
11293 	case _PC_FILESIZEBITS:
11294 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11295 		break;
11296 	case _PC_LINK_MAX:
11297 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11298 		break;
11299 	case _PC_NAME_MAX:
11300 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11301 		break;
11302 	case _PC_CHOWN_RESTRICTED:
11303 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11304 		break;
11305 	case _PC_NO_TRUNC:
11306 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11307 		break;
11308 	case _PC_XATTR_EXISTS:
11309 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists;
11310 		break;
11311 	default:
11312 		return (EINVAL);
11313 	}
11314 
11315 	return (0);
11316 }
11317 
11318 /*
11319  * Called by async thread to do synchronous pageio. Do the i/o, wait
11320  * for it to complete, and cleanup the page list when done.
11321  */
11322 static int
11323 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11324     int flags, cred_t *cr)
11325 {
11326 	int error;
11327 
11328 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11329 
11330 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11331 	if (flags & B_READ)
11332 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11333 	else
11334 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11335 	return (error);
11336 }
11337 
11338 /* ARGSUSED */
11339 static int
11340 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11341 	int flags, cred_t *cr, caller_context_t *ct)
11342 {
11343 	int error;
11344 	rnode4_t *rp;
11345 
11346 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11347 		return (EIO);
11348 
11349 	if (pp == NULL)
11350 		return (EINVAL);
11351 
11352 	rp = VTOR4(vp);
11353 	mutex_enter(&rp->r_statelock);
11354 	rp->r_count++;
11355 	mutex_exit(&rp->r_statelock);
11356 
11357 	if (flags & B_ASYNC) {
11358 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11359 		    nfs4_sync_pageio);
11360 	} else
11361 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11362 	mutex_enter(&rp->r_statelock);
11363 	rp->r_count--;
11364 	cv_broadcast(&rp->r_cv);
11365 	mutex_exit(&rp->r_statelock);
11366 	return (error);
11367 }
11368 
11369 /* ARGSUSED */
11370 static void
11371 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr,
11372 	caller_context_t *ct)
11373 {
11374 	int error;
11375 	rnode4_t *rp;
11376 	page_t *plist;
11377 	page_t *pptr;
11378 	offset3 offset;
11379 	count3 len;
11380 	k_sigset_t smask;
11381 
11382 	/*
11383 	 * We should get called with fl equal to either B_FREE or
11384 	 * B_INVAL.  Any other value is illegal.
11385 	 *
11386 	 * The page that we are either supposed to free or destroy
11387 	 * should be exclusive locked and its io lock should not
11388 	 * be held.
11389 	 */
11390 	ASSERT(fl == B_FREE || fl == B_INVAL);
11391 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11392 
11393 	rp = VTOR4(vp);
11394 
11395 	/*
11396 	 * If the page doesn't need to be committed or we shouldn't
11397 	 * even bother attempting to commit it, then just make sure
11398 	 * that the p_fsdata byte is clear and then either free or
11399 	 * destroy the page as appropriate.
11400 	 */
11401 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11402 		pp->p_fsdata = C_NOCOMMIT;
11403 		if (fl == B_FREE)
11404 			page_free(pp, dn);
11405 		else
11406 			page_destroy(pp, dn);
11407 		return;
11408 	}
11409 
11410 	/*
11411 	 * If there is a page invalidation operation going on, then
11412 	 * if this is one of the pages being destroyed, then just
11413 	 * clear the p_fsdata byte and then either free or destroy
11414 	 * the page as appropriate.
11415 	 */
11416 	mutex_enter(&rp->r_statelock);
11417 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11418 		mutex_exit(&rp->r_statelock);
11419 		pp->p_fsdata = C_NOCOMMIT;
11420 		if (fl == B_FREE)
11421 			page_free(pp, dn);
11422 		else
11423 			page_destroy(pp, dn);
11424 		return;
11425 	}
11426 
11427 	/*
11428 	 * If we are freeing this page and someone else is already
11429 	 * waiting to do a commit, then just unlock the page and
11430 	 * return.  That other thread will take care of commiting
11431 	 * this page.  The page can be freed sometime after the
11432 	 * commit has finished.  Otherwise, if the page is marked
11433 	 * as delay commit, then we may be getting called from
11434 	 * pvn_write_done, one page at a time.   This could result
11435 	 * in one commit per page, so we end up doing lots of small
11436 	 * commits instead of fewer larger commits.  This is bad,
11437 	 * we want do as few commits as possible.
11438 	 */
11439 	if (fl == B_FREE) {
11440 		if (rp->r_flags & R4COMMITWAIT) {
11441 			page_unlock(pp);
11442 			mutex_exit(&rp->r_statelock);
11443 			return;
11444 		}
11445 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11446 			pp->p_fsdata = C_COMMIT;
11447 			page_unlock(pp);
11448 			mutex_exit(&rp->r_statelock);
11449 			return;
11450 		}
11451 	}
11452 
11453 	/*
11454 	 * Check to see if there is a signal which would prevent an
11455 	 * attempt to commit the pages from being successful.  If so,
11456 	 * then don't bother with all of the work to gather pages and
11457 	 * generate the unsuccessful RPC.  Just return from here and
11458 	 * let the page be committed at some later time.
11459 	 */
11460 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11461 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11462 		sigunintr(&smask);
11463 		page_unlock(pp);
11464 		mutex_exit(&rp->r_statelock);
11465 		return;
11466 	}
11467 	sigunintr(&smask);
11468 
11469 	/*
11470 	 * We are starting to need to commit pages, so let's try
11471 	 * to commit as many as possible at once to reduce the
11472 	 * overhead.
11473 	 *
11474 	 * Set the `commit inprogress' state bit.  We must
11475 	 * first wait until any current one finishes.  Then
11476 	 * we initialize the c_pages list with this page.
11477 	 */
11478 	while (rp->r_flags & R4COMMIT) {
11479 		rp->r_flags |= R4COMMITWAIT;
11480 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11481 		rp->r_flags &= ~R4COMMITWAIT;
11482 	}
11483 	rp->r_flags |= R4COMMIT;
11484 	mutex_exit(&rp->r_statelock);
11485 	ASSERT(rp->r_commit.c_pages == NULL);
11486 	rp->r_commit.c_pages = pp;
11487 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11488 	rp->r_commit.c_commlen = PAGESIZE;
11489 
11490 	/*
11491 	 * Gather together all other pages which can be committed.
11492 	 * They will all be chained off r_commit.c_pages.
11493 	 */
11494 	nfs4_get_commit(vp);
11495 
11496 	/*
11497 	 * Clear the `commit inprogress' status and disconnect
11498 	 * the list of pages to be committed from the rnode.
11499 	 * At this same time, we also save the starting offset
11500 	 * and length of data to be committed on the server.
11501 	 */
11502 	plist = rp->r_commit.c_pages;
11503 	rp->r_commit.c_pages = NULL;
11504 	offset = rp->r_commit.c_commbase;
11505 	len = rp->r_commit.c_commlen;
11506 	mutex_enter(&rp->r_statelock);
11507 	rp->r_flags &= ~R4COMMIT;
11508 	cv_broadcast(&rp->r_commit.c_cv);
11509 	mutex_exit(&rp->r_statelock);
11510 
11511 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11512 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11513 		nfs4_async_commit(vp, plist, offset, len,
11514 		    cr, do_nfs4_async_commit);
11515 		return;
11516 	}
11517 
11518 	/*
11519 	 * Actually generate the COMMIT op over the wire operation.
11520 	 */
11521 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11522 
11523 	/*
11524 	 * If we got an error during the commit, just unlock all
11525 	 * of the pages.  The pages will get retransmitted to the
11526 	 * server during a putpage operation.
11527 	 */
11528 	if (error) {
11529 		while (plist != NULL) {
11530 			pptr = plist;
11531 			page_sub(&plist, pptr);
11532 			page_unlock(pptr);
11533 		}
11534 		return;
11535 	}
11536 
11537 	/*
11538 	 * We've tried as hard as we can to commit the data to stable
11539 	 * storage on the server.  We just unlock the rest of the pages
11540 	 * and clear the commit required state.  They will be put
11541 	 * onto the tail of the cachelist if they are nolonger
11542 	 * mapped.
11543 	 */
11544 	while (plist != pp) {
11545 		pptr = plist;
11546 		page_sub(&plist, pptr);
11547 		pptr->p_fsdata = C_NOCOMMIT;
11548 		page_unlock(pptr);
11549 	}
11550 
11551 	/*
11552 	 * It is possible that nfs4_commit didn't return error but
11553 	 * some other thread has modified the page we are going
11554 	 * to free/destroy.
11555 	 *    In this case we need to rewrite the page. Do an explicit check
11556 	 * before attempting to free/destroy the page. If modified, needs to
11557 	 * be rewritten so unlock the page and return.
11558 	 */
11559 	if (hat_ismod(pp)) {
11560 		pp->p_fsdata = C_NOCOMMIT;
11561 		page_unlock(pp);
11562 		return;
11563 	}
11564 
11565 	/*
11566 	 * Now, as appropriate, either free or destroy the page
11567 	 * that we were called with.
11568 	 */
11569 	pp->p_fsdata = C_NOCOMMIT;
11570 	if (fl == B_FREE)
11571 		page_free(pp, dn);
11572 	else
11573 		page_destroy(pp, dn);
11574 }
11575 
11576 /*
11577  * Commit requires that the current fh be the file written to.
11578  * The compound op structure is:
11579  *      PUTFH(file), COMMIT
11580  */
11581 static int
11582 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11583 {
11584 	COMPOUND4args_clnt args;
11585 	COMPOUND4res_clnt res;
11586 	COMMIT4res *cm_res;
11587 	nfs_argop4 argop[2];
11588 	nfs_resop4 *resop;
11589 	int doqueue;
11590 	mntinfo4_t *mi;
11591 	rnode4_t *rp;
11592 	cred_t *cred_otw = NULL;
11593 	bool_t needrecov = FALSE;
11594 	nfs4_recov_state_t recov_state;
11595 	nfs4_open_stream_t *osp = NULL;
11596 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11597 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11598 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11599 
11600 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11601 
11602 	rp = VTOR4(vp);
11603 
11604 	mi = VTOMI4(vp);
11605 	recov_state.rs_flags = 0;
11606 	recov_state.rs_num_retry_despite_err = 0;
11607 get_commit_cred:
11608 	/*
11609 	 * Releases the osp, if a valid open stream is provided.
11610 	 * Puts a hold on the cred_otw and the new osp (if found).
11611 	 */
11612 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11613 	    &first_time, &last_time);
11614 	args.ctag = TAG_COMMIT;
11615 recov_retry:
11616 	/*
11617 	 * Commit ops: putfh file; commit
11618 	 */
11619 	args.array_len = 2;
11620 	args.array = argop;
11621 
11622 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11623 	    &recov_state, NULL);
11624 	if (e.error) {
11625 		crfree(cred_otw);
11626 		if (osp != NULL)
11627 			open_stream_rele(osp, rp);
11628 		return (e.error);
11629 	}
11630 
11631 	/* putfh directory */
11632 	argop[0].argop = OP_CPUTFH;
11633 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11634 
11635 	/* commit */
11636 	argop[1].argop = OP_COMMIT;
11637 	argop[1].nfs_argop4_u.opcommit.offset = offset;
11638 	argop[1].nfs_argop4_u.opcommit.count = count;
11639 
11640 	doqueue = 1;
11641 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
11642 
11643 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
11644 	if (!needrecov && e.error) {
11645 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
11646 		    needrecov);
11647 		crfree(cred_otw);
11648 		if (e.error == EACCES && last_time == FALSE)
11649 			goto get_commit_cred;
11650 		if (osp != NULL)
11651 			open_stream_rele(osp, rp);
11652 		return (e.error);
11653 	}
11654 
11655 	if (needrecov) {
11656 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
11657 		    NULL, OP_COMMIT, NULL) == FALSE) {
11658 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11659 			    &recov_state, needrecov);
11660 			if (!e.error)
11661 				(void) xdr_free(xdr_COMPOUND4res_clnt,
11662 				    (caddr_t)&res);
11663 			goto recov_retry;
11664 		}
11665 		if (e.error) {
11666 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11667 			    &recov_state, needrecov);
11668 			crfree(cred_otw);
11669 			if (osp != NULL)
11670 				open_stream_rele(osp, rp);
11671 			return (e.error);
11672 		}
11673 		/* fall through for res.status case */
11674 	}
11675 
11676 	if (res.status) {
11677 		e.error = geterrno4(res.status);
11678 		if (e.error == EACCES && last_time == FALSE) {
11679 			crfree(cred_otw);
11680 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11681 			    &recov_state, needrecov);
11682 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11683 			goto get_commit_cred;
11684 		}
11685 		/*
11686 		 * Can't do a nfs4_purge_stale_fh here because this
11687 		 * can cause a deadlock.  nfs4_commit can
11688 		 * be called from nfs4_dispose which can be called
11689 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
11690 		 * can call back to pvn_vplist_dirty.
11691 		 */
11692 		if (e.error == ESTALE) {
11693 			mutex_enter(&rp->r_statelock);
11694 			rp->r_flags |= R4STALE;
11695 			if (!rp->r_error)
11696 				rp->r_error = e.error;
11697 			mutex_exit(&rp->r_statelock);
11698 			PURGE_ATTRCACHE4(vp);
11699 		} else {
11700 			mutex_enter(&rp->r_statelock);
11701 			if (!rp->r_error)
11702 				rp->r_error = e.error;
11703 			mutex_exit(&rp->r_statelock);
11704 		}
11705 	} else {
11706 		ASSERT(rp->r_flags & R4HAVEVERF);
11707 		resop = &res.array[1];	/* commit res */
11708 		cm_res = &resop->nfs_resop4_u.opcommit;
11709 		mutex_enter(&rp->r_statelock);
11710 		if (cm_res->writeverf == rp->r_writeverf) {
11711 			mutex_exit(&rp->r_statelock);
11712 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11713 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11714 			    &recov_state, needrecov);
11715 			crfree(cred_otw);
11716 			if (osp != NULL)
11717 				open_stream_rele(osp, rp);
11718 			return (0);
11719 		}
11720 		nfs4_set_mod(vp);
11721 		rp->r_writeverf = cm_res->writeverf;
11722 		mutex_exit(&rp->r_statelock);
11723 		e.error = NFS_VERF_MISMATCH;
11724 	}
11725 
11726 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11727 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
11728 	crfree(cred_otw);
11729 	if (osp != NULL)
11730 		open_stream_rele(osp, rp);
11731 
11732 	return (e.error);
11733 }
11734 
11735 static void
11736 nfs4_set_mod(vnode_t *vp)
11737 {
11738 	page_t *pp;
11739 	kmutex_t *vphm;
11740 	rnode4_t *rp;
11741 
11742 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11743 
11744 	/* make sure we're looking at the master vnode, not a shadow */
11745 
11746 	rp = VTOR4(vp);
11747 	if (IS_SHADOW(vp, rp))
11748 		vp = RTOV4(rp);
11749 
11750 	vphm = page_vnode_mutex(vp);
11751 	mutex_enter(vphm);
11752 	/*
11753 	 * If there are no pages associated with this vnode, then
11754 	 * just return.
11755 	 */
11756 	if ((pp = vp->v_pages) == NULL) {
11757 		mutex_exit(vphm);
11758 		return;
11759 	}
11760 
11761 	do {
11762 		if (pp->p_fsdata != C_NOCOMMIT) {
11763 			hat_setmod(pp);
11764 			pp->p_fsdata = C_NOCOMMIT;
11765 		}
11766 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11767 	mutex_exit(vphm);
11768 }
11769 
11770 /*
11771  * This function is used to gather a page list of the pages which
11772  * can be committed on the server.
11773  *
11774  * The calling thread must have set R4COMMIT.  This bit is used to
11775  * serialize access to the commit structure in the rnode.  As long
11776  * as the thread has set R4COMMIT, then it can manipulate the commit
11777  * structure without requiring any other locks.
11778  *
11779  * When this function is called from nfs4_dispose() the page passed
11780  * into nfs4_dispose() will be SE_EXCL locked, and so this function
11781  * will skip it. This is not a problem since we initially add the
11782  * page to the r_commit page list.
11783  *
11784  */
11785 static void
11786 nfs4_get_commit(vnode_t *vp)
11787 {
11788 	rnode4_t *rp;
11789 	page_t *pp;
11790 	kmutex_t *vphm;
11791 
11792 	rp = VTOR4(vp);
11793 
11794 	ASSERT(rp->r_flags & R4COMMIT);
11795 
11796 	/* make sure we're looking at the master vnode, not a shadow */
11797 
11798 	if (IS_SHADOW(vp, rp))
11799 		vp = RTOV4(rp);
11800 
11801 	vphm = page_vnode_mutex(vp);
11802 	mutex_enter(vphm);
11803 
11804 	/*
11805 	 * If there are no pages associated with this vnode, then
11806 	 * just return.
11807 	 */
11808 	if ((pp = vp->v_pages) == NULL) {
11809 		mutex_exit(vphm);
11810 		return;
11811 	}
11812 
11813 	/*
11814 	 * Step through all of the pages associated with this vnode
11815 	 * looking for pages which need to be committed.
11816 	 */
11817 	do {
11818 		/*
11819 		 * First short-cut everything (without the page_lock)
11820 		 * and see if this page does not need to be committed
11821 		 * or is modified if so then we'll just skip it.
11822 		 */
11823 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
11824 			continue;
11825 
11826 		/*
11827 		 * Attempt to lock the page.  If we can't, then
11828 		 * someone else is messing with it or we have been
11829 		 * called from nfs4_dispose and this is the page that
11830 		 * nfs4_dispose was called with.. anyway just skip it.
11831 		 */
11832 		if (!page_trylock(pp, SE_EXCL))
11833 			continue;
11834 
11835 		/*
11836 		 * Lets check again now that we have the page lock.
11837 		 */
11838 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11839 			page_unlock(pp);
11840 			continue;
11841 		}
11842 
11843 		/* this had better not be a free page */
11844 		ASSERT(PP_ISFREE(pp) == 0);
11845 
11846 		/*
11847 		 * The page needs to be committed and we locked it.
11848 		 * Update the base and length parameters and add it
11849 		 * to r_pages.
11850 		 */
11851 		if (rp->r_commit.c_pages == NULL) {
11852 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11853 			rp->r_commit.c_commlen = PAGESIZE;
11854 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
11855 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
11856 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
11857 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11858 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
11859 		    <= pp->p_offset) {
11860 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11861 			    rp->r_commit.c_commbase + PAGESIZE;
11862 		}
11863 		page_add(&rp->r_commit.c_pages, pp);
11864 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11865 
11866 	mutex_exit(vphm);
11867 }
11868 
11869 /*
11870  * This routine is used to gather together a page list of the pages
11871  * which are to be committed on the server.  This routine must not
11872  * be called if the calling thread holds any locked pages.
11873  *
11874  * The calling thread must have set R4COMMIT.  This bit is used to
11875  * serialize access to the commit structure in the rnode.  As long
11876  * as the thread has set R4COMMIT, then it can manipulate the commit
11877  * structure without requiring any other locks.
11878  */
11879 static void
11880 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
11881 {
11882 
11883 	rnode4_t *rp;
11884 	page_t *pp;
11885 	u_offset_t end;
11886 	u_offset_t off;
11887 	ASSERT(len != 0);
11888 	rp = VTOR4(vp);
11889 	ASSERT(rp->r_flags & R4COMMIT);
11890 
11891 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11892 
11893 	/* make sure we're looking at the master vnode, not a shadow */
11894 
11895 	if (IS_SHADOW(vp, rp))
11896 		vp = RTOV4(rp);
11897 
11898 	/*
11899 	 * If there are no pages associated with this vnode, then
11900 	 * just return.
11901 	 */
11902 	if ((pp = vp->v_pages) == NULL)
11903 		return;
11904 	/*
11905 	 * Calculate the ending offset.
11906 	 */
11907 	end = soff + len;
11908 	for (off = soff; off < end; off += PAGESIZE) {
11909 		/*
11910 		 * Lookup each page by vp, offset.
11911 		 */
11912 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
11913 			continue;
11914 		/*
11915 		 * If this page does not need to be committed or is
11916 		 * modified, then just skip it.
11917 		 */
11918 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11919 			page_unlock(pp);
11920 			continue;
11921 		}
11922 
11923 		ASSERT(PP_ISFREE(pp) == 0);
11924 		/*
11925 		 * The page needs to be committed and we locked it.
11926 		 * Update the base and length parameters and add it
11927 		 * to r_pages.
11928 		 */
11929 		if (rp->r_commit.c_pages == NULL) {
11930 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11931 			rp->r_commit.c_commlen = PAGESIZE;
11932 		} else {
11933 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11934 			    rp->r_commit.c_commbase + PAGESIZE;
11935 		}
11936 		page_add(&rp->r_commit.c_pages, pp);
11937 	}
11938 }
11939 
11940 /*
11941  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
11942  * Flushes and commits data to the server.
11943  */
11944 static int
11945 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
11946 {
11947 	int error;
11948 	verifier4 write_verf;
11949 	rnode4_t *rp = VTOR4(vp);
11950 
11951 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11952 
11953 	/*
11954 	 * Flush the data portion of the file and then commit any
11955 	 * portions which need to be committed.  This may need to
11956 	 * be done twice if the server has changed state since
11957 	 * data was last written.  The data will need to be
11958 	 * rewritten to the server and then a new commit done.
11959 	 *
11960 	 * In fact, this may need to be done several times if the
11961 	 * server is having problems and crashing while we are
11962 	 * attempting to do this.
11963 	 */
11964 
11965 top:
11966 	/*
11967 	 * Do a flush based on the poff and plen arguments.  This
11968 	 * will synchronously write out any modified pages in the
11969 	 * range specified by (poff, plen). This starts all of the
11970 	 * i/o operations which will be waited for in the next
11971 	 * call to nfs4_putpage
11972 	 */
11973 
11974 	mutex_enter(&rp->r_statelock);
11975 	write_verf = rp->r_writeverf;
11976 	mutex_exit(&rp->r_statelock);
11977 
11978 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr, NULL);
11979 	if (error == EAGAIN)
11980 		error = 0;
11981 
11982 	/*
11983 	 * Do a flush based on the poff and plen arguments.  This
11984 	 * will synchronously write out any modified pages in the
11985 	 * range specified by (poff, plen) and wait until all of
11986 	 * the asynchronous i/o's in that range are done as well.
11987 	 */
11988 	if (!error)
11989 		error = nfs4_putpage(vp, poff, plen, 0, cr, NULL);
11990 
11991 	if (error)
11992 		return (error);
11993 
11994 	mutex_enter(&rp->r_statelock);
11995 	if (rp->r_writeverf != write_verf) {
11996 		mutex_exit(&rp->r_statelock);
11997 		goto top;
11998 	}
11999 	mutex_exit(&rp->r_statelock);
12000 
12001 	/*
12002 	 * Now commit any pages which might need to be committed.
12003 	 * If the error, NFS_VERF_MISMATCH, is returned, then
12004 	 * start over with the flush operation.
12005 	 */
12006 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
12007 
12008 	if (error == NFS_VERF_MISMATCH)
12009 		goto top;
12010 
12011 	return (error);
12012 }
12013 
12014 /*
12015  * nfs4_commit_vp()  will wait for other pending commits and
12016  * will either commit the whole file or a range, plen dictates
12017  * if we commit whole file. a value of zero indicates the whole
12018  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
12019  */
12020 static int
12021 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12022     cred_t *cr, int wait_on_writes)
12023 {
12024 	rnode4_t *rp;
12025 	page_t *plist;
12026 	offset3 offset;
12027 	count3 len;
12028 
12029 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12030 
12031 	rp = VTOR4(vp);
12032 
12033 	/*
12034 	 *  before we gather commitable pages make
12035 	 *  sure there are no outstanding async writes
12036 	 */
12037 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12038 		mutex_enter(&rp->r_statelock);
12039 		while (rp->r_count > 0) {
12040 			cv_wait(&rp->r_cv, &rp->r_statelock);
12041 		}
12042 		mutex_exit(&rp->r_statelock);
12043 	}
12044 
12045 	/*
12046 	 * Set the `commit inprogress' state bit.  We must
12047 	 * first wait until any current one finishes.
12048 	 */
12049 	mutex_enter(&rp->r_statelock);
12050 	while (rp->r_flags & R4COMMIT) {
12051 		rp->r_flags |= R4COMMITWAIT;
12052 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12053 		rp->r_flags &= ~R4COMMITWAIT;
12054 	}
12055 	rp->r_flags |= R4COMMIT;
12056 	mutex_exit(&rp->r_statelock);
12057 
12058 	/*
12059 	 * Gather all of the pages which need to be
12060 	 * committed.
12061 	 */
12062 	if (plen == 0)
12063 		nfs4_get_commit(vp);
12064 	else
12065 		nfs4_get_commit_range(vp, poff, plen);
12066 
12067 	/*
12068 	 * Clear the `commit inprogress' bit and disconnect the
12069 	 * page list which was gathered by nfs4_get_commit.
12070 	 */
12071 	plist = rp->r_commit.c_pages;
12072 	rp->r_commit.c_pages = NULL;
12073 	offset = rp->r_commit.c_commbase;
12074 	len = rp->r_commit.c_commlen;
12075 	mutex_enter(&rp->r_statelock);
12076 	rp->r_flags &= ~R4COMMIT;
12077 	cv_broadcast(&rp->r_commit.c_cv);
12078 	mutex_exit(&rp->r_statelock);
12079 
12080 	/*
12081 	 * If any pages need to be committed, commit them and
12082 	 * then unlock them so that they can be freed some
12083 	 * time later.
12084 	 */
12085 	if (plist == NULL)
12086 		return (0);
12087 
12088 	/*
12089 	 * No error occurred during the flush portion
12090 	 * of this operation, so now attempt to commit
12091 	 * the data to stable storage on the server.
12092 	 *
12093 	 * This will unlock all of the pages on the list.
12094 	 */
12095 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12096 }
12097 
12098 static int
12099 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12100     cred_t *cr)
12101 {
12102 	int error;
12103 	page_t *pp;
12104 
12105 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12106 
12107 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12108 
12109 	/*
12110 	 * If we got an error, then just unlock all of the pages
12111 	 * on the list.
12112 	 */
12113 	if (error) {
12114 		while (plist != NULL) {
12115 			pp = plist;
12116 			page_sub(&plist, pp);
12117 			page_unlock(pp);
12118 		}
12119 		return (error);
12120 	}
12121 	/*
12122 	 * We've tried as hard as we can to commit the data to stable
12123 	 * storage on the server.  We just unlock the pages and clear
12124 	 * the commit required state.  They will get freed later.
12125 	 */
12126 	while (plist != NULL) {
12127 		pp = plist;
12128 		page_sub(&plist, pp);
12129 		pp->p_fsdata = C_NOCOMMIT;
12130 		page_unlock(pp);
12131 	}
12132 
12133 	return (error);
12134 }
12135 
12136 static void
12137 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12138     cred_t *cr)
12139 {
12140 
12141 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12142 }
12143 
12144 /*ARGSUSED*/
12145 static int
12146 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12147 	caller_context_t *ct)
12148 {
12149 	int		error = 0;
12150 	mntinfo4_t	*mi;
12151 	vattr_t		va;
12152 	vsecattr_t	nfsace4_vsap;
12153 
12154 	mi = VTOMI4(vp);
12155 	if (nfs_zone() != mi->mi_zone)
12156 		return (EIO);
12157 	if (mi->mi_flags & MI4_ACL) {
12158 		/* if we have a delegation, return it */
12159 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12160 			(void) nfs4delegreturn(VTOR4(vp),
12161 			    NFS4_DR_REOPEN|NFS4_DR_PUSH);
12162 
12163 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12164 		    NFS4_ACL_SET);
12165 		if (error) /* EINVAL */
12166 			return (error);
12167 
12168 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12169 			/*
12170 			 * These are aclent_t type entries.
12171 			 */
12172 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12173 			    vp->v_type == VDIR, FALSE);
12174 			if (error)
12175 				return (error);
12176 		} else {
12177 			/*
12178 			 * These are ace_t type entries.
12179 			 */
12180 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12181 			    FALSE);
12182 			if (error)
12183 				return (error);
12184 		}
12185 		bzero(&va, sizeof (va));
12186 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12187 		vs_ace4_destroy(&nfsace4_vsap);
12188 		return (error);
12189 	}
12190 	return (ENOSYS);
12191 }
12192 
12193 /* ARGSUSED */
12194 int
12195 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12196 	caller_context_t *ct)
12197 {
12198 	int		error;
12199 	mntinfo4_t	*mi;
12200 	nfs4_ga_res_t	gar;
12201 	rnode4_t	*rp = VTOR4(vp);
12202 
12203 	mi = VTOMI4(vp);
12204 	if (nfs_zone() != mi->mi_zone)
12205 		return (EIO);
12206 
12207 	bzero(&gar, sizeof (gar));
12208 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12209 
12210 	/*
12211 	 * vsecattr->vsa_mask holds the original acl request mask.
12212 	 * This is needed when determining what to return.
12213 	 * (See: nfs4_create_getsecattr_return())
12214 	 */
12215 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12216 	if (error) /* EINVAL */
12217 		return (error);
12218 
12219 	if (mi->mi_flags & MI4_ACL) {
12220 		/*
12221 		 * Check if the data is cached and the cache is valid.  If it
12222 		 * is we don't go over the wire.
12223 		 */
12224 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12225 			mutex_enter(&rp->r_statelock);
12226 			if (rp->r_secattr != NULL) {
12227 				error = nfs4_create_getsecattr_return(
12228 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12229 				    rp->r_attr.va_gid,
12230 				    vp->v_type == VDIR);
12231 				if (!error) { /* error == 0 - Success! */
12232 					mutex_exit(&rp->r_statelock);
12233 					return (error);
12234 				}
12235 			}
12236 			mutex_exit(&rp->r_statelock);
12237 		}
12238 
12239 		/*
12240 		 * The getattr otw call will always get both the acl, in
12241 		 * the form of a list of nfsace4's, and the number of acl
12242 		 * entries; independent of the value of gar.n4g_vsa.vsa_mask.
12243 		 */
12244 		gar.n4g_va.va_mask = AT_ALL;
12245 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12246 		if (error) {
12247 			vs_ace4_destroy(&gar.n4g_vsa);
12248 			if (error == ENOTSUP || error == EOPNOTSUPP)
12249 				error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12250 			return (error);
12251 		}
12252 
12253 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12254 			/*
12255 			 * No error was returned, but according to the response
12256 			 * bitmap, neither was an acl.
12257 			 */
12258 			vs_ace4_destroy(&gar.n4g_vsa);
12259 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12260 			return (error);
12261 		}
12262 
12263 		/*
12264 		 * Update the cache with the ACL.
12265 		 */
12266 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12267 
12268 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12269 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12270 		    vp->v_type == VDIR);
12271 		vs_ace4_destroy(&gar.n4g_vsa);
12272 		if ((error) && (vsecattr->vsa_mask &
12273 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12274 		    (error != EACCES)) {
12275 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12276 		}
12277 		return (error);
12278 	}
12279 	error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12280 	return (error);
12281 }
12282 
12283 /*
12284  * The function returns:
12285  * 	- 0 (zero) if the passed in "acl_mask" is a valid request.
12286  * 	- EINVAL if the passed in "acl_mask" is an invalid request.
12287  *
12288  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12289  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12290  *
12291  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12292  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12293  * - We have a count field set without the corresponding acl field set. (e.g. -
12294  * VSA_ACECNT is set, but VSA_ACE is not)
12295  */
12296 static int
12297 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12298 {
12299 	/* Shortcut the masks that are always valid. */
12300 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12301 		return (0);
12302 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12303 		return (0);
12304 
12305 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12306 		/*
12307 		 * We can't have any VSA_ACL type stuff in the mask now.
12308 		 */
12309 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12310 		    VSA_DFACLCNT))
12311 			return (EINVAL);
12312 
12313 		if (op == NFS4_ACL_SET) {
12314 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12315 				return (EINVAL);
12316 		}
12317 	}
12318 
12319 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12320 		/*
12321 		 * We can't have any VSA_ACE type stuff in the mask now.
12322 		 */
12323 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12324 			return (EINVAL);
12325 
12326 		if (op == NFS4_ACL_SET) {
12327 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12328 				return (EINVAL);
12329 
12330 			if ((acl_mask & VSA_DFACLCNT) &&
12331 			    !(acl_mask & VSA_DFACL))
12332 				return (EINVAL);
12333 		}
12334 	}
12335 	return (0);
12336 }
12337 
12338 /*
12339  * The theory behind creating the correct getsecattr return is simply this:
12340  * "Don't return anything that the caller is not expecting to have to free."
12341  */
12342 static int
12343 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12344     uid_t uid, gid_t gid, int isdir)
12345 {
12346 	int error = 0;
12347 	/* Save the mask since the translators modify it. */
12348 	uint_t	orig_mask = vsap->vsa_mask;
12349 
12350 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12351 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid,
12352 		    FALSE, ((orig_mask & VSA_ACE) ? FALSE : TRUE));
12353 
12354 		if (error)
12355 			return (error);
12356 
12357 		/*
12358 		 * If the caller only asked for the ace count (VSA_ACECNT)
12359 		 * don't give them the full acl (VSA_ACE), free it.
12360 		 */
12361 		if (!orig_mask & VSA_ACE) {
12362 			if (vsap->vsa_aclentp != NULL) {
12363 				kmem_free(vsap->vsa_aclentp,
12364 				    vsap->vsa_aclcnt * sizeof (ace_t));
12365 				vsap->vsa_aclentp = NULL;
12366 			}
12367 		}
12368 		vsap->vsa_mask = orig_mask;
12369 
12370 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12371 	    VSA_DFACLCNT)) {
12372 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12373 		    isdir, FALSE,
12374 		    ((orig_mask & (VSA_ACL | VSA_DFACL)) ? FALSE : TRUE));
12375 
12376 		if (error)
12377 			return (error);
12378 
12379 		/*
12380 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12381 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12382 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12383 		 */
12384 		if (!orig_mask & VSA_ACL) {
12385 			if (vsap->vsa_aclentp != NULL) {
12386 				kmem_free(vsap->vsa_aclentp,
12387 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12388 				vsap->vsa_aclentp = NULL;
12389 			}
12390 		}
12391 
12392 		if (!orig_mask & VSA_DFACL) {
12393 			if (vsap->vsa_dfaclentp != NULL) {
12394 				kmem_free(vsap->vsa_dfaclentp,
12395 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12396 				vsap->vsa_dfaclentp = NULL;
12397 			}
12398 		}
12399 		vsap->vsa_mask = orig_mask;
12400 	}
12401 	return (0);
12402 }
12403 
12404 /* ARGSUSED */
12405 int
12406 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr,
12407     caller_context_t *ct)
12408 {
12409 	int error;
12410 
12411 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12412 		return (EIO);
12413 	/*
12414 	 * check for valid cmd parameter
12415 	 */
12416 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12417 		return (EINVAL);
12418 
12419 	/*
12420 	 * Check access permissions
12421 	 */
12422 	if ((cmd & F_SHARE) &&
12423 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12424 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12425 		return (EBADF);
12426 
12427 	/*
12428 	 * If the filesystem is mounted using local locking, pass the
12429 	 * request off to the local share code.
12430 	 */
12431 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12432 		return (fs_shrlock(vp, cmd, shr, flag, cr, ct));
12433 
12434 	switch (cmd) {
12435 	case F_SHARE:
12436 	case F_UNSHARE:
12437 		/*
12438 		 * This will be properly implemented later,
12439 		 * see RFE: 4823948 .
12440 		 */
12441 		error = EAGAIN;
12442 		break;
12443 
12444 	case F_HASREMOTELOCKS:
12445 		/*
12446 		 * NFS client can't store remote locks itself
12447 		 */
12448 		shr->s_access = 0;
12449 		error = 0;
12450 		break;
12451 
12452 	default:
12453 		error = EINVAL;
12454 		break;
12455 	}
12456 
12457 	return (error);
12458 }
12459 
12460 /*
12461  * Common code called by directory ops to update the attrcache
12462  */
12463 static int
12464 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12465     hrtime_t t, vnode_t *vp, cred_t *cr)
12466 {
12467 	int error = 0;
12468 
12469 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12470 
12471 	if (status != NFS4_OK) {
12472 		/* getattr not done or failed */
12473 		PURGE_ATTRCACHE4(vp);
12474 		return (error);
12475 	}
12476 
12477 	if (garp) {
12478 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12479 	} else {
12480 		PURGE_ATTRCACHE4(vp);
12481 	}
12482 	return (error);
12483 }
12484 
12485 /*
12486  * Update directory caches for directory modification ops (link, rename, etc.)
12487  * When dinfo is NULL, manage dircaches in the old way.
12488  */
12489 static void
12490 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12491     dirattr_info_t *dinfo)
12492 {
12493 	rnode4_t	*drp = VTOR4(dvp);
12494 
12495 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12496 
12497 	/* Purge rddir cache for dir since it changed */
12498 	if (drp->r_dir != NULL)
12499 		nfs4_purge_rddir_cache(dvp);
12500 
12501 	/*
12502 	 * If caller provided dinfo, then use it to manage dir caches.
12503 	 */
12504 	if (dinfo != NULL) {
12505 		if (vp != NULL) {
12506 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12507 			if (!VTOR4(vp)->created_v4) {
12508 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12509 				dnlc_update(dvp, nm, vp);
12510 			} else {
12511 				/*
12512 				 * XXX don't update if the created_v4 flag is
12513 				 * set
12514 				 */
12515 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12516 				NFS4_DEBUG(nfs4_client_state_debug,
12517 				    (CE_NOTE, "nfs4_update_dircaches: "
12518 				    "don't update dnlc: created_v4 flag"));
12519 			}
12520 		}
12521 
12522 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12523 		    dinfo->di_cred, FALSE, cinfo);
12524 
12525 		return;
12526 	}
12527 
12528 	/*
12529 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12530 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12531 	 * attrs, the dir's attrs must be purged.
12532 	 *
12533 	 * XXX this check and dnlc update/purge should really be atomic,
12534 	 * XXX but can't use rnode statelock because it'll deadlock in
12535 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12536 	 * XXX does occur.
12537 	 *
12538 	 * XXX We also may want to check that atomic is true in the
12539 	 * XXX change_info struct. If it is not, the change_info may
12540 	 * XXX reflect changes by more than one clients which means that
12541 	 * XXX our cache may not be valid.
12542 	 */
12543 	PURGE_ATTRCACHE4(dvp);
12544 	if (drp->r_change == cinfo->before) {
12545 		/* no changes took place in the directory prior to our link */
12546 		if (vp != NULL) {
12547 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12548 			if (!VTOR4(vp)->created_v4) {
12549 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12550 				dnlc_update(dvp, nm, vp);
12551 			} else {
12552 				/*
12553 				 * XXX dont' update if the created_v4 flag
12554 				 * is set
12555 				 */
12556 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12557 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12558 				    "nfs4_update_dircaches: don't"
12559 				    " update dnlc: created_v4 flag"));
12560 			}
12561 		}
12562 	} else {
12563 		/* Another client modified directory - purge its dnlc cache */
12564 		dnlc_purge_vp(dvp);
12565 	}
12566 }
12567 
12568 /*
12569  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12570  * file.
12571  *
12572  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12573  * file (ie: client recovery) and otherwise set to FALSE.
12574  *
12575  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12576  * initiated) calling functions.
12577  *
12578  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12579  * of resending a 'lost' open request.
12580  *
12581  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12582  * server that hands out BAD_SEQID on open confirm.
12583  *
12584  * Errors are returned via the nfs4_error_t parameter.
12585  */
12586 void
12587 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12588     bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12589     bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12590 {
12591 	COMPOUND4args_clnt args;
12592 	COMPOUND4res_clnt res;
12593 	nfs_argop4 argop[2];
12594 	nfs_resop4 *resop;
12595 	int doqueue = 1;
12596 	mntinfo4_t *mi;
12597 	OPEN_CONFIRM4args *open_confirm_args;
12598 	int needrecov;
12599 
12600 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12601 #if DEBUG
12602 	mutex_enter(&oop->oo_lock);
12603 	ASSERT(oop->oo_seqid_inuse);
12604 	mutex_exit(&oop->oo_lock);
12605 #endif
12606 
12607 recov_retry_confirm:
12608 	nfs4_error_zinit(ep);
12609 	*retry_open = FALSE;
12610 
12611 	if (resend)
12612 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12613 	else
12614 		args.ctag = TAG_OPEN_CONFIRM;
12615 
12616 	args.array_len = 2;
12617 	args.array = argop;
12618 
12619 	/* putfh target fh */
12620 	argop[0].argop = OP_CPUTFH;
12621 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12622 
12623 	argop[1].argop = OP_OPEN_CONFIRM;
12624 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12625 
12626 	(*seqid) += 1;
12627 	open_confirm_args->seqid = *seqid;
12628 	open_confirm_args->open_stateid = *stateid;
12629 
12630 	mi = VTOMI4(vp);
12631 
12632 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12633 
12634 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12635 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12636 	}
12637 
12638 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12639 	if (!needrecov && ep->error)
12640 		return;
12641 
12642 	if (needrecov) {
12643 		bool_t abort = FALSE;
12644 
12645 		if (reopening_file == FALSE) {
12646 			nfs4_bseqid_entry_t *bsep = NULL;
12647 
12648 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12649 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12650 				    vp, 0, args.ctag,
12651 				    open_confirm_args->seqid);
12652 
12653 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp,
12654 			    NULL, NULL, NULL, OP_OPEN_CONFIRM, bsep);
12655 			if (bsep) {
12656 				kmem_free(bsep, sizeof (*bsep));
12657 				if (num_bseqid_retryp &&
12658 				    --(*num_bseqid_retryp) == 0)
12659 					abort = TRUE;
12660 			}
12661 		}
12662 		if ((ep->error == ETIMEDOUT ||
12663 		    res.status == NFS4ERR_RESOURCE) &&
12664 		    abort == FALSE && resend == FALSE) {
12665 			if (!ep->error)
12666 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12667 				    (caddr_t)&res);
12668 
12669 			delay(SEC_TO_TICK(confirm_retry_sec));
12670 			goto recov_retry_confirm;
12671 		}
12672 		/* State may have changed so retry the entire OPEN op */
12673 		if (abort == FALSE)
12674 			*retry_open = TRUE;
12675 		else
12676 			*retry_open = FALSE;
12677 		if (!ep->error)
12678 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12679 		return;
12680 	}
12681 
12682 	if (res.status) {
12683 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12684 		return;
12685 	}
12686 
12687 	resop = &res.array[1];  /* open confirm res */
12688 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
12689 	    stateid, sizeof (*stateid));
12690 
12691 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12692 }
12693 
12694 /*
12695  * Return the credentials associated with a client state object.  The
12696  * caller is responsible for freeing the credentials.
12697  */
12698 
12699 static cred_t *
12700 state_to_cred(nfs4_open_stream_t *osp)
12701 {
12702 	cred_t *cr;
12703 
12704 	/*
12705 	 * It's ok to not lock the open stream and open owner to get
12706 	 * the oo_cred since this is only written once (upon creation)
12707 	 * and will not change.
12708 	 */
12709 	cr = osp->os_open_owner->oo_cred;
12710 	crhold(cr);
12711 
12712 	return (cr);
12713 }
12714 
12715 /*
12716  * nfs4_find_sysid
12717  *
12718  * Find the sysid for the knetconfig associated with the given mi.
12719  */
12720 static struct lm_sysid *
12721 nfs4_find_sysid(mntinfo4_t *mi)
12722 {
12723 	ASSERT(nfs_zone() == mi->mi_zone);
12724 
12725 	/*
12726 	 * Switch from RDMA knconf to original mount knconf
12727 	 */
12728 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
12729 	    mi->mi_curr_serv->sv_hostname, NULL));
12730 }
12731 
12732 #ifdef DEBUG
12733 /*
12734  * Return a string version of the call type for easy reading.
12735  */
12736 static char *
12737 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
12738 {
12739 	switch (ctype) {
12740 	case NFS4_LCK_CTYPE_NORM:
12741 		return ("NORMAL");
12742 	case NFS4_LCK_CTYPE_RECLAIM:
12743 		return ("RECLAIM");
12744 	case NFS4_LCK_CTYPE_RESEND:
12745 		return ("RESEND");
12746 	case NFS4_LCK_CTYPE_REINSTATE:
12747 		return ("REINSTATE");
12748 	default:
12749 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
12750 		    "type %d", ctype);
12751 		return ("");
12752 	}
12753 }
12754 #endif
12755 
12756 /*
12757  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
12758  * Unlock requests don't have an over-the-wire locktype, so we just return
12759  * something non-threatening.
12760  */
12761 
12762 static nfs_lock_type4
12763 flk_to_locktype(int cmd, int l_type)
12764 {
12765 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
12766 
12767 	switch (l_type) {
12768 	case F_UNLCK:
12769 		return (READ_LT);
12770 	case F_RDLCK:
12771 		if (cmd == F_SETLK)
12772 			return (READ_LT);
12773 		else
12774 			return (READW_LT);
12775 	case F_WRLCK:
12776 		if (cmd == F_SETLK)
12777 			return (WRITE_LT);
12778 		else
12779 			return (WRITEW_LT);
12780 	}
12781 	panic("flk_to_locktype");
12782 	/*NOTREACHED*/
12783 }
12784 
12785 /*
12786  * Do some preliminary checks for nfs4frlock.
12787  */
12788 static int
12789 nfs4frlock_validate_args(int cmd, flock64_t *flk, int flag, vnode_t *vp,
12790     u_offset_t offset)
12791 {
12792 	int error = 0;
12793 
12794 	/*
12795 	 * If we are setting a lock, check that the file is opened
12796 	 * with the correct mode.
12797 	 */
12798 	if (cmd == F_SETLK || cmd == F_SETLKW) {
12799 		if ((flk->l_type == F_RDLCK && (flag & FREAD) == 0) ||
12800 		    (flk->l_type == F_WRLCK && (flag & FWRITE) == 0)) {
12801 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12802 			    "nfs4frlock_validate_args: file was opened with "
12803 			    "incorrect mode"));
12804 			return (EBADF);
12805 		}
12806 	}
12807 
12808 	/* Convert the offset. It may need to be restored before returning. */
12809 	if (error = convoff(vp, flk, 0, offset)) {
12810 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12811 		    "nfs4frlock_validate_args: convoff  =>  error= %d\n",
12812 		    error));
12813 		return (error);
12814 	}
12815 
12816 	return (error);
12817 }
12818 
12819 /*
12820  * Set the flock64's lm_sysid for nfs4frlock.
12821  */
12822 static int
12823 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
12824 {
12825 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12826 
12827 	/* Find the lm_sysid */
12828 	*lspp = nfs4_find_sysid(VTOMI4(vp));
12829 
12830 	if (*lspp == NULL) {
12831 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12832 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
12833 		return (ENOLCK);
12834 	}
12835 
12836 	flk->l_sysid = lm_sysidt(*lspp);
12837 
12838 	return (0);
12839 }
12840 
12841 /*
12842  * Do the remaining preliminary setup for nfs4frlock.
12843  */
12844 static void
12845 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
12846     flock64_t *flk, short *whencep, vnode_t *vp, cred_t *search_cr,
12847     cred_t **cred_otw)
12848 {
12849 	/*
12850 	 * set tick_delay to the base delay time.
12851 	 * (NFS4_BASE_WAIT_TIME is in secs)
12852 	 */
12853 
12854 	*tick_delayp = drv_usectohz(NFS4_BASE_WAIT_TIME * 1000 * 1000);
12855 
12856 	/*
12857 	 * If lock is relative to EOF, we need the newest length of the
12858 	 * file. Therefore invalidate the ATTR_CACHE.
12859 	 */
12860 
12861 	*whencep = flk->l_whence;
12862 
12863 	if (*whencep == 2)		/* SEEK_END */
12864 		PURGE_ATTRCACHE4(vp);
12865 
12866 	recov_statep->rs_flags = 0;
12867 	recov_statep->rs_num_retry_despite_err = 0;
12868 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
12869 }
12870 
12871 /*
12872  * Initialize and allocate the data structures necessary for
12873  * the nfs4frlock call.
12874  * Allocates argsp's op array, frees up the saved_rqstpp if there is one.
12875  */
12876 static void
12877 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
12878     nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
12879     bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
12880     bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
12881 {
12882 	int		argoplist_size;
12883 	int		num_ops = 2;
12884 
12885 	*retry = FALSE;
12886 	*did_start_fop = FALSE;
12887 	*skip_get_err = FALSE;
12888 	lost_rqstp->lr_op = 0;
12889 	argoplist_size  = num_ops * sizeof (nfs_argop4);
12890 	/* fill array with zero */
12891 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
12892 
12893 	*argspp = argsp;
12894 	*respp = NULL;
12895 
12896 	argsp->array_len = num_ops;
12897 	argsp->array = *argopp;
12898 
12899 	/* initialize in case of error; will get real value down below */
12900 	argsp->ctag = TAG_NONE;
12901 
12902 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
12903 		*op_hintp = OH_LOCKU;
12904 	else
12905 		*op_hintp = OH_OTHER;
12906 }
12907 
12908 /*
12909  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
12910  * the proper nfs4_server_t for this instance of nfs4frlock.
12911  * Returns 0 (success) or an errno value.
12912  */
12913 static int
12914 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
12915     nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
12916     bool_t *did_start_fop, bool_t *startrecovp)
12917 {
12918 	int error = 0;
12919 	rnode4_t *rp;
12920 
12921 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12922 
12923 	if (ctype == NFS4_LCK_CTYPE_NORM) {
12924 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
12925 		    recov_statep, startrecovp);
12926 		if (error)
12927 			return (error);
12928 		*did_start_fop = TRUE;
12929 	} else {
12930 		*did_start_fop = FALSE;
12931 		*startrecovp = FALSE;
12932 	}
12933 
12934 	if (!error) {
12935 		rp = VTOR4(vp);
12936 
12937 		/* If the file failed recovery, just quit. */
12938 		mutex_enter(&rp->r_statelock);
12939 		if (rp->r_flags & R4RECOVERR) {
12940 			error = EIO;
12941 		}
12942 		mutex_exit(&rp->r_statelock);
12943 	}
12944 
12945 	return (error);
12946 }
12947 
12948 /*
12949  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
12950  * resend nfs4frlock call is initiated by the recovery framework.
12951  * Acquires the lop and oop seqid synchronization.
12952  */
12953 static void
12954 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
12955     COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
12956     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
12957     LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
12958 {
12959 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
12960 	int error;
12961 
12962 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
12963 	    (CE_NOTE,
12964 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
12965 	ASSERT(resend_rqstp != NULL);
12966 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
12967 	    resend_rqstp->lr_op == OP_LOCKU);
12968 
12969 	*oopp = resend_rqstp->lr_oop;
12970 	if (resend_rqstp->lr_oop) {
12971 		open_owner_hold(resend_rqstp->lr_oop);
12972 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
12973 		ASSERT(error == 0);	/* recov thread always succeeds */
12974 	}
12975 
12976 	/* Must resend this lost lock/locku request. */
12977 	ASSERT(resend_rqstp->lr_lop != NULL);
12978 	*lopp = resend_rqstp->lr_lop;
12979 	lock_owner_hold(resend_rqstp->lr_lop);
12980 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
12981 	ASSERT(error == 0);	/* recov thread always succeeds */
12982 
12983 	*ospp = resend_rqstp->lr_osp;
12984 	if (*ospp)
12985 		open_stream_hold(resend_rqstp->lr_osp);
12986 
12987 	if (resend_rqstp->lr_op == OP_LOCK) {
12988 		LOCK4args *lock_args;
12989 
12990 		argop->argop = OP_LOCK;
12991 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
12992 		lock_args->locktype = resend_rqstp->lr_locktype;
12993 		lock_args->reclaim =
12994 		    (resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
12995 		lock_args->offset = resend_rqstp->lr_flk->l_start;
12996 		lock_args->length = resend_rqstp->lr_flk->l_len;
12997 		if (lock_args->length == 0)
12998 			lock_args->length = ~lock_args->length;
12999 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
13000 		    mi2clientid(mi), &lock_args->locker);
13001 
13002 		switch (resend_rqstp->lr_ctype) {
13003 		case NFS4_LCK_CTYPE_RESEND:
13004 			argsp->ctag = TAG_LOCK_RESEND;
13005 			break;
13006 		case NFS4_LCK_CTYPE_REINSTATE:
13007 			argsp->ctag = TAG_LOCK_REINSTATE;
13008 			break;
13009 		case NFS4_LCK_CTYPE_RECLAIM:
13010 			argsp->ctag = TAG_LOCK_RECLAIM;
13011 			break;
13012 		default:
13013 			argsp->ctag = TAG_LOCK_UNKNOWN;
13014 			break;
13015 		}
13016 	} else {
13017 		LOCKU4args *locku_args;
13018 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
13019 
13020 		argop->argop = OP_LOCKU;
13021 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
13022 		locku_args->locktype = READ_LT;
13023 		locku_args->seqid = lop->lock_seqid + 1;
13024 		mutex_enter(&lop->lo_lock);
13025 		locku_args->lock_stateid = lop->lock_stateid;
13026 		mutex_exit(&lop->lo_lock);
13027 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13028 		locku_args->length = resend_rqstp->lr_flk->l_len;
13029 		if (locku_args->length == 0)
13030 			locku_args->length = ~locku_args->length;
13031 
13032 		switch (resend_rqstp->lr_ctype) {
13033 		case NFS4_LCK_CTYPE_RESEND:
13034 			argsp->ctag = TAG_LOCKU_RESEND;
13035 			break;
13036 		case NFS4_LCK_CTYPE_REINSTATE:
13037 			argsp->ctag = TAG_LOCKU_REINSTATE;
13038 			break;
13039 		default:
13040 			argsp->ctag = TAG_LOCK_UNKNOWN;
13041 			break;
13042 		}
13043 	}
13044 }
13045 
13046 /*
13047  * Setup the LOCKT4 arguments.
13048  */
13049 static void
13050 nfs4frlock_setup_lockt_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13051     LOCKT4args **lockt_argsp, COMPOUND4args_clnt *argsp, flock64_t *flk,
13052     rnode4_t *rp)
13053 {
13054 	LOCKT4args *lockt_args;
13055 
13056 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13057 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13058 	argop->argop = OP_LOCKT;
13059 	argsp->ctag = TAG_LOCKT;
13060 	lockt_args = &argop->nfs_argop4_u.oplockt;
13061 
13062 	/*
13063 	 * The locktype will be READ_LT unless it's
13064 	 * a write lock. We do this because the Solaris
13065 	 * system call allows the combination of
13066 	 * F_UNLCK and F_GETLK* and so in that case the
13067 	 * unlock is mapped to a read.
13068 	 */
13069 	if (flk->l_type == F_WRLCK)
13070 		lockt_args->locktype = WRITE_LT;
13071 	else
13072 		lockt_args->locktype = READ_LT;
13073 
13074 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13075 	/* set the lock owner4 args */
13076 	nfs4_setlockowner_args(&lockt_args->owner, rp,
13077 	    ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13078 	    flk->l_pid);
13079 	lockt_args->offset = flk->l_start;
13080 	lockt_args->length = flk->l_len;
13081 	if (flk->l_len == 0)
13082 		lockt_args->length = ~lockt_args->length;
13083 
13084 	*lockt_argsp = lockt_args;
13085 }
13086 
13087 /*
13088  * If the client is holding a delegation, and the open stream to be used
13089  * with this lock request is a delegation open stream, then re-open the stream.
13090  * Sets the nfs4_error_t to all zeros unless the open stream has already
13091  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13092  * means the caller should retry (like a recovery retry).
13093  */
13094 static void
13095 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13096 {
13097 	open_delegation_type4	dt;
13098 	bool_t			reopen_needed, force;
13099 	nfs4_open_stream_t	*osp;
13100 	open_claim_type4 	oclaim;
13101 	rnode4_t		*rp = VTOR4(vp);
13102 	mntinfo4_t		*mi = VTOMI4(vp);
13103 
13104 	ASSERT(nfs_zone() == mi->mi_zone);
13105 
13106 	nfs4_error_zinit(ep);
13107 
13108 	mutex_enter(&rp->r_statev4_lock);
13109 	dt = rp->r_deleg_type;
13110 	mutex_exit(&rp->r_statev4_lock);
13111 
13112 	if (dt != OPEN_DELEGATE_NONE) {
13113 		nfs4_open_owner_t	*oop;
13114 
13115 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13116 		if (!oop) {
13117 			ep->stat = NFS4ERR_IO;
13118 			return;
13119 		}
13120 		/* returns with 'os_sync_lock' held */
13121 		osp = find_open_stream(oop, rp);
13122 		if (!osp) {
13123 			open_owner_rele(oop);
13124 			ep->stat = NFS4ERR_IO;
13125 			return;
13126 		}
13127 
13128 		if (osp->os_failed_reopen) {
13129 			NFS4_DEBUG((nfs4_open_stream_debug ||
13130 			    nfs4_client_lock_debug), (CE_NOTE,
13131 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13132 			    "for osp %p, cr %p, rp %s", (void *)osp,
13133 			    (void *)cr, rnode4info(rp)));
13134 			mutex_exit(&osp->os_sync_lock);
13135 			open_stream_rele(osp, rp);
13136 			open_owner_rele(oop);
13137 			ep->stat = NFS4ERR_IO;
13138 			return;
13139 		}
13140 
13141 		/*
13142 		 * Determine whether a reopen is needed.  If this
13143 		 * is a delegation open stream, then send the open
13144 		 * to the server to give visibility to the open owner.
13145 		 * Even if it isn't a delegation open stream, we need
13146 		 * to check if the previous open CLAIM_DELEGATE_CUR
13147 		 * was sufficient.
13148 		 */
13149 
13150 		reopen_needed = osp->os_delegation ||
13151 		    ((lt == F_RDLCK &&
13152 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13153 		    (lt == F_WRLCK &&
13154 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13155 
13156 		mutex_exit(&osp->os_sync_lock);
13157 		open_owner_rele(oop);
13158 
13159 		if (reopen_needed) {
13160 			/*
13161 			 * Always use CLAIM_PREVIOUS after server reboot.
13162 			 * The server will reject CLAIM_DELEGATE_CUR if
13163 			 * it is used during the grace period.
13164 			 */
13165 			mutex_enter(&mi->mi_lock);
13166 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13167 				oclaim = CLAIM_PREVIOUS;
13168 				force = TRUE;
13169 			} else {
13170 				oclaim = CLAIM_DELEGATE_CUR;
13171 				force = FALSE;
13172 			}
13173 			mutex_exit(&mi->mi_lock);
13174 
13175 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13176 			if (ep->error == EAGAIN) {
13177 				nfs4_error_zinit(ep);
13178 				ep->stat = NFS4ERR_DELAY;
13179 			}
13180 		}
13181 		open_stream_rele(osp, rp);
13182 		osp = NULL;
13183 	}
13184 }
13185 
13186 /*
13187  * Setup the LOCKU4 arguments.
13188  * Returns errors via the nfs4_error_t.
13189  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13190  *			over-the-wire.  The caller must release the
13191  *			reference on *lopp.
13192  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13193  * (other)		unrecoverable error.
13194  */
13195 static void
13196 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13197     LOCKU4args **locku_argsp, flock64_t *flk,
13198     nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13199     vnode_t *vp, int flag, u_offset_t offset, cred_t *cr,
13200     bool_t *skip_get_err, bool_t *go_otwp)
13201 {
13202 	nfs4_lock_owner_t	*lop = NULL;
13203 	LOCKU4args		*locku_args;
13204 	pid_t			pid;
13205 	bool_t			is_spec = FALSE;
13206 	rnode4_t		*rp = VTOR4(vp);
13207 
13208 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13209 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13210 
13211 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13212 	if (ep->error || ep->stat)
13213 		return;
13214 
13215 	argop->argop = OP_LOCKU;
13216 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13217 		argsp->ctag = TAG_LOCKU_REINSTATE;
13218 	else
13219 		argsp->ctag = TAG_LOCKU;
13220 	locku_args = &argop->nfs_argop4_u.oplocku;
13221 	*locku_argsp = locku_args;
13222 
13223 	/*
13224 	 * XXX what should locku_args->locktype be?
13225 	 * setting to ALWAYS be READ_LT so at least
13226 	 * it is a valid locktype.
13227 	 */
13228 
13229 	locku_args->locktype = READ_LT;
13230 
13231 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13232 	    flk->l_pid;
13233 
13234 	/*
13235 	 * Get the lock owner stateid.  If no lock owner
13236 	 * exists, return success.
13237 	 */
13238 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13239 	*lopp = lop;
13240 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13241 		is_spec = TRUE;
13242 	if (!lop || is_spec) {
13243 		/*
13244 		 * No lock owner so no locks to unlock.
13245 		 * Return success.  If there was a failed
13246 		 * reclaim earlier, the lock might still be
13247 		 * registered with the local locking code,
13248 		 * so notify it of the unlock.
13249 		 *
13250 		 * If the lockowner is using a special stateid,
13251 		 * then the original lock request (that created
13252 		 * this lockowner) was never successful, so we
13253 		 * have no lock to undo OTW.
13254 		 */
13255 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13256 		    "nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13257 		    "(%ld) so return success", (long)pid));
13258 
13259 		if (ctype == NFS4_LCK_CTYPE_NORM)
13260 			flk->l_pid = curproc->p_pid;
13261 		nfs4_register_lock_locally(vp, flk, flag, offset);
13262 		/*
13263 		 * Release our hold and NULL out so final_cleanup
13264 		 * doesn't try to end a lock seqid sync we
13265 		 * never started.
13266 		 */
13267 		if (is_spec) {
13268 			lock_owner_rele(lop);
13269 			*lopp = NULL;
13270 		}
13271 		*skip_get_err = TRUE;
13272 		*go_otwp = FALSE;
13273 		return;
13274 	}
13275 
13276 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13277 	if (ep->error == EAGAIN) {
13278 		lock_owner_rele(lop);
13279 		*lopp = NULL;
13280 		return;
13281 	}
13282 
13283 	mutex_enter(&lop->lo_lock);
13284 	locku_args->lock_stateid = lop->lock_stateid;
13285 	mutex_exit(&lop->lo_lock);
13286 	locku_args->seqid = lop->lock_seqid + 1;
13287 
13288 	/* leave the ref count on lop, rele after RPC call */
13289 
13290 	locku_args->offset = flk->l_start;
13291 	locku_args->length = flk->l_len;
13292 	if (flk->l_len == 0)
13293 		locku_args->length = ~locku_args->length;
13294 
13295 	*go_otwp = TRUE;
13296 }
13297 
13298 /*
13299  * Setup the LOCK4 arguments.
13300  *
13301  * Returns errors via the nfs4_error_t.
13302  * NFS4_OK		no problems
13303  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13304  * (other)		unrecoverable error
13305  */
13306 static void
13307 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13308     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13309     nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13310     flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13311 {
13312 	LOCK4args		*lock_args;
13313 	nfs4_open_owner_t	*oop = NULL;
13314 	nfs4_open_stream_t	*osp = NULL;
13315 	nfs4_lock_owner_t	*lop = NULL;
13316 	pid_t			pid;
13317 	rnode4_t		*rp = VTOR4(vp);
13318 
13319 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13320 
13321 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13322 	if (ep->error || ep->stat != NFS4_OK)
13323 		return;
13324 
13325 	argop->argop = OP_LOCK;
13326 	if (ctype == NFS4_LCK_CTYPE_NORM)
13327 		argsp->ctag = TAG_LOCK;
13328 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13329 		argsp->ctag = TAG_RELOCK;
13330 	else
13331 		argsp->ctag = TAG_LOCK_REINSTATE;
13332 	lock_args = &argop->nfs_argop4_u.oplock;
13333 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13334 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13335 	/*
13336 	 * Get the lock owner.  If no lock owner exists,
13337 	 * create a 'temporary' one and grab the open seqid
13338 	 * synchronization (which puts a hold on the open
13339 	 * owner and open stream).
13340 	 * This also grabs the lock seqid synchronization.
13341 	 */
13342 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid : flk->l_pid;
13343 	ep->stat =
13344 	    nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13345 
13346 	if (ep->stat != NFS4_OK)
13347 		goto out;
13348 
13349 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13350 	    &lock_args->locker);
13351 
13352 	lock_args->offset = flk->l_start;
13353 	lock_args->length = flk->l_len;
13354 	if (flk->l_len == 0)
13355 		lock_args->length = ~lock_args->length;
13356 	*lock_argsp = lock_args;
13357 out:
13358 	*oopp = oop;
13359 	*ospp = osp;
13360 	*lopp = lop;
13361 }
13362 
13363 /*
13364  * After we get the reply from the server, record the proper information
13365  * for possible resend lock requests.
13366  *
13367  * Allocates memory for the saved_rqstp if we have a lost lock to save.
13368  */
13369 static void
13370 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13371     nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13372     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13373     nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13374 {
13375 	bool_t unlock = (flk->l_type == F_UNLCK);
13376 
13377 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13378 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13379 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13380 
13381 	if (error != 0 && !unlock) {
13382 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13383 		    nfs4_client_lock_debug), (CE_NOTE,
13384 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13385 		    " for lop %p", (void *)lop));
13386 		ASSERT(lop != NULL);
13387 		mutex_enter(&lop->lo_lock);
13388 		lop->lo_pending_rqsts = 1;
13389 		mutex_exit(&lop->lo_lock);
13390 	}
13391 
13392 	lost_rqstp->lr_putfirst = FALSE;
13393 	lost_rqstp->lr_op = 0;
13394 
13395 	/*
13396 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13397 	 * recovery purposes so that the lock request that was sent
13398 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13399 	 * unmount.  This is done to have the client's local locking state
13400 	 * match the v4 server's state; that is, the request was
13401 	 * potentially received and accepted by the server but the client
13402 	 * thinks it was not.
13403 	 */
13404 	if (error == ETIMEDOUT || error == EINTR ||
13405 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13406 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13407 		    nfs4_client_lock_debug), (CE_NOTE,
13408 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13409 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13410 		    (void *)lop, (void *)oop, (void *)osp));
13411 		if (unlock)
13412 			lost_rqstp->lr_op = OP_LOCKU;
13413 		else {
13414 			lost_rqstp->lr_op = OP_LOCK;
13415 			lost_rqstp->lr_locktype = locktype;
13416 		}
13417 		/*
13418 		 * Objects are held and rele'd via the recovery code.
13419 		 * See nfs4_save_lost_rqst.
13420 		 */
13421 		lost_rqstp->lr_vp = vp;
13422 		lost_rqstp->lr_dvp = NULL;
13423 		lost_rqstp->lr_oop = oop;
13424 		lost_rqstp->lr_osp = osp;
13425 		lost_rqstp->lr_lop = lop;
13426 		lost_rqstp->lr_cr = cr;
13427 		switch (ctype) {
13428 		case NFS4_LCK_CTYPE_NORM:
13429 			flk->l_pid = ttoproc(curthread)->p_pid;
13430 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13431 			break;
13432 		case NFS4_LCK_CTYPE_REINSTATE:
13433 			lost_rqstp->lr_putfirst = TRUE;
13434 			lost_rqstp->lr_ctype = ctype;
13435 			break;
13436 		default:
13437 			break;
13438 		}
13439 		lost_rqstp->lr_flk = flk;
13440 	}
13441 }
13442 
13443 /*
13444  * Update lop's seqid.  Also update the seqid stored in a resend request,
13445  * if any.  (Some recovery errors increment the seqid, and we may have to
13446  * send the resend request again.)
13447  */
13448 
13449 static void
13450 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13451     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13452 {
13453 	if (lock_args) {
13454 		if (lock_args->locker.new_lock_owner == TRUE)
13455 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13456 		else {
13457 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13458 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13459 		}
13460 	} else if (locku_args) {
13461 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13462 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13463 	}
13464 }
13465 
13466 /*
13467  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13468  * COMPOUND4 args/res for calls that need to retry.
13469  * Switches the *cred_otwp to base_cr.
13470  */
13471 static void
13472 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13473     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13474     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13475     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13476     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13477 {
13478 	nfs4_open_owner_t	*oop = *oopp;
13479 	nfs4_open_stream_t	*osp = *ospp;
13480 	nfs4_lock_owner_t	*lop = *lopp;
13481 	nfs_argop4		*argop = (*argspp)->array;
13482 
13483 	if (*did_start_fop) {
13484 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13485 		    needrecov);
13486 		*did_start_fop = FALSE;
13487 	}
13488 	ASSERT((*argspp)->array_len == 2);
13489 	if (argop[1].argop == OP_LOCK)
13490 		nfs4args_lock_free(&argop[1]);
13491 	else if (argop[1].argop == OP_LOCKT)
13492 		nfs4args_lockt_free(&argop[1]);
13493 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13494 	if (!error)
13495 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13496 	*argspp = NULL;
13497 	*respp = NULL;
13498 
13499 	if (lop) {
13500 		nfs4_end_lock_seqid_sync(lop);
13501 		lock_owner_rele(lop);
13502 		*lopp = NULL;
13503 	}
13504 
13505 	/* need to free up the reference on osp for lock args */
13506 	if (osp != NULL) {
13507 		open_stream_rele(osp, VTOR4(vp));
13508 		*ospp = NULL;
13509 	}
13510 
13511 	/* need to free up the reference on oop for lock args */
13512 	if (oop != NULL) {
13513 		nfs4_end_open_seqid_sync(oop);
13514 		open_owner_rele(oop);
13515 		*oopp = NULL;
13516 	}
13517 
13518 	crfree(*cred_otwp);
13519 	*cred_otwp = base_cr;
13520 	crhold(*cred_otwp);
13521 }
13522 
13523 /*
13524  * Function to process the client's recovery for nfs4frlock.
13525  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13526  *
13527  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13528  * COMPOUND4 args/res for calls that need to retry.
13529  *
13530  * Note: the rp's r_lkserlock is *not* dropped during this path.
13531  */
13532 static bool_t
13533 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13534     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13535     LOCK4args *lock_args, LOCKU4args *locku_args,
13536     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13537     nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13538     nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13539     bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13540 {
13541 	nfs4_open_owner_t	*oop = *oopp;
13542 	nfs4_open_stream_t	*osp = *ospp;
13543 	nfs4_lock_owner_t	*lop = *lopp;
13544 
13545 	bool_t abort, retry;
13546 
13547 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13548 	ASSERT((*argspp) != NULL);
13549 	ASSERT((*respp) != NULL);
13550 	if (lock_args || locku_args)
13551 		ASSERT(lop != NULL);
13552 
13553 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13554 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13555 
13556 	retry = TRUE;
13557 	abort = FALSE;
13558 	if (needrecov) {
13559 		nfs4_bseqid_entry_t *bsep = NULL;
13560 		nfs_opnum4 op;
13561 
13562 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13563 
13564 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13565 			seqid4 seqid;
13566 
13567 			if (lock_args) {
13568 				if (lock_args->locker.new_lock_owner == TRUE)
13569 					seqid = lock_args->locker.locker4_u.
13570 					    open_owner.open_seqid;
13571 				else
13572 					seqid = lock_args->locker.locker4_u.
13573 					    lock_owner.lock_seqid;
13574 			} else if (locku_args) {
13575 				seqid = locku_args->seqid;
13576 			} else {
13577 				seqid = 0;
13578 			}
13579 
13580 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13581 			    flk->l_pid, (*argspp)->ctag, seqid);
13582 		}
13583 
13584 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13585 		    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13586 		    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13587 		    NULL, op, bsep);
13588 
13589 		if (bsep)
13590 			kmem_free(bsep, sizeof (*bsep));
13591 	}
13592 
13593 	/*
13594 	 * Return that we do not want to retry the request for 3 cases:
13595 	 * 1. If we received EINTR or are bailing out because of a forced
13596 	 *    unmount, we came into this code path just for the sake of
13597 	 *    initiating recovery, we now need to return the error.
13598 	 * 2. If we have aborted recovery.
13599 	 * 3. We received NFS4ERR_BAD_SEQID.
13600 	 */
13601 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13602 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13603 		retry = FALSE;
13604 
13605 	if (*did_start_fop == TRUE) {
13606 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13607 		    needrecov);
13608 		*did_start_fop = FALSE;
13609 	}
13610 
13611 	if (retry == TRUE) {
13612 		nfs_argop4	*argop;
13613 
13614 		argop = (*argspp)->array;
13615 		ASSERT((*argspp)->array_len == 2);
13616 
13617 		if (argop[1].argop == OP_LOCK)
13618 			nfs4args_lock_free(&argop[1]);
13619 		else if (argop[1].argop == OP_LOCKT)
13620 			nfs4args_lockt_free(&argop[1]);
13621 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13622 		if (!ep->error)
13623 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13624 		*respp = NULL;
13625 		*argspp = NULL;
13626 	}
13627 
13628 	if (lop != NULL) {
13629 		nfs4_end_lock_seqid_sync(lop);
13630 		lock_owner_rele(lop);
13631 	}
13632 
13633 	*lopp = NULL;
13634 
13635 	/* need to free up the reference on osp for lock args */
13636 	if (osp != NULL) {
13637 		open_stream_rele(osp, rp);
13638 		*ospp = NULL;
13639 	}
13640 
13641 	/* need to free up the reference on oop for lock args */
13642 	if (oop != NULL) {
13643 		nfs4_end_open_seqid_sync(oop);
13644 		open_owner_rele(oop);
13645 		*oopp = NULL;
13646 	}
13647 
13648 	return (retry);
13649 }
13650 
13651 /*
13652  * Handles the successful reply from the server for nfs4frlock.
13653  */
13654 static void
13655 nfs4frlock_results_ok(nfs4_lock_call_type_t ctype, int cmd, flock64_t *flk,
13656     vnode_t *vp, int flag, u_offset_t offset,
13657     nfs4_lost_rqst_t *resend_rqstp)
13658 {
13659 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13660 	if ((cmd == F_SETLK || cmd == F_SETLKW) &&
13661 	    (flk->l_type == F_RDLCK || flk->l_type == F_WRLCK)) {
13662 		if (ctype == NFS4_LCK_CTYPE_NORM) {
13663 			flk->l_pid = ttoproc(curthread)->p_pid;
13664 			/*
13665 			 * We do not register lost locks locally in
13666 			 * the 'resend' case since the user/application
13667 			 * doesn't think we have the lock.
13668 			 */
13669 			ASSERT(!resend_rqstp);
13670 			nfs4_register_lock_locally(vp, flk, flag, offset);
13671 		}
13672 	}
13673 }
13674 
13675 /*
13676  * Handle the DENIED reply from the server for nfs4frlock.
13677  * Returns TRUE if we should retry the request; FALSE otherwise.
13678  *
13679  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13680  * COMPOUND4 args/res for calls that need to retry.  Can also
13681  * drop and regrab the r_lkserlock.
13682  */
13683 static bool_t
13684 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13685     LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13686     nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13687     vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13688     nfs4_recov_state_t *recov_statep, int needrecov,
13689     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13690     clock_t *tick_delayp, short *whencep, int *errorp,
13691     nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13692     bool_t *skip_get_err)
13693 {
13694 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13695 
13696 	if (lock_args) {
13697 		nfs4_open_owner_t	*oop = *oopp;
13698 		nfs4_open_stream_t	*osp = *ospp;
13699 		nfs4_lock_owner_t	*lop = *lopp;
13700 		int			intr;
13701 
13702 		/*
13703 		 * Blocking lock needs to sleep and retry from the request.
13704 		 *
13705 		 * Do not block and wait for 'resend' or 'reinstate'
13706 		 * lock requests, just return the error.
13707 		 *
13708 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13709 		 */
13710 		if (cmd == F_SETLKW) {
13711 			rnode4_t *rp = VTOR4(vp);
13712 			nfs_argop4 *argop = (*argspp)->array;
13713 
13714 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13715 
13716 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13717 			    recov_statep, needrecov);
13718 			*did_start_fop = FALSE;
13719 			ASSERT((*argspp)->array_len == 2);
13720 			if (argop[1].argop == OP_LOCK)
13721 				nfs4args_lock_free(&argop[1]);
13722 			else if (argop[1].argop == OP_LOCKT)
13723 				nfs4args_lockt_free(&argop[1]);
13724 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13725 			if (*respp)
13726 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13727 				    (caddr_t)*respp);
13728 			*argspp = NULL;
13729 			*respp = NULL;
13730 			nfs4_end_lock_seqid_sync(lop);
13731 			lock_owner_rele(lop);
13732 			*lopp = NULL;
13733 			if (osp != NULL) {
13734 				open_stream_rele(osp, rp);
13735 				*ospp = NULL;
13736 			}
13737 			if (oop != NULL) {
13738 				nfs4_end_open_seqid_sync(oop);
13739 				open_owner_rele(oop);
13740 				*oopp = NULL;
13741 			}
13742 
13743 			nfs_rw_exit(&rp->r_lkserlock);
13744 
13745 			intr = nfs4_block_and_wait(tick_delayp, rp);
13746 
13747 			if (intr) {
13748 				(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13749 				    RW_WRITER, FALSE);
13750 				*errorp = EINTR;
13751 				return (FALSE);
13752 			}
13753 
13754 			(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13755 			    RW_WRITER, FALSE);
13756 
13757 			/*
13758 			 * Make sure we are still safe to lock with
13759 			 * regards to mmapping.
13760 			 */
13761 			if (!nfs4_safelock(vp, flk, cr)) {
13762 				*errorp = EAGAIN;
13763 				return (FALSE);
13764 			}
13765 
13766 			return (TRUE);
13767 		}
13768 		if (ctype == NFS4_LCK_CTYPE_NORM)
13769 			*errorp = EAGAIN;
13770 		*skip_get_err = TRUE;
13771 		flk->l_whence = 0;
13772 		*whencep = 0;
13773 		return (FALSE);
13774 	} else if (lockt_args) {
13775 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13776 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
13777 
13778 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
13779 		    flk, lockt_args);
13780 
13781 		/* according to NLM code */
13782 		*errorp = 0;
13783 		*whencep = 0;
13784 		*skip_get_err = TRUE;
13785 		return (FALSE);
13786 	}
13787 	return (FALSE);
13788 }
13789 
13790 /*
13791  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
13792  */
13793 static void
13794 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
13795 {
13796 	switch (resp->status) {
13797 	case NFS4ERR_ACCESS:
13798 	case NFS4ERR_ADMIN_REVOKED:
13799 	case NFS4ERR_BADHANDLE:
13800 	case NFS4ERR_BAD_RANGE:
13801 	case NFS4ERR_BAD_SEQID:
13802 	case NFS4ERR_BAD_STATEID:
13803 	case NFS4ERR_BADXDR:
13804 	case NFS4ERR_DEADLOCK:
13805 	case NFS4ERR_DELAY:
13806 	case NFS4ERR_EXPIRED:
13807 	case NFS4ERR_FHEXPIRED:
13808 	case NFS4ERR_GRACE:
13809 	case NFS4ERR_INVAL:
13810 	case NFS4ERR_ISDIR:
13811 	case NFS4ERR_LEASE_MOVED:
13812 	case NFS4ERR_LOCK_NOTSUPP:
13813 	case NFS4ERR_LOCK_RANGE:
13814 	case NFS4ERR_MOVED:
13815 	case NFS4ERR_NOFILEHANDLE:
13816 	case NFS4ERR_NO_GRACE:
13817 	case NFS4ERR_OLD_STATEID:
13818 	case NFS4ERR_OPENMODE:
13819 	case NFS4ERR_RECLAIM_BAD:
13820 	case NFS4ERR_RECLAIM_CONFLICT:
13821 	case NFS4ERR_RESOURCE:
13822 	case NFS4ERR_SERVERFAULT:
13823 	case NFS4ERR_STALE:
13824 	case NFS4ERR_STALE_CLIENTID:
13825 	case NFS4ERR_STALE_STATEID:
13826 		return;
13827 	default:
13828 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13829 		    "nfs4frlock_results_default: got unrecognizable "
13830 		    "res.status %d", resp->status));
13831 		*errorp = NFS4ERR_INVAL;
13832 	}
13833 }
13834 
13835 /*
13836  * The lock request was successful, so update the client's state.
13837  */
13838 static void
13839 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
13840     LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
13841     vnode_t *vp, flock64_t *flk, cred_t *cr,
13842     nfs4_lost_rqst_t *resend_rqstp)
13843 {
13844 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13845 
13846 	if (lock_args) {
13847 		LOCK4res *lock_res;
13848 
13849 		lock_res = &resop->nfs_resop4_u.oplock;
13850 		/* update the stateid with server's response */
13851 
13852 		if (lock_args->locker.new_lock_owner == TRUE) {
13853 			mutex_enter(&lop->lo_lock);
13854 			lop->lo_just_created = NFS4_PERM_CREATED;
13855 			mutex_exit(&lop->lo_lock);
13856 		}
13857 
13858 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
13859 
13860 		/*
13861 		 * If the lock was the result of a resending a lost
13862 		 * request, we've synched up the stateid and seqid
13863 		 * with the server, but now the server might be out of sync
13864 		 * with what the application thinks it has for locks.
13865 		 * Clean that up here.  It's unclear whether we should do
13866 		 * this even if the filesystem has been forcibly unmounted.
13867 		 * For most servers, it's probably wasted effort, but
13868 		 * RFC3530 lets servers require that unlocks exactly match
13869 		 * the locks that are held.
13870 		 */
13871 		if (resend_rqstp != NULL &&
13872 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
13873 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
13874 		} else {
13875 			flk->l_whence = 0;
13876 		}
13877 	} else if (locku_args) {
13878 		LOCKU4res *locku_res;
13879 
13880 		locku_res = &resop->nfs_resop4_u.oplocku;
13881 
13882 		/* Update the stateid with the server's response */
13883 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
13884 	} else if (lockt_args) {
13885 		/* Switch the lock type to express success, see fcntl */
13886 		flk->l_type = F_UNLCK;
13887 		flk->l_whence = 0;
13888 	}
13889 }
13890 
13891 /*
13892  * Do final cleanup before exiting nfs4frlock.
13893  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13894  * COMPOUND4 args/res for calls that haven't already.
13895  */
13896 static void
13897 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
13898     COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
13899     nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
13900     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13901     short whence, u_offset_t offset, struct lm_sysid *ls,
13902     int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
13903     bool_t did_start_fop, bool_t skip_get_err,
13904     cred_t *cred_otw, cred_t *cred)
13905 {
13906 	mntinfo4_t	*mi = VTOMI4(vp);
13907 	rnode4_t	*rp = VTOR4(vp);
13908 	int		error = *errorp;
13909 	nfs_argop4	*argop;
13910 
13911 	ASSERT(nfs_zone() == mi->mi_zone);
13912 	/*
13913 	 * The client recovery code wants the raw status information,
13914 	 * so don't map the NFS status code to an errno value for
13915 	 * non-normal call types.
13916 	 */
13917 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13918 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
13919 			*errorp = geterrno4(resp->status);
13920 		if (did_start_fop == TRUE)
13921 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
13922 			    needrecov);
13923 
13924 		/*
13925 		 * We've established a new lock on the server, so invalidate
13926 		 * the pages associated with the vnode to get the most up to
13927 		 * date pages from the server after acquiring the lock. We
13928 		 * want to be sure that the read operation gets the newest data.
13929 		 * N.B.
13930 		 * We used to do this in nfs4frlock_results_ok but that doesn't
13931 		 * work since VOP_PUTPAGE can call nfs4_commit which calls
13932 		 * nfs4_start_fop. We flush the pages below after calling
13933 		 * nfs4_end_fop above
13934 		 */
13935 		if (!error && resp && resp->status == NFS4_OK) {
13936 			int error;
13937 
13938 			error = VOP_PUTPAGE(vp, (u_offset_t)0,
13939 			    0, B_INVAL, cred, NULL);
13940 
13941 			if (error && (error == ENOSPC || error == EDQUOT)) {
13942 				rnode4_t *rp = VTOR4(vp);
13943 
13944 				mutex_enter(&rp->r_statelock);
13945 				if (!rp->r_error)
13946 					rp->r_error = error;
13947 				mutex_exit(&rp->r_statelock);
13948 			}
13949 		}
13950 	}
13951 	if (argsp) {
13952 		ASSERT(argsp->array_len == 2);
13953 		argop = argsp->array;
13954 		if (argop[1].argop == OP_LOCK)
13955 			nfs4args_lock_free(&argop[1]);
13956 		else if (argop[1].argop == OP_LOCKT)
13957 			nfs4args_lockt_free(&argop[1]);
13958 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13959 		if (resp)
13960 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
13961 	}
13962 
13963 	/* free the reference on the lock owner */
13964 	if (lop != NULL) {
13965 		nfs4_end_lock_seqid_sync(lop);
13966 		lock_owner_rele(lop);
13967 	}
13968 
13969 	/* need to free up the reference on osp for lock args */
13970 	if (osp != NULL)
13971 		open_stream_rele(osp, rp);
13972 
13973 	/* need to free up the reference on oop for lock args */
13974 	if (oop != NULL) {
13975 		nfs4_end_open_seqid_sync(oop);
13976 		open_owner_rele(oop);
13977 	}
13978 
13979 	(void) convoff(vp, flk, whence, offset);
13980 
13981 	lm_rel_sysid(ls);
13982 
13983 	/*
13984 	 * Record debug information in the event we get EINVAL.
13985 	 */
13986 	mutex_enter(&mi->mi_lock);
13987 	if (*errorp == EINVAL && (lock_args || locku_args) &&
13988 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
13989 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
13990 			zcmn_err(getzoneid(), CE_NOTE,
13991 			    "%s operation failed with "
13992 			    "EINVAL probably since the server, %s,"
13993 			    " doesn't support POSIX style locking",
13994 			    lock_args ? "LOCK" : "LOCKU",
13995 			    mi->mi_curr_serv->sv_hostname);
13996 			mi->mi_flags |= MI4_LOCK_DEBUG;
13997 		}
13998 	}
13999 	mutex_exit(&mi->mi_lock);
14000 
14001 	if (cred_otw)
14002 		crfree(cred_otw);
14003 }
14004 
14005 /*
14006  * This calls the server and the local locking code.
14007  *
14008  * Client locks are registerred locally by oring the sysid with
14009  * LM_SYSID_CLIENT. The server registers locks locally using just the sysid.
14010  * We need to distinguish between the two to avoid collision in case one
14011  * machine is used as both client and server.
14012  *
14013  * Blocking lock requests will continually retry to acquire the lock
14014  * forever.
14015  *
14016  * The ctype is defined as follows:
14017  * NFS4_LCK_CTYPE_NORM: normal lock request.
14018  *
14019  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
14020  * recovery, get the pid from flk instead of curproc, and don't reregister
14021  * the lock locally.
14022  *
14023  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
14024  * that we will use the information passed in via resend_rqstp to setup the
14025  * lock/locku request.  This resend is the exact same request as the 'lost
14026  * lock', and is initiated by the recovery framework. A successful resend
14027  * request can initiate one or more reinstate requests.
14028  *
14029  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14030  * does not trigger additional reinstate requests.  This lock call type is
14031  * set for setting the v4 server's locking state back to match what the
14032  * client's local locking state is in the event of a received 'lost lock'.
14033  *
14034  * Errors are returned via the nfs4_error_t parameter.
14035  */
14036 void
14037 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14038     int flag, u_offset_t offset, cred_t *cr, nfs4_error_t *ep,
14039     nfs4_lost_rqst_t *resend_rqstp, int *did_reclaimp)
14040 {
14041 	COMPOUND4args_clnt	args, *argsp = NULL;
14042 	COMPOUND4res_clnt	res, *resp = NULL;
14043 	nfs_argop4	*argop;
14044 	nfs_resop4	*resop;
14045 	rnode4_t	*rp;
14046 	int		doqueue = 1;
14047 	clock_t		tick_delay;  /* delay in clock ticks */
14048 	struct lm_sysid	*ls;
14049 	LOCK4args	*lock_args = NULL;
14050 	LOCKU4args	*locku_args = NULL;
14051 	LOCKT4args	*lockt_args = NULL;
14052 	nfs4_open_owner_t *oop = NULL;
14053 	nfs4_open_stream_t *osp = NULL;
14054 	nfs4_lock_owner_t *lop = NULL;
14055 	bool_t		needrecov = FALSE;
14056 	nfs4_recov_state_t recov_state;
14057 	short		whence;
14058 	nfs4_op_hint_t	op_hint;
14059 	nfs4_lost_rqst_t lost_rqst;
14060 	bool_t		retry = FALSE;
14061 	bool_t		did_start_fop = FALSE;
14062 	bool_t		skip_get_err = FALSE;
14063 	cred_t		*cred_otw = NULL;
14064 	bool_t		recovonly;	/* just queue request */
14065 	int		frc_no_reclaim = 0;
14066 #ifdef DEBUG
14067 	char *name;
14068 #endif
14069 
14070 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14071 
14072 #ifdef DEBUG
14073 	name = fn_name(VTOSV(vp)->sv_name);
14074 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14075 	    "%s: cmd %d, type %d, offset %llu, start %"PRIx64", "
14076 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14077 	    "resend request %s", name, cmd, flk->l_type, offset, flk->l_start,
14078 	    flk->l_len, ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid :
14079 	    flk->l_pid, flk->l_sysid, nfs4frlock_get_call_type(ctype),
14080 	    resend_rqstp ? "TRUE" : "FALSE"));
14081 	kmem_free(name, MAXNAMELEN);
14082 #endif
14083 
14084 	nfs4_error_zinit(ep);
14085 	ep->error = nfs4frlock_validate_args(cmd, flk, flag, vp, offset);
14086 	if (ep->error)
14087 		return;
14088 	ep->error = nfs4frlock_get_sysid(&ls, vp, flk);
14089 	if (ep->error)
14090 		return;
14091 	nfs4frlock_pre_setup(&tick_delay, &recov_state, flk, &whence,
14092 	    vp, cr, &cred_otw);
14093 
14094 recov_retry:
14095 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14096 	    &retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14097 	rp = VTOR4(vp);
14098 
14099 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14100 	    &did_start_fop, &recovonly);
14101 
14102 	if (ep->error)
14103 		goto out;
14104 
14105 	if (recovonly) {
14106 		/*
14107 		 * Leave the request for the recovery system to deal with.
14108 		 */
14109 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14110 		ASSERT(cmd != F_GETLK);
14111 		ASSERT(flk->l_type == F_UNLCK);
14112 
14113 		nfs4_error_init(ep, EINTR);
14114 		needrecov = TRUE;
14115 		lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14116 		if (lop != NULL) {
14117 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14118 			    NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14119 			(void) nfs4_start_recovery(ep,
14120 			    VTOMI4(vp), vp, NULL, NULL,
14121 			    (lost_rqst.lr_op == OP_LOCK ||
14122 			    lost_rqst.lr_op == OP_LOCKU) ?
14123 			    &lost_rqst : NULL, OP_LOCKU, NULL);
14124 			lock_owner_rele(lop);
14125 			lop = NULL;
14126 		}
14127 		flk->l_pid = curproc->p_pid;
14128 		nfs4_register_lock_locally(vp, flk, flag, offset);
14129 		goto out;
14130 	}
14131 
14132 	/* putfh directory fh */
14133 	argop[0].argop = OP_CPUTFH;
14134 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14135 
14136 	/*
14137 	 * Set up the over-the-wire arguments and get references to the
14138 	 * open owner, etc.
14139 	 */
14140 
14141 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14142 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14143 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14144 		    &argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14145 	} else {
14146 		bool_t go_otw = TRUE;
14147 
14148 		ASSERT(resend_rqstp == NULL);
14149 
14150 		switch (cmd) {
14151 		case F_GETLK:
14152 		case F_O_GETLK:
14153 			nfs4frlock_setup_lockt_args(ctype, &argop[1],
14154 			    &lockt_args, argsp, flk, rp);
14155 			break;
14156 		case F_SETLKW:
14157 		case F_SETLK:
14158 			if (flk->l_type == F_UNLCK)
14159 				nfs4frlock_setup_locku_args(ctype,
14160 				    &argop[1], &locku_args, flk,
14161 				    &lop, ep, argsp,
14162 				    vp, flag, offset, cr,
14163 				    &skip_get_err, &go_otw);
14164 			else
14165 				nfs4frlock_setup_lock_args(ctype,
14166 				    &lock_args, &oop, &osp, &lop, &argop[1],
14167 				    argsp, flk, cmd, vp, cr, ep);
14168 
14169 			if (ep->error)
14170 				goto out;
14171 
14172 			switch (ep->stat) {
14173 			case NFS4_OK:
14174 				break;
14175 			case NFS4ERR_DELAY:
14176 				/* recov thread never gets this error */
14177 				ASSERT(resend_rqstp == NULL);
14178 				ASSERT(did_start_fop);
14179 
14180 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14181 				    &recov_state, TRUE);
14182 				did_start_fop = FALSE;
14183 				if (argop[1].argop == OP_LOCK)
14184 					nfs4args_lock_free(&argop[1]);
14185 				else if (argop[1].argop == OP_LOCKT)
14186 					nfs4args_lockt_free(&argop[1]);
14187 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14188 				argsp = NULL;
14189 				goto recov_retry;
14190 			default:
14191 				ep->error = EIO;
14192 				goto out;
14193 			}
14194 			break;
14195 		default:
14196 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14197 			    "nfs4_frlock: invalid cmd %d", cmd));
14198 			ep->error = EINVAL;
14199 			goto out;
14200 		}
14201 
14202 		if (!go_otw)
14203 			goto out;
14204 	}
14205 
14206 	/* XXX should we use the local reclock as a cache ? */
14207 	/*
14208 	 * Unregister the lock with the local locking code before
14209 	 * contacting the server.  This avoids a potential race where
14210 	 * another process gets notified that it has been granted a lock
14211 	 * before we can unregister ourselves locally.
14212 	 */
14213 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK) {
14214 		if (ctype == NFS4_LCK_CTYPE_NORM)
14215 			flk->l_pid = ttoproc(curthread)->p_pid;
14216 		nfs4_register_lock_locally(vp, flk, flag, offset);
14217 	}
14218 
14219 	/*
14220 	 * Send the server the lock request.  Continually loop with a delay
14221 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14222 	 */
14223 	resp = &res;
14224 
14225 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14226 	    (CE_NOTE,
14227 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14228 	    rnode4info(rp)));
14229 
14230 	if (lock_args && frc_no_reclaim) {
14231 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14232 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14233 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14234 		lock_args->reclaim = FALSE;
14235 		if (did_reclaimp)
14236 			*did_reclaimp = 0;
14237 	}
14238 
14239 	/*
14240 	 * Do the OTW call.
14241 	 */
14242 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14243 
14244 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14245 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14246 
14247 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14248 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14249 	    "nfs4frlock: needrecov %d", needrecov));
14250 
14251 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14252 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14253 		    args.ctag);
14254 
14255 	/*
14256 	 * Check if one of these mutually exclusive error cases has
14257 	 * happened:
14258 	 *   need to swap credentials due to access error
14259 	 *   recovery is needed
14260 	 *   different error (only known case is missing Kerberos ticket)
14261 	 */
14262 
14263 	if ((ep->error == EACCES ||
14264 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14265 	    cred_otw != cr) {
14266 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14267 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14268 		    cr, &cred_otw);
14269 		goto recov_retry;
14270 	}
14271 
14272 	if (needrecov) {
14273 		/*
14274 		 * LOCKT requests don't need to recover from lost
14275 		 * requests since they don't create/modify state.
14276 		 */
14277 		if ((ep->error == EINTR ||
14278 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14279 		    lockt_args)
14280 			goto out;
14281 		/*
14282 		 * Do not attempt recovery for requests initiated by
14283 		 * the recovery framework.  Let the framework redrive them.
14284 		 */
14285 		if (ctype != NFS4_LCK_CTYPE_NORM)
14286 			goto out;
14287 		else {
14288 			ASSERT(resend_rqstp == NULL);
14289 		}
14290 
14291 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14292 		    flk_to_locktype(cmd, flk->l_type),
14293 		    oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14294 
14295 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14296 		    &resp, lock_args, locku_args, &oop, &osp, &lop,
14297 		    rp, vp, &recov_state, op_hint, &did_start_fop,
14298 		    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14299 
14300 		if (retry) {
14301 			ASSERT(oop == NULL);
14302 			ASSERT(osp == NULL);
14303 			ASSERT(lop == NULL);
14304 			goto recov_retry;
14305 		}
14306 		goto out;
14307 	}
14308 
14309 	/*
14310 	 * Bail out if have reached this point with ep->error set. Can
14311 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14312 	 * This happens if Kerberos ticket has expired or has been
14313 	 * destroyed.
14314 	 */
14315 	if (ep->error != 0)
14316 		goto out;
14317 
14318 	/*
14319 	 * Process the reply.
14320 	 */
14321 	switch (resp->status) {
14322 	case NFS4_OK:
14323 		resop = &resp->array[1];
14324 		nfs4frlock_results_ok(ctype, cmd, flk, vp, flag, offset,
14325 		    resend_rqstp);
14326 		/*
14327 		 * Have a successful lock operation, now update state.
14328 		 */
14329 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14330 		    resop, lop, vp, flk, cr, resend_rqstp);
14331 		break;
14332 
14333 	case NFS4ERR_DENIED:
14334 		resop = &resp->array[1];
14335 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14336 		    &oop, &osp, &lop, cmd, vp, flk, op_hint,
14337 		    &recov_state, needrecov, &argsp, &resp,
14338 		    &tick_delay, &whence, &ep->error, resop, cr,
14339 		    &did_start_fop, &skip_get_err);
14340 
14341 		if (retry) {
14342 			ASSERT(oop == NULL);
14343 			ASSERT(osp == NULL);
14344 			ASSERT(lop == NULL);
14345 			goto recov_retry;
14346 		}
14347 		break;
14348 	/*
14349 	 * If the server won't let us reclaim, fall-back to trying to lock
14350 	 * the file from scratch. Code elsewhere will check the changeinfo
14351 	 * to ensure the file hasn't been changed.
14352 	 */
14353 	case NFS4ERR_NO_GRACE:
14354 		if (lock_args && lock_args->reclaim == TRUE) {
14355 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14356 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14357 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14358 			frc_no_reclaim = 1;
14359 			/* clean up before retrying */
14360 			needrecov = 0;
14361 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14362 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14363 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14364 			goto recov_retry;
14365 		}
14366 		/* FALLTHROUGH */
14367 
14368 	default:
14369 		nfs4frlock_results_default(resp, &ep->error);
14370 		break;
14371 	}
14372 out:
14373 	/*
14374 	 * Process and cleanup from error.  Make interrupted unlock
14375 	 * requests look successful, since they will be handled by the
14376 	 * client recovery code.
14377 	 */
14378 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14379 	    needrecov, oop, osp, lop, flk, whence, offset, ls, &ep->error,
14380 	    lock_args, locku_args, did_start_fop,
14381 	    skip_get_err, cred_otw, cr);
14382 
14383 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14384 	    (cmd == F_SETLK || cmd == F_SETLKW))
14385 		ep->error = 0;
14386 }
14387 
14388 /*
14389  * nfs4_safelock:
14390  *
14391  * Return non-zero if the given lock request can be handled without
14392  * violating the constraints on concurrent mapping and locking.
14393  */
14394 
14395 static int
14396 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14397 {
14398 	rnode4_t *rp = VTOR4(vp);
14399 	struct vattr va;
14400 	int error;
14401 
14402 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14403 	ASSERT(rp->r_mapcnt >= 0);
14404 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14405 	    "(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14406 	    "write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14407 	    bfp->l_start, bfp->l_len, rp->r_mapcnt));
14408 
14409 	if (rp->r_mapcnt == 0)
14410 		return (1);		/* always safe if not mapped */
14411 
14412 	/*
14413 	 * If the file is already mapped and there are locks, then they
14414 	 * should be all safe locks.  So adding or removing a lock is safe
14415 	 * as long as the new request is safe (i.e., whole-file, meaning
14416 	 * length and starting offset are both zero).
14417 	 */
14418 
14419 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14420 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14421 		    "cannot lock a memory mapped file unless locking the "
14422 		    "entire file: start %"PRIx64", len %"PRIx64,
14423 		    bfp->l_start, bfp->l_len));
14424 		return (0);
14425 	}
14426 
14427 	/* mandatory locking and mapping don't mix */
14428 	va.va_mask = AT_MODE;
14429 	error = VOP_GETATTR(vp, &va, 0, cr, NULL);
14430 	if (error != 0) {
14431 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14432 		    "getattr error %d", error));
14433 		return (0);		/* treat errors conservatively */
14434 	}
14435 	if (MANDLOCK(vp, va.va_mode)) {
14436 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14437 		    "cannot mandatory lock and mmap a file"));
14438 		return (0);
14439 	}
14440 
14441 	return (1);
14442 }
14443 
14444 
14445 /*
14446  * Register the lock locally within Solaris.
14447  * As the client, we "or" the sysid with LM_SYSID_CLIENT when
14448  * recording locks locally.
14449  *
14450  * This should handle conflicts/cooperation with NFS v2/v3 since all locks
14451  * are registered locally.
14452  */
14453 void
14454 nfs4_register_lock_locally(vnode_t *vp, struct flock64 *flk, int flag,
14455     u_offset_t offset)
14456 {
14457 	int oldsysid;
14458 	int error;
14459 #ifdef DEBUG
14460 	char *name;
14461 #endif
14462 
14463 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14464 
14465 #ifdef DEBUG
14466 	name = fn_name(VTOSV(vp)->sv_name);
14467 	NFS4_DEBUG(nfs4_client_lock_debug,
14468 	    (CE_NOTE, "nfs4_register_lock_locally: %s: type %d, "
14469 	    "start %"PRIx64", length %"PRIx64", pid %ld, sysid %d",
14470 	    name, flk->l_type, flk->l_start, flk->l_len, (long)flk->l_pid,
14471 	    flk->l_sysid));
14472 	kmem_free(name, MAXNAMELEN);
14473 #endif
14474 
14475 	/* register the lock with local locking */
14476 	oldsysid = flk->l_sysid;
14477 	flk->l_sysid |= LM_SYSID_CLIENT;
14478 	error = reclock(vp, flk, SETFLCK, flag, offset, NULL);
14479 #ifdef DEBUG
14480 	if (error != 0) {
14481 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14482 		    "nfs4_register_lock_locally: could not register with"
14483 		    " local locking"));
14484 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14485 		    "error %d, vp 0x%p, pid %d, sysid 0x%x",
14486 		    error, (void *)vp, flk->l_pid, flk->l_sysid));
14487 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14488 		    "type %d off 0x%" PRIx64 " len 0x%" PRIx64,
14489 		    flk->l_type, flk->l_start, flk->l_len));
14490 		(void) reclock(vp, flk, 0, flag, offset, NULL);
14491 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14492 		    "blocked by pid %d sysid 0x%x type %d "
14493 		    "off 0x%" PRIx64 " len 0x%" PRIx64,
14494 		    flk->l_pid, flk->l_sysid, flk->l_type, flk->l_start,
14495 		    flk->l_len));
14496 	}
14497 #endif
14498 	flk->l_sysid = oldsysid;
14499 }
14500 
14501 /*
14502  * nfs4_lockrelease:
14503  *
14504  * Release any locks on the given vnode that are held by the current
14505  * process.  Also removes the lock owner (if one exists) from the rnode's
14506  * list.
14507  */
14508 static int
14509 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14510 {
14511 	flock64_t ld;
14512 	int ret, error;
14513 	rnode4_t *rp;
14514 	nfs4_lock_owner_t *lop;
14515 	nfs4_recov_state_t recov_state;
14516 	mntinfo4_t *mi;
14517 	bool_t possible_orphan = FALSE;
14518 	bool_t recovonly;
14519 
14520 	ASSERT((uintptr_t)vp > KERNELBASE);
14521 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14522 
14523 	rp = VTOR4(vp);
14524 	mi = VTOMI4(vp);
14525 
14526 	/*
14527 	 * If we have not locked anything then we can
14528 	 * just return since we have no work to do.
14529 	 */
14530 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14531 		return (0);
14532 	}
14533 
14534 	/*
14535 	 * We need to comprehend that another thread may
14536 	 * kick off recovery and the lock_owner we have stashed
14537 	 * in lop might be invalid so we should NOT cache it
14538 	 * locally!
14539 	 */
14540 	recov_state.rs_flags = 0;
14541 	recov_state.rs_num_retry_despite_err = 0;
14542 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14543 	    &recovonly);
14544 	if (error) {
14545 		mutex_enter(&rp->r_statelock);
14546 		rp->r_flags |= R4LODANGLERS;
14547 		mutex_exit(&rp->r_statelock);
14548 		return (error);
14549 	}
14550 
14551 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14552 
14553 	/*
14554 	 * Check if the lock owner might have a lock (request was sent but
14555 	 * no response was received).  Also check if there are any remote
14556 	 * locks on the file.  (In theory we shouldn't have to make this
14557 	 * second check if there's no lock owner, but for now we'll be
14558 	 * conservative and do it anyway.)  If either condition is true,
14559 	 * send an unlock for the entire file to the server.
14560 	 *
14561 	 * Note that no explicit synchronization is needed here.  At worst,
14562 	 * flk_has_remote_locks() will return a false positive, in which case
14563 	 * the unlock call wastes time but doesn't harm correctness.
14564 	 */
14565 
14566 	if (lop) {
14567 		mutex_enter(&lop->lo_lock);
14568 		possible_orphan = lop->lo_pending_rqsts;
14569 		mutex_exit(&lop->lo_lock);
14570 		lock_owner_rele(lop);
14571 	}
14572 
14573 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14574 
14575 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14576 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14577 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14578 	    (void *)lop));
14579 
14580 	if (possible_orphan || flk_has_remote_locks(vp)) {
14581 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14582 		ld.l_whence = 0;	/* unlock from start of file */
14583 		ld.l_start = 0;
14584 		ld.l_len = 0;		/* do entire file */
14585 
14586 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL,
14587 		    cr, NULL);
14588 
14589 		if (ret != 0) {
14590 			/*
14591 			 * If VOP_FRLOCK fails, make sure we unregister
14592 			 * local locks before we continue.
14593 			 */
14594 			ld.l_pid = ttoproc(curthread)->p_pid;
14595 			nfs4_register_lock_locally(vp, &ld, flag, offset);
14596 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14597 			    "nfs4_lockrelease: lock release error on vp"
14598 			    " %p: error %d.\n", (void *)vp, ret));
14599 		}
14600 	}
14601 
14602 	recov_state.rs_flags = 0;
14603 	recov_state.rs_num_retry_despite_err = 0;
14604 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14605 	    &recovonly);
14606 	if (error) {
14607 		mutex_enter(&rp->r_statelock);
14608 		rp->r_flags |= R4LODANGLERS;
14609 		mutex_exit(&rp->r_statelock);
14610 		return (error);
14611 	}
14612 
14613 	/*
14614 	 * So, here we're going to need to retrieve the lock-owner
14615 	 * again (in case recovery has done a switch-a-roo) and
14616 	 * remove it because we can.
14617 	 */
14618 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14619 
14620 	if (lop) {
14621 		nfs4_rnode_remove_lock_owner(rp, lop);
14622 		lock_owner_rele(lop);
14623 	}
14624 
14625 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14626 	return (0);
14627 }
14628 
14629 /*
14630  * Wait for 'tick_delay' clock ticks.
14631  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14632  * NOTE: lock_lease_time is in seconds.
14633  *
14634  * XXX For future improvements, should implement a waiting queue scheme.
14635  */
14636 static int
14637 nfs4_block_and_wait(clock_t *tick_delay, rnode4_t *rp)
14638 {
14639 	long milliseconds_delay;
14640 	time_t lock_lease_time;
14641 
14642 	/* wait tick_delay clock ticks or siginteruptus */
14643 	if (delay_sig(*tick_delay)) {
14644 		return (EINTR);
14645 	}
14646 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14647 	    "reissue the lock request: blocked for %ld clock ticks: %ld "
14648 	    "milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14649 
14650 	/* get the lease time */
14651 	lock_lease_time = r2lease_time(rp);
14652 
14653 	/* drv_hztousec converts ticks to microseconds */
14654 	milliseconds_delay = drv_hztousec(*tick_delay) / 1000;
14655 	if (milliseconds_delay < lock_lease_time * 1000) {
14656 		*tick_delay = 2 * *tick_delay;
14657 		if (drv_hztousec(*tick_delay) > lock_lease_time * 1000 * 1000)
14658 			*tick_delay = drv_usectohz(lock_lease_time*1000*1000);
14659 	}
14660 	return (0);
14661 }
14662 
14663 
14664 void
14665 nfs4_vnops_init(void)
14666 {
14667 }
14668 
14669 void
14670 nfs4_vnops_fini(void)
14671 {
14672 }
14673 
14674 /*
14675  * Return a reference to the directory (parent) vnode for a given vnode,
14676  * using the saved pathname information and the directory file handle.  The
14677  * caller is responsible for disposing of the reference.
14678  * Returns zero or an errno value.
14679  *
14680  * Caller should set need_start_op to FALSE if it is the recovery
14681  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14682  */
14683 int
14684 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14685 {
14686 	svnode_t *svnp;
14687 	vnode_t *dvp = NULL;
14688 	servinfo4_t *svp;
14689 	nfs4_fname_t *mfname;
14690 	int error;
14691 
14692 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14693 
14694 	if (vp->v_flag & VROOT) {
14695 		nfs4_sharedfh_t *sfh;
14696 		nfs_fh4 fh;
14697 		mntinfo4_t *mi;
14698 
14699 		ASSERT(vp->v_type == VREG);
14700 
14701 		mi = VTOMI4(vp);
14702 		svp = mi->mi_curr_serv;
14703 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14704 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14705 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14706 		sfh = sfh4_get(&fh, VTOMI4(vp));
14707 		nfs_rw_exit(&svp->sv_lock);
14708 		mfname = mi->mi_fname;
14709 		fn_hold(mfname);
14710 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14711 		sfh4_rele(&sfh);
14712 
14713 		if (dvp->v_type == VNON)
14714 			dvp->v_type = VDIR;
14715 		*dvpp = dvp;
14716 		return (0);
14717 	}
14718 
14719 	svnp = VTOSV(vp);
14720 
14721 	if (svnp == NULL) {
14722 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14723 		    "shadow node is NULL"));
14724 		return (EINVAL);
14725 	}
14726 
14727 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14728 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14729 		    "shadow node name or dfh val == NULL"));
14730 		return (EINVAL);
14731 	}
14732 
14733 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14734 	    (int)need_start_op);
14735 	if (error != 0) {
14736 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14737 		    "nfs4_make_dotdot returned %d", error));
14738 		return (error);
14739 	}
14740 	if (!dvp) {
14741 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14742 		    "nfs4_make_dotdot returned a NULL dvp"));
14743 		return (EIO);
14744 	}
14745 	if (dvp->v_type == VNON)
14746 		dvp->v_type = VDIR;
14747 	ASSERT(dvp->v_type == VDIR);
14748 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14749 		mutex_enter(&dvp->v_lock);
14750 		dvp->v_flag |= V_XATTRDIR;
14751 		mutex_exit(&dvp->v_lock);
14752 	}
14753 	*dvpp = dvp;
14754 	return (0);
14755 }
14756 
14757 /*
14758  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14759  * length that fnamep can accept, including the trailing null.
14760  * Returns 0 if okay, returns an errno value if there was a problem.
14761  */
14762 
14763 int
14764 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14765 {
14766 	char *fn;
14767 	int err = 0;
14768 	servinfo4_t *svp;
14769 	svnode_t *shvp;
14770 
14771 	/*
14772 	 * If the file being opened has VROOT set, then this is
14773 	 * a "file" mount.  sv_name will not be interesting, so
14774 	 * go back to the servinfo4 to get the original mount
14775 	 * path and strip off all but the final edge.  Otherwise
14776 	 * just return the name from the shadow vnode.
14777 	 */
14778 
14779 	if (vp->v_flag & VROOT) {
14780 
14781 		svp = VTOMI4(vp)->mi_curr_serv;
14782 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14783 
14784 		fn = strrchr(svp->sv_path, '/');
14785 		if (fn == NULL)
14786 			err = EINVAL;
14787 		else
14788 			fn++;
14789 	} else {
14790 		shvp = VTOSV(vp);
14791 		fn = fn_name(shvp->sv_name);
14792 	}
14793 
14794 	if (err == 0)
14795 		if (strlen(fn) < maxlen)
14796 			(void) strcpy(fnamep, fn);
14797 		else
14798 			err = ENAMETOOLONG;
14799 
14800 	if (vp->v_flag & VROOT)
14801 		nfs_rw_exit(&svp->sv_lock);
14802 	else
14803 		kmem_free(fn, MAXNAMELEN);
14804 
14805 	return (err);
14806 }
14807 
14808 /*
14809  * Bookkeeping for a close that doesn't need to go over the wire.
14810  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14811  * it is left at 1.
14812  */
14813 void
14814 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14815 {
14816 	rnode4_t		*rp;
14817 	mntinfo4_t		*mi;
14818 
14819 	mi = VTOMI4(vp);
14820 	rp = VTOR4(vp);
14821 
14822 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14823 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14824 	ASSERT(nfs_zone() == mi->mi_zone);
14825 	ASSERT(mutex_owned(&osp->os_sync_lock));
14826 	ASSERT(*have_lockp);
14827 
14828 	if (!osp->os_valid ||
14829 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14830 		return;
14831 	}
14832 
14833 	/*
14834 	 * This removes the reference obtained at OPEN; ie,
14835 	 * when the open stream structure was created.
14836 	 *
14837 	 * We don't have to worry about calling 'open_stream_rele'
14838 	 * since we our currently holding a reference to this
14839 	 * open stream which means the count can not go to 0 with
14840 	 * this decrement.
14841 	 */
14842 	ASSERT(osp->os_ref_count >= 2);
14843 	osp->os_ref_count--;
14844 	osp->os_valid = 0;
14845 	mutex_exit(&osp->os_sync_lock);
14846 	*have_lockp = 0;
14847 
14848 	nfs4_dec_state_ref_count(mi);
14849 }
14850 
14851 /*
14852  * Close all remaining open streams on the rnode.  These open streams
14853  * could be here because:
14854  * - The close attempted at either close or delmap failed
14855  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
14856  * - Someone did mknod on a regular file but never opened it
14857  */
14858 int
14859 nfs4close_all(vnode_t *vp, cred_t *cr)
14860 {
14861 	nfs4_open_stream_t *osp;
14862 	int error;
14863 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
14864 	rnode4_t *rp;
14865 
14866 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14867 
14868 	error = 0;
14869 	rp = VTOR4(vp);
14870 
14871 	/*
14872 	 * At this point, all we know is that the last time
14873 	 * someone called vn_rele, the count was 1.  Since then,
14874 	 * the vnode could have been re-activated.  We want to
14875 	 * loop through the open streams and close each one, but
14876 	 * we have to be careful since once we release the rnode
14877 	 * hash bucket lock, someone else is free to come in and
14878 	 * re-activate the rnode and add new open streams.  The
14879 	 * strategy is take the rnode hash bucket lock, verify that
14880 	 * the count is still 1, grab the open stream off the
14881 	 * head of the list and mark it invalid, then release the
14882 	 * rnode hash bucket lock and proceed with that open stream.
14883 	 * This is ok because nfs4close_one() will acquire the proper
14884 	 * open/create to close/destroy synchronization for open
14885 	 * streams, and will ensure that if someone has reopened
14886 	 * the open stream after we've dropped the hash bucket lock
14887 	 * then we'll just simply return without destroying the
14888 	 * open stream.
14889 	 * Repeat until the list is empty.
14890 	 */
14891 
14892 	for (;;) {
14893 
14894 		/* make sure vnode hasn't been reactivated */
14895 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
14896 		mutex_enter(&vp->v_lock);
14897 		if (vp->v_count > 1) {
14898 			mutex_exit(&vp->v_lock);
14899 			rw_exit(&rp->r_hashq->r_lock);
14900 			break;
14901 		}
14902 		/*
14903 		 * Grabbing r_os_lock before releasing v_lock prevents
14904 		 * a window where the rnode/open stream could get
14905 		 * reactivated (and os_force_close set to 0) before we
14906 		 * had a chance to set os_force_close to 1.
14907 		 */
14908 		mutex_enter(&rp->r_os_lock);
14909 		mutex_exit(&vp->v_lock);
14910 
14911 		osp = list_head(&rp->r_open_streams);
14912 		if (!osp) {
14913 			/* nothing left to CLOSE OTW, so return */
14914 			mutex_exit(&rp->r_os_lock);
14915 			rw_exit(&rp->r_hashq->r_lock);
14916 			break;
14917 		}
14918 
14919 		mutex_enter(&rp->r_statev4_lock);
14920 		/* the file can't still be mem mapped */
14921 		ASSERT(rp->r_mapcnt == 0);
14922 		if (rp->created_v4)
14923 			rp->created_v4 = 0;
14924 		mutex_exit(&rp->r_statev4_lock);
14925 
14926 		/*
14927 		 * Grab a ref on this open stream; nfs4close_one
14928 		 * will mark it as invalid
14929 		 */
14930 		mutex_enter(&osp->os_sync_lock);
14931 		osp->os_ref_count++;
14932 		osp->os_force_close = 1;
14933 		mutex_exit(&osp->os_sync_lock);
14934 		mutex_exit(&rp->r_os_lock);
14935 		rw_exit(&rp->r_hashq->r_lock);
14936 
14937 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
14938 
14939 		/* Update error if it isn't already non-zero */
14940 		if (error == 0) {
14941 			if (e.error)
14942 				error = e.error;
14943 			else if (e.stat)
14944 				error = geterrno4(e.stat);
14945 		}
14946 
14947 #ifdef	DEBUG
14948 		nfs4close_all_cnt++;
14949 #endif
14950 		/* Release the ref on osp acquired above. */
14951 		open_stream_rele(osp, rp);
14952 
14953 		/* Proceed to the next open stream, if any */
14954 	}
14955 	return (error);
14956 }
14957 
14958 /*
14959  * nfs4close_one - close one open stream for a file if needed.
14960  *
14961  * "close_type" indicates which close path this is:
14962  * CLOSE_NORM: close initiated via VOP_CLOSE.
14963  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
14964  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
14965  *	the close and release of client state for this open stream
14966  *	(unless someone else has the open stream open).
14967  * CLOSE_RESEND: indicates the request is a replay of an earlier request
14968  *	(e.g., due to abort because of a signal).
14969  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
14970  *
14971  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
14972  * recovery.  Instead, the caller is expected to deal with retries.
14973  *
14974  * The caller can either pass in the osp ('provided_osp') or not.
14975  *
14976  * 'access_bits' represents the access we are closing/downgrading.
14977  *
14978  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
14979  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
14980  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
14981  *
14982  * Errors are returned via the nfs4_error_t.
14983  */
14984 void
14985 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
14986     int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
14987     nfs4_close_type_t close_type, size_t len, uint_t maxprot,
14988     uint_t mmap_flags)
14989 {
14990 	nfs4_open_owner_t *oop;
14991 	nfs4_open_stream_t *osp = NULL;
14992 	int retry = 0;
14993 	int num_retries = NFS4_NUM_RECOV_RETRIES;
14994 	rnode4_t *rp;
14995 	mntinfo4_t *mi;
14996 	nfs4_recov_state_t recov_state;
14997 	cred_t *cred_otw = NULL;
14998 	bool_t recovonly = FALSE;
14999 	int isrecov;
15000 	int force_close;
15001 	int close_failed = 0;
15002 	int did_dec_count = 0;
15003 	int did_start_op = 0;
15004 	int did_force_recovlock = 0;
15005 	int did_start_seqid_sync = 0;
15006 	int have_sync_lock = 0;
15007 
15008 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15009 
15010 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
15011 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
15012 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
15013 	    len, maxprot, mmap_flags, access_bits));
15014 
15015 	nfs4_error_zinit(ep);
15016 	rp = VTOR4(vp);
15017 	mi = VTOMI4(vp);
15018 	isrecov = (close_type == CLOSE_RESEND ||
15019 	    close_type == CLOSE_AFTER_RESEND);
15020 
15021 	/*
15022 	 * First get the open owner.
15023 	 */
15024 	if (!provided_osp) {
15025 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
15026 	} else {
15027 		oop = provided_osp->os_open_owner;
15028 		ASSERT(oop != NULL);
15029 		open_owner_hold(oop);
15030 	}
15031 
15032 	if (!oop) {
15033 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15034 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15035 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15036 		    (void *)provided_osp, close_type));
15037 		ep->error = EIO;
15038 		goto out;
15039 	}
15040 
15041 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15042 recov_retry:
15043 	osp = NULL;
15044 	close_failed = 0;
15045 	force_close = (close_type == CLOSE_FORCE);
15046 	retry = 0;
15047 	did_start_op = 0;
15048 	did_force_recovlock = 0;
15049 	did_start_seqid_sync = 0;
15050 	have_sync_lock = 0;
15051 	recovonly = FALSE;
15052 	recov_state.rs_flags = 0;
15053 	recov_state.rs_num_retry_despite_err = 0;
15054 
15055 	/*
15056 	 * Second synchronize with recovery.
15057 	 */
15058 	if (!isrecov) {
15059 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15060 		    &recov_state, &recovonly);
15061 		if (!ep->error) {
15062 			did_start_op = 1;
15063 		} else {
15064 			close_failed = 1;
15065 			/*
15066 			 * If we couldn't get start_fop, but have to
15067 			 * cleanup state, then at least acquire the
15068 			 * mi_recovlock so we can synchronize with
15069 			 * recovery.
15070 			 */
15071 			if (close_type == CLOSE_FORCE) {
15072 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15073 				    RW_READER, FALSE);
15074 				did_force_recovlock = 1;
15075 			} else
15076 				goto out;
15077 		}
15078 	}
15079 
15080 	/*
15081 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15082 	 * set 'recovonly' to TRUE since most likely this is due to
15083 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15084 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15085 	 * to retry, causing us to loop until recovery finishes.  Plus we
15086 	 * don't need protection over the open seqid since we're not going
15087 	 * OTW, hence don't need to use the seqid.
15088 	 */
15089 	if (recovonly == FALSE) {
15090 		/* need to grab the open owner sync before 'os_sync_lock' */
15091 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15092 		if (ep->error == EAGAIN) {
15093 			ASSERT(!isrecov);
15094 			if (did_start_op)
15095 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15096 				    &recov_state, TRUE);
15097 			if (did_force_recovlock)
15098 				nfs_rw_exit(&mi->mi_recovlock);
15099 			goto recov_retry;
15100 		}
15101 		did_start_seqid_sync = 1;
15102 	}
15103 
15104 	/*
15105 	 * Third get an open stream and acquire 'os_sync_lock' to
15106 	 * sychronize the opening/creating of an open stream with the
15107 	 * closing/destroying of an open stream.
15108 	 */
15109 	if (!provided_osp) {
15110 		/* returns with 'os_sync_lock' held */
15111 		osp = find_open_stream(oop, rp);
15112 		if (!osp) {
15113 			ep->error = EIO;
15114 			goto out;
15115 		}
15116 	} else {
15117 		osp = provided_osp;
15118 		open_stream_hold(osp);
15119 		mutex_enter(&osp->os_sync_lock);
15120 	}
15121 	have_sync_lock = 1;
15122 
15123 	ASSERT(oop == osp->os_open_owner);
15124 
15125 	/*
15126 	 * Fourth, do any special pre-OTW CLOSE processing
15127 	 * based on the specific close type.
15128 	 */
15129 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15130 	    !did_dec_count) {
15131 		ASSERT(osp->os_open_ref_count > 0);
15132 		osp->os_open_ref_count--;
15133 		did_dec_count = 1;
15134 		if (osp->os_open_ref_count == 0)
15135 			osp->os_final_close = 1;
15136 	}
15137 
15138 	if (close_type == CLOSE_FORCE) {
15139 		/* see if somebody reopened the open stream. */
15140 		if (!osp->os_force_close) {
15141 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15142 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15143 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15144 			ep->error = 0;
15145 			ep->stat = NFS4_OK;
15146 			goto out;
15147 		}
15148 
15149 		if (!osp->os_final_close && !did_dec_count) {
15150 			osp->os_open_ref_count--;
15151 			did_dec_count = 1;
15152 		}
15153 
15154 		/*
15155 		 * We can't depend on os_open_ref_count being 0 due to the
15156 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15157 		 */
15158 #ifdef	NOTYET
15159 		ASSERT(osp->os_open_ref_count == 0);
15160 #endif
15161 		if (osp->os_open_ref_count != 0) {
15162 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15163 			    "nfs4close_one: should panic here on an "
15164 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15165 			    "since this is probably the exec problem."));
15166 
15167 			osp->os_open_ref_count = 0;
15168 		}
15169 
15170 		/*
15171 		 * There is the possibility that nfs4close_one()
15172 		 * for close_type == CLOSE_DELMAP couldn't find the
15173 		 * open stream, thus couldn't decrement its os_mapcnt;
15174 		 * therefore we can't use this ASSERT yet.
15175 		 */
15176 #ifdef	NOTYET
15177 		ASSERT(osp->os_mapcnt == 0);
15178 #endif
15179 		osp->os_mapcnt = 0;
15180 	}
15181 
15182 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15183 		ASSERT(osp->os_mapcnt >= btopr(len));
15184 
15185 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15186 			osp->os_mmap_write -= btopr(len);
15187 		if (maxprot & PROT_READ)
15188 			osp->os_mmap_read -= btopr(len);
15189 		if (maxprot & PROT_EXEC)
15190 			osp->os_mmap_read -= btopr(len);
15191 		/* mirror the PROT_NONE check in nfs4_addmap() */
15192 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15193 		    !(maxprot & PROT_EXEC))
15194 			osp->os_mmap_read -= btopr(len);
15195 		osp->os_mapcnt -= btopr(len);
15196 		did_dec_count = 1;
15197 	}
15198 
15199 	if (recovonly) {
15200 		nfs4_lost_rqst_t lost_rqst;
15201 
15202 		/* request should not already be in recovery queue */
15203 		ASSERT(lrp == NULL);
15204 		nfs4_error_init(ep, EINTR);
15205 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15206 		    osp, cred_otw, vp);
15207 		mutex_exit(&osp->os_sync_lock);
15208 		have_sync_lock = 0;
15209 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15210 		    lost_rqst.lr_op == OP_CLOSE ?
15211 		    &lost_rqst : NULL, OP_CLOSE, NULL);
15212 		close_failed = 1;
15213 		force_close = 0;
15214 		goto close_cleanup;
15215 	}
15216 
15217 	/*
15218 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15219 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15220 	 * space, which means we stopped operating on the open stream
15221 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15222 	 * stateid could be stale, potentially triggering a false
15223 	 * setclientid), and just clean up the client's internal state.
15224 	 */
15225 	if (osp->os_orig_oo_name != oop->oo_name) {
15226 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15227 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15228 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15229 		    "oo_name %" PRIx64")",
15230 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15231 		    oop->oo_name));
15232 		close_failed = 1;
15233 	}
15234 
15235 	/* If the file failed recovery, just quit. */
15236 	mutex_enter(&rp->r_statelock);
15237 	if (rp->r_flags & R4RECOVERR) {
15238 		close_failed = 1;
15239 	}
15240 	mutex_exit(&rp->r_statelock);
15241 
15242 	/*
15243 	 * If the force close path failed to obtain start_fop
15244 	 * then skip the OTW close and just remove the state.
15245 	 */
15246 	if (close_failed)
15247 		goto close_cleanup;
15248 
15249 	/*
15250 	 * Fifth, check to see if there are still mapped pages or other
15251 	 * opens using this open stream.  If there are then we can't
15252 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15253 	 */
15254 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15255 		nfs4_lost_rqst_t	new_lost_rqst;
15256 		bool_t			needrecov = FALSE;
15257 		cred_t			*odg_cred_otw = NULL;
15258 		seqid4			open_dg_seqid = 0;
15259 
15260 		if (osp->os_delegation) {
15261 			/*
15262 			 * If this open stream was never OPENed OTW then we
15263 			 * surely can't DOWNGRADE it (especially since the
15264 			 * osp->open_stateid is really a delegation stateid
15265 			 * when os_delegation is 1).
15266 			 */
15267 			if (access_bits & FREAD)
15268 				osp->os_share_acc_read--;
15269 			if (access_bits & FWRITE)
15270 				osp->os_share_acc_write--;
15271 			osp->os_share_deny_none--;
15272 			nfs4_error_zinit(ep);
15273 			goto out;
15274 		}
15275 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15276 		    lrp, ep, &odg_cred_otw, &open_dg_seqid);
15277 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15278 		if (needrecov && !isrecov) {
15279 			bool_t abort;
15280 			nfs4_bseqid_entry_t *bsep = NULL;
15281 
15282 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15283 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15284 				    vp, 0,
15285 				    lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15286 				    open_dg_seqid);
15287 
15288 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15289 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15290 			mutex_exit(&osp->os_sync_lock);
15291 			have_sync_lock = 0;
15292 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15293 			    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15294 			    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15295 			    bsep);
15296 			if (odg_cred_otw)
15297 				crfree(odg_cred_otw);
15298 			if (bsep)
15299 				kmem_free(bsep, sizeof (*bsep));
15300 
15301 			if (abort == TRUE)
15302 				goto out;
15303 
15304 			if (did_start_seqid_sync) {
15305 				nfs4_end_open_seqid_sync(oop);
15306 				did_start_seqid_sync = 0;
15307 			}
15308 			open_stream_rele(osp, rp);
15309 
15310 			if (did_start_op)
15311 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15312 				    &recov_state, FALSE);
15313 			if (did_force_recovlock)
15314 				nfs_rw_exit(&mi->mi_recovlock);
15315 
15316 			goto recov_retry;
15317 		} else {
15318 			if (odg_cred_otw)
15319 				crfree(odg_cred_otw);
15320 		}
15321 		goto out;
15322 	}
15323 
15324 	/*
15325 	 * If this open stream was created as the results of an open
15326 	 * while holding a delegation, then just release it; no need
15327 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15328 	 */
15329 	if (osp->os_delegation) {
15330 		nfs4close_notw(vp, osp, &have_sync_lock);
15331 		nfs4_error_zinit(ep);
15332 		goto out;
15333 	}
15334 
15335 	/*
15336 	 * If this stream is not valid, we're done.
15337 	 */
15338 	if (!osp->os_valid) {
15339 		nfs4_error_zinit(ep);
15340 		goto out;
15341 	}
15342 
15343 	/*
15344 	 * Last open or mmap ref has vanished, need to do an OTW close.
15345 	 * First check to see if a close is still necessary.
15346 	 */
15347 	if (osp->os_failed_reopen) {
15348 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15349 		    "don't close OTW osp %p since reopen failed.",
15350 		    (void *)osp));
15351 		/*
15352 		 * Reopen of the open stream failed, hence the
15353 		 * stateid of the open stream is invalid/stale, and
15354 		 * sending this OTW would incorrectly cause another
15355 		 * round of recovery.  In this case, we need to set
15356 		 * the 'os_valid' bit to 0 so another thread doesn't
15357 		 * come in and re-open this open stream before
15358 		 * this "closing" thread cleans up state (decrementing
15359 		 * the nfs4_server_t's state_ref_count and decrementing
15360 		 * the os_ref_count).
15361 		 */
15362 		osp->os_valid = 0;
15363 		/*
15364 		 * This removes the reference obtained at OPEN; ie,
15365 		 * when the open stream structure was created.
15366 		 *
15367 		 * We don't have to worry about calling 'open_stream_rele'
15368 		 * since we our currently holding a reference to this
15369 		 * open stream which means the count can not go to 0 with
15370 		 * this decrement.
15371 		 */
15372 		ASSERT(osp->os_ref_count >= 2);
15373 		osp->os_ref_count--;
15374 		nfs4_error_zinit(ep);
15375 		close_failed = 0;
15376 		goto close_cleanup;
15377 	}
15378 
15379 	ASSERT(osp->os_ref_count > 1);
15380 
15381 	/*
15382 	 * Sixth, try the CLOSE OTW.
15383 	 */
15384 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15385 	    close_type, ep, &have_sync_lock);
15386 
15387 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15388 		/*
15389 		 * Let the recovery thread be responsible for
15390 		 * removing the state for CLOSE.
15391 		 */
15392 		close_failed = 1;
15393 		force_close = 0;
15394 		retry = 0;
15395 	}
15396 
15397 	/* See if we need to retry with a different cred */
15398 	if ((ep->error == EACCES ||
15399 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15400 	    cred_otw != cr) {
15401 		crfree(cred_otw);
15402 		cred_otw = cr;
15403 		crhold(cred_otw);
15404 		retry = 1;
15405 	}
15406 
15407 	if (ep->error || ep->stat)
15408 		close_failed = 1;
15409 
15410 	if (retry && !isrecov && num_retries-- > 0) {
15411 		if (have_sync_lock) {
15412 			mutex_exit(&osp->os_sync_lock);
15413 			have_sync_lock = 0;
15414 		}
15415 		if (did_start_seqid_sync) {
15416 			nfs4_end_open_seqid_sync(oop);
15417 			did_start_seqid_sync = 0;
15418 		}
15419 		open_stream_rele(osp, rp);
15420 
15421 		if (did_start_op)
15422 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15423 			    &recov_state, FALSE);
15424 		if (did_force_recovlock)
15425 			nfs_rw_exit(&mi->mi_recovlock);
15426 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15427 		    "nfs4close_one: need to retry the close "
15428 		    "operation"));
15429 		goto recov_retry;
15430 	}
15431 close_cleanup:
15432 	/*
15433 	 * Seventh and lastly, process our results.
15434 	 */
15435 	if (close_failed && force_close) {
15436 		/*
15437 		 * It's ok to drop and regrab the 'os_sync_lock' since
15438 		 * nfs4close_notw() will recheck to make sure the
15439 		 * "close"/removal of state should happen.
15440 		 */
15441 		if (!have_sync_lock) {
15442 			mutex_enter(&osp->os_sync_lock);
15443 			have_sync_lock = 1;
15444 		}
15445 		/*
15446 		 * This is last call, remove the ref on the open
15447 		 * stream created by open and clean everything up.
15448 		 */
15449 		osp->os_pending_close = 0;
15450 		nfs4close_notw(vp, osp, &have_sync_lock);
15451 		nfs4_error_zinit(ep);
15452 	}
15453 
15454 	if (!close_failed) {
15455 		if (have_sync_lock) {
15456 			osp->os_pending_close = 0;
15457 			mutex_exit(&osp->os_sync_lock);
15458 			have_sync_lock = 0;
15459 		} else {
15460 			mutex_enter(&osp->os_sync_lock);
15461 			osp->os_pending_close = 0;
15462 			mutex_exit(&osp->os_sync_lock);
15463 		}
15464 		if (did_start_op && recov_state.rs_sp != NULL) {
15465 			mutex_enter(&recov_state.rs_sp->s_lock);
15466 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15467 			mutex_exit(&recov_state.rs_sp->s_lock);
15468 		} else {
15469 			nfs4_dec_state_ref_count(mi);
15470 		}
15471 		nfs4_error_zinit(ep);
15472 	}
15473 
15474 out:
15475 	if (have_sync_lock)
15476 		mutex_exit(&osp->os_sync_lock);
15477 	if (did_start_op)
15478 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15479 		    recovonly ? TRUE : FALSE);
15480 	if (did_force_recovlock)
15481 		nfs_rw_exit(&mi->mi_recovlock);
15482 	if (cred_otw)
15483 		crfree(cred_otw);
15484 	if (osp)
15485 		open_stream_rele(osp, rp);
15486 	if (oop) {
15487 		if (did_start_seqid_sync)
15488 			nfs4_end_open_seqid_sync(oop);
15489 		open_owner_rele(oop);
15490 	}
15491 }
15492 
15493 /*
15494  * Convert information returned by the server in the LOCK4denied
15495  * structure to the form required by fcntl.
15496  */
15497 static void
15498 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15499 {
15500 	nfs4_lo_name_t *lo;
15501 
15502 #ifdef	DEBUG
15503 	if (denied_to_flk_debug) {
15504 		lockt_denied_debug = lockt_denied;
15505 		debug_enter("lockt_denied");
15506 	}
15507 #endif
15508 
15509 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15510 	flk->l_whence = 0;	/* aka SEEK_SET */
15511 	flk->l_start = lockt_denied->offset;
15512 	flk->l_len = lockt_denied->length;
15513 
15514 	/*
15515 	 * If the blocking clientid matches our client id, then we can
15516 	 * interpret the lockowner (since we built it).  If not, then
15517 	 * fabricate a sysid and pid.  Note that the l_sysid field
15518 	 * in *flk already has the local sysid.
15519 	 */
15520 
15521 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15522 
15523 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15524 			lo = (nfs4_lo_name_t *)
15525 			    lockt_denied->owner.owner_val;
15526 
15527 			flk->l_pid = lo->ln_pid;
15528 		} else {
15529 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15530 			    "denied_to_flk: bad lock owner length\n"));
15531 
15532 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15533 		}
15534 	} else {
15535 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15536 		"denied_to_flk: foreign clientid\n"));
15537 
15538 		/*
15539 		 * Construct a new sysid which should be different from
15540 		 * sysids of other systems.
15541 		 */
15542 
15543 		flk->l_sysid++;
15544 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15545 	}
15546 }
15547 
15548 static pid_t
15549 lo_to_pid(lock_owner4 *lop)
15550 {
15551 	pid_t pid = 0;
15552 	uchar_t *cp;
15553 	int i;
15554 
15555 	cp = (uchar_t *)&lop->clientid;
15556 
15557 	for (i = 0; i < sizeof (lop->clientid); i++)
15558 		pid += (pid_t)*cp++;
15559 
15560 	cp = (uchar_t *)lop->owner_val;
15561 
15562 	for (i = 0; i < lop->owner_len; i++)
15563 		pid += (pid_t)*cp++;
15564 
15565 	return (pid);
15566 }
15567 
15568 /*
15569  * Given a lock pointer, returns the length of that lock.
15570  * "end" is the last locked offset the "l_len" covers from
15571  * the start of the lock.
15572  */
15573 static off64_t
15574 lock_to_end(flock64_t *lock)
15575 {
15576 	off64_t lock_end;
15577 
15578 	if (lock->l_len == 0)
15579 		lock_end = (off64_t)MAXEND;
15580 	else
15581 		lock_end = lock->l_start + lock->l_len - 1;
15582 
15583 	return (lock_end);
15584 }
15585 
15586 /*
15587  * Given the end of a lock, it will return you the length "l_len" for that lock.
15588  */
15589 static off64_t
15590 end_to_len(off64_t start, off64_t end)
15591 {
15592 	off64_t lock_len;
15593 
15594 	ASSERT(end >= start);
15595 	if (end == MAXEND)
15596 		lock_len = 0;
15597 	else
15598 		lock_len = end - start + 1;
15599 
15600 	return (lock_len);
15601 }
15602 
15603 /*
15604  * On given end for a lock it determines if it is the last locked offset
15605  * or not, if so keeps it as is, else adds one to return the length for
15606  * valid start.
15607  */
15608 static off64_t
15609 start_check(off64_t x)
15610 {
15611 	if (x == MAXEND)
15612 		return (x);
15613 	else
15614 		return (x + 1);
15615 }
15616 
15617 /*
15618  * See if these two locks overlap, and if so return 1;
15619  * otherwise, return 0.
15620  */
15621 static int
15622 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15623 {
15624 	off64_t llfp_end, curfp_end;
15625 
15626 	llfp_end = lock_to_end(llfp);
15627 	curfp_end = lock_to_end(curfp);
15628 
15629 	if (((llfp_end >= curfp->l_start) &&
15630 	    (llfp->l_start <= curfp->l_start)) ||
15631 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15632 		return (1);
15633 	return (0);
15634 }
15635 
15636 /*
15637  * Determine what the intersecting lock region is, and add that to the
15638  * 'nl_llpp' locklist in increasing order (by l_start).
15639  */
15640 static void
15641 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15642     locklist_t **nl_llpp, vnode_t *vp)
15643 {
15644 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15645 	off64_t lost_flp_end, local_flp_end, len, start;
15646 
15647 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15648 
15649 	if (!locks_intersect(lost_flp, local_flp))
15650 		return;
15651 
15652 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15653 	    "locks intersect"));
15654 
15655 	lost_flp_end = lock_to_end(lost_flp);
15656 	local_flp_end = lock_to_end(local_flp);
15657 
15658 	/* Find the starting point of the intersecting region */
15659 	if (local_flp->l_start > lost_flp->l_start)
15660 		start = local_flp->l_start;
15661 	else
15662 		start = lost_flp->l_start;
15663 
15664 	/* Find the lenght of the intersecting region */
15665 	if (lost_flp_end < local_flp_end)
15666 		len = end_to_len(start, lost_flp_end);
15667 	else
15668 		len = end_to_len(start, local_flp_end);
15669 
15670 	/*
15671 	 * Prepare the flock structure for the intersection found and insert
15672 	 * it into the new list in increasing l_start order. This list contains
15673 	 * intersections of locks registered by the client with the local host
15674 	 * and the lost lock.
15675 	 * The lock type of this lock is the same as that of the local_flp.
15676 	 */
15677 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15678 	intersect_llp->ll_flock.l_start = start;
15679 	intersect_llp->ll_flock.l_len = len;
15680 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15681 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15682 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15683 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15684 	intersect_llp->ll_vp = vp;
15685 
15686 	tmp_fllp = *nl_llpp;
15687 	cur_fllp = NULL;
15688 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15689 	    intersect_llp->ll_flock.l_start) {
15690 			cur_fllp = tmp_fllp;
15691 			tmp_fllp = tmp_fllp->ll_next;
15692 	}
15693 	if (cur_fllp == NULL) {
15694 		/* first on the list */
15695 		intersect_llp->ll_next = *nl_llpp;
15696 		*nl_llpp = intersect_llp;
15697 	} else {
15698 		intersect_llp->ll_next = cur_fllp->ll_next;
15699 		cur_fllp->ll_next = intersect_llp;
15700 	}
15701 
15702 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15703 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15704 	    intersect_llp->ll_flock.l_start,
15705 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15706 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15707 }
15708 
15709 /*
15710  * Our local locking current state is potentially different than
15711  * what the NFSv4 server thinks we have due to a lost lock that was
15712  * resent and then received.  We need to reset our "NFSv4" locking
15713  * state to match the current local locking state for this pid since
15714  * that is what the user/application sees as what the world is.
15715  *
15716  * We cannot afford to drop the open/lock seqid sync since then we can
15717  * get confused about what the current local locking state "is" versus
15718  * "was".
15719  *
15720  * If we are unable to fix up the locks, we send SIGLOST to the affected
15721  * process.  This is not done if the filesystem has been forcibly
15722  * unmounted, in case the process has already exited and a new process
15723  * exists with the same pid.
15724  */
15725 static void
15726 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15727     nfs4_lock_owner_t *lop)
15728 {
15729 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15730 	mntinfo4_t *mi = VTOMI4(vp);
15731 	const int cmd = F_SETLK;
15732 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15733 	flock64_t ul_fl;
15734 
15735 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15736 	    "nfs4_reinstitute_local_lock_state"));
15737 
15738 	/*
15739 	 * Find active locks for this vp from the local locking code.
15740 	 * Scan through this list and find out the locks that intersect with
15741 	 * the lost lock. Once we find the lock that intersects, add the
15742 	 * intersection area as a new lock to a new list "ri_llp". The lock
15743 	 * type of the intersection region lock added to ri_llp is the same
15744 	 * as that found in the active lock list, "list". The intersecting
15745 	 * region locks are added to ri_llp in increasing l_start order.
15746 	 */
15747 	ASSERT(nfs_zone() == mi->mi_zone);
15748 
15749 	locks = flk_active_locks_for_vp(vp);
15750 	ri_llp = NULL;
15751 
15752 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15753 		ASSERT(llp->ll_vp == vp);
15754 		/*
15755 		 * Pick locks that belong to this pid/lockowner
15756 		 */
15757 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15758 			continue;
15759 
15760 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15761 	}
15762 
15763 	/*
15764 	 * Now we have the list of intersections with the lost lock. These are
15765 	 * the locks that were/are active before the server replied to the
15766 	 * last/lost lock. Issue these locks to the server here. Playing these
15767 	 * locks to the server will re-establish aur current local locking state
15768 	 * with the v4 server.
15769 	 * If we get an error, send SIGLOST to the application for that lock.
15770 	 */
15771 
15772 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15773 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15774 		    "nfs4_reinstitute_local_lock_state: need to issue "
15775 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15776 		    llp->ll_flock.l_start,
15777 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15778 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15779 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15780 		/*
15781 		 * No need to relock what we already have
15782 		 */
15783 		if (llp->ll_flock.l_type == lost_flp->l_type)
15784 			continue;
15785 
15786 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15787 	}
15788 
15789 	/*
15790 	 * Now keeping the start of the lost lock as our reference parse the
15791 	 * newly created ri_llp locklist to find the ranges that we have locked
15792 	 * with the v4 server but not in the current local locking. We need
15793 	 * to unlock these ranges.
15794 	 * These ranges can also be reffered to as those ranges, where the lost
15795 	 * lock does not overlap with the locks in the ri_llp but are locked
15796 	 * since the server replied to the lost lock.
15797 	 */
15798 	cur_start = lost_flp->l_start;
15799 	lost_flp_end = lock_to_end(lost_flp);
15800 
15801 	ul_fl.l_type = F_UNLCK;
15802 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15803 	ul_fl.l_sysid = lost_flp->l_sysid;
15804 	ul_fl.l_pid = lost_flp->l_pid;
15805 
15806 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15807 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15808 
15809 		if (llp->ll_flock.l_start <= cur_start) {
15810 			cur_start = start_check(llp_ll_flock_end);
15811 			continue;
15812 		}
15813 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15814 		    "nfs4_reinstitute_local_lock_state: "
15815 		    "UNLOCK [%"PRIx64" - %"PRIx64"]",
15816 		    cur_start, llp->ll_flock.l_start));
15817 
15818 		ul_fl.l_start = cur_start;
15819 		ul_fl.l_len = end_to_len(cur_start,
15820 		    (llp->ll_flock.l_start - 1));
15821 
15822 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15823 		cur_start = start_check(llp_ll_flock_end);
15824 	}
15825 
15826 	/*
15827 	 * In the case where the lost lock ends after all intersecting locks,
15828 	 * unlock the last part of the lost lock range.
15829 	 */
15830 	if (cur_start != start_check(lost_flp_end)) {
15831 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15832 		    "nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15833 		    "lost lock region [%"PRIx64" - %"PRIx64"]",
15834 		    cur_start, lost_flp->l_start + lost_flp->l_len));
15835 
15836 		ul_fl.l_start = cur_start;
15837 		/*
15838 		 * Is it an to-EOF lock? if so unlock till the end
15839 		 */
15840 		if (lost_flp->l_len == 0)
15841 			ul_fl.l_len = 0;
15842 		else
15843 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15844 
15845 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15846 	}
15847 
15848 	if (locks != NULL)
15849 		flk_free_locklist(locks);
15850 
15851 	/* Free up our newly created locklist */
15852 	for (llp = ri_llp; llp != NULL; ) {
15853 		tmp_llp = llp->ll_next;
15854 		kmem_free(llp, sizeof (locklist_t));
15855 		llp = tmp_llp;
15856 	}
15857 
15858 	/*
15859 	 * Now return back to the original calling nfs4frlock()
15860 	 * and let us naturally drop our seqid syncs.
15861 	 */
15862 }
15863 
15864 /*
15865  * Create a lost state record for the given lock reinstantiation request
15866  * and push it onto the lost state queue.
15867  */
15868 static void
15869 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
15870     nfs4_lock_owner_t *lop)
15871 {
15872 	nfs4_lost_rqst_t req;
15873 	nfs_lock_type4 locktype;
15874 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
15875 
15876 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15877 
15878 	locktype = flk_to_locktype(cmd, flk->l_type);
15879 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
15880 	    NULL, NULL, lop, flk, &req, cr, vp);
15881 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
15882 	    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
15883 	    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
15884 	    NULL);
15885 }
15886