xref: /illumos-gate/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision 6dc7d057)
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 /*
23  * Copyright (c) 2016 STRATO AG. All rights reserved.
24  */
25 
26 /*
27  * Copyright 2015 Nexenta Systems, Inc.  All rights reserved.
28  */
29 
30 /*
31  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
32  * Use is subject to license terms.
33  */
34 
35 /*
36  *	Copyright 1983,1984,1985,1986,1987,1988,1989 AT&T.
37  *	All Rights Reserved
38  */
39 
40 /*
41  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
42  */
43 
44 #include <sys/param.h>
45 #include <sys/types.h>
46 #include <sys/systm.h>
47 #include <sys/cred.h>
48 #include <sys/time.h>
49 #include <sys/vnode.h>
50 #include <sys/vfs.h>
51 #include <sys/vfs_opreg.h>
52 #include <sys/file.h>
53 #include <sys/filio.h>
54 #include <sys/uio.h>
55 #include <sys/buf.h>
56 #include <sys/mman.h>
57 #include <sys/pathname.h>
58 #include <sys/dirent.h>
59 #include <sys/debug.h>
60 #include <sys/vmsystm.h>
61 #include <sys/fcntl.h>
62 #include <sys/flock.h>
63 #include <sys/swap.h>
64 #include <sys/errno.h>
65 #include <sys/strsubr.h>
66 #include <sys/sysmacros.h>
67 #include <sys/kmem.h>
68 #include <sys/cmn_err.h>
69 #include <sys/pathconf.h>
70 #include <sys/utsname.h>
71 #include <sys/dnlc.h>
72 #include <sys/acl.h>
73 #include <sys/systeminfo.h>
74 #include <sys/policy.h>
75 #include <sys/sdt.h>
76 #include <sys/list.h>
77 #include <sys/stat.h>
78 #include <sys/zone.h>
79 
80 #include <rpc/types.h>
81 #include <rpc/auth.h>
82 #include <rpc/clnt.h>
83 
84 #include <nfs/nfs.h>
85 #include <nfs/nfs_clnt.h>
86 #include <nfs/nfs_acl.h>
87 #include <nfs/lm.h>
88 #include <nfs/nfs4.h>
89 #include <nfs/nfs4_kprot.h>
90 #include <nfs/rnode4.h>
91 #include <nfs/nfs4_clnt.h>
92 
93 #include <vm/hat.h>
94 #include <vm/as.h>
95 #include <vm/page.h>
96 #include <vm/pvn.h>
97 #include <vm/seg.h>
98 #include <vm/seg_map.h>
99 #include <vm/seg_kpm.h>
100 #include <vm/seg_vn.h>
101 
102 #include <fs/fs_subr.h>
103 
104 #include <sys/ddi.h>
105 #include <sys/int_fmtio.h>
106 #include <sys/fs/autofs.h>
107 
108 typedef struct {
109 	nfs4_ga_res_t	*di_garp;
110 	cred_t		*di_cred;
111 	hrtime_t	di_time_call;
112 } dirattr_info_t;
113 
114 typedef enum nfs4_acl_op {
115 	NFS4_ACL_GET,
116 	NFS4_ACL_SET
117 } nfs4_acl_op_t;
118 
119 static struct lm_sysid *nfs4_find_sysid(mntinfo4_t *);
120 
121 static void	nfs4_update_dircaches(change_info4 *, vnode_t *, vnode_t *,
122 			char *, dirattr_info_t *);
123 
124 static void	nfs4close_otw(rnode4_t *, cred_t *, nfs4_open_owner_t *,
125 		    nfs4_open_stream_t *, int *, int *, nfs4_close_type_t,
126 		    nfs4_error_t *, int *);
127 static int	nfs4_rdwrlbn(vnode_t *, page_t *, u_offset_t, size_t, int,
128 			cred_t *);
129 static int	nfs4write(vnode_t *, caddr_t, u_offset_t, int, cred_t *,
130 			stable_how4 *);
131 static int	nfs4read(vnode_t *, caddr_t, offset_t, int, size_t *,
132 			cred_t *, bool_t, struct uio *);
133 static int	nfs4setattr(vnode_t *, struct vattr *, int, cred_t *,
134 			vsecattr_t *);
135 static int	nfs4openattr(vnode_t *, vnode_t **, int, cred_t *);
136 static int	nfs4lookup(vnode_t *, char *, vnode_t **, cred_t *, int);
137 static int	nfs4lookup_xattr(vnode_t *, char *, vnode_t **, int, cred_t *);
138 static int	nfs4lookupvalidate_otw(vnode_t *, char *, vnode_t **, cred_t *);
139 static int	nfs4lookupnew_otw(vnode_t *, char *, vnode_t **, cred_t *);
140 static int	nfs4mknod(vnode_t *, char *, struct vattr *, enum vcexcl,
141 			int, vnode_t **, cred_t *);
142 static int	nfs4open_otw(vnode_t *, char *, struct vattr *, vnode_t **,
143 			cred_t *, int, int, enum createmode4, int);
144 static int	nfs4rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
145 			caller_context_t *);
146 static int	nfs4rename_persistent_fh(vnode_t *, char *, vnode_t *,
147 			vnode_t *, char *, cred_t *, nfsstat4 *);
148 static int	nfs4rename_volatile_fh(vnode_t *, char *, vnode_t *,
149 			vnode_t *, char *, cred_t *, nfsstat4 *);
150 static int	do_nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
151 static void	nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
152 static int	nfs4_bio(struct buf *, stable_how4 *, cred_t *, bool_t);
153 static int	nfs4_getapage(vnode_t *, u_offset_t, size_t, uint_t *,
154 			page_t *[], size_t, struct seg *, caddr_t,
155 			enum seg_rw, cred_t *);
156 static void	nfs4_readahead(vnode_t *, u_offset_t, caddr_t, struct seg *,
157 			cred_t *);
158 static int	nfs4_sync_putapage(vnode_t *, page_t *, u_offset_t, size_t,
159 			int, cred_t *);
160 static int	nfs4_sync_pageio(vnode_t *, page_t *, u_offset_t, size_t,
161 			int, cred_t *);
162 static int	nfs4_commit(vnode_t *, offset4, count4, cred_t *);
163 static void	nfs4_set_mod(vnode_t *);
164 static void	nfs4_get_commit(vnode_t *);
165 static void	nfs4_get_commit_range(vnode_t *, u_offset_t, size_t);
166 static int	nfs4_putpage_commit(vnode_t *, offset_t, size_t, cred_t *);
167 static int	nfs4_commit_vp(vnode_t *, u_offset_t, size_t, cred_t *, int);
168 static int	nfs4_sync_commit(vnode_t *, page_t *, offset3, count3,
169 			cred_t *);
170 static void	do_nfs4_async_commit(vnode_t *, page_t *, offset3, count3,
171 			cred_t *);
172 static int	nfs4_update_attrcache(nfsstat4, nfs4_ga_res_t *,
173 			hrtime_t, vnode_t *, cred_t *);
174 static int	nfs4_open_non_reg_file(vnode_t **, int, cred_t *);
175 static int	nfs4_safelock(vnode_t *, const struct flock64 *, cred_t *);
176 static void	nfs4_register_lock_locally(vnode_t *, struct flock64 *, int,
177 			u_offset_t);
178 static int	nfs4_lockrelease(vnode_t *, int, offset_t, cred_t *);
179 static int	nfs4_block_and_wait(clock_t *, rnode4_t *);
180 static cred_t  *state_to_cred(nfs4_open_stream_t *);
181 static void	denied_to_flk(LOCK4denied *, flock64_t *, LOCKT4args *);
182 static pid_t	lo_to_pid(lock_owner4 *);
183 static void	nfs4_reinstitute_local_lock_state(vnode_t *, flock64_t *,
184 			cred_t *, nfs4_lock_owner_t *);
185 static void	push_reinstate(vnode_t *, int, flock64_t *, cred_t *,
186 			nfs4_lock_owner_t *);
187 static int	open_and_get_osp(vnode_t *, cred_t *, nfs4_open_stream_t **);
188 static void	nfs4_delmap_callback(struct as *, void *, uint_t);
189 static void	nfs4_free_delmapcall(nfs4_delmapcall_t *);
190 static nfs4_delmapcall_t	*nfs4_init_delmapcall();
191 static int	nfs4_find_and_delete_delmapcall(rnode4_t *, int *);
192 static int	nfs4_is_acl_mask_valid(uint_t, nfs4_acl_op_t);
193 static int	nfs4_create_getsecattr_return(vsecattr_t *, vsecattr_t *,
194 			uid_t, gid_t, int);
195 
196 /*
197  * Routines that implement the setting of v4 args for the misc. ops
198  */
199 static void	nfs4args_lock_free(nfs_argop4 *);
200 static void	nfs4args_lockt_free(nfs_argop4 *);
201 static void	nfs4args_setattr(nfs_argop4 *, vattr_t *, vsecattr_t *,
202 			int, rnode4_t *, cred_t *, bitmap4, int *,
203 			nfs4_stateid_types_t *);
204 static void	nfs4args_setattr_free(nfs_argop4 *);
205 static int	nfs4args_verify(nfs_argop4 *, vattr_t *, enum nfs_opnum4,
206 			bitmap4);
207 static void	nfs4args_verify_free(nfs_argop4 *);
208 static void	nfs4args_write(nfs_argop4 *, stable_how4, rnode4_t *, cred_t *,
209 			WRITE4args **, nfs4_stateid_types_t *);
210 
211 /*
212  * These are the vnode ops functions that implement the vnode interface to
213  * the networked file system.  See more comments below at nfs4_vnodeops.
214  */
215 static int	nfs4_open(vnode_t **, int, cred_t *, caller_context_t *);
216 static int	nfs4_close(vnode_t *, int, int, offset_t, cred_t *,
217 			caller_context_t *);
218 static int	nfs4_read(vnode_t *, struct uio *, int, cred_t *,
219 			caller_context_t *);
220 static int	nfs4_write(vnode_t *, struct uio *, int, cred_t *,
221 			caller_context_t *);
222 static int	nfs4_ioctl(vnode_t *, int, intptr_t, int, cred_t *, int *,
223 			caller_context_t *);
224 static int	nfs4_setattr(vnode_t *, struct vattr *, int, cred_t *,
225 			caller_context_t *);
226 static int	nfs4_access(vnode_t *, int, int, cred_t *, caller_context_t *);
227 static int	nfs4_readlink(vnode_t *, struct uio *, cred_t *,
228 			caller_context_t *);
229 static int	nfs4_fsync(vnode_t *, int, cred_t *, caller_context_t *);
230 static int	nfs4_create(vnode_t *, char *, struct vattr *, enum vcexcl,
231 			int, vnode_t **, cred_t *, int, caller_context_t *,
232 			vsecattr_t *);
233 static int	nfs4_remove(vnode_t *, char *, cred_t *, caller_context_t *,
234 			int);
235 static int	nfs4_link(vnode_t *, vnode_t *, char *, cred_t *,
236 			caller_context_t *, int);
237 static int	nfs4_rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
238 			caller_context_t *, int);
239 static int	nfs4_mkdir(vnode_t *, char *, struct vattr *, vnode_t **,
240 			cred_t *, caller_context_t *, int, vsecattr_t *);
241 static int	nfs4_rmdir(vnode_t *, char *, vnode_t *, cred_t *,
242 			caller_context_t *, int);
243 static int	nfs4_symlink(vnode_t *, char *, struct vattr *, char *,
244 			cred_t *, caller_context_t *, int);
245 static int	nfs4_readdir(vnode_t *, struct uio *, cred_t *, int *,
246 			caller_context_t *, int);
247 static int	nfs4_seek(vnode_t *, offset_t, offset_t *, caller_context_t *);
248 static int	nfs4_getpage(vnode_t *, offset_t, size_t, uint_t *,
249 			page_t *[], size_t, struct seg *, caddr_t,
250 			enum seg_rw, cred_t *, caller_context_t *);
251 static int	nfs4_putpage(vnode_t *, offset_t, size_t, int, cred_t *,
252 			caller_context_t *);
253 static int	nfs4_map(vnode_t *, offset_t, struct as *, caddr_t *, size_t,
254 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
255 static int	nfs4_addmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
256 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
257 static int	nfs4_cmp(vnode_t *, vnode_t *, caller_context_t *);
258 static int	nfs4_frlock(vnode_t *, int, struct flock64 *, int, offset_t,
259 			struct flk_callback *, cred_t *, caller_context_t *);
260 static int	nfs4_space(vnode_t *, int, struct flock64 *, int, offset_t,
261 			cred_t *, caller_context_t *);
262 static int	nfs4_delmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
263 			uint_t, uint_t, uint_t, cred_t *, caller_context_t *);
264 static int	nfs4_pageio(vnode_t *, page_t *, u_offset_t, size_t, int,
265 			cred_t *, caller_context_t *);
266 static void	nfs4_dispose(vnode_t *, page_t *, int, int, cred_t *,
267 			caller_context_t *);
268 static int	nfs4_setsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
269 			caller_context_t *);
270 /*
271  * These vnode ops are required to be called from outside this source file,
272  * e.g. by ephemeral mount stub vnode ops, and so may not be declared
273  * as static.
274  */
275 int	nfs4_getattr(vnode_t *, struct vattr *, int, cred_t *,
276 	    caller_context_t *);
277 void	nfs4_inactive(vnode_t *, cred_t *, caller_context_t *);
278 int	nfs4_lookup(vnode_t *, char *, vnode_t **,
279 	    struct pathname *, int, vnode_t *, cred_t *,
280 	    caller_context_t *, int *, pathname_t *);
281 int	nfs4_fid(vnode_t *, fid_t *, caller_context_t *);
282 int	nfs4_rwlock(vnode_t *, int, caller_context_t *);
283 void	nfs4_rwunlock(vnode_t *, int, caller_context_t *);
284 int	nfs4_realvp(vnode_t *, vnode_t **, caller_context_t *);
285 int	nfs4_pathconf(vnode_t *, int, ulong_t *, cred_t *,
286 	    caller_context_t *);
287 int	nfs4_getsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
288 	    caller_context_t *);
289 int	nfs4_shrlock(vnode_t *, int, struct shrlock *, int, cred_t *,
290 	    caller_context_t *);
291 
292 /*
293  * Used for nfs4_commit_vp() to indicate if we should
294  * wait on pending writes.
295  */
296 #define	NFS4_WRITE_NOWAIT	0
297 #define	NFS4_WRITE_WAIT		1
298 
299 #define	NFS4_BASE_WAIT_TIME 1	/* 1 second */
300 
301 /*
302  * Error flags used to pass information about certain special errors
303  * which need to be handled specially.
304  */
305 #define	NFS_EOF			-98
306 #define	NFS_VERF_MISMATCH	-97
307 
308 /*
309  * Flags used to differentiate between which operation drove the
310  * potential CLOSE OTW. (see nfs4_close_otw_if_necessary)
311  */
312 #define	NFS4_CLOSE_OP		0x1
313 #define	NFS4_DELMAP_OP		0x2
314 #define	NFS4_INACTIVE_OP	0x3
315 
316 #define	ISVDEV(t) ((t == VBLK) || (t == VCHR) || (t == VFIFO))
317 
318 /* ALIGN64 aligns the given buffer and adjust buffer size to 64 bit */
319 #define	ALIGN64(x, ptr, sz)						\
320 	x = ((uintptr_t)(ptr)) & (sizeof (uint64_t) - 1);		\
321 	if (x) {							\
322 		x = sizeof (uint64_t) - (x);				\
323 		sz -= (x);						\
324 		ptr += (x);						\
325 	}
326 
327 #ifdef DEBUG
328 int nfs4_client_attr_debug = 0;
329 int nfs4_client_state_debug = 0;
330 int nfs4_client_shadow_debug = 0;
331 int nfs4_client_lock_debug = 0;
332 int nfs4_seqid_sync = 0;
333 int nfs4_client_map_debug = 0;
334 static int nfs4_pageio_debug = 0;
335 int nfs4_client_inactive_debug = 0;
336 int nfs4_client_recov_debug = 0;
337 int nfs4_client_failover_debug = 0;
338 int nfs4_client_call_debug = 0;
339 int nfs4_client_lookup_debug = 0;
340 int nfs4_client_zone_debug = 0;
341 int nfs4_lost_rqst_debug = 0;
342 int nfs4_rdattrerr_debug = 0;
343 int nfs4_open_stream_debug = 0;
344 
345 int nfs4read_error_inject;
346 
347 static int nfs4_create_misses = 0;
348 
349 static int nfs4_readdir_cache_shorts = 0;
350 static int nfs4_readdir_readahead = 0;
351 
352 static int nfs4_bio_do_stop = 0;
353 
354 static int nfs4_lostpage = 0;	/* number of times we lost original page */
355 
356 int nfs4_mmap_debug = 0;
357 
358 static int nfs4_pathconf_cache_hits = 0;
359 static int nfs4_pathconf_cache_misses = 0;
360 
361 int nfs4close_all_cnt;
362 int nfs4close_one_debug = 0;
363 int nfs4close_notw_debug = 0;
364 
365 int denied_to_flk_debug = 0;
366 void *lockt_denied_debug;
367 
368 #endif
369 
370 /*
371  * How long to wait before trying again if OPEN_CONFIRM gets ETIMEDOUT
372  * or NFS4ERR_RESOURCE.
373  */
374 static int confirm_retry_sec = 30;
375 
376 static int nfs4_lookup_neg_cache = 1;
377 
378 /*
379  * number of pages to read ahead
380  * optimized for 100 base-T.
381  */
382 static int nfs4_nra = 4;
383 
384 static int nfs4_do_symlink_cache = 1;
385 
386 static int nfs4_pathconf_disable_cache = 0;
387 
388 /*
389  * These are the vnode ops routines which implement the vnode interface to
390  * the networked file system.  These routines just take their parameters,
391  * make them look networkish by putting the right info into interface structs,
392  * and then calling the appropriate remote routine(s) to do the work.
393  *
394  * Note on directory name lookup cacheing:  If we detect a stale fhandle,
395  * we purge the directory cache relative to that vnode.  This way, the
396  * user won't get burned by the cache repeatedly.  See <nfs/rnode4.h> for
397  * more details on rnode locking.
398  */
399 
400 struct vnodeops *nfs4_vnodeops;
401 
402 const fs_operation_def_t nfs4_vnodeops_template[] = {
403 	VOPNAME_OPEN,		{ .vop_open = nfs4_open },
404 	VOPNAME_CLOSE,		{ .vop_close = nfs4_close },
405 	VOPNAME_READ,		{ .vop_read = nfs4_read },
406 	VOPNAME_WRITE,		{ .vop_write = nfs4_write },
407 	VOPNAME_IOCTL,		{ .vop_ioctl = nfs4_ioctl },
408 	VOPNAME_GETATTR,	{ .vop_getattr = nfs4_getattr },
409 	VOPNAME_SETATTR,	{ .vop_setattr = nfs4_setattr },
410 	VOPNAME_ACCESS,		{ .vop_access = nfs4_access },
411 	VOPNAME_LOOKUP,		{ .vop_lookup = nfs4_lookup },
412 	VOPNAME_CREATE,		{ .vop_create = nfs4_create },
413 	VOPNAME_REMOVE,		{ .vop_remove = nfs4_remove },
414 	VOPNAME_LINK,		{ .vop_link = nfs4_link },
415 	VOPNAME_RENAME,		{ .vop_rename = nfs4_rename },
416 	VOPNAME_MKDIR,		{ .vop_mkdir = nfs4_mkdir },
417 	VOPNAME_RMDIR,		{ .vop_rmdir = nfs4_rmdir },
418 	VOPNAME_READDIR,	{ .vop_readdir = nfs4_readdir },
419 	VOPNAME_SYMLINK,	{ .vop_symlink = nfs4_symlink },
420 	VOPNAME_READLINK,	{ .vop_readlink = nfs4_readlink },
421 	VOPNAME_FSYNC,		{ .vop_fsync = nfs4_fsync },
422 	VOPNAME_INACTIVE,	{ .vop_inactive = nfs4_inactive },
423 	VOPNAME_FID,		{ .vop_fid = nfs4_fid },
424 	VOPNAME_RWLOCK,		{ .vop_rwlock = nfs4_rwlock },
425 	VOPNAME_RWUNLOCK,	{ .vop_rwunlock = nfs4_rwunlock },
426 	VOPNAME_SEEK,		{ .vop_seek = nfs4_seek },
427 	VOPNAME_FRLOCK,		{ .vop_frlock = nfs4_frlock },
428 	VOPNAME_SPACE,		{ .vop_space = nfs4_space },
429 	VOPNAME_REALVP,		{ .vop_realvp = nfs4_realvp },
430 	VOPNAME_GETPAGE,	{ .vop_getpage = nfs4_getpage },
431 	VOPNAME_PUTPAGE,	{ .vop_putpage = nfs4_putpage },
432 	VOPNAME_MAP,		{ .vop_map = nfs4_map },
433 	VOPNAME_ADDMAP,		{ .vop_addmap = nfs4_addmap },
434 	VOPNAME_DELMAP,		{ .vop_delmap = nfs4_delmap },
435 	/* no separate nfs4_dump */
436 	VOPNAME_DUMP,		{ .vop_dump = nfs_dump },
437 	VOPNAME_PATHCONF,	{ .vop_pathconf = nfs4_pathconf },
438 	VOPNAME_PAGEIO,		{ .vop_pageio = nfs4_pageio },
439 	VOPNAME_DISPOSE,	{ .vop_dispose = nfs4_dispose },
440 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = nfs4_setsecattr },
441 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = nfs4_getsecattr },
442 	VOPNAME_SHRLOCK,	{ .vop_shrlock = nfs4_shrlock },
443 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
444 	NULL,			NULL
445 };
446 
447 /*
448  * The following are subroutines and definitions to set args or get res
449  * for the different nfsv4 ops
450  */
451 
452 void
453 nfs4args_lookup_free(nfs_argop4 *argop, int arglen)
454 {
455 	int		i;
456 
457 	for (i = 0; i < arglen; i++) {
458 		if (argop[i].argop == OP_LOOKUP) {
459 			kmem_free(
460 			    argop[i].nfs_argop4_u.oplookup.
461 			    objname.utf8string_val,
462 			    argop[i].nfs_argop4_u.oplookup.
463 			    objname.utf8string_len);
464 		}
465 	}
466 }
467 
468 static void
469 nfs4args_lock_free(nfs_argop4 *argop)
470 {
471 	locker4 *locker = &argop->nfs_argop4_u.oplock.locker;
472 
473 	if (locker->new_lock_owner == TRUE) {
474 		open_to_lock_owner4 *open_owner;
475 
476 		open_owner = &locker->locker4_u.open_owner;
477 		if (open_owner->lock_owner.owner_val != NULL) {
478 			kmem_free(open_owner->lock_owner.owner_val,
479 			    open_owner->lock_owner.owner_len);
480 		}
481 	}
482 }
483 
484 static void
485 nfs4args_lockt_free(nfs_argop4 *argop)
486 {
487 	lock_owner4 *lowner = &argop->nfs_argop4_u.oplockt.owner;
488 
489 	if (lowner->owner_val != NULL) {
490 		kmem_free(lowner->owner_val, lowner->owner_len);
491 	}
492 }
493 
494 static void
495 nfs4args_setattr(nfs_argop4 *argop, vattr_t *vap, vsecattr_t *vsap, int flags,
496     rnode4_t *rp, cred_t *cr, bitmap4 supp, int *error,
497     nfs4_stateid_types_t *sid_types)
498 {
499 	fattr4		*attr = &argop->nfs_argop4_u.opsetattr.obj_attributes;
500 	mntinfo4_t	*mi;
501 
502 	argop->argop = OP_SETATTR;
503 	/*
504 	 * The stateid is set to 0 if client is not modifying the size
505 	 * and otherwise to whatever nfs4_get_stateid() returns.
506 	 *
507 	 * XXX Note: nfs4_get_stateid() returns 0 if no lockowner and/or no
508 	 * state struct could be found for the process/file pair.  We may
509 	 * want to change this in the future (by OPENing the file).  See
510 	 * bug # 4474852.
511 	 */
512 	if (vap->va_mask & AT_SIZE) {
513 
514 		ASSERT(rp != NULL);
515 		mi = VTOMI4(RTOV4(rp));
516 
517 		argop->nfs_argop4_u.opsetattr.stateid =
518 		    nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
519 		    OP_SETATTR, sid_types, FALSE);
520 	} else {
521 		bzero(&argop->nfs_argop4_u.opsetattr.stateid,
522 		    sizeof (stateid4));
523 	}
524 
525 	*error = vattr_to_fattr4(vap, vsap, attr, flags, OP_SETATTR, supp);
526 	if (*error)
527 		bzero(attr, sizeof (*attr));
528 }
529 
530 static void
531 nfs4args_setattr_free(nfs_argop4 *argop)
532 {
533 	nfs4_fattr4_free(&argop->nfs_argop4_u.opsetattr.obj_attributes);
534 }
535 
536 static int
537 nfs4args_verify(nfs_argop4 *argop, vattr_t *vap, enum nfs_opnum4 op,
538     bitmap4 supp)
539 {
540 	fattr4 *attr;
541 	int error = 0;
542 
543 	argop->argop = op;
544 	switch (op) {
545 	case OP_VERIFY:
546 		attr = &argop->nfs_argop4_u.opverify.obj_attributes;
547 		break;
548 	case OP_NVERIFY:
549 		attr = &argop->nfs_argop4_u.opnverify.obj_attributes;
550 		break;
551 	default:
552 		return (EINVAL);
553 	}
554 	if (!error)
555 		error = vattr_to_fattr4(vap, NULL, attr, 0, op, supp);
556 	if (error)
557 		bzero(attr, sizeof (*attr));
558 	return (error);
559 }
560 
561 static void
562 nfs4args_verify_free(nfs_argop4 *argop)
563 {
564 	switch (argop->argop) {
565 	case OP_VERIFY:
566 		nfs4_fattr4_free(&argop->nfs_argop4_u.opverify.obj_attributes);
567 		break;
568 	case OP_NVERIFY:
569 		nfs4_fattr4_free(&argop->nfs_argop4_u.opnverify.obj_attributes);
570 		break;
571 	default:
572 		break;
573 	}
574 }
575 
576 static void
577 nfs4args_write(nfs_argop4 *argop, stable_how4 stable, rnode4_t *rp, cred_t *cr,
578     WRITE4args **wargs_pp, nfs4_stateid_types_t *sid_tp)
579 {
580 	WRITE4args *wargs = &argop->nfs_argop4_u.opwrite;
581 	mntinfo4_t *mi = VTOMI4(RTOV4(rp));
582 
583 	argop->argop = OP_WRITE;
584 	wargs->stable = stable;
585 	wargs->stateid = nfs4_get_w_stateid(cr, rp, curproc->p_pidp->pid_id,
586 	    mi, OP_WRITE, sid_tp);
587 	wargs->mblk = NULL;
588 	*wargs_pp = wargs;
589 }
590 
591 void
592 nfs4args_copen_free(OPEN4cargs *open_args)
593 {
594 	if (open_args->owner.owner_val) {
595 		kmem_free(open_args->owner.owner_val,
596 		    open_args->owner.owner_len);
597 	}
598 	if ((open_args->opentype == OPEN4_CREATE) &&
599 	    (open_args->mode != EXCLUSIVE4)) {
600 		nfs4_fattr4_free(&open_args->createhow4_u.createattrs);
601 	}
602 }
603 
604 /*
605  * XXX:  This is referenced in modstubs.s
606  */
607 struct vnodeops *
608 nfs4_getvnodeops(void)
609 {
610 	return (nfs4_vnodeops);
611 }
612 
613 /*
614  * The OPEN operation opens a regular file.
615  */
616 /*ARGSUSED3*/
617 static int
618 nfs4_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
619 {
620 	vnode_t *dvp = NULL;
621 	rnode4_t *rp, *drp;
622 	int error;
623 	int just_been_created;
624 	char fn[MAXNAMELEN];
625 
626 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4_open: "));
627 	if (nfs_zone() != VTOMI4(*vpp)->mi_zone)
628 		return (EIO);
629 	rp = VTOR4(*vpp);
630 
631 	/*
632 	 * Check to see if opening something besides a regular file;
633 	 * if so skip the OTW call
634 	 */
635 	if ((*vpp)->v_type != VREG) {
636 		error = nfs4_open_non_reg_file(vpp, flag, cr);
637 		return (error);
638 	}
639 
640 	/*
641 	 * XXX - would like a check right here to know if the file is
642 	 * executable or not, so as to skip OTW
643 	 */
644 
645 	if ((error = vtodv(*vpp, &dvp, cr, TRUE)) != 0)
646 		return (error);
647 
648 	drp = VTOR4(dvp);
649 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
650 		return (EINTR);
651 
652 	if ((error = vtoname(*vpp, fn, MAXNAMELEN)) != 0) {
653 		nfs_rw_exit(&drp->r_rwlock);
654 		return (error);
655 	}
656 
657 	/*
658 	 * See if this file has just been CREATEd.
659 	 * If so, clear the flag and update the dnlc, which was previously
660 	 * skipped in nfs4_create.
661 	 * XXX need better serilization on this.
662 	 * XXX move this into the nf4open_otw call, after we have
663 	 * XXX acquired the open owner seqid sync.
664 	 */
665 	mutex_enter(&rp->r_statev4_lock);
666 	if (rp->created_v4) {
667 		rp->created_v4 = 0;
668 		mutex_exit(&rp->r_statev4_lock);
669 
670 		dnlc_update(dvp, fn, *vpp);
671 		/* This is needed so we don't bump the open ref count */
672 		just_been_created = 1;
673 	} else {
674 		mutex_exit(&rp->r_statev4_lock);
675 		just_been_created = 0;
676 	}
677 
678 	/*
679 	 * If caller specified O_TRUNC/FTRUNC, then be sure to set
680 	 * FWRITE (to drive successful setattr(size=0) after open)
681 	 */
682 	if (flag & FTRUNC)
683 		flag |= FWRITE;
684 
685 	error = nfs4open_otw(dvp, fn, NULL, vpp, cr, 0, flag, 0,
686 	    just_been_created);
687 
688 	if (!error && !((*vpp)->v_flag & VROOT))
689 		dnlc_update(dvp, fn, *vpp);
690 
691 	nfs_rw_exit(&drp->r_rwlock);
692 
693 	/* release the hold from vtodv */
694 	VN_RELE(dvp);
695 
696 	/* exchange the shadow for the master vnode, if needed */
697 
698 	if (error == 0 && IS_SHADOW(*vpp, rp))
699 		sv_exchange(vpp);
700 
701 	return (error);
702 }
703 
704 /*
705  * See if there's a "lost open" request to be saved and recovered.
706  */
707 static void
708 nfs4open_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
709     nfs4_open_owner_t *oop, cred_t *cr, vnode_t *vp,
710     vnode_t *dvp, OPEN4cargs *open_args)
711 {
712 	vfs_t *vfsp;
713 	char *srccfp;
714 
715 	vfsp = (dvp ? dvp->v_vfsp : vp->v_vfsp);
716 
717 	if (error != ETIMEDOUT && error != EINTR &&
718 	    !NFS4_FRC_UNMT_ERR(error, vfsp)) {
719 		lost_rqstp->lr_op = 0;
720 		return;
721 	}
722 
723 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
724 	    "nfs4open_save_lost_rqst: error %d", error));
725 
726 	lost_rqstp->lr_op = OP_OPEN;
727 
728 	/*
729 	 * The vp (if it is not NULL) and dvp are held and rele'd via
730 	 * the recovery code.  See nfs4_save_lost_rqst.
731 	 */
732 	lost_rqstp->lr_vp = vp;
733 	lost_rqstp->lr_dvp = dvp;
734 	lost_rqstp->lr_oop = oop;
735 	lost_rqstp->lr_osp = NULL;
736 	lost_rqstp->lr_lop = NULL;
737 	lost_rqstp->lr_cr = cr;
738 	lost_rqstp->lr_flk = NULL;
739 	lost_rqstp->lr_oacc = open_args->share_access;
740 	lost_rqstp->lr_odeny = open_args->share_deny;
741 	lost_rqstp->lr_oclaim = open_args->claim;
742 	if (open_args->claim == CLAIM_DELEGATE_CUR) {
743 		lost_rqstp->lr_ostateid =
744 		    open_args->open_claim4_u.delegate_cur_info.delegate_stateid;
745 		srccfp = open_args->open_claim4_u.delegate_cur_info.cfile;
746 	} else {
747 		srccfp = open_args->open_claim4_u.cfile;
748 	}
749 	lost_rqstp->lr_ofile.utf8string_len = 0;
750 	lost_rqstp->lr_ofile.utf8string_val = NULL;
751 	(void) str_to_utf8(srccfp, &lost_rqstp->lr_ofile);
752 	lost_rqstp->lr_putfirst = FALSE;
753 }
754 
755 struct nfs4_excl_time {
756 	uint32 seconds;
757 	uint32 nseconds;
758 };
759 
760 /*
761  * The OPEN operation creates and/or opens a regular file
762  *
763  * ARGSUSED
764  */
765 static int
766 nfs4open_otw(vnode_t *dvp, char *file_name, struct vattr *in_va,
767     vnode_t **vpp, cred_t *cr, int create_flag, int open_flag,
768     enum createmode4 createmode, int file_just_been_created)
769 {
770 	rnode4_t *rp;
771 	rnode4_t *drp = VTOR4(dvp);
772 	vnode_t *vp = NULL;
773 	vnode_t *vpi = *vpp;
774 	bool_t needrecov = FALSE;
775 
776 	int doqueue = 1;
777 
778 	COMPOUND4args_clnt args;
779 	COMPOUND4res_clnt res;
780 	nfs_argop4 *argop;
781 	nfs_resop4 *resop;
782 	int argoplist_size;
783 	int idx_open, idx_fattr;
784 
785 	GETFH4res *gf_res = NULL;
786 	OPEN4res *op_res = NULL;
787 	nfs4_ga_res_t *garp;
788 	fattr4 *attr = NULL;
789 	struct nfs4_excl_time verf;
790 	bool_t did_excl_setup = FALSE;
791 	int created_osp;
792 
793 	OPEN4cargs *open_args;
794 	nfs4_open_owner_t	*oop = NULL;
795 	nfs4_open_stream_t	*osp = NULL;
796 	seqid4 seqid = 0;
797 	bool_t retry_open = FALSE;
798 	nfs4_recov_state_t recov_state;
799 	nfs4_lost_rqst_t lost_rqst;
800 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
801 	hrtime_t t;
802 	int acc = 0;
803 	cred_t *cred_otw = NULL;	/* cred used to do the RPC call */
804 	cred_t *ncr = NULL;
805 
806 	nfs4_sharedfh_t *otw_sfh;
807 	nfs4_sharedfh_t *orig_sfh;
808 	int fh_differs = 0;
809 	int numops, setgid_flag;
810 	int num_bseqid_retry = NFS4_NUM_RETRY_BAD_SEQID + 1;
811 
812 	/*
813 	 * Make sure we properly deal with setting the right gid on
814 	 * a newly created file to reflect the parent's setgid bit
815 	 */
816 	setgid_flag = 0;
817 	if (create_flag && in_va) {
818 
819 		/*
820 		 * If there is grpid mount flag used or
821 		 * the parent's directory has the setgid bit set
822 		 * _and_ the client was able to get a valid mapping
823 		 * for the parent dir's owner_group, we want to
824 		 * append NVERIFY(owner_group == dva.va_gid) and
825 		 * SETATTR to the CREATE compound.
826 		 */
827 		mutex_enter(&drp->r_statelock);
828 		if ((VTOMI4(dvp)->mi_flags & MI4_GRPID ||
829 		    drp->r_attr.va_mode & VSGID) &&
830 		    drp->r_attr.va_gid != GID_NOBODY) {
831 			in_va->va_mask |= AT_GID;
832 			in_va->va_gid = drp->r_attr.va_gid;
833 			setgid_flag = 1;
834 		}
835 		mutex_exit(&drp->r_statelock);
836 	}
837 
838 	/*
839 	 * Normal/non-create compound:
840 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new)
841 	 *
842 	 * Open(create) compound no setgid:
843 	 * PUTFH(dfh) + SAVEFH + OPEN(create) + GETFH + GETATTR(new) +
844 	 * RESTOREFH + GETATTR
845 	 *
846 	 * Open(create) setgid:
847 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new) +
848 	 * SAVEFH + PUTFH(dfh) + GETATTR(dvp) + RESTOREFH +
849 	 * NVERIFY(grp) + SETATTR
850 	 */
851 	if (setgid_flag) {
852 		numops = 10;
853 		idx_open = 1;
854 		idx_fattr = 3;
855 	} else if (create_flag) {
856 		numops = 7;
857 		idx_open = 2;
858 		idx_fattr = 4;
859 	} else {
860 		numops = 4;
861 		idx_open = 1;
862 		idx_fattr = 3;
863 	}
864 
865 	args.array_len = numops;
866 	argoplist_size = numops * sizeof (nfs_argop4);
867 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
868 
869 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw: "
870 	    "open %s open flag 0x%x cred %p", file_name, open_flag,
871 	    (void *)cr));
872 
873 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
874 	if (create_flag) {
875 		/*
876 		 * We are to create a file.  Initialize the passed in vnode
877 		 * pointer.
878 		 */
879 		vpi = NULL;
880 	} else {
881 		/*
882 		 * Check to see if the client owns a read delegation and is
883 		 * trying to open for write.  If so, then return the delegation
884 		 * to avoid the server doing a cb_recall and returning DELAY.
885 		 * NB - we don't use the statev4_lock here because we'd have
886 		 * to drop the lock anyway and the result would be stale.
887 		 */
888 		if ((open_flag & FWRITE) &&
889 		    VTOR4(vpi)->r_deleg_type == OPEN_DELEGATE_READ)
890 			(void) nfs4delegreturn(VTOR4(vpi), NFS4_DR_REOPEN);
891 
892 		/*
893 		 * If the file has a delegation, then do an access check up
894 		 * front.  This avoids having to an access check later after
895 		 * we've already done start_op, which could deadlock.
896 		 */
897 		if (VTOR4(vpi)->r_deleg_type != OPEN_DELEGATE_NONE) {
898 			if (open_flag & FREAD &&
899 			    nfs4_access(vpi, VREAD, 0, cr, NULL) == 0)
900 				acc |= VREAD;
901 			if (open_flag & FWRITE &&
902 			    nfs4_access(vpi, VWRITE, 0, cr, NULL) == 0)
903 				acc |= VWRITE;
904 		}
905 	}
906 
907 	drp = VTOR4(dvp);
908 
909 	recov_state.rs_flags = 0;
910 	recov_state.rs_num_retry_despite_err = 0;
911 	cred_otw = cr;
912 
913 recov_retry:
914 	fh_differs = 0;
915 	nfs4_error_zinit(&e);
916 
917 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, vpi, &recov_state);
918 	if (e.error) {
919 		if (ncr != NULL)
920 			crfree(ncr);
921 		kmem_free(argop, argoplist_size);
922 		return (e.error);
923 	}
924 
925 	args.ctag = TAG_OPEN;
926 	args.array_len = numops;
927 	args.array = argop;
928 
929 	/* putfh directory fh */
930 	argop[0].argop = OP_CPUTFH;
931 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
932 
933 	/* OPEN: either op 1 or op 2 depending upon create/setgid flags */
934 	argop[idx_open].argop = OP_COPEN;
935 	open_args = &argop[idx_open].nfs_argop4_u.opcopen;
936 	open_args->claim = CLAIM_NULL;
937 
938 	/* name of file */
939 	open_args->open_claim4_u.cfile = file_name;
940 	open_args->owner.owner_len = 0;
941 	open_args->owner.owner_val = NULL;
942 
943 	if (create_flag) {
944 		/* CREATE a file */
945 		open_args->opentype = OPEN4_CREATE;
946 		open_args->mode = createmode;
947 		if (createmode == EXCLUSIVE4) {
948 			if (did_excl_setup == FALSE) {
949 				verf.seconds = zone_get_hostid(NULL);
950 				if (verf.seconds != 0)
951 					verf.nseconds = newnum();
952 				else {
953 					timestruc_t now;
954 
955 					gethrestime(&now);
956 					verf.seconds = now.tv_sec;
957 					verf.nseconds = now.tv_nsec;
958 				}
959 				/*
960 				 * Since the server will use this value for the
961 				 * mtime, make sure that it can't overflow. Zero
962 				 * out the MSB. The actual value does not matter
963 				 * here, only its uniqeness.
964 				 */
965 				verf.seconds &= INT32_MAX;
966 				did_excl_setup = TRUE;
967 			}
968 
969 			/* Now copy over verifier to OPEN4args. */
970 			open_args->createhow4_u.createverf = *(uint64_t *)&verf;
971 		} else {
972 			int v_error;
973 			bitmap4 supp_attrs;
974 			servinfo4_t *svp;
975 
976 			attr = &open_args->createhow4_u.createattrs;
977 
978 			svp = drp->r_server;
979 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
980 			supp_attrs = svp->sv_supp_attrs;
981 			nfs_rw_exit(&svp->sv_lock);
982 
983 			/* GUARDED4 or UNCHECKED4 */
984 			v_error = vattr_to_fattr4(in_va, NULL, attr, 0, OP_OPEN,
985 			    supp_attrs);
986 			if (v_error) {
987 				bzero(attr, sizeof (*attr));
988 				nfs4args_copen_free(open_args);
989 				nfs4_end_op(VTOMI4(dvp), dvp, vpi,
990 				    &recov_state, FALSE);
991 				if (ncr != NULL)
992 					crfree(ncr);
993 				kmem_free(argop, argoplist_size);
994 				return (v_error);
995 			}
996 		}
997 	} else {
998 		/* NO CREATE */
999 		open_args->opentype = OPEN4_NOCREATE;
1000 	}
1001 
1002 	if (recov_state.rs_sp != NULL) {
1003 		mutex_enter(&recov_state.rs_sp->s_lock);
1004 		open_args->owner.clientid = recov_state.rs_sp->clientid;
1005 		mutex_exit(&recov_state.rs_sp->s_lock);
1006 	} else {
1007 		/* XXX should we just fail here? */
1008 		open_args->owner.clientid = 0;
1009 	}
1010 
1011 	/*
1012 	 * This increments oop's ref count or creates a temporary 'just_created'
1013 	 * open owner that will become valid when this OPEN/OPEN_CONFIRM call
1014 	 * completes.
1015 	 */
1016 	mutex_enter(&VTOMI4(dvp)->mi_lock);
1017 
1018 	/* See if a permanent or just created open owner exists */
1019 	oop = find_open_owner_nolock(cr, NFS4_JUST_CREATED, VTOMI4(dvp));
1020 	if (!oop) {
1021 		/*
1022 		 * This open owner does not exist so create a temporary
1023 		 * just created one.
1024 		 */
1025 		oop = create_open_owner(cr, VTOMI4(dvp));
1026 		ASSERT(oop != NULL);
1027 	}
1028 	mutex_exit(&VTOMI4(dvp)->mi_lock);
1029 
1030 	/* this length never changes, do alloc before seqid sync */
1031 	open_args->owner.owner_len = sizeof (oop->oo_name);
1032 	open_args->owner.owner_val =
1033 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1034 
1035 	e.error = nfs4_start_open_seqid_sync(oop, VTOMI4(dvp));
1036 	if (e.error == EAGAIN) {
1037 		open_owner_rele(oop);
1038 		nfs4args_copen_free(open_args);
1039 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1040 		if (ncr != NULL) {
1041 			crfree(ncr);
1042 			ncr = NULL;
1043 		}
1044 		goto recov_retry;
1045 	}
1046 
1047 	/* Check to see if we need to do the OTW call */
1048 	if (!create_flag) {
1049 		if (!nfs4_is_otw_open_necessary(oop, open_flag, vpi,
1050 		    file_just_been_created, &e.error, acc, &recov_state)) {
1051 
1052 			/*
1053 			 * The OTW open is not necessary.  Either
1054 			 * the open can succeed without it (eg.
1055 			 * delegation, error == 0) or the open
1056 			 * must fail due to an access failure
1057 			 * (error != 0).  In either case, tidy
1058 			 * up and return.
1059 			 */
1060 
1061 			nfs4_end_open_seqid_sync(oop);
1062 			open_owner_rele(oop);
1063 			nfs4args_copen_free(open_args);
1064 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, FALSE);
1065 			if (ncr != NULL)
1066 				crfree(ncr);
1067 			kmem_free(argop, argoplist_size);
1068 			return (e.error);
1069 		}
1070 	}
1071 
1072 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1073 	    open_args->owner.owner_len);
1074 
1075 	seqid = nfs4_get_open_seqid(oop) + 1;
1076 	open_args->seqid = seqid;
1077 	open_args->share_access = 0;
1078 	if (open_flag & FREAD)
1079 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1080 	if (open_flag & FWRITE)
1081 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1082 	open_args->share_deny = OPEN4_SHARE_DENY_NONE;
1083 
1084 
1085 
1086 	/*
1087 	 * getfh w/sanity check for idx_open/idx_fattr
1088 	 */
1089 	ASSERT((idx_open + 1) == (idx_fattr - 1));
1090 	argop[idx_open + 1].argop = OP_GETFH;
1091 
1092 	/* getattr */
1093 	argop[idx_fattr].argop = OP_GETATTR;
1094 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1095 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1096 
1097 	if (setgid_flag) {
1098 		vattr_t	_v;
1099 		servinfo4_t *svp;
1100 		bitmap4	supp_attrs;
1101 
1102 		svp = drp->r_server;
1103 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1104 		supp_attrs = svp->sv_supp_attrs;
1105 		nfs_rw_exit(&svp->sv_lock);
1106 
1107 		/*
1108 		 * For setgid case, we need to:
1109 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1110 		 */
1111 		argop[4].argop = OP_SAVEFH;
1112 
1113 		argop[5].argop = OP_CPUTFH;
1114 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
1115 
1116 		argop[6].argop = OP_GETATTR;
1117 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1118 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1119 
1120 		argop[7].argop = OP_RESTOREFH;
1121 
1122 		/*
1123 		 * nverify
1124 		 */
1125 		_v.va_mask = AT_GID;
1126 		_v.va_gid = in_va->va_gid;
1127 		if (!(e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
1128 		    supp_attrs))) {
1129 
1130 			/*
1131 			 * setattr
1132 			 *
1133 			 * We _know_ we're not messing with AT_SIZE or
1134 			 * AT_XTIME, so no need for stateid or flags.
1135 			 * Also we specify NULL rp since we're only
1136 			 * interested in setting owner_group attributes.
1137 			 */
1138 			nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr,
1139 			    supp_attrs, &e.error, 0);
1140 			if (e.error)
1141 				nfs4args_verify_free(&argop[8]);
1142 		}
1143 
1144 		if (e.error) {
1145 			/*
1146 			 * XXX - Revisit the last argument to nfs4_end_op()
1147 			 *	 once 5020486 is fixed.
1148 			 */
1149 			nfs4_end_open_seqid_sync(oop);
1150 			open_owner_rele(oop);
1151 			nfs4args_copen_free(open_args);
1152 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1153 			if (ncr != NULL)
1154 				crfree(ncr);
1155 			kmem_free(argop, argoplist_size);
1156 			return (e.error);
1157 		}
1158 	} else if (create_flag) {
1159 		argop[1].argop = OP_SAVEFH;
1160 
1161 		argop[5].argop = OP_RESTOREFH;
1162 
1163 		argop[6].argop = OP_GETATTR;
1164 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1165 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1166 	}
1167 
1168 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1169 	    "nfs4open_otw: %s call, nm %s, rp %s",
1170 	    needrecov ? "recov" : "first", file_name,
1171 	    rnode4info(VTOR4(dvp))));
1172 
1173 	t = gethrtime();
1174 
1175 	rfs4call(VTOMI4(dvp), &args, &res, cred_otw, &doqueue, 0, &e);
1176 
1177 	if (!e.error && nfs4_need_to_bump_seqid(&res))
1178 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1179 
1180 	needrecov = nfs4_needs_recovery(&e, TRUE, dvp->v_vfsp);
1181 
1182 	if (e.error || needrecov) {
1183 		bool_t abort = FALSE;
1184 
1185 		if (needrecov) {
1186 			nfs4_bseqid_entry_t *bsep = NULL;
1187 
1188 			nfs4open_save_lost_rqst(e.error, &lost_rqst, oop,
1189 			    cred_otw, vpi, dvp, open_args);
1190 
1191 			if (!e.error && res.status == NFS4ERR_BAD_SEQID) {
1192 				bsep = nfs4_create_bseqid_entry(oop, NULL,
1193 				    vpi, 0, args.ctag, open_args->seqid);
1194 				num_bseqid_retry--;
1195 			}
1196 
1197 			abort = nfs4_start_recovery(&e, VTOMI4(dvp), dvp, vpi,
1198 			    NULL, lost_rqst.lr_op == OP_OPEN ?
1199 			    &lost_rqst : NULL, OP_OPEN, bsep, NULL, NULL);
1200 
1201 			if (bsep)
1202 				kmem_free(bsep, sizeof (*bsep));
1203 			/* give up if we keep getting BAD_SEQID */
1204 			if (num_bseqid_retry == 0)
1205 				abort = TRUE;
1206 			if (abort == TRUE && e.error == 0)
1207 				e.error = geterrno4(res.status);
1208 		}
1209 		nfs4_end_open_seqid_sync(oop);
1210 		open_owner_rele(oop);
1211 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1212 		nfs4args_copen_free(open_args);
1213 		if (setgid_flag) {
1214 			nfs4args_verify_free(&argop[8]);
1215 			nfs4args_setattr_free(&argop[9]);
1216 		}
1217 		if (!e.error)
1218 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1219 		if (ncr != NULL) {
1220 			crfree(ncr);
1221 			ncr = NULL;
1222 		}
1223 		if (!needrecov || abort == TRUE || e.error == EINTR ||
1224 		    NFS4_FRC_UNMT_ERR(e.error, dvp->v_vfsp)) {
1225 			kmem_free(argop, argoplist_size);
1226 			return (e.error);
1227 		}
1228 		goto recov_retry;
1229 	}
1230 
1231 	/*
1232 	 * Will check and update lease after checking the rflag for
1233 	 * OPEN_CONFIRM in the successful OPEN call.
1234 	 */
1235 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
1236 
1237 		/*
1238 		 * XXX what if we're crossing mount points from server1:/drp
1239 		 * to server2:/drp/rp.
1240 		 */
1241 
1242 		/* Signal our end of use of the open seqid */
1243 		nfs4_end_open_seqid_sync(oop);
1244 
1245 		/*
1246 		 * This will destroy the open owner if it was just created,
1247 		 * and no one else has put a reference on it.
1248 		 */
1249 		open_owner_rele(oop);
1250 		if (create_flag && (createmode != EXCLUSIVE4) &&
1251 		    res.status == NFS4ERR_BADOWNER)
1252 			nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1253 
1254 		e.error = geterrno4(res.status);
1255 		nfs4args_copen_free(open_args);
1256 		if (setgid_flag) {
1257 			nfs4args_verify_free(&argop[8]);
1258 			nfs4args_setattr_free(&argop[9]);
1259 		}
1260 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1261 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1262 		/*
1263 		 * If the reply is NFS4ERR_ACCESS, it may be because
1264 		 * we are root (no root net access).  If the real uid
1265 		 * is not root, then retry with the real uid instead.
1266 		 */
1267 		if (ncr != NULL) {
1268 			crfree(ncr);
1269 			ncr = NULL;
1270 		}
1271 		if (res.status == NFS4ERR_ACCESS &&
1272 		    (ncr = crnetadjust(cred_otw)) != NULL) {
1273 			cred_otw = ncr;
1274 			goto recov_retry;
1275 		}
1276 		kmem_free(argop, argoplist_size);
1277 		return (e.error);
1278 	}
1279 
1280 	resop = &res.array[idx_open];  /* open res */
1281 	op_res = &resop->nfs_resop4_u.opopen;
1282 
1283 #ifdef DEBUG
1284 	/*
1285 	 * verify attrset bitmap
1286 	 */
1287 	if (create_flag &&
1288 	    (createmode == UNCHECKED4 || createmode == GUARDED4)) {
1289 		/* make sure attrset returned is what we asked for */
1290 		/* XXX Ignore this 'error' for now */
1291 		if (attr->attrmask != op_res->attrset)
1292 			/* EMPTY */;
1293 	}
1294 #endif
1295 
1296 	if (op_res->rflags & OPEN4_RESULT_LOCKTYPE_POSIX) {
1297 		mutex_enter(&VTOMI4(dvp)->mi_lock);
1298 		VTOMI4(dvp)->mi_flags |= MI4_POSIX_LOCK;
1299 		mutex_exit(&VTOMI4(dvp)->mi_lock);
1300 	}
1301 
1302 	resop = &res.array[idx_open + 1];  /* getfh res */
1303 	gf_res = &resop->nfs_resop4_u.opgetfh;
1304 
1305 	otw_sfh = sfh4_get(&gf_res->object, VTOMI4(dvp));
1306 
1307 	/*
1308 	 * The open stateid has been updated on the server but not
1309 	 * on the client yet.  There is a path: makenfs4node->nfs4_attr_cache->
1310 	 * flush_pages->VOP_PUTPAGE->...->nfs4write where we will issue an OTW
1311 	 * WRITE call.  That, however, will use the old stateid, so go ahead
1312 	 * and upate the open stateid now, before any call to makenfs4node.
1313 	 */
1314 	if (vpi) {
1315 		nfs4_open_stream_t	*tmp_osp;
1316 		rnode4_t		*tmp_rp = VTOR4(vpi);
1317 
1318 		tmp_osp = find_open_stream(oop, tmp_rp);
1319 		if (tmp_osp) {
1320 			tmp_osp->open_stateid = op_res->stateid;
1321 			mutex_exit(&tmp_osp->os_sync_lock);
1322 			open_stream_rele(tmp_osp, tmp_rp);
1323 		}
1324 
1325 		/*
1326 		 * We must determine if the file handle given by the otw open
1327 		 * is the same as the file handle which was passed in with
1328 		 * *vpp.  This case can be reached if the file we are trying
1329 		 * to open has been removed and another file has been created
1330 		 * having the same file name.  The passed in vnode is released
1331 		 * later.
1332 		 */
1333 		orig_sfh = VTOR4(vpi)->r_fh;
1334 		fh_differs = nfs4cmpfh(&orig_sfh->sfh_fh, &otw_sfh->sfh_fh);
1335 	}
1336 
1337 	garp = &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res;
1338 
1339 	if (create_flag || fh_differs) {
1340 		int rnode_err = 0;
1341 
1342 		vp = makenfs4node(otw_sfh, garp, dvp->v_vfsp, t, cr,
1343 		    dvp, fn_get(VTOSV(dvp)->sv_name, file_name, otw_sfh));
1344 
1345 		if (e.error)
1346 			PURGE_ATTRCACHE4(vp);
1347 		/*
1348 		 * For the newly created vp case, make sure the rnode
1349 		 * isn't bad before using it.
1350 		 */
1351 		mutex_enter(&(VTOR4(vp))->r_statelock);
1352 		if (VTOR4(vp)->r_flags & R4RECOVERR)
1353 			rnode_err = EIO;
1354 		mutex_exit(&(VTOR4(vp))->r_statelock);
1355 
1356 		if (rnode_err) {
1357 			nfs4_end_open_seqid_sync(oop);
1358 			nfs4args_copen_free(open_args);
1359 			if (setgid_flag) {
1360 				nfs4args_verify_free(&argop[8]);
1361 				nfs4args_setattr_free(&argop[9]);
1362 			}
1363 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1364 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1365 			    needrecov);
1366 			open_owner_rele(oop);
1367 			VN_RELE(vp);
1368 			if (ncr != NULL)
1369 				crfree(ncr);
1370 			sfh4_rele(&otw_sfh);
1371 			kmem_free(argop, argoplist_size);
1372 			return (EIO);
1373 		}
1374 	} else {
1375 		vp = vpi;
1376 	}
1377 	sfh4_rele(&otw_sfh);
1378 
1379 	/*
1380 	 * It seems odd to get a full set of attrs and then not update
1381 	 * the object's attrcache in the non-create case.  Create case uses
1382 	 * the attrs since makenfs4node checks to see if the attrs need to
1383 	 * be updated (and then updates them).  The non-create case should
1384 	 * update attrs also.
1385 	 */
1386 	if (! create_flag && ! fh_differs && !e.error) {
1387 		nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
1388 	}
1389 
1390 	nfs4_error_zinit(&e);
1391 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
1392 		/* This does not do recovery for vp explicitly. */
1393 		nfs4open_confirm(vp, &seqid, &op_res->stateid, cred_otw, FALSE,
1394 		    &retry_open, oop, FALSE, &e, &num_bseqid_retry);
1395 
1396 		if (e.error || e.stat) {
1397 			nfs4_end_open_seqid_sync(oop);
1398 			nfs4args_copen_free(open_args);
1399 			if (setgid_flag) {
1400 				nfs4args_verify_free(&argop[8]);
1401 				nfs4args_setattr_free(&argop[9]);
1402 			}
1403 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1404 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1405 			    needrecov);
1406 			open_owner_rele(oop);
1407 			if (create_flag || fh_differs) {
1408 				/* rele the makenfs4node */
1409 				VN_RELE(vp);
1410 			}
1411 			if (ncr != NULL) {
1412 				crfree(ncr);
1413 				ncr = NULL;
1414 			}
1415 			if (retry_open == TRUE) {
1416 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1417 				    "nfs4open_otw: retry the open since OPEN "
1418 				    "CONFIRM failed with error %d stat %d",
1419 				    e.error, e.stat));
1420 				if (create_flag && createmode == GUARDED4) {
1421 					NFS4_DEBUG(nfs4_client_recov_debug,
1422 					    (CE_NOTE, "nfs4open_otw: switch "
1423 					    "createmode from GUARDED4 to "
1424 					    "UNCHECKED4"));
1425 					createmode = UNCHECKED4;
1426 				}
1427 				goto recov_retry;
1428 			}
1429 			if (!e.error) {
1430 				if (create_flag && (createmode != EXCLUSIVE4) &&
1431 				    e.stat == NFS4ERR_BADOWNER)
1432 					nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1433 
1434 				e.error = geterrno4(e.stat);
1435 			}
1436 			kmem_free(argop, argoplist_size);
1437 			return (e.error);
1438 		}
1439 	}
1440 
1441 	rp = VTOR4(vp);
1442 
1443 	mutex_enter(&rp->r_statev4_lock);
1444 	if (create_flag)
1445 		rp->created_v4 = 1;
1446 	mutex_exit(&rp->r_statev4_lock);
1447 
1448 	mutex_enter(&oop->oo_lock);
1449 	/* Doesn't matter if 'oo_just_created' already was set as this */
1450 	oop->oo_just_created = NFS4_PERM_CREATED;
1451 	if (oop->oo_cred_otw)
1452 		crfree(oop->oo_cred_otw);
1453 	oop->oo_cred_otw = cred_otw;
1454 	crhold(oop->oo_cred_otw);
1455 	mutex_exit(&oop->oo_lock);
1456 
1457 	/* returns with 'os_sync_lock' held */
1458 	osp = find_or_create_open_stream(oop, rp, &created_osp);
1459 	if (!osp) {
1460 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1461 		    "nfs4open_otw: failed to create an open stream"));
1462 		NFS4_DEBUG(nfs4_seqid_sync, (CE_NOTE, "nfs4open_otw: "
1463 		    "signal our end of use of the open seqid"));
1464 
1465 		nfs4_end_open_seqid_sync(oop);
1466 		open_owner_rele(oop);
1467 		nfs4args_copen_free(open_args);
1468 		if (setgid_flag) {
1469 			nfs4args_verify_free(&argop[8]);
1470 			nfs4args_setattr_free(&argop[9]);
1471 		}
1472 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1473 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1474 		if (create_flag || fh_differs)
1475 			VN_RELE(vp);
1476 		if (ncr != NULL)
1477 			crfree(ncr);
1478 
1479 		kmem_free(argop, argoplist_size);
1480 		return (EINVAL);
1481 
1482 	}
1483 
1484 	osp->open_stateid = op_res->stateid;
1485 
1486 	if (open_flag & FREAD)
1487 		osp->os_share_acc_read++;
1488 	if (open_flag & FWRITE)
1489 		osp->os_share_acc_write++;
1490 	osp->os_share_deny_none++;
1491 
1492 	/*
1493 	 * Need to reset this bitfield for the possible case where we were
1494 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
1495 	 * we could retry the CLOSE, OPENed the file again.
1496 	 */
1497 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
1498 	osp->os_final_close = 0;
1499 	osp->os_force_close = 0;
1500 #ifdef DEBUG
1501 	if (osp->os_failed_reopen)
1502 		NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE, "nfs4open_otw:"
1503 		    " clearing os_failed_reopen for osp %p, cr %p, rp %s",
1504 		    (void *)osp, (void *)cr, rnode4info(rp)));
1505 #endif
1506 	osp->os_failed_reopen = 0;
1507 
1508 	mutex_exit(&osp->os_sync_lock);
1509 
1510 	nfs4_end_open_seqid_sync(oop);
1511 
1512 	if (created_osp && recov_state.rs_sp != NULL) {
1513 		mutex_enter(&recov_state.rs_sp->s_lock);
1514 		nfs4_inc_state_ref_count_nolock(recov_state.rs_sp, VTOMI4(dvp));
1515 		mutex_exit(&recov_state.rs_sp->s_lock);
1516 	}
1517 
1518 	/* get rid of our reference to find oop */
1519 	open_owner_rele(oop);
1520 
1521 	open_stream_rele(osp, rp);
1522 
1523 	/* accept delegation, if any */
1524 	nfs4_delegation_accept(rp, CLAIM_NULL, op_res, garp, cred_otw);
1525 
1526 	nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1527 
1528 	if (createmode == EXCLUSIVE4 &&
1529 	    (in_va->va_mask & ~(AT_GID | AT_SIZE))) {
1530 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw:"
1531 		    " EXCLUSIVE4: sending a SETATTR"));
1532 		/*
1533 		 * If doing an exclusive create, then generate
1534 		 * a SETATTR to set the initial attributes.
1535 		 * Try to set the mtime and the atime to the
1536 		 * server's current time.  It is somewhat
1537 		 * expected that these fields will be used to
1538 		 * store the exclusive create cookie.  If not,
1539 		 * server implementors will need to know that
1540 		 * a SETATTR will follow an exclusive create
1541 		 * and the cookie should be destroyed if
1542 		 * appropriate.
1543 		 *
1544 		 * The AT_GID and AT_SIZE bits are turned off
1545 		 * so that the SETATTR request will not attempt
1546 		 * to process these.  The gid will be set
1547 		 * separately if appropriate.  The size is turned
1548 		 * off because it is assumed that a new file will
1549 		 * be created empty and if the file wasn't empty,
1550 		 * then the exclusive create will have failed
1551 		 * because the file must have existed already.
1552 		 * Therefore, no truncate operation is needed.
1553 		 */
1554 		in_va->va_mask &= ~(AT_GID | AT_SIZE);
1555 		in_va->va_mask |= (AT_MTIME | AT_ATIME);
1556 
1557 		e.error = nfs4setattr(vp, in_va, 0, cr, NULL);
1558 		if (e.error) {
1559 			nfs4_error_t err;
1560 
1561 			/*
1562 			 * Couldn't correct the attributes of
1563 			 * the newly created file and the
1564 			 * attributes are wrong.  Remove the
1565 			 * file and return an error to the
1566 			 * application.
1567 			 */
1568 			/* XXX will this take care of client state ? */
1569 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1570 			    "nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1571 			    " remove file", e.error));
1572 
1573 			/*
1574 			 * The file is currently open so try to close it first.
1575 			 *
1576 			 * If we do not close the file explicitly here then the
1577 			 * VN_RELE() would do an (implicit and asynchronous)
1578 			 * close for us.  But such async close could race with
1579 			 * the nfs4_remove() below.  If the async close is
1580 			 * slower than nfs4_remove() then nfs4_remove()
1581 			 * wouldn't remove the file but rename it to .nfsXXXX
1582 			 * instead.
1583 			 */
1584 			nfs4close_one(vp, NULL, cr, open_flag, NULL, &err,
1585 			    CLOSE_NORM, 0, 0, 0);
1586 			VN_RELE(vp);
1587 			(void) nfs4_remove(dvp, file_name, cr, NULL, 0);
1588 
1589 			/*
1590 			 * Since we've reled the vnode and removed
1591 			 * the file we now need to return the error.
1592 			 * At this point we don't want to update the
1593 			 * dircaches, call nfs4_waitfor_purge_complete
1594 			 * or set vpp to vp so we need to skip these
1595 			 * as well.
1596 			 */
1597 			goto skip_update_dircaches;
1598 		}
1599 	}
1600 
1601 	/*
1602 	 * If we created or found the correct vnode, due to create_flag or
1603 	 * fh_differs being set, then update directory cache attribute, readdir
1604 	 * and dnlc caches.
1605 	 */
1606 	if (create_flag || fh_differs) {
1607 		dirattr_info_t dinfo, *dinfop;
1608 
1609 		/*
1610 		 * Make sure getattr succeeded before using results.
1611 		 * note: op 7 is getattr(dir) for both flavors of
1612 		 * open(create).
1613 		 */
1614 		if (create_flag && res.status == NFS4_OK) {
1615 			dinfo.di_time_call = t;
1616 			dinfo.di_cred = cr;
1617 			dinfo.di_garp =
1618 			    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
1619 			dinfop = &dinfo;
1620 		} else {
1621 			dinfop = NULL;
1622 		}
1623 
1624 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1625 		    dinfop);
1626 	}
1627 
1628 	/*
1629 	 * If the page cache for this file was flushed from actions
1630 	 * above, it was done asynchronously and if that is true,
1631 	 * there is a need to wait here for it to complete.  This must
1632 	 * be done outside of start_fop/end_fop.
1633 	 */
1634 	(void) nfs4_waitfor_purge_complete(vp);
1635 
1636 	/*
1637 	 * It is implicit that we are in the open case (create_flag == 0) since
1638 	 * fh_differs can only be set to a non-zero value in the open case.
1639 	 */
1640 	if (fh_differs != 0 && vpi != NULL)
1641 		VN_RELE(vpi);
1642 
1643 	/*
1644 	 * Be sure to set *vpp to the correct value before returning.
1645 	 */
1646 	*vpp = vp;
1647 
1648 skip_update_dircaches:
1649 
1650 	nfs4args_copen_free(open_args);
1651 	if (setgid_flag) {
1652 		nfs4args_verify_free(&argop[8]);
1653 		nfs4args_setattr_free(&argop[9]);
1654 	}
1655 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1656 
1657 	if (ncr)
1658 		crfree(ncr);
1659 	kmem_free(argop, argoplist_size);
1660 	return (e.error);
1661 }
1662 
1663 /*
1664  * Reopen an open instance.  cf. nfs4open_otw().
1665  *
1666  * Errors are returned by the nfs4_error_t parameter.
1667  * - ep->error contains an errno value or zero.
1668  * - if it is zero, ep->stat is set to an NFS status code, if any.
1669  *   If the file could not be reopened, but the caller should continue, the
1670  *   file is marked dead and no error values are returned.  If the caller
1671  *   should stop recovering open files and start over, either the ep->error
1672  *   value or ep->stat will indicate an error (either something that requires
1673  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1674  *   filehandles) may be handled silently by this routine.
1675  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1676  *   will be started, so the caller should not do it.
1677  *
1678  * Gotos:
1679  * - kill_file : reopen failed in such a fashion to constitute marking the
1680  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1681  *   is for cases where recovery is not possible.
1682  * - failed_reopen : same as above, except that the file has already been
1683  *   marked dead, so no need to do it again.
1684  * - bailout : reopen failed but we are able to recover and retry the reopen -
1685  *   either within this function immediately or via the calling function.
1686  */
1687 
1688 void
1689 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1690     open_claim_type4 claim, bool_t frc_use_claim_previous,
1691     bool_t is_recov)
1692 {
1693 	COMPOUND4args_clnt args;
1694 	COMPOUND4res_clnt res;
1695 	nfs_argop4 argop[4];
1696 	nfs_resop4 *resop;
1697 	OPEN4res *op_res = NULL;
1698 	OPEN4cargs *open_args;
1699 	GETFH4res *gf_res;
1700 	rnode4_t *rp = VTOR4(vp);
1701 	int doqueue = 1;
1702 	cred_t *cr = NULL, *cred_otw = NULL;
1703 	nfs4_open_owner_t *oop = NULL;
1704 	seqid4 seqid;
1705 	nfs4_ga_res_t *garp;
1706 	char fn[MAXNAMELEN];
1707 	nfs4_recov_state_t recov = {NULL, 0};
1708 	nfs4_lost_rqst_t lost_rqst;
1709 	mntinfo4_t *mi = VTOMI4(vp);
1710 	bool_t abort;
1711 	char *failed_msg = "";
1712 	int fh_different;
1713 	hrtime_t t;
1714 	nfs4_bseqid_entry_t *bsep = NULL;
1715 
1716 	ASSERT(nfs4_consistent_type(vp));
1717 	ASSERT(nfs_zone() == mi->mi_zone);
1718 
1719 	nfs4_error_zinit(ep);
1720 
1721 	/* this is the cred used to find the open owner */
1722 	cr = state_to_cred(osp);
1723 	if (cr == NULL) {
1724 		failed_msg = "Couldn't reopen: no cred";
1725 		goto kill_file;
1726 	}
1727 	/* use this cred for OTW operations */
1728 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1729 
1730 top:
1731 	nfs4_error_zinit(ep);
1732 
1733 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1734 		/* File system has been unmounted, quit */
1735 		ep->error = EIO;
1736 		failed_msg = "Couldn't reopen: file system has been unmounted";
1737 		goto kill_file;
1738 	}
1739 
1740 	oop = osp->os_open_owner;
1741 
1742 	ASSERT(oop != NULL);
1743 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1744 		failed_msg = "can't reopen: no open owner";
1745 		goto kill_file;
1746 	}
1747 	open_owner_hold(oop);
1748 
1749 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1750 	if (ep->error) {
1751 		open_owner_rele(oop);
1752 		oop = NULL;
1753 		goto bailout;
1754 	}
1755 
1756 	/*
1757 	 * If the rnode has a delegation and the delegation has been
1758 	 * recovered and the server didn't request a recall and the caller
1759 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1760 	 * recovery) and the rnode hasn't been marked dead, then install
1761 	 * the delegation stateid in the open stream.  Otherwise, proceed
1762 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1763 	 */
1764 	mutex_enter(&rp->r_statev4_lock);
1765 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1766 	    !rp->r_deleg_return_pending &&
1767 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1768 	    !rp->r_deleg_needs_recall &&
1769 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1770 	    !(rp->r_flags & R4RECOVERR)) {
1771 		mutex_enter(&osp->os_sync_lock);
1772 		osp->os_delegation = 1;
1773 		osp->open_stateid = rp->r_deleg_stateid;
1774 		mutex_exit(&osp->os_sync_lock);
1775 		mutex_exit(&rp->r_statev4_lock);
1776 		goto bailout;
1777 	}
1778 	mutex_exit(&rp->r_statev4_lock);
1779 
1780 	/*
1781 	 * If the file failed recovery, just quit.  This failure need not
1782 	 * affect other reopens, so don't return an error.
1783 	 */
1784 	mutex_enter(&rp->r_statelock);
1785 	if (rp->r_flags & R4RECOVERR) {
1786 		mutex_exit(&rp->r_statelock);
1787 		ep->error = 0;
1788 		goto failed_reopen;
1789 	}
1790 	mutex_exit(&rp->r_statelock);
1791 
1792 	/*
1793 	 * argop is empty here
1794 	 *
1795 	 * PUTFH, OPEN, GETATTR
1796 	 */
1797 	args.ctag = TAG_REOPEN;
1798 	args.array_len = 4;
1799 	args.array = argop;
1800 
1801 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1802 	    "nfs4_reopen: file is type %d, id %s",
1803 	    vp->v_type, rnode4info(VTOR4(vp))));
1804 
1805 	argop[0].argop = OP_CPUTFH;
1806 
1807 	if (claim != CLAIM_PREVIOUS) {
1808 		/*
1809 		 * if this is a file mount then
1810 		 * use the mntinfo parentfh
1811 		 */
1812 		argop[0].nfs_argop4_u.opcputfh.sfh =
1813 		    (vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1814 		    VTOSV(vp)->sv_dfh;
1815 	} else {
1816 		/* putfh fh to reopen */
1817 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1818 	}
1819 
1820 	argop[1].argop = OP_COPEN;
1821 	open_args = &argop[1].nfs_argop4_u.opcopen;
1822 	open_args->claim = claim;
1823 
1824 	if (claim == CLAIM_NULL) {
1825 
1826 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1827 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1828 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1829 			    (void *)vp);
1830 			failed_msg = "Couldn't reopen: vtoname failed for "
1831 			    "CLAIM_NULL";
1832 			/* nothing allocated yet */
1833 			goto kill_file;
1834 		}
1835 
1836 		open_args->open_claim4_u.cfile = fn;
1837 	} else if (claim == CLAIM_PREVIOUS) {
1838 
1839 		/*
1840 		 * We have two cases to deal with here:
1841 		 * 1) We're being called to reopen files in order to satisfy
1842 		 *    a lock operation request which requires us to explicitly
1843 		 *    reopen files which were opened under a delegation.  If
1844 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1845 		 *    that case, frc_use_claim_previous is TRUE and we must
1846 		 *    use the rnode's current delegation type (r_deleg_type).
1847 		 * 2) We're reopening files during some form of recovery.
1848 		 *    In this case, frc_use_claim_previous is FALSE and we
1849 		 *    use the delegation type appropriate for recovery
1850 		 *    (r_deleg_needs_recovery).
1851 		 */
1852 		mutex_enter(&rp->r_statev4_lock);
1853 		open_args->open_claim4_u.delegate_type =
1854 		    frc_use_claim_previous ?
1855 		    rp->r_deleg_type :
1856 		    rp->r_deleg_needs_recovery;
1857 		mutex_exit(&rp->r_statev4_lock);
1858 
1859 	} else if (claim == CLAIM_DELEGATE_CUR) {
1860 
1861 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1862 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1863 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1864 			    "with %m", (void *)vp);
1865 			failed_msg = "Couldn't reopen: vtoname failed for "
1866 			    "CLAIM_DELEGATE_CUR";
1867 			/* nothing allocated yet */
1868 			goto kill_file;
1869 		}
1870 
1871 		mutex_enter(&rp->r_statev4_lock);
1872 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1873 		    rp->r_deleg_stateid;
1874 		mutex_exit(&rp->r_statev4_lock);
1875 
1876 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1877 	}
1878 	open_args->opentype = OPEN4_NOCREATE;
1879 	open_args->owner.clientid = mi2clientid(mi);
1880 	open_args->owner.owner_len = sizeof (oop->oo_name);
1881 	open_args->owner.owner_val =
1882 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1883 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1884 	    open_args->owner.owner_len);
1885 	open_args->share_access = 0;
1886 	open_args->share_deny = 0;
1887 
1888 	mutex_enter(&osp->os_sync_lock);
1889 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1890 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1891 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1892 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1893 	    osp->os_share_acc_write, osp->os_open_ref_count,
1894 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1895 
1896 	if (osp->os_share_acc_read || osp->os_mmap_read)
1897 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1898 	if (osp->os_share_acc_write || osp->os_mmap_write)
1899 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1900 	if (osp->os_share_deny_read)
1901 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1902 	if (osp->os_share_deny_write)
1903 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1904 	mutex_exit(&osp->os_sync_lock);
1905 
1906 	seqid = nfs4_get_open_seqid(oop) + 1;
1907 	open_args->seqid = seqid;
1908 
1909 	/* Construct the getfh part of the compound */
1910 	argop[2].argop = OP_GETFH;
1911 
1912 	/* Construct the getattr part of the compound */
1913 	argop[3].argop = OP_GETATTR;
1914 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1915 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1916 
1917 	t = gethrtime();
1918 
1919 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1920 
1921 	if (ep->error) {
1922 		if (!is_recov && !frc_use_claim_previous &&
1923 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1924 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1925 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1926 			    cred_otw, vp, NULL, open_args);
1927 			abort = nfs4_start_recovery(ep,
1928 			    VTOMI4(vp), vp, NULL, NULL,
1929 			    lost_rqst.lr_op == OP_OPEN ?
1930 			    &lost_rqst : NULL, OP_OPEN, NULL, NULL, NULL);
1931 			nfs4args_copen_free(open_args);
1932 			goto bailout;
1933 		}
1934 
1935 		nfs4args_copen_free(open_args);
1936 
1937 		if (ep->error == EACCES && cred_otw != cr) {
1938 			crfree(cred_otw);
1939 			cred_otw = cr;
1940 			crhold(cred_otw);
1941 			nfs4_end_open_seqid_sync(oop);
1942 			open_owner_rele(oop);
1943 			oop = NULL;
1944 			goto top;
1945 		}
1946 		if (ep->error == ETIMEDOUT)
1947 			goto bailout;
1948 		failed_msg = "Couldn't reopen: rpc error";
1949 		goto kill_file;
1950 	}
1951 
1952 	if (nfs4_need_to_bump_seqid(&res))
1953 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1954 
1955 	switch (res.status) {
1956 	case NFS4_OK:
1957 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1958 			mutex_enter(&rp->r_statelock);
1959 			rp->r_delay_interval = 0;
1960 			mutex_exit(&rp->r_statelock);
1961 		}
1962 		break;
1963 	case NFS4ERR_BAD_SEQID:
1964 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1965 		    args.ctag, open_args->seqid);
1966 
1967 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1968 		    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1969 		    NULL, OP_OPEN, bsep, NULL, NULL);
1970 
1971 		nfs4args_copen_free(open_args);
1972 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1973 		nfs4_end_open_seqid_sync(oop);
1974 		open_owner_rele(oop);
1975 		oop = NULL;
1976 		kmem_free(bsep, sizeof (*bsep));
1977 
1978 		goto kill_file;
1979 	case NFS4ERR_NO_GRACE:
1980 		nfs4args_copen_free(open_args);
1981 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1982 		nfs4_end_open_seqid_sync(oop);
1983 		open_owner_rele(oop);
1984 		oop = NULL;
1985 		if (claim == CLAIM_PREVIOUS) {
1986 			/*
1987 			 * Retry as a plain open. We don't need to worry about
1988 			 * checking the changeinfo: it is acceptable for a
1989 			 * client to re-open a file and continue processing
1990 			 * (in the absence of locks).
1991 			 */
1992 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1993 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1994 			    "will retry as CLAIM_NULL"));
1995 			claim = CLAIM_NULL;
1996 			nfs4_mi_kstat_inc_no_grace(mi);
1997 			goto top;
1998 		}
1999 		failed_msg =
2000 		    "Couldn't reopen: tried reclaim outside grace period. ";
2001 		goto kill_file;
2002 	case NFS4ERR_GRACE:
2003 		nfs4_set_grace_wait(mi);
2004 		nfs4args_copen_free(open_args);
2005 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2006 		nfs4_end_open_seqid_sync(oop);
2007 		open_owner_rele(oop);
2008 		oop = NULL;
2009 		ep->error = nfs4_wait_for_grace(mi, &recov);
2010 		if (ep->error != 0)
2011 			goto bailout;
2012 		goto top;
2013 	case NFS4ERR_DELAY:
2014 		nfs4_set_delay_wait(vp);
2015 		nfs4args_copen_free(open_args);
2016 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2017 		nfs4_end_open_seqid_sync(oop);
2018 		open_owner_rele(oop);
2019 		oop = NULL;
2020 		ep->error = nfs4_wait_for_delay(vp, &recov);
2021 		nfs4_mi_kstat_inc_delay(mi);
2022 		if (ep->error != 0)
2023 			goto bailout;
2024 		goto top;
2025 	case NFS4ERR_FHEXPIRED:
2026 		/* recover filehandle and retry */
2027 		abort = nfs4_start_recovery(ep,
2028 		    mi, vp, NULL, NULL, NULL, OP_OPEN, NULL, NULL, NULL);
2029 		nfs4args_copen_free(open_args);
2030 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2031 		nfs4_end_open_seqid_sync(oop);
2032 		open_owner_rele(oop);
2033 		oop = NULL;
2034 		if (abort == FALSE)
2035 			goto top;
2036 		failed_msg = "Couldn't reopen: recovery aborted";
2037 		goto kill_file;
2038 	case NFS4ERR_RESOURCE:
2039 	case NFS4ERR_STALE_CLIENTID:
2040 	case NFS4ERR_WRONGSEC:
2041 	case NFS4ERR_EXPIRED:
2042 		/*
2043 		 * Do not mark the file dead and let the calling
2044 		 * function initiate recovery.
2045 		 */
2046 		nfs4args_copen_free(open_args);
2047 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2048 		nfs4_end_open_seqid_sync(oop);
2049 		open_owner_rele(oop);
2050 		oop = NULL;
2051 		goto bailout;
2052 	case NFS4ERR_ACCESS:
2053 		if (cred_otw != cr) {
2054 			crfree(cred_otw);
2055 			cred_otw = cr;
2056 			crhold(cred_otw);
2057 			nfs4args_copen_free(open_args);
2058 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2059 			nfs4_end_open_seqid_sync(oop);
2060 			open_owner_rele(oop);
2061 			oop = NULL;
2062 			goto top;
2063 		}
2064 		/* fall through */
2065 	default:
2066 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2067 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2068 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2069 		    rnode4info(VTOR4(vp))));
2070 		failed_msg = "Couldn't reopen: NFSv4 error";
2071 		nfs4args_copen_free(open_args);
2072 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2073 		goto kill_file;
2074 	}
2075 
2076 	resop = &res.array[1];  /* open res */
2077 	op_res = &resop->nfs_resop4_u.opopen;
2078 
2079 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2080 
2081 	/*
2082 	 * Check if the path we reopened really is the same
2083 	 * file. We could end up in a situation where the file
2084 	 * was removed and a new file created with the same name.
2085 	 */
2086 	resop = &res.array[2];
2087 	gf_res = &resop->nfs_resop4_u.opgetfh;
2088 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2089 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2090 	if (fh_different) {
2091 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2092 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2093 			/* Oops, we don't have the same file */
2094 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2095 				failed_msg = "Couldn't reopen: Persistent "
2096 				    "file handle changed";
2097 			else
2098 				failed_msg = "Couldn't reopen: Volatile "
2099 				    "(no expire on open) file handle changed";
2100 
2101 			nfs4args_copen_free(open_args);
2102 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2103 			nfs_rw_exit(&mi->mi_fh_lock);
2104 			goto kill_file;
2105 
2106 		} else {
2107 			/*
2108 			 * We have volatile file handles that don't compare.
2109 			 * If the fids are the same then we assume that the
2110 			 * file handle expired but the rnode still refers to
2111 			 * the same file object.
2112 			 *
2113 			 * First check that we have fids or not.
2114 			 * If we don't we have a dumb server so we will
2115 			 * just assume every thing is ok for now.
2116 			 */
2117 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2118 			    rp->r_attr.va_mask & AT_NODEID &&
2119 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2120 				/*
2121 				 * We have fids, but they don't
2122 				 * compare. So kill the file.
2123 				 */
2124 				failed_msg =
2125 				    "Couldn't reopen: file handle changed"
2126 				    " due to mismatched fids";
2127 				nfs4args_copen_free(open_args);
2128 				xdr_free(xdr_COMPOUND4res_clnt,
2129 				    (caddr_t)&res);
2130 				nfs_rw_exit(&mi->mi_fh_lock);
2131 				goto kill_file;
2132 			} else {
2133 				/*
2134 				 * We have volatile file handles that refers
2135 				 * to the same file (at least they have the
2136 				 * same fid) or we don't have fids so we
2137 				 * can't tell. :(. We'll be a kind and accepting
2138 				 * client so we'll update the rnode's file
2139 				 * handle with the otw handle.
2140 				 *
2141 				 * We need to drop mi->mi_fh_lock since
2142 				 * sh4_update acquires it. Since there is
2143 				 * only one recovery thread there is no
2144 				 * race.
2145 				 */
2146 				nfs_rw_exit(&mi->mi_fh_lock);
2147 				sfh4_update(rp->r_fh, &gf_res->object);
2148 			}
2149 		}
2150 	} else {
2151 		nfs_rw_exit(&mi->mi_fh_lock);
2152 	}
2153 
2154 	ASSERT(nfs4_consistent_type(vp));
2155 
2156 	/*
2157 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2158 	 * over.  Presumably if there is a persistent error it will show up
2159 	 * when we resend the OPEN.
2160 	 */
2161 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2162 		bool_t retry_open = FALSE;
2163 
2164 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2165 		    cred_otw, is_recov, &retry_open,
2166 		    oop, FALSE, ep, NULL);
2167 		if (ep->error || ep->stat) {
2168 			nfs4args_copen_free(open_args);
2169 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2170 			nfs4_end_open_seqid_sync(oop);
2171 			open_owner_rele(oop);
2172 			oop = NULL;
2173 			goto top;
2174 		}
2175 	}
2176 
2177 	mutex_enter(&osp->os_sync_lock);
2178 	osp->open_stateid = op_res->stateid;
2179 	osp->os_delegation = 0;
2180 	/*
2181 	 * Need to reset this bitfield for the possible case where we were
2182 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2183 	 * we could retry the CLOSE, OPENed the file again.
2184 	 */
2185 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2186 	osp->os_final_close = 0;
2187 	osp->os_force_close = 0;
2188 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2189 		osp->os_dc_openacc = open_args->share_access;
2190 	mutex_exit(&osp->os_sync_lock);
2191 
2192 	nfs4_end_open_seqid_sync(oop);
2193 
2194 	/* accept delegation, if any */
2195 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2196 
2197 	nfs4args_copen_free(open_args);
2198 
2199 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2200 
2201 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2202 
2203 	ASSERT(nfs4_consistent_type(vp));
2204 
2205 	open_owner_rele(oop);
2206 	crfree(cr);
2207 	crfree(cred_otw);
2208 	return;
2209 
2210 kill_file:
2211 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2212 failed_reopen:
2213 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2214 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2215 	    (void *)osp, (void *)cr, rnode4info(rp)));
2216 	mutex_enter(&osp->os_sync_lock);
2217 	osp->os_failed_reopen = 1;
2218 	mutex_exit(&osp->os_sync_lock);
2219 bailout:
2220 	if (oop != NULL) {
2221 		nfs4_end_open_seqid_sync(oop);
2222 		open_owner_rele(oop);
2223 	}
2224 	if (cr != NULL)
2225 		crfree(cr);
2226 	if (cred_otw != NULL)
2227 		crfree(cred_otw);
2228 }
2229 
2230 /* for . and .. OPENs */
2231 /* ARGSUSED */
2232 static int
2233 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2234 {
2235 	rnode4_t *rp;
2236 	nfs4_ga_res_t gar;
2237 
2238 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2239 
2240 	/*
2241 	 * If close-to-open consistency checking is turned off or
2242 	 * if there is no cached data, we can avoid
2243 	 * the over the wire getattr.  Otherwise, force a
2244 	 * call to the server to get fresh attributes and to
2245 	 * check caches. This is required for close-to-open
2246 	 * consistency.
2247 	 */
2248 	rp = VTOR4(*vpp);
2249 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2250 	    (rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2251 		return (0);
2252 
2253 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2254 }
2255 
2256 /*
2257  * CLOSE a file
2258  */
2259 /* ARGSUSED */
2260 static int
2261 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
2262     caller_context_t *ct)
2263 {
2264 	rnode4_t	*rp;
2265 	int		 error = 0;
2266 	int		 r_error = 0;
2267 	int		 n4error = 0;
2268 	nfs4_error_t	 e = { 0, NFS4_OK, RPC_SUCCESS };
2269 
2270 	/*
2271 	 * Remove client state for this (lockowner, file) pair.
2272 	 * Issue otw v4 call to have the server do the same.
2273 	 */
2274 
2275 	rp = VTOR4(vp);
2276 
2277 	/*
2278 	 * zone_enter(2) prevents processes from changing zones with NFS files
2279 	 * open; if we happen to get here from the wrong zone we can't do
2280 	 * anything over the wire.
2281 	 */
2282 	if (VTOMI4(vp)->mi_zone != nfs_zone()) {
2283 		/*
2284 		 * We could attempt to clean up locks, except we're sure
2285 		 * that the current process didn't acquire any locks on
2286 		 * the file: any attempt to lock a file belong to another zone
2287 		 * will fail, and one can't lock an NFS file and then change
2288 		 * zones, as that fails too.
2289 		 *
2290 		 * Returning an error here is the sane thing to do.  A
2291 		 * subsequent call to VN_RELE() which translates to a
2292 		 * nfs4_inactive() will clean up state: if the zone of the
2293 		 * vnode's origin is still alive and kicking, the inactive
2294 		 * thread will handle the request (from the correct zone), and
2295 		 * everything (minus the OTW close call) should be OK.  If the
2296 		 * zone is going away nfs4_async_inactive() will throw away
2297 		 * delegations, open streams and cached pages inline.
2298 		 */
2299 		return (EIO);
2300 	}
2301 
2302 	/*
2303 	 * If we are using local locking for this filesystem, then
2304 	 * release all of the SYSV style record locks.  Otherwise,
2305 	 * we are doing network locking and we need to release all
2306 	 * of the network locks.  All of the locks held by this
2307 	 * process on this file are released no matter what the
2308 	 * incoming reference count is.
2309 	 */
2310 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK) {
2311 		cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
2312 		cleanshares(vp, ttoproc(curthread)->p_pid);
2313 	} else
2314 		e.error = nfs4_lockrelease(vp, flag, offset, cr);
2315 
2316 	if (e.error) {
2317 		struct lm_sysid *lmsid;
2318 		lmsid = nfs4_find_sysid(VTOMI4(vp));
2319 		if (lmsid == NULL) {
2320 			DTRACE_PROBE2(unknown__sysid, int, e.error,
2321 			    vnode_t *, vp);
2322 		} else {
2323 			cleanlocks(vp, ttoproc(curthread)->p_pid,
2324 			    (lm_sysidt(lmsid) | LM_SYSID_CLIENT));
2325 
2326 			lm_rel_sysid(lmsid);
2327 		}
2328 		return (e.error);
2329 	}
2330 
2331 	if (count > 1)
2332 		return (0);
2333 
2334 	/*
2335 	 * If the file has been `unlinked', then purge the
2336 	 * DNLC so that this vnode will get reycled quicker
2337 	 * and the .nfs* file on the server will get removed.
2338 	 */
2339 	if (rp->r_unldvp != NULL)
2340 		dnlc_purge_vp(vp);
2341 
2342 	/*
2343 	 * If the file was open for write and there are pages,
2344 	 * do a synchronous flush and commit of all of the
2345 	 * dirty and uncommitted pages.
2346 	 */
2347 	ASSERT(!e.error);
2348 	if ((flag & FWRITE) && nfs4_has_pages(vp))
2349 		error = nfs4_putpage_commit(vp, 0, 0, cr);
2350 
2351 	mutex_enter(&rp->r_statelock);
2352 	r_error = rp->r_error;
2353 	rp->r_error = 0;
2354 	mutex_exit(&rp->r_statelock);
2355 
2356 	/*
2357 	 * If this file type is one for which no explicit 'open' was
2358 	 * done, then bail now (ie. no need for protocol 'close'). If
2359 	 * there was an error w/the vm subsystem, return _that_ error,
2360 	 * otherwise, return any errors that may've been reported via
2361 	 * the rnode.
2362 	 */
2363 	if (vp->v_type != VREG)
2364 		return (error ? error : r_error);
2365 
2366 	/*
2367 	 * The sync putpage commit may have failed above, but since
2368 	 * we're working w/a regular file, we need to do the protocol
2369 	 * 'close' (nfs4close_one will figure out if an otw close is
2370 	 * needed or not). Report any errors _after_ doing the protocol
2371 	 * 'close'.
2372 	 */
2373 	nfs4close_one(vp, NULL, cr, flag, NULL, &e, CLOSE_NORM, 0, 0, 0);
2374 	n4error = e.error ? e.error : geterrno4(e.stat);
2375 
2376 	/*
2377 	 * Error reporting prio (Hi -> Lo)
2378 	 *
2379 	 *   i) nfs4_putpage_commit (error)
2380 	 *  ii) rnode's (r_error)
2381 	 * iii) nfs4close_one (n4error)
2382 	 */
2383 	return (error ? error : (r_error ? r_error : n4error));
2384 }
2385 
2386 /*
2387  * Initialize *lost_rqstp.
2388  */
2389 
2390 static void
2391 nfs4close_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
2392     nfs4_open_owner_t *oop, nfs4_open_stream_t *osp, cred_t *cr,
2393     vnode_t *vp)
2394 {
2395 	if (error != ETIMEDOUT && error != EINTR &&
2396 	    !NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
2397 		lost_rqstp->lr_op = 0;
2398 		return;
2399 	}
2400 
2401 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
2402 	    "nfs4close_save_lost_rqst: error %d", error));
2403 
2404 	lost_rqstp->lr_op = OP_CLOSE;
2405 	/*
2406 	 * The vp is held and rele'd via the recovery code.
2407 	 * See nfs4_save_lost_rqst.
2408 	 */
2409 	lost_rqstp->lr_vp = vp;
2410 	lost_rqstp->lr_dvp = NULL;
2411 	lost_rqstp->lr_oop = oop;
2412 	lost_rqstp->lr_osp = osp;
2413 	ASSERT(osp != NULL);
2414 	ASSERT(mutex_owned(&osp->os_sync_lock));
2415 	osp->os_pending_close = 1;
2416 	lost_rqstp->lr_lop = NULL;
2417 	lost_rqstp->lr_cr = cr;
2418 	lost_rqstp->lr_flk = NULL;
2419 	lost_rqstp->lr_putfirst = FALSE;
2420 }
2421 
2422 /*
2423  * Assumes you already have the open seqid sync grabbed as well as the
2424  * 'os_sync_lock'.  Note: this will release the open seqid sync and
2425  * 'os_sync_lock' if client recovery starts.  Calling functions have to
2426  * be prepared to handle this.
2427  *
2428  * 'recov' is returned as 1 if the CLOSE operation detected client recovery
2429  * was needed and was started, and that the calling function should retry
2430  * this function; otherwise it is returned as 0.
2431  *
2432  * Errors are returned via the nfs4_error_t parameter.
2433  */
2434 static void
2435 nfs4close_otw(rnode4_t *rp, cred_t *cred_otw, nfs4_open_owner_t *oop,
2436     nfs4_open_stream_t *osp, int *recov, int *did_start_seqid_syncp,
2437     nfs4_close_type_t close_type, nfs4_error_t *ep, int *have_sync_lockp)
2438 {
2439 	COMPOUND4args_clnt args;
2440 	COMPOUND4res_clnt res;
2441 	CLOSE4args *close_args;
2442 	nfs_resop4 *resop;
2443 	nfs_argop4 argop[3];
2444 	int doqueue = 1;
2445 	mntinfo4_t *mi;
2446 	seqid4 seqid;
2447 	vnode_t *vp;
2448 	bool_t needrecov = FALSE;
2449 	nfs4_lost_rqst_t lost_rqst;
2450 	hrtime_t t;
2451 
2452 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
2453 
2454 	ASSERT(MUTEX_HELD(&osp->os_sync_lock));
2455 
2456 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw"));
2457 
2458 	/* Only set this to 1 if recovery is started */
2459 	*recov = 0;
2460 
2461 	/* do the OTW call to close the file */
2462 
2463 	if (close_type == CLOSE_RESEND)
2464 		args.ctag = TAG_CLOSE_LOST;
2465 	else if (close_type == CLOSE_AFTER_RESEND)
2466 		args.ctag = TAG_CLOSE_UNDO;
2467 	else
2468 		args.ctag = TAG_CLOSE;
2469 
2470 	args.array_len = 3;
2471 	args.array = argop;
2472 
2473 	vp = RTOV4(rp);
2474 
2475 	mi = VTOMI4(vp);
2476 
2477 	/* putfh target fh */
2478 	argop[0].argop = OP_CPUTFH;
2479 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
2480 
2481 	argop[1].argop = OP_GETATTR;
2482 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
2483 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
2484 
2485 	argop[2].argop = OP_CLOSE;
2486 	close_args = &argop[2].nfs_argop4_u.opclose;
2487 
2488 	seqid = nfs4_get_open_seqid(oop) + 1;
2489 
2490 	close_args->seqid = seqid;
2491 	close_args->open_stateid = osp->open_stateid;
2492 
2493 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
2494 	    "nfs4close_otw: %s call, rp %s", needrecov ? "recov" : "first",
2495 	    rnode4info(rp)));
2496 
2497 	t = gethrtime();
2498 
2499 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
2500 
2501 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
2502 		nfs4_set_open_seqid(seqid, oop, args.ctag);
2503 	}
2504 
2505 	needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
2506 	if (ep->error && !needrecov) {
2507 		/*
2508 		 * if there was an error and no recovery is to be done
2509 		 * then then set up the file to flush its cache if
2510 		 * needed for the next caller.
2511 		 */
2512 		mutex_enter(&rp->r_statelock);
2513 		PURGE_ATTRCACHE4_LOCKED(rp);
2514 		rp->r_flags &= ~R4WRITEMODIFIED;
2515 		mutex_exit(&rp->r_statelock);
2516 		return;
2517 	}
2518 
2519 	if (needrecov) {
2520 		bool_t abort;
2521 		nfs4_bseqid_entry_t *bsep = NULL;
2522 
2523 		if (close_type != CLOSE_RESEND)
2524 			nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
2525 			    osp, cred_otw, vp);
2526 
2527 		if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
2528 			bsep = nfs4_create_bseqid_entry(oop, NULL, vp,
2529 			    0, args.ctag, close_args->seqid);
2530 
2531 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
2532 		    "nfs4close_otw: initiating recovery. error %d "
2533 		    "res.status %d", ep->error, res.status));
2534 
2535 		/*
2536 		 * Drop the 'os_sync_lock' here so we don't hit
2537 		 * a potential recursive mutex_enter via an
2538 		 * 'open_stream_hold()'.
2539 		 */
2540 		mutex_exit(&osp->os_sync_lock);
2541 		*have_sync_lockp = 0;
2542 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
2543 		    (close_type != CLOSE_RESEND &&
2544 		    lost_rqst.lr_op == OP_CLOSE) ? &lost_rqst : NULL,
2545 		    OP_CLOSE, bsep, NULL, NULL);
2546 
2547 		/* drop open seq sync, and let the calling function regrab it */
2548 		nfs4_end_open_seqid_sync(oop);
2549 		*did_start_seqid_syncp = 0;
2550 
2551 		if (bsep)
2552 			kmem_free(bsep, sizeof (*bsep));
2553 		/*
2554 		 * For signals, the caller wants to quit, so don't say to
2555 		 * retry.  For forced unmount, if it's a user thread, it
2556 		 * wants to quit.  If it's a recovery thread, the retry
2557 		 * will happen higher-up on the call stack.  Either way,
2558 		 * don't say to retry.
2559 		 */
2560 		if (abort == FALSE && ep->error != EINTR &&
2561 		    !NFS4_FRC_UNMT_ERR(ep->error, mi->mi_vfsp) &&
2562 		    close_type != CLOSE_RESEND &&
2563 		    close_type != CLOSE_AFTER_RESEND)
2564 			*recov = 1;
2565 		else
2566 			*recov = 0;
2567 
2568 		if (!ep->error)
2569 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2570 		return;
2571 	}
2572 
2573 	if (res.status) {
2574 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2575 		return;
2576 	}
2577 
2578 	mutex_enter(&rp->r_statev4_lock);
2579 	rp->created_v4 = 0;
2580 	mutex_exit(&rp->r_statev4_lock);
2581 
2582 	resop = &res.array[2];
2583 	osp->open_stateid = resop->nfs_resop4_u.opclose.open_stateid;
2584 	osp->os_valid = 0;
2585 
2586 	/*
2587 	 * This removes the reference obtained at OPEN; ie, when the
2588 	 * open stream structure was created.
2589 	 *
2590 	 * We don't have to worry about calling 'open_stream_rele'
2591 	 * since we our currently holding a reference to the open
2592 	 * stream which means the count cannot go to 0 with this
2593 	 * decrement.
2594 	 */
2595 	ASSERT(osp->os_ref_count >= 2);
2596 	osp->os_ref_count--;
2597 
2598 	if (ep->error == 0) {
2599 		mutex_exit(&osp->os_sync_lock);
2600 		*have_sync_lockp = 0;
2601 
2602 		nfs4_attr_cache(vp,
2603 		    &res.array[1].nfs_resop4_u.opgetattr.ga_res,
2604 		    t, cred_otw, TRUE, NULL);
2605 	}
2606 
2607 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw:"
2608 	    " returning %d", ep->error));
2609 
2610 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2611 }
2612 
2613 /* ARGSUSED */
2614 static int
2615 nfs4_read(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2616     caller_context_t *ct)
2617 {
2618 	rnode4_t *rp;
2619 	u_offset_t off;
2620 	offset_t diff;
2621 	uint_t on;
2622 	uint_t n;
2623 	caddr_t base;
2624 	uint_t flags;
2625 	int error;
2626 	mntinfo4_t *mi;
2627 
2628 	rp = VTOR4(vp);
2629 
2630 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2631 
2632 	if (IS_SHADOW(vp, rp))
2633 		vp = RTOV4(rp);
2634 
2635 	if (vp->v_type != VREG)
2636 		return (EISDIR);
2637 
2638 	mi = VTOMI4(vp);
2639 
2640 	if (nfs_zone() != mi->mi_zone)
2641 		return (EIO);
2642 
2643 	if (uiop->uio_resid == 0)
2644 		return (0);
2645 
2646 	if (uiop->uio_loffset < 0 || uiop->uio_loffset + uiop->uio_resid < 0)
2647 		return (EINVAL);
2648 
2649 	mutex_enter(&rp->r_statelock);
2650 	if (rp->r_flags & R4RECOVERRP)
2651 		error = (rp->r_error ? rp->r_error : EIO);
2652 	else
2653 		error = 0;
2654 	mutex_exit(&rp->r_statelock);
2655 	if (error)
2656 		return (error);
2657 
2658 	/*
2659 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2660 	 * using client-side direct I/O and the file is not mmap'd and
2661 	 * there are no cached pages.
2662 	 */
2663 	if ((vp->v_flag & VNOCACHE) ||
2664 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2665 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2666 		size_t resid = 0;
2667 
2668 		return (nfs4read(vp, NULL, uiop->uio_loffset,
2669 		    uiop->uio_resid, &resid, cr, FALSE, uiop));
2670 	}
2671 
2672 	error = 0;
2673 
2674 	do {
2675 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2676 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2677 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2678 
2679 		if (error = nfs4_validate_caches(vp, cr))
2680 			break;
2681 
2682 		mutex_enter(&rp->r_statelock);
2683 		while (rp->r_flags & R4INCACHEPURGE) {
2684 			if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2685 				mutex_exit(&rp->r_statelock);
2686 				return (EINTR);
2687 			}
2688 		}
2689 		diff = rp->r_size - uiop->uio_loffset;
2690 		mutex_exit(&rp->r_statelock);
2691 		if (diff <= 0)
2692 			break;
2693 		if (diff < n)
2694 			n = (uint_t)diff;
2695 
2696 		if (vpm_enable) {
2697 			/*
2698 			 * Copy data.
2699 			 */
2700 			error = vpm_data_copy(vp, off + on, n, uiop,
2701 			    1, NULL, 0, S_READ);
2702 		} else {
2703 			base = segmap_getmapflt(segkmap, vp, off + on, n, 1,
2704 			    S_READ);
2705 
2706 			error = uiomove(base + on, n, UIO_READ, uiop);
2707 		}
2708 
2709 		if (!error) {
2710 			/*
2711 			 * If read a whole block or read to eof,
2712 			 * won't need this buffer again soon.
2713 			 */
2714 			mutex_enter(&rp->r_statelock);
2715 			if (n + on == MAXBSIZE ||
2716 			    uiop->uio_loffset == rp->r_size)
2717 				flags = SM_DONTNEED;
2718 			else
2719 				flags = 0;
2720 			mutex_exit(&rp->r_statelock);
2721 			if (vpm_enable) {
2722 				error = vpm_sync_pages(vp, off, n, flags);
2723 			} else {
2724 				error = segmap_release(segkmap, base, flags);
2725 			}
2726 		} else {
2727 			if (vpm_enable) {
2728 				(void) vpm_sync_pages(vp, off, n, 0);
2729 			} else {
2730 				(void) segmap_release(segkmap, base, 0);
2731 			}
2732 		}
2733 	} while (!error && uiop->uio_resid > 0);
2734 
2735 	return (error);
2736 }
2737 
2738 /* ARGSUSED */
2739 static int
2740 nfs4_write(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2741     caller_context_t *ct)
2742 {
2743 	rlim64_t limit = uiop->uio_llimit;
2744 	rnode4_t *rp;
2745 	u_offset_t off;
2746 	caddr_t base;
2747 	uint_t flags;
2748 	int remainder;
2749 	size_t n;
2750 	int on;
2751 	int error;
2752 	int resid;
2753 	u_offset_t offset;
2754 	mntinfo4_t *mi;
2755 	uint_t bsize;
2756 
2757 	rp = VTOR4(vp);
2758 
2759 	if (IS_SHADOW(vp, rp))
2760 		vp = RTOV4(rp);
2761 
2762 	if (vp->v_type != VREG)
2763 		return (EISDIR);
2764 
2765 	mi = VTOMI4(vp);
2766 
2767 	if (nfs_zone() != mi->mi_zone)
2768 		return (EIO);
2769 
2770 	if (uiop->uio_resid == 0)
2771 		return (0);
2772 
2773 	mutex_enter(&rp->r_statelock);
2774 	if (rp->r_flags & R4RECOVERRP)
2775 		error = (rp->r_error ? rp->r_error : EIO);
2776 	else
2777 		error = 0;
2778 	mutex_exit(&rp->r_statelock);
2779 	if (error)
2780 		return (error);
2781 
2782 	if (ioflag & FAPPEND) {
2783 		struct vattr va;
2784 
2785 		/*
2786 		 * Must serialize if appending.
2787 		 */
2788 		if (nfs_rw_lock_held(&rp->r_rwlock, RW_READER)) {
2789 			nfs_rw_exit(&rp->r_rwlock);
2790 			if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER,
2791 			    INTR4(vp)))
2792 				return (EINTR);
2793 		}
2794 
2795 		va.va_mask = AT_SIZE;
2796 		error = nfs4getattr(vp, &va, cr);
2797 		if (error)
2798 			return (error);
2799 		uiop->uio_loffset = va.va_size;
2800 	}
2801 
2802 	offset = uiop->uio_loffset + uiop->uio_resid;
2803 
2804 	if (uiop->uio_loffset < (offset_t)0 || offset < 0)
2805 		return (EINVAL);
2806 
2807 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
2808 		limit = MAXOFFSET_T;
2809 
2810 	/*
2811 	 * Check to make sure that the process will not exceed
2812 	 * its limit on file size.  It is okay to write up to
2813 	 * the limit, but not beyond.  Thus, the write which
2814 	 * reaches the limit will be short and the next write
2815 	 * will return an error.
2816 	 */
2817 	remainder = 0;
2818 	if (offset > uiop->uio_llimit) {
2819 		remainder = offset - uiop->uio_llimit;
2820 		uiop->uio_resid = uiop->uio_llimit - uiop->uio_loffset;
2821 		if (uiop->uio_resid <= 0) {
2822 			proc_t *p = ttoproc(curthread);
2823 
2824 			uiop->uio_resid += remainder;
2825 			mutex_enter(&p->p_lock);
2826 			(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE],
2827 			    p->p_rctls, p, RCA_UNSAFE_SIGINFO);
2828 			mutex_exit(&p->p_lock);
2829 			return (EFBIG);
2830 		}
2831 	}
2832 
2833 	/* update the change attribute, if we have a write delegation */
2834 
2835 	mutex_enter(&rp->r_statev4_lock);
2836 	if (rp->r_deleg_type == OPEN_DELEGATE_WRITE)
2837 		rp->r_deleg_change++;
2838 
2839 	mutex_exit(&rp->r_statev4_lock);
2840 
2841 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
2842 		return (EINTR);
2843 
2844 	/*
2845 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2846 	 * using client-side direct I/O and the file is not mmap'd and
2847 	 * there are no cached pages.
2848 	 */
2849 	if ((vp->v_flag & VNOCACHE) ||
2850 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2851 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2852 		size_t bufsize;
2853 		int count;
2854 		u_offset_t org_offset;
2855 		stable_how4 stab_comm;
2856 nfs4_fwrite:
2857 		if (rp->r_flags & R4STALE) {
2858 			resid = uiop->uio_resid;
2859 			offset = uiop->uio_loffset;
2860 			error = rp->r_error;
2861 			/*
2862 			 * A close may have cleared r_error, if so,
2863 			 * propagate ESTALE error return properly
2864 			 */
2865 			if (error == 0)
2866 				error = ESTALE;
2867 			goto bottom;
2868 		}
2869 
2870 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2871 		base = kmem_alloc(bufsize, KM_SLEEP);
2872 		do {
2873 			if (ioflag & FDSYNC)
2874 				stab_comm = DATA_SYNC4;
2875 			else
2876 				stab_comm = FILE_SYNC4;
2877 			resid = uiop->uio_resid;
2878 			offset = uiop->uio_loffset;
2879 			count = MIN(uiop->uio_resid, bufsize);
2880 			org_offset = uiop->uio_loffset;
2881 			error = uiomove(base, count, UIO_WRITE, uiop);
2882 			if (!error) {
2883 				error = nfs4write(vp, base, org_offset,
2884 				    count, cr, &stab_comm);
2885 				if (!error) {
2886 					mutex_enter(&rp->r_statelock);
2887 					if (rp->r_size < uiop->uio_loffset)
2888 						rp->r_size = uiop->uio_loffset;
2889 					mutex_exit(&rp->r_statelock);
2890 				}
2891 			}
2892 		} while (!error && uiop->uio_resid > 0);
2893 		kmem_free(base, bufsize);
2894 		goto bottom;
2895 	}
2896 
2897 	bsize = vp->v_vfsp->vfs_bsize;
2898 
2899 	do {
2900 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2901 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2902 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2903 
2904 		resid = uiop->uio_resid;
2905 		offset = uiop->uio_loffset;
2906 
2907 		if (rp->r_flags & R4STALE) {
2908 			error = rp->r_error;
2909 			/*
2910 			 * A close may have cleared r_error, if so,
2911 			 * propagate ESTALE error return properly
2912 			 */
2913 			if (error == 0)
2914 				error = ESTALE;
2915 			break;
2916 		}
2917 
2918 		/*
2919 		 * Don't create dirty pages faster than they
2920 		 * can be cleaned so that the system doesn't
2921 		 * get imbalanced.  If the async queue is
2922 		 * maxed out, then wait for it to drain before
2923 		 * creating more dirty pages.  Also, wait for
2924 		 * any threads doing pagewalks in the vop_getattr
2925 		 * entry points so that they don't block for
2926 		 * long periods.
2927 		 */
2928 		mutex_enter(&rp->r_statelock);
2929 		while ((mi->mi_max_threads != 0 &&
2930 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2931 		    rp->r_gcount > 0) {
2932 			if (INTR4(vp)) {
2933 				klwp_t *lwp = ttolwp(curthread);
2934 
2935 				if (lwp != NULL)
2936 					lwp->lwp_nostop++;
2937 				if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2938 					mutex_exit(&rp->r_statelock);
2939 					if (lwp != NULL)
2940 						lwp->lwp_nostop--;
2941 					error = EINTR;
2942 					goto bottom;
2943 				}
2944 				if (lwp != NULL)
2945 					lwp->lwp_nostop--;
2946 			} else
2947 				cv_wait(&rp->r_cv, &rp->r_statelock);
2948 		}
2949 		mutex_exit(&rp->r_statelock);
2950 
2951 		/*
2952 		 * Touch the page and fault it in if it is not in core
2953 		 * before segmap_getmapflt or vpm_data_copy can lock it.
2954 		 * This is to avoid the deadlock if the buffer is mapped
2955 		 * to the same file through mmap which we want to write.
2956 		 */
2957 		uio_prefaultpages((long)n, uiop);
2958 
2959 		if (vpm_enable) {
2960 			/*
2961 			 * It will use kpm mappings, so no need to
2962 			 * pass an address.
2963 			 */
2964 			error = writerp4(rp, NULL, n, uiop, 0);
2965 		} else  {
2966 			if (segmap_kpm) {
2967 				int pon = uiop->uio_loffset & PAGEOFFSET;
2968 				size_t pn = MIN(PAGESIZE - pon,
2969 				    uiop->uio_resid);
2970 				int pagecreate;
2971 
2972 				mutex_enter(&rp->r_statelock);
2973 				pagecreate = (pon == 0) && (pn == PAGESIZE ||
2974 				    uiop->uio_loffset + pn >= rp->r_size);
2975 				mutex_exit(&rp->r_statelock);
2976 
2977 				base = segmap_getmapflt(segkmap, vp, off + on,
2978 				    pn, !pagecreate, S_WRITE);
2979 
2980 				error = writerp4(rp, base + pon, n, uiop,
2981 				    pagecreate);
2982 
2983 			} else {
2984 				base = segmap_getmapflt(segkmap, vp, off + on,
2985 				    n, 0, S_READ);
2986 				error = writerp4(rp, base + on, n, uiop, 0);
2987 			}
2988 		}
2989 
2990 		if (!error) {
2991 			if (mi->mi_flags & MI4_NOAC)
2992 				flags = SM_WRITE;
2993 			else if ((uiop->uio_loffset % bsize) == 0 ||
2994 			    IS_SWAPVP(vp)) {
2995 				/*
2996 				 * Have written a whole block.
2997 				 * Start an asynchronous write
2998 				 * and mark the buffer to
2999 				 * indicate that it won't be
3000 				 * needed again soon.
3001 				 */
3002 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
3003 			} else
3004 				flags = 0;
3005 			if ((ioflag & (FSYNC|FDSYNC)) ||
3006 			    (rp->r_flags & R4OUTOFSPACE)) {
3007 				flags &= ~SM_ASYNC;
3008 				flags |= SM_WRITE;
3009 			}
3010 			if (vpm_enable) {
3011 				error = vpm_sync_pages(vp, off, n, flags);
3012 			} else {
3013 				error = segmap_release(segkmap, base, flags);
3014 			}
3015 		} else {
3016 			if (vpm_enable) {
3017 				(void) vpm_sync_pages(vp, off, n, 0);
3018 			} else {
3019 				(void) segmap_release(segkmap, base, 0);
3020 			}
3021 			/*
3022 			 * In the event that we got an access error while
3023 			 * faulting in a page for a write-only file just
3024 			 * force a write.
3025 			 */
3026 			if (error == EACCES)
3027 				goto nfs4_fwrite;
3028 		}
3029 	} while (!error && uiop->uio_resid > 0);
3030 
3031 bottom:
3032 	if (error) {
3033 		uiop->uio_resid = resid + remainder;
3034 		uiop->uio_loffset = offset;
3035 	} else {
3036 		uiop->uio_resid += remainder;
3037 
3038 		mutex_enter(&rp->r_statev4_lock);
3039 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
3040 			gethrestime(&rp->r_attr.va_mtime);
3041 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3042 		}
3043 		mutex_exit(&rp->r_statev4_lock);
3044 	}
3045 
3046 	nfs_rw_exit(&rp->r_lkserlock);
3047 
3048 	return (error);
3049 }
3050 
3051 /*
3052  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
3053  */
3054 static int
3055 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
3056     int flags, cred_t *cr)
3057 {
3058 	struct buf *bp;
3059 	int error;
3060 	page_t *savepp;
3061 	uchar_t fsdata;
3062 	stable_how4 stab_comm;
3063 
3064 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3065 	bp = pageio_setup(pp, len, vp, flags);
3066 	ASSERT(bp != NULL);
3067 
3068 	/*
3069 	 * pageio_setup should have set b_addr to 0.  This
3070 	 * is correct since we want to do I/O on a page
3071 	 * boundary.  bp_mapin will use this addr to calculate
3072 	 * an offset, and then set b_addr to the kernel virtual
3073 	 * address it allocated for us.
3074 	 */
3075 	ASSERT(bp->b_un.b_addr == 0);
3076 
3077 	bp->b_edev = 0;
3078 	bp->b_dev = 0;
3079 	bp->b_lblkno = lbtodb(off);
3080 	bp->b_file = vp;
3081 	bp->b_offset = (offset_t)off;
3082 	bp_mapin(bp);
3083 
3084 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
3085 	    freemem > desfree)
3086 		stab_comm = UNSTABLE4;
3087 	else
3088 		stab_comm = FILE_SYNC4;
3089 
3090 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
3091 
3092 	bp_mapout(bp);
3093 	pageio_done(bp);
3094 
3095 	if (stab_comm == UNSTABLE4)
3096 		fsdata = C_DELAYCOMMIT;
3097 	else
3098 		fsdata = C_NOCOMMIT;
3099 
3100 	savepp = pp;
3101 	do {
3102 		pp->p_fsdata = fsdata;
3103 	} while ((pp = pp->p_next) != savepp);
3104 
3105 	return (error);
3106 }
3107 
3108 /*
3109  */
3110 static int
3111 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
3112 {
3113 	nfs4_open_owner_t	*oop;
3114 	nfs4_open_stream_t	*osp;
3115 	rnode4_t		*rp = VTOR4(vp);
3116 	mntinfo4_t		*mi = VTOMI4(vp);
3117 	int			reopen_needed;
3118 
3119 	ASSERT(nfs_zone() == mi->mi_zone);
3120 
3121 
3122 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
3123 	if (!oop)
3124 		return (EIO);
3125 
3126 	/* returns with 'os_sync_lock' held */
3127 	osp = find_open_stream(oop, rp);
3128 	if (!osp) {
3129 		open_owner_rele(oop);
3130 		return (EIO);
3131 	}
3132 
3133 	if (osp->os_failed_reopen) {
3134 		mutex_exit(&osp->os_sync_lock);
3135 		open_stream_rele(osp, rp);
3136 		open_owner_rele(oop);
3137 		return (EIO);
3138 	}
3139 
3140 	/*
3141 	 * Determine whether a reopen is needed.  If this
3142 	 * is a delegation open stream, then the os_delegation bit
3143 	 * should be set.
3144 	 */
3145 
3146 	reopen_needed = osp->os_delegation;
3147 
3148 	mutex_exit(&osp->os_sync_lock);
3149 	open_owner_rele(oop);
3150 
3151 	if (reopen_needed) {
3152 		nfs4_error_zinit(ep);
3153 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
3154 		mutex_enter(&osp->os_sync_lock);
3155 		if (ep->error || ep->stat || osp->os_failed_reopen) {
3156 			mutex_exit(&osp->os_sync_lock);
3157 			open_stream_rele(osp, rp);
3158 			return (EIO);
3159 		}
3160 		mutex_exit(&osp->os_sync_lock);
3161 	}
3162 	open_stream_rele(osp, rp);
3163 
3164 	return (0);
3165 }
3166 
3167 /*
3168  * Write to file.  Writes to remote server in largest size
3169  * chunks that the server can handle.  Write is synchronous.
3170  */
3171 static int
3172 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3173     stable_how4 *stab_comm)
3174 {
3175 	mntinfo4_t *mi;
3176 	COMPOUND4args_clnt args;
3177 	COMPOUND4res_clnt res;
3178 	WRITE4args *wargs;
3179 	WRITE4res *wres;
3180 	nfs_argop4 argop[2];
3181 	nfs_resop4 *resop;
3182 	int tsize;
3183 	stable_how4 stable;
3184 	rnode4_t *rp;
3185 	int doqueue = 1;
3186 	bool_t needrecov;
3187 	nfs4_recov_state_t recov_state;
3188 	nfs4_stateid_types_t sid_types;
3189 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3190 	int recov;
3191 
3192 	rp = VTOR4(vp);
3193 	mi = VTOMI4(vp);
3194 
3195 	ASSERT(nfs_zone() == mi->mi_zone);
3196 
3197 	stable = *stab_comm;
3198 	*stab_comm = FILE_SYNC4;
3199 
3200 	needrecov = FALSE;
3201 	recov_state.rs_flags = 0;
3202 	recov_state.rs_num_retry_despite_err = 0;
3203 	nfs4_init_stateid_types(&sid_types);
3204 
3205 	/* Is curthread the recovery thread? */
3206 	mutex_enter(&mi->mi_lock);
3207 	recov = (mi->mi_recovthread == curthread);
3208 	mutex_exit(&mi->mi_lock);
3209 
3210 recov_retry:
3211 	args.ctag = TAG_WRITE;
3212 	args.array_len = 2;
3213 	args.array = argop;
3214 
3215 	if (!recov) {
3216 		e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3217 		    &recov_state, NULL);
3218 		if (e.error)
3219 			return (e.error);
3220 	}
3221 
3222 	/* 0. putfh target fh */
3223 	argop[0].argop = OP_CPUTFH;
3224 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3225 
3226 	/* 1. write */
3227 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3228 
3229 	do {
3230 
3231 		wargs->offset = (offset4)offset;
3232 		wargs->data_val = base;
3233 
3234 		if (mi->mi_io_kstats) {
3235 			mutex_enter(&mi->mi_lock);
3236 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3237 			mutex_exit(&mi->mi_lock);
3238 		}
3239 
3240 		if ((vp->v_flag & VNOCACHE) ||
3241 		    (rp->r_flags & R4DIRECTIO) ||
3242 		    (mi->mi_flags & MI4_DIRECTIO))
3243 			tsize = MIN(mi->mi_stsize, count);
3244 		else
3245 			tsize = MIN(mi->mi_curwrite, count);
3246 		wargs->data_len = (uint_t)tsize;
3247 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3248 
3249 		if (mi->mi_io_kstats) {
3250 			mutex_enter(&mi->mi_lock);
3251 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3252 			mutex_exit(&mi->mi_lock);
3253 		}
3254 
3255 		if (!recov) {
3256 			needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3257 			if (e.error && !needrecov) {
3258 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3259 				    &recov_state, needrecov);
3260 				return (e.error);
3261 			}
3262 		} else {
3263 			if (e.error)
3264 				return (e.error);
3265 		}
3266 
3267 		/*
3268 		 * Do handling of OLD_STATEID outside
3269 		 * of the normal recovery framework.
3270 		 *
3271 		 * If write receives a BAD stateid error while using a
3272 		 * delegation stateid, retry using the open stateid (if it
3273 		 * exists).  If it doesn't have an open stateid, reopen the
3274 		 * file first, then retry.
3275 		 */
3276 		if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3277 		    sid_types.cur_sid_type != SPEC_SID) {
3278 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3279 			if (!recov)
3280 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3281 				    &recov_state, needrecov);
3282 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3283 			goto recov_retry;
3284 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3285 		    sid_types.cur_sid_type == DEL_SID) {
3286 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3287 			mutex_enter(&rp->r_statev4_lock);
3288 			rp->r_deleg_return_pending = TRUE;
3289 			mutex_exit(&rp->r_statev4_lock);
3290 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3291 				if (!recov)
3292 					nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3293 					    &recov_state, needrecov);
3294 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3295 				return (EIO);
3296 			}
3297 			if (!recov)
3298 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3299 				    &recov_state, needrecov);
3300 			/* hold needed for nfs4delegreturn_thread */
3301 			VN_HOLD(vp);
3302 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3303 			    NFS4_DR_DISCARD), FALSE);
3304 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3305 			goto recov_retry;
3306 		}
3307 
3308 		if (needrecov) {
3309 			bool_t abort;
3310 
3311 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3312 			    "nfs4write: client got error %d, res.status %d"
3313 			    ", so start recovery", e.error, res.status));
3314 
3315 			abort = nfs4_start_recovery(&e,
3316 			    VTOMI4(vp), vp, NULL, &wargs->stateid,
3317 			    NULL, OP_WRITE, NULL, NULL, NULL);
3318 			if (!e.error) {
3319 				e.error = geterrno4(res.status);
3320 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3321 			}
3322 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3323 			    &recov_state, needrecov);
3324 			if (abort == FALSE)
3325 				goto recov_retry;
3326 			return (e.error);
3327 		}
3328 
3329 		if (res.status) {
3330 			e.error = geterrno4(res.status);
3331 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3332 			if (!recov)
3333 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3334 				    &recov_state, needrecov);
3335 			return (e.error);
3336 		}
3337 
3338 		resop = &res.array[1];	/* write res */
3339 		wres = &resop->nfs_resop4_u.opwrite;
3340 
3341 		if ((int)wres->count > tsize) {
3342 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3343 
3344 			zcmn_err(getzoneid(), CE_WARN,
3345 			    "nfs4write: server wrote %u, requested was %u",
3346 			    (int)wres->count, tsize);
3347 			if (!recov)
3348 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3349 				    &recov_state, needrecov);
3350 			return (EIO);
3351 		}
3352 		if (wres->committed == UNSTABLE4) {
3353 			*stab_comm = UNSTABLE4;
3354 			if (wargs->stable == DATA_SYNC4 ||
3355 			    wargs->stable == FILE_SYNC4) {
3356 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3357 				zcmn_err(getzoneid(), CE_WARN,
3358 				    "nfs4write: server %s did not commit "
3359 				    "to stable storage",
3360 				    rp->r_server->sv_hostname);
3361 				if (!recov)
3362 					nfs4_end_fop(VTOMI4(vp), vp, NULL,
3363 					    OH_WRITE, &recov_state, needrecov);
3364 				return (EIO);
3365 			}
3366 		}
3367 
3368 		tsize = (int)wres->count;
3369 		count -= tsize;
3370 		base += tsize;
3371 		offset += tsize;
3372 		if (mi->mi_io_kstats) {
3373 			mutex_enter(&mi->mi_lock);
3374 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3375 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3376 			    tsize;
3377 			mutex_exit(&mi->mi_lock);
3378 		}
3379 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3380 		mutex_enter(&rp->r_statelock);
3381 		if (rp->r_flags & R4HAVEVERF) {
3382 			if (rp->r_writeverf != wres->writeverf) {
3383 				nfs4_set_mod(vp);
3384 				rp->r_writeverf = wres->writeverf;
3385 			}
3386 		} else {
3387 			rp->r_writeverf = wres->writeverf;
3388 			rp->r_flags |= R4HAVEVERF;
3389 		}
3390 		PURGE_ATTRCACHE4_LOCKED(rp);
3391 		rp->r_flags |= R4WRITEMODIFIED;
3392 		gethrestime(&rp->r_attr.va_mtime);
3393 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3394 		mutex_exit(&rp->r_statelock);
3395 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3396 	} while (count);
3397 
3398 	if (!recov)
3399 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state,
3400 		    needrecov);
3401 
3402 	return (e.error);
3403 }
3404 
3405 /*
3406  * Read from a file.  Reads data in largest chunks our interface can handle.
3407  */
3408 static int
3409 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3410     size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3411 {
3412 	mntinfo4_t *mi;
3413 	COMPOUND4args_clnt args;
3414 	COMPOUND4res_clnt res;
3415 	READ4args *rargs;
3416 	nfs_argop4 argop[2];
3417 	int tsize;
3418 	int doqueue;
3419 	rnode4_t *rp;
3420 	int data_len;
3421 	bool_t is_eof;
3422 	bool_t needrecov = FALSE;
3423 	nfs4_recov_state_t recov_state;
3424 	nfs4_stateid_types_t sid_types;
3425 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3426 
3427 	rp = VTOR4(vp);
3428 	mi = VTOMI4(vp);
3429 	doqueue = 1;
3430 
3431 	ASSERT(nfs_zone() == mi->mi_zone);
3432 
3433 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3434 
3435 	args.array_len = 2;
3436 	args.array = argop;
3437 
3438 	nfs4_init_stateid_types(&sid_types);
3439 
3440 	recov_state.rs_flags = 0;
3441 	recov_state.rs_num_retry_despite_err = 0;
3442 
3443 recov_retry:
3444 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3445 	    &recov_state, NULL);
3446 	if (e.error)
3447 		return (e.error);
3448 
3449 	/* putfh target fh */
3450 	argop[0].argop = OP_CPUTFH;
3451 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3452 
3453 	/* read */
3454 	argop[1].argop = OP_READ;
3455 	rargs = &argop[1].nfs_argop4_u.opread;
3456 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3457 	    OP_READ, &sid_types, async);
3458 
3459 	do {
3460 		if (mi->mi_io_kstats) {
3461 			mutex_enter(&mi->mi_lock);
3462 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3463 			mutex_exit(&mi->mi_lock);
3464 		}
3465 
3466 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3467 		    "nfs4read: %s call, rp %s",
3468 		    needrecov ? "recov" : "first",
3469 		    rnode4info(rp)));
3470 
3471 		if ((vp->v_flag & VNOCACHE) ||
3472 		    (rp->r_flags & R4DIRECTIO) ||
3473 		    (mi->mi_flags & MI4_DIRECTIO))
3474 			tsize = MIN(mi->mi_tsize, count);
3475 		else
3476 			tsize = MIN(mi->mi_curread, count);
3477 
3478 		rargs->offset = (offset4)offset;
3479 		rargs->count = (count4)tsize;
3480 		rargs->res_data_val_alt = NULL;
3481 		rargs->res_mblk = NULL;
3482 		rargs->res_uiop = NULL;
3483 		rargs->res_maxsize = 0;
3484 		rargs->wlist = NULL;
3485 
3486 		if (uiop)
3487 			rargs->res_uiop = uiop;
3488 		else
3489 			rargs->res_data_val_alt = base;
3490 		rargs->res_maxsize = tsize;
3491 
3492 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3493 #ifdef	DEBUG
3494 		if (nfs4read_error_inject) {
3495 			res.status = nfs4read_error_inject;
3496 			nfs4read_error_inject = 0;
3497 		}
3498 #endif
3499 
3500 		if (mi->mi_io_kstats) {
3501 			mutex_enter(&mi->mi_lock);
3502 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3503 			mutex_exit(&mi->mi_lock);
3504 		}
3505 
3506 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3507 		if (e.error != 0 && !needrecov) {
3508 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3509 			    &recov_state, needrecov);
3510 			return (e.error);
3511 		}
3512 
3513 		/*
3514 		 * Do proper retry for OLD and BAD stateid errors outside
3515 		 * of the normal recovery framework.  There are two differences
3516 		 * between async and sync reads.  The first is that we allow
3517 		 * retry on BAD_STATEID for async reads, but not sync reads.
3518 		 * The second is that we mark the file dead for a failed
3519 		 * attempt with a special stateid for sync reads, but just
3520 		 * return EIO for async reads.
3521 		 *
3522 		 * If a sync read receives a BAD stateid error while using a
3523 		 * delegation stateid, retry using the open stateid (if it
3524 		 * exists).  If it doesn't have an open stateid, reopen the
3525 		 * file first, then retry.
3526 		 */
3527 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3528 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3529 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3530 			    &recov_state, needrecov);
3531 			if (sid_types.cur_sid_type == SPEC_SID) {
3532 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3533 				return (EIO);
3534 			}
3535 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3536 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3537 			goto recov_retry;
3538 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3539 		    !async && sid_types.cur_sid_type != SPEC_SID) {
3540 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3541 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3542 			    &recov_state, needrecov);
3543 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3544 			goto recov_retry;
3545 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3546 		    sid_types.cur_sid_type == DEL_SID) {
3547 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3548 			mutex_enter(&rp->r_statev4_lock);
3549 			rp->r_deleg_return_pending = TRUE;
3550 			mutex_exit(&rp->r_statev4_lock);
3551 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3552 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3553 				    &recov_state, needrecov);
3554 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3555 				return (EIO);
3556 			}
3557 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3558 			    &recov_state, needrecov);
3559 			/* hold needed for nfs4delegreturn_thread */
3560 			VN_HOLD(vp);
3561 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3562 			    NFS4_DR_DISCARD), FALSE);
3563 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3564 			goto recov_retry;
3565 		}
3566 		if (needrecov) {
3567 			bool_t abort;
3568 
3569 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3570 			    "nfs4read: initiating recovery\n"));
3571 			abort = nfs4_start_recovery(&e,
3572 			    mi, vp, NULL, &rargs->stateid,
3573 			    NULL, OP_READ, NULL, NULL, NULL);
3574 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3575 			    &recov_state, needrecov);
3576 			/*
3577 			 * Do not retry if we got OLD_STATEID using a special
3578 			 * stateid.  This avoids looping with a broken server.
3579 			 */
3580 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3581 			    sid_types.cur_sid_type == SPEC_SID)
3582 				abort = TRUE;
3583 
3584 			if (abort == FALSE) {
3585 				/*
3586 				 * Need to retry all possible stateids in
3587 				 * case the recovery error wasn't stateid
3588 				 * related or the stateids have become
3589 				 * stale (server reboot).
3590 				 */
3591 				nfs4_init_stateid_types(&sid_types);
3592 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3593 				goto recov_retry;
3594 			}
3595 
3596 			if (!e.error) {
3597 				e.error = geterrno4(res.status);
3598 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3599 			}
3600 			return (e.error);
3601 		}
3602 
3603 		if (res.status) {
3604 			e.error = geterrno4(res.status);
3605 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3606 			    &recov_state, needrecov);
3607 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3608 			return (e.error);
3609 		}
3610 
3611 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3612 		count -= data_len;
3613 		if (base)
3614 			base += data_len;
3615 		offset += data_len;
3616 		if (mi->mi_io_kstats) {
3617 			mutex_enter(&mi->mi_lock);
3618 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3619 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3620 			mutex_exit(&mi->mi_lock);
3621 		}
3622 		lwp_stat_update(LWP_STAT_INBLK, 1);
3623 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3624 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3625 
3626 	} while (count && !is_eof);
3627 
3628 	*residp = count;
3629 
3630 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3631 
3632 	return (e.error);
3633 }
3634 
3635 /* ARGSUSED */
3636 static int
3637 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp,
3638     caller_context_t *ct)
3639 {
3640 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3641 		return (EIO);
3642 	switch (cmd) {
3643 		case _FIODIRECTIO:
3644 			return (nfs4_directio(vp, (int)arg, cr));
3645 		default:
3646 			return (ENOTTY);
3647 	}
3648 }
3649 
3650 /* ARGSUSED */
3651 int
3652 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3653     caller_context_t *ct)
3654 {
3655 	int error;
3656 	rnode4_t *rp = VTOR4(vp);
3657 
3658 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3659 		return (EIO);
3660 	/*
3661 	 * If it has been specified that the return value will
3662 	 * just be used as a hint, and we are only being asked
3663 	 * for size, fsid or rdevid, then return the client's
3664 	 * notion of these values without checking to make sure
3665 	 * that the attribute cache is up to date.
3666 	 * The whole point is to avoid an over the wire GETATTR
3667 	 * call.
3668 	 */
3669 	if (flags & ATTR_HINT) {
3670 		if (!(vap->va_mask & ~(AT_SIZE | AT_FSID | AT_RDEV))) {
3671 			mutex_enter(&rp->r_statelock);
3672 			if (vap->va_mask & AT_SIZE)
3673 				vap->va_size = rp->r_size;
3674 			if (vap->va_mask & AT_FSID)
3675 				vap->va_fsid = rp->r_attr.va_fsid;
3676 			if (vap->va_mask & AT_RDEV)
3677 				vap->va_rdev = rp->r_attr.va_rdev;
3678 			mutex_exit(&rp->r_statelock);
3679 			return (0);
3680 		}
3681 	}
3682 
3683 	/*
3684 	 * Only need to flush pages if asking for the mtime
3685 	 * and if there any dirty pages or any outstanding
3686 	 * asynchronous (write) requests for this file.
3687 	 */
3688 	if (vap->va_mask & AT_MTIME) {
3689 		rp = VTOR4(vp);
3690 		if (nfs4_has_pages(vp)) {
3691 			mutex_enter(&rp->r_statev4_lock);
3692 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3693 				mutex_exit(&rp->r_statev4_lock);
3694 				if (rp->r_flags & R4DIRTY ||
3695 				    rp->r_awcount > 0) {
3696 					mutex_enter(&rp->r_statelock);
3697 					rp->r_gcount++;
3698 					mutex_exit(&rp->r_statelock);
3699 					error =
3700 					    nfs4_putpage(vp, (u_offset_t)0,
3701 					    0, 0, cr, NULL);
3702 					mutex_enter(&rp->r_statelock);
3703 					if (error && (error == ENOSPC ||
3704 					    error == EDQUOT)) {
3705 						if (!rp->r_error)
3706 							rp->r_error = error;
3707 					}
3708 					if (--rp->r_gcount == 0)
3709 						cv_broadcast(&rp->r_cv);
3710 					mutex_exit(&rp->r_statelock);
3711 				}
3712 			} else {
3713 				mutex_exit(&rp->r_statev4_lock);
3714 			}
3715 		}
3716 	}
3717 	return (nfs4getattr(vp, vap, cr));
3718 }
3719 
3720 int
3721 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3722 {
3723 	/*
3724 	 * If these are the only two bits cleared
3725 	 * on the server then return 0 (OK) else
3726 	 * return 1 (BAD).
3727 	 */
3728 	on_client &= ~(S_ISUID|S_ISGID);
3729 	if (on_client == from_server)
3730 		return (0);
3731 	else
3732 		return (1);
3733 }
3734 
3735 /*ARGSUSED4*/
3736 static int
3737 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3738     caller_context_t *ct)
3739 {
3740 	int error;
3741 
3742 	if (vap->va_mask & AT_NOSET)
3743 		return (EINVAL);
3744 
3745 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3746 		return (EIO);
3747 
3748 	/*
3749 	 * Don't call secpolicy_vnode_setattr, the client cannot
3750 	 * use its cached attributes to make security decisions
3751 	 * as the server may be faking mode bits or mapping uid/gid.
3752 	 * Always just let the server to the checking.
3753 	 * If we provide the ability to remove basic priviledges
3754 	 * to setattr (e.g. basic without chmod) then we will
3755 	 * need to add a check here before calling the server.
3756 	 */
3757 	error = nfs4setattr(vp, vap, flags, cr, NULL);
3758 
3759 	if (error == 0 && (vap->va_mask & AT_SIZE) && vap->va_size == 0)
3760 		vnevent_truncate(vp, ct);
3761 
3762 	return (error);
3763 }
3764 
3765 /*
3766  * To replace the "guarded" version 3 setattr, we use two types of compound
3767  * setattr requests:
3768  * 1. The "normal" setattr, used when the size of the file isn't being
3769  *    changed - { Putfh <fh>; Setattr; Getattr }/
3770  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3771  *    with only ctime as the argument. If the server ctime differs from
3772  *    what is cached on the client, the verify will fail, but we would
3773  *    already have the ctime from the preceding getattr, so just set it
3774  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3775  *	Setattr; Getattr }.
3776  *
3777  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3778  * this setattr and NULL if they are not.
3779  */
3780 static int
3781 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3782     vsecattr_t *vsap)
3783 {
3784 	COMPOUND4args_clnt args;
3785 	COMPOUND4res_clnt res, *resp = NULL;
3786 	nfs4_ga_res_t *garp = NULL;
3787 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3788 	nfs_argop4 argop[5];
3789 	int verify_argop = -1;
3790 	int setattr_argop = 1;
3791 	nfs_resop4 *resop;
3792 	vattr_t va;
3793 	rnode4_t *rp;
3794 	int doqueue = 1;
3795 	uint_t mask = vap->va_mask;
3796 	mode_t omode;
3797 	vsecattr_t *vsp;
3798 	timestruc_t ctime;
3799 	bool_t needrecov = FALSE;
3800 	nfs4_recov_state_t recov_state;
3801 	nfs4_stateid_types_t sid_types;
3802 	stateid4 stateid;
3803 	hrtime_t t;
3804 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3805 	servinfo4_t *svp;
3806 	bitmap4 supp_attrs;
3807 
3808 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3809 	rp = VTOR4(vp);
3810 	nfs4_init_stateid_types(&sid_types);
3811 
3812 	/*
3813 	 * Only need to flush pages if there are any pages and
3814 	 * if the file is marked as dirty in some fashion.  The
3815 	 * file must be flushed so that we can accurately
3816 	 * determine the size of the file and the cached data
3817 	 * after the SETATTR returns.  A file is considered to
3818 	 * be dirty if it is either marked with R4DIRTY, has
3819 	 * outstanding i/o's active, or is mmap'd.  In this
3820 	 * last case, we can't tell whether there are dirty
3821 	 * pages, so we flush just to be sure.
3822 	 */
3823 	if (nfs4_has_pages(vp) &&
3824 	    ((rp->r_flags & R4DIRTY) ||
3825 	    rp->r_count > 0 ||
3826 	    rp->r_mapcnt > 0)) {
3827 		ASSERT(vp->v_type != VCHR);
3828 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr, NULL);
3829 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3830 			mutex_enter(&rp->r_statelock);
3831 			if (!rp->r_error)
3832 				rp->r_error = e.error;
3833 			mutex_exit(&rp->r_statelock);
3834 		}
3835 	}
3836 
3837 	if (mask & AT_SIZE) {
3838 		/*
3839 		 * Verification setattr compound for non-deleg AT_SIZE:
3840 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3841 		 * Set ctime local here (outside the do_again label)
3842 		 * so that subsequent retries (after failed VERIFY)
3843 		 * will use ctime from GETATTR results (from failed
3844 		 * verify compound) as VERIFY arg.
3845 		 * If file has delegation, then VERIFY(time_metadata)
3846 		 * is of little added value, so don't bother.
3847 		 */
3848 		mutex_enter(&rp->r_statev4_lock);
3849 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3850 		    rp->r_deleg_return_pending) {
3851 			numops = 5;
3852 			ctime = rp->r_attr.va_ctime;
3853 		}
3854 		mutex_exit(&rp->r_statev4_lock);
3855 	}
3856 
3857 	recov_state.rs_flags = 0;
3858 	recov_state.rs_num_retry_despite_err = 0;
3859 
3860 	args.ctag = TAG_SETATTR;
3861 do_again:
3862 recov_retry:
3863 	setattr_argop = numops - 2;
3864 
3865 	args.array = argop;
3866 	args.array_len = numops;
3867 
3868 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3869 	if (e.error)
3870 		return (e.error);
3871 
3872 
3873 	/* putfh target fh */
3874 	argop[0].argop = OP_CPUTFH;
3875 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3876 
3877 	if (numops == 5) {
3878 		/*
3879 		 * We only care about the ctime, but need to get mtime
3880 		 * and size for proper cache update.
3881 		 */
3882 		/* getattr */
3883 		argop[1].argop = OP_GETATTR;
3884 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3885 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3886 
3887 		/* verify - set later in loop */
3888 		verify_argop = 2;
3889 	}
3890 
3891 	/* setattr */
3892 	svp = rp->r_server;
3893 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3894 	supp_attrs = svp->sv_supp_attrs;
3895 	nfs_rw_exit(&svp->sv_lock);
3896 
3897 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3898 	    supp_attrs, &e.error, &sid_types);
3899 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3900 	if (e.error) {
3901 		/* req time field(s) overflow - return immediately */
3902 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3903 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3904 		    opsetattr.obj_attributes);
3905 		return (e.error);
3906 	}
3907 	omode = rp->r_attr.va_mode;
3908 
3909 	/* getattr */
3910 	argop[numops-1].argop = OP_GETATTR;
3911 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3912 	/*
3913 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3914 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3915 	 * used in updating the ACL cache.
3916 	 */
3917 	if (vsap != NULL)
3918 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3919 		    FATTR4_ACL_MASK;
3920 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3921 
3922 	/*
3923 	 * setattr iterates if the object size is set and the cached ctime
3924 	 * does not match the file ctime. In that case, verify the ctime first.
3925 	 */
3926 
3927 	do {
3928 		if (verify_argop != -1) {
3929 			/*
3930 			 * Verify that the ctime match before doing setattr.
3931 			 */
3932 			va.va_mask = AT_CTIME;
3933 			va.va_ctime = ctime;
3934 			svp = rp->r_server;
3935 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3936 			supp_attrs = svp->sv_supp_attrs;
3937 			nfs_rw_exit(&svp->sv_lock);
3938 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3939 			    OP_VERIFY, supp_attrs);
3940 			if (e.error) {
3941 				/* req time field(s) overflow - return */
3942 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3943 				    needrecov);
3944 				break;
3945 			}
3946 		}
3947 
3948 		doqueue = 1;
3949 
3950 		t = gethrtime();
3951 
3952 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3953 
3954 		/*
3955 		 * Purge the access cache and ACL cache if changing either the
3956 		 * owner of the file, the group owner, or the mode.  These may
3957 		 * change the access permissions of the file, so purge old
3958 		 * information and start over again.
3959 		 */
3960 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3961 			(void) nfs4_access_purge_rp(rp);
3962 			if (rp->r_secattr != NULL) {
3963 				mutex_enter(&rp->r_statelock);
3964 				vsp = rp->r_secattr;
3965 				rp->r_secattr = NULL;
3966 				mutex_exit(&rp->r_statelock);
3967 				if (vsp != NULL)
3968 					nfs4_acl_free_cache(vsp);
3969 			}
3970 		}
3971 
3972 		/*
3973 		 * If res.array_len == numops, then everything succeeded,
3974 		 * except for possibly the final getattr.  If only the
3975 		 * last getattr failed, give up, and don't try recovery.
3976 		 */
3977 		if (res.array_len == numops) {
3978 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3979 			    needrecov);
3980 			if (! e.error)
3981 				resp = &res;
3982 			break;
3983 		}
3984 
3985 		/*
3986 		 * if either rpc call failed or completely succeeded - done
3987 		 */
3988 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
3989 		if (e.error) {
3990 			PURGE_ATTRCACHE4(vp);
3991 			if (!needrecov) {
3992 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3993 				    needrecov);
3994 				break;
3995 			}
3996 		}
3997 
3998 		/*
3999 		 * Do proper retry for OLD_STATEID outside of the normal
4000 		 * recovery framework.
4001 		 */
4002 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
4003 		    sid_types.cur_sid_type != SPEC_SID &&
4004 		    sid_types.cur_sid_type != NO_SID) {
4005 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4006 			    needrecov);
4007 			nfs4_save_stateid(&stateid, &sid_types);
4008 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4009 			    opsetattr.obj_attributes);
4010 			if (verify_argop != -1) {
4011 				nfs4args_verify_free(&argop[verify_argop]);
4012 				verify_argop = -1;
4013 			}
4014 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4015 			goto recov_retry;
4016 		}
4017 
4018 		if (needrecov) {
4019 			bool_t abort;
4020 
4021 			abort = nfs4_start_recovery(&e,
4022 			    VTOMI4(vp), vp, NULL, NULL, NULL,
4023 			    OP_SETATTR, NULL, NULL, NULL);
4024 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4025 			    needrecov);
4026 			/*
4027 			 * Do not retry if we failed with OLD_STATEID using
4028 			 * a special stateid.  This is done to avoid looping
4029 			 * with a broken server.
4030 			 */
4031 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
4032 			    (sid_types.cur_sid_type == SPEC_SID ||
4033 			    sid_types.cur_sid_type == NO_SID))
4034 				abort = TRUE;
4035 			if (!e.error) {
4036 				if (res.status == NFS4ERR_BADOWNER)
4037 					nfs4_log_badowner(VTOMI4(vp),
4038 					    OP_SETATTR);
4039 
4040 				e.error = geterrno4(res.status);
4041 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4042 			}
4043 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4044 			    opsetattr.obj_attributes);
4045 			if (verify_argop != -1) {
4046 				nfs4args_verify_free(&argop[verify_argop]);
4047 				verify_argop = -1;
4048 			}
4049 			if (abort == FALSE) {
4050 				/*
4051 				 * Need to retry all possible stateids in
4052 				 * case the recovery error wasn't stateid
4053 				 * related or the stateids have become
4054 				 * stale (server reboot).
4055 				 */
4056 				nfs4_init_stateid_types(&sid_types);
4057 				goto recov_retry;
4058 			}
4059 			return (e.error);
4060 		}
4061 
4062 		/*
4063 		 * Need to call nfs4_end_op before nfs4getattr to
4064 		 * avoid potential nfs4_start_op deadlock. See RFE
4065 		 * 4777612.  Calls to nfs4_invalidate_pages() and
4066 		 * nfs4_purge_stale_fh() might also generate over the
4067 		 * wire calls which my cause nfs4_start_op() deadlock.
4068 		 */
4069 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4070 
4071 		/*
4072 		 * Check to update lease.
4073 		 */
4074 		resp = &res;
4075 		if (res.status == NFS4_OK) {
4076 			break;
4077 		}
4078 
4079 		/*
4080 		 * Check if verify failed to see if try again
4081 		 */
4082 		if ((verify_argop == -1) || (res.array_len != 3)) {
4083 			/*
4084 			 * can't continue...
4085 			 */
4086 			if (res.status == NFS4ERR_BADOWNER)
4087 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
4088 
4089 			e.error = geterrno4(res.status);
4090 		} else {
4091 			/*
4092 			 * When the verify request fails, the client ctime is
4093 			 * not in sync with the server. This is the same as
4094 			 * the version 3 "not synchronized" error, and we
4095 			 * handle it in a similar manner (XXX do we need to???).
4096 			 * Use the ctime returned in the first getattr for
4097 			 * the input to the next verify.
4098 			 * If we couldn't get the attributes, then we give up
4099 			 * because we can't complete the operation as required.
4100 			 */
4101 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
4102 		}
4103 		if (e.error) {
4104 			PURGE_ATTRCACHE4(vp);
4105 			nfs4_purge_stale_fh(e.error, vp, cr);
4106 		} else {
4107 			/*
4108 			 * retry with a new verify value
4109 			 */
4110 			ctime = garp->n4g_va.va_ctime;
4111 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4112 			resp = NULL;
4113 		}
4114 		if (!e.error) {
4115 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4116 			    opsetattr.obj_attributes);
4117 			if (verify_argop != -1) {
4118 				nfs4args_verify_free(&argop[verify_argop]);
4119 				verify_argop = -1;
4120 			}
4121 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4122 			goto do_again;
4123 		}
4124 	} while (!e.error);
4125 
4126 	if (e.error) {
4127 		/*
4128 		 * If we are here, rfs4call has an irrecoverable error - return
4129 		 */
4130 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4131 		    opsetattr.obj_attributes);
4132 		if (verify_argop != -1) {
4133 			nfs4args_verify_free(&argop[verify_argop]);
4134 			verify_argop = -1;
4135 		}
4136 		if (resp)
4137 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4138 		return (e.error);
4139 	}
4140 
4141 
4142 
4143 	/*
4144 	 * If changing the size of the file, invalidate
4145 	 * any local cached data which is no longer part
4146 	 * of the file.  We also possibly invalidate the
4147 	 * last page in the file.  We could use
4148 	 * pvn_vpzero(), but this would mark the page as
4149 	 * modified and require it to be written back to
4150 	 * the server for no particularly good reason.
4151 	 * This way, if we access it, then we bring it
4152 	 * back in.  A read should be cheaper than a
4153 	 * write.
4154 	 */
4155 	if (mask & AT_SIZE) {
4156 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
4157 	}
4158 
4159 	/* either no error or one of the postop getattr failed */
4160 
4161 	/*
4162 	 * XXX Perform a simplified version of wcc checking. Instead of
4163 	 * have another getattr to get pre-op, just purge cache if
4164 	 * any of the ops prior to and including the getattr failed.
4165 	 * If the getattr succeeded then update the attrcache accordingly.
4166 	 */
4167 
4168 	garp = NULL;
4169 	if (res.status == NFS4_OK) {
4170 		/*
4171 		 * Last getattr
4172 		 */
4173 		resop = &res.array[numops - 1];
4174 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4175 	}
4176 	/*
4177 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
4178 	 * rather than filling it.  See the function itself for details.
4179 	 */
4180 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4181 	if (garp != NULL) {
4182 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
4183 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
4184 			vs_ace4_destroy(&garp->n4g_vsa);
4185 		} else {
4186 			if (vsap != NULL) {
4187 				/*
4188 				 * The ACL was supposed to be set and to be
4189 				 * returned in the last getattr of this
4190 				 * compound, but for some reason the getattr
4191 				 * result doesn't contain the ACL.  In this
4192 				 * case, purge the ACL cache.
4193 				 */
4194 				if (rp->r_secattr != NULL) {
4195 					mutex_enter(&rp->r_statelock);
4196 					vsp = rp->r_secattr;
4197 					rp->r_secattr = NULL;
4198 					mutex_exit(&rp->r_statelock);
4199 					if (vsp != NULL)
4200 						nfs4_acl_free_cache(vsp);
4201 				}
4202 			}
4203 		}
4204 	}
4205 
4206 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4207 		/*
4208 		 * Set the size, rather than relying on getting it updated
4209 		 * via a GETATTR.  With delegations the client tries to
4210 		 * suppress GETATTR calls.
4211 		 */
4212 		mutex_enter(&rp->r_statelock);
4213 		rp->r_size = vap->va_size;
4214 		mutex_exit(&rp->r_statelock);
4215 	}
4216 
4217 	/*
4218 	 * Can free up request args and res
4219 	 */
4220 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4221 	    opsetattr.obj_attributes);
4222 	if (verify_argop != -1) {
4223 		nfs4args_verify_free(&argop[verify_argop]);
4224 		verify_argop = -1;
4225 	}
4226 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4227 
4228 	/*
4229 	 * Some servers will change the mode to clear the setuid
4230 	 * and setgid bits when changing the uid or gid.  The
4231 	 * client needs to compensate appropriately.
4232 	 */
4233 	if (mask & (AT_UID | AT_GID)) {
4234 		int terror, do_setattr;
4235 
4236 		do_setattr = 0;
4237 		va.va_mask = AT_MODE;
4238 		terror = nfs4getattr(vp, &va, cr);
4239 		if (!terror &&
4240 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4241 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4242 			va.va_mask = AT_MODE;
4243 			if (mask & AT_MODE) {
4244 				/*
4245 				 * We asked the mode to be changed and what
4246 				 * we just got from the server in getattr is
4247 				 * not what we wanted it to be, so set it now.
4248 				 */
4249 				va.va_mode = vap->va_mode;
4250 				do_setattr = 1;
4251 			} else {
4252 				/*
4253 				 * We did not ask the mode to be changed,
4254 				 * Check to see that the server just cleared
4255 				 * I_SUID and I_GUID from it. If not then
4256 				 * set mode to omode with UID/GID cleared.
4257 				 */
4258 				if (nfs4_compare_modes(va.va_mode, omode)) {
4259 					omode &= ~(S_ISUID|S_ISGID);
4260 					va.va_mode = omode;
4261 					do_setattr = 1;
4262 				}
4263 			}
4264 
4265 			if (do_setattr)
4266 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4267 		}
4268 	}
4269 
4270 	return (e.error);
4271 }
4272 
4273 /* ARGSUSED */
4274 static int
4275 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr, caller_context_t *ct)
4276 {
4277 	COMPOUND4args_clnt args;
4278 	COMPOUND4res_clnt res;
4279 	int doqueue;
4280 	uint32_t acc, resacc, argacc;
4281 	rnode4_t *rp;
4282 	cred_t *cred, *ncr, *ncrfree = NULL;
4283 	nfs4_access_type_t cacc;
4284 	int num_ops;
4285 	nfs_argop4 argop[3];
4286 	nfs_resop4 *resop;
4287 	bool_t needrecov = FALSE, do_getattr;
4288 	nfs4_recov_state_t recov_state;
4289 	int rpc_error;
4290 	hrtime_t t;
4291 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4292 	mntinfo4_t *mi = VTOMI4(vp);
4293 
4294 	if (nfs_zone() != mi->mi_zone)
4295 		return (EIO);
4296 
4297 	acc = 0;
4298 	if (mode & VREAD)
4299 		acc |= ACCESS4_READ;
4300 	if (mode & VWRITE) {
4301 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4302 			return (EROFS);
4303 		if (vp->v_type == VDIR)
4304 			acc |= ACCESS4_DELETE;
4305 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4306 	}
4307 	if (mode & VEXEC) {
4308 		if (vp->v_type == VDIR)
4309 			acc |= ACCESS4_LOOKUP;
4310 		else
4311 			acc |= ACCESS4_EXECUTE;
4312 	}
4313 
4314 	if (VTOR4(vp)->r_acache != NULL) {
4315 		e.error = nfs4_validate_caches(vp, cr);
4316 		if (e.error)
4317 			return (e.error);
4318 	}
4319 
4320 	rp = VTOR4(vp);
4321 	if (vp->v_type == VDIR)
4322 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4323 		    ACCESS4_EXTEND | ACCESS4_LOOKUP;
4324 	else
4325 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4326 		    ACCESS4_EXECUTE;
4327 	recov_state.rs_flags = 0;
4328 	recov_state.rs_num_retry_despite_err = 0;
4329 
4330 	cred = cr;
4331 	/*
4332 	 * ncr and ncrfree both initially
4333 	 * point to the memory area returned
4334 	 * by crnetadjust();
4335 	 * ncrfree not NULL when exiting means
4336 	 * that we need to release it
4337 	 */
4338 	ncr = crnetadjust(cred);
4339 	ncrfree = ncr;
4340 
4341 tryagain:
4342 	cacc = nfs4_access_check(rp, acc, cred);
4343 	if (cacc == NFS4_ACCESS_ALLOWED) {
4344 		if (ncrfree != NULL)
4345 			crfree(ncrfree);
4346 		return (0);
4347 	}
4348 	if (cacc == NFS4_ACCESS_DENIED) {
4349 		/*
4350 		 * If the cred can be adjusted, try again
4351 		 * with the new cred.
4352 		 */
4353 		if (ncr != NULL) {
4354 			cred = ncr;
4355 			ncr = NULL;
4356 			goto tryagain;
4357 		}
4358 		if (ncrfree != NULL)
4359 			crfree(ncrfree);
4360 		return (EACCES);
4361 	}
4362 
4363 recov_retry:
4364 	/*
4365 	 * Don't take with r_statev4_lock here. r_deleg_type could
4366 	 * change as soon as lock is released.  Since it is an int,
4367 	 * there is no atomicity issue.
4368 	 */
4369 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4370 	num_ops = do_getattr ? 3 : 2;
4371 
4372 	args.ctag = TAG_ACCESS;
4373 
4374 	args.array_len = num_ops;
4375 	args.array = argop;
4376 
4377 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4378 	    &recov_state, NULL)) {
4379 		if (ncrfree != NULL)
4380 			crfree(ncrfree);
4381 		return (e.error);
4382 	}
4383 
4384 	/* putfh target fh */
4385 	argop[0].argop = OP_CPUTFH;
4386 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4387 
4388 	/* access */
4389 	argop[1].argop = OP_ACCESS;
4390 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4391 
4392 	/* getattr */
4393 	if (do_getattr) {
4394 		argop[2].argop = OP_GETATTR;
4395 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4396 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4397 	}
4398 
4399 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4400 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4401 	    rnode4info(VTOR4(vp))));
4402 
4403 	doqueue = 1;
4404 	t = gethrtime();
4405 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4406 	rpc_error = e.error;
4407 
4408 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4409 	if (needrecov) {
4410 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4411 		    "nfs4_access: initiating recovery\n"));
4412 
4413 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4414 		    NULL, OP_ACCESS, NULL, NULL, NULL) == FALSE) {
4415 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4416 			    &recov_state, needrecov);
4417 			if (!e.error)
4418 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4419 			goto recov_retry;
4420 		}
4421 	}
4422 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4423 
4424 	if (e.error)
4425 		goto out;
4426 
4427 	if (res.status) {
4428 		e.error = geterrno4(res.status);
4429 		/*
4430 		 * This might generate over the wire calls throught
4431 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4432 		 * here to avoid a deadlock.
4433 		 */
4434 		nfs4_purge_stale_fh(e.error, vp, cr);
4435 		goto out;
4436 	}
4437 	resop = &res.array[1];	/* access res */
4438 
4439 	resacc = resop->nfs_resop4_u.opaccess.access;
4440 
4441 	if (do_getattr) {
4442 		resop++;	/* getattr res */
4443 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4444 		    t, cr, FALSE, NULL);
4445 	}
4446 
4447 	if (!e.error) {
4448 		nfs4_access_cache(rp, argacc, resacc, cred);
4449 		/*
4450 		 * we just cached results with cred; if cred is the
4451 		 * adjusted credentials from crnetadjust, we do not want
4452 		 * to release them before exiting: hence setting ncrfree
4453 		 * to NULL
4454 		 */
4455 		if (cred != cr)
4456 			ncrfree = NULL;
4457 		/* XXX check the supported bits too? */
4458 		if ((acc & resacc) != acc) {
4459 			/*
4460 			 * The following code implements the semantic
4461 			 * that a setuid root program has *at least* the
4462 			 * permissions of the user that is running the
4463 			 * program.  See rfs3call() for more portions
4464 			 * of the implementation of this functionality.
4465 			 */
4466 			/* XXX-LP */
4467 			if (ncr != NULL) {
4468 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4469 				cred = ncr;
4470 				ncr = NULL;
4471 				goto tryagain;
4472 			}
4473 			e.error = EACCES;
4474 		}
4475 	}
4476 
4477 out:
4478 	if (!rpc_error)
4479 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4480 
4481 	if (ncrfree != NULL)
4482 		crfree(ncrfree);
4483 
4484 	return (e.error);
4485 }
4486 
4487 /* ARGSUSED */
4488 static int
4489 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr, caller_context_t *ct)
4490 {
4491 	COMPOUND4args_clnt args;
4492 	COMPOUND4res_clnt res;
4493 	int doqueue;
4494 	rnode4_t *rp;
4495 	nfs_argop4 argop[3];
4496 	nfs_resop4 *resop;
4497 	READLINK4res *lr_res;
4498 	nfs4_ga_res_t *garp;
4499 	uint_t len;
4500 	char *linkdata;
4501 	bool_t needrecov = FALSE;
4502 	nfs4_recov_state_t recov_state;
4503 	hrtime_t t;
4504 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4505 
4506 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4507 		return (EIO);
4508 	/*
4509 	 * Can't readlink anything other than a symbolic link.
4510 	 */
4511 	if (vp->v_type != VLNK)
4512 		return (EINVAL);
4513 
4514 	rp = VTOR4(vp);
4515 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4516 		e.error = nfs4_validate_caches(vp, cr);
4517 		if (e.error)
4518 			return (e.error);
4519 		mutex_enter(&rp->r_statelock);
4520 		if (rp->r_symlink.contents != NULL) {
4521 			e.error = uiomove(rp->r_symlink.contents,
4522 			    rp->r_symlink.len, UIO_READ, uiop);
4523 			mutex_exit(&rp->r_statelock);
4524 			return (e.error);
4525 		}
4526 		mutex_exit(&rp->r_statelock);
4527 	}
4528 	recov_state.rs_flags = 0;
4529 	recov_state.rs_num_retry_despite_err = 0;
4530 
4531 recov_retry:
4532 	args.array_len = 3;
4533 	args.array = argop;
4534 	args.ctag = TAG_READLINK;
4535 
4536 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4537 	if (e.error) {
4538 		return (e.error);
4539 	}
4540 
4541 	/* 0. putfh symlink fh */
4542 	argop[0].argop = OP_CPUTFH;
4543 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4544 
4545 	/* 1. readlink */
4546 	argop[1].argop = OP_READLINK;
4547 
4548 	/* 2. getattr */
4549 	argop[2].argop = OP_GETATTR;
4550 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4551 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4552 
4553 	doqueue = 1;
4554 
4555 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4556 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4557 	    rnode4info(VTOR4(vp))));
4558 
4559 	t = gethrtime();
4560 
4561 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4562 
4563 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4564 	if (needrecov) {
4565 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4566 		    "nfs4_readlink: initiating recovery\n"));
4567 
4568 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4569 		    NULL, OP_READLINK, NULL, NULL, NULL) == FALSE) {
4570 			if (!e.error)
4571 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4572 
4573 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4574 			    needrecov);
4575 			goto recov_retry;
4576 		}
4577 	}
4578 
4579 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4580 
4581 	if (e.error)
4582 		return (e.error);
4583 
4584 	/*
4585 	 * There is an path in the code below which calls
4586 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4587 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4588 	 * here to avoid nfs4_start_op() deadlock.
4589 	 */
4590 
4591 	if (res.status && (res.array_len < args.array_len)) {
4592 		/*
4593 		 * either Putfh or Link failed
4594 		 */
4595 		e.error = geterrno4(res.status);
4596 		nfs4_purge_stale_fh(e.error, vp, cr);
4597 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4598 		return (e.error);
4599 	}
4600 
4601 	resop = &res.array[1];	/* readlink res */
4602 	lr_res = &resop->nfs_resop4_u.opreadlink;
4603 
4604 	/*
4605 	 * treat symlink names as data
4606 	 */
4607 	linkdata = utf8_to_str((utf8string *)&lr_res->link, &len, NULL);
4608 	if (linkdata != NULL) {
4609 		int uio_len = len - 1;
4610 		/* len includes null byte, which we won't uiomove */
4611 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4612 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4613 			mutex_enter(&rp->r_statelock);
4614 			if (rp->r_symlink.contents == NULL) {
4615 				rp->r_symlink.contents = linkdata;
4616 				rp->r_symlink.len = uio_len;
4617 				rp->r_symlink.size = len;
4618 				mutex_exit(&rp->r_statelock);
4619 			} else {
4620 				mutex_exit(&rp->r_statelock);
4621 				kmem_free(linkdata, len);
4622 			}
4623 		} else {
4624 			kmem_free(linkdata, len);
4625 		}
4626 	}
4627 	if (res.status == NFS4_OK) {
4628 		resop++;	/* getattr res */
4629 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4630 	}
4631 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4632 
4633 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4634 
4635 	/*
4636 	 * The over the wire error for attempting to readlink something
4637 	 * other than a symbolic link is ENXIO.  However, we need to
4638 	 * return EINVAL instead of ENXIO, so we map it here.
4639 	 */
4640 	return (e.error == ENXIO ? EINVAL : e.error);
4641 }
4642 
4643 /*
4644  * Flush local dirty pages to stable storage on the server.
4645  *
4646  * If FNODSYNC is specified, then there is nothing to do because
4647  * metadata changes are not cached on the client before being
4648  * sent to the server.
4649  */
4650 /* ARGSUSED */
4651 static int
4652 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
4653 {
4654 	int error;
4655 
4656 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4657 		return (0);
4658 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4659 		return (EIO);
4660 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4661 	if (!error)
4662 		error = VTOR4(vp)->r_error;
4663 	return (error);
4664 }
4665 
4666 /*
4667  * Weirdness: if the file was removed or the target of a rename
4668  * operation while it was open, it got renamed instead.  Here we
4669  * remove the renamed file.
4670  */
4671 /* ARGSUSED */
4672 void
4673 nfs4_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4674 {
4675 	rnode4_t *rp;
4676 
4677 	ASSERT(vp != DNLC_NO_VNODE);
4678 
4679 	rp = VTOR4(vp);
4680 
4681 	if (IS_SHADOW(vp, rp)) {
4682 		sv_inactive(vp);
4683 		return;
4684 	}
4685 
4686 	/*
4687 	 * If this is coming from the wrong zone, we let someone in the right
4688 	 * zone take care of it asynchronously.  We can get here due to
4689 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4690 	 * potentially turn into an expensive no-op if, for instance, v_count
4691 	 * gets incremented in the meantime, but it's still correct.
4692 	 */
4693 	if (nfs_zone() != VTOMI4(vp)->mi_zone) {
4694 		nfs4_async_inactive(vp, cr);
4695 		return;
4696 	}
4697 
4698 	/*
4699 	 * Some of the cleanup steps might require over-the-wire
4700 	 * operations.  Since VOP_INACTIVE can get called as a result of
4701 	 * other over-the-wire operations (e.g., an attribute cache update
4702 	 * can lead to a DNLC purge), doing those steps now would lead to a
4703 	 * nested call to the recovery framework, which can deadlock.  So
4704 	 * do any over-the-wire cleanups asynchronously, in a separate
4705 	 * thread.
4706 	 */
4707 
4708 	mutex_enter(&rp->r_os_lock);
4709 	mutex_enter(&rp->r_statelock);
4710 	mutex_enter(&rp->r_statev4_lock);
4711 
4712 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4713 		mutex_exit(&rp->r_statev4_lock);
4714 		mutex_exit(&rp->r_statelock);
4715 		mutex_exit(&rp->r_os_lock);
4716 		nfs4_async_inactive(vp, cr);
4717 		return;
4718 	}
4719 
4720 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4721 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4722 		mutex_exit(&rp->r_statev4_lock);
4723 		mutex_exit(&rp->r_statelock);
4724 		mutex_exit(&rp->r_os_lock);
4725 		nfs4_async_inactive(vp, cr);
4726 		return;
4727 	}
4728 
4729 	if (rp->r_unldvp != NULL) {
4730 		mutex_exit(&rp->r_statev4_lock);
4731 		mutex_exit(&rp->r_statelock);
4732 		mutex_exit(&rp->r_os_lock);
4733 		nfs4_async_inactive(vp, cr);
4734 		return;
4735 	}
4736 	mutex_exit(&rp->r_statev4_lock);
4737 	mutex_exit(&rp->r_statelock);
4738 	mutex_exit(&rp->r_os_lock);
4739 
4740 	rp4_addfree(rp, cr);
4741 }
4742 
4743 /*
4744  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4745  * various bits of state.  The caller must not refer to vp after this call.
4746  */
4747 
4748 void
4749 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4750 {
4751 	rnode4_t *rp = VTOR4(vp);
4752 	nfs4_recov_state_t recov_state;
4753 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4754 	vnode_t *unldvp;
4755 	char *unlname;
4756 	cred_t *unlcred;
4757 	COMPOUND4args_clnt args;
4758 	COMPOUND4res_clnt res, *resp;
4759 	nfs_argop4 argop[2];
4760 	int doqueue;
4761 #ifdef DEBUG
4762 	char *name;
4763 #endif
4764 
4765 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
4766 	ASSERT(!IS_SHADOW(vp, rp));
4767 
4768 #ifdef DEBUG
4769 	name = fn_name(VTOSV(vp)->sv_name);
4770 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4771 	    "release vnode %s", name));
4772 	kmem_free(name, MAXNAMELEN);
4773 #endif
4774 
4775 	if (vp->v_type == VREG) {
4776 		bool_t recov_failed = FALSE;
4777 
4778 		e.error = nfs4close_all(vp, cr);
4779 		if (e.error) {
4780 			/* Check to see if recovery failed */
4781 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4782 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4783 				recov_failed = TRUE;
4784 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4785 			if (!recov_failed) {
4786 				mutex_enter(&rp->r_statelock);
4787 				if (rp->r_flags & R4RECOVERR)
4788 					recov_failed = TRUE;
4789 				mutex_exit(&rp->r_statelock);
4790 			}
4791 			if (recov_failed) {
4792 				NFS4_DEBUG(nfs4_client_recov_debug,
4793 				    (CE_NOTE, "nfs4_inactive_otw: "
4794 				    "close failed (recovery failure)"));
4795 			}
4796 		}
4797 	}
4798 
4799 redo:
4800 	if (rp->r_unldvp == NULL) {
4801 		rp4_addfree(rp, cr);
4802 		return;
4803 	}
4804 
4805 	/*
4806 	 * Save the vnode pointer for the directory where the
4807 	 * unlinked-open file got renamed, then set it to NULL
4808 	 * to prevent another thread from getting here before
4809 	 * we're done with the remove.  While we have the
4810 	 * statelock, make local copies of the pertinent rnode
4811 	 * fields.  If we weren't to do this in an atomic way, the
4812 	 * the unl* fields could become inconsistent with respect
4813 	 * to each other due to a race condition between this
4814 	 * code and nfs_remove().  See bug report 1034328.
4815 	 */
4816 	mutex_enter(&rp->r_statelock);
4817 	if (rp->r_unldvp == NULL) {
4818 		mutex_exit(&rp->r_statelock);
4819 		rp4_addfree(rp, cr);
4820 		return;
4821 	}
4822 
4823 	unldvp = rp->r_unldvp;
4824 	rp->r_unldvp = NULL;
4825 	unlname = rp->r_unlname;
4826 	rp->r_unlname = NULL;
4827 	unlcred = rp->r_unlcred;
4828 	rp->r_unlcred = NULL;
4829 	mutex_exit(&rp->r_statelock);
4830 
4831 	/*
4832 	 * If there are any dirty pages left, then flush
4833 	 * them.  This is unfortunate because they just
4834 	 * may get thrown away during the remove operation,
4835 	 * but we have to do this for correctness.
4836 	 */
4837 	if (nfs4_has_pages(vp) &&
4838 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4839 		ASSERT(vp->v_type != VCHR);
4840 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, NULL);
4841 		if (e.error) {
4842 			mutex_enter(&rp->r_statelock);
4843 			if (!rp->r_error)
4844 				rp->r_error = e.error;
4845 			mutex_exit(&rp->r_statelock);
4846 		}
4847 	}
4848 
4849 	recov_state.rs_flags = 0;
4850 	recov_state.rs_num_retry_despite_err = 0;
4851 recov_retry_remove:
4852 	/*
4853 	 * Do the remove operation on the renamed file
4854 	 */
4855 	args.ctag = TAG_INACTIVE;
4856 
4857 	/*
4858 	 * Remove ops: putfh dir; remove
4859 	 */
4860 	args.array_len = 2;
4861 	args.array = argop;
4862 
4863 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4864 	if (e.error) {
4865 		kmem_free(unlname, MAXNAMELEN);
4866 		crfree(unlcred);
4867 		VN_RELE(unldvp);
4868 		/*
4869 		 * Try again; this time around r_unldvp will be NULL, so we'll
4870 		 * just call rp4_addfree() and return.
4871 		 */
4872 		goto redo;
4873 	}
4874 
4875 	/* putfh directory */
4876 	argop[0].argop = OP_CPUTFH;
4877 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4878 
4879 	/* remove */
4880 	argop[1].argop = OP_CREMOVE;
4881 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4882 
4883 	doqueue = 1;
4884 	resp = &res;
4885 
4886 #if 0 /* notyet */
4887 	/*
4888 	 * Can't do this yet.  We may be being called from
4889 	 * dnlc_purge_XXX while that routine is holding a
4890 	 * mutex lock to the nc_rele list.  The calls to
4891 	 * nfs3_cache_wcc_data may result in calls to
4892 	 * dnlc_purge_XXX.  This will result in a deadlock.
4893 	 */
4894 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4895 	if (e.error) {
4896 		PURGE_ATTRCACHE4(unldvp);
4897 		resp = NULL;
4898 	} else if (res.status) {
4899 		e.error = geterrno4(res.status);
4900 		PURGE_ATTRCACHE4(unldvp);
4901 		/*
4902 		 * This code is inactive right now
4903 		 * but if made active there should
4904 		 * be a nfs4_end_op() call before
4905 		 * nfs4_purge_stale_fh to avoid start_op()
4906 		 * deadlock. See BugId: 4948726
4907 		 */
4908 		nfs4_purge_stale_fh(error, unldvp, cr);
4909 	} else {
4910 		nfs_resop4 *resop;
4911 		REMOVE4res *rm_res;
4912 
4913 		resop = &res.array[1];
4914 		rm_res = &resop->nfs_resop4_u.opremove;
4915 		/*
4916 		 * Update directory cache attribute,
4917 		 * readdir and dnlc caches.
4918 		 */
4919 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4920 	}
4921 #else
4922 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4923 
4924 	PURGE_ATTRCACHE4(unldvp);
4925 #endif
4926 
4927 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4928 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4929 		    NULL, NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
4930 			if (!e.error)
4931 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4932 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4933 			    &recov_state, TRUE);
4934 			goto recov_retry_remove;
4935 		}
4936 	}
4937 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4938 
4939 	/*
4940 	 * Release stuff held for the remove
4941 	 */
4942 	VN_RELE(unldvp);
4943 	if (!e.error && resp)
4944 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4945 
4946 	kmem_free(unlname, MAXNAMELEN);
4947 	crfree(unlcred);
4948 	goto redo;
4949 }
4950 
4951 /*
4952  * Remote file system operations having to do with directory manipulation.
4953  */
4954 /* ARGSUSED3 */
4955 int
4956 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4957     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
4958     int *direntflags, pathname_t *realpnp)
4959 {
4960 	int error;
4961 	vnode_t *vp, *avp = NULL;
4962 	rnode4_t *drp;
4963 
4964 	*vpp = NULL;
4965 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4966 		return (EPERM);
4967 	/*
4968 	 * if LOOKUP_XATTR, must replace dvp (object) with
4969 	 * object's attrdir before continuing with lookup
4970 	 */
4971 	if (flags & LOOKUP_XATTR) {
4972 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4973 		if (error)
4974 			return (error);
4975 
4976 		dvp = avp;
4977 
4978 		/*
4979 		 * If lookup is for "", just return dvp now.  The attrdir
4980 		 * has already been activated (from nfs4lookup_xattr), and
4981 		 * the caller will RELE the original dvp -- not
4982 		 * the attrdir.  So, set vpp and return.
4983 		 * Currently, when the LOOKUP_XATTR flag is
4984 		 * passed to VOP_LOOKUP, the name is always empty, and
4985 		 * shortcircuiting here avoids 3 unneeded lock/unlock
4986 		 * pairs.
4987 		 *
4988 		 * If a non-empty name was provided, then it is the
4989 		 * attribute name, and it will be looked up below.
4990 		 */
4991 		if (*nm == '\0') {
4992 			*vpp = dvp;
4993 			return (0);
4994 		}
4995 
4996 		/*
4997 		 * The vfs layer never sends a name when asking for the
4998 		 * attrdir, so we should never get here (unless of course
4999 		 * name is passed at some time in future -- at which time
5000 		 * we'll blow up here).
5001 		 */
5002 		ASSERT(0);
5003 	}
5004 
5005 	drp = VTOR4(dvp);
5006 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
5007 		return (EINTR);
5008 
5009 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
5010 	nfs_rw_exit(&drp->r_rwlock);
5011 
5012 	/*
5013 	 * If vnode is a device, create special vnode.
5014 	 */
5015 	if (!error && ISVDEV((*vpp)->v_type)) {
5016 		vp = *vpp;
5017 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
5018 		VN_RELE(vp);
5019 	}
5020 
5021 	return (error);
5022 }
5023 
5024 /* ARGSUSED */
5025 static int
5026 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
5027 {
5028 	int error;
5029 	rnode4_t *drp;
5030 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
5031 	mntinfo4_t *mi;
5032 
5033 	mi = VTOMI4(dvp);
5034 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR) &&
5035 	    !vfs_has_feature(mi->mi_vfsp, VFSFT_SYSATTR_VIEWS))
5036 		return (EINVAL);
5037 
5038 	drp = VTOR4(dvp);
5039 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
5040 		return (EINTR);
5041 
5042 	mutex_enter(&drp->r_statelock);
5043 	/*
5044 	 * If the server doesn't support xattrs just return EINVAL
5045 	 */
5046 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
5047 		mutex_exit(&drp->r_statelock);
5048 		nfs_rw_exit(&drp->r_rwlock);
5049 		return (EINVAL);
5050 	}
5051 
5052 	/*
5053 	 * If there is a cached xattr directory entry,
5054 	 * use it as long as the attributes are valid. If the
5055 	 * attributes are not valid, take the simple approach and
5056 	 * free the cached value and re-fetch a new value.
5057 	 *
5058 	 * We don't negative entry cache for now, if we did we
5059 	 * would need to check if the file has changed on every
5060 	 * lookup. But xattrs don't exist very often and failing
5061 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
5062 	 * so do an openattr over the wire for now.
5063 	 */
5064 	if (drp->r_xattr_dir != NULL) {
5065 		if (ATTRCACHE4_VALID(dvp)) {
5066 			VN_HOLD(drp->r_xattr_dir);
5067 			*vpp = drp->r_xattr_dir;
5068 			mutex_exit(&drp->r_statelock);
5069 			nfs_rw_exit(&drp->r_rwlock);
5070 			return (0);
5071 		}
5072 		VN_RELE(drp->r_xattr_dir);
5073 		drp->r_xattr_dir = NULL;
5074 	}
5075 	mutex_exit(&drp->r_statelock);
5076 
5077 	error = nfs4openattr(dvp, vpp, cflag, cr);
5078 
5079 	nfs_rw_exit(&drp->r_rwlock);
5080 
5081 	return (error);
5082 }
5083 
5084 static int
5085 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
5086 {
5087 	int error;
5088 	rnode4_t *drp;
5089 
5090 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5091 
5092 	/*
5093 	 * If lookup is for "", just return dvp.  Don't need
5094 	 * to send it over the wire, look it up in the dnlc,
5095 	 * or perform any access checks.
5096 	 */
5097 	if (*nm == '\0') {
5098 		VN_HOLD(dvp);
5099 		*vpp = dvp;
5100 		return (0);
5101 	}
5102 
5103 	/*
5104 	 * Can't do lookups in non-directories.
5105 	 */
5106 	if (dvp->v_type != VDIR)
5107 		return (ENOTDIR);
5108 
5109 	/*
5110 	 * If lookup is for ".", just return dvp.  Don't need
5111 	 * to send it over the wire or look it up in the dnlc,
5112 	 * just need to check access.
5113 	 */
5114 	if (nm[0] == '.' && nm[1] == '\0') {
5115 		error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5116 		if (error)
5117 			return (error);
5118 		VN_HOLD(dvp);
5119 		*vpp = dvp;
5120 		return (0);
5121 	}
5122 
5123 	drp = VTOR4(dvp);
5124 	if (!(drp->r_flags & R4LOOKUP)) {
5125 		mutex_enter(&drp->r_statelock);
5126 		drp->r_flags |= R4LOOKUP;
5127 		mutex_exit(&drp->r_statelock);
5128 	}
5129 
5130 	*vpp = NULL;
5131 	/*
5132 	 * Lookup this name in the DNLC.  If there is no entry
5133 	 * lookup over the wire.
5134 	 */
5135 	if (!skipdnlc)
5136 		*vpp = dnlc_lookup(dvp, nm);
5137 	if (*vpp == NULL) {
5138 		/*
5139 		 * We need to go over the wire to lookup the name.
5140 		 */
5141 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
5142 	}
5143 
5144 	/*
5145 	 * We hit on the dnlc
5146 	 */
5147 	if (*vpp != DNLC_NO_VNODE ||
5148 	    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
5149 		/*
5150 		 * But our attrs may not be valid.
5151 		 */
5152 		if (ATTRCACHE4_VALID(dvp)) {
5153 			error = nfs4_waitfor_purge_complete(dvp);
5154 			if (error) {
5155 				VN_RELE(*vpp);
5156 				*vpp = NULL;
5157 				return (error);
5158 			}
5159 
5160 			/*
5161 			 * If after the purge completes, check to make sure
5162 			 * our attrs are still valid.
5163 			 */
5164 			if (ATTRCACHE4_VALID(dvp)) {
5165 				/*
5166 				 * If we waited for a purge we may have
5167 				 * lost our vnode so look it up again.
5168 				 */
5169 				VN_RELE(*vpp);
5170 				*vpp = dnlc_lookup(dvp, nm);
5171 				if (*vpp == NULL)
5172 					return (nfs4lookupnew_otw(dvp,
5173 					    nm, vpp, cr));
5174 
5175 				/*
5176 				 * The access cache should almost always hit
5177 				 */
5178 				error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5179 
5180 				if (error) {
5181 					VN_RELE(*vpp);
5182 					*vpp = NULL;
5183 					return (error);
5184 				}
5185 				if (*vpp == DNLC_NO_VNODE) {
5186 					VN_RELE(*vpp);
5187 					*vpp = NULL;
5188 					return (ENOENT);
5189 				}
5190 				return (0);
5191 			}
5192 		}
5193 	}
5194 
5195 	ASSERT(*vpp != NULL);
5196 
5197 	/*
5198 	 * We may have gotten here we have one of the following cases:
5199 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5200 	 *		need to validate them.
5201 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5202 	 *		must validate.
5203 	 *
5204 	 * Go to the server and check if the directory has changed, if
5205 	 * it hasn't we are done and can use the dnlc entry.
5206 	 */
5207 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5208 }
5209 
5210 /*
5211  * Go to the server and check if the directory has changed, if
5212  * it hasn't we are done and can use the dnlc entry.  If it
5213  * has changed we get a new copy of its attributes and check
5214  * the access for VEXEC, then relookup the filename and
5215  * get its filehandle and attributes.
5216  *
5217  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5218  *	if the NVERIFY failed we must
5219  *		purge the caches
5220  *		cache new attributes (will set r_time_attr_inval)
5221  *		cache new access
5222  *		recheck VEXEC access
5223  *		add name to dnlc, possibly negative
5224  *		if LOOKUP succeeded
5225  *			cache new attributes
5226  *	else
5227  *		set a new r_time_attr_inval for dvp
5228  *		check to make sure we have access
5229  *
5230  * The vpp returned is the vnode passed in if the directory is valid,
5231  * a new vnode if successful lookup, or NULL on error.
5232  */
5233 static int
5234 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5235 {
5236 	COMPOUND4args_clnt args;
5237 	COMPOUND4res_clnt res;
5238 	fattr4 *ver_fattr;
5239 	fattr4_change dchange;
5240 	int32_t *ptr;
5241 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5242 	nfs_argop4 *argop;
5243 	int doqueue;
5244 	mntinfo4_t *mi;
5245 	nfs4_recov_state_t recov_state;
5246 	hrtime_t t;
5247 	int isdotdot;
5248 	vnode_t *nvp;
5249 	nfs_fh4 *fhp;
5250 	nfs4_sharedfh_t *sfhp;
5251 	nfs4_access_type_t cacc;
5252 	rnode4_t *nrp;
5253 	rnode4_t *drp = VTOR4(dvp);
5254 	nfs4_ga_res_t *garp = NULL;
5255 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5256 
5257 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5258 	ASSERT(nm != NULL);
5259 	ASSERT(nm[0] != '\0');
5260 	ASSERT(dvp->v_type == VDIR);
5261 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5262 	ASSERT(*vpp != NULL);
5263 
5264 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5265 		isdotdot = 1;
5266 		args.ctag = TAG_LOOKUP_VPARENT;
5267 	} else {
5268 		/*
5269 		 * If dvp were a stub, it should have triggered and caused
5270 		 * a mount for us to get this far.
5271 		 */
5272 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5273 
5274 		isdotdot = 0;
5275 		args.ctag = TAG_LOOKUP_VALID;
5276 	}
5277 
5278 	mi = VTOMI4(dvp);
5279 	recov_state.rs_flags = 0;
5280 	recov_state.rs_num_retry_despite_err = 0;
5281 
5282 	nvp = NULL;
5283 
5284 	/* Save the original mount point security information */
5285 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5286 
5287 recov_retry:
5288 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5289 	    &recov_state, NULL);
5290 	if (e.error) {
5291 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5292 		VN_RELE(*vpp);
5293 		*vpp = NULL;
5294 		return (e.error);
5295 	}
5296 
5297 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5298 
5299 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5300 	args.array_len = 7;
5301 	args.array = argop;
5302 
5303 	/* 0. putfh file */
5304 	argop[0].argop = OP_CPUTFH;
5305 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5306 
5307 	/* 1. nverify the change info */
5308 	argop[1].argop = OP_NVERIFY;
5309 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5310 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5311 	ver_fattr->attrlist4 = (char *)&dchange;
5312 	ptr = (int32_t *)&dchange;
5313 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5314 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5315 
5316 	/* 2. getattr directory */
5317 	argop[2].argop = OP_GETATTR;
5318 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5319 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5320 
5321 	/* 3. access directory */
5322 	argop[3].argop = OP_ACCESS;
5323 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5324 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5325 
5326 	/* 4. lookup name */
5327 	if (isdotdot) {
5328 		argop[4].argop = OP_LOOKUPP;
5329 	} else {
5330 		argop[4].argop = OP_CLOOKUP;
5331 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5332 	}
5333 
5334 	/* 5. resulting file handle */
5335 	argop[5].argop = OP_GETFH;
5336 
5337 	/* 6. resulting file attributes */
5338 	argop[6].argop = OP_GETATTR;
5339 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5340 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5341 
5342 	doqueue = 1;
5343 	t = gethrtime();
5344 
5345 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5346 
5347 	if (!isdotdot && res.status == NFS4ERR_MOVED) {
5348 		e.error = nfs4_setup_referral(dvp, nm, vpp, cr);
5349 		if (e.error != 0 && *vpp != NULL)
5350 			VN_RELE(*vpp);
5351 		nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5352 		    &recov_state, FALSE);
5353 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5354 		kmem_free(argop, argoplist_size);
5355 		return (e.error);
5356 	}
5357 
5358 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5359 		/*
5360 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5361 		 * from this thread, do not go thru the recovery thread since
5362 		 * we need the nm information.
5363 		 *
5364 		 * Not doing dotdot case because there is no specification
5365 		 * for (PUTFH, SECINFO "..") yet.
5366 		 */
5367 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5368 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5369 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5370 				    &recov_state, FALSE);
5371 			else
5372 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5373 				    &recov_state, TRUE);
5374 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5375 			kmem_free(argop, argoplist_size);
5376 			if (!e.error)
5377 				goto recov_retry;
5378 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5379 			VN_RELE(*vpp);
5380 			*vpp = NULL;
5381 			return (e.error);
5382 		}
5383 
5384 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5385 		    OP_LOOKUP, NULL, NULL, NULL) == FALSE) {
5386 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5387 			    &recov_state, TRUE);
5388 
5389 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5390 			kmem_free(argop, argoplist_size);
5391 			goto recov_retry;
5392 		}
5393 	}
5394 
5395 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5396 
5397 	if (e.error || res.array_len == 0) {
5398 		/*
5399 		 * If e.error isn't set, then reply has no ops (or we couldn't
5400 		 * be here).  The only legal way to reply without an op array
5401 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5402 		 * be in the reply for all other status values.
5403 		 *
5404 		 * For valid replies without an ops array, return ENOTSUP
5405 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5406 		 * return EIO -- don't trust status.
5407 		 */
5408 		if (e.error == 0)
5409 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5410 			    ENOTSUP : EIO;
5411 		VN_RELE(*vpp);
5412 		*vpp = NULL;
5413 		kmem_free(argop, argoplist_size);
5414 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5415 		return (e.error);
5416 	}
5417 
5418 	if (res.status != NFS4ERR_SAME) {
5419 		e.error = geterrno4(res.status);
5420 
5421 		/*
5422 		 * The NVERIFY "failed" so the directory has changed
5423 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5424 		 * cleanly.
5425 		 */
5426 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5427 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5428 			nfs4_purge_stale_fh(e.error, dvp, cr);
5429 			VN_RELE(*vpp);
5430 			*vpp = NULL;
5431 			goto exit;
5432 		}
5433 
5434 		/*
5435 		 * We know the NVERIFY "failed" so we must:
5436 		 *	purge the caches (access and indirectly dnlc if needed)
5437 		 */
5438 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5439 
5440 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5441 			nfs4_purge_stale_fh(e.error, dvp, cr);
5442 			VN_RELE(*vpp);
5443 			*vpp = NULL;
5444 			goto exit;
5445 		}
5446 
5447 		/*
5448 		 * Install new cached attributes for the directory
5449 		 */
5450 		nfs4_attr_cache(dvp,
5451 		    &res.array[2].nfs_resop4_u.opgetattr.ga_res,
5452 		    t, cr, FALSE, NULL);
5453 
5454 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5455 			nfs4_purge_stale_fh(e.error, dvp, cr);
5456 			VN_RELE(*vpp);
5457 			*vpp = NULL;
5458 			e.error = geterrno4(res.status);
5459 			goto exit;
5460 		}
5461 
5462 		/*
5463 		 * Now we know the directory is valid,
5464 		 * cache new directory access
5465 		 */
5466 		nfs4_access_cache(drp,
5467 		    args.array[3].nfs_argop4_u.opaccess.access,
5468 		    res.array[3].nfs_resop4_u.opaccess.access, cr);
5469 
5470 		/*
5471 		 * recheck VEXEC access
5472 		 */
5473 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5474 		if (cacc != NFS4_ACCESS_ALLOWED) {
5475 			/*
5476 			 * Directory permissions might have been revoked
5477 			 */
5478 			if (cacc == NFS4_ACCESS_DENIED) {
5479 				e.error = EACCES;
5480 				VN_RELE(*vpp);
5481 				*vpp = NULL;
5482 				goto exit;
5483 			}
5484 
5485 			/*
5486 			 * Somehow we must not have asked for enough
5487 			 * so try a singleton ACCESS, should never happen.
5488 			 */
5489 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5490 			if (e.error) {
5491 				VN_RELE(*vpp);
5492 				*vpp = NULL;
5493 				goto exit;
5494 			}
5495 		}
5496 
5497 		e.error = geterrno4(res.status);
5498 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5499 			/*
5500 			 * The lookup failed, probably no entry
5501 			 */
5502 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5503 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5504 			} else {
5505 				/*
5506 				 * Might be some other error, so remove
5507 				 * the dnlc entry to make sure we start all
5508 				 * over again, next time.
5509 				 */
5510 				dnlc_remove(dvp, nm);
5511 			}
5512 			VN_RELE(*vpp);
5513 			*vpp = NULL;
5514 			goto exit;
5515 		}
5516 
5517 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5518 			/*
5519 			 * The file exists but we can't get its fh for
5520 			 * some unknown reason.  Remove it from the dnlc
5521 			 * and error out to be safe.
5522 			 */
5523 			dnlc_remove(dvp, nm);
5524 			VN_RELE(*vpp);
5525 			*vpp = NULL;
5526 			goto exit;
5527 		}
5528 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5529 		if (fhp->nfs_fh4_len == 0) {
5530 			/*
5531 			 * The file exists but a bogus fh
5532 			 * some unknown reason.  Remove it from the dnlc
5533 			 * and error out to be safe.
5534 			 */
5535 			e.error = ENOENT;
5536 			dnlc_remove(dvp, nm);
5537 			VN_RELE(*vpp);
5538 			*vpp = NULL;
5539 			goto exit;
5540 		}
5541 		sfhp = sfh4_get(fhp, mi);
5542 
5543 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5544 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5545 
5546 		/*
5547 		 * Make the new rnode
5548 		 */
5549 		if (isdotdot) {
5550 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5551 			if (e.error) {
5552 				sfh4_rele(&sfhp);
5553 				VN_RELE(*vpp);
5554 				*vpp = NULL;
5555 				goto exit;
5556 			}
5557 			/*
5558 			 * XXX if nfs4_make_dotdot uses an existing rnode
5559 			 * XXX it doesn't update the attributes.
5560 			 * XXX for now just save them again to save an OTW
5561 			 */
5562 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5563 		} else {
5564 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5565 			    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
5566 			/*
5567 			 * If v_type == VNON, then garp was NULL because
5568 			 * the last op in the compound failed and makenfs4node
5569 			 * could not find the vnode for sfhp. It created
5570 			 * a new vnode, so we have nothing to purge here.
5571 			 */
5572 			if (nvp->v_type == VNON) {
5573 				vattr_t vattr;
5574 
5575 				vattr.va_mask = AT_TYPE;
5576 				/*
5577 				 * N.B. We've already called nfs4_end_fop above.
5578 				 */
5579 				e.error = nfs4getattr(nvp, &vattr, cr);
5580 				if (e.error) {
5581 					sfh4_rele(&sfhp);
5582 					VN_RELE(*vpp);
5583 					*vpp = NULL;
5584 					VN_RELE(nvp);
5585 					goto exit;
5586 				}
5587 				nvp->v_type = vattr.va_type;
5588 			}
5589 		}
5590 		sfh4_rele(&sfhp);
5591 
5592 		nrp = VTOR4(nvp);
5593 		mutex_enter(&nrp->r_statev4_lock);
5594 		if (!nrp->created_v4) {
5595 			mutex_exit(&nrp->r_statev4_lock);
5596 			dnlc_update(dvp, nm, nvp);
5597 		} else
5598 			mutex_exit(&nrp->r_statev4_lock);
5599 
5600 		VN_RELE(*vpp);
5601 		*vpp = nvp;
5602 	} else {
5603 		hrtime_t now;
5604 		hrtime_t delta = 0;
5605 
5606 		e.error = 0;
5607 
5608 		/*
5609 		 * Because the NVERIFY "succeeded" we know that the
5610 		 * directory attributes are still valid
5611 		 * so update r_time_attr_inval
5612 		 */
5613 		now = gethrtime();
5614 		mutex_enter(&drp->r_statelock);
5615 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5616 			delta = now - drp->r_time_attr_saved;
5617 			if (delta < mi->mi_acdirmin)
5618 				delta = mi->mi_acdirmin;
5619 			else if (delta > mi->mi_acdirmax)
5620 				delta = mi->mi_acdirmax;
5621 		}
5622 		drp->r_time_attr_inval = now + delta;
5623 		mutex_exit(&drp->r_statelock);
5624 		dnlc_update(dvp, nm, *vpp);
5625 
5626 		/*
5627 		 * Even though we have a valid directory attr cache
5628 		 * and dnlc entry, we may not have access.
5629 		 * This should almost always hit the cache.
5630 		 */
5631 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5632 		if (e.error) {
5633 			VN_RELE(*vpp);
5634 			*vpp = NULL;
5635 		}
5636 
5637 		if (*vpp == DNLC_NO_VNODE) {
5638 			VN_RELE(*vpp);
5639 			*vpp = NULL;
5640 			e.error = ENOENT;
5641 		}
5642 	}
5643 
5644 exit:
5645 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5646 	kmem_free(argop, argoplist_size);
5647 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5648 	return (e.error);
5649 }
5650 
5651 /*
5652  * We need to go over the wire to lookup the name, but
5653  * while we are there verify the directory has not
5654  * changed but if it has, get new attributes and check access
5655  *
5656  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5657  *					NVERIFY GETATTR ACCESS
5658  *
5659  * With the results:
5660  *	if the NVERIFY failed we must purge the caches, add new attributes,
5661  *		and cache new access.
5662  *	set a new r_time_attr_inval
5663  *	add name to dnlc, possibly negative
5664  *	if LOOKUP succeeded
5665  *		cache new attributes
5666  */
5667 static int
5668 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5669 {
5670 	COMPOUND4args_clnt args;
5671 	COMPOUND4res_clnt res;
5672 	fattr4 *ver_fattr;
5673 	fattr4_change dchange;
5674 	int32_t *ptr;
5675 	nfs4_ga_res_t *garp = NULL;
5676 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5677 	nfs_argop4 *argop;
5678 	int doqueue;
5679 	mntinfo4_t *mi;
5680 	nfs4_recov_state_t recov_state;
5681 	hrtime_t t;
5682 	int isdotdot;
5683 	vnode_t *nvp;
5684 	nfs_fh4 *fhp;
5685 	nfs4_sharedfh_t *sfhp;
5686 	nfs4_access_type_t cacc;
5687 	rnode4_t *nrp;
5688 	rnode4_t *drp = VTOR4(dvp);
5689 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5690 
5691 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5692 	ASSERT(nm != NULL);
5693 	ASSERT(nm[0] != '\0');
5694 	ASSERT(dvp->v_type == VDIR);
5695 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5696 	ASSERT(*vpp == NULL);
5697 
5698 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5699 		isdotdot = 1;
5700 		args.ctag = TAG_LOOKUP_PARENT;
5701 	} else {
5702 		/*
5703 		 * If dvp were a stub, it should have triggered and caused
5704 		 * a mount for us to get this far.
5705 		 */
5706 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5707 
5708 		isdotdot = 0;
5709 		args.ctag = TAG_LOOKUP;
5710 	}
5711 
5712 	mi = VTOMI4(dvp);
5713 	recov_state.rs_flags = 0;
5714 	recov_state.rs_num_retry_despite_err = 0;
5715 
5716 	nvp = NULL;
5717 
5718 	/* Save the original mount point security information */
5719 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5720 
5721 recov_retry:
5722 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5723 	    &recov_state, NULL);
5724 	if (e.error) {
5725 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5726 		return (e.error);
5727 	}
5728 
5729 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5730 
5731 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5732 	args.array_len = 9;
5733 	args.array = argop;
5734 
5735 	/* 0. putfh file */
5736 	argop[0].argop = OP_CPUTFH;
5737 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5738 
5739 	/* 1. savefh for the nverify */
5740 	argop[1].argop = OP_SAVEFH;
5741 
5742 	/* 2. lookup name */
5743 	if (isdotdot) {
5744 		argop[2].argop = OP_LOOKUPP;
5745 	} else {
5746 		argop[2].argop = OP_CLOOKUP;
5747 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5748 	}
5749 
5750 	/* 3. resulting file handle */
5751 	argop[3].argop = OP_GETFH;
5752 
5753 	/* 4. resulting file attributes */
5754 	argop[4].argop = OP_GETATTR;
5755 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5756 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5757 
5758 	/* 5. restorefh back the directory for the nverify */
5759 	argop[5].argop = OP_RESTOREFH;
5760 
5761 	/* 6. nverify the change info */
5762 	argop[6].argop = OP_NVERIFY;
5763 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5764 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5765 	ver_fattr->attrlist4 = (char *)&dchange;
5766 	ptr = (int32_t *)&dchange;
5767 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5768 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5769 
5770 	/* 7. getattr directory */
5771 	argop[7].argop = OP_GETATTR;
5772 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5773 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5774 
5775 	/* 8. access directory */
5776 	argop[8].argop = OP_ACCESS;
5777 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5778 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5779 
5780 	doqueue = 1;
5781 	t = gethrtime();
5782 
5783 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5784 
5785 	if (!isdotdot && res.status == NFS4ERR_MOVED) {
5786 		e.error = nfs4_setup_referral(dvp, nm, vpp, cr);
5787 		if (e.error != 0 && *vpp != NULL)
5788 			VN_RELE(*vpp);
5789 		nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5790 		    &recov_state, FALSE);
5791 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5792 		kmem_free(argop, argoplist_size);
5793 		return (e.error);
5794 	}
5795 
5796 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5797 		/*
5798 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5799 		 * from this thread, do not go thru the recovery thread since
5800 		 * we need the nm information.
5801 		 *
5802 		 * Not doing dotdot case because there is no specification
5803 		 * for (PUTFH, SECINFO "..") yet.
5804 		 */
5805 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5806 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5807 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5808 				    &recov_state, FALSE);
5809 			else
5810 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5811 				    &recov_state, TRUE);
5812 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5813 			kmem_free(argop, argoplist_size);
5814 			if (!e.error)
5815 				goto recov_retry;
5816 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5817 			return (e.error);
5818 		}
5819 
5820 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5821 		    OP_LOOKUP, NULL, NULL, NULL) == FALSE) {
5822 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5823 			    &recov_state, TRUE);
5824 
5825 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5826 			kmem_free(argop, argoplist_size);
5827 			goto recov_retry;
5828 		}
5829 	}
5830 
5831 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5832 
5833 	if (e.error || res.array_len == 0) {
5834 		/*
5835 		 * If e.error isn't set, then reply has no ops (or we couldn't
5836 		 * be here).  The only legal way to reply without an op array
5837 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5838 		 * be in the reply for all other status values.
5839 		 *
5840 		 * For valid replies without an ops array, return ENOTSUP
5841 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5842 		 * return EIO -- don't trust status.
5843 		 */
5844 		if (e.error == 0)
5845 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5846 			    ENOTSUP : EIO;
5847 
5848 		kmem_free(argop, argoplist_size);
5849 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5850 		return (e.error);
5851 	}
5852 
5853 	e.error = geterrno4(res.status);
5854 
5855 	/*
5856 	 * The PUTFH and SAVEFH may have failed.
5857 	 */
5858 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5859 	    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5860 		nfs4_purge_stale_fh(e.error, dvp, cr);
5861 		goto exit;
5862 	}
5863 
5864 	/*
5865 	 * Check if the file exists, if it does delay entering
5866 	 * into the dnlc until after we update the directory
5867 	 * attributes so we don't cause it to get purged immediately.
5868 	 */
5869 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5870 		/*
5871 		 * The lookup failed, probably no entry
5872 		 */
5873 		if (e.error == ENOENT && nfs4_lookup_neg_cache)
5874 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5875 		goto exit;
5876 	}
5877 
5878 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5879 		/*
5880 		 * The file exists but we can't get its fh for
5881 		 * some unknown reason. Error out to be safe.
5882 		 */
5883 		goto exit;
5884 	}
5885 
5886 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5887 	if (fhp->nfs_fh4_len == 0) {
5888 		/*
5889 		 * The file exists but a bogus fh
5890 		 * some unknown reason.  Error out to be safe.
5891 		 */
5892 		e.error = EIO;
5893 		goto exit;
5894 	}
5895 	sfhp = sfh4_get(fhp, mi);
5896 
5897 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5898 		sfh4_rele(&sfhp);
5899 		goto exit;
5900 	}
5901 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5902 
5903 	/*
5904 	 * The RESTOREFH may have failed
5905 	 */
5906 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5907 		sfh4_rele(&sfhp);
5908 		e.error = EIO;
5909 		goto exit;
5910 	}
5911 
5912 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5913 		/*
5914 		 * First make sure the NVERIFY failed as we expected,
5915 		 * if it didn't then be conservative and error out
5916 		 * as we can't trust the directory.
5917 		 */
5918 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5919 			sfh4_rele(&sfhp);
5920 			e.error = EIO;
5921 			goto exit;
5922 		}
5923 
5924 		/*
5925 		 * We know the NVERIFY "failed" so the directory has changed,
5926 		 * so we must:
5927 		 *	purge the caches (access and indirectly dnlc if needed)
5928 		 */
5929 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5930 
5931 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5932 			sfh4_rele(&sfhp);
5933 			goto exit;
5934 		}
5935 		nfs4_attr_cache(dvp,
5936 		    &res.array[7].nfs_resop4_u.opgetattr.ga_res,
5937 		    t, cr, FALSE, NULL);
5938 
5939 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5940 			nfs4_purge_stale_fh(e.error, dvp, cr);
5941 			sfh4_rele(&sfhp);
5942 			e.error = geterrno4(res.status);
5943 			goto exit;
5944 		}
5945 
5946 		/*
5947 		 * Now we know the directory is valid,
5948 		 * cache new directory access
5949 		 */
5950 		nfs4_access_cache(drp,
5951 		    args.array[8].nfs_argop4_u.opaccess.access,
5952 		    res.array[8].nfs_resop4_u.opaccess.access, cr);
5953 
5954 		/*
5955 		 * recheck VEXEC access
5956 		 */
5957 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5958 		if (cacc != NFS4_ACCESS_ALLOWED) {
5959 			/*
5960 			 * Directory permissions might have been revoked
5961 			 */
5962 			if (cacc == NFS4_ACCESS_DENIED) {
5963 				sfh4_rele(&sfhp);
5964 				e.error = EACCES;
5965 				goto exit;
5966 			}
5967 
5968 			/*
5969 			 * Somehow we must not have asked for enough
5970 			 * so try a singleton ACCESS should never happen
5971 			 */
5972 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5973 			if (e.error) {
5974 				sfh4_rele(&sfhp);
5975 				goto exit;
5976 			}
5977 		}
5978 
5979 		e.error = geterrno4(res.status);
5980 	} else {
5981 		hrtime_t now;
5982 		hrtime_t delta = 0;
5983 
5984 		e.error = 0;
5985 
5986 		/*
5987 		 * Because the NVERIFY "succeeded" we know that the
5988 		 * directory attributes are still valid
5989 		 * so update r_time_attr_inval
5990 		 */
5991 		now = gethrtime();
5992 		mutex_enter(&drp->r_statelock);
5993 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5994 			delta = now - drp->r_time_attr_saved;
5995 			if (delta < mi->mi_acdirmin)
5996 				delta = mi->mi_acdirmin;
5997 			else if (delta > mi->mi_acdirmax)
5998 				delta = mi->mi_acdirmax;
5999 		}
6000 		drp->r_time_attr_inval = now + delta;
6001 		mutex_exit(&drp->r_statelock);
6002 
6003 		/*
6004 		 * Even though we have a valid directory attr cache,
6005 		 * we may not have access.
6006 		 * This should almost always hit the cache.
6007 		 */
6008 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
6009 		if (e.error) {
6010 			sfh4_rele(&sfhp);
6011 			goto exit;
6012 		}
6013 	}
6014 
6015 	/*
6016 	 * Now we have successfully completed the lookup, if the
6017 	 * directory has changed we now have the valid attributes.
6018 	 * We also know we have directory access.
6019 	 * Create the new rnode and insert it in the dnlc.
6020 	 */
6021 	if (isdotdot) {
6022 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
6023 		if (e.error) {
6024 			sfh4_rele(&sfhp);
6025 			goto exit;
6026 		}
6027 		/*
6028 		 * XXX if nfs4_make_dotdot uses an existing rnode
6029 		 * XXX it doesn't update the attributes.
6030 		 * XXX for now just save them again to save an OTW
6031 		 */
6032 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
6033 	} else {
6034 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
6035 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
6036 	}
6037 	sfh4_rele(&sfhp);
6038 
6039 	nrp = VTOR4(nvp);
6040 	mutex_enter(&nrp->r_statev4_lock);
6041 	if (!nrp->created_v4) {
6042 		mutex_exit(&nrp->r_statev4_lock);
6043 		dnlc_update(dvp, nm, nvp);
6044 	} else
6045 		mutex_exit(&nrp->r_statev4_lock);
6046 
6047 	*vpp = nvp;
6048 
6049 exit:
6050 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6051 	kmem_free(argop, argoplist_size);
6052 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
6053 	return (e.error);
6054 }
6055 
6056 #ifdef DEBUG
6057 void
6058 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
6059 {
6060 	uint_t i, len;
6061 	zoneid_t zoneid = getzoneid();
6062 	char *s;
6063 
6064 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
6065 	for (i = 0; i < argcnt; i++) {
6066 		nfs_argop4 *op = &argbase[i];
6067 		switch (op->argop) {
6068 		case OP_CPUTFH:
6069 		case OP_PUTFH:
6070 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
6071 			break;
6072 		case OP_PUTROOTFH:
6073 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
6074 			break;
6075 		case OP_CLOOKUP:
6076 			s = op->nfs_argop4_u.opclookup.cname;
6077 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6078 			break;
6079 		case OP_LOOKUP:
6080 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
6081 			    &len, NULL);
6082 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6083 			kmem_free(s, len);
6084 			break;
6085 		case OP_LOOKUPP:
6086 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
6087 			break;
6088 		case OP_GETFH:
6089 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
6090 			break;
6091 		case OP_GETATTR:
6092 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
6093 			break;
6094 		case OP_OPENATTR:
6095 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
6096 			break;
6097 		default:
6098 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
6099 			    op->argop);
6100 			break;
6101 		}
6102 	}
6103 }
6104 #endif
6105 
6106 /*
6107  * nfs4lookup_setup - constructs a multi-lookup compound request.
6108  *
6109  * Given the path "nm1/nm2/.../nmn", the following compound requests
6110  * may be created:
6111  *
6112  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
6113  * is faster, for now.
6114  *
6115  * l4_getattrs indicates the type of compound requested.
6116  *
6117  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
6118  *
6119  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
6120  *
6121  *   total number of ops is n + 1.
6122  *
6123  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
6124  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
6125  *      before the last component, and only get attributes
6126  *      for the last component.  Note that the second-to-last
6127  *	pathname component is XATTR_RPATH, which does NOT go
6128  *	over-the-wire as a lookup.
6129  *
6130  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
6131  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
6132  *
6133  *   and total number of ops is n + 5.
6134  *
6135  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
6136  *      attribute directory: create lookups plus an OPENATTR
6137  *	replacing the last lookup.  Note that the last pathname
6138  *	component is XATTR_RPATH, which does NOT go over-the-wire
6139  *	as a lookup.
6140  *
6141  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
6142  *		Openattr; Getfh; Getattr }
6143  *
6144  *   and total number of ops is n + 5.
6145  *
6146  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6147  *	nodes too.
6148  *
6149  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6150  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6151  *
6152  *   and total number of ops is 3*n + 1.
6153  *
6154  * All cases: returns the index in the arg array of the final LOOKUP op, or
6155  * -1 if no LOOKUPs were used.
6156  */
6157 int
6158 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6159 {
6160 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6161 	nfs_argop4 *argbase, *argop;
6162 	int arglen, argcnt;
6163 	int n = 1;	/* number of components */
6164 	int nga = 1;	/* number of Getattr's in request */
6165 	char c = '\0', *s, *p;
6166 	int lookup_idx = -1;
6167 	int argoplist_size;
6168 
6169 	/* set lookuparg response result to 0 */
6170 	lookupargp->resp->status = NFS4_OK;
6171 
6172 	/* skip leading "/" or "." e.g. ".//./" if there is */
6173 	for (; ; nm++) {
6174 		if (*nm != '/' && *nm != '.')
6175 			break;
6176 
6177 		/* ".." is counted as 1 component */
6178 		if (*nm == '.' && *(nm + 1) != '/')
6179 			break;
6180 	}
6181 
6182 	/*
6183 	 * Find n = number of components - nm must be null terminated
6184 	 * Skip "." components.
6185 	 */
6186 	if (*nm != '\0')
6187 		for (n = 1, s = nm; *s != '\0'; s++) {
6188 			if ((*s == '/') && (*(s + 1) != '/') &&
6189 			    (*(s + 1) != '\0') &&
6190 			    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6191 			    *(s + 2) == '\0')))
6192 				n++;
6193 		}
6194 	else
6195 		n = 0;
6196 
6197 	/*
6198 	 * nga is number of components that need Getfh+Getattr
6199 	 */
6200 	switch (l4_getattrs) {
6201 	case LKP4_NO_ATTRIBUTES:
6202 		nga = 0;
6203 		break;
6204 	case LKP4_ALL_ATTRIBUTES:
6205 		nga = n;
6206 		/*
6207 		 * Always have at least 1 getfh, getattr pair
6208 		 */
6209 		if (nga == 0)
6210 			nga++;
6211 		break;
6212 	case LKP4_LAST_ATTRDIR:
6213 	case LKP4_LAST_NAMED_ATTR:
6214 		nga = n+1;
6215 		break;
6216 	}
6217 
6218 	/*
6219 	 * If change to use the filehandle attr instead of getfh
6220 	 * the following line can be deleted.
6221 	 */
6222 	nga *= 2;
6223 
6224 	/*
6225 	 * calculate number of ops in request as
6226 	 * header + trailer + lookups + getattrs
6227 	 */
6228 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6229 
6230 	argoplist_size = arglen * sizeof (nfs_argop4);
6231 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6232 	lookupargp->argsp->array = argop;
6233 
6234 	argcnt = lookupargp->header_len;
6235 	argop += argcnt;
6236 
6237 	/*
6238 	 * loop and create a lookup op and possibly getattr/getfh for
6239 	 * each component. Skip "." components.
6240 	 */
6241 	for (s = nm; *s != '\0'; s = p) {
6242 		/*
6243 		 * Set up a pathname struct for each component if needed
6244 		 */
6245 		while (*s == '/')
6246 			s++;
6247 		if (*s == '\0')
6248 			break;
6249 
6250 		for (p = s; (*p != '/') && (*p != '\0'); p++)
6251 			;
6252 		c = *p;
6253 		*p = '\0';
6254 
6255 		if (s[0] == '.' && s[1] == '\0') {
6256 			*p = c;
6257 			continue;
6258 		}
6259 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6260 		    strcmp(s, XATTR_RPATH) == 0) {
6261 			/* getfh XXX may not be needed in future */
6262 			argop->argop = OP_GETFH;
6263 			argop++;
6264 			argcnt++;
6265 
6266 			/* getattr */
6267 			argop->argop = OP_GETATTR;
6268 			argop->nfs_argop4_u.opgetattr.attr_request =
6269 			    lookupargp->ga_bits;
6270 			argop->nfs_argop4_u.opgetattr.mi =
6271 			    lookupargp->mi;
6272 			argop++;
6273 			argcnt++;
6274 
6275 			/* openattr */
6276 			argop->argop = OP_OPENATTR;
6277 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6278 		    strcmp(s, XATTR_RPATH) == 0) {
6279 			/* openattr */
6280 			argop->argop = OP_OPENATTR;
6281 			argop++;
6282 			argcnt++;
6283 
6284 			/* getfh XXX may not be needed in future */
6285 			argop->argop = OP_GETFH;
6286 			argop++;
6287 			argcnt++;
6288 
6289 			/* getattr */
6290 			argop->argop = OP_GETATTR;
6291 			argop->nfs_argop4_u.opgetattr.attr_request =
6292 			    lookupargp->ga_bits;
6293 			argop->nfs_argop4_u.opgetattr.mi =
6294 			    lookupargp->mi;
6295 			argop++;
6296 			argcnt++;
6297 			*p = c;
6298 			continue;
6299 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6300 			/* lookupp */
6301 			argop->argop = OP_LOOKUPP;
6302 		} else {
6303 			/* lookup */
6304 			argop->argop = OP_LOOKUP;
6305 			(void) str_to_utf8(s,
6306 			    &argop->nfs_argop4_u.oplookup.objname);
6307 		}
6308 		lookup_idx = argcnt;
6309 		argop++;
6310 		argcnt++;
6311 
6312 		*p = c;
6313 
6314 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6315 			/* getfh XXX may not be needed in future */
6316 			argop->argop = OP_GETFH;
6317 			argop++;
6318 			argcnt++;
6319 
6320 			/* getattr */
6321 			argop->argop = OP_GETATTR;
6322 			argop->nfs_argop4_u.opgetattr.attr_request =
6323 			    lookupargp->ga_bits;
6324 			argop->nfs_argop4_u.opgetattr.mi =
6325 			    lookupargp->mi;
6326 			argop++;
6327 			argcnt++;
6328 		}
6329 	}
6330 
6331 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6332 	    ((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6333 		if (needgetfh) {
6334 			/* stick in a post-lookup getfh */
6335 			argop->argop = OP_GETFH;
6336 			argcnt++;
6337 			argop++;
6338 		}
6339 		/* post-lookup getattr */
6340 		argop->argop = OP_GETATTR;
6341 		argop->nfs_argop4_u.opgetattr.attr_request =
6342 		    lookupargp->ga_bits;
6343 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6344 		argcnt++;
6345 	}
6346 	argcnt += lookupargp->trailer_len;	/* actual op count */
6347 	lookupargp->argsp->array_len = argcnt;
6348 	lookupargp->arglen = arglen;
6349 
6350 #ifdef DEBUG
6351 	if (nfs4_client_lookup_debug)
6352 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6353 #endif
6354 
6355 	return (lookup_idx);
6356 }
6357 
6358 static int
6359 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6360 {
6361 	COMPOUND4args_clnt	args;
6362 	COMPOUND4res_clnt	res;
6363 	GETFH4res	*gf_res = NULL;
6364 	nfs_argop4	argop[4];
6365 	nfs_resop4	*resop = NULL;
6366 	nfs4_sharedfh_t *sfhp;
6367 	hrtime_t t;
6368 	nfs4_error_t	e;
6369 
6370 	rnode4_t	*drp;
6371 	int		doqueue = 1;
6372 	vnode_t		*vp;
6373 	int		needrecov = 0;
6374 	nfs4_recov_state_t recov_state;
6375 
6376 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6377 
6378 	*avp = NULL;
6379 	recov_state.rs_flags = 0;
6380 	recov_state.rs_num_retry_despite_err = 0;
6381 
6382 recov_retry:
6383 	/* COMPOUND: putfh, openattr, getfh, getattr */
6384 	args.array_len = 4;
6385 	args.array = argop;
6386 	args.ctag = TAG_OPENATTR;
6387 
6388 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6389 	if (e.error)
6390 		return (e.error);
6391 
6392 	drp = VTOR4(dvp);
6393 
6394 	/* putfh */
6395 	argop[0].argop = OP_CPUTFH;
6396 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6397 
6398 	/* openattr */
6399 	argop[1].argop = OP_OPENATTR;
6400 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6401 
6402 	/* getfh */
6403 	argop[2].argop = OP_GETFH;
6404 
6405 	/* getattr */
6406 	argop[3].argop = OP_GETATTR;
6407 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6408 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6409 
6410 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6411 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6412 	    rnode4info(drp)));
6413 
6414 	t = gethrtime();
6415 
6416 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6417 
6418 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6419 	if (needrecov) {
6420 		bool_t abort;
6421 
6422 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6423 		    "nfs4openattr: initiating recovery\n"));
6424 
6425 		abort = nfs4_start_recovery(&e,
6426 		    VTOMI4(dvp), dvp, NULL, NULL, NULL,
6427 		    OP_OPENATTR, NULL, NULL, NULL);
6428 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6429 		if (!e.error) {
6430 			e.error = geterrno4(res.status);
6431 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6432 		}
6433 		if (abort == FALSE)
6434 			goto recov_retry;
6435 		return (e.error);
6436 	}
6437 
6438 	if (e.error) {
6439 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6440 		return (e.error);
6441 	}
6442 
6443 	if (res.status) {
6444 		/*
6445 		 * If OTW errro is NOTSUPP, then it should be
6446 		 * translated to EINVAL.  All Solaris file system
6447 		 * implementations return EINVAL to the syscall layer
6448 		 * when the attrdir cannot be created due to an
6449 		 * implementation restriction or noxattr mount option.
6450 		 */
6451 		if (res.status == NFS4ERR_NOTSUPP) {
6452 			mutex_enter(&drp->r_statelock);
6453 			if (drp->r_xattr_dir)
6454 				VN_RELE(drp->r_xattr_dir);
6455 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6456 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6457 			mutex_exit(&drp->r_statelock);
6458 
6459 			e.error = EINVAL;
6460 		} else {
6461 			e.error = geterrno4(res.status);
6462 		}
6463 
6464 		if (e.error) {
6465 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6466 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6467 			    needrecov);
6468 			return (e.error);
6469 		}
6470 	}
6471 
6472 	resop = &res.array[0];  /* putfh res */
6473 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6474 
6475 	resop = &res.array[1];  /* openattr res */
6476 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6477 
6478 	resop = &res.array[2];  /* getfh res */
6479 	gf_res = &resop->nfs_resop4_u.opgetfh;
6480 	if (gf_res->object.nfs_fh4_len == 0) {
6481 		*avp = NULL;
6482 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6483 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6484 		return (ENOENT);
6485 	}
6486 
6487 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6488 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6489 	    dvp->v_vfsp, t, cr, dvp,
6490 	    fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH, sfhp));
6491 	sfh4_rele(&sfhp);
6492 
6493 	if (e.error)
6494 		PURGE_ATTRCACHE4(vp);
6495 
6496 	mutex_enter(&vp->v_lock);
6497 	vp->v_flag |= V_XATTRDIR;
6498 	mutex_exit(&vp->v_lock);
6499 
6500 	*avp = vp;
6501 
6502 	mutex_enter(&drp->r_statelock);
6503 	if (drp->r_xattr_dir)
6504 		VN_RELE(drp->r_xattr_dir);
6505 	VN_HOLD(vp);
6506 	drp->r_xattr_dir = vp;
6507 
6508 	/*
6509 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6510 	 * NULL.  xattrs could be created at any time, and we have no
6511 	 * way to update pc4_xattr_exists in the base object if/when
6512 	 * it happens.
6513 	 */
6514 	drp->r_pathconf.pc4_xattr_valid = 0;
6515 
6516 	mutex_exit(&drp->r_statelock);
6517 
6518 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6519 
6520 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6521 
6522 	return (0);
6523 }
6524 
6525 /* ARGSUSED */
6526 static int
6527 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6528     int mode, vnode_t **vpp, cred_t *cr, int flags, caller_context_t *ct,
6529     vsecattr_t *vsecp)
6530 {
6531 	int error;
6532 	vnode_t *vp = NULL;
6533 	rnode4_t *rp;
6534 	struct vattr vattr;
6535 	rnode4_t *drp;
6536 	vnode_t *tempvp;
6537 	enum createmode4 createmode;
6538 	bool_t must_trunc = FALSE;
6539 	int	truncating = 0;
6540 
6541 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6542 		return (EPERM);
6543 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6544 		return (EINVAL);
6545 	}
6546 
6547 	/* . and .. have special meaning in the protocol, reject them. */
6548 
6549 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6550 		return (EISDIR);
6551 
6552 	drp = VTOR4(dvp);
6553 
6554 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6555 		return (EINTR);
6556 
6557 top:
6558 	/*
6559 	 * We make a copy of the attributes because the caller does not
6560 	 * expect us to change what va points to.
6561 	 */
6562 	vattr = *va;
6563 
6564 	/*
6565 	 * If the pathname is "", then dvp is the root vnode of
6566 	 * a remote file mounted over a local directory.
6567 	 * All that needs to be done is access
6568 	 * checking and truncation.  Note that we avoid doing
6569 	 * open w/ create because the parent directory might
6570 	 * be in pseudo-fs and the open would fail.
6571 	 */
6572 	if (*nm == '\0') {
6573 		error = 0;
6574 		VN_HOLD(dvp);
6575 		vp = dvp;
6576 		must_trunc = TRUE;
6577 	} else {
6578 		/*
6579 		 * We need to go over the wire, just to be sure whether the
6580 		 * file exists or not.  Using the DNLC can be dangerous in
6581 		 * this case when making a decision regarding existence.
6582 		 */
6583 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6584 	}
6585 
6586 	if (exclusive)
6587 		createmode = EXCLUSIVE4;
6588 	else
6589 		createmode = GUARDED4;
6590 
6591 	/*
6592 	 * error would be set if the file does not exist on the
6593 	 * server, so lets go create it.
6594 	 */
6595 	if (error) {
6596 		goto create_otw;
6597 	}
6598 
6599 	/*
6600 	 * File does exist on the server
6601 	 */
6602 	if (exclusive == EXCL)
6603 		error = EEXIST;
6604 	else if (vp->v_type == VDIR && (mode & VWRITE))
6605 		error = EISDIR;
6606 	else {
6607 		/*
6608 		 * If vnode is a device, create special vnode.
6609 		 */
6610 		if (ISVDEV(vp->v_type)) {
6611 			tempvp = vp;
6612 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6613 			VN_RELE(tempvp);
6614 		}
6615 		if (!(error = VOP_ACCESS(vp, mode, 0, cr, ct))) {
6616 			if ((vattr.va_mask & AT_SIZE) &&
6617 			    vp->v_type == VREG) {
6618 				rp = VTOR4(vp);
6619 				/*
6620 				 * Check here for large file handled
6621 				 * by LF-unaware process (as
6622 				 * ufs_create() does)
6623 				 */
6624 				if (!(flags & FOFFMAX)) {
6625 					mutex_enter(&rp->r_statelock);
6626 					if (rp->r_size > MAXOFF32_T)
6627 						error = EOVERFLOW;
6628 					mutex_exit(&rp->r_statelock);
6629 				}
6630 
6631 				/* if error is set then we need to return */
6632 				if (error) {
6633 					nfs_rw_exit(&drp->r_rwlock);
6634 					VN_RELE(vp);
6635 					return (error);
6636 				}
6637 
6638 				if (must_trunc) {
6639 					vattr.va_mask = AT_SIZE;
6640 					error = nfs4setattr(vp, &vattr, 0, cr,
6641 					    NULL);
6642 				} else {
6643 				/*
6644 				 * we know we have a regular file that already
6645 				 * exists and we may end up truncating the file
6646 				 * as a result of the open_otw, so flush out
6647 				 * any dirty pages for this file first.
6648 				 */
6649 					if (nfs4_has_pages(vp) &&
6650 					    ((rp->r_flags & R4DIRTY) ||
6651 					    rp->r_count > 0 ||
6652 					    rp->r_mapcnt > 0)) {
6653 						error = nfs4_putpage(vp,
6654 						    (offset_t)0, 0, 0, cr, ct);
6655 						if (error && (error == ENOSPC ||
6656 						    error == EDQUOT)) {
6657 							mutex_enter(
6658 							    &rp->r_statelock);
6659 							if (!rp->r_error)
6660 								rp->r_error =
6661 								    error;
6662 							mutex_exit(
6663 							    &rp->r_statelock);
6664 						}
6665 					}
6666 					vattr.va_mask = (AT_SIZE |
6667 					    AT_TYPE | AT_MODE);
6668 					vattr.va_type = VREG;
6669 					createmode = UNCHECKED4;
6670 					truncating = 1;
6671 					goto create_otw;
6672 				}
6673 			}
6674 		}
6675 	}
6676 	nfs_rw_exit(&drp->r_rwlock);
6677 	if (error) {
6678 		VN_RELE(vp);
6679 	} else {
6680 		vnode_t *tvp;
6681 		rnode4_t *trp;
6682 		tvp = vp;
6683 		if (vp->v_type == VREG) {
6684 			trp = VTOR4(vp);
6685 			if (IS_SHADOW(vp, trp))
6686 				tvp = RTOV4(trp);
6687 		}
6688 
6689 		if (must_trunc) {
6690 			/*
6691 			 * existing file got truncated, notify.
6692 			 */
6693 			vnevent_create(tvp, ct);
6694 		}
6695 
6696 		*vpp = vp;
6697 	}
6698 	return (error);
6699 
6700 create_otw:
6701 	dnlc_remove(dvp, nm);
6702 
6703 	ASSERT(vattr.va_mask & AT_TYPE);
6704 
6705 	/*
6706 	 * If not a regular file let nfs4mknod() handle it.
6707 	 */
6708 	if (vattr.va_type != VREG) {
6709 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6710 		nfs_rw_exit(&drp->r_rwlock);
6711 		return (error);
6712 	}
6713 
6714 	/*
6715 	 * It _is_ a regular file.
6716 	 */
6717 	ASSERT(vattr.va_mask & AT_MODE);
6718 	if (MANDMODE(vattr.va_mode)) {
6719 		nfs_rw_exit(&drp->r_rwlock);
6720 		return (EACCES);
6721 	}
6722 
6723 	/*
6724 	 * If this happens to be a mknod of a regular file, then flags will
6725 	 * have neither FREAD or FWRITE.  However, we must set at least one
6726 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6727 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6728 	 * set (based on openmode specified by app).
6729 	 */
6730 	if ((flags & (FREAD|FWRITE)) == 0)
6731 		flags |= (FREAD|FWRITE);
6732 
6733 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6734 
6735 	if (vp != NULL) {
6736 		/* if create was successful, throw away the file's pages */
6737 		if (!error && (vattr.va_mask & AT_SIZE))
6738 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6739 			    cr);
6740 		/* release the lookup hold */
6741 		VN_RELE(vp);
6742 		vp = NULL;
6743 	}
6744 
6745 	/*
6746 	 * validate that we opened a regular file. This handles a misbehaving
6747 	 * server that returns an incorrect FH.
6748 	 */
6749 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6750 		error = EISDIR;
6751 		VN_RELE(*vpp);
6752 	}
6753 
6754 	/*
6755 	 * If this is not an exclusive create, then the CREATE
6756 	 * request will be made with the GUARDED mode set.  This
6757 	 * means that the server will return EEXIST if the file
6758 	 * exists.  The file could exist because of a retransmitted
6759 	 * request.  In this case, we recover by starting over and
6760 	 * checking to see whether the file exists.  This second
6761 	 * time through it should and a CREATE request will not be
6762 	 * sent.
6763 	 *
6764 	 * This handles the problem of a dangling CREATE request
6765 	 * which contains attributes which indicate that the file
6766 	 * should be truncated.  This retransmitted request could
6767 	 * possibly truncate valid data in the file if not caught
6768 	 * by the duplicate request mechanism on the server or if
6769 	 * not caught by other means.  The scenario is:
6770 	 *
6771 	 * Client transmits CREATE request with size = 0
6772 	 * Client times out, retransmits request.
6773 	 * Response to the first request arrives from the server
6774 	 *  and the client proceeds on.
6775 	 * Client writes data to the file.
6776 	 * The server now processes retransmitted CREATE request
6777 	 *  and truncates file.
6778 	 *
6779 	 * The use of the GUARDED CREATE request prevents this from
6780 	 * happening because the retransmitted CREATE would fail
6781 	 * with EEXIST and would not truncate the file.
6782 	 */
6783 	if (error == EEXIST && exclusive == NONEXCL) {
6784 #ifdef DEBUG
6785 		nfs4_create_misses++;
6786 #endif
6787 		goto top;
6788 	}
6789 	nfs_rw_exit(&drp->r_rwlock);
6790 	if (truncating && !error && *vpp) {
6791 		vnode_t *tvp;
6792 		rnode4_t *trp;
6793 		/*
6794 		 * existing file got truncated, notify.
6795 		 */
6796 		tvp = *vpp;
6797 		trp = VTOR4(tvp);
6798 		if (IS_SHADOW(tvp, trp))
6799 			tvp = RTOV4(trp);
6800 		vnevent_create(tvp, ct);
6801 	}
6802 	return (error);
6803 }
6804 
6805 /*
6806  * Create compound (for mkdir, mknod, symlink):
6807  * { Putfh <dfh>; Create; Getfh; Getattr }
6808  * It's okay if setattr failed to set gid - this is not considered
6809  * an error, but purge attrs in that case.
6810  */
6811 static int
6812 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6813     vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6814 {
6815 	int need_end_op = FALSE;
6816 	COMPOUND4args_clnt args;
6817 	COMPOUND4res_clnt res, *resp = NULL;
6818 	nfs_argop4 *argop;
6819 	nfs_resop4 *resop;
6820 	int doqueue;
6821 	mntinfo4_t *mi;
6822 	rnode4_t *drp = VTOR4(dvp);
6823 	change_info4 *cinfo;
6824 	GETFH4res *gf_res;
6825 	struct vattr vattr;
6826 	vnode_t *vp;
6827 	fattr4 *crattr;
6828 	bool_t needrecov = FALSE;
6829 	nfs4_recov_state_t recov_state;
6830 	nfs4_sharedfh_t *sfhp = NULL;
6831 	hrtime_t t;
6832 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6833 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6834 	dirattr_info_t dinfo, *dinfop;
6835 	servinfo4_t *svp;
6836 	bitmap4 supp_attrs;
6837 
6838 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6839 	    type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6840 
6841 	mi = VTOMI4(dvp);
6842 
6843 	/*
6844 	 * Make sure we properly deal with setting the right gid
6845 	 * on a new directory to reflect the parent's setgid bit
6846 	 */
6847 	setgid_flag = 0;
6848 	if (type == NF4DIR) {
6849 		struct vattr dva;
6850 
6851 		va->va_mode &= ~VSGID;
6852 		dva.va_mask = AT_MODE | AT_GID;
6853 		if (VOP_GETATTR(dvp, &dva, 0, cr, NULL) == 0) {
6854 
6855 			/*
6856 			 * If the parent's directory has the setgid bit set
6857 			 * _and_ the client was able to get a valid mapping
6858 			 * for the parent dir's owner_group, we want to
6859 			 * append NVERIFY(owner_group == dva.va_gid) and
6860 			 * SETTATTR to the CREATE compound.
6861 			 */
6862 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6863 				setgid_flag = 1;
6864 				va->va_mode |= VSGID;
6865 				if (dva.va_gid != GID_NOBODY) {
6866 					va->va_mask |= AT_GID;
6867 					va->va_gid = dva.va_gid;
6868 				}
6869 			}
6870 		}
6871 	}
6872 
6873 	/*
6874 	 * Create ops:
6875 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6876 	 *	5:restorefh(dir) 6:getattr(dir)
6877 	 *
6878 	 * if (setgid)
6879 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6880 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6881 	 *	8:nverify 9:setattr
6882 	 */
6883 	if (setgid_flag) {
6884 		numops = 10;
6885 		idx_create = 1;
6886 		idx_fattr = 3;
6887 	} else {
6888 		numops = 7;
6889 		idx_create = 2;
6890 		idx_fattr = 4;
6891 	}
6892 
6893 	ASSERT(nfs_zone() == mi->mi_zone);
6894 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6895 		return (EINTR);
6896 	}
6897 	recov_state.rs_flags = 0;
6898 	recov_state.rs_num_retry_despite_err = 0;
6899 
6900 	argoplist_size = numops * sizeof (nfs_argop4);
6901 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6902 
6903 recov_retry:
6904 	if (type == NF4LNK)
6905 		args.ctag = TAG_SYMLINK;
6906 	else if (type == NF4DIR)
6907 		args.ctag = TAG_MKDIR;
6908 	else
6909 		args.ctag = TAG_MKNOD;
6910 
6911 	args.array_len = numops;
6912 	args.array = argop;
6913 
6914 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6915 		nfs_rw_exit(&drp->r_rwlock);
6916 		kmem_free(argop, argoplist_size);
6917 		return (e.error);
6918 	}
6919 	need_end_op = TRUE;
6920 
6921 
6922 	/* 0: putfh directory */
6923 	argop[0].argop = OP_CPUTFH;
6924 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6925 
6926 	/* 1/2: Create object */
6927 	argop[idx_create].argop = OP_CCREATE;
6928 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6929 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6930 	if (type == NF4LNK) {
6931 		/*
6932 		 * symlink, treat name as data
6933 		 */
6934 		ASSERT(data != NULL);
6935 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6936 		    (char *)data;
6937 	}
6938 	if (type == NF4BLK || type == NF4CHR) {
6939 		ASSERT(data != NULL);
6940 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6941 		    *((specdata4 *)data);
6942 	}
6943 
6944 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6945 
6946 	svp = drp->r_server;
6947 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6948 	supp_attrs = svp->sv_supp_attrs;
6949 	nfs_rw_exit(&svp->sv_lock);
6950 
6951 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6952 		nfs_rw_exit(&drp->r_rwlock);
6953 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6954 		e.error = EINVAL;
6955 		kmem_free(argop, argoplist_size);
6956 		return (e.error);
6957 	}
6958 
6959 	/* 2/3: getfh fh of created object */
6960 	ASSERT(idx_create + 1 == idx_fattr - 1);
6961 	argop[idx_create + 1].argop = OP_GETFH;
6962 
6963 	/* 3/4: getattr of new object */
6964 	argop[idx_fattr].argop = OP_GETATTR;
6965 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6966 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6967 
6968 	if (setgid_flag) {
6969 		vattr_t	_v;
6970 
6971 		argop[4].argop = OP_SAVEFH;
6972 
6973 		argop[5].argop = OP_CPUTFH;
6974 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6975 
6976 		argop[6].argop = OP_GETATTR;
6977 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6978 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6979 
6980 		argop[7].argop = OP_RESTOREFH;
6981 
6982 		/*
6983 		 * nverify
6984 		 *
6985 		 * XXX - Revisit the last argument to nfs4_end_op()
6986 		 *	 once 5020486 is fixed.
6987 		 */
6988 		_v.va_mask = AT_GID;
6989 		_v.va_gid = va->va_gid;
6990 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6991 		    supp_attrs)) {
6992 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6993 			nfs_rw_exit(&drp->r_rwlock);
6994 			nfs4_fattr4_free(crattr);
6995 			kmem_free(argop, argoplist_size);
6996 			return (e.error);
6997 		}
6998 
6999 		/*
7000 		 * setattr
7001 		 *
7002 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
7003 		 * so no need for stateid or flags. Also we specify NULL
7004 		 * rp since we're only interested in setting owner_group
7005 		 * attributes.
7006 		 */
7007 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
7008 		    &e.error, 0);
7009 
7010 		if (e.error) {
7011 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
7012 			nfs_rw_exit(&drp->r_rwlock);
7013 			nfs4_fattr4_free(crattr);
7014 			nfs4args_verify_free(&argop[8]);
7015 			kmem_free(argop, argoplist_size);
7016 			return (e.error);
7017 		}
7018 	} else {
7019 		argop[1].argop = OP_SAVEFH;
7020 
7021 		argop[5].argop = OP_RESTOREFH;
7022 
7023 		argop[6].argop = OP_GETATTR;
7024 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7025 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
7026 	}
7027 
7028 	dnlc_remove(dvp, nm);
7029 
7030 	doqueue = 1;
7031 	t = gethrtime();
7032 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7033 
7034 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7035 	if (e.error) {
7036 		PURGE_ATTRCACHE4(dvp);
7037 		if (!needrecov)
7038 			goto out;
7039 	}
7040 
7041 	if (needrecov) {
7042 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
7043 		    OP_CREATE, NULL, NULL, NULL) == FALSE) {
7044 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7045 			    needrecov);
7046 			need_end_op = FALSE;
7047 			nfs4_fattr4_free(crattr);
7048 			if (setgid_flag) {
7049 				nfs4args_verify_free(&argop[8]);
7050 				nfs4args_setattr_free(&argop[9]);
7051 			}
7052 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
7053 			goto recov_retry;
7054 		}
7055 	}
7056 
7057 	resp = &res;
7058 
7059 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
7060 
7061 		if (res.status == NFS4ERR_BADOWNER)
7062 			nfs4_log_badowner(mi, OP_CREATE);
7063 
7064 		e.error = geterrno4(res.status);
7065 
7066 		/*
7067 		 * This check is left over from when create was implemented
7068 		 * using a setattr op (instead of createattrs).  If the
7069 		 * putfh/create/getfh failed, the error was returned.  If
7070 		 * setattr/getattr failed, we keep going.
7071 		 *
7072 		 * It might be better to get rid of the GETFH also, and just
7073 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
7074 		 * Then if any of the operations failed, we could return the
7075 		 * error now, and remove much of the error code below.
7076 		 */
7077 		if (res.array_len <= idx_fattr) {
7078 			/*
7079 			 * Either Putfh, Create or Getfh failed.
7080 			 */
7081 			PURGE_ATTRCACHE4(dvp);
7082 			/*
7083 			 * nfs4_purge_stale_fh() may generate otw calls through
7084 			 * nfs4_invalidate_pages. Hence the need to call
7085 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
7086 			 */
7087 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7088 			    needrecov);
7089 			need_end_op = FALSE;
7090 			nfs4_purge_stale_fh(e.error, dvp, cr);
7091 			goto out;
7092 		}
7093 	}
7094 
7095 	resop = &res.array[idx_create];	/* create res */
7096 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
7097 
7098 	resop = &res.array[idx_create + 1]; /* getfh res */
7099 	gf_res = &resop->nfs_resop4_u.opgetfh;
7100 
7101 	sfhp = sfh4_get(&gf_res->object, mi);
7102 	if (e.error) {
7103 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
7104 		    fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7105 		if (vp->v_type == VNON) {
7106 			vattr.va_mask = AT_TYPE;
7107 			/*
7108 			 * Need to call nfs4_end_op before nfs4getattr to avoid
7109 			 * potential nfs4_start_op deadlock. See RFE 4777612.
7110 			 */
7111 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7112 			    needrecov);
7113 			need_end_op = FALSE;
7114 			e.error = nfs4getattr(vp, &vattr, cr);
7115 			if (e.error) {
7116 				VN_RELE(vp);
7117 				*vpp = NULL;
7118 				goto out;
7119 			}
7120 			vp->v_type = vattr.va_type;
7121 		}
7122 		e.error = 0;
7123 	} else {
7124 		*vpp = vp = makenfs4node(sfhp,
7125 		    &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
7126 		    dvp->v_vfsp, t, cr,
7127 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7128 	}
7129 
7130 	/*
7131 	 * If compound succeeded, then update dir attrs
7132 	 */
7133 	if (res.status == NFS4_OK) {
7134 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
7135 		dinfo.di_cred = cr;
7136 		dinfo.di_time_call = t;
7137 		dinfop = &dinfo;
7138 	} else
7139 		dinfop = NULL;
7140 
7141 	/* Update directory cache attribute, readdir and dnlc caches */
7142 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
7143 
7144 out:
7145 	if (sfhp != NULL)
7146 		sfh4_rele(&sfhp);
7147 	nfs_rw_exit(&drp->r_rwlock);
7148 	nfs4_fattr4_free(crattr);
7149 	if (setgid_flag) {
7150 		nfs4args_verify_free(&argop[8]);
7151 		nfs4args_setattr_free(&argop[9]);
7152 	}
7153 	if (resp)
7154 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7155 	if (need_end_op)
7156 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7157 
7158 	kmem_free(argop, argoplist_size);
7159 	return (e.error);
7160 }
7161 
7162 /* ARGSUSED */
7163 static int
7164 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7165     int mode, vnode_t **vpp, cred_t *cr)
7166 {
7167 	int error;
7168 	vnode_t *vp;
7169 	nfs_ftype4 type;
7170 	specdata4 spec, *specp = NULL;
7171 
7172 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7173 
7174 	switch (va->va_type) {
7175 	case VCHR:
7176 	case VBLK:
7177 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7178 		spec.specdata1 = getmajor(va->va_rdev);
7179 		spec.specdata2 = getminor(va->va_rdev);
7180 		specp = &spec;
7181 		break;
7182 
7183 	case VFIFO:
7184 		type = NF4FIFO;
7185 		break;
7186 	case VSOCK:
7187 		type = NF4SOCK;
7188 		break;
7189 
7190 	default:
7191 		return (EINVAL);
7192 	}
7193 
7194 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7195 	if (error) {
7196 		return (error);
7197 	}
7198 
7199 	/*
7200 	 * This might not be needed any more; special case to deal
7201 	 * with problematic v2/v3 servers.  Since create was unable
7202 	 * to set group correctly, not sure what hope setattr has.
7203 	 */
7204 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7205 		va->va_mask = AT_GID;
7206 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7207 	}
7208 
7209 	/*
7210 	 * If vnode is a device create special vnode
7211 	 */
7212 	if (ISVDEV(vp->v_type)) {
7213 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7214 		VN_RELE(vp);
7215 	} else {
7216 		*vpp = vp;
7217 	}
7218 	return (error);
7219 }
7220 
7221 /*
7222  * Remove requires that the current fh be the target directory.
7223  * After the operation, the current fh is unchanged.
7224  * The compound op structure is:
7225  *      PUTFH(targetdir), REMOVE
7226  *
7227  * Weirdness: if the vnode to be removed is open
7228  * we rename it instead of removing it and nfs_inactive
7229  * will remove the new name.
7230  */
7231 /* ARGSUSED */
7232 static int
7233 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr, caller_context_t *ct, int flags)
7234 {
7235 	COMPOUND4args_clnt args;
7236 	COMPOUND4res_clnt res, *resp = NULL;
7237 	REMOVE4res *rm_res;
7238 	nfs_argop4 argop[3];
7239 	nfs_resop4 *resop;
7240 	vnode_t *vp;
7241 	char *tmpname;
7242 	int doqueue;
7243 	mntinfo4_t *mi;
7244 	rnode4_t *rp;
7245 	rnode4_t *drp;
7246 	int needrecov = 0;
7247 	nfs4_recov_state_t recov_state;
7248 	int isopen;
7249 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7250 	dirattr_info_t dinfo;
7251 
7252 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7253 		return (EPERM);
7254 	drp = VTOR4(dvp);
7255 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7256 		return (EINTR);
7257 
7258 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7259 	if (e.error) {
7260 		nfs_rw_exit(&drp->r_rwlock);
7261 		return (e.error);
7262 	}
7263 
7264 	if (vp->v_type == VDIR) {
7265 		VN_RELE(vp);
7266 		nfs_rw_exit(&drp->r_rwlock);
7267 		return (EISDIR);
7268 	}
7269 
7270 	/*
7271 	 * First just remove the entry from the name cache, as it
7272 	 * is most likely the only entry for this vp.
7273 	 */
7274 	dnlc_remove(dvp, nm);
7275 
7276 	rp = VTOR4(vp);
7277 
7278 	/*
7279 	 * For regular file types, check to see if the file is open by looking
7280 	 * at the open streams.
7281 	 * For all other types, check the reference count on the vnode.  Since
7282 	 * they are not opened OTW they never have an open stream.
7283 	 *
7284 	 * If the file is open, rename it to .nfsXXXX.
7285 	 */
7286 	if (vp->v_type != VREG) {
7287 		/*
7288 		 * If the file has a v_count > 1 then there may be more than one
7289 		 * entry in the name cache due multiple links or an open file,
7290 		 * but we don't have the real reference count so flush all
7291 		 * possible entries.
7292 		 */
7293 		if (vp->v_count > 1)
7294 			dnlc_purge_vp(vp);
7295 
7296 		/*
7297 		 * Now we have the real reference count.
7298 		 */
7299 		isopen = vp->v_count > 1;
7300 	} else {
7301 		mutex_enter(&rp->r_os_lock);
7302 		isopen = list_head(&rp->r_open_streams) != NULL;
7303 		mutex_exit(&rp->r_os_lock);
7304 	}
7305 
7306 	mutex_enter(&rp->r_statelock);
7307 	if (isopen &&
7308 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7309 		mutex_exit(&rp->r_statelock);
7310 		tmpname = newname();
7311 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr, ct);
7312 		if (e.error)
7313 			kmem_free(tmpname, MAXNAMELEN);
7314 		else {
7315 			mutex_enter(&rp->r_statelock);
7316 			if (rp->r_unldvp == NULL) {
7317 				VN_HOLD(dvp);
7318 				rp->r_unldvp = dvp;
7319 				if (rp->r_unlcred != NULL)
7320 					crfree(rp->r_unlcred);
7321 				crhold(cr);
7322 				rp->r_unlcred = cr;
7323 				rp->r_unlname = tmpname;
7324 			} else {
7325 				kmem_free(rp->r_unlname, MAXNAMELEN);
7326 				rp->r_unlname = tmpname;
7327 			}
7328 			mutex_exit(&rp->r_statelock);
7329 		}
7330 		VN_RELE(vp);
7331 		nfs_rw_exit(&drp->r_rwlock);
7332 		return (e.error);
7333 	}
7334 	/*
7335 	 * Actually remove the file/dir
7336 	 */
7337 	mutex_exit(&rp->r_statelock);
7338 
7339 	/*
7340 	 * We need to flush any dirty pages which happen to
7341 	 * be hanging around before removing the file.
7342 	 * This shouldn't happen very often since in NFSv4
7343 	 * we should be close to open consistent.
7344 	 */
7345 	if (nfs4_has_pages(vp) &&
7346 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7347 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, ct);
7348 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7349 			mutex_enter(&rp->r_statelock);
7350 			if (!rp->r_error)
7351 				rp->r_error = e.error;
7352 			mutex_exit(&rp->r_statelock);
7353 		}
7354 	}
7355 
7356 	mi = VTOMI4(dvp);
7357 
7358 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7359 	recov_state.rs_flags = 0;
7360 	recov_state.rs_num_retry_despite_err = 0;
7361 
7362 recov_retry:
7363 	/*
7364 	 * Remove ops: putfh dir; remove
7365 	 */
7366 	args.ctag = TAG_REMOVE;
7367 	args.array_len = 3;
7368 	args.array = argop;
7369 
7370 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7371 	if (e.error) {
7372 		nfs_rw_exit(&drp->r_rwlock);
7373 		VN_RELE(vp);
7374 		return (e.error);
7375 	}
7376 
7377 	/* putfh directory */
7378 	argop[0].argop = OP_CPUTFH;
7379 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7380 
7381 	/* remove */
7382 	argop[1].argop = OP_CREMOVE;
7383 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7384 
7385 	/* getattr dir */
7386 	argop[2].argop = OP_GETATTR;
7387 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7388 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7389 
7390 	doqueue = 1;
7391 	dinfo.di_time_call = gethrtime();
7392 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7393 
7394 	PURGE_ATTRCACHE4(vp);
7395 
7396 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7397 	if (e.error)
7398 		PURGE_ATTRCACHE4(dvp);
7399 
7400 	if (needrecov) {
7401 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7402 		    NULL, NULL, NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
7403 			if (!e.error)
7404 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
7405 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7406 			    needrecov);
7407 			goto recov_retry;
7408 		}
7409 	}
7410 
7411 	/*
7412 	 * Matching nfs4_end_op() for start_op() above.
7413 	 * There is a path in the code below which calls
7414 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7415 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7416 	 * here to avoid nfs4_start_op() deadlock.
7417 	 */
7418 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7419 
7420 	if (!e.error) {
7421 		resp = &res;
7422 
7423 		if (res.status) {
7424 			e.error = geterrno4(res.status);
7425 			PURGE_ATTRCACHE4(dvp);
7426 			nfs4_purge_stale_fh(e.error, dvp, cr);
7427 		} else {
7428 			resop = &res.array[1];	/* remove res */
7429 			rm_res = &resop->nfs_resop4_u.opremove;
7430 
7431 			dinfo.di_garp =
7432 			    &res.array[2].nfs_resop4_u.opgetattr.ga_res;
7433 			dinfo.di_cred = cr;
7434 
7435 			/* Update directory attr, readdir and dnlc caches */
7436 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7437 			    &dinfo);
7438 		}
7439 	}
7440 	nfs_rw_exit(&drp->r_rwlock);
7441 	if (resp)
7442 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7443 
7444 	if (e.error == 0) {
7445 		vnode_t *tvp;
7446 		rnode4_t *trp;
7447 		trp = VTOR4(vp);
7448 		tvp = vp;
7449 		if (IS_SHADOW(vp, trp))
7450 			tvp = RTOV4(trp);
7451 		vnevent_remove(tvp, dvp, nm, ct);
7452 	}
7453 	VN_RELE(vp);
7454 	return (e.error);
7455 }
7456 
7457 /*
7458  * Link requires that the current fh be the target directory and the
7459  * saved fh be the source fh. After the operation, the current fh is unchanged.
7460  * Thus the compound op structure is:
7461  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7462  *	GETATTR(file)
7463  */
7464 /* ARGSUSED */
7465 static int
7466 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr,
7467     caller_context_t *ct, int flags)
7468 {
7469 	COMPOUND4args_clnt args;
7470 	COMPOUND4res_clnt res, *resp = NULL;
7471 	LINK4res *ln_res;
7472 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7473 	nfs_argop4 *argop;
7474 	nfs_resop4 *resop;
7475 	vnode_t *realvp, *nvp;
7476 	int doqueue;
7477 	mntinfo4_t *mi;
7478 	rnode4_t *tdrp;
7479 	bool_t needrecov = FALSE;
7480 	nfs4_recov_state_t recov_state;
7481 	hrtime_t t;
7482 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7483 	dirattr_info_t dinfo;
7484 
7485 	ASSERT(*tnm != '\0');
7486 	ASSERT(tdvp->v_type == VDIR);
7487 	ASSERT(nfs4_consistent_type(tdvp));
7488 	ASSERT(nfs4_consistent_type(svp));
7489 
7490 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7491 		return (EPERM);
7492 	if (VOP_REALVP(svp, &realvp, ct) == 0) {
7493 		svp = realvp;
7494 		ASSERT(nfs4_consistent_type(svp));
7495 	}
7496 
7497 	tdrp = VTOR4(tdvp);
7498 	mi = VTOMI4(svp);
7499 
7500 	if (!(mi->mi_flags & MI4_LINK)) {
7501 		return (EOPNOTSUPP);
7502 	}
7503 	recov_state.rs_flags = 0;
7504 	recov_state.rs_num_retry_despite_err = 0;
7505 
7506 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7507 		return (EINTR);
7508 
7509 recov_retry:
7510 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7511 
7512 	args.ctag = TAG_LINK;
7513 
7514 	/*
7515 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7516 	 * restorefh; getattr(fl)
7517 	 */
7518 	args.array_len = 7;
7519 	args.array = argop;
7520 
7521 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7522 	if (e.error) {
7523 		kmem_free(argop, argoplist_size);
7524 		nfs_rw_exit(&tdrp->r_rwlock);
7525 		return (e.error);
7526 	}
7527 
7528 	/* 0. putfh file */
7529 	argop[0].argop = OP_CPUTFH;
7530 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7531 
7532 	/* 1. save current fh to free up the space for the dir */
7533 	argop[1].argop = OP_SAVEFH;
7534 
7535 	/* 2. putfh targetdir */
7536 	argop[2].argop = OP_CPUTFH;
7537 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7538 
7539 	/* 3. link: current_fh is targetdir, saved_fh is source */
7540 	argop[3].argop = OP_CLINK;
7541 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7542 
7543 	/* 4. Get attributes of dir */
7544 	argop[4].argop = OP_GETATTR;
7545 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7546 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7547 
7548 	/* 5. If link was successful, restore current vp to file */
7549 	argop[5].argop = OP_RESTOREFH;
7550 
7551 	/* 6. Get attributes of linked object */
7552 	argop[6].argop = OP_GETATTR;
7553 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7554 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7555 
7556 	dnlc_remove(tdvp, tnm);
7557 
7558 	doqueue = 1;
7559 	t = gethrtime();
7560 
7561 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7562 
7563 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7564 	if (e.error != 0 && !needrecov) {
7565 		PURGE_ATTRCACHE4(tdvp);
7566 		PURGE_ATTRCACHE4(svp);
7567 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7568 		goto out;
7569 	}
7570 
7571 	if (needrecov) {
7572 		bool_t abort;
7573 
7574 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7575 		    NULL, NULL, OP_LINK, NULL, NULL, NULL);
7576 		if (abort == FALSE) {
7577 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7578 			    needrecov);
7579 			kmem_free(argop, argoplist_size);
7580 			if (!e.error)
7581 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
7582 			goto recov_retry;
7583 		} else {
7584 			if (e.error != 0) {
7585 				PURGE_ATTRCACHE4(tdvp);
7586 				PURGE_ATTRCACHE4(svp);
7587 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7588 				    &recov_state, needrecov);
7589 				goto out;
7590 			}
7591 			/* fall through for res.status case */
7592 		}
7593 	}
7594 
7595 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7596 
7597 	resp = &res;
7598 	if (res.status) {
7599 		/* If link succeeded, then don't return error */
7600 		e.error = geterrno4(res.status);
7601 		if (res.array_len <= 4) {
7602 			/*
7603 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7604 			 */
7605 			PURGE_ATTRCACHE4(svp);
7606 			PURGE_ATTRCACHE4(tdvp);
7607 			if (e.error == EOPNOTSUPP) {
7608 				mutex_enter(&mi->mi_lock);
7609 				mi->mi_flags &= ~MI4_LINK;
7610 				mutex_exit(&mi->mi_lock);
7611 			}
7612 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7613 			/* XXX-LP */
7614 			if (e.error == EISDIR && crgetuid(cr) != 0)
7615 				e.error = EPERM;
7616 			goto out;
7617 		}
7618 	}
7619 
7620 	/* either no error or one of the postop getattr failed */
7621 
7622 	/*
7623 	 * XXX - if LINK succeeded, but no attrs were returned for link
7624 	 * file, purge its cache.
7625 	 *
7626 	 * XXX Perform a simplified version of wcc checking. Instead of
7627 	 * have another getattr to get pre-op, just purge cache if
7628 	 * any of the ops prior to and including the getattr failed.
7629 	 * If the getattr succeeded then update the attrcache accordingly.
7630 	 */
7631 
7632 	/*
7633 	 * update cache with link file postattrs.
7634 	 * Note: at this point resop points to link res.
7635 	 */
7636 	resop = &res.array[3];	/* link res */
7637 	ln_res = &resop->nfs_resop4_u.oplink;
7638 	if (res.status == NFS4_OK)
7639 		e.error = nfs4_update_attrcache(res.status,
7640 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res,
7641 		    t, svp, cr);
7642 
7643 	/*
7644 	 * Call makenfs4node to create the new shadow vp for tnm.
7645 	 * We pass NULL attrs because we just cached attrs for
7646 	 * the src object.  All we're trying to accomplish is to
7647 	 * to create the new shadow vnode.
7648 	 */
7649 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7650 	    tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm, VTOR4(svp)->r_fh));
7651 
7652 	/* Update target cache attribute, readdir and dnlc caches */
7653 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7654 	dinfo.di_time_call = t;
7655 	dinfo.di_cred = cr;
7656 
7657 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7658 	ASSERT(nfs4_consistent_type(tdvp));
7659 	ASSERT(nfs4_consistent_type(svp));
7660 	ASSERT(nfs4_consistent_type(nvp));
7661 	VN_RELE(nvp);
7662 
7663 	if (!e.error) {
7664 		vnode_t *tvp;
7665 		rnode4_t *trp;
7666 		/*
7667 		 * Notify the source file of this link operation.
7668 		 */
7669 		trp = VTOR4(svp);
7670 		tvp = svp;
7671 		if (IS_SHADOW(svp, trp))
7672 			tvp = RTOV4(trp);
7673 		vnevent_link(tvp, ct);
7674 	}
7675 out:
7676 	kmem_free(argop, argoplist_size);
7677 	if (resp)
7678 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7679 
7680 	nfs_rw_exit(&tdrp->r_rwlock);
7681 
7682 	return (e.error);
7683 }
7684 
7685 /* ARGSUSED */
7686 static int
7687 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7688     caller_context_t *ct, int flags)
7689 {
7690 	vnode_t *realvp;
7691 
7692 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7693 		return (EPERM);
7694 	if (VOP_REALVP(ndvp, &realvp, ct) == 0)
7695 		ndvp = realvp;
7696 
7697 	return (nfs4rename(odvp, onm, ndvp, nnm, cr, ct));
7698 }
7699 
7700 /*
7701  * nfs4rename does the real work of renaming in NFS Version 4.
7702  *
7703  * A file handle is considered volatile for renaming purposes if either
7704  * of the volatile bits are turned on. However, the compound may differ
7705  * based on the likelihood of the filehandle to change during rename.
7706  */
7707 static int
7708 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7709     caller_context_t *ct)
7710 {
7711 	int error;
7712 	mntinfo4_t *mi;
7713 	vnode_t *nvp = NULL;
7714 	vnode_t *ovp = NULL;
7715 	char *tmpname = NULL;
7716 	rnode4_t *rp;
7717 	rnode4_t *odrp;
7718 	rnode4_t *ndrp;
7719 	int did_link = 0;
7720 	int do_link = 1;
7721 	nfsstat4 stat = NFS4_OK;
7722 
7723 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7724 	ASSERT(nfs4_consistent_type(odvp));
7725 	ASSERT(nfs4_consistent_type(ndvp));
7726 
7727 	if (onm[0] == '.' && (onm[1] == '\0' ||
7728 	    (onm[1] == '.' && onm[2] == '\0')))
7729 		return (EINVAL);
7730 
7731 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7732 	    (nnm[1] == '.' && nnm[2] == '\0')))
7733 		return (EINVAL);
7734 
7735 	odrp = VTOR4(odvp);
7736 	ndrp = VTOR4(ndvp);
7737 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7738 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7739 			return (EINTR);
7740 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7741 			nfs_rw_exit(&odrp->r_rwlock);
7742 			return (EINTR);
7743 		}
7744 	} else {
7745 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7746 			return (EINTR);
7747 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7748 			nfs_rw_exit(&ndrp->r_rwlock);
7749 			return (EINTR);
7750 		}
7751 	}
7752 
7753 	/*
7754 	 * Lookup the target file.  If it exists, it needs to be
7755 	 * checked to see whether it is a mount point and whether
7756 	 * it is active (open).
7757 	 */
7758 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7759 	if (!error) {
7760 		int	isactive;
7761 
7762 		ASSERT(nfs4_consistent_type(nvp));
7763 		/*
7764 		 * If this file has been mounted on, then just
7765 		 * return busy because renaming to it would remove
7766 		 * the mounted file system from the name space.
7767 		 */
7768 		if (vn_ismntpt(nvp)) {
7769 			VN_RELE(nvp);
7770 			nfs_rw_exit(&odrp->r_rwlock);
7771 			nfs_rw_exit(&ndrp->r_rwlock);
7772 			return (EBUSY);
7773 		}
7774 
7775 		/*
7776 		 * First just remove the entry from the name cache, as it
7777 		 * is most likely the only entry for this vp.
7778 		 */
7779 		dnlc_remove(ndvp, nnm);
7780 
7781 		rp = VTOR4(nvp);
7782 
7783 		if (nvp->v_type != VREG) {
7784 			/*
7785 			 * Purge the name cache of all references to this vnode
7786 			 * so that we can check the reference count to infer
7787 			 * whether it is active or not.
7788 			 */
7789 			if (nvp->v_count > 1)
7790 				dnlc_purge_vp(nvp);
7791 
7792 			isactive = nvp->v_count > 1;
7793 		} else {
7794 			mutex_enter(&rp->r_os_lock);
7795 			isactive = list_head(&rp->r_open_streams) != NULL;
7796 			mutex_exit(&rp->r_os_lock);
7797 		}
7798 
7799 		/*
7800 		 * If the vnode is active and is not a directory,
7801 		 * arrange to rename it to a
7802 		 * temporary file so that it will continue to be
7803 		 * accessible.  This implements the "unlink-open-file"
7804 		 * semantics for the target of a rename operation.
7805 		 * Before doing this though, make sure that the
7806 		 * source and target files are not already the same.
7807 		 */
7808 		if (isactive && nvp->v_type != VDIR) {
7809 			/*
7810 			 * Lookup the source name.
7811 			 */
7812 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7813 
7814 			/*
7815 			 * The source name *should* already exist.
7816 			 */
7817 			if (error) {
7818 				VN_RELE(nvp);
7819 				nfs_rw_exit(&odrp->r_rwlock);
7820 				nfs_rw_exit(&ndrp->r_rwlock);
7821 				return (error);
7822 			}
7823 
7824 			ASSERT(nfs4_consistent_type(ovp));
7825 
7826 			/*
7827 			 * Compare the two vnodes.  If they are the same,
7828 			 * just release all held vnodes and return success.
7829 			 */
7830 			if (VN_CMP(ovp, nvp)) {
7831 				VN_RELE(ovp);
7832 				VN_RELE(nvp);
7833 				nfs_rw_exit(&odrp->r_rwlock);
7834 				nfs_rw_exit(&ndrp->r_rwlock);
7835 				return (0);
7836 			}
7837 
7838 			/*
7839 			 * Can't mix and match directories and non-
7840 			 * directories in rename operations.  We already
7841 			 * know that the target is not a directory.  If
7842 			 * the source is a directory, return an error.
7843 			 */
7844 			if (ovp->v_type == VDIR) {
7845 				VN_RELE(ovp);
7846 				VN_RELE(nvp);
7847 				nfs_rw_exit(&odrp->r_rwlock);
7848 				nfs_rw_exit(&ndrp->r_rwlock);
7849 				return (ENOTDIR);
7850 			}
7851 link_call:
7852 			/*
7853 			 * The target file exists, is not the same as
7854 			 * the source file, and is active.  We first
7855 			 * try to Link it to a temporary filename to
7856 			 * avoid having the server removing the file
7857 			 * completely (which could cause data loss to
7858 			 * the user's POV in the event the Rename fails
7859 			 * -- see bug 1165874).
7860 			 */
7861 			/*
7862 			 * The do_link and did_link booleans are
7863 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7864 			 * returned for the Rename.  Some servers can
7865 			 * not Rename over an Open file, so they return
7866 			 * this error.  The client needs to Remove the
7867 			 * newly created Link and do two Renames, just
7868 			 * as if the server didn't support LINK.
7869 			 */
7870 			tmpname = newname();
7871 			error = 0;
7872 
7873 			if (do_link) {
7874 				error = nfs4_link(ndvp, nvp, tmpname, cr,
7875 				    NULL, 0);
7876 			}
7877 			if (error == EOPNOTSUPP || !do_link) {
7878 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7879 				    cr, NULL, 0);
7880 				did_link = 0;
7881 			} else {
7882 				did_link = 1;
7883 			}
7884 			if (error) {
7885 				kmem_free(tmpname, MAXNAMELEN);
7886 				VN_RELE(ovp);
7887 				VN_RELE(nvp);
7888 				nfs_rw_exit(&odrp->r_rwlock);
7889 				nfs_rw_exit(&ndrp->r_rwlock);
7890 				return (error);
7891 			}
7892 
7893 			mutex_enter(&rp->r_statelock);
7894 			if (rp->r_unldvp == NULL) {
7895 				VN_HOLD(ndvp);
7896 				rp->r_unldvp = ndvp;
7897 				if (rp->r_unlcred != NULL)
7898 					crfree(rp->r_unlcred);
7899 				crhold(cr);
7900 				rp->r_unlcred = cr;
7901 				rp->r_unlname = tmpname;
7902 			} else {
7903 				if (rp->r_unlname)
7904 					kmem_free(rp->r_unlname, MAXNAMELEN);
7905 				rp->r_unlname = tmpname;
7906 			}
7907 			mutex_exit(&rp->r_statelock);
7908 		}
7909 
7910 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7911 
7912 		ASSERT(nfs4_consistent_type(nvp));
7913 	}
7914 
7915 	if (ovp == NULL) {
7916 		/*
7917 		 * When renaming directories to be a subdirectory of a
7918 		 * different parent, the dnlc entry for ".." will no
7919 		 * longer be valid, so it must be removed.
7920 		 *
7921 		 * We do a lookup here to determine whether we are renaming
7922 		 * a directory and we need to check if we are renaming
7923 		 * an unlinked file.  This might have already been done
7924 		 * in previous code, so we check ovp == NULL to avoid
7925 		 * doing it twice.
7926 		 */
7927 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7928 		/*
7929 		 * The source name *should* already exist.
7930 		 */
7931 		if (error) {
7932 			nfs_rw_exit(&odrp->r_rwlock);
7933 			nfs_rw_exit(&ndrp->r_rwlock);
7934 			if (nvp) {
7935 				VN_RELE(nvp);
7936 			}
7937 			return (error);
7938 		}
7939 		ASSERT(ovp != NULL);
7940 		ASSERT(nfs4_consistent_type(ovp));
7941 	}
7942 
7943 	/*
7944 	 * Is the object being renamed a dir, and if so, is
7945 	 * it being renamed to a child of itself?  The underlying
7946 	 * fs should ultimately return EINVAL for this case;
7947 	 * however, buggy beta non-Solaris NFSv4 servers at
7948 	 * interop testing events have allowed this behavior,
7949 	 * and it caused our client to panic due to a recursive
7950 	 * mutex_enter in fn_move.
7951 	 *
7952 	 * The tedious locking in fn_move could be changed to
7953 	 * deal with this case, and the client could avoid the
7954 	 * panic; however, the client would just confuse itself
7955 	 * later and misbehave.  A better way to handle the broken
7956 	 * server is to detect this condition and return EINVAL
7957 	 * without ever sending the the bogus rename to the server.
7958 	 * We know the rename is invalid -- just fail it now.
7959 	 */
7960 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7961 		VN_RELE(ovp);
7962 		nfs_rw_exit(&odrp->r_rwlock);
7963 		nfs_rw_exit(&ndrp->r_rwlock);
7964 		if (nvp) {
7965 			VN_RELE(nvp);
7966 		}
7967 		return (EINVAL);
7968 	}
7969 
7970 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7971 
7972 	/*
7973 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7974 	 * possible for the filehandle to change due to the rename.
7975 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7976 	 * the fh will not change because of the rename, but we still need
7977 	 * to update its rnode entry with the new name for
7978 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7979 	 * has no effect on these for now, but for future improvements,
7980 	 * we might want to use it too to simplify handling of files
7981 	 * that are open with that flag on. (XXX)
7982 	 */
7983 	mi = VTOMI4(odvp);
7984 	if (NFS4_VOLATILE_FH(mi))
7985 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7986 		    &stat);
7987 	else
7988 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7989 		    &stat);
7990 
7991 	ASSERT(nfs4_consistent_type(odvp));
7992 	ASSERT(nfs4_consistent_type(ndvp));
7993 	ASSERT(nfs4_consistent_type(ovp));
7994 
7995 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
7996 		do_link = 0;
7997 		/*
7998 		 * Before the 'link_call' code, we did a nfs4_lookup
7999 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
8000 		 * call we call VN_RELE to match that hold.  We need
8001 		 * to place an additional VN_HOLD here since we will
8002 		 * be hitting that VN_RELE again.
8003 		 */
8004 		VN_HOLD(nvp);
8005 
8006 		(void) nfs4_remove(ndvp, tmpname, cr, NULL, 0);
8007 
8008 		/* Undo the unlinked file naming stuff we just did */
8009 		mutex_enter(&rp->r_statelock);
8010 		if (rp->r_unldvp) {
8011 			VN_RELE(ndvp);
8012 			rp->r_unldvp = NULL;
8013 			if (rp->r_unlcred != NULL)
8014 				crfree(rp->r_unlcred);
8015 			rp->r_unlcred = NULL;
8016 			/* rp->r_unlanme points to tmpname */
8017 			if (rp->r_unlname)
8018 				kmem_free(rp->r_unlname, MAXNAMELEN);
8019 			rp->r_unlname = NULL;
8020 		}
8021 		mutex_exit(&rp->r_statelock);
8022 
8023 		if (nvp) {
8024 			VN_RELE(nvp);
8025 		}
8026 		goto link_call;
8027 	}
8028 
8029 	if (error) {
8030 		VN_RELE(ovp);
8031 		nfs_rw_exit(&odrp->r_rwlock);
8032 		nfs_rw_exit(&ndrp->r_rwlock);
8033 		if (nvp) {
8034 			VN_RELE(nvp);
8035 		}
8036 		return (error);
8037 	}
8038 
8039 	/*
8040 	 * when renaming directories to be a subdirectory of a
8041 	 * different parent, the dnlc entry for ".." will no
8042 	 * longer be valid, so it must be removed
8043 	 */
8044 	rp = VTOR4(ovp);
8045 	if (ndvp != odvp) {
8046 		if (ovp->v_type == VDIR) {
8047 			dnlc_remove(ovp, "..");
8048 			if (rp->r_dir != NULL)
8049 				nfs4_purge_rddir_cache(ovp);
8050 		}
8051 	}
8052 
8053 	/*
8054 	 * If we are renaming the unlinked file, update the
8055 	 * r_unldvp and r_unlname as needed.
8056 	 */
8057 	mutex_enter(&rp->r_statelock);
8058 	if (rp->r_unldvp != NULL) {
8059 		if (strcmp(rp->r_unlname, onm) == 0) {
8060 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
8061 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
8062 			if (ndvp != rp->r_unldvp) {
8063 				VN_RELE(rp->r_unldvp);
8064 				rp->r_unldvp = ndvp;
8065 				VN_HOLD(ndvp);
8066 			}
8067 		}
8068 	}
8069 	mutex_exit(&rp->r_statelock);
8070 
8071 	/*
8072 	 * Notify the rename vnevents to source vnode, and to the target
8073 	 * vnode if it already existed.
8074 	 */
8075 	if (error == 0) {
8076 		vnode_t *tvp;
8077 		rnode4_t *trp;
8078 		/*
8079 		 * Notify the vnode. Each links is represented by
8080 		 * a different vnode, in nfsv4.
8081 		 */
8082 		if (nvp) {
8083 			trp = VTOR4(nvp);
8084 			tvp = nvp;
8085 			if (IS_SHADOW(nvp, trp))
8086 				tvp = RTOV4(trp);
8087 			vnevent_rename_dest(tvp, ndvp, nnm, ct);
8088 		}
8089 
8090 		/*
8091 		 * if the source and destination directory are not the
8092 		 * same notify the destination directory.
8093 		 */
8094 		if (VTOR4(odvp) != VTOR4(ndvp)) {
8095 			trp = VTOR4(ndvp);
8096 			tvp = ndvp;
8097 			if (IS_SHADOW(ndvp, trp))
8098 				tvp = RTOV4(trp);
8099 			vnevent_rename_dest_dir(tvp, ct);
8100 		}
8101 
8102 		trp = VTOR4(ovp);
8103 		tvp = ovp;
8104 		if (IS_SHADOW(ovp, trp))
8105 			tvp = RTOV4(trp);
8106 		vnevent_rename_src(tvp, odvp, onm, ct);
8107 	}
8108 
8109 	if (nvp) {
8110 		VN_RELE(nvp);
8111 	}
8112 	VN_RELE(ovp);
8113 
8114 	nfs_rw_exit(&odrp->r_rwlock);
8115 	nfs_rw_exit(&ndrp->r_rwlock);
8116 
8117 	return (error);
8118 }
8119 
8120 /*
8121  * When the parent directory has changed, sv_dfh must be updated
8122  */
8123 static void
8124 update_parentdir_sfh(vnode_t *vp, vnode_t *ndvp)
8125 {
8126 	svnode_t *sv = VTOSV(vp);
8127 	nfs4_sharedfh_t *old_dfh = sv->sv_dfh;
8128 	nfs4_sharedfh_t *new_dfh = VTOR4(ndvp)->r_fh;
8129 
8130 	sfh4_hold(new_dfh);
8131 	sv->sv_dfh = new_dfh;
8132 	sfh4_rele(&old_dfh);
8133 }
8134 
8135 /*
8136  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
8137  * when it is known that the filehandle is persistent through rename.
8138  *
8139  * Rename requires that the current fh be the target directory and the
8140  * saved fh be the source directory. After the operation, the current fh
8141  * is unchanged.
8142  * The compound op structure for persistent fh rename is:
8143  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
8144  * Rather than bother with the directory postop args, we'll simply
8145  * update that a change occurred in the cache, so no post-op getattrs.
8146  */
8147 static int
8148 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
8149     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8150 {
8151 	COMPOUND4args_clnt args;
8152 	COMPOUND4res_clnt res, *resp = NULL;
8153 	nfs_argop4 *argop;
8154 	nfs_resop4 *resop;
8155 	int doqueue, argoplist_size;
8156 	mntinfo4_t *mi;
8157 	rnode4_t *odrp = VTOR4(odvp);
8158 	rnode4_t *ndrp = VTOR4(ndvp);
8159 	RENAME4res *rn_res;
8160 	bool_t needrecov;
8161 	nfs4_recov_state_t recov_state;
8162 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8163 	dirattr_info_t dinfo, *dinfop;
8164 
8165 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8166 
8167 	recov_state.rs_flags = 0;
8168 	recov_state.rs_num_retry_despite_err = 0;
8169 
8170 	/*
8171 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
8172 	 *
8173 	 * If source/target are different dirs, then append putfh(src); getattr
8174 	 */
8175 	args.array_len = (odvp == ndvp) ? 5 : 7;
8176 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8177 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8178 
8179 recov_retry:
8180 	*statp = NFS4_OK;
8181 
8182 	/* No need to Lookup the file, persistent fh */
8183 	args.ctag = TAG_RENAME;
8184 
8185 	mi = VTOMI4(odvp);
8186 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8187 	if (e.error) {
8188 		kmem_free(argop, argoplist_size);
8189 		return (e.error);
8190 	}
8191 
8192 	/* 0: putfh source directory */
8193 	argop[0].argop = OP_CPUTFH;
8194 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8195 
8196 	/* 1: Save source fh to free up current for target */
8197 	argop[1].argop = OP_SAVEFH;
8198 
8199 	/* 2: putfh targetdir */
8200 	argop[2].argop = OP_CPUTFH;
8201 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8202 
8203 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8204 	argop[3].argop = OP_CRENAME;
8205 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8206 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8207 
8208 	/* 4: getattr (targetdir) */
8209 	argop[4].argop = OP_GETATTR;
8210 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8211 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8212 
8213 	if (ndvp != odvp) {
8214 
8215 		/* 5: putfh (sourcedir) */
8216 		argop[5].argop = OP_CPUTFH;
8217 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8218 
8219 		/* 6: getattr (sourcedir) */
8220 		argop[6].argop = OP_GETATTR;
8221 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8222 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8223 	}
8224 
8225 	dnlc_remove(odvp, onm);
8226 	dnlc_remove(ndvp, nnm);
8227 
8228 	doqueue = 1;
8229 	dinfo.di_time_call = gethrtime();
8230 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8231 
8232 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8233 	if (e.error) {
8234 		PURGE_ATTRCACHE4(odvp);
8235 		PURGE_ATTRCACHE4(ndvp);
8236 	} else {
8237 		*statp = res.status;
8238 	}
8239 
8240 	if (needrecov) {
8241 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8242 		    OP_RENAME, NULL, NULL, NULL) == FALSE) {
8243 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8244 			if (!e.error)
8245 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
8246 			goto recov_retry;
8247 		}
8248 	}
8249 
8250 	if (!e.error) {
8251 		resp = &res;
8252 		/*
8253 		 * as long as OP_RENAME
8254 		 */
8255 		if (res.status != NFS4_OK && res.array_len <= 4) {
8256 			e.error = geterrno4(res.status);
8257 			PURGE_ATTRCACHE4(odvp);
8258 			PURGE_ATTRCACHE4(ndvp);
8259 			/*
8260 			 * System V defines rename to return EEXIST, not
8261 			 * ENOTEMPTY if the target directory is not empty.
8262 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8263 			 * which geterrno4 maps to ENOTEMPTY.
8264 			 */
8265 			if (e.error == ENOTEMPTY)
8266 				e.error = EEXIST;
8267 		} else {
8268 
8269 			resop = &res.array[3];	/* rename res */
8270 			rn_res = &resop->nfs_resop4_u.oprename;
8271 
8272 			if (res.status == NFS4_OK) {
8273 				/*
8274 				 * Update target attribute, readdir and dnlc
8275 				 * caches.
8276 				 */
8277 				dinfo.di_garp =
8278 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8279 				dinfo.di_cred = cr;
8280 				dinfop = &dinfo;
8281 			} else
8282 				dinfop = NULL;
8283 
8284 			nfs4_update_dircaches(&rn_res->target_cinfo,
8285 			    ndvp, NULL, NULL, dinfop);
8286 
8287 			/*
8288 			 * Update source attribute, readdir and dnlc caches
8289 			 *
8290 			 */
8291 			if (ndvp != odvp) {
8292 				update_parentdir_sfh(renvp, ndvp);
8293 
8294 				if (dinfop)
8295 					dinfo.di_garp =
8296 					    &(res.array[6].nfs_resop4_u.
8297 					    opgetattr.ga_res);
8298 
8299 				nfs4_update_dircaches(&rn_res->source_cinfo,
8300 				    odvp, NULL, NULL, dinfop);
8301 			}
8302 
8303 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8304 			    nnm);
8305 		}
8306 	}
8307 
8308 	if (resp)
8309 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8310 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8311 	kmem_free(argop, argoplist_size);
8312 
8313 	return (e.error);
8314 }
8315 
8316 /*
8317  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8318  * it is possible for the filehandle to change due to the rename.
8319  *
8320  * The compound req in this case includes a post-rename lookup and getattr
8321  * to ensure that we have the correct fh and attributes for the object.
8322  *
8323  * Rename requires that the current fh be the target directory and the
8324  * saved fh be the source directory. After the operation, the current fh
8325  * is unchanged.
8326  *
8327  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8328  * update the filehandle for the renamed object.  We also get the old
8329  * filehandle for historical reasons; this should be taken out sometime.
8330  * This results in a rather cumbersome compound...
8331  *
8332  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8333  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8334  *
8335  */
8336 static int
8337 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8338     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8339 {
8340 	COMPOUND4args_clnt args;
8341 	COMPOUND4res_clnt res, *resp = NULL;
8342 	int argoplist_size;
8343 	nfs_argop4 *argop;
8344 	nfs_resop4 *resop;
8345 	int doqueue;
8346 	mntinfo4_t *mi;
8347 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8348 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8349 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8350 	RENAME4res *rn_res;
8351 	GETFH4res *ngf_res;
8352 	bool_t needrecov;
8353 	nfs4_recov_state_t recov_state;
8354 	hrtime_t t;
8355 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8356 	dirattr_info_t dinfo, *dinfop = &dinfo;
8357 
8358 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8359 
8360 	recov_state.rs_flags = 0;
8361 	recov_state.rs_num_retry_despite_err = 0;
8362 
8363 recov_retry:
8364 	*statp = NFS4_OK;
8365 
8366 	/*
8367 	 * There is a window between the RPC and updating the path and
8368 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8369 	 * code, so that it doesn't try to use the old path during that
8370 	 * window.
8371 	 */
8372 	mutex_enter(&orp->r_statelock);
8373 	while (orp->r_flags & R4RECEXPFH) {
8374 		klwp_t *lwp = ttolwp(curthread);
8375 
8376 		if (lwp != NULL)
8377 			lwp->lwp_nostop++;
8378 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8379 			mutex_exit(&orp->r_statelock);
8380 			if (lwp != NULL)
8381 				lwp->lwp_nostop--;
8382 			return (EINTR);
8383 		}
8384 		if (lwp != NULL)
8385 			lwp->lwp_nostop--;
8386 	}
8387 	orp->r_flags |= R4RECEXPFH;
8388 	mutex_exit(&orp->r_statelock);
8389 
8390 	mi = VTOMI4(odvp);
8391 
8392 	args.ctag = TAG_RENAME_VFH;
8393 	args.array_len = (odvp == ndvp) ? 10 : 12;
8394 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8395 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8396 
8397 	/*
8398 	 * Rename ops:
8399 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8400 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8401 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8402 	 *
8403 	 *    if (odvp != ndvp)
8404 	 *	add putfh(sourcedir), getattr(sourcedir) }
8405 	 */
8406 	args.array = argop;
8407 
8408 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8409 	    &recov_state, NULL);
8410 	if (e.error) {
8411 		kmem_free(argop, argoplist_size);
8412 		mutex_enter(&orp->r_statelock);
8413 		orp->r_flags &= ~R4RECEXPFH;
8414 		cv_broadcast(&orp->r_cv);
8415 		mutex_exit(&orp->r_statelock);
8416 		return (e.error);
8417 	}
8418 
8419 	/* 0: putfh source directory */
8420 	argop[0].argop = OP_CPUTFH;
8421 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8422 
8423 	/* 1: Save source fh to free up current for target */
8424 	argop[1].argop = OP_SAVEFH;
8425 
8426 	/* 2: Lookup pre-rename fh of renamed object */
8427 	argop[2].argop = OP_CLOOKUP;
8428 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8429 
8430 	/* 3: getfh fh of renamed object (before rename) */
8431 	argop[3].argop = OP_GETFH;
8432 
8433 	/* 4: putfh targetdir */
8434 	argop[4].argop = OP_CPUTFH;
8435 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8436 
8437 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8438 	argop[5].argop = OP_CRENAME;
8439 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8440 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8441 
8442 	/* 6: getattr of target dir (post op attrs) */
8443 	argop[6].argop = OP_GETATTR;
8444 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8445 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8446 
8447 	/* 7: Lookup post-rename fh of renamed object */
8448 	argop[7].argop = OP_CLOOKUP;
8449 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8450 
8451 	/* 8: getfh fh of renamed object (after rename) */
8452 	argop[8].argop = OP_GETFH;
8453 
8454 	/* 9: getattr of renamed object */
8455 	argop[9].argop = OP_GETATTR;
8456 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8457 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8458 
8459 	/*
8460 	 * If source/target dirs are different, then get new post-op
8461 	 * attrs for source dir also.
8462 	 */
8463 	if (ndvp != odvp) {
8464 		/* 10: putfh (sourcedir) */
8465 		argop[10].argop = OP_CPUTFH;
8466 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8467 
8468 		/* 11: getattr (sourcedir) */
8469 		argop[11].argop = OP_GETATTR;
8470 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8471 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8472 	}
8473 
8474 	dnlc_remove(odvp, onm);
8475 	dnlc_remove(ndvp, nnm);
8476 
8477 	doqueue = 1;
8478 	t = gethrtime();
8479 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8480 
8481 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8482 	if (e.error) {
8483 		PURGE_ATTRCACHE4(odvp);
8484 		PURGE_ATTRCACHE4(ndvp);
8485 		if (!needrecov) {
8486 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8487 			    &recov_state, needrecov);
8488 			goto out;
8489 		}
8490 	} else {
8491 		*statp = res.status;
8492 	}
8493 
8494 	if (needrecov) {
8495 		bool_t abort;
8496 
8497 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8498 		    OP_RENAME, NULL, NULL, NULL);
8499 		if (abort == FALSE) {
8500 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8501 			    &recov_state, needrecov);
8502 			kmem_free(argop, argoplist_size);
8503 			if (!e.error)
8504 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
8505 			mutex_enter(&orp->r_statelock);
8506 			orp->r_flags &= ~R4RECEXPFH;
8507 			cv_broadcast(&orp->r_cv);
8508 			mutex_exit(&orp->r_statelock);
8509 			goto recov_retry;
8510 		} else {
8511 			if (e.error != 0) {
8512 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8513 				    &recov_state, needrecov);
8514 				goto out;
8515 			}
8516 			/* fall through for res.status case */
8517 		}
8518 	}
8519 
8520 	resp = &res;
8521 	/*
8522 	 * If OP_RENAME (or any prev op) failed, then return an error.
8523 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8524 	 */
8525 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8526 		/*
8527 		 * Error in an op other than last Getattr
8528 		 */
8529 		e.error = geterrno4(res.status);
8530 		PURGE_ATTRCACHE4(odvp);
8531 		PURGE_ATTRCACHE4(ndvp);
8532 		/*
8533 		 * System V defines rename to return EEXIST, not
8534 		 * ENOTEMPTY if the target directory is not empty.
8535 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8536 		 * which geterrno4 maps to ENOTEMPTY.
8537 		 */
8538 		if (e.error == ENOTEMPTY)
8539 			e.error = EEXIST;
8540 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8541 		    needrecov);
8542 		goto out;
8543 	}
8544 
8545 	/* rename results */
8546 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8547 
8548 	if (res.status == NFS4_OK) {
8549 		/* Update target attribute, readdir and dnlc caches */
8550 		dinfo.di_garp =
8551 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
8552 		dinfo.di_cred = cr;
8553 		dinfo.di_time_call = t;
8554 	} else
8555 		dinfop = NULL;
8556 
8557 	/* Update source cache attribute, readdir and dnlc caches */
8558 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8559 
8560 	/* Update source cache attribute, readdir and dnlc caches */
8561 	if (ndvp != odvp) {
8562 		update_parentdir_sfh(ovp, ndvp);
8563 
8564 		/*
8565 		 * If dinfop is non-NULL, then compound succeded, so
8566 		 * set di_garp to attrs for source dir.  dinfop is only
8567 		 * set to NULL when compound fails.
8568 		 */
8569 		if (dinfop)
8570 			dinfo.di_garp =
8571 			    &res.array[11].nfs_resop4_u.opgetattr.ga_res;
8572 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8573 		    dinfop);
8574 	}
8575 
8576 	/*
8577 	 * Update the rnode with the new component name and args,
8578 	 * and if the file handle changed, also update it with the new fh.
8579 	 * This is only necessary if the target object has an rnode
8580 	 * entry and there is no need to create one for it.
8581 	 */
8582 	resop = &res.array[8];	/* getfh new res */
8583 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8584 
8585 	/*
8586 	 * Update the path and filehandle for the renamed object.
8587 	 */
8588 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8589 
8590 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8591 
8592 	if (res.status == NFS4_OK) {
8593 		resop++;	/* getattr res */
8594 		e.error = nfs4_update_attrcache(res.status,
8595 		    &resop->nfs_resop4_u.opgetattr.ga_res,
8596 		    t, ovp, cr);
8597 	}
8598 
8599 out:
8600 	kmem_free(argop, argoplist_size);
8601 	if (resp)
8602 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8603 	mutex_enter(&orp->r_statelock);
8604 	orp->r_flags &= ~R4RECEXPFH;
8605 	cv_broadcast(&orp->r_cv);
8606 	mutex_exit(&orp->r_statelock);
8607 
8608 	return (e.error);
8609 }
8610 
8611 /* ARGSUSED */
8612 static int
8613 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr,
8614     caller_context_t *ct, int flags, vsecattr_t *vsecp)
8615 {
8616 	int error;
8617 	vnode_t *vp;
8618 
8619 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8620 		return (EPERM);
8621 	/*
8622 	 * As ".." has special meaning and rather than send a mkdir
8623 	 * over the wire to just let the server freak out, we just
8624 	 * short circuit it here and return EEXIST
8625 	 */
8626 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8627 		return (EEXIST);
8628 
8629 	/*
8630 	 * Decision to get the right gid and setgid bit of the
8631 	 * new directory is now made in call_nfs4_create_req.
8632 	 */
8633 	va->va_mask |= AT_MODE;
8634 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8635 	if (error)
8636 		return (error);
8637 
8638 	*vpp = vp;
8639 	return (0);
8640 }
8641 
8642 
8643 /*
8644  * rmdir is using the same remove v4 op as does remove.
8645  * Remove requires that the current fh be the target directory.
8646  * After the operation, the current fh is unchanged.
8647  * The compound op structure is:
8648  *      PUTFH(targetdir), REMOVE
8649  */
8650 /*ARGSUSED4*/
8651 static int
8652 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr,
8653     caller_context_t *ct, int flags)
8654 {
8655 	int need_end_op = FALSE;
8656 	COMPOUND4args_clnt args;
8657 	COMPOUND4res_clnt res, *resp = NULL;
8658 	REMOVE4res *rm_res;
8659 	nfs_argop4 argop[3];
8660 	nfs_resop4 *resop;
8661 	vnode_t *vp;
8662 	int doqueue;
8663 	mntinfo4_t *mi;
8664 	rnode4_t *drp;
8665 	bool_t needrecov = FALSE;
8666 	nfs4_recov_state_t recov_state;
8667 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8668 	dirattr_info_t dinfo, *dinfop;
8669 
8670 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8671 		return (EPERM);
8672 	/*
8673 	 * As ".." has special meaning and rather than send a rmdir
8674 	 * over the wire to just let the server freak out, we just
8675 	 * short circuit it here and return EEXIST
8676 	 */
8677 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8678 		return (EEXIST);
8679 
8680 	drp = VTOR4(dvp);
8681 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8682 		return (EINTR);
8683 
8684 	/*
8685 	 * Attempt to prevent a rmdir(".") from succeeding.
8686 	 */
8687 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8688 	if (e.error) {
8689 		nfs_rw_exit(&drp->r_rwlock);
8690 		return (e.error);
8691 	}
8692 	if (vp == cdir) {
8693 		VN_RELE(vp);
8694 		nfs_rw_exit(&drp->r_rwlock);
8695 		return (EINVAL);
8696 	}
8697 
8698 	/*
8699 	 * Since nfsv4 remove op works on both files and directories,
8700 	 * check that the removed object is indeed a directory.
8701 	 */
8702 	if (vp->v_type != VDIR) {
8703 		VN_RELE(vp);
8704 		nfs_rw_exit(&drp->r_rwlock);
8705 		return (ENOTDIR);
8706 	}
8707 
8708 	/*
8709 	 * First just remove the entry from the name cache, as it
8710 	 * is most likely an entry for this vp.
8711 	 */
8712 	dnlc_remove(dvp, nm);
8713 
8714 	/*
8715 	 * If there vnode reference count is greater than one, then
8716 	 * there may be additional references in the DNLC which will
8717 	 * need to be purged.  First, trying removing the entry for
8718 	 * the parent directory and see if that removes the additional
8719 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8720 	 * to completely remove any references to the directory which
8721 	 * might still exist in the DNLC.
8722 	 */
8723 	if (vp->v_count > 1) {
8724 		dnlc_remove(vp, "..");
8725 		if (vp->v_count > 1)
8726 			dnlc_purge_vp(vp);
8727 	}
8728 
8729 	mi = VTOMI4(dvp);
8730 	recov_state.rs_flags = 0;
8731 	recov_state.rs_num_retry_despite_err = 0;
8732 
8733 recov_retry:
8734 	args.ctag = TAG_RMDIR;
8735 
8736 	/*
8737 	 * Rmdir ops: putfh dir; remove
8738 	 */
8739 	args.array_len = 3;
8740 	args.array = argop;
8741 
8742 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8743 	if (e.error) {
8744 		nfs_rw_exit(&drp->r_rwlock);
8745 		return (e.error);
8746 	}
8747 	need_end_op = TRUE;
8748 
8749 	/* putfh directory */
8750 	argop[0].argop = OP_CPUTFH;
8751 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8752 
8753 	/* remove */
8754 	argop[1].argop = OP_CREMOVE;
8755 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8756 
8757 	/* getattr (postop attrs for dir that contained removed dir) */
8758 	argop[2].argop = OP_GETATTR;
8759 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8760 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8761 
8762 	dinfo.di_time_call = gethrtime();
8763 	doqueue = 1;
8764 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8765 
8766 	PURGE_ATTRCACHE4(vp);
8767 
8768 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8769 	if (e.error) {
8770 		PURGE_ATTRCACHE4(dvp);
8771 	}
8772 
8773 	if (needrecov) {
8774 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8775 		    NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
8776 			if (!e.error)
8777 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
8778 
8779 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8780 			    needrecov);
8781 			need_end_op = FALSE;
8782 			goto recov_retry;
8783 		}
8784 	}
8785 
8786 	if (!e.error) {
8787 		resp = &res;
8788 
8789 		/*
8790 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8791 		 * failed.
8792 		 */
8793 		if (res.status != NFS4_OK && res.array_len <= 2) {
8794 			e.error = geterrno4(res.status);
8795 			PURGE_ATTRCACHE4(dvp);
8796 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8797 			    &recov_state, needrecov);
8798 			need_end_op = FALSE;
8799 			nfs4_purge_stale_fh(e.error, dvp, cr);
8800 			/*
8801 			 * System V defines rmdir to return EEXIST, not
8802 			 * ENOTEMPTY if the directory is not empty.  Over
8803 			 * the wire, the error is NFSERR_ENOTEMPTY which
8804 			 * geterrno4 maps to ENOTEMPTY.
8805 			 */
8806 			if (e.error == ENOTEMPTY)
8807 				e.error = EEXIST;
8808 		} else {
8809 			resop = &res.array[1];	/* remove res */
8810 			rm_res = &resop->nfs_resop4_u.opremove;
8811 
8812 			if (res.status == NFS4_OK) {
8813 				resop = &res.array[2];	/* dir attrs */
8814 				dinfo.di_garp =
8815 				    &resop->nfs_resop4_u.opgetattr.ga_res;
8816 				dinfo.di_cred = cr;
8817 				dinfop = &dinfo;
8818 			} else
8819 				dinfop = NULL;
8820 
8821 			/* Update dir attribute, readdir and dnlc caches */
8822 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8823 			    dinfop);
8824 
8825 			/* destroy rddir cache for dir that was removed */
8826 			if (VTOR4(vp)->r_dir != NULL)
8827 				nfs4_purge_rddir_cache(vp);
8828 		}
8829 	}
8830 
8831 	if (need_end_op)
8832 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8833 
8834 	nfs_rw_exit(&drp->r_rwlock);
8835 
8836 	if (resp)
8837 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8838 
8839 	if (e.error == 0) {
8840 		vnode_t *tvp;
8841 		rnode4_t *trp;
8842 		trp = VTOR4(vp);
8843 		tvp = vp;
8844 		if (IS_SHADOW(vp, trp))
8845 			tvp = RTOV4(trp);
8846 		vnevent_rmdir(tvp, dvp, nm, ct);
8847 	}
8848 
8849 	VN_RELE(vp);
8850 
8851 	return (e.error);
8852 }
8853 
8854 /* ARGSUSED */
8855 static int
8856 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr,
8857     caller_context_t *ct, int flags)
8858 {
8859 	int error;
8860 	vnode_t *vp;
8861 	rnode4_t *rp;
8862 	char *contents;
8863 	mntinfo4_t *mi = VTOMI4(dvp);
8864 
8865 	if (nfs_zone() != mi->mi_zone)
8866 		return (EPERM);
8867 	if (!(mi->mi_flags & MI4_SYMLINK))
8868 		return (EOPNOTSUPP);
8869 
8870 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8871 	if (error)
8872 		return (error);
8873 
8874 	ASSERT(nfs4_consistent_type(vp));
8875 	rp = VTOR4(vp);
8876 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8877 
8878 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8879 
8880 		if (contents != NULL) {
8881 			mutex_enter(&rp->r_statelock);
8882 			if (rp->r_symlink.contents == NULL) {
8883 				rp->r_symlink.len = strlen(tnm);
8884 				bcopy(tnm, contents, rp->r_symlink.len);
8885 				rp->r_symlink.contents = contents;
8886 				rp->r_symlink.size = MAXPATHLEN;
8887 				mutex_exit(&rp->r_statelock);
8888 			} else {
8889 				mutex_exit(&rp->r_statelock);
8890 				kmem_free((void *)contents, MAXPATHLEN);
8891 			}
8892 		}
8893 	}
8894 	VN_RELE(vp);
8895 
8896 	return (error);
8897 }
8898 
8899 
8900 /*
8901  * Read directory entries.
8902  * There are some weird things to look out for here.  The uio_loffset
8903  * field is either 0 or it is the offset returned from a previous
8904  * readdir.  It is an opaque value used by the server to find the
8905  * correct directory block to read. The count field is the number
8906  * of blocks to read on the server.  This is advisory only, the server
8907  * may return only one block's worth of entries.  Entries may be compressed
8908  * on the server.
8909  */
8910 /* ARGSUSED */
8911 static int
8912 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp,
8913     caller_context_t *ct, int flags)
8914 {
8915 	int error;
8916 	uint_t count;
8917 	rnode4_t *rp;
8918 	rddir4_cache *rdc;
8919 	rddir4_cache *rrdc;
8920 
8921 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8922 		return (EIO);
8923 	rp = VTOR4(vp);
8924 
8925 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8926 
8927 	/*
8928 	 * Make sure that the directory cache is valid.
8929 	 */
8930 	if (rp->r_dir != NULL) {
8931 		if (nfs_disable_rddir_cache != 0) {
8932 			/*
8933 			 * Setting nfs_disable_rddir_cache in /etc/system
8934 			 * allows interoperability with servers that do not
8935 			 * properly update the attributes of directories.
8936 			 * Any cached information gets purged before an
8937 			 * access is made to it.
8938 			 */
8939 			nfs4_purge_rddir_cache(vp);
8940 		}
8941 
8942 		error = nfs4_validate_caches(vp, cr);
8943 		if (error)
8944 			return (error);
8945 	}
8946 
8947 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8948 
8949 	/*
8950 	 * Short circuit last readdir which always returns 0 bytes.
8951 	 * This can be done after the directory has been read through
8952 	 * completely at least once.  This will set r_direof which
8953 	 * can be used to find the value of the last cookie.
8954 	 */
8955 	mutex_enter(&rp->r_statelock);
8956 	if (rp->r_direof != NULL &&
8957 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8958 		mutex_exit(&rp->r_statelock);
8959 #ifdef DEBUG
8960 		nfs4_readdir_cache_shorts++;
8961 #endif
8962 		if (eofp)
8963 			*eofp = 1;
8964 		return (0);
8965 	}
8966 
8967 	/*
8968 	 * Look for a cache entry.  Cache entries are identified
8969 	 * by the NFS cookie value and the byte count requested.
8970 	 */
8971 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8972 
8973 	/*
8974 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8975 	 */
8976 	if (rdc == NULL) {
8977 		mutex_exit(&rp->r_statelock);
8978 		return (EINTR);
8979 	}
8980 
8981 	/*
8982 	 * Check to see if we need to fill this entry in.
8983 	 */
8984 	if (rdc->flags & RDDIRREQ) {
8985 		rdc->flags &= ~RDDIRREQ;
8986 		rdc->flags |= RDDIR;
8987 		mutex_exit(&rp->r_statelock);
8988 
8989 		/*
8990 		 * Do the readdir.
8991 		 */
8992 		nfs4readdir(vp, rdc, cr);
8993 
8994 		/*
8995 		 * Reacquire the lock, so that we can continue
8996 		 */
8997 		mutex_enter(&rp->r_statelock);
8998 		/*
8999 		 * The entry is now complete
9000 		 */
9001 		rdc->flags &= ~RDDIR;
9002 	}
9003 
9004 	ASSERT(!(rdc->flags & RDDIR));
9005 
9006 	/*
9007 	 * If an error occurred while attempting
9008 	 * to fill the cache entry, mark the entry invalid and
9009 	 * just return the error.
9010 	 */
9011 	if (rdc->error) {
9012 		error = rdc->error;
9013 		rdc->flags |= RDDIRREQ;
9014 		rddir4_cache_rele(rp, rdc);
9015 		mutex_exit(&rp->r_statelock);
9016 		return (error);
9017 	}
9018 
9019 	/*
9020 	 * The cache entry is complete and good,
9021 	 * copyout the dirent structs to the calling
9022 	 * thread.
9023 	 */
9024 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
9025 
9026 	/*
9027 	 * If no error occurred during the copyout,
9028 	 * update the offset in the uio struct to
9029 	 * contain the value of the next NFS 4 cookie
9030 	 * and set the eof value appropriately.
9031 	 */
9032 	if (!error) {
9033 		uiop->uio_loffset = rdc->nfs4_ncookie;
9034 		if (eofp)
9035 			*eofp = rdc->eof;
9036 	}
9037 
9038 	/*
9039 	 * Decide whether to do readahead.  Don't if we
9040 	 * have already read to the end of directory.
9041 	 */
9042 	if (rdc->eof) {
9043 		/*
9044 		 * Make the entry the direof only if it is cached
9045 		 */
9046 		if (rdc->flags & RDDIRCACHED)
9047 			rp->r_direof = rdc;
9048 		rddir4_cache_rele(rp, rdc);
9049 		mutex_exit(&rp->r_statelock);
9050 		return (error);
9051 	}
9052 
9053 	/* Determine if a readdir readahead should be done */
9054 	if (!(rp->r_flags & R4LOOKUP)) {
9055 		rddir4_cache_rele(rp, rdc);
9056 		mutex_exit(&rp->r_statelock);
9057 		return (error);
9058 	}
9059 
9060 	/*
9061 	 * Now look for a readahead entry.
9062 	 *
9063 	 * Check to see whether we found an entry for the readahead.
9064 	 * If so, we don't need to do anything further, so free the new
9065 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
9066 	 * it to the cache, and then initiate an asynchronous readdir
9067 	 * operation to fill it.
9068 	 */
9069 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
9070 
9071 	/*
9072 	 * A readdir cache entry could not be obtained for the readahead.  In
9073 	 * this case we skip the readahead and return.
9074 	 */
9075 	if (rrdc == NULL) {
9076 		rddir4_cache_rele(rp, rdc);
9077 		mutex_exit(&rp->r_statelock);
9078 		return (error);
9079 	}
9080 
9081 	/*
9082 	 * Check to see if we need to fill this entry in.
9083 	 */
9084 	if (rrdc->flags & RDDIRREQ) {
9085 		rrdc->flags &= ~RDDIRREQ;
9086 		rrdc->flags |= RDDIR;
9087 		rddir4_cache_rele(rp, rdc);
9088 		mutex_exit(&rp->r_statelock);
9089 #ifdef DEBUG
9090 		nfs4_readdir_readahead++;
9091 #endif
9092 		/*
9093 		 * Do the readdir.
9094 		 */
9095 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
9096 		return (error);
9097 	}
9098 
9099 	rddir4_cache_rele(rp, rrdc);
9100 	rddir4_cache_rele(rp, rdc);
9101 	mutex_exit(&rp->r_statelock);
9102 	return (error);
9103 }
9104 
9105 static int
9106 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9107 {
9108 	int error;
9109 	rnode4_t *rp;
9110 
9111 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9112 
9113 	rp = VTOR4(vp);
9114 
9115 	/*
9116 	 * Obtain the readdir results for the caller.
9117 	 */
9118 	nfs4readdir(vp, rdc, cr);
9119 
9120 	mutex_enter(&rp->r_statelock);
9121 	/*
9122 	 * The entry is now complete
9123 	 */
9124 	rdc->flags &= ~RDDIR;
9125 
9126 	error = rdc->error;
9127 	if (error)
9128 		rdc->flags |= RDDIRREQ;
9129 	rddir4_cache_rele(rp, rdc);
9130 	mutex_exit(&rp->r_statelock);
9131 
9132 	return (error);
9133 }
9134 
9135 /*
9136  * Read directory entries.
9137  * There are some weird things to look out for here.  The uio_loffset
9138  * field is either 0 or it is the offset returned from a previous
9139  * readdir.  It is an opaque value used by the server to find the
9140  * correct directory block to read. The count field is the number
9141  * of blocks to read on the server.  This is advisory only, the server
9142  * may return only one block's worth of entries.  Entries may be compressed
9143  * on the server.
9144  *
9145  * Generates the following compound request:
9146  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9147  *    must include a Lookupp as well. In this case, send:
9148  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9149  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9150  *
9151  * Get complete attributes and filehandles for entries if this is the
9152  * first read of the directory. Otherwise, just get fileid's.
9153  */
9154 static void
9155 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9156 {
9157 	COMPOUND4args_clnt args;
9158 	COMPOUND4res_clnt res;
9159 	READDIR4args *rargs;
9160 	READDIR4res_clnt *rd_res;
9161 	bitmap4 rd_bitsval;
9162 	nfs_argop4 argop[5];
9163 	nfs_resop4 *resop;
9164 	rnode4_t *rp = VTOR4(vp);
9165 	mntinfo4_t *mi = VTOMI4(vp);
9166 	int doqueue;
9167 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9168 	vnode_t *dvp;
9169 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9170 	int num_ops, res_opcnt;
9171 	bool_t needrecov = FALSE;
9172 	nfs4_recov_state_t recov_state;
9173 	hrtime_t t;
9174 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9175 
9176 	ASSERT(nfs_zone() == mi->mi_zone);
9177 	ASSERT(rdc->flags & RDDIR);
9178 	ASSERT(rdc->entries == NULL);
9179 
9180 	/*
9181 	 * If rp were a stub, it should have triggered and caused
9182 	 * a mount for us to get this far.
9183 	 */
9184 	ASSERT(!RP_ISSTUB(rp));
9185 
9186 	num_ops = 2;
9187 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9188 		/*
9189 		 * Since nfsv4 readdir may not return entries for "." and "..",
9190 		 * the client must recreate them:
9191 		 * To find the correct nodeid, do the following:
9192 		 * For current node, get nodeid from dnlc.
9193 		 * - if current node is rootvp, set pnodeid to nodeid.
9194 		 * - else if parent is in the dnlc, get its nodeid from there.
9195 		 * - else add LOOKUPP+GETATTR to compound.
9196 		 */
9197 		nodeid = rp->r_attr.va_nodeid;
9198 		if (vp->v_flag & VROOT) {
9199 			pnodeid = nodeid;	/* root of mount point */
9200 		} else {
9201 			dvp = dnlc_lookup(vp, "..");
9202 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9203 				/* parent in dnlc cache - no need for otw */
9204 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9205 			} else {
9206 				/*
9207 				 * parent not in dnlc cache,
9208 				 * do lookupp to get its id
9209 				 */
9210 				num_ops = 5;
9211 				pnodeid = 0; /* set later by getattr parent */
9212 			}
9213 			if (dvp)
9214 				VN_RELE(dvp);
9215 		}
9216 	}
9217 	recov_state.rs_flags = 0;
9218 	recov_state.rs_num_retry_despite_err = 0;
9219 
9220 	/* Save the original mount point security flavor */
9221 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9222 
9223 recov_retry:
9224 	args.ctag = TAG_READDIR;
9225 
9226 	args.array = argop;
9227 	args.array_len = num_ops;
9228 
9229 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9230 	    &recov_state, NULL)) {
9231 		/*
9232 		 * If readdir a node that is a stub for a crossed mount point,
9233 		 * keep the original secinfo flavor for the current file
9234 		 * system, not the crossed one.
9235 		 */
9236 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9237 		rdc->error = e.error;
9238 		return;
9239 	}
9240 
9241 	/*
9242 	 * Determine which attrs to request for dirents.  This code
9243 	 * must be protected by nfs4_start/end_fop because of r_server
9244 	 * (which will change during failover recovery).
9245 	 *
9246 	 */
9247 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9248 		/*
9249 		 * Get all vattr attrs plus filehandle and rdattr_error
9250 		 */
9251 		rd_bitsval = NFS4_VATTR_MASK |
9252 		    FATTR4_RDATTR_ERROR_MASK |
9253 		    FATTR4_FILEHANDLE_MASK;
9254 
9255 		if (rp->r_flags & R4READDIRWATTR) {
9256 			mutex_enter(&rp->r_statelock);
9257 			rp->r_flags &= ~R4READDIRWATTR;
9258 			mutex_exit(&rp->r_statelock);
9259 		}
9260 	} else {
9261 		servinfo4_t *svp = rp->r_server;
9262 
9263 		/*
9264 		 * Already read directory. Use readdir with
9265 		 * no attrs (except for mounted_on_fileid) for updates.
9266 		 */
9267 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9268 
9269 		/*
9270 		 * request mounted on fileid if supported, else request
9271 		 * fileid.  maybe we should verify that fileid is supported
9272 		 * and request something else if not.
9273 		 */
9274 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9275 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9276 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9277 		nfs_rw_exit(&svp->sv_lock);
9278 	}
9279 
9280 	/* putfh directory fh */
9281 	argop[0].argop = OP_CPUTFH;
9282 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9283 
9284 	argop[1].argop = OP_READDIR;
9285 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9286 	/*
9287 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9288 	 * cookie 0 should be used over-the-wire to start reading at
9289 	 * the beginning of the directory excluding "." and "..".
9290 	 */
9291 	if (rdc->nfs4_cookie == 0 ||
9292 	    rdc->nfs4_cookie == 1 ||
9293 	    rdc->nfs4_cookie == 2) {
9294 		rargs->cookie = (nfs_cookie4)0;
9295 		rargs->cookieverf = 0;
9296 	} else {
9297 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9298 		mutex_enter(&rp->r_statelock);
9299 		rargs->cookieverf = rp->r_cookieverf4;
9300 		mutex_exit(&rp->r_statelock);
9301 	}
9302 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9303 	rargs->maxcount = mi->mi_tsize;
9304 	rargs->attr_request = rd_bitsval;
9305 	rargs->rdc = rdc;
9306 	rargs->dvp = vp;
9307 	rargs->mi = mi;
9308 	rargs->cr = cr;
9309 
9310 
9311 	/*
9312 	 * If count < than the minimum required, we return no entries
9313 	 * and fail with EINVAL
9314 	 */
9315 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9316 		rdc->error = EINVAL;
9317 		goto out;
9318 	}
9319 
9320 	if (args.array_len == 5) {
9321 		/*
9322 		 * Add lookupp and getattr for parent nodeid.
9323 		 */
9324 		argop[2].argop = OP_LOOKUPP;
9325 
9326 		argop[3].argop = OP_GETFH;
9327 
9328 		/* getattr parent */
9329 		argop[4].argop = OP_GETATTR;
9330 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9331 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9332 	}
9333 
9334 	doqueue = 1;
9335 
9336 	if (mi->mi_io_kstats) {
9337 		mutex_enter(&mi->mi_lock);
9338 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9339 		mutex_exit(&mi->mi_lock);
9340 	}
9341 
9342 	/* capture the time of this call */
9343 	rargs->t = t = gethrtime();
9344 
9345 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9346 
9347 	if (mi->mi_io_kstats) {
9348 		mutex_enter(&mi->mi_lock);
9349 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9350 		mutex_exit(&mi->mi_lock);
9351 	}
9352 
9353 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9354 
9355 	/*
9356 	 * If RPC error occurred and it isn't an error that
9357 	 * triggers recovery, then go ahead and fail now.
9358 	 */
9359 	if (e.error != 0 && !needrecov) {
9360 		rdc->error = e.error;
9361 		goto out;
9362 	}
9363 
9364 	if (needrecov) {
9365 		bool_t abort;
9366 
9367 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9368 		    "nfs4readdir: initiating recovery.\n"));
9369 
9370 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9371 		    NULL, OP_READDIR, NULL, NULL, NULL);
9372 		if (abort == FALSE) {
9373 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9374 			    &recov_state, needrecov);
9375 			if (!e.error)
9376 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9377 			if (rdc->entries != NULL) {
9378 				kmem_free(rdc->entries, rdc->entlen);
9379 				rdc->entries = NULL;
9380 			}
9381 			goto recov_retry;
9382 		}
9383 
9384 		if (e.error != 0) {
9385 			rdc->error = e.error;
9386 			goto out;
9387 		}
9388 
9389 		/* fall through for res.status case */
9390 	}
9391 
9392 	res_opcnt = res.array_len;
9393 
9394 	/*
9395 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9396 	 * failure here.  Subsequent ops are for filling out dot-dot
9397 	 * dirent, and if they fail, we still want to give the caller
9398 	 * the dirents returned by (the successful) READDIR op, so we need
9399 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9400 	 *
9401 	 * One example where PUTFH+READDIR ops would succeed but
9402 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9403 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9404 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9405 	 * x perm.  We need to come up with a non-vendor-specific way
9406 	 * for a POSIX server to return d_ino from dotdot's dirent if
9407 	 * client only requests mounted_on_fileid, and just say the
9408 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9409 	 * client requested any mandatory attrs, server would be required
9410 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9411 	 * for dotdot.
9412 	 */
9413 
9414 	if (res.status) {
9415 		if (res_opcnt <= 2) {
9416 			e.error = geterrno4(res.status);
9417 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9418 			    &recov_state, needrecov);
9419 			nfs4_purge_stale_fh(e.error, vp, cr);
9420 			rdc->error = e.error;
9421 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9422 			if (rdc->entries != NULL) {
9423 				kmem_free(rdc->entries, rdc->entlen);
9424 				rdc->entries = NULL;
9425 			}
9426 			/*
9427 			 * If readdir a node that is a stub for a
9428 			 * crossed mount point, keep the original
9429 			 * secinfo flavor for the current file system,
9430 			 * not the crossed one.
9431 			 */
9432 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9433 			return;
9434 		}
9435 	}
9436 
9437 	resop = &res.array[1];	/* readdir res */
9438 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9439 
9440 	mutex_enter(&rp->r_statelock);
9441 	rp->r_cookieverf4 = rd_res->cookieverf;
9442 	mutex_exit(&rp->r_statelock);
9443 
9444 	/*
9445 	 * For "." and ".." entries
9446 	 * e.g.
9447 	 *	seek(cookie=0) -> "." entry with d_off = 1
9448 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9449 	 */
9450 	if (cookie == (nfs_cookie4) 0) {
9451 		if (rd_res->dotp)
9452 			rd_res->dotp->d_ino = nodeid;
9453 		if (rd_res->dotdotp)
9454 			rd_res->dotdotp->d_ino = pnodeid;
9455 	}
9456 	if (cookie == (nfs_cookie4) 1) {
9457 		if (rd_res->dotdotp)
9458 			rd_res->dotdotp->d_ino = pnodeid;
9459 	}
9460 
9461 
9462 	/* LOOKUPP+GETATTR attemped */
9463 	if (args.array_len == 5 && rd_res->dotdotp) {
9464 		if (res.status == NFS4_OK && res_opcnt == 5) {
9465 			nfs_fh4 *fhp;
9466 			nfs4_sharedfh_t *sfhp;
9467 			vnode_t *pvp;
9468 			nfs4_ga_res_t *garp;
9469 
9470 			resop++;	/* lookupp */
9471 			resop++;	/* getfh   */
9472 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9473 
9474 			resop++;	/* getattr of parent */
9475 
9476 			/*
9477 			 * First, take care of finishing the
9478 			 * readdir results.
9479 			 */
9480 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9481 			/*
9482 			 * The d_ino of .. must be the inode number
9483 			 * of the mounted filesystem.
9484 			 */
9485 			if (garp->n4g_va.va_mask & AT_NODEID)
9486 				rd_res->dotdotp->d_ino =
9487 				    garp->n4g_va.va_nodeid;
9488 
9489 
9490 			/*
9491 			 * Next, create the ".." dnlc entry
9492 			 */
9493 			sfhp = sfh4_get(fhp, mi);
9494 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9495 				dnlc_update(vp, "..", pvp);
9496 				VN_RELE(pvp);
9497 			}
9498 			sfh4_rele(&sfhp);
9499 		}
9500 	}
9501 
9502 	if (mi->mi_io_kstats) {
9503 		mutex_enter(&mi->mi_lock);
9504 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9505 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9506 		mutex_exit(&mi->mi_lock);
9507 	}
9508 
9509 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9510 
9511 out:
9512 	/*
9513 	 * If readdir a node that is a stub for a crossed mount point,
9514 	 * keep the original secinfo flavor for the current file system,
9515 	 * not the crossed one.
9516 	 */
9517 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9518 
9519 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9520 }
9521 
9522 
9523 static int
9524 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9525 {
9526 	rnode4_t *rp = VTOR4(bp->b_vp);
9527 	int count;
9528 	int error;
9529 	cred_t *cred_otw = NULL;
9530 	offset_t offset;
9531 	nfs4_open_stream_t *osp = NULL;
9532 	bool_t first_time = TRUE;	/* first time getting otw cred */
9533 	bool_t last_time = FALSE;	/* last time getting otw cred */
9534 
9535 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9536 
9537 	DTRACE_IO1(start, struct buf *, bp);
9538 	offset = ldbtob(bp->b_lblkno);
9539 
9540 	if (bp->b_flags & B_READ) {
9541 	read_again:
9542 		/*
9543 		 * Releases the osp, if it is provided.
9544 		 * Puts a hold on the cred_otw and the new osp (if found).
9545 		 */
9546 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9547 		    &first_time, &last_time);
9548 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9549 		    offset, bp->b_bcount, &bp->b_resid, cred_otw,
9550 		    readahead, NULL);
9551 		crfree(cred_otw);
9552 		if (!error) {
9553 			if (bp->b_resid) {
9554 				/*
9555 				 * Didn't get it all because we hit EOF,
9556 				 * zero all the memory beyond the EOF.
9557 				 */
9558 				/* bzero(rdaddr + */
9559 				bzero(bp->b_un.b_addr +
9560 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9561 			}
9562 			mutex_enter(&rp->r_statelock);
9563 			if (bp->b_resid == bp->b_bcount &&
9564 			    offset >= rp->r_size) {
9565 				/*
9566 				 * We didn't read anything at all as we are
9567 				 * past EOF.  Return an error indicator back
9568 				 * but don't destroy the pages (yet).
9569 				 */
9570 				error = NFS_EOF;
9571 			}
9572 			mutex_exit(&rp->r_statelock);
9573 		} else if (error == EACCES && last_time == FALSE) {
9574 				goto read_again;
9575 		}
9576 	} else {
9577 		if (!(rp->r_flags & R4STALE)) {
9578 write_again:
9579 			/*
9580 			 * Releases the osp, if it is provided.
9581 			 * Puts a hold on the cred_otw and the new
9582 			 * osp (if found).
9583 			 */
9584 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9585 			    &first_time, &last_time);
9586 			mutex_enter(&rp->r_statelock);
9587 			count = MIN(bp->b_bcount, rp->r_size - offset);
9588 			mutex_exit(&rp->r_statelock);
9589 			if (count < 0)
9590 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9591 #ifdef DEBUG
9592 			if (count == 0) {
9593 				zoneid_t zoneid = getzoneid();
9594 
9595 				zcmn_err(zoneid, CE_WARN,
9596 				    "nfs4_bio: zero length write at %lld",
9597 				    offset);
9598 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9599 				    "b_bcount=%ld, file size=%lld",
9600 				    rp->r_flags, (long)bp->b_bcount,
9601 				    rp->r_size);
9602 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9603 				if (nfs4_bio_do_stop)
9604 					debug_enter("nfs4_bio");
9605 			}
9606 #endif
9607 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9608 			    count, cred_otw, stab_comm);
9609 			if (error == EACCES && last_time == FALSE) {
9610 				crfree(cred_otw);
9611 				goto write_again;
9612 			}
9613 			bp->b_error = error;
9614 			if (error && error != EINTR &&
9615 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9616 				/*
9617 				 * Don't print EDQUOT errors on the console.
9618 				 * Don't print asynchronous EACCES errors.
9619 				 * Don't print EFBIG errors.
9620 				 * Print all other write errors.
9621 				 */
9622 				if (error != EDQUOT && error != EFBIG &&
9623 				    (error != EACCES ||
9624 				    !(bp->b_flags & B_ASYNC)))
9625 					nfs4_write_error(bp->b_vp,
9626 					    error, cred_otw);
9627 				/*
9628 				 * Update r_error and r_flags as appropriate.
9629 				 * If the error was ESTALE, then mark the
9630 				 * rnode as not being writeable and save
9631 				 * the error status.  Otherwise, save any
9632 				 * errors which occur from asynchronous
9633 				 * page invalidations.  Any errors occurring
9634 				 * from other operations should be saved
9635 				 * by the caller.
9636 				 */
9637 				mutex_enter(&rp->r_statelock);
9638 				if (error == ESTALE) {
9639 					rp->r_flags |= R4STALE;
9640 					if (!rp->r_error)
9641 						rp->r_error = error;
9642 				} else if (!rp->r_error &&
9643 				    (bp->b_flags &
9644 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9645 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9646 					rp->r_error = error;
9647 				}
9648 				mutex_exit(&rp->r_statelock);
9649 			}
9650 			crfree(cred_otw);
9651 		} else {
9652 			error = rp->r_error;
9653 			/*
9654 			 * A close may have cleared r_error, if so,
9655 			 * propagate ESTALE error return properly
9656 			 */
9657 			if (error == 0)
9658 				error = ESTALE;
9659 		}
9660 	}
9661 
9662 	if (error != 0 && error != NFS_EOF)
9663 		bp->b_flags |= B_ERROR;
9664 
9665 	if (osp)
9666 		open_stream_rele(osp, rp);
9667 
9668 	DTRACE_IO1(done, struct buf *, bp);
9669 
9670 	return (error);
9671 }
9672 
9673 /* ARGSUSED */
9674 int
9675 nfs4_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
9676 {
9677 	return (EREMOTE);
9678 }
9679 
9680 /* ARGSUSED2 */
9681 int
9682 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9683 {
9684 	rnode4_t *rp = VTOR4(vp);
9685 
9686 	if (!write_lock) {
9687 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9688 		return (V_WRITELOCK_FALSE);
9689 	}
9690 
9691 	if ((rp->r_flags & R4DIRECTIO) ||
9692 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9693 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9694 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9695 			return (V_WRITELOCK_FALSE);
9696 		nfs_rw_exit(&rp->r_rwlock);
9697 	}
9698 
9699 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9700 	return (V_WRITELOCK_TRUE);
9701 }
9702 
9703 /* ARGSUSED */
9704 void
9705 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9706 {
9707 	rnode4_t *rp = VTOR4(vp);
9708 
9709 	nfs_rw_exit(&rp->r_rwlock);
9710 }
9711 
9712 /* ARGSUSED */
9713 static int
9714 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp, caller_context_t *ct)
9715 {
9716 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9717 		return (EIO);
9718 
9719 	/*
9720 	 * Because we stuff the readdir cookie into the offset field
9721 	 * someone may attempt to do an lseek with the cookie which
9722 	 * we want to succeed.
9723 	 */
9724 	if (vp->v_type == VDIR)
9725 		return (0);
9726 	if (*noffp < 0)
9727 		return (EINVAL);
9728 	return (0);
9729 }
9730 
9731 
9732 /*
9733  * Return all the pages from [off..off+len) in file
9734  */
9735 /* ARGSUSED */
9736 static int
9737 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9738     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9739     enum seg_rw rw, cred_t *cr, caller_context_t *ct)
9740 {
9741 	rnode4_t *rp;
9742 	int error;
9743 	mntinfo4_t *mi;
9744 
9745 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9746 		return (EIO);
9747 	rp = VTOR4(vp);
9748 	if (IS_SHADOW(vp, rp))
9749 		vp = RTOV4(rp);
9750 
9751 	if (vp->v_flag & VNOMAP)
9752 		return (ENOSYS);
9753 
9754 	if (protp != NULL)
9755 		*protp = PROT_ALL;
9756 
9757 	/*
9758 	 * Now validate that the caches are up to date.
9759 	 */
9760 	if (error = nfs4_validate_caches(vp, cr))
9761 		return (error);
9762 
9763 	mi = VTOMI4(vp);
9764 retry:
9765 	mutex_enter(&rp->r_statelock);
9766 
9767 	/*
9768 	 * Don't create dirty pages faster than they
9769 	 * can be cleaned so that the system doesn't
9770 	 * get imbalanced.  If the async queue is
9771 	 * maxed out, then wait for it to drain before
9772 	 * creating more dirty pages.  Also, wait for
9773 	 * any threads doing pagewalks in the vop_getattr
9774 	 * entry points so that they don't block for
9775 	 * long periods.
9776 	 */
9777 	if (rw == S_CREATE) {
9778 		while ((mi->mi_max_threads != 0 &&
9779 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
9780 		    rp->r_gcount > 0)
9781 			cv_wait(&rp->r_cv, &rp->r_statelock);
9782 	}
9783 
9784 	/*
9785 	 * If we are getting called as a side effect of an nfs_write()
9786 	 * operation the local file size might not be extended yet.
9787 	 * In this case we want to be able to return pages of zeroes.
9788 	 */
9789 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9790 		NFS4_DEBUG(nfs4_pageio_debug,
9791 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9792 		    "len=%llu, size=%llu, attrsize =%llu", off,
9793 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9794 		mutex_exit(&rp->r_statelock);
9795 		return (EFAULT);		/* beyond EOF */
9796 	}
9797 
9798 	mutex_exit(&rp->r_statelock);
9799 
9800 	error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9801 	    pl, plsz, seg, addr, rw, cr);
9802 	NFS4_DEBUG(nfs4_pageio_debug && error,
9803 	    (CE_NOTE, "getpages error %d; off=%lld, len=%lld",
9804 	    error, off, (u_longlong_t)len));
9805 
9806 	switch (error) {
9807 	case NFS_EOF:
9808 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9809 		goto retry;
9810 	case ESTALE:
9811 		nfs4_purge_stale_fh(error, vp, cr);
9812 	}
9813 
9814 	return (error);
9815 }
9816 
9817 /*
9818  * Called from pvn_getpages to get a particular page.
9819  */
9820 /* ARGSUSED */
9821 static int
9822 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9823     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9824     enum seg_rw rw, cred_t *cr)
9825 {
9826 	rnode4_t *rp;
9827 	uint_t bsize;
9828 	struct buf *bp;
9829 	page_t *pp;
9830 	u_offset_t lbn;
9831 	u_offset_t io_off;
9832 	u_offset_t blkoff;
9833 	u_offset_t rablkoff;
9834 	size_t io_len;
9835 	uint_t blksize;
9836 	int error;
9837 	int readahead;
9838 	int readahead_issued = 0;
9839 	int ra_window; /* readahead window */
9840 	page_t *pagefound;
9841 	page_t *savepp;
9842 
9843 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9844 		return (EIO);
9845 
9846 	rp = VTOR4(vp);
9847 	ASSERT(!IS_SHADOW(vp, rp));
9848 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9849 
9850 reread:
9851 	bp = NULL;
9852 	pp = NULL;
9853 	pagefound = NULL;
9854 
9855 	if (pl != NULL)
9856 		pl[0] = NULL;
9857 
9858 	error = 0;
9859 	lbn = off / bsize;
9860 	blkoff = lbn * bsize;
9861 
9862 	/*
9863 	 * Queueing up the readahead before doing the synchronous read
9864 	 * results in a significant increase in read throughput because
9865 	 * of the increased parallelism between the async threads and
9866 	 * the process context.
9867 	 */
9868 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9869 	    rw != S_CREATE &&
9870 	    !(vp->v_flag & VNOCACHE)) {
9871 		mutex_enter(&rp->r_statelock);
9872 
9873 		/*
9874 		 * Calculate the number of readaheads to do.
9875 		 * a) No readaheads at offset = 0.
9876 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9877 		 *    window is closed.
9878 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9879 		 *    upon how far the readahead window is open or close.
9880 		 * d) No readaheads if rp->r_nextr is not within the scope
9881 		 *    of the readahead window (random i/o).
9882 		 */
9883 
9884 		if (off == 0)
9885 			readahead = 0;
9886 		else if (blkoff == rp->r_nextr)
9887 			readahead = nfs4_nra;
9888 		else if (rp->r_nextr > blkoff &&
9889 		    ((ra_window = (rp->r_nextr - blkoff) / bsize)
9890 		    <= (nfs4_nra - 1)))
9891 			readahead = nfs4_nra - ra_window;
9892 		else
9893 			readahead = 0;
9894 
9895 		rablkoff = rp->r_nextr;
9896 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9897 			mutex_exit(&rp->r_statelock);
9898 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9899 			    addr + (rablkoff + bsize - off),
9900 			    seg, cr, nfs4_readahead) < 0) {
9901 				mutex_enter(&rp->r_statelock);
9902 				break;
9903 			}
9904 			readahead--;
9905 			rablkoff += bsize;
9906 			/*
9907 			 * Indicate that we did a readahead so
9908 			 * readahead offset is not updated
9909 			 * by the synchronous read below.
9910 			 */
9911 			readahead_issued = 1;
9912 			mutex_enter(&rp->r_statelock);
9913 			/*
9914 			 * set readahead offset to
9915 			 * offset of last async readahead
9916 			 * request.
9917 			 */
9918 			rp->r_nextr = rablkoff;
9919 		}
9920 		mutex_exit(&rp->r_statelock);
9921 	}
9922 
9923 again:
9924 	if ((pagefound = page_exists(vp, off)) == NULL) {
9925 		if (pl == NULL) {
9926 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9927 			    nfs4_readahead);
9928 		} else if (rw == S_CREATE) {
9929 			/*
9930 			 * Block for this page is not allocated, or the offset
9931 			 * is beyond the current allocation size, or we're
9932 			 * allocating a swap slot and the page was not found,
9933 			 * so allocate it and return a zero page.
9934 			 */
9935 			if ((pp = page_create_va(vp, off,
9936 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9937 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9938 			io_len = PAGESIZE;
9939 			mutex_enter(&rp->r_statelock);
9940 			rp->r_nextr = off + PAGESIZE;
9941 			mutex_exit(&rp->r_statelock);
9942 		} else {
9943 			/*
9944 			 * Need to go to server to get a block
9945 			 */
9946 			mutex_enter(&rp->r_statelock);
9947 			if (blkoff < rp->r_size &&
9948 			    blkoff + bsize > rp->r_size) {
9949 				/*
9950 				 * If less than a block left in
9951 				 * file read less than a block.
9952 				 */
9953 				if (rp->r_size <= off) {
9954 					/*
9955 					 * Trying to access beyond EOF,
9956 					 * set up to get at least one page.
9957 					 */
9958 					blksize = off + PAGESIZE - blkoff;
9959 				} else
9960 					blksize = rp->r_size - blkoff;
9961 			} else if ((off == 0) ||
9962 			    (off != rp->r_nextr && !readahead_issued)) {
9963 				blksize = PAGESIZE;
9964 				blkoff = off; /* block = page here */
9965 			} else
9966 				blksize = bsize;
9967 			mutex_exit(&rp->r_statelock);
9968 
9969 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9970 			    &io_len, blkoff, blksize, 0);
9971 
9972 			/*
9973 			 * Some other thread has entered the page,
9974 			 * so just use it.
9975 			 */
9976 			if (pp == NULL)
9977 				goto again;
9978 
9979 			/*
9980 			 * Now round the request size up to page boundaries.
9981 			 * This ensures that the entire page will be
9982 			 * initialized to zeroes if EOF is encountered.
9983 			 */
9984 			io_len = ptob(btopr(io_len));
9985 
9986 			bp = pageio_setup(pp, io_len, vp, B_READ);
9987 			ASSERT(bp != NULL);
9988 
9989 			/*
9990 			 * pageio_setup should have set b_addr to 0.  This
9991 			 * is correct since we want to do I/O on a page
9992 			 * boundary.  bp_mapin will use this addr to calculate
9993 			 * an offset, and then set b_addr to the kernel virtual
9994 			 * address it allocated for us.
9995 			 */
9996 			ASSERT(bp->b_un.b_addr == 0);
9997 
9998 			bp->b_edev = 0;
9999 			bp->b_dev = 0;
10000 			bp->b_lblkno = lbtodb(io_off);
10001 			bp->b_file = vp;
10002 			bp->b_offset = (offset_t)off;
10003 			bp_mapin(bp);
10004 
10005 			/*
10006 			 * If doing a write beyond what we believe is EOF,
10007 			 * don't bother trying to read the pages from the
10008 			 * server, we'll just zero the pages here.  We
10009 			 * don't check that the rw flag is S_WRITE here
10010 			 * because some implementations may attempt a
10011 			 * read access to the buffer before copying data.
10012 			 */
10013 			mutex_enter(&rp->r_statelock);
10014 			if (io_off >= rp->r_size && seg == segkmap) {
10015 				mutex_exit(&rp->r_statelock);
10016 				bzero(bp->b_un.b_addr, io_len);
10017 			} else {
10018 				mutex_exit(&rp->r_statelock);
10019 				error = nfs4_bio(bp, NULL, cr, FALSE);
10020 			}
10021 
10022 			/*
10023 			 * Unmap the buffer before freeing it.
10024 			 */
10025 			bp_mapout(bp);
10026 			pageio_done(bp);
10027 
10028 			savepp = pp;
10029 			do {
10030 				pp->p_fsdata = C_NOCOMMIT;
10031 			} while ((pp = pp->p_next) != savepp);
10032 
10033 			if (error == NFS_EOF) {
10034 				/*
10035 				 * If doing a write system call just return
10036 				 * zeroed pages, else user tried to get pages
10037 				 * beyond EOF, return error.  We don't check
10038 				 * that the rw flag is S_WRITE here because
10039 				 * some implementations may attempt a read
10040 				 * access to the buffer before copying data.
10041 				 */
10042 				if (seg == segkmap)
10043 					error = 0;
10044 				else
10045 					error = EFAULT;
10046 			}
10047 
10048 			if (!readahead_issued && !error) {
10049 				mutex_enter(&rp->r_statelock);
10050 				rp->r_nextr = io_off + io_len;
10051 				mutex_exit(&rp->r_statelock);
10052 			}
10053 		}
10054 	}
10055 
10056 out:
10057 	if (pl == NULL)
10058 		return (error);
10059 
10060 	if (error) {
10061 		if (pp != NULL)
10062 			pvn_read_done(pp, B_ERROR);
10063 		return (error);
10064 	}
10065 
10066 	if (pagefound) {
10067 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
10068 
10069 		/*
10070 		 * Page exists in the cache, acquire the appropriate lock.
10071 		 * If this fails, start all over again.
10072 		 */
10073 		if ((pp = page_lookup(vp, off, se)) == NULL) {
10074 #ifdef DEBUG
10075 			nfs4_lostpage++;
10076 #endif
10077 			goto reread;
10078 		}
10079 		pl[0] = pp;
10080 		pl[1] = NULL;
10081 		return (0);
10082 	}
10083 
10084 	if (pp != NULL)
10085 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
10086 
10087 	return (error);
10088 }
10089 
10090 static void
10091 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
10092     cred_t *cr)
10093 {
10094 	int error;
10095 	page_t *pp;
10096 	u_offset_t io_off;
10097 	size_t io_len;
10098 	struct buf *bp;
10099 	uint_t bsize, blksize;
10100 	rnode4_t *rp = VTOR4(vp);
10101 	page_t *savepp;
10102 
10103 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10104 
10105 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10106 
10107 	mutex_enter(&rp->r_statelock);
10108 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
10109 		/*
10110 		 * If less than a block left in file read less
10111 		 * than a block.
10112 		 */
10113 		blksize = rp->r_size - blkoff;
10114 	} else
10115 		blksize = bsize;
10116 	mutex_exit(&rp->r_statelock);
10117 
10118 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
10119 	    &io_off, &io_len, blkoff, blksize, 1);
10120 	/*
10121 	 * The isra flag passed to the kluster function is 1, we may have
10122 	 * gotten a return value of NULL for a variety of reasons (# of free
10123 	 * pages < minfree, someone entered the page on the vnode etc). In all
10124 	 * cases, we want to punt on the readahead.
10125 	 */
10126 	if (pp == NULL)
10127 		return;
10128 
10129 	/*
10130 	 * Now round the request size up to page boundaries.
10131 	 * This ensures that the entire page will be
10132 	 * initialized to zeroes if EOF is encountered.
10133 	 */
10134 	io_len = ptob(btopr(io_len));
10135 
10136 	bp = pageio_setup(pp, io_len, vp, B_READ);
10137 	ASSERT(bp != NULL);
10138 
10139 	/*
10140 	 * pageio_setup should have set b_addr to 0.  This is correct since
10141 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10142 	 * to calculate an offset, and then set b_addr to the kernel virtual
10143 	 * address it allocated for us.
10144 	 */
10145 	ASSERT(bp->b_un.b_addr == 0);
10146 
10147 	bp->b_edev = 0;
10148 	bp->b_dev = 0;
10149 	bp->b_lblkno = lbtodb(io_off);
10150 	bp->b_file = vp;
10151 	bp->b_offset = (offset_t)blkoff;
10152 	bp_mapin(bp);
10153 
10154 	/*
10155 	 * If doing a write beyond what we believe is EOF, don't bother trying
10156 	 * to read the pages from the server, we'll just zero the pages here.
10157 	 * We don't check that the rw flag is S_WRITE here because some
10158 	 * implementations may attempt a read access to the buffer before
10159 	 * copying data.
10160 	 */
10161 	mutex_enter(&rp->r_statelock);
10162 	if (io_off >= rp->r_size && seg == segkmap) {
10163 		mutex_exit(&rp->r_statelock);
10164 		bzero(bp->b_un.b_addr, io_len);
10165 		error = 0;
10166 	} else {
10167 		mutex_exit(&rp->r_statelock);
10168 		error = nfs4_bio(bp, NULL, cr, TRUE);
10169 		if (error == NFS_EOF)
10170 			error = 0;
10171 	}
10172 
10173 	/*
10174 	 * Unmap the buffer before freeing it.
10175 	 */
10176 	bp_mapout(bp);
10177 	pageio_done(bp);
10178 
10179 	savepp = pp;
10180 	do {
10181 		pp->p_fsdata = C_NOCOMMIT;
10182 	} while ((pp = pp->p_next) != savepp);
10183 
10184 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10185 
10186 	/*
10187 	 * In case of error set readahead offset
10188 	 * to the lowest offset.
10189 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10190 	 */
10191 	if (error && rp->r_nextr > io_off) {
10192 		mutex_enter(&rp->r_statelock);
10193 		if (rp->r_nextr > io_off)
10194 			rp->r_nextr = io_off;
10195 		mutex_exit(&rp->r_statelock);
10196 	}
10197 }
10198 
10199 /*
10200  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10201  * If len == 0, do from off to EOF.
10202  *
10203  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10204  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10205  * (from pageout).
10206  */
10207 /* ARGSUSED */
10208 static int
10209 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
10210     caller_context_t *ct)
10211 {
10212 	int error;
10213 	rnode4_t *rp;
10214 
10215 	ASSERT(cr != NULL);
10216 
10217 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10218 		return (EIO);
10219 
10220 	rp = VTOR4(vp);
10221 	if (IS_SHADOW(vp, rp))
10222 		vp = RTOV4(rp);
10223 
10224 	/*
10225 	 * XXX - Why should this check be made here?
10226 	 */
10227 	if (vp->v_flag & VNOMAP)
10228 		return (ENOSYS);
10229 
10230 	if (len == 0 && !(flags & B_INVAL) &&
10231 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10232 		return (0);
10233 
10234 	mutex_enter(&rp->r_statelock);
10235 	rp->r_count++;
10236 	mutex_exit(&rp->r_statelock);
10237 	error = nfs4_putpages(vp, off, len, flags, cr);
10238 	mutex_enter(&rp->r_statelock);
10239 	rp->r_count--;
10240 	cv_broadcast(&rp->r_cv);
10241 	mutex_exit(&rp->r_statelock);
10242 
10243 	return (error);
10244 }
10245 
10246 /*
10247  * Write out a single page, possibly klustering adjacent dirty pages.
10248  */
10249 int
10250 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10251     int flags, cred_t *cr)
10252 {
10253 	u_offset_t io_off;
10254 	u_offset_t lbn_off;
10255 	u_offset_t lbn;
10256 	size_t io_len;
10257 	uint_t bsize;
10258 	int error;
10259 	rnode4_t *rp;
10260 
10261 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10262 	ASSERT(pp != NULL);
10263 	ASSERT(cr != NULL);
10264 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10265 
10266 	rp = VTOR4(vp);
10267 	ASSERT(rp->r_count > 0);
10268 	ASSERT(!IS_SHADOW(vp, rp));
10269 
10270 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10271 	lbn = pp->p_offset / bsize;
10272 	lbn_off = lbn * bsize;
10273 
10274 	/*
10275 	 * Find a kluster that fits in one block, or in
10276 	 * one page if pages are bigger than blocks.  If
10277 	 * there is less file space allocated than a whole
10278 	 * page, we'll shorten the i/o request below.
10279 	 */
10280 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10281 	    roundup(bsize, PAGESIZE), flags);
10282 
10283 	/*
10284 	 * pvn_write_kluster shouldn't have returned a page with offset
10285 	 * behind the original page we were given.  Verify that.
10286 	 */
10287 	ASSERT((pp->p_offset / bsize) >= lbn);
10288 
10289 	/*
10290 	 * Now pp will have the list of kept dirty pages marked for
10291 	 * write back.  It will also handle invalidation and freeing
10292 	 * of pages that are not dirty.  Check for page length rounding
10293 	 * problems.
10294 	 */
10295 	if (io_off + io_len > lbn_off + bsize) {
10296 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10297 		io_len = lbn_off + bsize - io_off;
10298 	}
10299 	/*
10300 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10301 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10302 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10303 	 * progress and the r_size has not been made consistent with the
10304 	 * new size of the file. When the uiomove() completes the r_size is
10305 	 * updated and the R4MODINPROGRESS flag is cleared.
10306 	 *
10307 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10308 	 * consistent value of r_size. Without this handshaking, it is
10309 	 * possible that nfs4_bio() picks  up the old value of r_size
10310 	 * before the uiomove() in writerp4() completes. This will result
10311 	 * in the write through nfs4_bio() being dropped.
10312 	 *
10313 	 * More precisely, there is a window between the time the uiomove()
10314 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10315 	 * operation intervenes in this window, the page will be picked up,
10316 	 * because it is dirty (it will be unlocked, unless it was
10317 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10318 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10319 	 * checked. This will still be the old size. Therefore the page will
10320 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10321 	 * the page will be found to be clean and the write will be dropped.
10322 	 */
10323 	if (rp->r_flags & R4MODINPROGRESS) {
10324 		mutex_enter(&rp->r_statelock);
10325 		if ((rp->r_flags & R4MODINPROGRESS) &&
10326 		    rp->r_modaddr + MAXBSIZE > io_off &&
10327 		    rp->r_modaddr < io_off + io_len) {
10328 			page_t *plist;
10329 			/*
10330 			 * A write is in progress for this region of the file.
10331 			 * If we did not detect R4MODINPROGRESS here then this
10332 			 * path through nfs_putapage() would eventually go to
10333 			 * nfs4_bio() and may not write out all of the data
10334 			 * in the pages. We end up losing data. So we decide
10335 			 * to set the modified bit on each page in the page
10336 			 * list and mark the rnode with R4DIRTY. This write
10337 			 * will be restarted at some later time.
10338 			 */
10339 			plist = pp;
10340 			while (plist != NULL) {
10341 				pp = plist;
10342 				page_sub(&plist, pp);
10343 				hat_setmod(pp);
10344 				page_io_unlock(pp);
10345 				page_unlock(pp);
10346 			}
10347 			rp->r_flags |= R4DIRTY;
10348 			mutex_exit(&rp->r_statelock);
10349 			if (offp)
10350 				*offp = io_off;
10351 			if (lenp)
10352 				*lenp = io_len;
10353 			return (0);
10354 		}
10355 		mutex_exit(&rp->r_statelock);
10356 	}
10357 
10358 	if (flags & B_ASYNC) {
10359 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10360 		    nfs4_sync_putapage);
10361 	} else
10362 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10363 
10364 	if (offp)
10365 		*offp = io_off;
10366 	if (lenp)
10367 		*lenp = io_len;
10368 	return (error);
10369 }
10370 
10371 static int
10372 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10373     int flags, cred_t *cr)
10374 {
10375 	int error;
10376 	rnode4_t *rp;
10377 
10378 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10379 
10380 	flags |= B_WRITE;
10381 
10382 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10383 
10384 	rp = VTOR4(vp);
10385 
10386 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10387 	    error == EACCES) &&
10388 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10389 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10390 			mutex_enter(&rp->r_statelock);
10391 			rp->r_flags |= R4OUTOFSPACE;
10392 			mutex_exit(&rp->r_statelock);
10393 		}
10394 		flags |= B_ERROR;
10395 		pvn_write_done(pp, flags);
10396 		/*
10397 		 * If this was not an async thread, then try again to
10398 		 * write out the pages, but this time, also destroy
10399 		 * them whether or not the write is successful.  This
10400 		 * will prevent memory from filling up with these
10401 		 * pages and destroying them is the only alternative
10402 		 * if they can't be written out.
10403 		 *
10404 		 * Don't do this if this is an async thread because
10405 		 * when the pages are unlocked in pvn_write_done,
10406 		 * some other thread could have come along, locked
10407 		 * them, and queued for an async thread.  It would be
10408 		 * possible for all of the async threads to be tied
10409 		 * up waiting to lock the pages again and they would
10410 		 * all already be locked and waiting for an async
10411 		 * thread to handle them.  Deadlock.
10412 		 */
10413 		if (!(flags & B_ASYNC)) {
10414 			error = nfs4_putpage(vp, io_off, io_len,
10415 			    B_INVAL | B_FORCE, cr, NULL);
10416 		}
10417 	} else {
10418 		if (error)
10419 			flags |= B_ERROR;
10420 		else if (rp->r_flags & R4OUTOFSPACE) {
10421 			mutex_enter(&rp->r_statelock);
10422 			rp->r_flags &= ~R4OUTOFSPACE;
10423 			mutex_exit(&rp->r_statelock);
10424 		}
10425 		pvn_write_done(pp, flags);
10426 		if (freemem < desfree)
10427 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10428 			    NFS4_WRITE_NOWAIT);
10429 	}
10430 
10431 	return (error);
10432 }
10433 
10434 #ifdef DEBUG
10435 int nfs4_force_open_before_mmap = 0;
10436 #endif
10437 
10438 /* ARGSUSED */
10439 static int
10440 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10441     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10442     caller_context_t *ct)
10443 {
10444 	struct segvn_crargs vn_a;
10445 	int error = 0;
10446 	rnode4_t *rp = VTOR4(vp);
10447 	mntinfo4_t *mi = VTOMI4(vp);
10448 
10449 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10450 		return (EIO);
10451 
10452 	if (vp->v_flag & VNOMAP)
10453 		return (ENOSYS);
10454 
10455 	if (off < 0 || (off + len) < 0)
10456 		return (ENXIO);
10457 
10458 	if (vp->v_type != VREG)
10459 		return (ENODEV);
10460 
10461 	/*
10462 	 * If the file is delegated to the client don't do anything.
10463 	 * If the file is not delegated, then validate the data cache.
10464 	 */
10465 	mutex_enter(&rp->r_statev4_lock);
10466 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10467 		mutex_exit(&rp->r_statev4_lock);
10468 		error = nfs4_validate_caches(vp, cr);
10469 		if (error)
10470 			return (error);
10471 	} else {
10472 		mutex_exit(&rp->r_statev4_lock);
10473 	}
10474 
10475 	/*
10476 	 * Check to see if the vnode is currently marked as not cachable.
10477 	 * This means portions of the file are locked (through VOP_FRLOCK).
10478 	 * In this case the map request must be refused.  We use
10479 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10480 	 *
10481 	 * Atomically increment r_inmap after acquiring r_rwlock. The
10482 	 * idea here is to acquire r_rwlock to block read/write and
10483 	 * not to protect r_inmap. r_inmap will inform nfs4_read/write()
10484 	 * that we are in nfs4_map(). Now, r_rwlock is acquired in order
10485 	 * and we can prevent the deadlock that would have occurred
10486 	 * when nfs4_addmap() would have acquired it out of order.
10487 	 *
10488 	 * Since we are not protecting r_inmap by any lock, we do not
10489 	 * hold any lock when we decrement it. We atomically decrement
10490 	 * r_inmap after we release r_lkserlock.
10491 	 */
10492 
10493 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR4(vp)))
10494 		return (EINTR);
10495 	atomic_inc_uint(&rp->r_inmap);
10496 	nfs_rw_exit(&rp->r_rwlock);
10497 
10498 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp))) {
10499 		atomic_dec_uint(&rp->r_inmap);
10500 		return (EINTR);
10501 	}
10502 
10503 	if (vp->v_flag & VNOCACHE) {
10504 		error = EAGAIN;
10505 		goto done;
10506 	}
10507 
10508 	/*
10509 	 * Don't allow concurrent locks and mapping if mandatory locking is
10510 	 * enabled.
10511 	 */
10512 	if (flk_has_remote_locks(vp)) {
10513 		struct vattr va;
10514 		va.va_mask = AT_MODE;
10515 		error = nfs4getattr(vp, &va, cr);
10516 		if (error != 0)
10517 			goto done;
10518 		if (MANDLOCK(vp, va.va_mode)) {
10519 			error = EAGAIN;
10520 			goto done;
10521 		}
10522 	}
10523 
10524 	/*
10525 	 * It is possible that the rnode has a lost lock request that we
10526 	 * are still trying to recover, and that the request conflicts with
10527 	 * this map request.
10528 	 *
10529 	 * An alternative approach would be for nfs4_safemap() to consider
10530 	 * queued lock requests when deciding whether to set or clear
10531 	 * VNOCACHE.  This would require the frlock code path to call
10532 	 * nfs4_safemap() after enqueing a lost request.
10533 	 */
10534 	if (nfs4_map_lost_lock_conflict(vp)) {
10535 		error = EAGAIN;
10536 		goto done;
10537 	}
10538 
10539 	as_rangelock(as);
10540 	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
10541 	if (error != 0) {
10542 		as_rangeunlock(as);
10543 		goto done;
10544 	}
10545 
10546 	if (vp->v_type == VREG) {
10547 		/*
10548 		 * We need to retrieve the open stream
10549 		 */
10550 		nfs4_open_stream_t	*osp = NULL;
10551 		nfs4_open_owner_t	*oop = NULL;
10552 
10553 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10554 		if (oop != NULL) {
10555 			/* returns with 'os_sync_lock' held */
10556 			osp = find_open_stream(oop, rp);
10557 			open_owner_rele(oop);
10558 		}
10559 		if (osp == NULL) {
10560 #ifdef DEBUG
10561 			if (nfs4_force_open_before_mmap) {
10562 				error = EIO;
10563 				goto done;
10564 			}
10565 #endif
10566 			/* returns with 'os_sync_lock' held */
10567 			error = open_and_get_osp(vp, cr, &osp);
10568 			if (osp == NULL) {
10569 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10570 				    "nfs4_map: we tried to OPEN the file "
10571 				    "but again no osp, so fail with EIO"));
10572 				goto done;
10573 			}
10574 		}
10575 
10576 		if (osp->os_failed_reopen) {
10577 			mutex_exit(&osp->os_sync_lock);
10578 			open_stream_rele(osp, rp);
10579 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10580 			    "nfs4_map: os_failed_reopen set on "
10581 			    "osp %p, cr %p, rp %s", (void *)osp,
10582 			    (void *)cr, rnode4info(rp)));
10583 			error = EIO;
10584 			goto done;
10585 		}
10586 		mutex_exit(&osp->os_sync_lock);
10587 		open_stream_rele(osp, rp);
10588 	}
10589 
10590 	vn_a.vp = vp;
10591 	vn_a.offset = off;
10592 	vn_a.type = (flags & MAP_TYPE);
10593 	vn_a.prot = (uchar_t)prot;
10594 	vn_a.maxprot = (uchar_t)maxprot;
10595 	vn_a.flags = (flags & ~MAP_TYPE);
10596 	vn_a.cred = cr;
10597 	vn_a.amp = NULL;
10598 	vn_a.szc = 0;
10599 	vn_a.lgrp_mem_policy_flags = 0;
10600 
10601 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10602 	as_rangeunlock(as);
10603 
10604 done:
10605 	nfs_rw_exit(&rp->r_lkserlock);
10606 	atomic_dec_uint(&rp->r_inmap);
10607 	return (error);
10608 }
10609 
10610 /*
10611  * We're most likely dealing with a kernel module that likes to READ
10612  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10613  * officially OPEN the file to create the necessary client state
10614  * for bookkeeping of os_mmap_read/write counts.
10615  *
10616  * Since VOP_MAP only passes in a pointer to the vnode rather than
10617  * a double pointer, we can't handle the case where nfs4open_otw()
10618  * returns a different vnode than the one passed into VOP_MAP (since
10619  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10620  * we return NULL and let nfs4_map() fail.  Note: the only case where
10621  * this should happen is if the file got removed and replaced with the
10622  * same name on the server (in addition to the fact that we're trying
10623  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10624  */
10625 static int
10626 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10627 {
10628 	rnode4_t		*rp, *drp;
10629 	vnode_t			*dvp, *open_vp;
10630 	char			file_name[MAXNAMELEN];
10631 	int			just_created;
10632 	nfs4_open_stream_t	*osp;
10633 	nfs4_open_owner_t	*oop;
10634 	int			error;
10635 
10636 	*ospp = NULL;
10637 	open_vp = map_vp;
10638 
10639 	rp = VTOR4(open_vp);
10640 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10641 		return (error);
10642 	drp = VTOR4(dvp);
10643 
10644 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10645 		VN_RELE(dvp);
10646 		return (EINTR);
10647 	}
10648 
10649 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10650 		nfs_rw_exit(&drp->r_rwlock);
10651 		VN_RELE(dvp);
10652 		return (error);
10653 	}
10654 
10655 	mutex_enter(&rp->r_statev4_lock);
10656 	if (rp->created_v4) {
10657 		rp->created_v4 = 0;
10658 		mutex_exit(&rp->r_statev4_lock);
10659 
10660 		dnlc_update(dvp, file_name, open_vp);
10661 		/* This is needed so we don't bump the open ref count */
10662 		just_created = 1;
10663 	} else {
10664 		mutex_exit(&rp->r_statev4_lock);
10665 		just_created = 0;
10666 	}
10667 
10668 	VN_HOLD(map_vp);
10669 
10670 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10671 	    just_created);
10672 	if (error) {
10673 		nfs_rw_exit(&drp->r_rwlock);
10674 		VN_RELE(dvp);
10675 		VN_RELE(map_vp);
10676 		return (error);
10677 	}
10678 
10679 	nfs_rw_exit(&drp->r_rwlock);
10680 	VN_RELE(dvp);
10681 
10682 	/*
10683 	 * If nfs4open_otw() returned a different vnode then "undo"
10684 	 * the open and return failure to the caller.
10685 	 */
10686 	if (!VN_CMP(open_vp, map_vp)) {
10687 		nfs4_error_t e;
10688 
10689 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10690 		    "open returned a different vnode"));
10691 		/*
10692 		 * If there's an error, ignore it,
10693 		 * and let VOP_INACTIVE handle it.
10694 		 */
10695 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10696 		    CLOSE_NORM, 0, 0, 0);
10697 		VN_RELE(map_vp);
10698 		return (EIO);
10699 	}
10700 
10701 	VN_RELE(map_vp);
10702 
10703 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10704 	if (!oop) {
10705 		nfs4_error_t e;
10706 
10707 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10708 		    "no open owner"));
10709 		/*
10710 		 * If there's an error, ignore it,
10711 		 * and let VOP_INACTIVE handle it.
10712 		 */
10713 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10714 		    CLOSE_NORM, 0, 0, 0);
10715 		return (EIO);
10716 	}
10717 	osp = find_open_stream(oop, rp);
10718 	open_owner_rele(oop);
10719 	*ospp = osp;
10720 	return (0);
10721 }
10722 
10723 /*
10724  * Please be aware that when this function is called, the address space write
10725  * a_lock is held.  Do not put over the wire calls in this function.
10726  */
10727 /* ARGSUSED */
10728 static int
10729 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10730     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10731     caller_context_t *ct)
10732 {
10733 	rnode4_t		*rp;
10734 	int			error = 0;
10735 	mntinfo4_t		*mi;
10736 
10737 	mi = VTOMI4(vp);
10738 	rp = VTOR4(vp);
10739 
10740 	if (nfs_zone() != mi->mi_zone)
10741 		return (EIO);
10742 	if (vp->v_flag & VNOMAP)
10743 		return (ENOSYS);
10744 
10745 	/*
10746 	 * Don't need to update the open stream first, since this
10747 	 * mmap can't add any additional share access that isn't
10748 	 * already contained in the open stream (for the case where we
10749 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10750 	 * take into account os_mmap_read[write] counts).
10751 	 */
10752 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10753 
10754 	if (vp->v_type == VREG) {
10755 		/*
10756 		 * We need to retrieve the open stream and update the counts.
10757 		 * If there is no open stream here, something is wrong.
10758 		 */
10759 		nfs4_open_stream_t	*osp = NULL;
10760 		nfs4_open_owner_t	*oop = NULL;
10761 
10762 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10763 		if (oop != NULL) {
10764 			/* returns with 'os_sync_lock' held */
10765 			osp = find_open_stream(oop, rp);
10766 			open_owner_rele(oop);
10767 		}
10768 		if (osp == NULL) {
10769 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10770 			    "nfs4_addmap: we should have an osp"
10771 			    "but we don't, so fail with EIO"));
10772 			error = EIO;
10773 			goto out;
10774 		}
10775 
10776 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10777 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10778 
10779 		/*
10780 		 * Update the map count in the open stream.
10781 		 * This is necessary in the case where we
10782 		 * open/mmap/close/, then the server reboots, and we
10783 		 * attempt to reopen.  If the mmap doesn't add share
10784 		 * access then we send an invalid reopen with
10785 		 * access = NONE.
10786 		 *
10787 		 * We need to specifically check each PROT_* so a mmap
10788 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10789 		 * read and write access.  A simple comparison of prot
10790 		 * to ~PROT_WRITE to determine read access is insufficient
10791 		 * since prot can be |= with PROT_USER, etc.
10792 		 */
10793 
10794 		/*
10795 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10796 		 */
10797 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10798 			osp->os_mmap_write += btopr(len);
10799 		if (maxprot & PROT_READ)
10800 			osp->os_mmap_read += btopr(len);
10801 		if (maxprot & PROT_EXEC)
10802 			osp->os_mmap_read += btopr(len);
10803 		/*
10804 		 * Ensure that os_mmap_read gets incremented, even if
10805 		 * maxprot were to look like PROT_NONE.
10806 		 */
10807 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10808 		    !(maxprot & PROT_EXEC))
10809 			osp->os_mmap_read += btopr(len);
10810 		osp->os_mapcnt += btopr(len);
10811 		mutex_exit(&osp->os_sync_lock);
10812 		open_stream_rele(osp, rp);
10813 	}
10814 
10815 out:
10816 	/*
10817 	 * If we got an error, then undo our
10818 	 * incrementing of 'r_mapcnt'.
10819 	 */
10820 
10821 	if (error) {
10822 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10823 		ASSERT(rp->r_mapcnt >= 0);
10824 	}
10825 	return (error);
10826 }
10827 
10828 /* ARGSUSED */
10829 static int
10830 nfs4_cmp(vnode_t *vp1, vnode_t *vp2, caller_context_t *ct)
10831 {
10832 
10833 	return (VTOR4(vp1) == VTOR4(vp2));
10834 }
10835 
10836 /* ARGSUSED */
10837 static int
10838 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10839     offset_t offset, struct flk_callback *flk_cbp, cred_t *cr,
10840     caller_context_t *ct)
10841 {
10842 	int rc;
10843 	u_offset_t start, end;
10844 	rnode4_t *rp;
10845 	int error = 0, intr = INTR4(vp);
10846 	nfs4_error_t e;
10847 
10848 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10849 		return (EIO);
10850 
10851 	/* check for valid cmd parameter */
10852 	if (cmd != F_GETLK && cmd != F_SETLK && cmd != F_SETLKW)
10853 		return (EINVAL);
10854 
10855 	/* Verify l_type. */
10856 	switch (bfp->l_type) {
10857 	case F_RDLCK:
10858 		if (cmd != F_GETLK && !(flag & FREAD))
10859 			return (EBADF);
10860 		break;
10861 	case F_WRLCK:
10862 		if (cmd != F_GETLK && !(flag & FWRITE))
10863 			return (EBADF);
10864 		break;
10865 	case F_UNLCK:
10866 		intr = 0;
10867 		break;
10868 
10869 	default:
10870 		return (EINVAL);
10871 	}
10872 
10873 	/* check the validity of the lock range */
10874 	if (rc = flk_convert_lock_data(vp, bfp, &start, &end, offset))
10875 		return (rc);
10876 	if (rc = flk_check_lock_data(start, end, MAXEND))
10877 		return (rc);
10878 
10879 	/*
10880 	 * If the filesystem is mounted using local locking, pass the
10881 	 * request off to the local locking code.
10882 	 */
10883 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10884 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10885 			/*
10886 			 * For complete safety, we should be holding
10887 			 * r_lkserlock.  However, we can't call
10888 			 * nfs4_safelock and then fs_frlock while
10889 			 * holding r_lkserlock, so just invoke
10890 			 * nfs4_safelock and expect that this will
10891 			 * catch enough of the cases.
10892 			 */
10893 			if (!nfs4_safelock(vp, bfp, cr))
10894 				return (EAGAIN);
10895 		}
10896 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
10897 	}
10898 
10899 	rp = VTOR4(vp);
10900 
10901 	/*
10902 	 * Check whether the given lock request can proceed, given the
10903 	 * current file mappings.
10904 	 */
10905 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr))
10906 		return (EINTR);
10907 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10908 		if (!nfs4_safelock(vp, bfp, cr)) {
10909 			rc = EAGAIN;
10910 			goto done;
10911 		}
10912 	}
10913 
10914 	/*
10915 	 * Flush the cache after waiting for async I/O to finish.  For new
10916 	 * locks, this is so that the process gets the latest bits from the
10917 	 * server.  For unlocks, this is so that other clients see the
10918 	 * latest bits once the file has been unlocked.  If currently dirty
10919 	 * pages can't be flushed, then don't allow a lock to be set.  But
10920 	 * allow unlocks to succeed, to avoid having orphan locks on the
10921 	 * server.
10922 	 */
10923 	if (cmd != F_GETLK) {
10924 		mutex_enter(&rp->r_statelock);
10925 		while (rp->r_count > 0) {
10926 			if (intr) {
10927 				klwp_t *lwp = ttolwp(curthread);
10928 
10929 				if (lwp != NULL)
10930 					lwp->lwp_nostop++;
10931 				if (cv_wait_sig(&rp->r_cv,
10932 				    &rp->r_statelock) == 0) {
10933 					if (lwp != NULL)
10934 						lwp->lwp_nostop--;
10935 					rc = EINTR;
10936 					break;
10937 				}
10938 				if (lwp != NULL)
10939 					lwp->lwp_nostop--;
10940 			} else {
10941 				cv_wait(&rp->r_cv, &rp->r_statelock);
10942 			}
10943 		}
10944 		mutex_exit(&rp->r_statelock);
10945 		if (rc != 0)
10946 			goto done;
10947 		error = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr, ct);
10948 		if (error) {
10949 			if (error == ENOSPC || error == EDQUOT) {
10950 				mutex_enter(&rp->r_statelock);
10951 				if (!rp->r_error)
10952 					rp->r_error = error;
10953 				mutex_exit(&rp->r_statelock);
10954 			}
10955 			if (bfp->l_type != F_UNLCK) {
10956 				rc = ENOLCK;
10957 				goto done;
10958 			}
10959 		}
10960 	}
10961 
10962 	/*
10963 	 * Call the lock manager to do the real work of contacting
10964 	 * the server and obtaining the lock.
10965 	 */
10966 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, flag, offset,
10967 	    cr, &e, NULL, NULL);
10968 	rc = e.error;
10969 
10970 	if (rc == 0)
10971 		nfs4_lockcompletion(vp, cmd);
10972 
10973 done:
10974 	nfs_rw_exit(&rp->r_lkserlock);
10975 
10976 	return (rc);
10977 }
10978 
10979 /*
10980  * Free storage space associated with the specified vnode.  The portion
10981  * to be freed is specified by bfp->l_start and bfp->l_len (already
10982  * normalized to a "whence" of 0).
10983  *
10984  * This is an experimental facility whose continued existence is not
10985  * guaranteed.  Currently, we only support the special case
10986  * of l_len == 0, meaning free to end of file.
10987  */
10988 /* ARGSUSED */
10989 static int
10990 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10991     offset_t offset, cred_t *cr, caller_context_t *ct)
10992 {
10993 	int error;
10994 
10995 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10996 		return (EIO);
10997 	ASSERT(vp->v_type == VREG);
10998 	if (cmd != F_FREESP)
10999 		return (EINVAL);
11000 
11001 	error = convoff(vp, bfp, 0, offset);
11002 	if (!error) {
11003 		ASSERT(bfp->l_start >= 0);
11004 		if (bfp->l_len == 0) {
11005 			struct vattr va;
11006 
11007 			va.va_mask = AT_SIZE;
11008 			va.va_size = bfp->l_start;
11009 			error = nfs4setattr(vp, &va, 0, cr, NULL);
11010 
11011 			if (error == 0 && bfp->l_start == 0)
11012 				vnevent_truncate(vp, ct);
11013 		} else
11014 			error = EINVAL;
11015 	}
11016 
11017 	return (error);
11018 }
11019 
11020 /* ARGSUSED */
11021 int
11022 nfs4_realvp(vnode_t *vp, vnode_t **vpp, caller_context_t *ct)
11023 {
11024 	rnode4_t *rp;
11025 	rp = VTOR4(vp);
11026 
11027 	if (vp->v_type == VREG && IS_SHADOW(vp, rp)) {
11028 		vp = RTOV4(rp);
11029 	}
11030 	*vpp = vp;
11031 	return (0);
11032 }
11033 
11034 /*
11035  * Setup and add an address space callback to do the work of the delmap call.
11036  * The callback will (and must be) deleted in the actual callback function.
11037  *
11038  * This is done in order to take care of the problem that we have with holding
11039  * the address space's a_lock for a long period of time (e.g. if the NFS server
11040  * is down).  Callbacks will be executed in the address space code while the
11041  * a_lock is not held.  Holding the address space's a_lock causes things such
11042  * as ps and fork to hang because they are trying to acquire this lock as well.
11043  */
11044 /* ARGSUSED */
11045 static int
11046 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
11047     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
11048     caller_context_t *ct)
11049 {
11050 	int			caller_found;
11051 	int			error;
11052 	rnode4_t		*rp;
11053 	nfs4_delmap_args_t	*dmapp;
11054 	nfs4_delmapcall_t	*delmap_call;
11055 
11056 	if (vp->v_flag & VNOMAP)
11057 		return (ENOSYS);
11058 
11059 	/*
11060 	 * A process may not change zones if it has NFS pages mmap'ed
11061 	 * in, so we can't legitimately get here from the wrong zone.
11062 	 */
11063 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11064 
11065 	rp = VTOR4(vp);
11066 
11067 	/*
11068 	 * The way that the address space of this process deletes its mapping
11069 	 * of this file is via the following call chains:
11070 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11071 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11072 	 *
11073 	 * With the use of address space callbacks we are allowed to drop the
11074 	 * address space lock, a_lock, while executing the NFS operations that
11075 	 * need to go over the wire.  Returning EAGAIN to the caller of this
11076 	 * function is what drives the execution of the callback that we add
11077 	 * below.  The callback will be executed by the address space code
11078 	 * after dropping the a_lock.  When the callback is finished, since
11079 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
11080 	 * is called again on the same segment to finish the rest of the work
11081 	 * that needs to happen during unmapping.
11082 	 *
11083 	 * This action of calling back into the segment driver causes
11084 	 * nfs4_delmap() to get called again, but since the callback was
11085 	 * already executed at this point, it already did the work and there
11086 	 * is nothing left for us to do.
11087 	 *
11088 	 * To Summarize:
11089 	 * - The first time nfs4_delmap is called by the current thread is when
11090 	 * we add the caller associated with this delmap to the delmap caller
11091 	 * list, add the callback, and return EAGAIN.
11092 	 * - The second time in this call chain when nfs4_delmap is called we
11093 	 * will find this caller in the delmap caller list and realize there
11094 	 * is no more work to do thus removing this caller from the list and
11095 	 * returning the error that was set in the callback execution.
11096 	 */
11097 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
11098 	if (caller_found) {
11099 		/*
11100 		 * 'error' is from the actual delmap operations.  To avoid
11101 		 * hangs, we need to handle the return of EAGAIN differently
11102 		 * since this is what drives the callback execution.
11103 		 * In this case, we don't want to return EAGAIN and do the
11104 		 * callback execution because there are none to execute.
11105 		 */
11106 		if (error == EAGAIN)
11107 			return (0);
11108 		else
11109 			return (error);
11110 	}
11111 
11112 	/* current caller was not in the list */
11113 	delmap_call = nfs4_init_delmapcall();
11114 
11115 	mutex_enter(&rp->r_statelock);
11116 	list_insert_tail(&rp->r_indelmap, delmap_call);
11117 	mutex_exit(&rp->r_statelock);
11118 
11119 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
11120 
11121 	dmapp->vp = vp;
11122 	dmapp->off = off;
11123 	dmapp->addr = addr;
11124 	dmapp->len = len;
11125 	dmapp->prot = prot;
11126 	dmapp->maxprot = maxprot;
11127 	dmapp->flags = flags;
11128 	dmapp->cr = cr;
11129 	dmapp->caller = delmap_call;
11130 
11131 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
11132 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
11133 
11134 	return (error ? error : EAGAIN);
11135 }
11136 
11137 static nfs4_delmapcall_t *
11138 nfs4_init_delmapcall()
11139 {
11140 	nfs4_delmapcall_t	*delmap_call;
11141 
11142 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
11143 	delmap_call->call_id = curthread;
11144 	delmap_call->error = 0;
11145 
11146 	return (delmap_call);
11147 }
11148 
11149 static void
11150 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11151 {
11152 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11153 }
11154 
11155 /*
11156  * Searches for the current delmap caller (based on curthread) in the list of
11157  * callers.  If it is found, we remove it and free the delmap caller.
11158  * Returns:
11159  *      0 if the caller wasn't found
11160  *      1 if the caller was found, removed and freed.  *errp will be set
11161  *	to what the result of the delmap was.
11162  */
11163 static int
11164 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11165 {
11166 	nfs4_delmapcall_t	*delmap_call;
11167 
11168 	/*
11169 	 * If the list doesn't exist yet, we create it and return
11170 	 * that the caller wasn't found.  No list = no callers.
11171 	 */
11172 	mutex_enter(&rp->r_statelock);
11173 	if (!(rp->r_flags & R4DELMAPLIST)) {
11174 		/* The list does not exist */
11175 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11176 		    offsetof(nfs4_delmapcall_t, call_node));
11177 		rp->r_flags |= R4DELMAPLIST;
11178 		mutex_exit(&rp->r_statelock);
11179 		return (0);
11180 	} else {
11181 		/* The list exists so search it */
11182 		for (delmap_call = list_head(&rp->r_indelmap);
11183 		    delmap_call != NULL;
11184 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11185 			if (delmap_call->call_id == curthread) {
11186 				/* current caller is in the list */
11187 				*errp = delmap_call->error;
11188 				list_remove(&rp->r_indelmap, delmap_call);
11189 				mutex_exit(&rp->r_statelock);
11190 				nfs4_free_delmapcall(delmap_call);
11191 				return (1);
11192 			}
11193 		}
11194 	}
11195 	mutex_exit(&rp->r_statelock);
11196 	return (0);
11197 }
11198 
11199 /*
11200  * Remove some pages from an mmap'd vnode.  Just update the
11201  * count of pages.  If doing close-to-open, then flush and
11202  * commit all of the pages associated with this file.
11203  * Otherwise, start an asynchronous page flush to write out
11204  * any dirty pages.  This will also associate a credential
11205  * with the rnode which can be used to write the pages.
11206  */
11207 /* ARGSUSED */
11208 static void
11209 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11210 {
11211 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11212 	rnode4_t		*rp;
11213 	mntinfo4_t		*mi;
11214 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11215 
11216 	rp = VTOR4(dmapp->vp);
11217 	mi = VTOMI4(dmapp->vp);
11218 
11219 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11220 	ASSERT(rp->r_mapcnt >= 0);
11221 
11222 	/*
11223 	 * Initiate a page flush and potential commit if there are
11224 	 * pages, the file system was not mounted readonly, the segment
11225 	 * was mapped shared, and the pages themselves were writeable.
11226 	 */
11227 	if (nfs4_has_pages(dmapp->vp) &&
11228 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11229 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11230 		mutex_enter(&rp->r_statelock);
11231 		rp->r_flags |= R4DIRTY;
11232 		mutex_exit(&rp->r_statelock);
11233 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11234 		    dmapp->len, dmapp->cr);
11235 		if (!e.error) {
11236 			mutex_enter(&rp->r_statelock);
11237 			e.error = rp->r_error;
11238 			rp->r_error = 0;
11239 			mutex_exit(&rp->r_statelock);
11240 		}
11241 	} else
11242 		e.error = 0;
11243 
11244 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11245 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11246 		    B_INVAL, dmapp->cr, NULL);
11247 
11248 	if (e.error) {
11249 		e.stat = puterrno4(e.error);
11250 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11251 		    OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11252 		dmapp->caller->error = e.error;
11253 	}
11254 
11255 	/* Check to see if we need to close the file */
11256 
11257 	if (dmapp->vp->v_type == VREG) {
11258 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11259 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11260 
11261 		if (e.error != 0 || e.stat != NFS4_OK) {
11262 			/*
11263 			 * Since it is possible that e.error == 0 and
11264 			 * e.stat != NFS4_OK (and vice versa),
11265 			 * we do the proper checking in order to get both
11266 			 * e.error and e.stat reporting the correct info.
11267 			 */
11268 			if (e.stat == NFS4_OK)
11269 				e.stat = puterrno4(e.error);
11270 			if (e.error == 0)
11271 				e.error = geterrno4(e.stat);
11272 
11273 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11274 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11275 			dmapp->caller->error = e.error;
11276 		}
11277 	}
11278 
11279 	(void) as_delete_callback(as, arg);
11280 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11281 }
11282 
11283 
11284 static uint_t
11285 fattr4_maxfilesize_to_bits(uint64_t ll)
11286 {
11287 	uint_t l = 1;
11288 
11289 	if (ll == 0) {
11290 		return (0);
11291 	}
11292 
11293 	if (ll & 0xffffffff00000000) {
11294 		l += 32; ll >>= 32;
11295 	}
11296 	if (ll & 0xffff0000) {
11297 		l += 16; ll >>= 16;
11298 	}
11299 	if (ll & 0xff00) {
11300 		l += 8; ll >>= 8;
11301 	}
11302 	if (ll & 0xf0) {
11303 		l += 4; ll >>= 4;
11304 	}
11305 	if (ll & 0xc) {
11306 		l += 2; ll >>= 2;
11307 	}
11308 	if (ll & 0x2) {
11309 		l += 1;
11310 	}
11311 	return (l);
11312 }
11313 
11314 static int
11315 nfs4_have_xattrs(vnode_t *vp, ulong_t *valp, cred_t *cr)
11316 {
11317 	vnode_t *avp = NULL;
11318 	int error;
11319 
11320 	if ((error = nfs4lookup_xattr(vp, "", &avp,
11321 	    LOOKUP_XATTR, cr)) == 0)
11322 		error = do_xattr_exists_check(avp, valp, cr);
11323 	if (avp)
11324 		VN_RELE(avp);
11325 
11326 	return (error);
11327 }
11328 
11329 /* ARGSUSED */
11330 int
11331 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
11332     caller_context_t *ct)
11333 {
11334 	int error;
11335 	hrtime_t t;
11336 	rnode4_t *rp;
11337 	nfs4_ga_res_t gar;
11338 	nfs4_ga_ext_res_t ger;
11339 
11340 	gar.n4g_ext_res = &ger;
11341 
11342 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11343 		return (EIO);
11344 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11345 		*valp = MAXPATHLEN;
11346 		return (0);
11347 	}
11348 	if (cmd == _PC_ACL_ENABLED) {
11349 		*valp = _ACL_ACE_ENABLED;
11350 		return (0);
11351 	}
11352 
11353 	rp = VTOR4(vp);
11354 	if (cmd == _PC_XATTR_EXISTS) {
11355 		/*
11356 		 * The existence of the xattr directory is not sufficient
11357 		 * for determining whether generic user attributes exists.
11358 		 * The attribute directory could only be a transient directory
11359 		 * used for Solaris sysattr support.  Do a small readdir
11360 		 * to verify if the only entries are sysattrs or not.
11361 		 *
11362 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11363 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11364 		 * and we don't have any way to update the "base" object's
11365 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11366 		 * could help out.
11367 		 */
11368 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11369 		    rp->r_xattr_dir == NULL) {
11370 			return (nfs4_have_xattrs(vp, valp, cr));
11371 		}
11372 	} else {  /* OLD CODE */
11373 		if (ATTRCACHE4_VALID(vp)) {
11374 			mutex_enter(&rp->r_statelock);
11375 			if (rp->r_pathconf.pc4_cache_valid) {
11376 				error = 0;
11377 				switch (cmd) {
11378 				case _PC_FILESIZEBITS:
11379 					*valp =
11380 					    rp->r_pathconf.pc4_filesizebits;
11381 					break;
11382 				case _PC_LINK_MAX:
11383 					*valp =
11384 					    rp->r_pathconf.pc4_link_max;
11385 					break;
11386 				case _PC_NAME_MAX:
11387 					*valp =
11388 					    rp->r_pathconf.pc4_name_max;
11389 					break;
11390 				case _PC_CHOWN_RESTRICTED:
11391 					*valp =
11392 					    rp->r_pathconf.pc4_chown_restricted;
11393 					break;
11394 				case _PC_NO_TRUNC:
11395 					*valp =
11396 					    rp->r_pathconf.pc4_no_trunc;
11397 					break;
11398 				default:
11399 					error = EINVAL;
11400 					break;
11401 				}
11402 				mutex_exit(&rp->r_statelock);
11403 #ifdef DEBUG
11404 				nfs4_pathconf_cache_hits++;
11405 #endif
11406 				return (error);
11407 			}
11408 			mutex_exit(&rp->r_statelock);
11409 		}
11410 	}
11411 #ifdef DEBUG
11412 	nfs4_pathconf_cache_misses++;
11413 #endif
11414 
11415 	t = gethrtime();
11416 
11417 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11418 
11419 	if (error) {
11420 		mutex_enter(&rp->r_statelock);
11421 		rp->r_pathconf.pc4_cache_valid = FALSE;
11422 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11423 		mutex_exit(&rp->r_statelock);
11424 		return (error);
11425 	}
11426 
11427 	/* interpret the max filesize */
11428 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11429 	    fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11430 
11431 	/* Store the attributes we just received */
11432 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11433 
11434 	switch (cmd) {
11435 	case _PC_FILESIZEBITS:
11436 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11437 		break;
11438 	case _PC_LINK_MAX:
11439 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11440 		break;
11441 	case _PC_NAME_MAX:
11442 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11443 		break;
11444 	case _PC_CHOWN_RESTRICTED:
11445 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11446 		break;
11447 	case _PC_NO_TRUNC:
11448 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11449 		break;
11450 	case _PC_XATTR_EXISTS:
11451 		if (gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists) {
11452 			if (error = nfs4_have_xattrs(vp, valp, cr))
11453 				return (error);
11454 		}
11455 		break;
11456 	default:
11457 		return (EINVAL);
11458 	}
11459 
11460 	return (0);
11461 }
11462 
11463 /*
11464  * Called by async thread to do synchronous pageio. Do the i/o, wait
11465  * for it to complete, and cleanup the page list when done.
11466  */
11467 static int
11468 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11469     int flags, cred_t *cr)
11470 {
11471 	int error;
11472 
11473 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11474 
11475 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11476 	if (flags & B_READ)
11477 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11478 	else
11479 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11480 	return (error);
11481 }
11482 
11483 /* ARGSUSED */
11484 static int
11485 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11486     int flags, cred_t *cr, caller_context_t *ct)
11487 {
11488 	int error;
11489 	rnode4_t *rp;
11490 
11491 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11492 		return (EIO);
11493 
11494 	if (pp == NULL)
11495 		return (EINVAL);
11496 
11497 	rp = VTOR4(vp);
11498 	mutex_enter(&rp->r_statelock);
11499 	rp->r_count++;
11500 	mutex_exit(&rp->r_statelock);
11501 
11502 	if (flags & B_ASYNC) {
11503 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11504 		    nfs4_sync_pageio);
11505 	} else
11506 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11507 	mutex_enter(&rp->r_statelock);
11508 	rp->r_count--;
11509 	cv_broadcast(&rp->r_cv);
11510 	mutex_exit(&rp->r_statelock);
11511 	return (error);
11512 }
11513 
11514 /* ARGSUSED */
11515 static void
11516 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr,
11517     caller_context_t *ct)
11518 {
11519 	int error;
11520 	rnode4_t *rp;
11521 	page_t *plist;
11522 	page_t *pptr;
11523 	offset3 offset;
11524 	count3 len;
11525 	k_sigset_t smask;
11526 
11527 	/*
11528 	 * We should get called with fl equal to either B_FREE or
11529 	 * B_INVAL.  Any other value is illegal.
11530 	 *
11531 	 * The page that we are either supposed to free or destroy
11532 	 * should be exclusive locked and its io lock should not
11533 	 * be held.
11534 	 */
11535 	ASSERT(fl == B_FREE || fl == B_INVAL);
11536 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11537 
11538 	rp = VTOR4(vp);
11539 
11540 	/*
11541 	 * If the page doesn't need to be committed or we shouldn't
11542 	 * even bother attempting to commit it, then just make sure
11543 	 * that the p_fsdata byte is clear and then either free or
11544 	 * destroy the page as appropriate.
11545 	 */
11546 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11547 		pp->p_fsdata = C_NOCOMMIT;
11548 		if (fl == B_FREE)
11549 			page_free(pp, dn);
11550 		else
11551 			page_destroy(pp, dn);
11552 		return;
11553 	}
11554 
11555 	/*
11556 	 * If there is a page invalidation operation going on, then
11557 	 * if this is one of the pages being destroyed, then just
11558 	 * clear the p_fsdata byte and then either free or destroy
11559 	 * the page as appropriate.
11560 	 */
11561 	mutex_enter(&rp->r_statelock);
11562 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11563 		mutex_exit(&rp->r_statelock);
11564 		pp->p_fsdata = C_NOCOMMIT;
11565 		if (fl == B_FREE)
11566 			page_free(pp, dn);
11567 		else
11568 			page_destroy(pp, dn);
11569 		return;
11570 	}
11571 
11572 	/*
11573 	 * If we are freeing this page and someone else is already
11574 	 * waiting to do a commit, then just unlock the page and
11575 	 * return.  That other thread will take care of commiting
11576 	 * this page.  The page can be freed sometime after the
11577 	 * commit has finished.  Otherwise, if the page is marked
11578 	 * as delay commit, then we may be getting called from
11579 	 * pvn_write_done, one page at a time.   This could result
11580 	 * in one commit per page, so we end up doing lots of small
11581 	 * commits instead of fewer larger commits.  This is bad,
11582 	 * we want do as few commits as possible.
11583 	 */
11584 	if (fl == B_FREE) {
11585 		if (rp->r_flags & R4COMMITWAIT) {
11586 			page_unlock(pp);
11587 			mutex_exit(&rp->r_statelock);
11588 			return;
11589 		}
11590 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11591 			pp->p_fsdata = C_COMMIT;
11592 			page_unlock(pp);
11593 			mutex_exit(&rp->r_statelock);
11594 			return;
11595 		}
11596 	}
11597 
11598 	/*
11599 	 * Check to see if there is a signal which would prevent an
11600 	 * attempt to commit the pages from being successful.  If so,
11601 	 * then don't bother with all of the work to gather pages and
11602 	 * generate the unsuccessful RPC.  Just return from here and
11603 	 * let the page be committed at some later time.
11604 	 */
11605 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11606 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11607 		sigunintr(&smask);
11608 		page_unlock(pp);
11609 		mutex_exit(&rp->r_statelock);
11610 		return;
11611 	}
11612 	sigunintr(&smask);
11613 
11614 	/*
11615 	 * We are starting to need to commit pages, so let's try
11616 	 * to commit as many as possible at once to reduce the
11617 	 * overhead.
11618 	 *
11619 	 * Set the `commit inprogress' state bit.  We must
11620 	 * first wait until any current one finishes.  Then
11621 	 * we initialize the c_pages list with this page.
11622 	 */
11623 	while (rp->r_flags & R4COMMIT) {
11624 		rp->r_flags |= R4COMMITWAIT;
11625 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11626 		rp->r_flags &= ~R4COMMITWAIT;
11627 	}
11628 	rp->r_flags |= R4COMMIT;
11629 	mutex_exit(&rp->r_statelock);
11630 	ASSERT(rp->r_commit.c_pages == NULL);
11631 	rp->r_commit.c_pages = pp;
11632 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11633 	rp->r_commit.c_commlen = PAGESIZE;
11634 
11635 	/*
11636 	 * Gather together all other pages which can be committed.
11637 	 * They will all be chained off r_commit.c_pages.
11638 	 */
11639 	nfs4_get_commit(vp);
11640 
11641 	/*
11642 	 * Clear the `commit inprogress' status and disconnect
11643 	 * the list of pages to be committed from the rnode.
11644 	 * At this same time, we also save the starting offset
11645 	 * and length of data to be committed on the server.
11646 	 */
11647 	plist = rp->r_commit.c_pages;
11648 	rp->r_commit.c_pages = NULL;
11649 	offset = rp->r_commit.c_commbase;
11650 	len = rp->r_commit.c_commlen;
11651 	mutex_enter(&rp->r_statelock);
11652 	rp->r_flags &= ~R4COMMIT;
11653 	cv_broadcast(&rp->r_commit.c_cv);
11654 	mutex_exit(&rp->r_statelock);
11655 
11656 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11657 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11658 		nfs4_async_commit(vp, plist, offset, len,
11659 		    cr, do_nfs4_async_commit);
11660 		return;
11661 	}
11662 
11663 	/*
11664 	 * Actually generate the COMMIT op over the wire operation.
11665 	 */
11666 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11667 
11668 	/*
11669 	 * If we got an error during the commit, just unlock all
11670 	 * of the pages.  The pages will get retransmitted to the
11671 	 * server during a putpage operation.
11672 	 */
11673 	if (error) {
11674 		while (plist != NULL) {
11675 			pptr = plist;
11676 			page_sub(&plist, pptr);
11677 			page_unlock(pptr);
11678 		}
11679 		return;
11680 	}
11681 
11682 	/*
11683 	 * We've tried as hard as we can to commit the data to stable
11684 	 * storage on the server.  We just unlock the rest of the pages
11685 	 * and clear the commit required state.  They will be put
11686 	 * onto the tail of the cachelist if they are nolonger
11687 	 * mapped.
11688 	 */
11689 	while (plist != pp) {
11690 		pptr = plist;
11691 		page_sub(&plist, pptr);
11692 		pptr->p_fsdata = C_NOCOMMIT;
11693 		page_unlock(pptr);
11694 	}
11695 
11696 	/*
11697 	 * It is possible that nfs4_commit didn't return error but
11698 	 * some other thread has modified the page we are going
11699 	 * to free/destroy.
11700 	 *    In this case we need to rewrite the page. Do an explicit check
11701 	 * before attempting to free/destroy the page. If modified, needs to
11702 	 * be rewritten so unlock the page and return.
11703 	 */
11704 	if (hat_ismod(pp)) {
11705 		pp->p_fsdata = C_NOCOMMIT;
11706 		page_unlock(pp);
11707 		return;
11708 	}
11709 
11710 	/*
11711 	 * Now, as appropriate, either free or destroy the page
11712 	 * that we were called with.
11713 	 */
11714 	pp->p_fsdata = C_NOCOMMIT;
11715 	if (fl == B_FREE)
11716 		page_free(pp, dn);
11717 	else
11718 		page_destroy(pp, dn);
11719 }
11720 
11721 /*
11722  * Commit requires that the current fh be the file written to.
11723  * The compound op structure is:
11724  *      PUTFH(file), COMMIT
11725  */
11726 static int
11727 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11728 {
11729 	COMPOUND4args_clnt args;
11730 	COMPOUND4res_clnt res;
11731 	COMMIT4res *cm_res;
11732 	nfs_argop4 argop[2];
11733 	nfs_resop4 *resop;
11734 	int doqueue;
11735 	mntinfo4_t *mi;
11736 	rnode4_t *rp;
11737 	cred_t *cred_otw = NULL;
11738 	bool_t needrecov = FALSE;
11739 	nfs4_recov_state_t recov_state;
11740 	nfs4_open_stream_t *osp = NULL;
11741 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11742 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11743 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11744 
11745 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11746 
11747 	rp = VTOR4(vp);
11748 
11749 	mi = VTOMI4(vp);
11750 	recov_state.rs_flags = 0;
11751 	recov_state.rs_num_retry_despite_err = 0;
11752 get_commit_cred:
11753 	/*
11754 	 * Releases the osp, if a valid open stream is provided.
11755 	 * Puts a hold on the cred_otw and the new osp (if found).
11756 	 */
11757 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11758 	    &first_time, &last_time);
11759 	args.ctag = TAG_COMMIT;
11760 recov_retry:
11761 	/*
11762 	 * Commit ops: putfh file; commit
11763 	 */
11764 	args.array_len = 2;
11765 	args.array = argop;
11766 
11767 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11768 	    &recov_state, NULL);
11769 	if (e.error) {
11770 		crfree(cred_otw);
11771 		if (osp != NULL)
11772 			open_stream_rele(osp, rp);
11773 		return (e.error);
11774 	}
11775 
11776 	/* putfh directory */
11777 	argop[0].argop = OP_CPUTFH;
11778 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11779 
11780 	/* commit */
11781 	argop[1].argop = OP_COMMIT;
11782 	argop[1].nfs_argop4_u.opcommit.offset = offset;
11783 	argop[1].nfs_argop4_u.opcommit.count = count;
11784 
11785 	doqueue = 1;
11786 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
11787 
11788 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
11789 	if (!needrecov && e.error) {
11790 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
11791 		    needrecov);
11792 		crfree(cred_otw);
11793 		if (e.error == EACCES && last_time == FALSE)
11794 			goto get_commit_cred;
11795 		if (osp != NULL)
11796 			open_stream_rele(osp, rp);
11797 		return (e.error);
11798 	}
11799 
11800 	if (needrecov) {
11801 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
11802 		    NULL, OP_COMMIT, NULL, NULL, NULL) == FALSE) {
11803 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11804 			    &recov_state, needrecov);
11805 			if (!e.error)
11806 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11807 			goto recov_retry;
11808 		}
11809 		if (e.error) {
11810 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11811 			    &recov_state, needrecov);
11812 			crfree(cred_otw);
11813 			if (osp != NULL)
11814 				open_stream_rele(osp, rp);
11815 			return (e.error);
11816 		}
11817 		/* fall through for res.status case */
11818 	}
11819 
11820 	if (res.status) {
11821 		e.error = geterrno4(res.status);
11822 		if (e.error == EACCES && last_time == FALSE) {
11823 			crfree(cred_otw);
11824 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11825 			    &recov_state, needrecov);
11826 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11827 			goto get_commit_cred;
11828 		}
11829 		/*
11830 		 * Can't do a nfs4_purge_stale_fh here because this
11831 		 * can cause a deadlock.  nfs4_commit can
11832 		 * be called from nfs4_dispose which can be called
11833 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
11834 		 * can call back to pvn_vplist_dirty.
11835 		 */
11836 		if (e.error == ESTALE) {
11837 			mutex_enter(&rp->r_statelock);
11838 			rp->r_flags |= R4STALE;
11839 			if (!rp->r_error)
11840 				rp->r_error = e.error;
11841 			mutex_exit(&rp->r_statelock);
11842 			PURGE_ATTRCACHE4(vp);
11843 		} else {
11844 			mutex_enter(&rp->r_statelock);
11845 			if (!rp->r_error)
11846 				rp->r_error = e.error;
11847 			mutex_exit(&rp->r_statelock);
11848 		}
11849 	} else {
11850 		ASSERT(rp->r_flags & R4HAVEVERF);
11851 		resop = &res.array[1];	/* commit res */
11852 		cm_res = &resop->nfs_resop4_u.opcommit;
11853 		mutex_enter(&rp->r_statelock);
11854 		if (cm_res->writeverf == rp->r_writeverf) {
11855 			mutex_exit(&rp->r_statelock);
11856 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11857 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11858 			    &recov_state, needrecov);
11859 			crfree(cred_otw);
11860 			if (osp != NULL)
11861 				open_stream_rele(osp, rp);
11862 			return (0);
11863 		}
11864 		nfs4_set_mod(vp);
11865 		rp->r_writeverf = cm_res->writeverf;
11866 		mutex_exit(&rp->r_statelock);
11867 		e.error = NFS_VERF_MISMATCH;
11868 	}
11869 
11870 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11871 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
11872 	crfree(cred_otw);
11873 	if (osp != NULL)
11874 		open_stream_rele(osp, rp);
11875 
11876 	return (e.error);
11877 }
11878 
11879 static void
11880 nfs4_set_mod(vnode_t *vp)
11881 {
11882 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11883 
11884 	/* make sure we're looking at the master vnode, not a shadow */
11885 	pvn_vplist_setdirty(RTOV4(VTOR4(vp)), nfs_setmod_check);
11886 }
11887 
11888 /*
11889  * This function is used to gather a page list of the pages which
11890  * can be committed on the server.
11891  *
11892  * The calling thread must have set R4COMMIT.  This bit is used to
11893  * serialize access to the commit structure in the rnode.  As long
11894  * as the thread has set R4COMMIT, then it can manipulate the commit
11895  * structure without requiring any other locks.
11896  *
11897  * When this function is called from nfs4_dispose() the page passed
11898  * into nfs4_dispose() will be SE_EXCL locked, and so this function
11899  * will skip it. This is not a problem since we initially add the
11900  * page to the r_commit page list.
11901  *
11902  */
11903 static void
11904 nfs4_get_commit(vnode_t *vp)
11905 {
11906 	rnode4_t *rp;
11907 	page_t *pp;
11908 	kmutex_t *vphm;
11909 
11910 	rp = VTOR4(vp);
11911 
11912 	ASSERT(rp->r_flags & R4COMMIT);
11913 
11914 	/* make sure we're looking at the master vnode, not a shadow */
11915 
11916 	if (IS_SHADOW(vp, rp))
11917 		vp = RTOV4(rp);
11918 
11919 	vphm = page_vnode_mutex(vp);
11920 	mutex_enter(vphm);
11921 
11922 	/*
11923 	 * If there are no pages associated with this vnode, then
11924 	 * just return.
11925 	 */
11926 	if ((pp = vp->v_pages) == NULL) {
11927 		mutex_exit(vphm);
11928 		return;
11929 	}
11930 
11931 	/*
11932 	 * Step through all of the pages associated with this vnode
11933 	 * looking for pages which need to be committed.
11934 	 */
11935 	do {
11936 		/* Skip marker pages. */
11937 		if (pp->p_hash == PVN_VPLIST_HASH_TAG)
11938 			continue;
11939 
11940 		/*
11941 		 * First short-cut everything (without the page_lock)
11942 		 * and see if this page does not need to be committed
11943 		 * or is modified if so then we'll just skip it.
11944 		 */
11945 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
11946 			continue;
11947 
11948 		/*
11949 		 * Attempt to lock the page.  If we can't, then
11950 		 * someone else is messing with it or we have been
11951 		 * called from nfs4_dispose and this is the page that
11952 		 * nfs4_dispose was called with.. anyway just skip it.
11953 		 */
11954 		if (!page_trylock(pp, SE_EXCL))
11955 			continue;
11956 
11957 		/*
11958 		 * Lets check again now that we have the page lock.
11959 		 */
11960 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11961 			page_unlock(pp);
11962 			continue;
11963 		}
11964 
11965 		/* this had better not be a free page */
11966 		ASSERT(PP_ISFREE(pp) == 0);
11967 
11968 		/*
11969 		 * The page needs to be committed and we locked it.
11970 		 * Update the base and length parameters and add it
11971 		 * to r_pages.
11972 		 */
11973 		if (rp->r_commit.c_pages == NULL) {
11974 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11975 			rp->r_commit.c_commlen = PAGESIZE;
11976 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
11977 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
11978 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
11979 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11980 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
11981 		    <= pp->p_offset) {
11982 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11983 			    rp->r_commit.c_commbase + PAGESIZE;
11984 		}
11985 		page_add(&rp->r_commit.c_pages, pp);
11986 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11987 
11988 	mutex_exit(vphm);
11989 }
11990 
11991 /*
11992  * This routine is used to gather together a page list of the pages
11993  * which are to be committed on the server.  This routine must not
11994  * be called if the calling thread holds any locked pages.
11995  *
11996  * The calling thread must have set R4COMMIT.  This bit is used to
11997  * serialize access to the commit structure in the rnode.  As long
11998  * as the thread has set R4COMMIT, then it can manipulate the commit
11999  * structure without requiring any other locks.
12000  */
12001 static void
12002 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
12003 {
12004 
12005 	rnode4_t *rp;
12006 	page_t *pp;
12007 	u_offset_t end;
12008 	u_offset_t off;
12009 	ASSERT(len != 0);
12010 	rp = VTOR4(vp);
12011 	ASSERT(rp->r_flags & R4COMMIT);
12012 
12013 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12014 
12015 	/* make sure we're looking at the master vnode, not a shadow */
12016 
12017 	if (IS_SHADOW(vp, rp))
12018 		vp = RTOV4(rp);
12019 
12020 	/*
12021 	 * If there are no pages associated with this vnode, then
12022 	 * just return.
12023 	 */
12024 	if ((pp = vp->v_pages) == NULL)
12025 		return;
12026 	/*
12027 	 * Calculate the ending offset.
12028 	 */
12029 	end = soff + len;
12030 	for (off = soff; off < end; off += PAGESIZE) {
12031 		/*
12032 		 * Lookup each page by vp, offset.
12033 		 */
12034 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
12035 			continue;
12036 		/*
12037 		 * If this page does not need to be committed or is
12038 		 * modified, then just skip it.
12039 		 */
12040 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
12041 			page_unlock(pp);
12042 			continue;
12043 		}
12044 
12045 		ASSERT(PP_ISFREE(pp) == 0);
12046 		/*
12047 		 * The page needs to be committed and we locked it.
12048 		 * Update the base and length parameters and add it
12049 		 * to r_pages.
12050 		 */
12051 		if (rp->r_commit.c_pages == NULL) {
12052 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
12053 			rp->r_commit.c_commlen = PAGESIZE;
12054 		} else {
12055 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
12056 			    rp->r_commit.c_commbase + PAGESIZE;
12057 		}
12058 		page_add(&rp->r_commit.c_pages, pp);
12059 	}
12060 }
12061 
12062 /*
12063  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
12064  * Flushes and commits data to the server.
12065  */
12066 static int
12067 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
12068 {
12069 	int error;
12070 	verifier4 write_verf;
12071 	rnode4_t *rp = VTOR4(vp);
12072 
12073 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12074 
12075 	/*
12076 	 * Flush the data portion of the file and then commit any
12077 	 * portions which need to be committed.  This may need to
12078 	 * be done twice if the server has changed state since
12079 	 * data was last written.  The data will need to be
12080 	 * rewritten to the server and then a new commit done.
12081 	 *
12082 	 * In fact, this may need to be done several times if the
12083 	 * server is having problems and crashing while we are
12084 	 * attempting to do this.
12085 	 */
12086 
12087 top:
12088 	/*
12089 	 * Do a flush based on the poff and plen arguments.  This
12090 	 * will synchronously write out any modified pages in the
12091 	 * range specified by (poff, plen). This starts all of the
12092 	 * i/o operations which will be waited for in the next
12093 	 * call to nfs4_putpage
12094 	 */
12095 
12096 	mutex_enter(&rp->r_statelock);
12097 	write_verf = rp->r_writeverf;
12098 	mutex_exit(&rp->r_statelock);
12099 
12100 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr, NULL);
12101 	if (error == EAGAIN)
12102 		error = 0;
12103 
12104 	/*
12105 	 * Do a flush based on the poff and plen arguments.  This
12106 	 * will synchronously write out any modified pages in the
12107 	 * range specified by (poff, plen) and wait until all of
12108 	 * the asynchronous i/o's in that range are done as well.
12109 	 */
12110 	if (!error)
12111 		error = nfs4_putpage(vp, poff, plen, 0, cr, NULL);
12112 
12113 	if (error)
12114 		return (error);
12115 
12116 	mutex_enter(&rp->r_statelock);
12117 	if (rp->r_writeverf != write_verf) {
12118 		mutex_exit(&rp->r_statelock);
12119 		goto top;
12120 	}
12121 	mutex_exit(&rp->r_statelock);
12122 
12123 	/*
12124 	 * Now commit any pages which might need to be committed.
12125 	 * If the error, NFS_VERF_MISMATCH, is returned, then
12126 	 * start over with the flush operation.
12127 	 */
12128 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
12129 
12130 	if (error == NFS_VERF_MISMATCH)
12131 		goto top;
12132 
12133 	return (error);
12134 }
12135 
12136 /*
12137  * nfs4_commit_vp()  will wait for other pending commits and
12138  * will either commit the whole file or a range, plen dictates
12139  * if we commit whole file. a value of zero indicates the whole
12140  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
12141  */
12142 static int
12143 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12144     cred_t *cr, int wait_on_writes)
12145 {
12146 	rnode4_t *rp;
12147 	page_t *plist;
12148 	offset3 offset;
12149 	count3 len;
12150 
12151 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12152 
12153 	rp = VTOR4(vp);
12154 
12155 	/*
12156 	 *  before we gather commitable pages make
12157 	 *  sure there are no outstanding async writes
12158 	 */
12159 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12160 		mutex_enter(&rp->r_statelock);
12161 		while (rp->r_count > 0) {
12162 			cv_wait(&rp->r_cv, &rp->r_statelock);
12163 		}
12164 		mutex_exit(&rp->r_statelock);
12165 	}
12166 
12167 	/*
12168 	 * Set the `commit inprogress' state bit.  We must
12169 	 * first wait until any current one finishes.
12170 	 */
12171 	mutex_enter(&rp->r_statelock);
12172 	while (rp->r_flags & R4COMMIT) {
12173 		rp->r_flags |= R4COMMITWAIT;
12174 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12175 		rp->r_flags &= ~R4COMMITWAIT;
12176 	}
12177 	rp->r_flags |= R4COMMIT;
12178 	mutex_exit(&rp->r_statelock);
12179 
12180 	/*
12181 	 * Gather all of the pages which need to be
12182 	 * committed.
12183 	 */
12184 	if (plen == 0)
12185 		nfs4_get_commit(vp);
12186 	else
12187 		nfs4_get_commit_range(vp, poff, plen);
12188 
12189 	/*
12190 	 * Clear the `commit inprogress' bit and disconnect the
12191 	 * page list which was gathered by nfs4_get_commit.
12192 	 */
12193 	plist = rp->r_commit.c_pages;
12194 	rp->r_commit.c_pages = NULL;
12195 	offset = rp->r_commit.c_commbase;
12196 	len = rp->r_commit.c_commlen;
12197 	mutex_enter(&rp->r_statelock);
12198 	rp->r_flags &= ~R4COMMIT;
12199 	cv_broadcast(&rp->r_commit.c_cv);
12200 	mutex_exit(&rp->r_statelock);
12201 
12202 	/*
12203 	 * If any pages need to be committed, commit them and
12204 	 * then unlock them so that they can be freed some
12205 	 * time later.
12206 	 */
12207 	if (plist == NULL)
12208 		return (0);
12209 
12210 	/*
12211 	 * No error occurred during the flush portion
12212 	 * of this operation, so now attempt to commit
12213 	 * the data to stable storage on the server.
12214 	 *
12215 	 * This will unlock all of the pages on the list.
12216 	 */
12217 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12218 }
12219 
12220 static int
12221 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12222     cred_t *cr)
12223 {
12224 	int error;
12225 	page_t *pp;
12226 
12227 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12228 
12229 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12230 
12231 	/*
12232 	 * If we got an error, then just unlock all of the pages
12233 	 * on the list.
12234 	 */
12235 	if (error) {
12236 		while (plist != NULL) {
12237 			pp = plist;
12238 			page_sub(&plist, pp);
12239 			page_unlock(pp);
12240 		}
12241 		return (error);
12242 	}
12243 	/*
12244 	 * We've tried as hard as we can to commit the data to stable
12245 	 * storage on the server.  We just unlock the pages and clear
12246 	 * the commit required state.  They will get freed later.
12247 	 */
12248 	while (plist != NULL) {
12249 		pp = plist;
12250 		page_sub(&plist, pp);
12251 		pp->p_fsdata = C_NOCOMMIT;
12252 		page_unlock(pp);
12253 	}
12254 
12255 	return (error);
12256 }
12257 
12258 static void
12259 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12260     cred_t *cr)
12261 {
12262 
12263 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12264 }
12265 
12266 /*ARGSUSED*/
12267 static int
12268 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12269     caller_context_t *ct)
12270 {
12271 	int		error = 0;
12272 	mntinfo4_t	*mi;
12273 	vattr_t		va;
12274 	vsecattr_t	nfsace4_vsap;
12275 
12276 	mi = VTOMI4(vp);
12277 	if (nfs_zone() != mi->mi_zone)
12278 		return (EIO);
12279 	if (mi->mi_flags & MI4_ACL) {
12280 		/* if we have a delegation, return it */
12281 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12282 			(void) nfs4delegreturn(VTOR4(vp),
12283 			    NFS4_DR_REOPEN|NFS4_DR_PUSH);
12284 
12285 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12286 		    NFS4_ACL_SET);
12287 		if (error) /* EINVAL */
12288 			return (error);
12289 
12290 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12291 			/*
12292 			 * These are aclent_t type entries.
12293 			 */
12294 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12295 			    vp->v_type == VDIR, FALSE);
12296 			if (error)
12297 				return (error);
12298 		} else {
12299 			/*
12300 			 * These are ace_t type entries.
12301 			 */
12302 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12303 			    FALSE);
12304 			if (error)
12305 				return (error);
12306 		}
12307 		bzero(&va, sizeof (va));
12308 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12309 		vs_ace4_destroy(&nfsace4_vsap);
12310 		return (error);
12311 	}
12312 	return (ENOSYS);
12313 }
12314 
12315 /* ARGSUSED */
12316 int
12317 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12318     caller_context_t *ct)
12319 {
12320 	int		error;
12321 	mntinfo4_t	*mi;
12322 	nfs4_ga_res_t	gar;
12323 	rnode4_t	*rp = VTOR4(vp);
12324 
12325 	mi = VTOMI4(vp);
12326 	if (nfs_zone() != mi->mi_zone)
12327 		return (EIO);
12328 
12329 	bzero(&gar, sizeof (gar));
12330 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12331 
12332 	/*
12333 	 * vsecattr->vsa_mask holds the original acl request mask.
12334 	 * This is needed when determining what to return.
12335 	 * (See: nfs4_create_getsecattr_return())
12336 	 */
12337 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12338 	if (error) /* EINVAL */
12339 		return (error);
12340 
12341 	/*
12342 	 * If this is a referral stub, don't try to go OTW for an ACL
12343 	 */
12344 	if (RP_ISSTUB_REFERRAL(VTOR4(vp)))
12345 		return (fs_fab_acl(vp, vsecattr, flag, cr, ct));
12346 
12347 	if (mi->mi_flags & MI4_ACL) {
12348 		/*
12349 		 * Check if the data is cached and the cache is valid.  If it
12350 		 * is we don't go over the wire.
12351 		 */
12352 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12353 			mutex_enter(&rp->r_statelock);
12354 			if (rp->r_secattr != NULL) {
12355 				error = nfs4_create_getsecattr_return(
12356 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12357 				    rp->r_attr.va_gid,
12358 				    vp->v_type == VDIR);
12359 				if (!error) { /* error == 0 - Success! */
12360 					mutex_exit(&rp->r_statelock);
12361 					return (error);
12362 				}
12363 			}
12364 			mutex_exit(&rp->r_statelock);
12365 		}
12366 
12367 		/*
12368 		 * The getattr otw call will always get both the acl, in
12369 		 * the form of a list of nfsace4's, and the number of acl
12370 		 * entries; independent of the value of gar.n4g_va.va_mask.
12371 		 */
12372 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12373 		if (error) {
12374 			vs_ace4_destroy(&gar.n4g_vsa);
12375 			if (error == ENOTSUP || error == EOPNOTSUPP)
12376 				error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12377 			return (error);
12378 		}
12379 
12380 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12381 			/*
12382 			 * No error was returned, but according to the response
12383 			 * bitmap, neither was an acl.
12384 			 */
12385 			vs_ace4_destroy(&gar.n4g_vsa);
12386 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12387 			return (error);
12388 		}
12389 
12390 		/*
12391 		 * Update the cache with the ACL.
12392 		 */
12393 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12394 
12395 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12396 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12397 		    vp->v_type == VDIR);
12398 		vs_ace4_destroy(&gar.n4g_vsa);
12399 		if ((error) && (vsecattr->vsa_mask &
12400 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12401 		    (error != EACCES)) {
12402 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12403 		}
12404 		return (error);
12405 	}
12406 	error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12407 	return (error);
12408 }
12409 
12410 /*
12411  * The function returns:
12412  *	- 0 (zero) if the passed in "acl_mask" is a valid request.
12413  *	- EINVAL if the passed in "acl_mask" is an invalid request.
12414  *
12415  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12416  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12417  *
12418  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12419  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12420  * - We have a count field set without the corresponding acl field set. (e.g. -
12421  * VSA_ACECNT is set, but VSA_ACE is not)
12422  */
12423 static int
12424 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12425 {
12426 	/* Shortcut the masks that are always valid. */
12427 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12428 		return (0);
12429 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12430 		return (0);
12431 
12432 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12433 		/*
12434 		 * We can't have any VSA_ACL type stuff in the mask now.
12435 		 */
12436 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12437 		    VSA_DFACLCNT))
12438 			return (EINVAL);
12439 
12440 		if (op == NFS4_ACL_SET) {
12441 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12442 				return (EINVAL);
12443 		}
12444 	}
12445 
12446 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12447 		/*
12448 		 * We can't have any VSA_ACE type stuff in the mask now.
12449 		 */
12450 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12451 			return (EINVAL);
12452 
12453 		if (op == NFS4_ACL_SET) {
12454 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12455 				return (EINVAL);
12456 
12457 			if ((acl_mask & VSA_DFACLCNT) &&
12458 			    !(acl_mask & VSA_DFACL))
12459 				return (EINVAL);
12460 		}
12461 	}
12462 	return (0);
12463 }
12464 
12465 /*
12466  * The theory behind creating the correct getsecattr return is simply this:
12467  * "Don't return anything that the caller is not expecting to have to free."
12468  */
12469 static int
12470 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12471     uid_t uid, gid_t gid, int isdir)
12472 {
12473 	int error = 0;
12474 	/* Save the mask since the translators modify it. */
12475 	uint_t	orig_mask = vsap->vsa_mask;
12476 
12477 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12478 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid, FALSE);
12479 
12480 		if (error)
12481 			return (error);
12482 
12483 		/*
12484 		 * If the caller only asked for the ace count (VSA_ACECNT)
12485 		 * don't give them the full acl (VSA_ACE), free it.
12486 		 */
12487 		if (!orig_mask & VSA_ACE) {
12488 			if (vsap->vsa_aclentp != NULL) {
12489 				kmem_free(vsap->vsa_aclentp,
12490 				    vsap->vsa_aclcnt * sizeof (ace_t));
12491 				vsap->vsa_aclentp = NULL;
12492 			}
12493 		}
12494 		vsap->vsa_mask = orig_mask;
12495 
12496 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12497 	    VSA_DFACLCNT)) {
12498 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12499 		    isdir, FALSE);
12500 
12501 		if (error)
12502 			return (error);
12503 
12504 		/*
12505 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12506 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12507 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12508 		 */
12509 		if (!orig_mask & VSA_ACL) {
12510 			if (vsap->vsa_aclentp != NULL) {
12511 				kmem_free(vsap->vsa_aclentp,
12512 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12513 				vsap->vsa_aclentp = NULL;
12514 			}
12515 		}
12516 
12517 		if (!orig_mask & VSA_DFACL) {
12518 			if (vsap->vsa_dfaclentp != NULL) {
12519 				kmem_free(vsap->vsa_dfaclentp,
12520 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12521 				vsap->vsa_dfaclentp = NULL;
12522 			}
12523 		}
12524 		vsap->vsa_mask = orig_mask;
12525 	}
12526 	return (0);
12527 }
12528 
12529 /* ARGSUSED */
12530 int
12531 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr,
12532     caller_context_t *ct)
12533 {
12534 	int error;
12535 
12536 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12537 		return (EIO);
12538 	/*
12539 	 * check for valid cmd parameter
12540 	 */
12541 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12542 		return (EINVAL);
12543 
12544 	/*
12545 	 * Check access permissions
12546 	 */
12547 	if ((cmd & F_SHARE) &&
12548 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12549 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12550 		return (EBADF);
12551 
12552 	/*
12553 	 * If the filesystem is mounted using local locking, pass the
12554 	 * request off to the local share code.
12555 	 */
12556 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12557 		return (fs_shrlock(vp, cmd, shr, flag, cr, ct));
12558 
12559 	switch (cmd) {
12560 	case F_SHARE:
12561 	case F_UNSHARE:
12562 		/*
12563 		 * This will be properly implemented later,
12564 		 * see RFE: 4823948 .
12565 		 */
12566 		error = EAGAIN;
12567 		break;
12568 
12569 	case F_HASREMOTELOCKS:
12570 		/*
12571 		 * NFS client can't store remote locks itself
12572 		 */
12573 		shr->s_access = 0;
12574 		error = 0;
12575 		break;
12576 
12577 	default:
12578 		error = EINVAL;
12579 		break;
12580 	}
12581 
12582 	return (error);
12583 }
12584 
12585 /*
12586  * Common code called by directory ops to update the attrcache
12587  */
12588 static int
12589 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12590     hrtime_t t, vnode_t *vp, cred_t *cr)
12591 {
12592 	int error = 0;
12593 
12594 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12595 
12596 	if (status != NFS4_OK) {
12597 		/* getattr not done or failed */
12598 		PURGE_ATTRCACHE4(vp);
12599 		return (error);
12600 	}
12601 
12602 	if (garp) {
12603 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12604 	} else {
12605 		PURGE_ATTRCACHE4(vp);
12606 	}
12607 	return (error);
12608 }
12609 
12610 /*
12611  * Update directory caches for directory modification ops (link, rename, etc.)
12612  * When dinfo is NULL, manage dircaches in the old way.
12613  */
12614 static void
12615 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12616     dirattr_info_t *dinfo)
12617 {
12618 	rnode4_t	*drp = VTOR4(dvp);
12619 
12620 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12621 
12622 	/* Purge rddir cache for dir since it changed */
12623 	if (drp->r_dir != NULL)
12624 		nfs4_purge_rddir_cache(dvp);
12625 
12626 	/*
12627 	 * If caller provided dinfo, then use it to manage dir caches.
12628 	 */
12629 	if (dinfo != NULL) {
12630 		if (vp != NULL) {
12631 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12632 			if (!VTOR4(vp)->created_v4) {
12633 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12634 				dnlc_update(dvp, nm, vp);
12635 			} else {
12636 				/*
12637 				 * XXX don't update if the created_v4 flag is
12638 				 * set
12639 				 */
12640 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12641 				NFS4_DEBUG(nfs4_client_state_debug,
12642 				    (CE_NOTE, "nfs4_update_dircaches: "
12643 				    "don't update dnlc: created_v4 flag"));
12644 			}
12645 		}
12646 
12647 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12648 		    dinfo->di_cred, FALSE, cinfo);
12649 
12650 		return;
12651 	}
12652 
12653 	/*
12654 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12655 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12656 	 * attrs, the dir's attrs must be purged.
12657 	 *
12658 	 * XXX this check and dnlc update/purge should really be atomic,
12659 	 * XXX but can't use rnode statelock because it'll deadlock in
12660 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12661 	 * XXX does occur.
12662 	 *
12663 	 * XXX We also may want to check that atomic is true in the
12664 	 * XXX change_info struct. If it is not, the change_info may
12665 	 * XXX reflect changes by more than one clients which means that
12666 	 * XXX our cache may not be valid.
12667 	 */
12668 	PURGE_ATTRCACHE4(dvp);
12669 	if (drp->r_change == cinfo->before) {
12670 		/* no changes took place in the directory prior to our link */
12671 		if (vp != NULL) {
12672 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12673 			if (!VTOR4(vp)->created_v4) {
12674 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12675 				dnlc_update(dvp, nm, vp);
12676 			} else {
12677 				/*
12678 				 * XXX dont' update if the created_v4 flag
12679 				 * is set
12680 				 */
12681 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12682 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12683 				    "nfs4_update_dircaches: don't"
12684 				    " update dnlc: created_v4 flag"));
12685 			}
12686 		}
12687 	} else {
12688 		/* Another client modified directory - purge its dnlc cache */
12689 		dnlc_purge_vp(dvp);
12690 	}
12691 }
12692 
12693 /*
12694  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12695  * file.
12696  *
12697  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12698  * file (ie: client recovery) and otherwise set to FALSE.
12699  *
12700  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12701  * initiated) calling functions.
12702  *
12703  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12704  * of resending a 'lost' open request.
12705  *
12706  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12707  * server that hands out BAD_SEQID on open confirm.
12708  *
12709  * Errors are returned via the nfs4_error_t parameter.
12710  */
12711 void
12712 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12713     bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12714     bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12715 {
12716 	COMPOUND4args_clnt args;
12717 	COMPOUND4res_clnt res;
12718 	nfs_argop4 argop[2];
12719 	nfs_resop4 *resop;
12720 	int doqueue = 1;
12721 	mntinfo4_t *mi;
12722 	OPEN_CONFIRM4args *open_confirm_args;
12723 	int needrecov;
12724 
12725 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12726 #if DEBUG
12727 	mutex_enter(&oop->oo_lock);
12728 	ASSERT(oop->oo_seqid_inuse);
12729 	mutex_exit(&oop->oo_lock);
12730 #endif
12731 
12732 recov_retry_confirm:
12733 	nfs4_error_zinit(ep);
12734 	*retry_open = FALSE;
12735 
12736 	if (resend)
12737 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12738 	else
12739 		args.ctag = TAG_OPEN_CONFIRM;
12740 
12741 	args.array_len = 2;
12742 	args.array = argop;
12743 
12744 	/* putfh target fh */
12745 	argop[0].argop = OP_CPUTFH;
12746 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12747 
12748 	argop[1].argop = OP_OPEN_CONFIRM;
12749 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12750 
12751 	(*seqid) += 1;
12752 	open_confirm_args->seqid = *seqid;
12753 	open_confirm_args->open_stateid = *stateid;
12754 
12755 	mi = VTOMI4(vp);
12756 
12757 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12758 
12759 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12760 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12761 	}
12762 
12763 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12764 	if (!needrecov && ep->error)
12765 		return;
12766 
12767 	if (needrecov) {
12768 		bool_t abort = FALSE;
12769 
12770 		if (reopening_file == FALSE) {
12771 			nfs4_bseqid_entry_t *bsep = NULL;
12772 
12773 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12774 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12775 				    vp, 0, args.ctag,
12776 				    open_confirm_args->seqid);
12777 
12778 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
12779 			    NULL, NULL, OP_OPEN_CONFIRM, bsep, NULL, NULL);
12780 			if (bsep) {
12781 				kmem_free(bsep, sizeof (*bsep));
12782 				if (num_bseqid_retryp &&
12783 				    --(*num_bseqid_retryp) == 0)
12784 					abort = TRUE;
12785 			}
12786 		}
12787 		if ((ep->error == ETIMEDOUT ||
12788 		    res.status == NFS4ERR_RESOURCE) &&
12789 		    abort == FALSE && resend == FALSE) {
12790 			if (!ep->error)
12791 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12792 
12793 			delay(SEC_TO_TICK(confirm_retry_sec));
12794 			goto recov_retry_confirm;
12795 		}
12796 		/* State may have changed so retry the entire OPEN op */
12797 		if (abort == FALSE)
12798 			*retry_open = TRUE;
12799 		else
12800 			*retry_open = FALSE;
12801 		if (!ep->error)
12802 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12803 		return;
12804 	}
12805 
12806 	if (res.status) {
12807 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12808 		return;
12809 	}
12810 
12811 	resop = &res.array[1];  /* open confirm res */
12812 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
12813 	    stateid, sizeof (*stateid));
12814 
12815 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12816 }
12817 
12818 /*
12819  * Return the credentials associated with a client state object.  The
12820  * caller is responsible for freeing the credentials.
12821  */
12822 
12823 static cred_t *
12824 state_to_cred(nfs4_open_stream_t *osp)
12825 {
12826 	cred_t *cr;
12827 
12828 	/*
12829 	 * It's ok to not lock the open stream and open owner to get
12830 	 * the oo_cred since this is only written once (upon creation)
12831 	 * and will not change.
12832 	 */
12833 	cr = osp->os_open_owner->oo_cred;
12834 	crhold(cr);
12835 
12836 	return (cr);
12837 }
12838 
12839 /*
12840  * nfs4_find_sysid
12841  *
12842  * Find the sysid for the knetconfig associated with the given mi.
12843  */
12844 static struct lm_sysid *
12845 nfs4_find_sysid(mntinfo4_t *mi)
12846 {
12847 	ASSERT(nfs_zone() == mi->mi_zone);
12848 
12849 	/*
12850 	 * Switch from RDMA knconf to original mount knconf
12851 	 */
12852 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
12853 	    mi->mi_curr_serv->sv_hostname, NULL));
12854 }
12855 
12856 #ifdef DEBUG
12857 /*
12858  * Return a string version of the call type for easy reading.
12859  */
12860 static char *
12861 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
12862 {
12863 	switch (ctype) {
12864 	case NFS4_LCK_CTYPE_NORM:
12865 		return ("NORMAL");
12866 	case NFS4_LCK_CTYPE_RECLAIM:
12867 		return ("RECLAIM");
12868 	case NFS4_LCK_CTYPE_RESEND:
12869 		return ("RESEND");
12870 	case NFS4_LCK_CTYPE_REINSTATE:
12871 		return ("REINSTATE");
12872 	default:
12873 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
12874 		    "type %d", ctype);
12875 		return ("");
12876 	}
12877 }
12878 #endif
12879 
12880 /*
12881  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
12882  * Unlock requests don't have an over-the-wire locktype, so we just return
12883  * something non-threatening.
12884  */
12885 
12886 static nfs_lock_type4
12887 flk_to_locktype(int cmd, int l_type)
12888 {
12889 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
12890 
12891 	switch (l_type) {
12892 	case F_UNLCK:
12893 		return (READ_LT);
12894 	case F_RDLCK:
12895 		if (cmd == F_SETLK)
12896 			return (READ_LT);
12897 		else
12898 			return (READW_LT);
12899 	case F_WRLCK:
12900 		if (cmd == F_SETLK)
12901 			return (WRITE_LT);
12902 		else
12903 			return (WRITEW_LT);
12904 	}
12905 	panic("flk_to_locktype");
12906 	/*NOTREACHED*/
12907 }
12908 
12909 /*
12910  * Do some preliminary checks for nfs4frlock.
12911  */
12912 static int
12913 nfs4frlock_validate_args(int cmd, flock64_t *flk, int flag, vnode_t *vp,
12914     u_offset_t offset)
12915 {
12916 	int error = 0;
12917 
12918 	/*
12919 	 * If we are setting a lock, check that the file is opened
12920 	 * with the correct mode.
12921 	 */
12922 	if (cmd == F_SETLK || cmd == F_SETLKW) {
12923 		if ((flk->l_type == F_RDLCK && (flag & FREAD) == 0) ||
12924 		    (flk->l_type == F_WRLCK && (flag & FWRITE) == 0)) {
12925 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12926 			    "nfs4frlock_validate_args: file was opened with "
12927 			    "incorrect mode"));
12928 			return (EBADF);
12929 		}
12930 	}
12931 
12932 	/* Convert the offset. It may need to be restored before returning. */
12933 	if (error = convoff(vp, flk, 0, offset)) {
12934 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12935 		    "nfs4frlock_validate_args: convoff  =>  error= %d\n",
12936 		    error));
12937 		return (error);
12938 	}
12939 
12940 	return (error);
12941 }
12942 
12943 /*
12944  * Set the flock64's lm_sysid for nfs4frlock.
12945  */
12946 static int
12947 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
12948 {
12949 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12950 
12951 	/* Find the lm_sysid */
12952 	*lspp = nfs4_find_sysid(VTOMI4(vp));
12953 
12954 	if (*lspp == NULL) {
12955 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12956 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
12957 		return (ENOLCK);
12958 	}
12959 
12960 	flk->l_sysid = lm_sysidt(*lspp);
12961 
12962 	return (0);
12963 }
12964 
12965 /*
12966  * Do the remaining preliminary setup for nfs4frlock.
12967  */
12968 static void
12969 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
12970     flock64_t *flk, short *whencep, vnode_t *vp, cred_t *search_cr,
12971     cred_t **cred_otw)
12972 {
12973 	/*
12974 	 * set tick_delay to the base delay time.
12975 	 * (NFS4_BASE_WAIT_TIME is in secs)
12976 	 */
12977 
12978 	*tick_delayp = drv_usectohz(NFS4_BASE_WAIT_TIME * 1000 * 1000);
12979 
12980 	/*
12981 	 * If lock is relative to EOF, we need the newest length of the
12982 	 * file. Therefore invalidate the ATTR_CACHE.
12983 	 */
12984 
12985 	*whencep = flk->l_whence;
12986 
12987 	if (*whencep == 2)		/* SEEK_END */
12988 		PURGE_ATTRCACHE4(vp);
12989 
12990 	recov_statep->rs_flags = 0;
12991 	recov_statep->rs_num_retry_despite_err = 0;
12992 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
12993 }
12994 
12995 /*
12996  * Initialize and allocate the data structures necessary for
12997  * the nfs4frlock call.
12998  * Allocates argsp's op array.
12999  */
13000 static void
13001 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
13002     nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
13003     bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
13004     bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
13005 {
13006 	int		argoplist_size;
13007 	int		num_ops = 2;
13008 
13009 	*retry = FALSE;
13010 	*did_start_fop = FALSE;
13011 	*skip_get_err = FALSE;
13012 	lost_rqstp->lr_op = 0;
13013 	argoplist_size  = num_ops * sizeof (nfs_argop4);
13014 	/* fill array with zero */
13015 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
13016 
13017 	*argspp = argsp;
13018 	*respp = NULL;
13019 
13020 	argsp->array_len = num_ops;
13021 	argsp->array = *argopp;
13022 
13023 	/* initialize in case of error; will get real value down below */
13024 	argsp->ctag = TAG_NONE;
13025 
13026 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
13027 		*op_hintp = OH_LOCKU;
13028 	else
13029 		*op_hintp = OH_OTHER;
13030 }
13031 
13032 /*
13033  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
13034  * the proper nfs4_server_t for this instance of nfs4frlock.
13035  * Returns 0 (success) or an errno value.
13036  */
13037 static int
13038 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
13039     nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
13040     bool_t *did_start_fop, bool_t *startrecovp)
13041 {
13042 	int error = 0;
13043 	rnode4_t *rp;
13044 
13045 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13046 
13047 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13048 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
13049 		    recov_statep, startrecovp);
13050 		if (error)
13051 			return (error);
13052 		*did_start_fop = TRUE;
13053 	} else {
13054 		*did_start_fop = FALSE;
13055 		*startrecovp = FALSE;
13056 	}
13057 
13058 	if (!error) {
13059 		rp = VTOR4(vp);
13060 
13061 		/* If the file failed recovery, just quit. */
13062 		mutex_enter(&rp->r_statelock);
13063 		if (rp->r_flags & R4RECOVERR) {
13064 			error = EIO;
13065 		}
13066 		mutex_exit(&rp->r_statelock);
13067 	}
13068 
13069 	return (error);
13070 }
13071 
13072 /*
13073  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
13074  * resend nfs4frlock call is initiated by the recovery framework.
13075  * Acquires the lop and oop seqid synchronization.
13076  */
13077 static void
13078 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
13079     COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
13080     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13081     LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
13082 {
13083 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
13084 	int error;
13085 
13086 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
13087 	    (CE_NOTE,
13088 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
13089 	ASSERT(resend_rqstp != NULL);
13090 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
13091 	    resend_rqstp->lr_op == OP_LOCKU);
13092 
13093 	*oopp = resend_rqstp->lr_oop;
13094 	if (resend_rqstp->lr_oop) {
13095 		open_owner_hold(resend_rqstp->lr_oop);
13096 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
13097 		ASSERT(error == 0);	/* recov thread always succeeds */
13098 	}
13099 
13100 	/* Must resend this lost lock/locku request. */
13101 	ASSERT(resend_rqstp->lr_lop != NULL);
13102 	*lopp = resend_rqstp->lr_lop;
13103 	lock_owner_hold(resend_rqstp->lr_lop);
13104 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
13105 	ASSERT(error == 0);	/* recov thread always succeeds */
13106 
13107 	*ospp = resend_rqstp->lr_osp;
13108 	if (*ospp)
13109 		open_stream_hold(resend_rqstp->lr_osp);
13110 
13111 	if (resend_rqstp->lr_op == OP_LOCK) {
13112 		LOCK4args *lock_args;
13113 
13114 		argop->argop = OP_LOCK;
13115 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
13116 		lock_args->locktype = resend_rqstp->lr_locktype;
13117 		lock_args->reclaim =
13118 		    (resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
13119 		lock_args->offset = resend_rqstp->lr_flk->l_start;
13120 		lock_args->length = resend_rqstp->lr_flk->l_len;
13121 		if (lock_args->length == 0)
13122 			lock_args->length = ~lock_args->length;
13123 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
13124 		    mi2clientid(mi), &lock_args->locker);
13125 
13126 		switch (resend_rqstp->lr_ctype) {
13127 		case NFS4_LCK_CTYPE_RESEND:
13128 			argsp->ctag = TAG_LOCK_RESEND;
13129 			break;
13130 		case NFS4_LCK_CTYPE_REINSTATE:
13131 			argsp->ctag = TAG_LOCK_REINSTATE;
13132 			break;
13133 		case NFS4_LCK_CTYPE_RECLAIM:
13134 			argsp->ctag = TAG_LOCK_RECLAIM;
13135 			break;
13136 		default:
13137 			argsp->ctag = TAG_LOCK_UNKNOWN;
13138 			break;
13139 		}
13140 	} else {
13141 		LOCKU4args *locku_args;
13142 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
13143 
13144 		argop->argop = OP_LOCKU;
13145 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
13146 		locku_args->locktype = READ_LT;
13147 		locku_args->seqid = lop->lock_seqid + 1;
13148 		mutex_enter(&lop->lo_lock);
13149 		locku_args->lock_stateid = lop->lock_stateid;
13150 		mutex_exit(&lop->lo_lock);
13151 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13152 		locku_args->length = resend_rqstp->lr_flk->l_len;
13153 		if (locku_args->length == 0)
13154 			locku_args->length = ~locku_args->length;
13155 
13156 		switch (resend_rqstp->lr_ctype) {
13157 		case NFS4_LCK_CTYPE_RESEND:
13158 			argsp->ctag = TAG_LOCKU_RESEND;
13159 			break;
13160 		case NFS4_LCK_CTYPE_REINSTATE:
13161 			argsp->ctag = TAG_LOCKU_REINSTATE;
13162 			break;
13163 		default:
13164 			argsp->ctag = TAG_LOCK_UNKNOWN;
13165 			break;
13166 		}
13167 	}
13168 }
13169 
13170 /*
13171  * Setup the LOCKT4 arguments.
13172  */
13173 static void
13174 nfs4frlock_setup_lockt_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13175     LOCKT4args **lockt_argsp, COMPOUND4args_clnt *argsp, flock64_t *flk,
13176     rnode4_t *rp)
13177 {
13178 	LOCKT4args *lockt_args;
13179 
13180 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13181 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13182 	argop->argop = OP_LOCKT;
13183 	argsp->ctag = TAG_LOCKT;
13184 	lockt_args = &argop->nfs_argop4_u.oplockt;
13185 
13186 	/*
13187 	 * The locktype will be READ_LT unless it's
13188 	 * a write lock. We do this because the Solaris
13189 	 * system call allows the combination of
13190 	 * F_UNLCK and F_GETLK* and so in that case the
13191 	 * unlock is mapped to a read.
13192 	 */
13193 	if (flk->l_type == F_WRLCK)
13194 		lockt_args->locktype = WRITE_LT;
13195 	else
13196 		lockt_args->locktype = READ_LT;
13197 
13198 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13199 	/* set the lock owner4 args */
13200 	nfs4_setlockowner_args(&lockt_args->owner, rp,
13201 	    ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13202 	    flk->l_pid);
13203 	lockt_args->offset = flk->l_start;
13204 	lockt_args->length = flk->l_len;
13205 	if (flk->l_len == 0)
13206 		lockt_args->length = ~lockt_args->length;
13207 
13208 	*lockt_argsp = lockt_args;
13209 }
13210 
13211 /*
13212  * If the client is holding a delegation, and the open stream to be used
13213  * with this lock request is a delegation open stream, then re-open the stream.
13214  * Sets the nfs4_error_t to all zeros unless the open stream has already
13215  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13216  * means the caller should retry (like a recovery retry).
13217  */
13218 static void
13219 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13220 {
13221 	open_delegation_type4	dt;
13222 	bool_t			reopen_needed, force;
13223 	nfs4_open_stream_t	*osp;
13224 	open_claim_type4	oclaim;
13225 	rnode4_t		*rp = VTOR4(vp);
13226 	mntinfo4_t		*mi = VTOMI4(vp);
13227 
13228 	ASSERT(nfs_zone() == mi->mi_zone);
13229 
13230 	nfs4_error_zinit(ep);
13231 
13232 	mutex_enter(&rp->r_statev4_lock);
13233 	dt = rp->r_deleg_type;
13234 	mutex_exit(&rp->r_statev4_lock);
13235 
13236 	if (dt != OPEN_DELEGATE_NONE) {
13237 		nfs4_open_owner_t	*oop;
13238 
13239 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13240 		if (!oop) {
13241 			ep->stat = NFS4ERR_IO;
13242 			return;
13243 		}
13244 		/* returns with 'os_sync_lock' held */
13245 		osp = find_open_stream(oop, rp);
13246 		if (!osp) {
13247 			open_owner_rele(oop);
13248 			ep->stat = NFS4ERR_IO;
13249 			return;
13250 		}
13251 
13252 		if (osp->os_failed_reopen) {
13253 			NFS4_DEBUG((nfs4_open_stream_debug ||
13254 			    nfs4_client_lock_debug), (CE_NOTE,
13255 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13256 			    "for osp %p, cr %p, rp %s", (void *)osp,
13257 			    (void *)cr, rnode4info(rp)));
13258 			mutex_exit(&osp->os_sync_lock);
13259 			open_stream_rele(osp, rp);
13260 			open_owner_rele(oop);
13261 			ep->stat = NFS4ERR_IO;
13262 			return;
13263 		}
13264 
13265 		/*
13266 		 * Determine whether a reopen is needed.  If this
13267 		 * is a delegation open stream, then send the open
13268 		 * to the server to give visibility to the open owner.
13269 		 * Even if it isn't a delegation open stream, we need
13270 		 * to check if the previous open CLAIM_DELEGATE_CUR
13271 		 * was sufficient.
13272 		 */
13273 
13274 		reopen_needed = osp->os_delegation ||
13275 		    ((lt == F_RDLCK &&
13276 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13277 		    (lt == F_WRLCK &&
13278 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13279 
13280 		mutex_exit(&osp->os_sync_lock);
13281 		open_owner_rele(oop);
13282 
13283 		if (reopen_needed) {
13284 			/*
13285 			 * Always use CLAIM_PREVIOUS after server reboot.
13286 			 * The server will reject CLAIM_DELEGATE_CUR if
13287 			 * it is used during the grace period.
13288 			 */
13289 			mutex_enter(&mi->mi_lock);
13290 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13291 				oclaim = CLAIM_PREVIOUS;
13292 				force = TRUE;
13293 			} else {
13294 				oclaim = CLAIM_DELEGATE_CUR;
13295 				force = FALSE;
13296 			}
13297 			mutex_exit(&mi->mi_lock);
13298 
13299 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13300 			if (ep->error == EAGAIN) {
13301 				nfs4_error_zinit(ep);
13302 				ep->stat = NFS4ERR_DELAY;
13303 			}
13304 		}
13305 		open_stream_rele(osp, rp);
13306 		osp = NULL;
13307 	}
13308 }
13309 
13310 /*
13311  * Setup the LOCKU4 arguments.
13312  * Returns errors via the nfs4_error_t.
13313  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13314  *			over-the-wire.  The caller must release the
13315  *			reference on *lopp.
13316  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13317  * (other)		unrecoverable error.
13318  */
13319 static void
13320 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13321     LOCKU4args **locku_argsp, flock64_t *flk,
13322     nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13323     vnode_t *vp, int flag, u_offset_t offset, cred_t *cr,
13324     bool_t *skip_get_err, bool_t *go_otwp)
13325 {
13326 	nfs4_lock_owner_t	*lop = NULL;
13327 	LOCKU4args		*locku_args;
13328 	pid_t			pid;
13329 	bool_t			is_spec = FALSE;
13330 	rnode4_t		*rp = VTOR4(vp);
13331 
13332 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13333 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13334 
13335 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13336 	if (ep->error || ep->stat)
13337 		return;
13338 
13339 	argop->argop = OP_LOCKU;
13340 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13341 		argsp->ctag = TAG_LOCKU_REINSTATE;
13342 	else
13343 		argsp->ctag = TAG_LOCKU;
13344 	locku_args = &argop->nfs_argop4_u.oplocku;
13345 	*locku_argsp = locku_args;
13346 
13347 	/* locktype should be set to any legal value */
13348 	locku_args->locktype = READ_LT;
13349 
13350 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13351 	    flk->l_pid;
13352 
13353 	/*
13354 	 * Get the lock owner stateid.  If no lock owner
13355 	 * exists, return success.
13356 	 */
13357 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13358 	*lopp = lop;
13359 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13360 		is_spec = TRUE;
13361 	if (!lop || is_spec) {
13362 		/*
13363 		 * No lock owner so no locks to unlock.
13364 		 * Return success.  If there was a failed
13365 		 * reclaim earlier, the lock might still be
13366 		 * registered with the local locking code,
13367 		 * so notify it of the unlock.
13368 		 *
13369 		 * If the lockowner is using a special stateid,
13370 		 * then the original lock request (that created
13371 		 * this lockowner) was never successful, so we
13372 		 * have no lock to undo OTW.
13373 		 */
13374 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13375 		    "nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13376 		    "(%ld) so return success", (long)pid));
13377 
13378 		if (ctype == NFS4_LCK_CTYPE_NORM)
13379 			flk->l_pid = curproc->p_pid;
13380 		nfs4_register_lock_locally(vp, flk, flag, offset);
13381 		/*
13382 		 * Release our hold and NULL out so final_cleanup
13383 		 * doesn't try to end a lock seqid sync we
13384 		 * never started.
13385 		 */
13386 		if (is_spec) {
13387 			lock_owner_rele(lop);
13388 			*lopp = NULL;
13389 		}
13390 		*skip_get_err = TRUE;
13391 		*go_otwp = FALSE;
13392 		return;
13393 	}
13394 
13395 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13396 	if (ep->error == EAGAIN) {
13397 		lock_owner_rele(lop);
13398 		*lopp = NULL;
13399 		return;
13400 	}
13401 
13402 	mutex_enter(&lop->lo_lock);
13403 	locku_args->lock_stateid = lop->lock_stateid;
13404 	mutex_exit(&lop->lo_lock);
13405 	locku_args->seqid = lop->lock_seqid + 1;
13406 
13407 	/* leave the ref count on lop, rele after RPC call */
13408 
13409 	locku_args->offset = flk->l_start;
13410 	locku_args->length = flk->l_len;
13411 	if (flk->l_len == 0)
13412 		locku_args->length = ~locku_args->length;
13413 
13414 	*go_otwp = TRUE;
13415 }
13416 
13417 /*
13418  * Setup the LOCK4 arguments.
13419  *
13420  * Returns errors via the nfs4_error_t.
13421  * NFS4_OK		no problems
13422  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13423  * (other)		unrecoverable error
13424  */
13425 static void
13426 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13427     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13428     nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13429     flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13430 {
13431 	LOCK4args		*lock_args;
13432 	nfs4_open_owner_t	*oop = NULL;
13433 	nfs4_open_stream_t	*osp = NULL;
13434 	nfs4_lock_owner_t	*lop = NULL;
13435 	pid_t			pid;
13436 	rnode4_t		*rp = VTOR4(vp);
13437 
13438 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13439 
13440 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13441 	if (ep->error || ep->stat != NFS4_OK)
13442 		return;
13443 
13444 	argop->argop = OP_LOCK;
13445 	if (ctype == NFS4_LCK_CTYPE_NORM)
13446 		argsp->ctag = TAG_LOCK;
13447 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13448 		argsp->ctag = TAG_RELOCK;
13449 	else
13450 		argsp->ctag = TAG_LOCK_REINSTATE;
13451 	lock_args = &argop->nfs_argop4_u.oplock;
13452 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13453 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13454 	/*
13455 	 * Get the lock owner.  If no lock owner exists,
13456 	 * create a 'temporary' one and grab the open seqid
13457 	 * synchronization (which puts a hold on the open
13458 	 * owner and open stream).
13459 	 * This also grabs the lock seqid synchronization.
13460 	 */
13461 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid : flk->l_pid;
13462 	ep->stat =
13463 	    nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13464 
13465 	if (ep->stat != NFS4_OK)
13466 		goto out;
13467 
13468 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13469 	    &lock_args->locker);
13470 
13471 	lock_args->offset = flk->l_start;
13472 	lock_args->length = flk->l_len;
13473 	if (flk->l_len == 0)
13474 		lock_args->length = ~lock_args->length;
13475 	*lock_argsp = lock_args;
13476 out:
13477 	*oopp = oop;
13478 	*ospp = osp;
13479 	*lopp = lop;
13480 }
13481 
13482 /*
13483  * After we get the reply from the server, record the proper information
13484  * for possible resend lock requests.
13485  */
13486 static void
13487 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13488     nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13489     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13490     nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13491 {
13492 	bool_t unlock = (flk->l_type == F_UNLCK);
13493 
13494 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13495 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13496 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13497 
13498 	if (error != 0 && !unlock) {
13499 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13500 		    nfs4_client_lock_debug), (CE_NOTE,
13501 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13502 		    " for lop %p", (void *)lop));
13503 		ASSERT(lop != NULL);
13504 		mutex_enter(&lop->lo_lock);
13505 		lop->lo_pending_rqsts = 1;
13506 		mutex_exit(&lop->lo_lock);
13507 	}
13508 
13509 	lost_rqstp->lr_putfirst = FALSE;
13510 	lost_rqstp->lr_op = 0;
13511 
13512 	/*
13513 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13514 	 * recovery purposes so that the lock request that was sent
13515 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13516 	 * unmount.  This is done to have the client's local locking state
13517 	 * match the v4 server's state; that is, the request was
13518 	 * potentially received and accepted by the server but the client
13519 	 * thinks it was not.
13520 	 */
13521 	if (error == ETIMEDOUT || error == EINTR ||
13522 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13523 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13524 		    nfs4_client_lock_debug), (CE_NOTE,
13525 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13526 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13527 		    (void *)lop, (void *)oop, (void *)osp));
13528 		if (unlock)
13529 			lost_rqstp->lr_op = OP_LOCKU;
13530 		else {
13531 			lost_rqstp->lr_op = OP_LOCK;
13532 			lost_rqstp->lr_locktype = locktype;
13533 		}
13534 		/*
13535 		 * Objects are held and rele'd via the recovery code.
13536 		 * See nfs4_save_lost_rqst.
13537 		 */
13538 		lost_rqstp->lr_vp = vp;
13539 		lost_rqstp->lr_dvp = NULL;
13540 		lost_rqstp->lr_oop = oop;
13541 		lost_rqstp->lr_osp = osp;
13542 		lost_rqstp->lr_lop = lop;
13543 		lost_rqstp->lr_cr = cr;
13544 		switch (ctype) {
13545 		case NFS4_LCK_CTYPE_NORM:
13546 			flk->l_pid = ttoproc(curthread)->p_pid;
13547 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13548 			break;
13549 		case NFS4_LCK_CTYPE_REINSTATE:
13550 			lost_rqstp->lr_putfirst = TRUE;
13551 			lost_rqstp->lr_ctype = ctype;
13552 			break;
13553 		default:
13554 			break;
13555 		}
13556 		lost_rqstp->lr_flk = flk;
13557 	}
13558 }
13559 
13560 /*
13561  * Update lop's seqid.  Also update the seqid stored in a resend request,
13562  * if any.  (Some recovery errors increment the seqid, and we may have to
13563  * send the resend request again.)
13564  */
13565 
13566 static void
13567 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13568     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13569 {
13570 	if (lock_args) {
13571 		if (lock_args->locker.new_lock_owner == TRUE)
13572 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13573 		else {
13574 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13575 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13576 		}
13577 	} else if (locku_args) {
13578 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13579 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13580 	}
13581 }
13582 
13583 /*
13584  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13585  * COMPOUND4 args/res for calls that need to retry.
13586  * Switches the *cred_otwp to base_cr.
13587  */
13588 static void
13589 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13590     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13591     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13592     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13593     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13594 {
13595 	nfs4_open_owner_t	*oop = *oopp;
13596 	nfs4_open_stream_t	*osp = *ospp;
13597 	nfs4_lock_owner_t	*lop = *lopp;
13598 	nfs_argop4		*argop = (*argspp)->array;
13599 
13600 	if (*did_start_fop) {
13601 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13602 		    needrecov);
13603 		*did_start_fop = FALSE;
13604 	}
13605 	ASSERT((*argspp)->array_len == 2);
13606 	if (argop[1].argop == OP_LOCK)
13607 		nfs4args_lock_free(&argop[1]);
13608 	else if (argop[1].argop == OP_LOCKT)
13609 		nfs4args_lockt_free(&argop[1]);
13610 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13611 	if (!error)
13612 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13613 	*argspp = NULL;
13614 	*respp = NULL;
13615 
13616 	if (lop) {
13617 		nfs4_end_lock_seqid_sync(lop);
13618 		lock_owner_rele(lop);
13619 		*lopp = NULL;
13620 	}
13621 
13622 	/* need to free up the reference on osp for lock args */
13623 	if (osp != NULL) {
13624 		open_stream_rele(osp, VTOR4(vp));
13625 		*ospp = NULL;
13626 	}
13627 
13628 	/* need to free up the reference on oop for lock args */
13629 	if (oop != NULL) {
13630 		nfs4_end_open_seqid_sync(oop);
13631 		open_owner_rele(oop);
13632 		*oopp = NULL;
13633 	}
13634 
13635 	crfree(*cred_otwp);
13636 	*cred_otwp = base_cr;
13637 	crhold(*cred_otwp);
13638 }
13639 
13640 /*
13641  * Function to process the client's recovery for nfs4frlock.
13642  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13643  *
13644  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13645  * COMPOUND4 args/res for calls that need to retry.
13646  *
13647  * Note: the rp's r_lkserlock is *not* dropped during this path.
13648  */
13649 static bool_t
13650 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13651     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13652     LOCK4args *lock_args, LOCKU4args *locku_args,
13653     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13654     nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13655     nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13656     bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13657 {
13658 	nfs4_open_owner_t	*oop = *oopp;
13659 	nfs4_open_stream_t	*osp = *ospp;
13660 	nfs4_lock_owner_t	*lop = *lopp;
13661 
13662 	bool_t abort, retry;
13663 
13664 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13665 	ASSERT((*argspp) != NULL);
13666 	ASSERT((*respp) != NULL);
13667 	if (lock_args || locku_args)
13668 		ASSERT(lop != NULL);
13669 
13670 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13671 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13672 
13673 	retry = TRUE;
13674 	abort = FALSE;
13675 	if (needrecov) {
13676 		nfs4_bseqid_entry_t *bsep = NULL;
13677 		nfs_opnum4 op;
13678 
13679 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13680 
13681 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13682 			seqid4 seqid;
13683 
13684 			if (lock_args) {
13685 				if (lock_args->locker.new_lock_owner == TRUE)
13686 					seqid = lock_args->locker.locker4_u.
13687 					    open_owner.open_seqid;
13688 				else
13689 					seqid = lock_args->locker.locker4_u.
13690 					    lock_owner.lock_seqid;
13691 			} else if (locku_args) {
13692 				seqid = locku_args->seqid;
13693 			} else {
13694 				seqid = 0;
13695 			}
13696 
13697 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13698 			    flk->l_pid, (*argspp)->ctag, seqid);
13699 		}
13700 
13701 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13702 		    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13703 		    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13704 		    NULL, op, bsep, NULL, NULL);
13705 
13706 		if (bsep)
13707 			kmem_free(bsep, sizeof (*bsep));
13708 	}
13709 
13710 	/*
13711 	 * Return that we do not want to retry the request for 3 cases:
13712 	 * 1. If we received EINTR or are bailing out because of a forced
13713 	 *    unmount, we came into this code path just for the sake of
13714 	 *    initiating recovery, we now need to return the error.
13715 	 * 2. If we have aborted recovery.
13716 	 * 3. We received NFS4ERR_BAD_SEQID.
13717 	 */
13718 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13719 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13720 		retry = FALSE;
13721 
13722 	if (*did_start_fop == TRUE) {
13723 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13724 		    needrecov);
13725 		*did_start_fop = FALSE;
13726 	}
13727 
13728 	if (retry == TRUE) {
13729 		nfs_argop4	*argop;
13730 
13731 		argop = (*argspp)->array;
13732 		ASSERT((*argspp)->array_len == 2);
13733 
13734 		if (argop[1].argop == OP_LOCK)
13735 			nfs4args_lock_free(&argop[1]);
13736 		else if (argop[1].argop == OP_LOCKT)
13737 			nfs4args_lockt_free(&argop[1]);
13738 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13739 		if (!ep->error)
13740 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13741 		*respp = NULL;
13742 		*argspp = NULL;
13743 	}
13744 
13745 	if (lop != NULL) {
13746 		nfs4_end_lock_seqid_sync(lop);
13747 		lock_owner_rele(lop);
13748 	}
13749 
13750 	*lopp = NULL;
13751 
13752 	/* need to free up the reference on osp for lock args */
13753 	if (osp != NULL) {
13754 		open_stream_rele(osp, rp);
13755 		*ospp = NULL;
13756 	}
13757 
13758 	/* need to free up the reference on oop for lock args */
13759 	if (oop != NULL) {
13760 		nfs4_end_open_seqid_sync(oop);
13761 		open_owner_rele(oop);
13762 		*oopp = NULL;
13763 	}
13764 
13765 	return (retry);
13766 }
13767 
13768 /*
13769  * Handles the successful reply from the server for nfs4frlock.
13770  */
13771 static void
13772 nfs4frlock_results_ok(nfs4_lock_call_type_t ctype, int cmd, flock64_t *flk,
13773     vnode_t *vp, int flag, u_offset_t offset,
13774     nfs4_lost_rqst_t *resend_rqstp)
13775 {
13776 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13777 	if ((cmd == F_SETLK || cmd == F_SETLKW) &&
13778 	    (flk->l_type == F_RDLCK || flk->l_type == F_WRLCK)) {
13779 		if (ctype == NFS4_LCK_CTYPE_NORM) {
13780 			flk->l_pid = ttoproc(curthread)->p_pid;
13781 			/*
13782 			 * We do not register lost locks locally in
13783 			 * the 'resend' case since the user/application
13784 			 * doesn't think we have the lock.
13785 			 */
13786 			ASSERT(!resend_rqstp);
13787 			nfs4_register_lock_locally(vp, flk, flag, offset);
13788 		}
13789 	}
13790 }
13791 
13792 /*
13793  * Handle the DENIED reply from the server for nfs4frlock.
13794  * Returns TRUE if we should retry the request; FALSE otherwise.
13795  *
13796  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13797  * COMPOUND4 args/res for calls that need to retry.  Can also
13798  * drop and regrab the r_lkserlock.
13799  */
13800 static bool_t
13801 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13802     LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13803     nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13804     vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13805     nfs4_recov_state_t *recov_statep, int needrecov,
13806     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13807     clock_t *tick_delayp, short *whencep, int *errorp,
13808     nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13809     bool_t *skip_get_err)
13810 {
13811 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13812 
13813 	if (lock_args) {
13814 		nfs4_open_owner_t	*oop = *oopp;
13815 		nfs4_open_stream_t	*osp = *ospp;
13816 		nfs4_lock_owner_t	*lop = *lopp;
13817 		int			intr;
13818 
13819 		/*
13820 		 * Blocking lock needs to sleep and retry from the request.
13821 		 *
13822 		 * Do not block and wait for 'resend' or 'reinstate'
13823 		 * lock requests, just return the error.
13824 		 *
13825 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13826 		 */
13827 		if (cmd == F_SETLKW) {
13828 			rnode4_t *rp = VTOR4(vp);
13829 			nfs_argop4 *argop = (*argspp)->array;
13830 
13831 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13832 
13833 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13834 			    recov_statep, needrecov);
13835 			*did_start_fop = FALSE;
13836 			ASSERT((*argspp)->array_len == 2);
13837 			if (argop[1].argop == OP_LOCK)
13838 				nfs4args_lock_free(&argop[1]);
13839 			else if (argop[1].argop == OP_LOCKT)
13840 				nfs4args_lockt_free(&argop[1]);
13841 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13842 			if (*respp)
13843 				xdr_free(xdr_COMPOUND4res_clnt,
13844 				    (caddr_t)*respp);
13845 			*argspp = NULL;
13846 			*respp = NULL;
13847 			nfs4_end_lock_seqid_sync(lop);
13848 			lock_owner_rele(lop);
13849 			*lopp = NULL;
13850 			if (osp != NULL) {
13851 				open_stream_rele(osp, rp);
13852 				*ospp = NULL;
13853 			}
13854 			if (oop != NULL) {
13855 				nfs4_end_open_seqid_sync(oop);
13856 				open_owner_rele(oop);
13857 				*oopp = NULL;
13858 			}
13859 
13860 			nfs_rw_exit(&rp->r_lkserlock);
13861 
13862 			intr = nfs4_block_and_wait(tick_delayp, rp);
13863 
13864 			if (intr) {
13865 				(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13866 				    RW_WRITER, FALSE);
13867 				*errorp = EINTR;
13868 				return (FALSE);
13869 			}
13870 
13871 			(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13872 			    RW_WRITER, FALSE);
13873 
13874 			/*
13875 			 * Make sure we are still safe to lock with
13876 			 * regards to mmapping.
13877 			 */
13878 			if (!nfs4_safelock(vp, flk, cr)) {
13879 				*errorp = EAGAIN;
13880 				return (FALSE);
13881 			}
13882 
13883 			return (TRUE);
13884 		}
13885 		if (ctype == NFS4_LCK_CTYPE_NORM)
13886 			*errorp = EAGAIN;
13887 		*skip_get_err = TRUE;
13888 		flk->l_whence = 0;
13889 		*whencep = 0;
13890 		return (FALSE);
13891 	} else if (lockt_args) {
13892 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13893 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
13894 
13895 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
13896 		    flk, lockt_args);
13897 
13898 		/* according to NLM code */
13899 		*errorp = 0;
13900 		*whencep = 0;
13901 		*skip_get_err = TRUE;
13902 		return (FALSE);
13903 	}
13904 	return (FALSE);
13905 }
13906 
13907 /*
13908  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
13909  */
13910 static void
13911 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
13912 {
13913 	switch (resp->status) {
13914 	case NFS4ERR_ACCESS:
13915 	case NFS4ERR_ADMIN_REVOKED:
13916 	case NFS4ERR_BADHANDLE:
13917 	case NFS4ERR_BAD_RANGE:
13918 	case NFS4ERR_BAD_SEQID:
13919 	case NFS4ERR_BAD_STATEID:
13920 	case NFS4ERR_BADXDR:
13921 	case NFS4ERR_DEADLOCK:
13922 	case NFS4ERR_DELAY:
13923 	case NFS4ERR_EXPIRED:
13924 	case NFS4ERR_FHEXPIRED:
13925 	case NFS4ERR_GRACE:
13926 	case NFS4ERR_INVAL:
13927 	case NFS4ERR_ISDIR:
13928 	case NFS4ERR_LEASE_MOVED:
13929 	case NFS4ERR_LOCK_NOTSUPP:
13930 	case NFS4ERR_LOCK_RANGE:
13931 	case NFS4ERR_MOVED:
13932 	case NFS4ERR_NOFILEHANDLE:
13933 	case NFS4ERR_NO_GRACE:
13934 	case NFS4ERR_OLD_STATEID:
13935 	case NFS4ERR_OPENMODE:
13936 	case NFS4ERR_RECLAIM_BAD:
13937 	case NFS4ERR_RECLAIM_CONFLICT:
13938 	case NFS4ERR_RESOURCE:
13939 	case NFS4ERR_SERVERFAULT:
13940 	case NFS4ERR_STALE:
13941 	case NFS4ERR_STALE_CLIENTID:
13942 	case NFS4ERR_STALE_STATEID:
13943 		return;
13944 	default:
13945 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13946 		    "nfs4frlock_results_default: got unrecognizable "
13947 		    "res.status %d", resp->status));
13948 		*errorp = NFS4ERR_INVAL;
13949 	}
13950 }
13951 
13952 /*
13953  * The lock request was successful, so update the client's state.
13954  */
13955 static void
13956 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
13957     LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
13958     vnode_t *vp, flock64_t *flk, cred_t *cr,
13959     nfs4_lost_rqst_t *resend_rqstp)
13960 {
13961 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13962 
13963 	if (lock_args) {
13964 		LOCK4res *lock_res;
13965 
13966 		lock_res = &resop->nfs_resop4_u.oplock;
13967 		/* update the stateid with server's response */
13968 
13969 		if (lock_args->locker.new_lock_owner == TRUE) {
13970 			mutex_enter(&lop->lo_lock);
13971 			lop->lo_just_created = NFS4_PERM_CREATED;
13972 			mutex_exit(&lop->lo_lock);
13973 		}
13974 
13975 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
13976 
13977 		/*
13978 		 * If the lock was the result of a resending a lost
13979 		 * request, we've synched up the stateid and seqid
13980 		 * with the server, but now the server might be out of sync
13981 		 * with what the application thinks it has for locks.
13982 		 * Clean that up here.  It's unclear whether we should do
13983 		 * this even if the filesystem has been forcibly unmounted.
13984 		 * For most servers, it's probably wasted effort, but
13985 		 * RFC 7530 lets servers require that unlocks exactly match
13986 		 * the locks that are held.
13987 		 */
13988 		if (resend_rqstp != NULL &&
13989 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
13990 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
13991 		} else {
13992 			flk->l_whence = 0;
13993 		}
13994 	} else if (locku_args) {
13995 		LOCKU4res *locku_res;
13996 
13997 		locku_res = &resop->nfs_resop4_u.oplocku;
13998 
13999 		/* Update the stateid with the server's response */
14000 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
14001 	} else if (lockt_args) {
14002 		/* Switch the lock type to express success, see fcntl */
14003 		flk->l_type = F_UNLCK;
14004 		flk->l_whence = 0;
14005 	}
14006 }
14007 
14008 /*
14009  * Do final cleanup before exiting nfs4frlock.
14010  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
14011  * COMPOUND4 args/res for calls that haven't already.
14012  */
14013 static void
14014 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
14015     COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
14016     nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
14017     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
14018     short whence, u_offset_t offset, struct lm_sysid *ls,
14019     int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
14020     bool_t did_start_fop, bool_t skip_get_err,
14021     cred_t *cred_otw, cred_t *cred)
14022 {
14023 	mntinfo4_t	*mi = VTOMI4(vp);
14024 	rnode4_t	*rp = VTOR4(vp);
14025 	int		error = *errorp;
14026 	nfs_argop4	*argop;
14027 	int	do_flush_pages = 0;
14028 
14029 	ASSERT(nfs_zone() == mi->mi_zone);
14030 	/*
14031 	 * The client recovery code wants the raw status information,
14032 	 * so don't map the NFS status code to an errno value for
14033 	 * non-normal call types.
14034 	 */
14035 	if (ctype == NFS4_LCK_CTYPE_NORM) {
14036 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
14037 			*errorp = geterrno4(resp->status);
14038 		if (did_start_fop == TRUE)
14039 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
14040 			    needrecov);
14041 
14042 		/*
14043 		 * We've established a new lock on the server, so invalidate
14044 		 * the pages associated with the vnode to get the most up to
14045 		 * date pages from the server after acquiring the lock. We
14046 		 * want to be sure that the read operation gets the newest data.
14047 		 * N.B.
14048 		 * We used to do this in nfs4frlock_results_ok but that doesn't
14049 		 * work since VOP_PUTPAGE can call nfs4_commit which calls
14050 		 * nfs4_start_fop. We flush the pages below after calling
14051 		 * nfs4_end_fop above
14052 		 * The flush of the page cache must be done after
14053 		 * nfs4_end_open_seqid_sync() to avoid a 4-way hang.
14054 		 */
14055 		if (!error && resp && resp->status == NFS4_OK)
14056 			do_flush_pages = 1;
14057 	}
14058 	if (argsp) {
14059 		ASSERT(argsp->array_len == 2);
14060 		argop = argsp->array;
14061 		if (argop[1].argop == OP_LOCK)
14062 			nfs4args_lock_free(&argop[1]);
14063 		else if (argop[1].argop == OP_LOCKT)
14064 			nfs4args_lockt_free(&argop[1]);
14065 		kmem_free(argop, 2 * sizeof (nfs_argop4));
14066 		if (resp)
14067 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
14068 	}
14069 
14070 	/* free the reference on the lock owner */
14071 	if (lop != NULL) {
14072 		nfs4_end_lock_seqid_sync(lop);
14073 		lock_owner_rele(lop);
14074 	}
14075 
14076 	/* need to free up the reference on osp for lock args */
14077 	if (osp != NULL)
14078 		open_stream_rele(osp, rp);
14079 
14080 	/* need to free up the reference on oop for lock args */
14081 	if (oop != NULL) {
14082 		nfs4_end_open_seqid_sync(oop);
14083 		open_owner_rele(oop);
14084 	}
14085 
14086 	if (do_flush_pages)
14087 		nfs4_flush_pages(vp, cred);
14088 
14089 	(void) convoff(vp, flk, whence, offset);
14090 
14091 	lm_rel_sysid(ls);
14092 
14093 	/*
14094 	 * Record debug information in the event we get EINVAL.
14095 	 */
14096 	mutex_enter(&mi->mi_lock);
14097 	if (*errorp == EINVAL && (lock_args || locku_args) &&
14098 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
14099 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
14100 			zcmn_err(getzoneid(), CE_NOTE,
14101 			    "%s operation failed with "
14102 			    "EINVAL probably since the server, %s,"
14103 			    " doesn't support POSIX style locking",
14104 			    lock_args ? "LOCK" : "LOCKU",
14105 			    mi->mi_curr_serv->sv_hostname);
14106 			mi->mi_flags |= MI4_LOCK_DEBUG;
14107 		}
14108 	}
14109 	mutex_exit(&mi->mi_lock);
14110 
14111 	if (cred_otw)
14112 		crfree(cred_otw);
14113 }
14114 
14115 /*
14116  * This calls the server and the local locking code.
14117  *
14118  * Client locks are registerred locally by oring the sysid with
14119  * LM_SYSID_CLIENT. The server registers locks locally using just the sysid.
14120  * We need to distinguish between the two to avoid collision in case one
14121  * machine is used as both client and server.
14122  *
14123  * Blocking lock requests will continually retry to acquire the lock
14124  * forever.
14125  *
14126  * The ctype is defined as follows:
14127  * NFS4_LCK_CTYPE_NORM: normal lock request.
14128  *
14129  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
14130  * recovery, get the pid from flk instead of curproc, and don't reregister
14131  * the lock locally.
14132  *
14133  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
14134  * that we will use the information passed in via resend_rqstp to setup the
14135  * lock/locku request.  This resend is the exact same request as the 'lost
14136  * lock', and is initiated by the recovery framework. A successful resend
14137  * request can initiate one or more reinstate requests.
14138  *
14139  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14140  * does not trigger additional reinstate requests.  This lock call type is
14141  * set for setting the v4 server's locking state back to match what the
14142  * client's local locking state is in the event of a received 'lost lock'.
14143  *
14144  * Errors are returned via the nfs4_error_t parameter.
14145  */
14146 void
14147 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14148     int flag, u_offset_t offset, cred_t *cr, nfs4_error_t *ep,
14149     nfs4_lost_rqst_t *resend_rqstp, int *did_reclaimp)
14150 {
14151 	COMPOUND4args_clnt	args, *argsp = NULL;
14152 	COMPOUND4res_clnt	res, *resp = NULL;
14153 	nfs_argop4	*argop;
14154 	nfs_resop4	*resop;
14155 	rnode4_t	*rp;
14156 	int		doqueue = 1;
14157 	clock_t		tick_delay;  /* delay in clock ticks */
14158 	struct lm_sysid	*ls;
14159 	LOCK4args	*lock_args = NULL;
14160 	LOCKU4args	*locku_args = NULL;
14161 	LOCKT4args	*lockt_args = NULL;
14162 	nfs4_open_owner_t *oop = NULL;
14163 	nfs4_open_stream_t *osp = NULL;
14164 	nfs4_lock_owner_t *lop = NULL;
14165 	bool_t		needrecov = FALSE;
14166 	nfs4_recov_state_t recov_state;
14167 	short		whence;
14168 	nfs4_op_hint_t	op_hint;
14169 	nfs4_lost_rqst_t lost_rqst;
14170 	bool_t		retry = FALSE;
14171 	bool_t		did_start_fop = FALSE;
14172 	bool_t		skip_get_err = FALSE;
14173 	cred_t		*cred_otw = NULL;
14174 	bool_t		recovonly;	/* just queue request */
14175 	int		frc_no_reclaim = 0;
14176 #ifdef DEBUG
14177 	char *name;
14178 #endif
14179 
14180 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14181 
14182 #ifdef DEBUG
14183 	name = fn_name(VTOSV(vp)->sv_name);
14184 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14185 	    "%s: cmd %d, type %d, offset %llu, start %"PRIx64", "
14186 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14187 	    "resend request %s", name, cmd, flk->l_type, offset, flk->l_start,
14188 	    flk->l_len, ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid :
14189 	    flk->l_pid, flk->l_sysid, nfs4frlock_get_call_type(ctype),
14190 	    resend_rqstp ? "TRUE" : "FALSE"));
14191 	kmem_free(name, MAXNAMELEN);
14192 #endif
14193 
14194 	nfs4_error_zinit(ep);
14195 	ep->error = nfs4frlock_validate_args(cmd, flk, flag, vp, offset);
14196 	if (ep->error)
14197 		return;
14198 	ep->error = nfs4frlock_get_sysid(&ls, vp, flk);
14199 	if (ep->error)
14200 		return;
14201 	nfs4frlock_pre_setup(&tick_delay, &recov_state, flk, &whence,
14202 	    vp, cr, &cred_otw);
14203 
14204 recov_retry:
14205 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14206 	    &retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14207 	rp = VTOR4(vp);
14208 
14209 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14210 	    &did_start_fop, &recovonly);
14211 
14212 	if (ep->error)
14213 		goto out;
14214 
14215 	if (recovonly) {
14216 		/*
14217 		 * Leave the request for the recovery system to deal with.
14218 		 */
14219 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14220 		ASSERT(cmd != F_GETLK);
14221 		ASSERT(flk->l_type == F_UNLCK);
14222 
14223 		nfs4_error_init(ep, EINTR);
14224 		needrecov = TRUE;
14225 		lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14226 		if (lop != NULL) {
14227 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14228 			    NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14229 			(void) nfs4_start_recovery(ep,
14230 			    VTOMI4(vp), vp, NULL, NULL,
14231 			    (lost_rqst.lr_op == OP_LOCK ||
14232 			    lost_rqst.lr_op == OP_LOCKU) ?
14233 			    &lost_rqst : NULL, OP_LOCKU, NULL, NULL, NULL);
14234 			lock_owner_rele(lop);
14235 			lop = NULL;
14236 		}
14237 		flk->l_pid = curproc->p_pid;
14238 		nfs4_register_lock_locally(vp, flk, flag, offset);
14239 		goto out;
14240 	}
14241 
14242 	/* putfh directory fh */
14243 	argop[0].argop = OP_CPUTFH;
14244 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14245 
14246 	/*
14247 	 * Set up the over-the-wire arguments and get references to the
14248 	 * open owner, etc.
14249 	 */
14250 
14251 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14252 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14253 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14254 		    &argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14255 	} else {
14256 		bool_t go_otw = TRUE;
14257 
14258 		ASSERT(resend_rqstp == NULL);
14259 
14260 		switch (cmd) {
14261 		case F_GETLK:
14262 			nfs4frlock_setup_lockt_args(ctype, &argop[1],
14263 			    &lockt_args, argsp, flk, rp);
14264 			break;
14265 		case F_SETLKW:
14266 		case F_SETLK:
14267 			if (flk->l_type == F_UNLCK)
14268 				nfs4frlock_setup_locku_args(ctype,
14269 				    &argop[1], &locku_args, flk,
14270 				    &lop, ep, argsp,
14271 				    vp, flag, offset, cr,
14272 				    &skip_get_err, &go_otw);
14273 			else
14274 				nfs4frlock_setup_lock_args(ctype,
14275 				    &lock_args, &oop, &osp, &lop, &argop[1],
14276 				    argsp, flk, cmd, vp, cr, ep);
14277 
14278 			if (ep->error)
14279 				goto out;
14280 
14281 			switch (ep->stat) {
14282 			case NFS4_OK:
14283 				break;
14284 			case NFS4ERR_DELAY:
14285 				/* recov thread never gets this error */
14286 				ASSERT(resend_rqstp == NULL);
14287 				ASSERT(did_start_fop);
14288 
14289 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14290 				    &recov_state, TRUE);
14291 				did_start_fop = FALSE;
14292 				if (argop[1].argop == OP_LOCK)
14293 					nfs4args_lock_free(&argop[1]);
14294 				else if (argop[1].argop == OP_LOCKT)
14295 					nfs4args_lockt_free(&argop[1]);
14296 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14297 				argsp = NULL;
14298 				goto recov_retry;
14299 			default:
14300 				ep->error = EIO;
14301 				goto out;
14302 			}
14303 			break;
14304 		default:
14305 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14306 			    "nfs4_frlock: invalid cmd %d", cmd));
14307 			ep->error = EINVAL;
14308 			goto out;
14309 		}
14310 
14311 		if (!go_otw)
14312 			goto out;
14313 	}
14314 
14315 	/* XXX should we use the local reclock as a cache ? */
14316 	/*
14317 	 * Unregister the lock with the local locking code before
14318 	 * contacting the server.  This avoids a potential race where
14319 	 * another process gets notified that it has been granted a lock
14320 	 * before we can unregister ourselves locally.
14321 	 */
14322 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK) {
14323 		if (ctype == NFS4_LCK_CTYPE_NORM)
14324 			flk->l_pid = ttoproc(curthread)->p_pid;
14325 		nfs4_register_lock_locally(vp, flk, flag, offset);
14326 	}
14327 
14328 	/*
14329 	 * Send the server the lock request.  Continually loop with a delay
14330 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14331 	 */
14332 	resp = &res;
14333 
14334 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14335 	    (CE_NOTE,
14336 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14337 	    rnode4info(rp)));
14338 
14339 	if (lock_args && frc_no_reclaim) {
14340 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14341 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14342 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14343 		lock_args->reclaim = FALSE;
14344 		if (did_reclaimp)
14345 			*did_reclaimp = 0;
14346 	}
14347 
14348 	/*
14349 	 * Do the OTW call.
14350 	 */
14351 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14352 
14353 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14354 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14355 
14356 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14357 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14358 	    "nfs4frlock: needrecov %d", needrecov));
14359 
14360 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14361 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14362 		    args.ctag);
14363 
14364 	/*
14365 	 * Check if one of these mutually exclusive error cases has
14366 	 * happened:
14367 	 *   need to swap credentials due to access error
14368 	 *   recovery is needed
14369 	 *   different error (only known case is missing Kerberos ticket)
14370 	 */
14371 
14372 	if ((ep->error == EACCES ||
14373 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14374 	    cred_otw != cr) {
14375 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14376 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14377 		    cr, &cred_otw);
14378 		goto recov_retry;
14379 	}
14380 
14381 	if (needrecov) {
14382 		/*
14383 		 * LOCKT requests don't need to recover from lost
14384 		 * requests since they don't create/modify state.
14385 		 */
14386 		if ((ep->error == EINTR ||
14387 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14388 		    lockt_args)
14389 			goto out;
14390 		/*
14391 		 * Do not attempt recovery for requests initiated by
14392 		 * the recovery framework.  Let the framework redrive them.
14393 		 */
14394 		if (ctype != NFS4_LCK_CTYPE_NORM)
14395 			goto out;
14396 		else {
14397 			ASSERT(resend_rqstp == NULL);
14398 		}
14399 
14400 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14401 		    flk_to_locktype(cmd, flk->l_type),
14402 		    oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14403 
14404 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14405 		    &resp, lock_args, locku_args, &oop, &osp, &lop,
14406 		    rp, vp, &recov_state, op_hint, &did_start_fop,
14407 		    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14408 
14409 		if (retry) {
14410 			ASSERT(oop == NULL);
14411 			ASSERT(osp == NULL);
14412 			ASSERT(lop == NULL);
14413 			goto recov_retry;
14414 		}
14415 		goto out;
14416 	}
14417 
14418 	/*
14419 	 * Bail out if have reached this point with ep->error set. Can
14420 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14421 	 * This happens if Kerberos ticket has expired or has been
14422 	 * destroyed.
14423 	 */
14424 	if (ep->error != 0)
14425 		goto out;
14426 
14427 	/*
14428 	 * Process the reply.
14429 	 */
14430 	switch (resp->status) {
14431 	case NFS4_OK:
14432 		resop = &resp->array[1];
14433 		nfs4frlock_results_ok(ctype, cmd, flk, vp, flag, offset,
14434 		    resend_rqstp);
14435 		/*
14436 		 * Have a successful lock operation, now update state.
14437 		 */
14438 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14439 		    resop, lop, vp, flk, cr, resend_rqstp);
14440 		break;
14441 
14442 	case NFS4ERR_DENIED:
14443 		resop = &resp->array[1];
14444 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14445 		    &oop, &osp, &lop, cmd, vp, flk, op_hint,
14446 		    &recov_state, needrecov, &argsp, &resp,
14447 		    &tick_delay, &whence, &ep->error, resop, cr,
14448 		    &did_start_fop, &skip_get_err);
14449 
14450 		if (retry) {
14451 			ASSERT(oop == NULL);
14452 			ASSERT(osp == NULL);
14453 			ASSERT(lop == NULL);
14454 			goto recov_retry;
14455 		}
14456 		break;
14457 	/*
14458 	 * If the server won't let us reclaim, fall-back to trying to lock
14459 	 * the file from scratch. Code elsewhere will check the changeinfo
14460 	 * to ensure the file hasn't been changed.
14461 	 */
14462 	case NFS4ERR_NO_GRACE:
14463 		if (lock_args && lock_args->reclaim == TRUE) {
14464 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14465 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14466 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14467 			frc_no_reclaim = 1;
14468 			/* clean up before retrying */
14469 			needrecov = 0;
14470 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14471 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14472 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14473 			goto recov_retry;
14474 		}
14475 		/* FALLTHROUGH */
14476 
14477 	default:
14478 		nfs4frlock_results_default(resp, &ep->error);
14479 		break;
14480 	}
14481 out:
14482 	/*
14483 	 * Process and cleanup from error.  Make interrupted unlock
14484 	 * requests look successful, since they will be handled by the
14485 	 * client recovery code.
14486 	 */
14487 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14488 	    needrecov, oop, osp, lop, flk, whence, offset, ls, &ep->error,
14489 	    lock_args, locku_args, did_start_fop,
14490 	    skip_get_err, cred_otw, cr);
14491 
14492 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14493 	    (cmd == F_SETLK || cmd == F_SETLKW))
14494 		ep->error = 0;
14495 }
14496 
14497 /*
14498  * nfs4_safelock:
14499  *
14500  * Return non-zero if the given lock request can be handled without
14501  * violating the constraints on concurrent mapping and locking.
14502  */
14503 
14504 static int
14505 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14506 {
14507 	rnode4_t *rp = VTOR4(vp);
14508 	struct vattr va;
14509 	int error;
14510 
14511 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14512 	ASSERT(rp->r_mapcnt >= 0);
14513 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14514 	    "(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14515 	    "write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14516 	    bfp->l_start, bfp->l_len, rp->r_mapcnt));
14517 
14518 	if (rp->r_mapcnt == 0)
14519 		return (1);		/* always safe if not mapped */
14520 
14521 	/*
14522 	 * If the file is already mapped and there are locks, then they
14523 	 * should be all safe locks.  So adding or removing a lock is safe
14524 	 * as long as the new request is safe (i.e., whole-file, meaning
14525 	 * length and starting offset are both zero).
14526 	 */
14527 
14528 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14529 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14530 		    "cannot lock a memory mapped file unless locking the "
14531 		    "entire file: start %"PRIx64", len %"PRIx64,
14532 		    bfp->l_start, bfp->l_len));
14533 		return (0);
14534 	}
14535 
14536 	/* mandatory locking and mapping don't mix */
14537 	va.va_mask = AT_MODE;
14538 	error = VOP_GETATTR(vp, &va, 0, cr, NULL);
14539 	if (error != 0) {
14540 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14541 		    "getattr error %d", error));
14542 		return (0);		/* treat errors conservatively */
14543 	}
14544 	if (MANDLOCK(vp, va.va_mode)) {
14545 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14546 		    "cannot mandatory lock and mmap a file"));
14547 		return (0);
14548 	}
14549 
14550 	return (1);
14551 }
14552 
14553 
14554 /*
14555  * Register the lock locally within Solaris.
14556  * As the client, we "or" the sysid with LM_SYSID_CLIENT when
14557  * recording locks locally.
14558  *
14559  * This should handle conflicts/cooperation with NFS v2/v3 since all locks
14560  * are registered locally.
14561  */
14562 void
14563 nfs4_register_lock_locally(vnode_t *vp, struct flock64 *flk, int flag,
14564     u_offset_t offset)
14565 {
14566 	int oldsysid;
14567 	int error;
14568 #ifdef DEBUG
14569 	char *name;
14570 #endif
14571 
14572 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14573 
14574 #ifdef DEBUG
14575 	name = fn_name(VTOSV(vp)->sv_name);
14576 	NFS4_DEBUG(nfs4_client_lock_debug,
14577 	    (CE_NOTE, "nfs4_register_lock_locally: %s: type %d, "
14578 	    "start %"PRIx64", length %"PRIx64", pid %ld, sysid %d",
14579 	    name, flk->l_type, flk->l_start, flk->l_len, (long)flk->l_pid,
14580 	    flk->l_sysid));
14581 	kmem_free(name, MAXNAMELEN);
14582 #endif
14583 
14584 	/* register the lock with local locking */
14585 	oldsysid = flk->l_sysid;
14586 	flk->l_sysid |= LM_SYSID_CLIENT;
14587 	error = reclock(vp, flk, SETFLCK, flag, offset, NULL);
14588 #ifdef DEBUG
14589 	if (error != 0) {
14590 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14591 		    "nfs4_register_lock_locally: could not register with"
14592 		    " local locking"));
14593 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14594 		    "error %d, vp 0x%p, pid %d, sysid 0x%x",
14595 		    error, (void *)vp, flk->l_pid, flk->l_sysid));
14596 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14597 		    "type %d off 0x%" PRIx64 " len 0x%" PRIx64,
14598 		    flk->l_type, flk->l_start, flk->l_len));
14599 		(void) reclock(vp, flk, 0, flag, offset, NULL);
14600 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14601 		    "blocked by pid %d sysid 0x%x type %d "
14602 		    "off 0x%" PRIx64 " len 0x%" PRIx64,
14603 		    flk->l_pid, flk->l_sysid, flk->l_type, flk->l_start,
14604 		    flk->l_len));
14605 	}
14606 #endif
14607 	flk->l_sysid = oldsysid;
14608 }
14609 
14610 /*
14611  * nfs4_lockrelease:
14612  *
14613  * Release any locks on the given vnode that are held by the current
14614  * process.  Also removes the lock owner (if one exists) from the rnode's
14615  * list.
14616  */
14617 static int
14618 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14619 {
14620 	flock64_t ld;
14621 	int ret, error;
14622 	rnode4_t *rp;
14623 	nfs4_lock_owner_t *lop;
14624 	nfs4_recov_state_t recov_state;
14625 	mntinfo4_t *mi;
14626 	bool_t possible_orphan = FALSE;
14627 	bool_t recovonly;
14628 
14629 	ASSERT((uintptr_t)vp > KERNELBASE);
14630 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14631 
14632 	rp = VTOR4(vp);
14633 	mi = VTOMI4(vp);
14634 
14635 	/*
14636 	 * If we have not locked anything then we can
14637 	 * just return since we have no work to do.
14638 	 */
14639 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14640 		return (0);
14641 	}
14642 
14643 	/*
14644 	 * We need to comprehend that another thread may
14645 	 * kick off recovery and the lock_owner we have stashed
14646 	 * in lop might be invalid so we should NOT cache it
14647 	 * locally!
14648 	 */
14649 	recov_state.rs_flags = 0;
14650 	recov_state.rs_num_retry_despite_err = 0;
14651 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14652 	    &recovonly);
14653 	if (error) {
14654 		mutex_enter(&rp->r_statelock);
14655 		rp->r_flags |= R4LODANGLERS;
14656 		mutex_exit(&rp->r_statelock);
14657 		return (error);
14658 	}
14659 
14660 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14661 
14662 	/*
14663 	 * Check if the lock owner might have a lock (request was sent but
14664 	 * no response was received).  Also check if there are any remote
14665 	 * locks on the file.  (In theory we shouldn't have to make this
14666 	 * second check if there's no lock owner, but for now we'll be
14667 	 * conservative and do it anyway.)  If either condition is true,
14668 	 * send an unlock for the entire file to the server.
14669 	 *
14670 	 * Note that no explicit synchronization is needed here.  At worst,
14671 	 * flk_has_remote_locks() will return a false positive, in which case
14672 	 * the unlock call wastes time but doesn't harm correctness.
14673 	 */
14674 
14675 	if (lop) {
14676 		mutex_enter(&lop->lo_lock);
14677 		possible_orphan = lop->lo_pending_rqsts;
14678 		mutex_exit(&lop->lo_lock);
14679 		lock_owner_rele(lop);
14680 	}
14681 
14682 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14683 
14684 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14685 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14686 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14687 	    (void *)lop));
14688 
14689 	if (possible_orphan || flk_has_remote_locks(vp)) {
14690 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14691 		ld.l_whence = 0;	/* unlock from start of file */
14692 		ld.l_start = 0;
14693 		ld.l_len = 0;		/* do entire file */
14694 
14695 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL,
14696 		    cr, NULL);
14697 
14698 		if (ret != 0) {
14699 			/*
14700 			 * If VOP_FRLOCK fails, make sure we unregister
14701 			 * local locks before we continue.
14702 			 */
14703 			ld.l_pid = ttoproc(curthread)->p_pid;
14704 			nfs4_register_lock_locally(vp, &ld, flag, offset);
14705 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14706 			    "nfs4_lockrelease: lock release error on vp"
14707 			    " %p: error %d.\n", (void *)vp, ret));
14708 		}
14709 	}
14710 
14711 	recov_state.rs_flags = 0;
14712 	recov_state.rs_num_retry_despite_err = 0;
14713 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14714 	    &recovonly);
14715 	if (error) {
14716 		mutex_enter(&rp->r_statelock);
14717 		rp->r_flags |= R4LODANGLERS;
14718 		mutex_exit(&rp->r_statelock);
14719 		return (error);
14720 	}
14721 
14722 	/*
14723 	 * So, here we're going to need to retrieve the lock-owner
14724 	 * again (in case recovery has done a switch-a-roo) and
14725 	 * remove it because we can.
14726 	 */
14727 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14728 
14729 	if (lop) {
14730 		nfs4_rnode_remove_lock_owner(rp, lop);
14731 		lock_owner_rele(lop);
14732 	}
14733 
14734 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14735 	return (0);
14736 }
14737 
14738 /*
14739  * Wait for 'tick_delay' clock ticks.
14740  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14741  * NOTE: lock_lease_time is in seconds.
14742  *
14743  * XXX For future improvements, should implement a waiting queue scheme.
14744  */
14745 static int
14746 nfs4_block_and_wait(clock_t *tick_delay, rnode4_t *rp)
14747 {
14748 	long milliseconds_delay;
14749 	time_t lock_lease_time;
14750 
14751 	/* wait tick_delay clock ticks or siginteruptus */
14752 	if (delay_sig(*tick_delay)) {
14753 		return (EINTR);
14754 	}
14755 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14756 	    "reissue the lock request: blocked for %ld clock ticks: %ld "
14757 	    "milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14758 
14759 	/* get the lease time */
14760 	lock_lease_time = r2lease_time(rp);
14761 
14762 	/* drv_hztousec converts ticks to microseconds */
14763 	milliseconds_delay = drv_hztousec(*tick_delay) / 1000;
14764 	if (milliseconds_delay < lock_lease_time * 1000) {
14765 		*tick_delay = 2 * *tick_delay;
14766 		if (drv_hztousec(*tick_delay) > lock_lease_time * 1000 * 1000)
14767 			*tick_delay = drv_usectohz(lock_lease_time*1000*1000);
14768 	}
14769 	return (0);
14770 }
14771 
14772 
14773 void
14774 nfs4_vnops_init(void)
14775 {
14776 }
14777 
14778 void
14779 nfs4_vnops_fini(void)
14780 {
14781 }
14782 
14783 /*
14784  * Return a reference to the directory (parent) vnode for a given vnode,
14785  * using the saved pathname information and the directory file handle.  The
14786  * caller is responsible for disposing of the reference.
14787  * Returns zero or an errno value.
14788  *
14789  * Caller should set need_start_op to FALSE if it is the recovery
14790  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14791  */
14792 int
14793 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14794 {
14795 	svnode_t *svnp;
14796 	vnode_t *dvp = NULL;
14797 	servinfo4_t *svp;
14798 	nfs4_fname_t *mfname;
14799 	int error;
14800 
14801 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14802 
14803 	if (vp->v_flag & VROOT) {
14804 		nfs4_sharedfh_t *sfh;
14805 		nfs_fh4 fh;
14806 		mntinfo4_t *mi;
14807 
14808 		ASSERT(vp->v_type == VREG);
14809 
14810 		mi = VTOMI4(vp);
14811 		svp = mi->mi_curr_serv;
14812 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14813 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14814 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14815 		sfh = sfh4_get(&fh, VTOMI4(vp));
14816 		nfs_rw_exit(&svp->sv_lock);
14817 		mfname = mi->mi_fname;
14818 		fn_hold(mfname);
14819 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14820 		sfh4_rele(&sfh);
14821 
14822 		if (dvp->v_type == VNON)
14823 			dvp->v_type = VDIR;
14824 		*dvpp = dvp;
14825 		return (0);
14826 	}
14827 
14828 	svnp = VTOSV(vp);
14829 
14830 	if (svnp == NULL) {
14831 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14832 		    "shadow node is NULL"));
14833 		return (EINVAL);
14834 	}
14835 
14836 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14837 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14838 		    "shadow node name or dfh val == NULL"));
14839 		return (EINVAL);
14840 	}
14841 
14842 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14843 	    (int)need_start_op);
14844 	if (error != 0) {
14845 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14846 		    "nfs4_make_dotdot returned %d", error));
14847 		return (error);
14848 	}
14849 	if (!dvp) {
14850 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14851 		    "nfs4_make_dotdot returned a NULL dvp"));
14852 		return (EIO);
14853 	}
14854 	if (dvp->v_type == VNON)
14855 		dvp->v_type = VDIR;
14856 	ASSERT(dvp->v_type == VDIR);
14857 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14858 		mutex_enter(&dvp->v_lock);
14859 		dvp->v_flag |= V_XATTRDIR;
14860 		mutex_exit(&dvp->v_lock);
14861 	}
14862 	*dvpp = dvp;
14863 	return (0);
14864 }
14865 
14866 /*
14867  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14868  * length that fnamep can accept, including the trailing null.
14869  * Returns 0 if okay, returns an errno value if there was a problem.
14870  */
14871 
14872 int
14873 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14874 {
14875 	char *fn;
14876 	int err = 0;
14877 	servinfo4_t *svp;
14878 	svnode_t *shvp;
14879 
14880 	/*
14881 	 * If the file being opened has VROOT set, then this is
14882 	 * a "file" mount.  sv_name will not be interesting, so
14883 	 * go back to the servinfo4 to get the original mount
14884 	 * path and strip off all but the final edge.  Otherwise
14885 	 * just return the name from the shadow vnode.
14886 	 */
14887 
14888 	if (vp->v_flag & VROOT) {
14889 
14890 		svp = VTOMI4(vp)->mi_curr_serv;
14891 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14892 
14893 		fn = strrchr(svp->sv_path, '/');
14894 		if (fn == NULL)
14895 			err = EINVAL;
14896 		else
14897 			fn++;
14898 	} else {
14899 		shvp = VTOSV(vp);
14900 		fn = fn_name(shvp->sv_name);
14901 	}
14902 
14903 	if (err == 0)
14904 		if (strlen(fn) < maxlen)
14905 			(void) strcpy(fnamep, fn);
14906 		else
14907 			err = ENAMETOOLONG;
14908 
14909 	if (vp->v_flag & VROOT)
14910 		nfs_rw_exit(&svp->sv_lock);
14911 	else
14912 		kmem_free(fn, MAXNAMELEN);
14913 
14914 	return (err);
14915 }
14916 
14917 /*
14918  * Bookkeeping for a close that doesn't need to go over the wire.
14919  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14920  * it is left at 1.
14921  */
14922 void
14923 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14924 {
14925 	rnode4_t		*rp;
14926 	mntinfo4_t		*mi;
14927 
14928 	mi = VTOMI4(vp);
14929 	rp = VTOR4(vp);
14930 
14931 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14932 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14933 	ASSERT(nfs_zone() == mi->mi_zone);
14934 	ASSERT(mutex_owned(&osp->os_sync_lock));
14935 	ASSERT(*have_lockp);
14936 
14937 	if (!osp->os_valid ||
14938 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14939 		return;
14940 	}
14941 
14942 	/*
14943 	 * This removes the reference obtained at OPEN; ie,
14944 	 * when the open stream structure was created.
14945 	 *
14946 	 * We don't have to worry about calling 'open_stream_rele'
14947 	 * since we our currently holding a reference to this
14948 	 * open stream which means the count can not go to 0 with
14949 	 * this decrement.
14950 	 */
14951 	ASSERT(osp->os_ref_count >= 2);
14952 	osp->os_ref_count--;
14953 	osp->os_valid = 0;
14954 	mutex_exit(&osp->os_sync_lock);
14955 	*have_lockp = 0;
14956 
14957 	nfs4_dec_state_ref_count(mi);
14958 }
14959 
14960 /*
14961  * Close all remaining open streams on the rnode.  These open streams
14962  * could be here because:
14963  * - The close attempted at either close or delmap failed
14964  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
14965  * - Someone did mknod on a regular file but never opened it
14966  */
14967 int
14968 nfs4close_all(vnode_t *vp, cred_t *cr)
14969 {
14970 	nfs4_open_stream_t *osp;
14971 	int error;
14972 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
14973 	rnode4_t *rp;
14974 
14975 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14976 
14977 	error = 0;
14978 	rp = VTOR4(vp);
14979 
14980 	/*
14981 	 * At this point, all we know is that the last time
14982 	 * someone called vn_rele, the count was 1.  Since then,
14983 	 * the vnode could have been re-activated.  We want to
14984 	 * loop through the open streams and close each one, but
14985 	 * we have to be careful since once we release the rnode
14986 	 * hash bucket lock, someone else is free to come in and
14987 	 * re-activate the rnode and add new open streams.  The
14988 	 * strategy is take the rnode hash bucket lock, verify that
14989 	 * the count is still 1, grab the open stream off the
14990 	 * head of the list and mark it invalid, then release the
14991 	 * rnode hash bucket lock and proceed with that open stream.
14992 	 * This is ok because nfs4close_one() will acquire the proper
14993 	 * open/create to close/destroy synchronization for open
14994 	 * streams, and will ensure that if someone has reopened
14995 	 * the open stream after we've dropped the hash bucket lock
14996 	 * then we'll just simply return without destroying the
14997 	 * open stream.
14998 	 * Repeat until the list is empty.
14999 	 */
15000 
15001 	for (;;) {
15002 
15003 		/* make sure vnode hasn't been reactivated */
15004 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
15005 		mutex_enter(&vp->v_lock);
15006 		if (vp->v_count > 1) {
15007 			mutex_exit(&vp->v_lock);
15008 			rw_exit(&rp->r_hashq->r_lock);
15009 			break;
15010 		}
15011 		/*
15012 		 * Grabbing r_os_lock before releasing v_lock prevents
15013 		 * a window where the rnode/open stream could get
15014 		 * reactivated (and os_force_close set to 0) before we
15015 		 * had a chance to set os_force_close to 1.
15016 		 */
15017 		mutex_enter(&rp->r_os_lock);
15018 		mutex_exit(&vp->v_lock);
15019 
15020 		osp = list_head(&rp->r_open_streams);
15021 		if (!osp) {
15022 			/* nothing left to CLOSE OTW, so return */
15023 			mutex_exit(&rp->r_os_lock);
15024 			rw_exit(&rp->r_hashq->r_lock);
15025 			break;
15026 		}
15027 
15028 		mutex_enter(&rp->r_statev4_lock);
15029 		/* the file can't still be mem mapped */
15030 		ASSERT(rp->r_mapcnt == 0);
15031 		if (rp->created_v4)
15032 			rp->created_v4 = 0;
15033 		mutex_exit(&rp->r_statev4_lock);
15034 
15035 		/*
15036 		 * Grab a ref on this open stream; nfs4close_one
15037 		 * will mark it as invalid
15038 		 */
15039 		mutex_enter(&osp->os_sync_lock);
15040 		osp->os_ref_count++;
15041 		osp->os_force_close = 1;
15042 		mutex_exit(&osp->os_sync_lock);
15043 		mutex_exit(&rp->r_os_lock);
15044 		rw_exit(&rp->r_hashq->r_lock);
15045 
15046 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
15047 
15048 		/* Update error if it isn't already non-zero */
15049 		if (error == 0) {
15050 			if (e.error)
15051 				error = e.error;
15052 			else if (e.stat)
15053 				error = geterrno4(e.stat);
15054 		}
15055 
15056 #ifdef	DEBUG
15057 		nfs4close_all_cnt++;
15058 #endif
15059 		/* Release the ref on osp acquired above. */
15060 		open_stream_rele(osp, rp);
15061 
15062 		/* Proceed to the next open stream, if any */
15063 	}
15064 	return (error);
15065 }
15066 
15067 /*
15068  * nfs4close_one - close one open stream for a file if needed.
15069  *
15070  * "close_type" indicates which close path this is:
15071  * CLOSE_NORM: close initiated via VOP_CLOSE.
15072  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
15073  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
15074  *	the close and release of client state for this open stream
15075  *	(unless someone else has the open stream open).
15076  * CLOSE_RESEND: indicates the request is a replay of an earlier request
15077  *	(e.g., due to abort because of a signal).
15078  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
15079  *
15080  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
15081  * recovery.  Instead, the caller is expected to deal with retries.
15082  *
15083  * The caller can either pass in the osp ('provided_osp') or not.
15084  *
15085  * 'access_bits' represents the access we are closing/downgrading.
15086  *
15087  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
15088  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
15089  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
15090  *
15091  * Errors are returned via the nfs4_error_t.
15092  */
15093 void
15094 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
15095     int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
15096     nfs4_close_type_t close_type, size_t len, uint_t maxprot,
15097     uint_t mmap_flags)
15098 {
15099 	nfs4_open_owner_t *oop;
15100 	nfs4_open_stream_t *osp = NULL;
15101 	int retry = 0;
15102 	int num_retries = NFS4_NUM_RECOV_RETRIES;
15103 	rnode4_t *rp;
15104 	mntinfo4_t *mi;
15105 	nfs4_recov_state_t recov_state;
15106 	cred_t *cred_otw = NULL;
15107 	bool_t recovonly = FALSE;
15108 	int isrecov;
15109 	int force_close;
15110 	int close_failed = 0;
15111 	int did_dec_count = 0;
15112 	int did_start_op = 0;
15113 	int did_force_recovlock = 0;
15114 	int did_start_seqid_sync = 0;
15115 	int have_sync_lock = 0;
15116 
15117 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15118 
15119 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
15120 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
15121 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
15122 	    len, maxprot, mmap_flags, access_bits));
15123 
15124 	nfs4_error_zinit(ep);
15125 	rp = VTOR4(vp);
15126 	mi = VTOMI4(vp);
15127 	isrecov = (close_type == CLOSE_RESEND ||
15128 	    close_type == CLOSE_AFTER_RESEND);
15129 
15130 	/*
15131 	 * First get the open owner.
15132 	 */
15133 	if (!provided_osp) {
15134 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
15135 	} else {
15136 		oop = provided_osp->os_open_owner;
15137 		ASSERT(oop != NULL);
15138 		open_owner_hold(oop);
15139 	}
15140 
15141 	if (!oop) {
15142 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15143 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15144 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15145 		    (void *)provided_osp, close_type));
15146 		ep->error = EIO;
15147 		goto out;
15148 	}
15149 
15150 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15151 recov_retry:
15152 	osp = NULL;
15153 	close_failed = 0;
15154 	force_close = (close_type == CLOSE_FORCE);
15155 	retry = 0;
15156 	did_start_op = 0;
15157 	did_force_recovlock = 0;
15158 	did_start_seqid_sync = 0;
15159 	have_sync_lock = 0;
15160 	recovonly = FALSE;
15161 	recov_state.rs_flags = 0;
15162 	recov_state.rs_num_retry_despite_err = 0;
15163 
15164 	/*
15165 	 * Second synchronize with recovery.
15166 	 */
15167 	if (!isrecov) {
15168 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15169 		    &recov_state, &recovonly);
15170 		if (!ep->error) {
15171 			did_start_op = 1;
15172 		} else {
15173 			close_failed = 1;
15174 			/*
15175 			 * If we couldn't get start_fop, but have to
15176 			 * cleanup state, then at least acquire the
15177 			 * mi_recovlock so we can synchronize with
15178 			 * recovery.
15179 			 */
15180 			if (close_type == CLOSE_FORCE) {
15181 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15182 				    RW_READER, FALSE);
15183 				did_force_recovlock = 1;
15184 			} else
15185 				goto out;
15186 		}
15187 	}
15188 
15189 	/*
15190 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15191 	 * set 'recovonly' to TRUE since most likely this is due to
15192 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15193 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15194 	 * to retry, causing us to loop until recovery finishes.  Plus we
15195 	 * don't need protection over the open seqid since we're not going
15196 	 * OTW, hence don't need to use the seqid.
15197 	 */
15198 	if (recovonly == FALSE) {
15199 		/* need to grab the open owner sync before 'os_sync_lock' */
15200 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15201 		if (ep->error == EAGAIN) {
15202 			ASSERT(!isrecov);
15203 			if (did_start_op)
15204 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15205 				    &recov_state, TRUE);
15206 			if (did_force_recovlock)
15207 				nfs_rw_exit(&mi->mi_recovlock);
15208 			goto recov_retry;
15209 		}
15210 		did_start_seqid_sync = 1;
15211 	}
15212 
15213 	/*
15214 	 * Third get an open stream and acquire 'os_sync_lock' to
15215 	 * sychronize the opening/creating of an open stream with the
15216 	 * closing/destroying of an open stream.
15217 	 */
15218 	if (!provided_osp) {
15219 		/* returns with 'os_sync_lock' held */
15220 		osp = find_open_stream(oop, rp);
15221 		if (!osp) {
15222 			ep->error = EIO;
15223 			goto out;
15224 		}
15225 	} else {
15226 		osp = provided_osp;
15227 		open_stream_hold(osp);
15228 		mutex_enter(&osp->os_sync_lock);
15229 	}
15230 	have_sync_lock = 1;
15231 
15232 	ASSERT(oop == osp->os_open_owner);
15233 
15234 	/*
15235 	 * Fourth, do any special pre-OTW CLOSE processing
15236 	 * based on the specific close type.
15237 	 */
15238 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15239 	    !did_dec_count) {
15240 		ASSERT(osp->os_open_ref_count > 0);
15241 		osp->os_open_ref_count--;
15242 		did_dec_count = 1;
15243 		if (osp->os_open_ref_count == 0)
15244 			osp->os_final_close = 1;
15245 	}
15246 
15247 	if (close_type == CLOSE_FORCE) {
15248 		/* see if somebody reopened the open stream. */
15249 		if (!osp->os_force_close) {
15250 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15251 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15252 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15253 			ep->error = 0;
15254 			ep->stat = NFS4_OK;
15255 			goto out;
15256 		}
15257 
15258 		if (!osp->os_final_close && !did_dec_count) {
15259 			osp->os_open_ref_count--;
15260 			did_dec_count = 1;
15261 		}
15262 
15263 		/*
15264 		 * We can't depend on os_open_ref_count being 0 due to the
15265 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15266 		 */
15267 #ifdef	NOTYET
15268 		ASSERT(osp->os_open_ref_count == 0);
15269 #endif
15270 		if (osp->os_open_ref_count != 0) {
15271 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15272 			    "nfs4close_one: should panic here on an "
15273 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15274 			    "since this is probably the exec problem."));
15275 
15276 			osp->os_open_ref_count = 0;
15277 		}
15278 
15279 		/*
15280 		 * There is the possibility that nfs4close_one()
15281 		 * for close_type == CLOSE_DELMAP couldn't find the
15282 		 * open stream, thus couldn't decrement its os_mapcnt;
15283 		 * therefore we can't use this ASSERT yet.
15284 		 */
15285 #ifdef	NOTYET
15286 		ASSERT(osp->os_mapcnt == 0);
15287 #endif
15288 		osp->os_mapcnt = 0;
15289 	}
15290 
15291 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15292 		ASSERT(osp->os_mapcnt >= btopr(len));
15293 
15294 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15295 			osp->os_mmap_write -= btopr(len);
15296 		if (maxprot & PROT_READ)
15297 			osp->os_mmap_read -= btopr(len);
15298 		if (maxprot & PROT_EXEC)
15299 			osp->os_mmap_read -= btopr(len);
15300 		/* mirror the PROT_NONE check in nfs4_addmap() */
15301 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15302 		    !(maxprot & PROT_EXEC))
15303 			osp->os_mmap_read -= btopr(len);
15304 		osp->os_mapcnt -= btopr(len);
15305 		did_dec_count = 1;
15306 	}
15307 
15308 	if (recovonly) {
15309 		nfs4_lost_rqst_t lost_rqst;
15310 
15311 		/* request should not already be in recovery queue */
15312 		ASSERT(lrp == NULL);
15313 		nfs4_error_init(ep, EINTR);
15314 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15315 		    osp, cred_otw, vp);
15316 		mutex_exit(&osp->os_sync_lock);
15317 		have_sync_lock = 0;
15318 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15319 		    lost_rqst.lr_op == OP_CLOSE ?
15320 		    &lost_rqst : NULL, OP_CLOSE, NULL, NULL, NULL);
15321 		close_failed = 1;
15322 		force_close = 0;
15323 		goto close_cleanup;
15324 	}
15325 
15326 	/*
15327 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15328 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15329 	 * space, which means we stopped operating on the open stream
15330 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15331 	 * stateid could be stale, potentially triggering a false
15332 	 * setclientid), and just clean up the client's internal state.
15333 	 */
15334 	if (osp->os_orig_oo_name != oop->oo_name) {
15335 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15336 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15337 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15338 		    "oo_name %" PRIx64")",
15339 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15340 		    oop->oo_name));
15341 		close_failed = 1;
15342 	}
15343 
15344 	/* If the file failed recovery, just quit. */
15345 	mutex_enter(&rp->r_statelock);
15346 	if (rp->r_flags & R4RECOVERR) {
15347 		close_failed = 1;
15348 	}
15349 	mutex_exit(&rp->r_statelock);
15350 
15351 	/*
15352 	 * If the force close path failed to obtain start_fop
15353 	 * then skip the OTW close and just remove the state.
15354 	 */
15355 	if (close_failed)
15356 		goto close_cleanup;
15357 
15358 	/*
15359 	 * Fifth, check to see if there are still mapped pages or other
15360 	 * opens using this open stream.  If there are then we can't
15361 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15362 	 */
15363 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15364 		nfs4_lost_rqst_t	new_lost_rqst;
15365 		bool_t			needrecov = FALSE;
15366 		cred_t			*odg_cred_otw = NULL;
15367 		seqid4			open_dg_seqid = 0;
15368 
15369 		if (osp->os_delegation) {
15370 			/*
15371 			 * If this open stream was never OPENed OTW then we
15372 			 * surely can't DOWNGRADE it (especially since the
15373 			 * osp->open_stateid is really a delegation stateid
15374 			 * when os_delegation is 1).
15375 			 */
15376 			if (access_bits & FREAD)
15377 				osp->os_share_acc_read--;
15378 			if (access_bits & FWRITE)
15379 				osp->os_share_acc_write--;
15380 			osp->os_share_deny_none--;
15381 			nfs4_error_zinit(ep);
15382 			goto out;
15383 		}
15384 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15385 		    lrp, ep, &odg_cred_otw, &open_dg_seqid);
15386 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15387 		if (needrecov && !isrecov) {
15388 			bool_t abort;
15389 			nfs4_bseqid_entry_t *bsep = NULL;
15390 
15391 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15392 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15393 				    vp, 0,
15394 				    lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15395 				    open_dg_seqid);
15396 
15397 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15398 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15399 			mutex_exit(&osp->os_sync_lock);
15400 			have_sync_lock = 0;
15401 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15402 			    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15403 			    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15404 			    bsep, NULL, NULL);
15405 			if (odg_cred_otw)
15406 				crfree(odg_cred_otw);
15407 			if (bsep)
15408 				kmem_free(bsep, sizeof (*bsep));
15409 
15410 			if (abort == TRUE)
15411 				goto out;
15412 
15413 			if (did_start_seqid_sync) {
15414 				nfs4_end_open_seqid_sync(oop);
15415 				did_start_seqid_sync = 0;
15416 			}
15417 			open_stream_rele(osp, rp);
15418 
15419 			if (did_start_op)
15420 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15421 				    &recov_state, FALSE);
15422 			if (did_force_recovlock)
15423 				nfs_rw_exit(&mi->mi_recovlock);
15424 
15425 			goto recov_retry;
15426 		} else {
15427 			if (odg_cred_otw)
15428 				crfree(odg_cred_otw);
15429 		}
15430 		goto out;
15431 	}
15432 
15433 	/*
15434 	 * If this open stream was created as the results of an open
15435 	 * while holding a delegation, then just release it; no need
15436 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15437 	 */
15438 	if (osp->os_delegation) {
15439 		nfs4close_notw(vp, osp, &have_sync_lock);
15440 		nfs4_error_zinit(ep);
15441 		goto out;
15442 	}
15443 
15444 	/*
15445 	 * If this stream is not valid, we're done.
15446 	 */
15447 	if (!osp->os_valid) {
15448 		nfs4_error_zinit(ep);
15449 		goto out;
15450 	}
15451 
15452 	/*
15453 	 * Last open or mmap ref has vanished, need to do an OTW close.
15454 	 * First check to see if a close is still necessary.
15455 	 */
15456 	if (osp->os_failed_reopen) {
15457 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15458 		    "don't close OTW osp %p since reopen failed.",
15459 		    (void *)osp));
15460 		/*
15461 		 * Reopen of the open stream failed, hence the
15462 		 * stateid of the open stream is invalid/stale, and
15463 		 * sending this OTW would incorrectly cause another
15464 		 * round of recovery.  In this case, we need to set
15465 		 * the 'os_valid' bit to 0 so another thread doesn't
15466 		 * come in and re-open this open stream before
15467 		 * this "closing" thread cleans up state (decrementing
15468 		 * the nfs4_server_t's state_ref_count and decrementing
15469 		 * the os_ref_count).
15470 		 */
15471 		osp->os_valid = 0;
15472 		/*
15473 		 * This removes the reference obtained at OPEN; ie,
15474 		 * when the open stream structure was created.
15475 		 *
15476 		 * We don't have to worry about calling 'open_stream_rele'
15477 		 * since we our currently holding a reference to this
15478 		 * open stream which means the count can not go to 0 with
15479 		 * this decrement.
15480 		 */
15481 		ASSERT(osp->os_ref_count >= 2);
15482 		osp->os_ref_count--;
15483 		nfs4_error_zinit(ep);
15484 		close_failed = 0;
15485 		goto close_cleanup;
15486 	}
15487 
15488 	ASSERT(osp->os_ref_count > 1);
15489 
15490 	/*
15491 	 * Sixth, try the CLOSE OTW.
15492 	 */
15493 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15494 	    close_type, ep, &have_sync_lock);
15495 
15496 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15497 		/*
15498 		 * Let the recovery thread be responsible for
15499 		 * removing the state for CLOSE.
15500 		 */
15501 		close_failed = 1;
15502 		force_close = 0;
15503 		retry = 0;
15504 	}
15505 
15506 	/* See if we need to retry with a different cred */
15507 	if ((ep->error == EACCES ||
15508 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15509 	    cred_otw != cr) {
15510 		crfree(cred_otw);
15511 		cred_otw = cr;
15512 		crhold(cred_otw);
15513 		retry = 1;
15514 	}
15515 
15516 	if (ep->error || ep->stat)
15517 		close_failed = 1;
15518 
15519 	if (retry && !isrecov && num_retries-- > 0) {
15520 		if (have_sync_lock) {
15521 			mutex_exit(&osp->os_sync_lock);
15522 			have_sync_lock = 0;
15523 		}
15524 		if (did_start_seqid_sync) {
15525 			nfs4_end_open_seqid_sync(oop);
15526 			did_start_seqid_sync = 0;
15527 		}
15528 		open_stream_rele(osp, rp);
15529 
15530 		if (did_start_op)
15531 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15532 			    &recov_state, FALSE);
15533 		if (did_force_recovlock)
15534 			nfs_rw_exit(&mi->mi_recovlock);
15535 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15536 		    "nfs4close_one: need to retry the close "
15537 		    "operation"));
15538 		goto recov_retry;
15539 	}
15540 close_cleanup:
15541 	/*
15542 	 * Seventh and lastly, process our results.
15543 	 */
15544 	if (close_failed && force_close) {
15545 		/*
15546 		 * It's ok to drop and regrab the 'os_sync_lock' since
15547 		 * nfs4close_notw() will recheck to make sure the
15548 		 * "close"/removal of state should happen.
15549 		 */
15550 		if (!have_sync_lock) {
15551 			mutex_enter(&osp->os_sync_lock);
15552 			have_sync_lock = 1;
15553 		}
15554 		/*
15555 		 * This is last call, remove the ref on the open
15556 		 * stream created by open and clean everything up.
15557 		 */
15558 		osp->os_pending_close = 0;
15559 		nfs4close_notw(vp, osp, &have_sync_lock);
15560 		nfs4_error_zinit(ep);
15561 	}
15562 
15563 	if (!close_failed) {
15564 		if (have_sync_lock) {
15565 			osp->os_pending_close = 0;
15566 			mutex_exit(&osp->os_sync_lock);
15567 			have_sync_lock = 0;
15568 		} else {
15569 			mutex_enter(&osp->os_sync_lock);
15570 			osp->os_pending_close = 0;
15571 			mutex_exit(&osp->os_sync_lock);
15572 		}
15573 		if (did_start_op && recov_state.rs_sp != NULL) {
15574 			mutex_enter(&recov_state.rs_sp->s_lock);
15575 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15576 			mutex_exit(&recov_state.rs_sp->s_lock);
15577 		} else {
15578 			nfs4_dec_state_ref_count(mi);
15579 		}
15580 		nfs4_error_zinit(ep);
15581 	}
15582 
15583 out:
15584 	if (have_sync_lock)
15585 		mutex_exit(&osp->os_sync_lock);
15586 	if (did_start_op)
15587 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15588 		    recovonly ? TRUE : FALSE);
15589 	if (did_force_recovlock)
15590 		nfs_rw_exit(&mi->mi_recovlock);
15591 	if (cred_otw)
15592 		crfree(cred_otw);
15593 	if (osp)
15594 		open_stream_rele(osp, rp);
15595 	if (oop) {
15596 		if (did_start_seqid_sync)
15597 			nfs4_end_open_seqid_sync(oop);
15598 		open_owner_rele(oop);
15599 	}
15600 }
15601 
15602 /*
15603  * Convert information returned by the server in the LOCK4denied
15604  * structure to the form required by fcntl.
15605  */
15606 static void
15607 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15608 {
15609 	nfs4_lo_name_t *lo;
15610 
15611 #ifdef	DEBUG
15612 	if (denied_to_flk_debug) {
15613 		lockt_denied_debug = lockt_denied;
15614 		debug_enter("lockt_denied");
15615 	}
15616 #endif
15617 
15618 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15619 	flk->l_whence = 0;	/* aka SEEK_SET */
15620 	flk->l_start = lockt_denied->offset;
15621 	flk->l_len = lockt_denied->length;
15622 
15623 	/*
15624 	 * If the blocking clientid matches our client id, then we can
15625 	 * interpret the lockowner (since we built it).  If not, then
15626 	 * fabricate a sysid and pid.  Note that the l_sysid field
15627 	 * in *flk already has the local sysid.
15628 	 */
15629 
15630 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15631 
15632 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15633 			lo = (nfs4_lo_name_t *)
15634 			    lockt_denied->owner.owner_val;
15635 
15636 			flk->l_pid = lo->ln_pid;
15637 		} else {
15638 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15639 			    "denied_to_flk: bad lock owner length\n"));
15640 
15641 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15642 		}
15643 	} else {
15644 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15645 		"denied_to_flk: foreign clientid\n"));
15646 
15647 		/*
15648 		 * Construct a new sysid which should be different from
15649 		 * sysids of other systems.
15650 		 */
15651 
15652 		flk->l_sysid++;
15653 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15654 	}
15655 }
15656 
15657 static pid_t
15658 lo_to_pid(lock_owner4 *lop)
15659 {
15660 	pid_t pid = 0;
15661 	uchar_t *cp;
15662 	int i;
15663 
15664 	cp = (uchar_t *)&lop->clientid;
15665 
15666 	for (i = 0; i < sizeof (lop->clientid); i++)
15667 		pid += (pid_t)*cp++;
15668 
15669 	cp = (uchar_t *)lop->owner_val;
15670 
15671 	for (i = 0; i < lop->owner_len; i++)
15672 		pid += (pid_t)*cp++;
15673 
15674 	return (pid);
15675 }
15676 
15677 /*
15678  * Given a lock pointer, returns the length of that lock.
15679  * "end" is the last locked offset the "l_len" covers from
15680  * the start of the lock.
15681  */
15682 static off64_t
15683 lock_to_end(flock64_t *lock)
15684 {
15685 	off64_t lock_end;
15686 
15687 	if (lock->l_len == 0)
15688 		lock_end = (off64_t)MAXEND;
15689 	else
15690 		lock_end = lock->l_start + lock->l_len - 1;
15691 
15692 	return (lock_end);
15693 }
15694 
15695 /*
15696  * Given the end of a lock, it will return you the length "l_len" for that lock.
15697  */
15698 static off64_t
15699 end_to_len(off64_t start, off64_t end)
15700 {
15701 	off64_t lock_len;
15702 
15703 	ASSERT(end >= start);
15704 	if (end == MAXEND)
15705 		lock_len = 0;
15706 	else
15707 		lock_len = end - start + 1;
15708 
15709 	return (lock_len);
15710 }
15711 
15712 /*
15713  * On given end for a lock it determines if it is the last locked offset
15714  * or not, if so keeps it as is, else adds one to return the length for
15715  * valid start.
15716  */
15717 static off64_t
15718 start_check(off64_t x)
15719 {
15720 	if (x == MAXEND)
15721 		return (x);
15722 	else
15723 		return (x + 1);
15724 }
15725 
15726 /*
15727  * See if these two locks overlap, and if so return 1;
15728  * otherwise, return 0.
15729  */
15730 static int
15731 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15732 {
15733 	off64_t llfp_end, curfp_end;
15734 
15735 	llfp_end = lock_to_end(llfp);
15736 	curfp_end = lock_to_end(curfp);
15737 
15738 	if (((llfp_end >= curfp->l_start) &&
15739 	    (llfp->l_start <= curfp->l_start)) ||
15740 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15741 		return (1);
15742 	return (0);
15743 }
15744 
15745 /*
15746  * Determine what the intersecting lock region is, and add that to the
15747  * 'nl_llpp' locklist in increasing order (by l_start).
15748  */
15749 static void
15750 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15751     locklist_t **nl_llpp, vnode_t *vp)
15752 {
15753 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15754 	off64_t lost_flp_end, local_flp_end, len, start;
15755 
15756 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15757 
15758 	if (!locks_intersect(lost_flp, local_flp))
15759 		return;
15760 
15761 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15762 	    "locks intersect"));
15763 
15764 	lost_flp_end = lock_to_end(lost_flp);
15765 	local_flp_end = lock_to_end(local_flp);
15766 
15767 	/* Find the starting point of the intersecting region */
15768 	if (local_flp->l_start > lost_flp->l_start)
15769 		start = local_flp->l_start;
15770 	else
15771 		start = lost_flp->l_start;
15772 
15773 	/* Find the lenght of the intersecting region */
15774 	if (lost_flp_end < local_flp_end)
15775 		len = end_to_len(start, lost_flp_end);
15776 	else
15777 		len = end_to_len(start, local_flp_end);
15778 
15779 	/*
15780 	 * Prepare the flock structure for the intersection found and insert
15781 	 * it into the new list in increasing l_start order. This list contains
15782 	 * intersections of locks registered by the client with the local host
15783 	 * and the lost lock.
15784 	 * The lock type of this lock is the same as that of the local_flp.
15785 	 */
15786 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15787 	intersect_llp->ll_flock.l_start = start;
15788 	intersect_llp->ll_flock.l_len = len;
15789 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15790 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15791 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15792 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15793 	intersect_llp->ll_vp = vp;
15794 
15795 	tmp_fllp = *nl_llpp;
15796 	cur_fllp = NULL;
15797 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15798 	    intersect_llp->ll_flock.l_start) {
15799 			cur_fllp = tmp_fllp;
15800 			tmp_fllp = tmp_fllp->ll_next;
15801 	}
15802 	if (cur_fllp == NULL) {
15803 		/* first on the list */
15804 		intersect_llp->ll_next = *nl_llpp;
15805 		*nl_llpp = intersect_llp;
15806 	} else {
15807 		intersect_llp->ll_next = cur_fllp->ll_next;
15808 		cur_fllp->ll_next = intersect_llp;
15809 	}
15810 
15811 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15812 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15813 	    intersect_llp->ll_flock.l_start,
15814 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15815 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15816 }
15817 
15818 /*
15819  * Our local locking current state is potentially different than
15820  * what the NFSv4 server thinks we have due to a lost lock that was
15821  * resent and then received.  We need to reset our "NFSv4" locking
15822  * state to match the current local locking state for this pid since
15823  * that is what the user/application sees as what the world is.
15824  *
15825  * We cannot afford to drop the open/lock seqid sync since then we can
15826  * get confused about what the current local locking state "is" versus
15827  * "was".
15828  *
15829  * If we are unable to fix up the locks, we send SIGLOST to the affected
15830  * process.  This is not done if the filesystem has been forcibly
15831  * unmounted, in case the process has already exited and a new process
15832  * exists with the same pid.
15833  */
15834 static void
15835 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15836     nfs4_lock_owner_t *lop)
15837 {
15838 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15839 	mntinfo4_t *mi = VTOMI4(vp);
15840 	const int cmd = F_SETLK;
15841 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15842 	flock64_t ul_fl;
15843 
15844 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15845 	    "nfs4_reinstitute_local_lock_state"));
15846 
15847 	/*
15848 	 * Find active locks for this vp from the local locking code.
15849 	 * Scan through this list and find out the locks that intersect with
15850 	 * the lost lock. Once we find the lock that intersects, add the
15851 	 * intersection area as a new lock to a new list "ri_llp". The lock
15852 	 * type of the intersection region lock added to ri_llp is the same
15853 	 * as that found in the active lock list, "list". The intersecting
15854 	 * region locks are added to ri_llp in increasing l_start order.
15855 	 */
15856 	ASSERT(nfs_zone() == mi->mi_zone);
15857 
15858 	locks = flk_active_locks_for_vp(vp);
15859 	ri_llp = NULL;
15860 
15861 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15862 		ASSERT(llp->ll_vp == vp);
15863 		/*
15864 		 * Pick locks that belong to this pid/lockowner
15865 		 */
15866 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15867 			continue;
15868 
15869 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15870 	}
15871 
15872 	/*
15873 	 * Now we have the list of intersections with the lost lock. These are
15874 	 * the locks that were/are active before the server replied to the
15875 	 * last/lost lock. Issue these locks to the server here. Playing these
15876 	 * locks to the server will re-establish our current local locking state
15877 	 * with the v4 server.
15878 	 * If we get an error, send SIGLOST to the application for that lock.
15879 	 */
15880 
15881 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15882 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15883 		    "nfs4_reinstitute_local_lock_state: need to issue "
15884 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15885 		    llp->ll_flock.l_start,
15886 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15887 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15888 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15889 		/*
15890 		 * No need to relock what we already have
15891 		 */
15892 		if (llp->ll_flock.l_type == lost_flp->l_type)
15893 			continue;
15894 
15895 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15896 	}
15897 
15898 	/*
15899 	 * Now keeping the start of the lost lock as our reference parse the
15900 	 * newly created ri_llp locklist to find the ranges that we have locked
15901 	 * with the v4 server but not in the current local locking. We need
15902 	 * to unlock these ranges.
15903 	 * These ranges can also be reffered to as those ranges, where the lost
15904 	 * lock does not overlap with the locks in the ri_llp but are locked
15905 	 * since the server replied to the lost lock.
15906 	 */
15907 	cur_start = lost_flp->l_start;
15908 	lost_flp_end = lock_to_end(lost_flp);
15909 
15910 	ul_fl.l_type = F_UNLCK;
15911 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15912 	ul_fl.l_sysid = lost_flp->l_sysid;
15913 	ul_fl.l_pid = lost_flp->l_pid;
15914 
15915 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15916 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15917 
15918 		if (llp->ll_flock.l_start <= cur_start) {
15919 			cur_start = start_check(llp_ll_flock_end);
15920 			continue;
15921 		}
15922 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15923 		    "nfs4_reinstitute_local_lock_state: "
15924 		    "UNLOCK [%"PRIx64" - %"PRIx64"]",
15925 		    cur_start, llp->ll_flock.l_start));
15926 
15927 		ul_fl.l_start = cur_start;
15928 		ul_fl.l_len = end_to_len(cur_start,
15929 		    (llp->ll_flock.l_start - 1));
15930 
15931 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15932 		cur_start = start_check(llp_ll_flock_end);
15933 	}
15934 
15935 	/*
15936 	 * In the case where the lost lock ends after all intersecting locks,
15937 	 * unlock the last part of the lost lock range.
15938 	 */
15939 	if (cur_start != start_check(lost_flp_end)) {
15940 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15941 		    "nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15942 		    "lost lock region [%"PRIx64" - %"PRIx64"]",
15943 		    cur_start, lost_flp->l_start + lost_flp->l_len));
15944 
15945 		ul_fl.l_start = cur_start;
15946 		/*
15947 		 * Is it an to-EOF lock? if so unlock till the end
15948 		 */
15949 		if (lost_flp->l_len == 0)
15950 			ul_fl.l_len = 0;
15951 		else
15952 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15953 
15954 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15955 	}
15956 
15957 	if (locks != NULL)
15958 		flk_free_locklist(locks);
15959 
15960 	/* Free up our newly created locklist */
15961 	for (llp = ri_llp; llp != NULL; ) {
15962 		tmp_llp = llp->ll_next;
15963 		kmem_free(llp, sizeof (locklist_t));
15964 		llp = tmp_llp;
15965 	}
15966 
15967 	/*
15968 	 * Now return back to the original calling nfs4frlock()
15969 	 * and let us naturally drop our seqid syncs.
15970 	 */
15971 }
15972 
15973 /*
15974  * Create a lost state record for the given lock reinstantiation request
15975  * and push it onto the lost state queue.
15976  */
15977 static void
15978 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
15979     nfs4_lock_owner_t *lop)
15980 {
15981 	nfs4_lost_rqst_t req;
15982 	nfs_lock_type4 locktype;
15983 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
15984 
15985 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15986 
15987 	locktype = flk_to_locktype(cmd, flk->l_type);
15988 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
15989 	    NULL, NULL, lop, flk, &req, cr, vp);
15990 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
15991 	    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
15992 	    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
15993 	    NULL, NULL, NULL);
15994 }
15995