xref: /illumos-gate/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision cd277642e0bdc71a7f57c550df1279b0c091d6e2)
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 			(void) 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 		(void) 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 			(void) 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 			(void) 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 		(void) 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 			/*
1560 			 * Couldn't correct the attributes of
1561 			 * the newly created file and the
1562 			 * attributes are wrong.  Remove the
1563 			 * file and return an error to the
1564 			 * application.
1565 			 */
1566 			/* XXX will this take care of client state ? */
1567 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1568 			    "nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1569 			    " remove file", e.error));
1570 			VN_RELE(vp);
1571 			(void) nfs4_remove(dvp, file_name, cr, NULL, 0);
1572 			/*
1573 			 * Since we've reled the vnode and removed
1574 			 * the file we now need to return the error.
1575 			 * At this point we don't want to update the
1576 			 * dircaches, call nfs4_waitfor_purge_complete
1577 			 * or set vpp to vp so we need to skip these
1578 			 * as well.
1579 			 */
1580 			goto skip_update_dircaches;
1581 		}
1582 	}
1583 
1584 	/*
1585 	 * If we created or found the correct vnode, due to create_flag or
1586 	 * fh_differs being set, then update directory cache attribute, readdir
1587 	 * and dnlc caches.
1588 	 */
1589 	if (create_flag || fh_differs) {
1590 		dirattr_info_t dinfo, *dinfop;
1591 
1592 		/*
1593 		 * Make sure getattr succeeded before using results.
1594 		 * note: op 7 is getattr(dir) for both flavors of
1595 		 * open(create).
1596 		 */
1597 		if (create_flag && res.status == NFS4_OK) {
1598 			dinfo.di_time_call = t;
1599 			dinfo.di_cred = cr;
1600 			dinfo.di_garp =
1601 			    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
1602 			dinfop = &dinfo;
1603 		} else {
1604 			dinfop = NULL;
1605 		}
1606 
1607 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1608 		    dinfop);
1609 	}
1610 
1611 	/*
1612 	 * If the page cache for this file was flushed from actions
1613 	 * above, it was done asynchronously and if that is true,
1614 	 * there is a need to wait here for it to complete.  This must
1615 	 * be done outside of start_fop/end_fop.
1616 	 */
1617 	(void) nfs4_waitfor_purge_complete(vp);
1618 
1619 	/*
1620 	 * It is implicit that we are in the open case (create_flag == 0) since
1621 	 * fh_differs can only be set to a non-zero value in the open case.
1622 	 */
1623 	if (fh_differs != 0 && vpi != NULL)
1624 		VN_RELE(vpi);
1625 
1626 	/*
1627 	 * Be sure to set *vpp to the correct value before returning.
1628 	 */
1629 	*vpp = vp;
1630 
1631 skip_update_dircaches:
1632 
1633 	nfs4args_copen_free(open_args);
1634 	if (setgid_flag) {
1635 		nfs4args_verify_free(&argop[8]);
1636 		nfs4args_setattr_free(&argop[9]);
1637 	}
1638 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1639 
1640 	if (ncr)
1641 		crfree(ncr);
1642 	kmem_free(argop, argoplist_size);
1643 	return (e.error);
1644 }
1645 
1646 /*
1647  * Reopen an open instance.  cf. nfs4open_otw().
1648  *
1649  * Errors are returned by the nfs4_error_t parameter.
1650  * - ep->error contains an errno value or zero.
1651  * - if it is zero, ep->stat is set to an NFS status code, if any.
1652  *   If the file could not be reopened, but the caller should continue, the
1653  *   file is marked dead and no error values are returned.  If the caller
1654  *   should stop recovering open files and start over, either the ep->error
1655  *   value or ep->stat will indicate an error (either something that requires
1656  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1657  *   filehandles) may be handled silently by this routine.
1658  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1659  *   will be started, so the caller should not do it.
1660  *
1661  * Gotos:
1662  * - kill_file : reopen failed in such a fashion to constitute marking the
1663  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1664  *   is for cases where recovery is not possible.
1665  * - failed_reopen : same as above, except that the file has already been
1666  *   marked dead, so no need to do it again.
1667  * - bailout : reopen failed but we are able to recover and retry the reopen -
1668  *   either within this function immediately or via the calling function.
1669  */
1670 
1671 void
1672 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1673     open_claim_type4 claim, bool_t frc_use_claim_previous,
1674     bool_t is_recov)
1675 {
1676 	COMPOUND4args_clnt args;
1677 	COMPOUND4res_clnt res;
1678 	nfs_argop4 argop[4];
1679 	nfs_resop4 *resop;
1680 	OPEN4res *op_res = NULL;
1681 	OPEN4cargs *open_args;
1682 	GETFH4res *gf_res;
1683 	rnode4_t *rp = VTOR4(vp);
1684 	int doqueue = 1;
1685 	cred_t *cr = NULL, *cred_otw = NULL;
1686 	nfs4_open_owner_t *oop = NULL;
1687 	seqid4 seqid;
1688 	nfs4_ga_res_t *garp;
1689 	char fn[MAXNAMELEN];
1690 	nfs4_recov_state_t recov = {NULL, 0};
1691 	nfs4_lost_rqst_t lost_rqst;
1692 	mntinfo4_t *mi = VTOMI4(vp);
1693 	bool_t abort;
1694 	char *failed_msg = "";
1695 	int fh_different;
1696 	hrtime_t t;
1697 	nfs4_bseqid_entry_t *bsep = NULL;
1698 
1699 	ASSERT(nfs4_consistent_type(vp));
1700 	ASSERT(nfs_zone() == mi->mi_zone);
1701 
1702 	nfs4_error_zinit(ep);
1703 
1704 	/* this is the cred used to find the open owner */
1705 	cr = state_to_cred(osp);
1706 	if (cr == NULL) {
1707 		failed_msg = "Couldn't reopen: no cred";
1708 		goto kill_file;
1709 	}
1710 	/* use this cred for OTW operations */
1711 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1712 
1713 top:
1714 	nfs4_error_zinit(ep);
1715 
1716 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1717 		/* File system has been unmounted, quit */
1718 		ep->error = EIO;
1719 		failed_msg = "Couldn't reopen: file system has been unmounted";
1720 		goto kill_file;
1721 	}
1722 
1723 	oop = osp->os_open_owner;
1724 
1725 	ASSERT(oop != NULL);
1726 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1727 		failed_msg = "can't reopen: no open owner";
1728 		goto kill_file;
1729 	}
1730 	open_owner_hold(oop);
1731 
1732 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1733 	if (ep->error) {
1734 		open_owner_rele(oop);
1735 		oop = NULL;
1736 		goto bailout;
1737 	}
1738 
1739 	/*
1740 	 * If the rnode has a delegation and the delegation has been
1741 	 * recovered and the server didn't request a recall and the caller
1742 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1743 	 * recovery) and the rnode hasn't been marked dead, then install
1744 	 * the delegation stateid in the open stream.  Otherwise, proceed
1745 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1746 	 */
1747 	mutex_enter(&rp->r_statev4_lock);
1748 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1749 	    !rp->r_deleg_return_pending &&
1750 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1751 	    !rp->r_deleg_needs_recall &&
1752 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1753 	    !(rp->r_flags & R4RECOVERR)) {
1754 		mutex_enter(&osp->os_sync_lock);
1755 		osp->os_delegation = 1;
1756 		osp->open_stateid = rp->r_deleg_stateid;
1757 		mutex_exit(&osp->os_sync_lock);
1758 		mutex_exit(&rp->r_statev4_lock);
1759 		goto bailout;
1760 	}
1761 	mutex_exit(&rp->r_statev4_lock);
1762 
1763 	/*
1764 	 * If the file failed recovery, just quit.  This failure need not
1765 	 * affect other reopens, so don't return an error.
1766 	 */
1767 	mutex_enter(&rp->r_statelock);
1768 	if (rp->r_flags & R4RECOVERR) {
1769 		mutex_exit(&rp->r_statelock);
1770 		ep->error = 0;
1771 		goto failed_reopen;
1772 	}
1773 	mutex_exit(&rp->r_statelock);
1774 
1775 	/*
1776 	 * argop is empty here
1777 	 *
1778 	 * PUTFH, OPEN, GETATTR
1779 	 */
1780 	args.ctag = TAG_REOPEN;
1781 	args.array_len = 4;
1782 	args.array = argop;
1783 
1784 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1785 	    "nfs4_reopen: file is type %d, id %s",
1786 	    vp->v_type, rnode4info(VTOR4(vp))));
1787 
1788 	argop[0].argop = OP_CPUTFH;
1789 
1790 	if (claim != CLAIM_PREVIOUS) {
1791 		/*
1792 		 * if this is a file mount then
1793 		 * use the mntinfo parentfh
1794 		 */
1795 		argop[0].nfs_argop4_u.opcputfh.sfh =
1796 		    (vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1797 		    VTOSV(vp)->sv_dfh;
1798 	} else {
1799 		/* putfh fh to reopen */
1800 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1801 	}
1802 
1803 	argop[1].argop = OP_COPEN;
1804 	open_args = &argop[1].nfs_argop4_u.opcopen;
1805 	open_args->claim = claim;
1806 
1807 	if (claim == CLAIM_NULL) {
1808 
1809 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1810 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1811 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1812 			    (void *)vp);
1813 			failed_msg = "Couldn't reopen: vtoname failed for "
1814 			    "CLAIM_NULL";
1815 			/* nothing allocated yet */
1816 			goto kill_file;
1817 		}
1818 
1819 		open_args->open_claim4_u.cfile = fn;
1820 	} else if (claim == CLAIM_PREVIOUS) {
1821 
1822 		/*
1823 		 * We have two cases to deal with here:
1824 		 * 1) We're being called to reopen files in order to satisfy
1825 		 *    a lock operation request which requires us to explicitly
1826 		 *    reopen files which were opened under a delegation.  If
1827 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1828 		 *    that case, frc_use_claim_previous is TRUE and we must
1829 		 *    use the rnode's current delegation type (r_deleg_type).
1830 		 * 2) We're reopening files during some form of recovery.
1831 		 *    In this case, frc_use_claim_previous is FALSE and we
1832 		 *    use the delegation type appropriate for recovery
1833 		 *    (r_deleg_needs_recovery).
1834 		 */
1835 		mutex_enter(&rp->r_statev4_lock);
1836 		open_args->open_claim4_u.delegate_type =
1837 		    frc_use_claim_previous ?
1838 		    rp->r_deleg_type :
1839 		    rp->r_deleg_needs_recovery;
1840 		mutex_exit(&rp->r_statev4_lock);
1841 
1842 	} else if (claim == CLAIM_DELEGATE_CUR) {
1843 
1844 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1845 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1846 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1847 			    "with %m", (void *)vp);
1848 			failed_msg = "Couldn't reopen: vtoname failed for "
1849 			    "CLAIM_DELEGATE_CUR";
1850 			/* nothing allocated yet */
1851 			goto kill_file;
1852 		}
1853 
1854 		mutex_enter(&rp->r_statev4_lock);
1855 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1856 		    rp->r_deleg_stateid;
1857 		mutex_exit(&rp->r_statev4_lock);
1858 
1859 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1860 	}
1861 	open_args->opentype = OPEN4_NOCREATE;
1862 	open_args->owner.clientid = mi2clientid(mi);
1863 	open_args->owner.owner_len = sizeof (oop->oo_name);
1864 	open_args->owner.owner_val =
1865 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1866 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1867 	    open_args->owner.owner_len);
1868 	open_args->share_access = 0;
1869 	open_args->share_deny = 0;
1870 
1871 	mutex_enter(&osp->os_sync_lock);
1872 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1873 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1874 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1875 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1876 	    osp->os_share_acc_write, osp->os_open_ref_count,
1877 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1878 
1879 	if (osp->os_share_acc_read || osp->os_mmap_read)
1880 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1881 	if (osp->os_share_acc_write || osp->os_mmap_write)
1882 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1883 	if (osp->os_share_deny_read)
1884 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1885 	if (osp->os_share_deny_write)
1886 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1887 	mutex_exit(&osp->os_sync_lock);
1888 
1889 	seqid = nfs4_get_open_seqid(oop) + 1;
1890 	open_args->seqid = seqid;
1891 
1892 	/* Construct the getfh part of the compound */
1893 	argop[2].argop = OP_GETFH;
1894 
1895 	/* Construct the getattr part of the compound */
1896 	argop[3].argop = OP_GETATTR;
1897 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1898 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1899 
1900 	t = gethrtime();
1901 
1902 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1903 
1904 	if (ep->error) {
1905 		if (!is_recov && !frc_use_claim_previous &&
1906 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1907 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1908 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1909 			    cred_otw, vp, NULL, open_args);
1910 			abort = nfs4_start_recovery(ep,
1911 			    VTOMI4(vp), vp, NULL, NULL,
1912 			    lost_rqst.lr_op == OP_OPEN ?
1913 			    &lost_rqst : NULL, OP_OPEN, NULL, NULL, NULL);
1914 			nfs4args_copen_free(open_args);
1915 			goto bailout;
1916 		}
1917 
1918 		nfs4args_copen_free(open_args);
1919 
1920 		if (ep->error == EACCES && cred_otw != cr) {
1921 			crfree(cred_otw);
1922 			cred_otw = cr;
1923 			crhold(cred_otw);
1924 			nfs4_end_open_seqid_sync(oop);
1925 			open_owner_rele(oop);
1926 			oop = NULL;
1927 			goto top;
1928 		}
1929 		if (ep->error == ETIMEDOUT)
1930 			goto bailout;
1931 		failed_msg = "Couldn't reopen: rpc error";
1932 		goto kill_file;
1933 	}
1934 
1935 	if (nfs4_need_to_bump_seqid(&res))
1936 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1937 
1938 	switch (res.status) {
1939 	case NFS4_OK:
1940 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1941 			mutex_enter(&rp->r_statelock);
1942 			rp->r_delay_interval = 0;
1943 			mutex_exit(&rp->r_statelock);
1944 		}
1945 		break;
1946 	case NFS4ERR_BAD_SEQID:
1947 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1948 		    args.ctag, open_args->seqid);
1949 
1950 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1951 		    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1952 		    NULL, OP_OPEN, bsep, NULL, NULL);
1953 
1954 		nfs4args_copen_free(open_args);
1955 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1956 		nfs4_end_open_seqid_sync(oop);
1957 		open_owner_rele(oop);
1958 		oop = NULL;
1959 		kmem_free(bsep, sizeof (*bsep));
1960 
1961 		goto kill_file;
1962 	case NFS4ERR_NO_GRACE:
1963 		nfs4args_copen_free(open_args);
1964 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1965 		nfs4_end_open_seqid_sync(oop);
1966 		open_owner_rele(oop);
1967 		oop = NULL;
1968 		if (claim == CLAIM_PREVIOUS) {
1969 			/*
1970 			 * Retry as a plain open. We don't need to worry about
1971 			 * checking the changeinfo: it is acceptable for a
1972 			 * client to re-open a file and continue processing
1973 			 * (in the absence of locks).
1974 			 */
1975 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1976 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1977 			    "will retry as CLAIM_NULL"));
1978 			claim = CLAIM_NULL;
1979 			nfs4_mi_kstat_inc_no_grace(mi);
1980 			goto top;
1981 		}
1982 		failed_msg =
1983 		    "Couldn't reopen: tried reclaim outside grace period. ";
1984 		goto kill_file;
1985 	case NFS4ERR_GRACE:
1986 		nfs4_set_grace_wait(mi);
1987 		nfs4args_copen_free(open_args);
1988 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1989 		nfs4_end_open_seqid_sync(oop);
1990 		open_owner_rele(oop);
1991 		oop = NULL;
1992 		ep->error = nfs4_wait_for_grace(mi, &recov);
1993 		if (ep->error != 0)
1994 			goto bailout;
1995 		goto top;
1996 	case NFS4ERR_DELAY:
1997 		nfs4_set_delay_wait(vp);
1998 		nfs4args_copen_free(open_args);
1999 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2000 		nfs4_end_open_seqid_sync(oop);
2001 		open_owner_rele(oop);
2002 		oop = NULL;
2003 		ep->error = nfs4_wait_for_delay(vp, &recov);
2004 		nfs4_mi_kstat_inc_delay(mi);
2005 		if (ep->error != 0)
2006 			goto bailout;
2007 		goto top;
2008 	case NFS4ERR_FHEXPIRED:
2009 		/* recover filehandle and retry */
2010 		abort = nfs4_start_recovery(ep,
2011 		    mi, vp, NULL, NULL, NULL, OP_OPEN, NULL, NULL, NULL);
2012 		nfs4args_copen_free(open_args);
2013 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2014 		nfs4_end_open_seqid_sync(oop);
2015 		open_owner_rele(oop);
2016 		oop = NULL;
2017 		if (abort == FALSE)
2018 			goto top;
2019 		failed_msg = "Couldn't reopen: recovery aborted";
2020 		goto kill_file;
2021 	case NFS4ERR_RESOURCE:
2022 	case NFS4ERR_STALE_CLIENTID:
2023 	case NFS4ERR_WRONGSEC:
2024 	case NFS4ERR_EXPIRED:
2025 		/*
2026 		 * Do not mark the file dead and let the calling
2027 		 * function initiate recovery.
2028 		 */
2029 		nfs4args_copen_free(open_args);
2030 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2031 		nfs4_end_open_seqid_sync(oop);
2032 		open_owner_rele(oop);
2033 		oop = NULL;
2034 		goto bailout;
2035 	case NFS4ERR_ACCESS:
2036 		if (cred_otw != cr) {
2037 			crfree(cred_otw);
2038 			cred_otw = cr;
2039 			crhold(cred_otw);
2040 			nfs4args_copen_free(open_args);
2041 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2042 			nfs4_end_open_seqid_sync(oop);
2043 			open_owner_rele(oop);
2044 			oop = NULL;
2045 			goto top;
2046 		}
2047 		/* fall through */
2048 	default:
2049 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2050 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2051 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2052 		    rnode4info(VTOR4(vp))));
2053 		failed_msg = "Couldn't reopen: NFSv4 error";
2054 		nfs4args_copen_free(open_args);
2055 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2056 		goto kill_file;
2057 	}
2058 
2059 	resop = &res.array[1];  /* open res */
2060 	op_res = &resop->nfs_resop4_u.opopen;
2061 
2062 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2063 
2064 	/*
2065 	 * Check if the path we reopened really is the same
2066 	 * file. We could end up in a situation where the file
2067 	 * was removed and a new file created with the same name.
2068 	 */
2069 	resop = &res.array[2];
2070 	gf_res = &resop->nfs_resop4_u.opgetfh;
2071 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2072 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2073 	if (fh_different) {
2074 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2075 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2076 			/* Oops, we don't have the same file */
2077 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2078 				failed_msg = "Couldn't reopen: Persistent "
2079 				    "file handle changed";
2080 			else
2081 				failed_msg = "Couldn't reopen: Volatile "
2082 				    "(no expire on open) file handle changed";
2083 
2084 			nfs4args_copen_free(open_args);
2085 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2086 			nfs_rw_exit(&mi->mi_fh_lock);
2087 			goto kill_file;
2088 
2089 		} else {
2090 			/*
2091 			 * We have volatile file handles that don't compare.
2092 			 * If the fids are the same then we assume that the
2093 			 * file handle expired but the rnode still refers to
2094 			 * the same file object.
2095 			 *
2096 			 * First check that we have fids or not.
2097 			 * If we don't we have a dumb server so we will
2098 			 * just assume every thing is ok for now.
2099 			 */
2100 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2101 			    rp->r_attr.va_mask & AT_NODEID &&
2102 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2103 				/*
2104 				 * We have fids, but they don't
2105 				 * compare. So kill the file.
2106 				 */
2107 				failed_msg =
2108 				    "Couldn't reopen: file handle changed"
2109 				    " due to mismatched fids";
2110 				nfs4args_copen_free(open_args);
2111 				(void) xdr_free(xdr_COMPOUND4res_clnt,
2112 				    (caddr_t)&res);
2113 				nfs_rw_exit(&mi->mi_fh_lock);
2114 				goto kill_file;
2115 			} else {
2116 				/*
2117 				 * We have volatile file handles that refers
2118 				 * to the same file (at least they have the
2119 				 * same fid) or we don't have fids so we
2120 				 * can't tell. :(. We'll be a kind and accepting
2121 				 * client so we'll update the rnode's file
2122 				 * handle with the otw handle.
2123 				 *
2124 				 * We need to drop mi->mi_fh_lock since
2125 				 * sh4_update acquires it. Since there is
2126 				 * only one recovery thread there is no
2127 				 * race.
2128 				 */
2129 				nfs_rw_exit(&mi->mi_fh_lock);
2130 				sfh4_update(rp->r_fh, &gf_res->object);
2131 			}
2132 		}
2133 	} else {
2134 		nfs_rw_exit(&mi->mi_fh_lock);
2135 	}
2136 
2137 	ASSERT(nfs4_consistent_type(vp));
2138 
2139 	/*
2140 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2141 	 * over.  Presumably if there is a persistent error it will show up
2142 	 * when we resend the OPEN.
2143 	 */
2144 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2145 		bool_t retry_open = FALSE;
2146 
2147 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2148 		    cred_otw, is_recov, &retry_open,
2149 		    oop, FALSE, ep, NULL);
2150 		if (ep->error || ep->stat) {
2151 			nfs4args_copen_free(open_args);
2152 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2153 			nfs4_end_open_seqid_sync(oop);
2154 			open_owner_rele(oop);
2155 			oop = NULL;
2156 			goto top;
2157 		}
2158 	}
2159 
2160 	mutex_enter(&osp->os_sync_lock);
2161 	osp->open_stateid = op_res->stateid;
2162 	osp->os_delegation = 0;
2163 	/*
2164 	 * Need to reset this bitfield for the possible case where we were
2165 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2166 	 * we could retry the CLOSE, OPENed the file again.
2167 	 */
2168 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2169 	osp->os_final_close = 0;
2170 	osp->os_force_close = 0;
2171 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2172 		osp->os_dc_openacc = open_args->share_access;
2173 	mutex_exit(&osp->os_sync_lock);
2174 
2175 	nfs4_end_open_seqid_sync(oop);
2176 
2177 	/* accept delegation, if any */
2178 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2179 
2180 	nfs4args_copen_free(open_args);
2181 
2182 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2183 
2184 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2185 
2186 	ASSERT(nfs4_consistent_type(vp));
2187 
2188 	open_owner_rele(oop);
2189 	crfree(cr);
2190 	crfree(cred_otw);
2191 	return;
2192 
2193 kill_file:
2194 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2195 failed_reopen:
2196 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2197 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2198 	    (void *)osp, (void *)cr, rnode4info(rp)));
2199 	mutex_enter(&osp->os_sync_lock);
2200 	osp->os_failed_reopen = 1;
2201 	mutex_exit(&osp->os_sync_lock);
2202 bailout:
2203 	if (oop != NULL) {
2204 		nfs4_end_open_seqid_sync(oop);
2205 		open_owner_rele(oop);
2206 	}
2207 	if (cr != NULL)
2208 		crfree(cr);
2209 	if (cred_otw != NULL)
2210 		crfree(cred_otw);
2211 }
2212 
2213 /* for . and .. OPENs */
2214 /* ARGSUSED */
2215 static int
2216 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2217 {
2218 	rnode4_t *rp;
2219 	nfs4_ga_res_t gar;
2220 
2221 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2222 
2223 	/*
2224 	 * If close-to-open consistency checking is turned off or
2225 	 * if there is no cached data, we can avoid
2226 	 * the over the wire getattr.  Otherwise, force a
2227 	 * call to the server to get fresh attributes and to
2228 	 * check caches. This is required for close-to-open
2229 	 * consistency.
2230 	 */
2231 	rp = VTOR4(*vpp);
2232 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2233 	    (rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2234 		return (0);
2235 
2236 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2237 }
2238 
2239 /*
2240  * CLOSE a file
2241  */
2242 /* ARGSUSED */
2243 static int
2244 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
2245     caller_context_t *ct)
2246 {
2247 	rnode4_t	*rp;
2248 	int		 error = 0;
2249 	int		 r_error = 0;
2250 	int		 n4error = 0;
2251 	nfs4_error_t	 e = { 0, NFS4_OK, RPC_SUCCESS };
2252 
2253 	/*
2254 	 * Remove client state for this (lockowner, file) pair.
2255 	 * Issue otw v4 call to have the server do the same.
2256 	 */
2257 
2258 	rp = VTOR4(vp);
2259 
2260 	/*
2261 	 * zone_enter(2) prevents processes from changing zones with NFS files
2262 	 * open; if we happen to get here from the wrong zone we can't do
2263 	 * anything over the wire.
2264 	 */
2265 	if (VTOMI4(vp)->mi_zone != nfs_zone()) {
2266 		/*
2267 		 * We could attempt to clean up locks, except we're sure
2268 		 * that the current process didn't acquire any locks on
2269 		 * the file: any attempt to lock a file belong to another zone
2270 		 * will fail, and one can't lock an NFS file and then change
2271 		 * zones, as that fails too.
2272 		 *
2273 		 * Returning an error here is the sane thing to do.  A
2274 		 * subsequent call to VN_RELE() which translates to a
2275 		 * nfs4_inactive() will clean up state: if the zone of the
2276 		 * vnode's origin is still alive and kicking, the inactive
2277 		 * thread will handle the request (from the correct zone), and
2278 		 * everything (minus the OTW close call) should be OK.  If the
2279 		 * zone is going away nfs4_async_inactive() will throw away
2280 		 * delegations, open streams and cached pages inline.
2281 		 */
2282 		return (EIO);
2283 	}
2284 
2285 	/*
2286 	 * If we are using local locking for this filesystem, then
2287 	 * release all of the SYSV style record locks.  Otherwise,
2288 	 * we are doing network locking and we need to release all
2289 	 * of the network locks.  All of the locks held by this
2290 	 * process on this file are released no matter what the
2291 	 * incoming reference count is.
2292 	 */
2293 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK) {
2294 		cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
2295 		cleanshares(vp, ttoproc(curthread)->p_pid);
2296 	} else
2297 		e.error = nfs4_lockrelease(vp, flag, offset, cr);
2298 
2299 	if (e.error) {
2300 		struct lm_sysid *lmsid;
2301 		lmsid = nfs4_find_sysid(VTOMI4(vp));
2302 		if (lmsid == NULL) {
2303 			DTRACE_PROBE2(unknown__sysid, int, e.error,
2304 			    vnode_t *, vp);
2305 		} else {
2306 			cleanlocks(vp, ttoproc(curthread)->p_pid,
2307 			    (lm_sysidt(lmsid) | LM_SYSID_CLIENT));
2308 
2309 			lm_rel_sysid(lmsid);
2310 		}
2311 		return (e.error);
2312 	}
2313 
2314 	if (count > 1)
2315 		return (0);
2316 
2317 	/*
2318 	 * If the file has been `unlinked', then purge the
2319 	 * DNLC so that this vnode will get reycled quicker
2320 	 * and the .nfs* file on the server will get removed.
2321 	 */
2322 	if (rp->r_unldvp != NULL)
2323 		dnlc_purge_vp(vp);
2324 
2325 	/*
2326 	 * If the file was open for write and there are pages,
2327 	 * do a synchronous flush and commit of all of the
2328 	 * dirty and uncommitted pages.
2329 	 */
2330 	ASSERT(!e.error);
2331 	if ((flag & FWRITE) && nfs4_has_pages(vp))
2332 		error = nfs4_putpage_commit(vp, 0, 0, cr);
2333 
2334 	mutex_enter(&rp->r_statelock);
2335 	r_error = rp->r_error;
2336 	rp->r_error = 0;
2337 	mutex_exit(&rp->r_statelock);
2338 
2339 	/*
2340 	 * If this file type is one for which no explicit 'open' was
2341 	 * done, then bail now (ie. no need for protocol 'close'). If
2342 	 * there was an error w/the vm subsystem, return _that_ error,
2343 	 * otherwise, return any errors that may've been reported via
2344 	 * the rnode.
2345 	 */
2346 	if (vp->v_type != VREG)
2347 		return (error ? error : r_error);
2348 
2349 	/*
2350 	 * The sync putpage commit may have failed above, but since
2351 	 * we're working w/a regular file, we need to do the protocol
2352 	 * 'close' (nfs4close_one will figure out if an otw close is
2353 	 * needed or not). Report any errors _after_ doing the protocol
2354 	 * 'close'.
2355 	 */
2356 	nfs4close_one(vp, NULL, cr, flag, NULL, &e, CLOSE_NORM, 0, 0, 0);
2357 	n4error = e.error ? e.error : geterrno4(e.stat);
2358 
2359 	/*
2360 	 * Error reporting prio (Hi -> Lo)
2361 	 *
2362 	 *   i) nfs4_putpage_commit (error)
2363 	 *  ii) rnode's (r_error)
2364 	 * iii) nfs4close_one (n4error)
2365 	 */
2366 	return (error ? error : (r_error ? r_error : n4error));
2367 }
2368 
2369 /*
2370  * Initialize *lost_rqstp.
2371  */
2372 
2373 static void
2374 nfs4close_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
2375     nfs4_open_owner_t *oop, nfs4_open_stream_t *osp, cred_t *cr,
2376     vnode_t *vp)
2377 {
2378 	if (error != ETIMEDOUT && error != EINTR &&
2379 	    !NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
2380 		lost_rqstp->lr_op = 0;
2381 		return;
2382 	}
2383 
2384 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
2385 	    "nfs4close_save_lost_rqst: error %d", error));
2386 
2387 	lost_rqstp->lr_op = OP_CLOSE;
2388 	/*
2389 	 * The vp is held and rele'd via the recovery code.
2390 	 * See nfs4_save_lost_rqst.
2391 	 */
2392 	lost_rqstp->lr_vp = vp;
2393 	lost_rqstp->lr_dvp = NULL;
2394 	lost_rqstp->lr_oop = oop;
2395 	lost_rqstp->lr_osp = osp;
2396 	ASSERT(osp != NULL);
2397 	ASSERT(mutex_owned(&osp->os_sync_lock));
2398 	osp->os_pending_close = 1;
2399 	lost_rqstp->lr_lop = NULL;
2400 	lost_rqstp->lr_cr = cr;
2401 	lost_rqstp->lr_flk = NULL;
2402 	lost_rqstp->lr_putfirst = FALSE;
2403 }
2404 
2405 /*
2406  * Assumes you already have the open seqid sync grabbed as well as the
2407  * 'os_sync_lock'.  Note: this will release the open seqid sync and
2408  * 'os_sync_lock' if client recovery starts.  Calling functions have to
2409  * be prepared to handle this.
2410  *
2411  * 'recov' is returned as 1 if the CLOSE operation detected client recovery
2412  * was needed and was started, and that the calling function should retry
2413  * this function; otherwise it is returned as 0.
2414  *
2415  * Errors are returned via the nfs4_error_t parameter.
2416  */
2417 static void
2418 nfs4close_otw(rnode4_t *rp, cred_t *cred_otw, nfs4_open_owner_t *oop,
2419     nfs4_open_stream_t *osp, int *recov, int *did_start_seqid_syncp,
2420     nfs4_close_type_t close_type, nfs4_error_t *ep, int *have_sync_lockp)
2421 {
2422 	COMPOUND4args_clnt args;
2423 	COMPOUND4res_clnt res;
2424 	CLOSE4args *close_args;
2425 	nfs_resop4 *resop;
2426 	nfs_argop4 argop[3];
2427 	int doqueue = 1;
2428 	mntinfo4_t *mi;
2429 	seqid4 seqid;
2430 	vnode_t *vp;
2431 	bool_t needrecov = FALSE;
2432 	nfs4_lost_rqst_t lost_rqst;
2433 	hrtime_t t;
2434 
2435 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
2436 
2437 	ASSERT(MUTEX_HELD(&osp->os_sync_lock));
2438 
2439 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw"));
2440 
2441 	/* Only set this to 1 if recovery is started */
2442 	*recov = 0;
2443 
2444 	/* do the OTW call to close the file */
2445 
2446 	if (close_type == CLOSE_RESEND)
2447 		args.ctag = TAG_CLOSE_LOST;
2448 	else if (close_type == CLOSE_AFTER_RESEND)
2449 		args.ctag = TAG_CLOSE_UNDO;
2450 	else
2451 		args.ctag = TAG_CLOSE;
2452 
2453 	args.array_len = 3;
2454 	args.array = argop;
2455 
2456 	vp = RTOV4(rp);
2457 
2458 	mi = VTOMI4(vp);
2459 
2460 	/* putfh target fh */
2461 	argop[0].argop = OP_CPUTFH;
2462 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
2463 
2464 	argop[1].argop = OP_GETATTR;
2465 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
2466 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
2467 
2468 	argop[2].argop = OP_CLOSE;
2469 	close_args = &argop[2].nfs_argop4_u.opclose;
2470 
2471 	seqid = nfs4_get_open_seqid(oop) + 1;
2472 
2473 	close_args->seqid = seqid;
2474 	close_args->open_stateid = osp->open_stateid;
2475 
2476 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
2477 	    "nfs4close_otw: %s call, rp %s", needrecov ? "recov" : "first",
2478 	    rnode4info(rp)));
2479 
2480 	t = gethrtime();
2481 
2482 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
2483 
2484 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
2485 		nfs4_set_open_seqid(seqid, oop, args.ctag);
2486 	}
2487 
2488 	needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
2489 	if (ep->error && !needrecov) {
2490 		/*
2491 		 * if there was an error and no recovery is to be done
2492 		 * then then set up the file to flush its cache if
2493 		 * needed for the next caller.
2494 		 */
2495 		mutex_enter(&rp->r_statelock);
2496 		PURGE_ATTRCACHE4_LOCKED(rp);
2497 		rp->r_flags &= ~R4WRITEMODIFIED;
2498 		mutex_exit(&rp->r_statelock);
2499 		return;
2500 	}
2501 
2502 	if (needrecov) {
2503 		bool_t abort;
2504 		nfs4_bseqid_entry_t *bsep = NULL;
2505 
2506 		if (close_type != CLOSE_RESEND)
2507 			nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
2508 			    osp, cred_otw, vp);
2509 
2510 		if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
2511 			bsep = nfs4_create_bseqid_entry(oop, NULL, vp,
2512 			    0, args.ctag, close_args->seqid);
2513 
2514 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
2515 		    "nfs4close_otw: initiating recovery. error %d "
2516 		    "res.status %d", ep->error, res.status));
2517 
2518 		/*
2519 		 * Drop the 'os_sync_lock' here so we don't hit
2520 		 * a potential recursive mutex_enter via an
2521 		 * 'open_stream_hold()'.
2522 		 */
2523 		mutex_exit(&osp->os_sync_lock);
2524 		*have_sync_lockp = 0;
2525 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
2526 		    (close_type != CLOSE_RESEND &&
2527 		    lost_rqst.lr_op == OP_CLOSE) ? &lost_rqst : NULL,
2528 		    OP_CLOSE, bsep, NULL, NULL);
2529 
2530 		/* drop open seq sync, and let the calling function regrab it */
2531 		nfs4_end_open_seqid_sync(oop);
2532 		*did_start_seqid_syncp = 0;
2533 
2534 		if (bsep)
2535 			kmem_free(bsep, sizeof (*bsep));
2536 		/*
2537 		 * For signals, the caller wants to quit, so don't say to
2538 		 * retry.  For forced unmount, if it's a user thread, it
2539 		 * wants to quit.  If it's a recovery thread, the retry
2540 		 * will happen higher-up on the call stack.  Either way,
2541 		 * don't say to retry.
2542 		 */
2543 		if (abort == FALSE && ep->error != EINTR &&
2544 		    !NFS4_FRC_UNMT_ERR(ep->error, mi->mi_vfsp) &&
2545 		    close_type != CLOSE_RESEND &&
2546 		    close_type != CLOSE_AFTER_RESEND)
2547 			*recov = 1;
2548 		else
2549 			*recov = 0;
2550 
2551 		if (!ep->error)
2552 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2553 		return;
2554 	}
2555 
2556 	if (res.status) {
2557 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2558 		return;
2559 	}
2560 
2561 	mutex_enter(&rp->r_statev4_lock);
2562 	rp->created_v4 = 0;
2563 	mutex_exit(&rp->r_statev4_lock);
2564 
2565 	resop = &res.array[2];
2566 	osp->open_stateid = resop->nfs_resop4_u.opclose.open_stateid;
2567 	osp->os_valid = 0;
2568 
2569 	/*
2570 	 * This removes the reference obtained at OPEN; ie, when the
2571 	 * open stream structure was created.
2572 	 *
2573 	 * We don't have to worry about calling 'open_stream_rele'
2574 	 * since we our currently holding a reference to the open
2575 	 * stream which means the count cannot go to 0 with this
2576 	 * decrement.
2577 	 */
2578 	ASSERT(osp->os_ref_count >= 2);
2579 	osp->os_ref_count--;
2580 
2581 	if (ep->error == 0) {
2582 		/*
2583 		 * Avoid a deadlock with the r_serial thread waiting for
2584 		 * os_sync_lock in nfs4_get_otw_cred_by_osp() which might be
2585 		 * held by us. We will wait in nfs4_attr_cache() for the
2586 		 * completion of the r_serial thread.
2587 		 */
2588 		mutex_exit(&osp->os_sync_lock);
2589 		*have_sync_lockp = 0;
2590 
2591 		nfs4_attr_cache(vp,
2592 		    &res.array[1].nfs_resop4_u.opgetattr.ga_res,
2593 		    t, cred_otw, TRUE, NULL);
2594 	}
2595 
2596 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw:"
2597 	    " returning %d", ep->error));
2598 
2599 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2600 }
2601 
2602 /* ARGSUSED */
2603 static int
2604 nfs4_read(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2605     caller_context_t *ct)
2606 {
2607 	rnode4_t *rp;
2608 	u_offset_t off;
2609 	offset_t diff;
2610 	uint_t on;
2611 	uint_t n;
2612 	caddr_t base;
2613 	uint_t flags;
2614 	int error;
2615 	mntinfo4_t *mi;
2616 
2617 	rp = VTOR4(vp);
2618 
2619 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2620 
2621 	if (IS_SHADOW(vp, rp))
2622 		vp = RTOV4(rp);
2623 
2624 	if (vp->v_type != VREG)
2625 		return (EISDIR);
2626 
2627 	mi = VTOMI4(vp);
2628 
2629 	if (nfs_zone() != mi->mi_zone)
2630 		return (EIO);
2631 
2632 	if (uiop->uio_resid == 0)
2633 		return (0);
2634 
2635 	if (uiop->uio_loffset < 0 || uiop->uio_loffset + uiop->uio_resid < 0)
2636 		return (EINVAL);
2637 
2638 	mutex_enter(&rp->r_statelock);
2639 	if (rp->r_flags & R4RECOVERRP)
2640 		error = (rp->r_error ? rp->r_error : EIO);
2641 	else
2642 		error = 0;
2643 	mutex_exit(&rp->r_statelock);
2644 	if (error)
2645 		return (error);
2646 
2647 	/*
2648 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2649 	 * using client-side direct I/O and the file is not mmap'd and
2650 	 * there are no cached pages.
2651 	 */
2652 	if ((vp->v_flag & VNOCACHE) ||
2653 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2654 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2655 		size_t resid = 0;
2656 
2657 		return (nfs4read(vp, NULL, uiop->uio_loffset,
2658 		    uiop->uio_resid, &resid, cr, FALSE, uiop));
2659 	}
2660 
2661 	error = 0;
2662 
2663 	do {
2664 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2665 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2666 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2667 
2668 		if (error = nfs4_validate_caches(vp, cr))
2669 			break;
2670 
2671 		mutex_enter(&rp->r_statelock);
2672 		while (rp->r_flags & R4INCACHEPURGE) {
2673 			if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2674 				mutex_exit(&rp->r_statelock);
2675 				return (EINTR);
2676 			}
2677 		}
2678 		diff = rp->r_size - uiop->uio_loffset;
2679 		mutex_exit(&rp->r_statelock);
2680 		if (diff <= 0)
2681 			break;
2682 		if (diff < n)
2683 			n = (uint_t)diff;
2684 
2685 		if (vpm_enable) {
2686 			/*
2687 			 * Copy data.
2688 			 */
2689 			error = vpm_data_copy(vp, off + on, n, uiop,
2690 			    1, NULL, 0, S_READ);
2691 		} else {
2692 			base = segmap_getmapflt(segkmap, vp, off + on, n, 1,
2693 			    S_READ);
2694 
2695 			error = uiomove(base + on, n, UIO_READ, uiop);
2696 		}
2697 
2698 		if (!error) {
2699 			/*
2700 			 * If read a whole block or read to eof,
2701 			 * won't need this buffer again soon.
2702 			 */
2703 			mutex_enter(&rp->r_statelock);
2704 			if (n + on == MAXBSIZE ||
2705 			    uiop->uio_loffset == rp->r_size)
2706 				flags = SM_DONTNEED;
2707 			else
2708 				flags = 0;
2709 			mutex_exit(&rp->r_statelock);
2710 			if (vpm_enable) {
2711 				error = vpm_sync_pages(vp, off, n, flags);
2712 			} else {
2713 				error = segmap_release(segkmap, base, flags);
2714 			}
2715 		} else {
2716 			if (vpm_enable) {
2717 				(void) vpm_sync_pages(vp, off, n, 0);
2718 			} else {
2719 				(void) segmap_release(segkmap, base, 0);
2720 			}
2721 		}
2722 	} while (!error && uiop->uio_resid > 0);
2723 
2724 	return (error);
2725 }
2726 
2727 /* ARGSUSED */
2728 static int
2729 nfs4_write(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2730     caller_context_t *ct)
2731 {
2732 	rlim64_t limit = uiop->uio_llimit;
2733 	rnode4_t *rp;
2734 	u_offset_t off;
2735 	caddr_t base;
2736 	uint_t flags;
2737 	int remainder;
2738 	size_t n;
2739 	int on;
2740 	int error;
2741 	int resid;
2742 	u_offset_t offset;
2743 	mntinfo4_t *mi;
2744 	uint_t bsize;
2745 
2746 	rp = VTOR4(vp);
2747 
2748 	if (IS_SHADOW(vp, rp))
2749 		vp = RTOV4(rp);
2750 
2751 	if (vp->v_type != VREG)
2752 		return (EISDIR);
2753 
2754 	mi = VTOMI4(vp);
2755 
2756 	if (nfs_zone() != mi->mi_zone)
2757 		return (EIO);
2758 
2759 	if (uiop->uio_resid == 0)
2760 		return (0);
2761 
2762 	mutex_enter(&rp->r_statelock);
2763 	if (rp->r_flags & R4RECOVERRP)
2764 		error = (rp->r_error ? rp->r_error : EIO);
2765 	else
2766 		error = 0;
2767 	mutex_exit(&rp->r_statelock);
2768 	if (error)
2769 		return (error);
2770 
2771 	if (ioflag & FAPPEND) {
2772 		struct vattr va;
2773 
2774 		/*
2775 		 * Must serialize if appending.
2776 		 */
2777 		if (nfs_rw_lock_held(&rp->r_rwlock, RW_READER)) {
2778 			nfs_rw_exit(&rp->r_rwlock);
2779 			if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER,
2780 			    INTR4(vp)))
2781 				return (EINTR);
2782 		}
2783 
2784 		va.va_mask = AT_SIZE;
2785 		error = nfs4getattr(vp, &va, cr);
2786 		if (error)
2787 			return (error);
2788 		uiop->uio_loffset = va.va_size;
2789 	}
2790 
2791 	offset = uiop->uio_loffset + uiop->uio_resid;
2792 
2793 	if (uiop->uio_loffset < (offset_t)0 || offset < 0)
2794 		return (EINVAL);
2795 
2796 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
2797 		limit = MAXOFFSET_T;
2798 
2799 	/*
2800 	 * Check to make sure that the process will not exceed
2801 	 * its limit on file size.  It is okay to write up to
2802 	 * the limit, but not beyond.  Thus, the write which
2803 	 * reaches the limit will be short and the next write
2804 	 * will return an error.
2805 	 */
2806 	remainder = 0;
2807 	if (offset > uiop->uio_llimit) {
2808 		remainder = offset - uiop->uio_llimit;
2809 		uiop->uio_resid = uiop->uio_llimit - uiop->uio_loffset;
2810 		if (uiop->uio_resid <= 0) {
2811 			proc_t *p = ttoproc(curthread);
2812 
2813 			uiop->uio_resid += remainder;
2814 			mutex_enter(&p->p_lock);
2815 			(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE],
2816 			    p->p_rctls, p, RCA_UNSAFE_SIGINFO);
2817 			mutex_exit(&p->p_lock);
2818 			return (EFBIG);
2819 		}
2820 	}
2821 
2822 	/* update the change attribute, if we have a write delegation */
2823 
2824 	mutex_enter(&rp->r_statev4_lock);
2825 	if (rp->r_deleg_type == OPEN_DELEGATE_WRITE)
2826 		rp->r_deleg_change++;
2827 
2828 	mutex_exit(&rp->r_statev4_lock);
2829 
2830 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
2831 		return (EINTR);
2832 
2833 	/*
2834 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2835 	 * using client-side direct I/O and the file is not mmap'd and
2836 	 * there are no cached pages.
2837 	 */
2838 	if ((vp->v_flag & VNOCACHE) ||
2839 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2840 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2841 		size_t bufsize;
2842 		int count;
2843 		u_offset_t org_offset;
2844 		stable_how4 stab_comm;
2845 nfs4_fwrite:
2846 		if (rp->r_flags & R4STALE) {
2847 			resid = uiop->uio_resid;
2848 			offset = uiop->uio_loffset;
2849 			error = rp->r_error;
2850 			/*
2851 			 * A close may have cleared r_error, if so,
2852 			 * propagate ESTALE error return properly
2853 			 */
2854 			if (error == 0)
2855 				error = ESTALE;
2856 			goto bottom;
2857 		}
2858 
2859 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2860 		base = kmem_alloc(bufsize, KM_SLEEP);
2861 		do {
2862 			if (ioflag & FDSYNC)
2863 				stab_comm = DATA_SYNC4;
2864 			else
2865 				stab_comm = FILE_SYNC4;
2866 			resid = uiop->uio_resid;
2867 			offset = uiop->uio_loffset;
2868 			count = MIN(uiop->uio_resid, bufsize);
2869 			org_offset = uiop->uio_loffset;
2870 			error = uiomove(base, count, UIO_WRITE, uiop);
2871 			if (!error) {
2872 				error = nfs4write(vp, base, org_offset,
2873 				    count, cr, &stab_comm);
2874 				if (!error) {
2875 					mutex_enter(&rp->r_statelock);
2876 					if (rp->r_size < uiop->uio_loffset)
2877 						rp->r_size = uiop->uio_loffset;
2878 					mutex_exit(&rp->r_statelock);
2879 				}
2880 			}
2881 		} while (!error && uiop->uio_resid > 0);
2882 		kmem_free(base, bufsize);
2883 		goto bottom;
2884 	}
2885 
2886 	bsize = vp->v_vfsp->vfs_bsize;
2887 
2888 	do {
2889 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2890 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2891 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2892 
2893 		resid = uiop->uio_resid;
2894 		offset = uiop->uio_loffset;
2895 
2896 		if (rp->r_flags & R4STALE) {
2897 			error = rp->r_error;
2898 			/*
2899 			 * A close may have cleared r_error, if so,
2900 			 * propagate ESTALE error return properly
2901 			 */
2902 			if (error == 0)
2903 				error = ESTALE;
2904 			break;
2905 		}
2906 
2907 		/*
2908 		 * Don't create dirty pages faster than they
2909 		 * can be cleaned so that the system doesn't
2910 		 * get imbalanced.  If the async queue is
2911 		 * maxed out, then wait for it to drain before
2912 		 * creating more dirty pages.  Also, wait for
2913 		 * any threads doing pagewalks in the vop_getattr
2914 		 * entry points so that they don't block for
2915 		 * long periods.
2916 		 */
2917 		mutex_enter(&rp->r_statelock);
2918 		while ((mi->mi_max_threads != 0 &&
2919 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2920 		    rp->r_gcount > 0) {
2921 			if (INTR4(vp)) {
2922 				klwp_t *lwp = ttolwp(curthread);
2923 
2924 				if (lwp != NULL)
2925 					lwp->lwp_nostop++;
2926 				if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2927 					mutex_exit(&rp->r_statelock);
2928 					if (lwp != NULL)
2929 						lwp->lwp_nostop--;
2930 					error = EINTR;
2931 					goto bottom;
2932 				}
2933 				if (lwp != NULL)
2934 					lwp->lwp_nostop--;
2935 			} else
2936 				cv_wait(&rp->r_cv, &rp->r_statelock);
2937 		}
2938 		mutex_exit(&rp->r_statelock);
2939 
2940 		/*
2941 		 * Touch the page and fault it in if it is not in core
2942 		 * before segmap_getmapflt or vpm_data_copy can lock it.
2943 		 * This is to avoid the deadlock if the buffer is mapped
2944 		 * to the same file through mmap which we want to write.
2945 		 */
2946 		uio_prefaultpages((long)n, uiop);
2947 
2948 		if (vpm_enable) {
2949 			/*
2950 			 * It will use kpm mappings, so no need to
2951 			 * pass an address.
2952 			 */
2953 			error = writerp4(rp, NULL, n, uiop, 0);
2954 		} else  {
2955 			if (segmap_kpm) {
2956 				int pon = uiop->uio_loffset & PAGEOFFSET;
2957 				size_t pn = MIN(PAGESIZE - pon,
2958 				    uiop->uio_resid);
2959 				int pagecreate;
2960 
2961 				mutex_enter(&rp->r_statelock);
2962 				pagecreate = (pon == 0) && (pn == PAGESIZE ||
2963 				    uiop->uio_loffset + pn >= rp->r_size);
2964 				mutex_exit(&rp->r_statelock);
2965 
2966 				base = segmap_getmapflt(segkmap, vp, off + on,
2967 				    pn, !pagecreate, S_WRITE);
2968 
2969 				error = writerp4(rp, base + pon, n, uiop,
2970 				    pagecreate);
2971 
2972 			} else {
2973 				base = segmap_getmapflt(segkmap, vp, off + on,
2974 				    n, 0, S_READ);
2975 				error = writerp4(rp, base + on, n, uiop, 0);
2976 			}
2977 		}
2978 
2979 		if (!error) {
2980 			if (mi->mi_flags & MI4_NOAC)
2981 				flags = SM_WRITE;
2982 			else if ((uiop->uio_loffset % bsize) == 0 ||
2983 			    IS_SWAPVP(vp)) {
2984 				/*
2985 				 * Have written a whole block.
2986 				 * Start an asynchronous write
2987 				 * and mark the buffer to
2988 				 * indicate that it won't be
2989 				 * needed again soon.
2990 				 */
2991 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
2992 			} else
2993 				flags = 0;
2994 			if ((ioflag & (FSYNC|FDSYNC)) ||
2995 			    (rp->r_flags & R4OUTOFSPACE)) {
2996 				flags &= ~SM_ASYNC;
2997 				flags |= SM_WRITE;
2998 			}
2999 			if (vpm_enable) {
3000 				error = vpm_sync_pages(vp, off, n, flags);
3001 			} else {
3002 				error = segmap_release(segkmap, base, flags);
3003 			}
3004 		} else {
3005 			if (vpm_enable) {
3006 				(void) vpm_sync_pages(vp, off, n, 0);
3007 			} else {
3008 				(void) segmap_release(segkmap, base, 0);
3009 			}
3010 			/*
3011 			 * In the event that we got an access error while
3012 			 * faulting in a page for a write-only file just
3013 			 * force a write.
3014 			 */
3015 			if (error == EACCES)
3016 				goto nfs4_fwrite;
3017 		}
3018 	} while (!error && uiop->uio_resid > 0);
3019 
3020 bottom:
3021 	if (error) {
3022 		uiop->uio_resid = resid + remainder;
3023 		uiop->uio_loffset = offset;
3024 	} else {
3025 		uiop->uio_resid += remainder;
3026 
3027 		mutex_enter(&rp->r_statev4_lock);
3028 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
3029 			gethrestime(&rp->r_attr.va_mtime);
3030 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3031 		}
3032 		mutex_exit(&rp->r_statev4_lock);
3033 	}
3034 
3035 	nfs_rw_exit(&rp->r_lkserlock);
3036 
3037 	return (error);
3038 }
3039 
3040 /*
3041  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
3042  */
3043 static int
3044 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
3045     int flags, cred_t *cr)
3046 {
3047 	struct buf *bp;
3048 	int error;
3049 	page_t *savepp;
3050 	uchar_t fsdata;
3051 	stable_how4 stab_comm;
3052 
3053 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3054 	bp = pageio_setup(pp, len, vp, flags);
3055 	ASSERT(bp != NULL);
3056 
3057 	/*
3058 	 * pageio_setup should have set b_addr to 0.  This
3059 	 * is correct since we want to do I/O on a page
3060 	 * boundary.  bp_mapin will use this addr to calculate
3061 	 * an offset, and then set b_addr to the kernel virtual
3062 	 * address it allocated for us.
3063 	 */
3064 	ASSERT(bp->b_un.b_addr == 0);
3065 
3066 	bp->b_edev = 0;
3067 	bp->b_dev = 0;
3068 	bp->b_lblkno = lbtodb(off);
3069 	bp->b_file = vp;
3070 	bp->b_offset = (offset_t)off;
3071 	bp_mapin(bp);
3072 
3073 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
3074 	    freemem > desfree)
3075 		stab_comm = UNSTABLE4;
3076 	else
3077 		stab_comm = FILE_SYNC4;
3078 
3079 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
3080 
3081 	bp_mapout(bp);
3082 	pageio_done(bp);
3083 
3084 	if (stab_comm == UNSTABLE4)
3085 		fsdata = C_DELAYCOMMIT;
3086 	else
3087 		fsdata = C_NOCOMMIT;
3088 
3089 	savepp = pp;
3090 	do {
3091 		pp->p_fsdata = fsdata;
3092 	} while ((pp = pp->p_next) != savepp);
3093 
3094 	return (error);
3095 }
3096 
3097 /*
3098  */
3099 static int
3100 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
3101 {
3102 	nfs4_open_owner_t	*oop;
3103 	nfs4_open_stream_t	*osp;
3104 	rnode4_t		*rp = VTOR4(vp);
3105 	mntinfo4_t 		*mi = VTOMI4(vp);
3106 	int 			reopen_needed;
3107 
3108 	ASSERT(nfs_zone() == mi->mi_zone);
3109 
3110 
3111 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
3112 	if (!oop)
3113 		return (EIO);
3114 
3115 	/* returns with 'os_sync_lock' held */
3116 	osp = find_open_stream(oop, rp);
3117 	if (!osp) {
3118 		open_owner_rele(oop);
3119 		return (EIO);
3120 	}
3121 
3122 	if (osp->os_failed_reopen) {
3123 		mutex_exit(&osp->os_sync_lock);
3124 		open_stream_rele(osp, rp);
3125 		open_owner_rele(oop);
3126 		return (EIO);
3127 	}
3128 
3129 	/*
3130 	 * Determine whether a reopen is needed.  If this
3131 	 * is a delegation open stream, then the os_delegation bit
3132 	 * should be set.
3133 	 */
3134 
3135 	reopen_needed = osp->os_delegation;
3136 
3137 	mutex_exit(&osp->os_sync_lock);
3138 	open_owner_rele(oop);
3139 
3140 	if (reopen_needed) {
3141 		nfs4_error_zinit(ep);
3142 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
3143 		mutex_enter(&osp->os_sync_lock);
3144 		if (ep->error || ep->stat || osp->os_failed_reopen) {
3145 			mutex_exit(&osp->os_sync_lock);
3146 			open_stream_rele(osp, rp);
3147 			return (EIO);
3148 		}
3149 		mutex_exit(&osp->os_sync_lock);
3150 	}
3151 	open_stream_rele(osp, rp);
3152 
3153 	return (0);
3154 }
3155 
3156 /*
3157  * Write to file.  Writes to remote server in largest size
3158  * chunks that the server can handle.  Write is synchronous.
3159  */
3160 static int
3161 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3162     stable_how4 *stab_comm)
3163 {
3164 	mntinfo4_t *mi;
3165 	COMPOUND4args_clnt args;
3166 	COMPOUND4res_clnt res;
3167 	WRITE4args *wargs;
3168 	WRITE4res *wres;
3169 	nfs_argop4 argop[2];
3170 	nfs_resop4 *resop;
3171 	int tsize;
3172 	stable_how4 stable;
3173 	rnode4_t *rp;
3174 	int doqueue = 1;
3175 	bool_t needrecov;
3176 	nfs4_recov_state_t recov_state;
3177 	nfs4_stateid_types_t sid_types;
3178 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3179 	int recov;
3180 
3181 	rp = VTOR4(vp);
3182 	mi = VTOMI4(vp);
3183 
3184 	ASSERT(nfs_zone() == mi->mi_zone);
3185 
3186 	stable = *stab_comm;
3187 	*stab_comm = FILE_SYNC4;
3188 
3189 	needrecov = FALSE;
3190 	recov_state.rs_flags = 0;
3191 	recov_state.rs_num_retry_despite_err = 0;
3192 	nfs4_init_stateid_types(&sid_types);
3193 
3194 	/* Is curthread the recovery thread? */
3195 	mutex_enter(&mi->mi_lock);
3196 	recov = (mi->mi_recovthread == curthread);
3197 	mutex_exit(&mi->mi_lock);
3198 
3199 recov_retry:
3200 	args.ctag = TAG_WRITE;
3201 	args.array_len = 2;
3202 	args.array = argop;
3203 
3204 	if (!recov) {
3205 		e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3206 		    &recov_state, NULL);
3207 		if (e.error)
3208 			return (e.error);
3209 	}
3210 
3211 	/* 0. putfh target fh */
3212 	argop[0].argop = OP_CPUTFH;
3213 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3214 
3215 	/* 1. write */
3216 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3217 
3218 	do {
3219 
3220 		wargs->offset = (offset4)offset;
3221 		wargs->data_val = base;
3222 
3223 		if (mi->mi_io_kstats) {
3224 			mutex_enter(&mi->mi_lock);
3225 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3226 			mutex_exit(&mi->mi_lock);
3227 		}
3228 
3229 		if ((vp->v_flag & VNOCACHE) ||
3230 		    (rp->r_flags & R4DIRECTIO) ||
3231 		    (mi->mi_flags & MI4_DIRECTIO))
3232 			tsize = MIN(mi->mi_stsize, count);
3233 		else
3234 			tsize = MIN(mi->mi_curwrite, count);
3235 		wargs->data_len = (uint_t)tsize;
3236 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3237 
3238 		if (mi->mi_io_kstats) {
3239 			mutex_enter(&mi->mi_lock);
3240 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3241 			mutex_exit(&mi->mi_lock);
3242 		}
3243 
3244 		if (!recov) {
3245 			needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3246 			if (e.error && !needrecov) {
3247 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3248 				    &recov_state, needrecov);
3249 				return (e.error);
3250 			}
3251 		} else {
3252 			if (e.error)
3253 				return (e.error);
3254 		}
3255 
3256 		/*
3257 		 * Do handling of OLD_STATEID outside
3258 		 * of the normal recovery framework.
3259 		 *
3260 		 * If write receives a BAD stateid error while using a
3261 		 * delegation stateid, retry using the open stateid (if it
3262 		 * exists).  If it doesn't have an open stateid, reopen the
3263 		 * file first, then retry.
3264 		 */
3265 		if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3266 		    sid_types.cur_sid_type != SPEC_SID) {
3267 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3268 			if (!recov)
3269 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3270 				    &recov_state, needrecov);
3271 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3272 			goto recov_retry;
3273 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3274 		    sid_types.cur_sid_type == DEL_SID) {
3275 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3276 			mutex_enter(&rp->r_statev4_lock);
3277 			rp->r_deleg_return_pending = TRUE;
3278 			mutex_exit(&rp->r_statev4_lock);
3279 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3280 				if (!recov)
3281 					nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3282 					    &recov_state, needrecov);
3283 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3284 				    (caddr_t)&res);
3285 				return (EIO);
3286 			}
3287 			if (!recov)
3288 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3289 				    &recov_state, needrecov);
3290 			/* hold needed for nfs4delegreturn_thread */
3291 			VN_HOLD(vp);
3292 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3293 			    NFS4_DR_DISCARD), FALSE);
3294 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3295 			goto recov_retry;
3296 		}
3297 
3298 		if (needrecov) {
3299 			bool_t abort;
3300 
3301 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3302 			    "nfs4write: client got error %d, res.status %d"
3303 			    ", so start recovery", e.error, res.status));
3304 
3305 			abort = nfs4_start_recovery(&e,
3306 			    VTOMI4(vp), vp, NULL, &wargs->stateid,
3307 			    NULL, OP_WRITE, NULL, NULL, NULL);
3308 			if (!e.error) {
3309 				e.error = geterrno4(res.status);
3310 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3311 				    (caddr_t)&res);
3312 			}
3313 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3314 			    &recov_state, needrecov);
3315 			if (abort == FALSE)
3316 				goto recov_retry;
3317 			return (e.error);
3318 		}
3319 
3320 		if (res.status) {
3321 			e.error = geterrno4(res.status);
3322 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3323 			if (!recov)
3324 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3325 				    &recov_state, needrecov);
3326 			return (e.error);
3327 		}
3328 
3329 		resop = &res.array[1];	/* write res */
3330 		wres = &resop->nfs_resop4_u.opwrite;
3331 
3332 		if ((int)wres->count > tsize) {
3333 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3334 
3335 			zcmn_err(getzoneid(), CE_WARN,
3336 			    "nfs4write: server wrote %u, requested was %u",
3337 			    (int)wres->count, tsize);
3338 			if (!recov)
3339 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3340 				    &recov_state, needrecov);
3341 			return (EIO);
3342 		}
3343 		if (wres->committed == UNSTABLE4) {
3344 			*stab_comm = UNSTABLE4;
3345 			if (wargs->stable == DATA_SYNC4 ||
3346 			    wargs->stable == FILE_SYNC4) {
3347 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3348 				    (caddr_t)&res);
3349 				zcmn_err(getzoneid(), CE_WARN,
3350 				    "nfs4write: server %s did not commit "
3351 				    "to stable storage",
3352 				    rp->r_server->sv_hostname);
3353 				if (!recov)
3354 					nfs4_end_fop(VTOMI4(vp), vp, NULL,
3355 					    OH_WRITE, &recov_state, needrecov);
3356 				return (EIO);
3357 			}
3358 		}
3359 
3360 		tsize = (int)wres->count;
3361 		count -= tsize;
3362 		base += tsize;
3363 		offset += tsize;
3364 		if (mi->mi_io_kstats) {
3365 			mutex_enter(&mi->mi_lock);
3366 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3367 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3368 			    tsize;
3369 			mutex_exit(&mi->mi_lock);
3370 		}
3371 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3372 		mutex_enter(&rp->r_statelock);
3373 		if (rp->r_flags & R4HAVEVERF) {
3374 			if (rp->r_writeverf != wres->writeverf) {
3375 				nfs4_set_mod(vp);
3376 				rp->r_writeverf = wres->writeverf;
3377 			}
3378 		} else {
3379 			rp->r_writeverf = wres->writeverf;
3380 			rp->r_flags |= R4HAVEVERF;
3381 		}
3382 		PURGE_ATTRCACHE4_LOCKED(rp);
3383 		rp->r_flags |= R4WRITEMODIFIED;
3384 		gethrestime(&rp->r_attr.va_mtime);
3385 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3386 		mutex_exit(&rp->r_statelock);
3387 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3388 	} while (count);
3389 
3390 	if (!recov)
3391 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state,
3392 		    needrecov);
3393 
3394 	return (e.error);
3395 }
3396 
3397 /*
3398  * Read from a file.  Reads data in largest chunks our interface can handle.
3399  */
3400 static int
3401 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3402     size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3403 {
3404 	mntinfo4_t *mi;
3405 	COMPOUND4args_clnt args;
3406 	COMPOUND4res_clnt res;
3407 	READ4args *rargs;
3408 	nfs_argop4 argop[2];
3409 	int tsize;
3410 	int doqueue;
3411 	rnode4_t *rp;
3412 	int data_len;
3413 	bool_t is_eof;
3414 	bool_t needrecov = FALSE;
3415 	nfs4_recov_state_t recov_state;
3416 	nfs4_stateid_types_t sid_types;
3417 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3418 
3419 	rp = VTOR4(vp);
3420 	mi = VTOMI4(vp);
3421 	doqueue = 1;
3422 
3423 	ASSERT(nfs_zone() == mi->mi_zone);
3424 
3425 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3426 
3427 	args.array_len = 2;
3428 	args.array = argop;
3429 
3430 	nfs4_init_stateid_types(&sid_types);
3431 
3432 	recov_state.rs_flags = 0;
3433 	recov_state.rs_num_retry_despite_err = 0;
3434 
3435 recov_retry:
3436 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3437 	    &recov_state, NULL);
3438 	if (e.error)
3439 		return (e.error);
3440 
3441 	/* putfh target fh */
3442 	argop[0].argop = OP_CPUTFH;
3443 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3444 
3445 	/* read */
3446 	argop[1].argop = OP_READ;
3447 	rargs = &argop[1].nfs_argop4_u.opread;
3448 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3449 	    OP_READ, &sid_types, async);
3450 
3451 	do {
3452 		if (mi->mi_io_kstats) {
3453 			mutex_enter(&mi->mi_lock);
3454 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3455 			mutex_exit(&mi->mi_lock);
3456 		}
3457 
3458 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3459 		    "nfs4read: %s call, rp %s",
3460 		    needrecov ? "recov" : "first",
3461 		    rnode4info(rp)));
3462 
3463 		if ((vp->v_flag & VNOCACHE) ||
3464 		    (rp->r_flags & R4DIRECTIO) ||
3465 		    (mi->mi_flags & MI4_DIRECTIO))
3466 			tsize = MIN(mi->mi_tsize, count);
3467 		else
3468 			tsize = MIN(mi->mi_curread, count);
3469 
3470 		rargs->offset = (offset4)offset;
3471 		rargs->count = (count4)tsize;
3472 		rargs->res_data_val_alt = NULL;
3473 		rargs->res_mblk = NULL;
3474 		rargs->res_uiop = NULL;
3475 		rargs->res_maxsize = 0;
3476 		rargs->wlist = NULL;
3477 
3478 		if (uiop)
3479 			rargs->res_uiop = uiop;
3480 		else
3481 			rargs->res_data_val_alt = base;
3482 		rargs->res_maxsize = tsize;
3483 
3484 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3485 #ifdef	DEBUG
3486 		if (nfs4read_error_inject) {
3487 			res.status = nfs4read_error_inject;
3488 			nfs4read_error_inject = 0;
3489 		}
3490 #endif
3491 
3492 		if (mi->mi_io_kstats) {
3493 			mutex_enter(&mi->mi_lock);
3494 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3495 			mutex_exit(&mi->mi_lock);
3496 		}
3497 
3498 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3499 		if (e.error != 0 && !needrecov) {
3500 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3501 			    &recov_state, needrecov);
3502 			return (e.error);
3503 		}
3504 
3505 		/*
3506 		 * Do proper retry for OLD and BAD stateid errors outside
3507 		 * of the normal recovery framework.  There are two differences
3508 		 * between async and sync reads.  The first is that we allow
3509 		 * retry on BAD_STATEID for async reads, but not sync reads.
3510 		 * The second is that we mark the file dead for a failed
3511 		 * attempt with a special stateid for sync reads, but just
3512 		 * return EIO for async reads.
3513 		 *
3514 		 * If a sync read receives a BAD stateid error while using a
3515 		 * delegation stateid, retry using the open stateid (if it
3516 		 * exists).  If it doesn't have an open stateid, reopen the
3517 		 * file first, then retry.
3518 		 */
3519 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3520 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3521 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3522 			    &recov_state, needrecov);
3523 			if (sid_types.cur_sid_type == SPEC_SID) {
3524 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3525 				    (caddr_t)&res);
3526 				return (EIO);
3527 			}
3528 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3529 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3530 			goto recov_retry;
3531 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3532 		    !async && sid_types.cur_sid_type != SPEC_SID) {
3533 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3534 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3535 			    &recov_state, needrecov);
3536 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3537 			goto recov_retry;
3538 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3539 		    sid_types.cur_sid_type == DEL_SID) {
3540 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3541 			mutex_enter(&rp->r_statev4_lock);
3542 			rp->r_deleg_return_pending = TRUE;
3543 			mutex_exit(&rp->r_statev4_lock);
3544 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3545 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3546 				    &recov_state, needrecov);
3547 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3548 				    (caddr_t)&res);
3549 				return (EIO);
3550 			}
3551 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3552 			    &recov_state, needrecov);
3553 			/* hold needed for nfs4delegreturn_thread */
3554 			VN_HOLD(vp);
3555 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3556 			    NFS4_DR_DISCARD), FALSE);
3557 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3558 			goto recov_retry;
3559 		}
3560 		if (needrecov) {
3561 			bool_t abort;
3562 
3563 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3564 			    "nfs4read: initiating recovery\n"));
3565 			abort = nfs4_start_recovery(&e,
3566 			    mi, vp, NULL, &rargs->stateid,
3567 			    NULL, OP_READ, NULL, NULL, NULL);
3568 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3569 			    &recov_state, needrecov);
3570 			/*
3571 			 * Do not retry if we got OLD_STATEID using a special
3572 			 * stateid.  This avoids looping with a broken server.
3573 			 */
3574 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3575 			    sid_types.cur_sid_type == SPEC_SID)
3576 				abort = TRUE;
3577 
3578 			if (abort == FALSE) {
3579 				/*
3580 				 * Need to retry all possible stateids in
3581 				 * case the recovery error wasn't stateid
3582 				 * related or the stateids have become
3583 				 * stale (server reboot).
3584 				 */
3585 				nfs4_init_stateid_types(&sid_types);
3586 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3587 				    (caddr_t)&res);
3588 				goto recov_retry;
3589 			}
3590 
3591 			if (!e.error) {
3592 				e.error = geterrno4(res.status);
3593 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3594 				    (caddr_t)&res);
3595 			}
3596 			return (e.error);
3597 		}
3598 
3599 		if (res.status) {
3600 			e.error = geterrno4(res.status);
3601 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3602 			    &recov_state, needrecov);
3603 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3604 			return (e.error);
3605 		}
3606 
3607 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3608 		count -= data_len;
3609 		if (base)
3610 			base += data_len;
3611 		offset += data_len;
3612 		if (mi->mi_io_kstats) {
3613 			mutex_enter(&mi->mi_lock);
3614 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3615 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3616 			mutex_exit(&mi->mi_lock);
3617 		}
3618 		lwp_stat_update(LWP_STAT_INBLK, 1);
3619 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3620 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3621 
3622 	} while (count && !is_eof);
3623 
3624 	*residp = count;
3625 
3626 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3627 
3628 	return (e.error);
3629 }
3630 
3631 /* ARGSUSED */
3632 static int
3633 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp,
3634     caller_context_t *ct)
3635 {
3636 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3637 		return (EIO);
3638 	switch (cmd) {
3639 		case _FIODIRECTIO:
3640 			return (nfs4_directio(vp, (int)arg, cr));
3641 		default:
3642 			return (ENOTTY);
3643 	}
3644 }
3645 
3646 /* ARGSUSED */
3647 int
3648 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3649     caller_context_t *ct)
3650 {
3651 	int error;
3652 	rnode4_t *rp = VTOR4(vp);
3653 
3654 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3655 		return (EIO);
3656 	/*
3657 	 * If it has been specified that the return value will
3658 	 * just be used as a hint, and we are only being asked
3659 	 * for size, fsid or rdevid, then return the client's
3660 	 * notion of these values without checking to make sure
3661 	 * that the attribute cache is up to date.
3662 	 * The whole point is to avoid an over the wire GETATTR
3663 	 * call.
3664 	 */
3665 	if (flags & ATTR_HINT) {
3666 		if (!(vap->va_mask & ~(AT_SIZE | AT_FSID | AT_RDEV))) {
3667 			mutex_enter(&rp->r_statelock);
3668 			if (vap->va_mask & AT_SIZE)
3669 				vap->va_size = rp->r_size;
3670 			if (vap->va_mask & AT_FSID)
3671 				vap->va_fsid = rp->r_attr.va_fsid;
3672 			if (vap->va_mask & AT_RDEV)
3673 				vap->va_rdev = rp->r_attr.va_rdev;
3674 			mutex_exit(&rp->r_statelock);
3675 			return (0);
3676 		}
3677 	}
3678 
3679 	/*
3680 	 * Only need to flush pages if asking for the mtime
3681 	 * and if there any dirty pages or any outstanding
3682 	 * asynchronous (write) requests for this file.
3683 	 */
3684 	if (vap->va_mask & AT_MTIME) {
3685 		rp = VTOR4(vp);
3686 		if (nfs4_has_pages(vp)) {
3687 			mutex_enter(&rp->r_statev4_lock);
3688 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3689 				mutex_exit(&rp->r_statev4_lock);
3690 				if (rp->r_flags & R4DIRTY ||
3691 				    rp->r_awcount > 0) {
3692 					mutex_enter(&rp->r_statelock);
3693 					rp->r_gcount++;
3694 					mutex_exit(&rp->r_statelock);
3695 					error =
3696 					    nfs4_putpage(vp, (u_offset_t)0,
3697 					    0, 0, cr, NULL);
3698 					mutex_enter(&rp->r_statelock);
3699 					if (error && (error == ENOSPC ||
3700 					    error == EDQUOT)) {
3701 						if (!rp->r_error)
3702 							rp->r_error = error;
3703 					}
3704 					if (--rp->r_gcount == 0)
3705 						cv_broadcast(&rp->r_cv);
3706 					mutex_exit(&rp->r_statelock);
3707 				}
3708 			} else {
3709 				mutex_exit(&rp->r_statev4_lock);
3710 			}
3711 		}
3712 	}
3713 	return (nfs4getattr(vp, vap, cr));
3714 }
3715 
3716 int
3717 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3718 {
3719 	/*
3720 	 * If these are the only two bits cleared
3721 	 * on the server then return 0 (OK) else
3722 	 * return 1 (BAD).
3723 	 */
3724 	on_client &= ~(S_ISUID|S_ISGID);
3725 	if (on_client == from_server)
3726 		return (0);
3727 	else
3728 		return (1);
3729 }
3730 
3731 /*ARGSUSED4*/
3732 static int
3733 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3734     caller_context_t *ct)
3735 {
3736 	int error;
3737 
3738 	if (vap->va_mask & AT_NOSET)
3739 		return (EINVAL);
3740 
3741 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3742 		return (EIO);
3743 
3744 	/*
3745 	 * Don't call secpolicy_vnode_setattr, the client cannot
3746 	 * use its cached attributes to make security decisions
3747 	 * as the server may be faking mode bits or mapping uid/gid.
3748 	 * Always just let the server to the checking.
3749 	 * If we provide the ability to remove basic priviledges
3750 	 * to setattr (e.g. basic without chmod) then we will
3751 	 * need to add a check here before calling the server.
3752 	 */
3753 	error = nfs4setattr(vp, vap, flags, cr, NULL);
3754 
3755 	if (error == 0 && (vap->va_mask & AT_SIZE) && vap->va_size == 0)
3756 		vnevent_truncate(vp, ct);
3757 
3758 	return (error);
3759 }
3760 
3761 /*
3762  * To replace the "guarded" version 3 setattr, we use two types of compound
3763  * setattr requests:
3764  * 1. The "normal" setattr, used when the size of the file isn't being
3765  *    changed - { Putfh <fh>; Setattr; Getattr }/
3766  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3767  *    with only ctime as the argument. If the server ctime differs from
3768  *    what is cached on the client, the verify will fail, but we would
3769  *    already have the ctime from the preceding getattr, so just set it
3770  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3771  *	Setattr; Getattr }.
3772  *
3773  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3774  * this setattr and NULL if they are not.
3775  */
3776 static int
3777 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3778     vsecattr_t *vsap)
3779 {
3780 	COMPOUND4args_clnt args;
3781 	COMPOUND4res_clnt res, *resp = NULL;
3782 	nfs4_ga_res_t *garp = NULL;
3783 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3784 	nfs_argop4 argop[5];
3785 	int verify_argop = -1;
3786 	int setattr_argop = 1;
3787 	nfs_resop4 *resop;
3788 	vattr_t va;
3789 	rnode4_t *rp;
3790 	int doqueue = 1;
3791 	uint_t mask = vap->va_mask;
3792 	mode_t omode;
3793 	vsecattr_t *vsp;
3794 	timestruc_t ctime;
3795 	bool_t needrecov = FALSE;
3796 	nfs4_recov_state_t recov_state;
3797 	nfs4_stateid_types_t sid_types;
3798 	stateid4 stateid;
3799 	hrtime_t t;
3800 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3801 	servinfo4_t *svp;
3802 	bitmap4 supp_attrs;
3803 
3804 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3805 	rp = VTOR4(vp);
3806 	nfs4_init_stateid_types(&sid_types);
3807 
3808 	/*
3809 	 * Only need to flush pages if there are any pages and
3810 	 * if the file is marked as dirty in some fashion.  The
3811 	 * file must be flushed so that we can accurately
3812 	 * determine the size of the file and the cached data
3813 	 * after the SETATTR returns.  A file is considered to
3814 	 * be dirty if it is either marked with R4DIRTY, has
3815 	 * outstanding i/o's active, or is mmap'd.  In this
3816 	 * last case, we can't tell whether there are dirty
3817 	 * pages, so we flush just to be sure.
3818 	 */
3819 	if (nfs4_has_pages(vp) &&
3820 	    ((rp->r_flags & R4DIRTY) ||
3821 	    rp->r_count > 0 ||
3822 	    rp->r_mapcnt > 0)) {
3823 		ASSERT(vp->v_type != VCHR);
3824 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr, NULL);
3825 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3826 			mutex_enter(&rp->r_statelock);
3827 			if (!rp->r_error)
3828 				rp->r_error = e.error;
3829 			mutex_exit(&rp->r_statelock);
3830 		}
3831 	}
3832 
3833 	if (mask & AT_SIZE) {
3834 		/*
3835 		 * Verification setattr compound for non-deleg AT_SIZE:
3836 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3837 		 * Set ctime local here (outside the do_again label)
3838 		 * so that subsequent retries (after failed VERIFY)
3839 		 * will use ctime from GETATTR results (from failed
3840 		 * verify compound) as VERIFY arg.
3841 		 * If file has delegation, then VERIFY(time_metadata)
3842 		 * is of little added value, so don't bother.
3843 		 */
3844 		mutex_enter(&rp->r_statev4_lock);
3845 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3846 		    rp->r_deleg_return_pending) {
3847 			numops = 5;
3848 			ctime = rp->r_attr.va_ctime;
3849 		}
3850 		mutex_exit(&rp->r_statev4_lock);
3851 	}
3852 
3853 	recov_state.rs_flags = 0;
3854 	recov_state.rs_num_retry_despite_err = 0;
3855 
3856 	args.ctag = TAG_SETATTR;
3857 do_again:
3858 recov_retry:
3859 	setattr_argop = numops - 2;
3860 
3861 	args.array = argop;
3862 	args.array_len = numops;
3863 
3864 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3865 	if (e.error)
3866 		return (e.error);
3867 
3868 
3869 	/* putfh target fh */
3870 	argop[0].argop = OP_CPUTFH;
3871 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3872 
3873 	if (numops == 5) {
3874 		/*
3875 		 * We only care about the ctime, but need to get mtime
3876 		 * and size for proper cache update.
3877 		 */
3878 		/* getattr */
3879 		argop[1].argop = OP_GETATTR;
3880 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3881 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3882 
3883 		/* verify - set later in loop */
3884 		verify_argop = 2;
3885 	}
3886 
3887 	/* setattr */
3888 	svp = rp->r_server;
3889 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3890 	supp_attrs = svp->sv_supp_attrs;
3891 	nfs_rw_exit(&svp->sv_lock);
3892 
3893 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3894 	    supp_attrs, &e.error, &sid_types);
3895 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3896 	if (e.error) {
3897 		/* req time field(s) overflow - return immediately */
3898 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3899 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3900 		    opsetattr.obj_attributes);
3901 		return (e.error);
3902 	}
3903 	omode = rp->r_attr.va_mode;
3904 
3905 	/* getattr */
3906 	argop[numops-1].argop = OP_GETATTR;
3907 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3908 	/*
3909 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3910 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3911 	 * used in updating the ACL cache.
3912 	 */
3913 	if (vsap != NULL)
3914 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3915 		    FATTR4_ACL_MASK;
3916 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3917 
3918 	/*
3919 	 * setattr iterates if the object size is set and the cached ctime
3920 	 * does not match the file ctime. In that case, verify the ctime first.
3921 	 */
3922 
3923 	do {
3924 		if (verify_argop != -1) {
3925 			/*
3926 			 * Verify that the ctime match before doing setattr.
3927 			 */
3928 			va.va_mask = AT_CTIME;
3929 			va.va_ctime = ctime;
3930 			svp = rp->r_server;
3931 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3932 			supp_attrs = svp->sv_supp_attrs;
3933 			nfs_rw_exit(&svp->sv_lock);
3934 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3935 			    OP_VERIFY, supp_attrs);
3936 			if (e.error) {
3937 				/* req time field(s) overflow - return */
3938 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3939 				    needrecov);
3940 				break;
3941 			}
3942 		}
3943 
3944 		doqueue = 1;
3945 
3946 		t = gethrtime();
3947 
3948 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3949 
3950 		/*
3951 		 * Purge the access cache and ACL cache if changing either the
3952 		 * owner of the file, the group owner, or the mode.  These may
3953 		 * change the access permissions of the file, so purge old
3954 		 * information and start over again.
3955 		 */
3956 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3957 			(void) nfs4_access_purge_rp(rp);
3958 			if (rp->r_secattr != NULL) {
3959 				mutex_enter(&rp->r_statelock);
3960 				vsp = rp->r_secattr;
3961 				rp->r_secattr = NULL;
3962 				mutex_exit(&rp->r_statelock);
3963 				if (vsp != NULL)
3964 					nfs4_acl_free_cache(vsp);
3965 			}
3966 		}
3967 
3968 		/*
3969 		 * If res.array_len == numops, then everything succeeded,
3970 		 * except for possibly the final getattr.  If only the
3971 		 * last getattr failed, give up, and don't try recovery.
3972 		 */
3973 		if (res.array_len == numops) {
3974 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3975 			    needrecov);
3976 			if (! e.error)
3977 				resp = &res;
3978 			break;
3979 		}
3980 
3981 		/*
3982 		 * if either rpc call failed or completely succeeded - done
3983 		 */
3984 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
3985 		if (e.error) {
3986 			PURGE_ATTRCACHE4(vp);
3987 			if (!needrecov) {
3988 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3989 				    needrecov);
3990 				break;
3991 			}
3992 		}
3993 
3994 		/*
3995 		 * Do proper retry for OLD_STATEID outside of the normal
3996 		 * recovery framework.
3997 		 */
3998 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3999 		    sid_types.cur_sid_type != SPEC_SID &&
4000 		    sid_types.cur_sid_type != NO_SID) {
4001 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4002 			    needrecov);
4003 			nfs4_save_stateid(&stateid, &sid_types);
4004 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4005 			    opsetattr.obj_attributes);
4006 			if (verify_argop != -1) {
4007 				nfs4args_verify_free(&argop[verify_argop]);
4008 				verify_argop = -1;
4009 			}
4010 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4011 			goto recov_retry;
4012 		}
4013 
4014 		if (needrecov) {
4015 			bool_t abort;
4016 
4017 			abort = nfs4_start_recovery(&e,
4018 			    VTOMI4(vp), vp, NULL, NULL, NULL,
4019 			    OP_SETATTR, NULL, NULL, NULL);
4020 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4021 			    needrecov);
4022 			/*
4023 			 * Do not retry if we failed with OLD_STATEID using
4024 			 * a special stateid.  This is done to avoid looping
4025 			 * with a broken server.
4026 			 */
4027 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
4028 			    (sid_types.cur_sid_type == SPEC_SID ||
4029 			    sid_types.cur_sid_type == NO_SID))
4030 				abort = TRUE;
4031 			if (!e.error) {
4032 				if (res.status == NFS4ERR_BADOWNER)
4033 					nfs4_log_badowner(VTOMI4(vp),
4034 					    OP_SETATTR);
4035 
4036 				e.error = geterrno4(res.status);
4037 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4038 				    (caddr_t)&res);
4039 			}
4040 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4041 			    opsetattr.obj_attributes);
4042 			if (verify_argop != -1) {
4043 				nfs4args_verify_free(&argop[verify_argop]);
4044 				verify_argop = -1;
4045 			}
4046 			if (abort == FALSE) {
4047 				/*
4048 				 * Need to retry all possible stateids in
4049 				 * case the recovery error wasn't stateid
4050 				 * related or the stateids have become
4051 				 * stale (server reboot).
4052 				 */
4053 				nfs4_init_stateid_types(&sid_types);
4054 				goto recov_retry;
4055 			}
4056 			return (e.error);
4057 		}
4058 
4059 		/*
4060 		 * Need to call nfs4_end_op before nfs4getattr to
4061 		 * avoid potential nfs4_start_op deadlock. See RFE
4062 		 * 4777612.  Calls to nfs4_invalidate_pages() and
4063 		 * nfs4_purge_stale_fh() might also generate over the
4064 		 * wire calls which my cause nfs4_start_op() deadlock.
4065 		 */
4066 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4067 
4068 		/*
4069 		 * Check to update lease.
4070 		 */
4071 		resp = &res;
4072 		if (res.status == NFS4_OK) {
4073 			break;
4074 		}
4075 
4076 		/*
4077 		 * Check if verify failed to see if try again
4078 		 */
4079 		if ((verify_argop == -1) || (res.array_len != 3)) {
4080 			/*
4081 			 * can't continue...
4082 			 */
4083 			if (res.status == NFS4ERR_BADOWNER)
4084 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
4085 
4086 			e.error = geterrno4(res.status);
4087 		} else {
4088 			/*
4089 			 * When the verify request fails, the client ctime is
4090 			 * not in sync with the server. This is the same as
4091 			 * the version 3 "not synchronized" error, and we
4092 			 * handle it in a similar manner (XXX do we need to???).
4093 			 * Use the ctime returned in the first getattr for
4094 			 * the input to the next verify.
4095 			 * If we couldn't get the attributes, then we give up
4096 			 * because we can't complete the operation as required.
4097 			 */
4098 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
4099 		}
4100 		if (e.error) {
4101 			PURGE_ATTRCACHE4(vp);
4102 			nfs4_purge_stale_fh(e.error, vp, cr);
4103 		} else {
4104 			/*
4105 			 * retry with a new verify value
4106 			 */
4107 			ctime = garp->n4g_va.va_ctime;
4108 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4109 			resp = NULL;
4110 		}
4111 		if (!e.error) {
4112 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4113 			    opsetattr.obj_attributes);
4114 			if (verify_argop != -1) {
4115 				nfs4args_verify_free(&argop[verify_argop]);
4116 				verify_argop = -1;
4117 			}
4118 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4119 			goto do_again;
4120 		}
4121 	} while (!e.error);
4122 
4123 	if (e.error) {
4124 		/*
4125 		 * If we are here, rfs4call has an irrecoverable error - return
4126 		 */
4127 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4128 		    opsetattr.obj_attributes);
4129 		if (verify_argop != -1) {
4130 			nfs4args_verify_free(&argop[verify_argop]);
4131 			verify_argop = -1;
4132 		}
4133 		if (resp)
4134 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4135 		return (e.error);
4136 	}
4137 
4138 
4139 
4140 	/*
4141 	 * If changing the size of the file, invalidate
4142 	 * any local cached data which is no longer part
4143 	 * of the file.  We also possibly invalidate the
4144 	 * last page in the file.  We could use
4145 	 * pvn_vpzero(), but this would mark the page as
4146 	 * modified and require it to be written back to
4147 	 * the server for no particularly good reason.
4148 	 * This way, if we access it, then we bring it
4149 	 * back in.  A read should be cheaper than a
4150 	 * write.
4151 	 */
4152 	if (mask & AT_SIZE) {
4153 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
4154 	}
4155 
4156 	/* either no error or one of the postop getattr failed */
4157 
4158 	/*
4159 	 * XXX Perform a simplified version of wcc checking. Instead of
4160 	 * have another getattr to get pre-op, just purge cache if
4161 	 * any of the ops prior to and including the getattr failed.
4162 	 * If the getattr succeeded then update the attrcache accordingly.
4163 	 */
4164 
4165 	garp = NULL;
4166 	if (res.status == NFS4_OK) {
4167 		/*
4168 		 * Last getattr
4169 		 */
4170 		resop = &res.array[numops - 1];
4171 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4172 	}
4173 	/*
4174 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
4175 	 * rather than filling it.  See the function itself for details.
4176 	 */
4177 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4178 	if (garp != NULL) {
4179 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
4180 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
4181 			vs_ace4_destroy(&garp->n4g_vsa);
4182 		} else {
4183 			if (vsap != NULL) {
4184 				/*
4185 				 * The ACL was supposed to be set and to be
4186 				 * returned in the last getattr of this
4187 				 * compound, but for some reason the getattr
4188 				 * result doesn't contain the ACL.  In this
4189 				 * case, purge the ACL cache.
4190 				 */
4191 				if (rp->r_secattr != NULL) {
4192 					mutex_enter(&rp->r_statelock);
4193 					vsp = rp->r_secattr;
4194 					rp->r_secattr = NULL;
4195 					mutex_exit(&rp->r_statelock);
4196 					if (vsp != NULL)
4197 						nfs4_acl_free_cache(vsp);
4198 				}
4199 			}
4200 		}
4201 	}
4202 
4203 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4204 		/*
4205 		 * Set the size, rather than relying on getting it updated
4206 		 * via a GETATTR.  With delegations the client tries to
4207 		 * suppress GETATTR calls.
4208 		 */
4209 		mutex_enter(&rp->r_statelock);
4210 		rp->r_size = vap->va_size;
4211 		mutex_exit(&rp->r_statelock);
4212 	}
4213 
4214 	/*
4215 	 * Can free up request args and res
4216 	 */
4217 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4218 	    opsetattr.obj_attributes);
4219 	if (verify_argop != -1) {
4220 		nfs4args_verify_free(&argop[verify_argop]);
4221 		verify_argop = -1;
4222 	}
4223 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4224 
4225 	/*
4226 	 * Some servers will change the mode to clear the setuid
4227 	 * and setgid bits when changing the uid or gid.  The
4228 	 * client needs to compensate appropriately.
4229 	 */
4230 	if (mask & (AT_UID | AT_GID)) {
4231 		int terror, do_setattr;
4232 
4233 		do_setattr = 0;
4234 		va.va_mask = AT_MODE;
4235 		terror = nfs4getattr(vp, &va, cr);
4236 		if (!terror &&
4237 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4238 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4239 			va.va_mask = AT_MODE;
4240 			if (mask & AT_MODE) {
4241 				/*
4242 				 * We asked the mode to be changed and what
4243 				 * we just got from the server in getattr is
4244 				 * not what we wanted it to be, so set it now.
4245 				 */
4246 				va.va_mode = vap->va_mode;
4247 				do_setattr = 1;
4248 			} else {
4249 				/*
4250 				 * We did not ask the mode to be changed,
4251 				 * Check to see that the server just cleared
4252 				 * I_SUID and I_GUID from it. If not then
4253 				 * set mode to omode with UID/GID cleared.
4254 				 */
4255 				if (nfs4_compare_modes(va.va_mode, omode)) {
4256 					omode &= ~(S_ISUID|S_ISGID);
4257 					va.va_mode = omode;
4258 					do_setattr = 1;
4259 				}
4260 			}
4261 
4262 			if (do_setattr)
4263 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4264 		}
4265 	}
4266 
4267 	return (e.error);
4268 }
4269 
4270 /* ARGSUSED */
4271 static int
4272 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr, caller_context_t *ct)
4273 {
4274 	COMPOUND4args_clnt args;
4275 	COMPOUND4res_clnt res;
4276 	int doqueue;
4277 	uint32_t acc, resacc, argacc;
4278 	rnode4_t *rp;
4279 	cred_t *cred, *ncr, *ncrfree = NULL;
4280 	nfs4_access_type_t cacc;
4281 	int num_ops;
4282 	nfs_argop4 argop[3];
4283 	nfs_resop4 *resop;
4284 	bool_t needrecov = FALSE, do_getattr;
4285 	nfs4_recov_state_t recov_state;
4286 	int rpc_error;
4287 	hrtime_t t;
4288 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4289 	mntinfo4_t *mi = VTOMI4(vp);
4290 
4291 	if (nfs_zone() != mi->mi_zone)
4292 		return (EIO);
4293 
4294 	acc = 0;
4295 	if (mode & VREAD)
4296 		acc |= ACCESS4_READ;
4297 	if (mode & VWRITE) {
4298 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4299 			return (EROFS);
4300 		if (vp->v_type == VDIR)
4301 			acc |= ACCESS4_DELETE;
4302 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4303 	}
4304 	if (mode & VEXEC) {
4305 		if (vp->v_type == VDIR)
4306 			acc |= ACCESS4_LOOKUP;
4307 		else
4308 			acc |= ACCESS4_EXECUTE;
4309 	}
4310 
4311 	if (VTOR4(vp)->r_acache != NULL) {
4312 		e.error = nfs4_validate_caches(vp, cr);
4313 		if (e.error)
4314 			return (e.error);
4315 	}
4316 
4317 	rp = VTOR4(vp);
4318 	if (vp->v_type == VDIR)
4319 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4320 		    ACCESS4_EXTEND | ACCESS4_LOOKUP;
4321 	else
4322 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4323 		    ACCESS4_EXECUTE;
4324 	recov_state.rs_flags = 0;
4325 	recov_state.rs_num_retry_despite_err = 0;
4326 
4327 	cred = cr;
4328 	/*
4329 	 * ncr and ncrfree both initially
4330 	 * point to the memory area returned
4331 	 * by crnetadjust();
4332 	 * ncrfree not NULL when exiting means
4333 	 * that we need to release it
4334 	 */
4335 	ncr = crnetadjust(cred);
4336 	ncrfree = ncr;
4337 
4338 tryagain:
4339 	cacc = nfs4_access_check(rp, acc, cred);
4340 	if (cacc == NFS4_ACCESS_ALLOWED) {
4341 		if (ncrfree != NULL)
4342 			crfree(ncrfree);
4343 		return (0);
4344 	}
4345 	if (cacc == NFS4_ACCESS_DENIED) {
4346 		/*
4347 		 * If the cred can be adjusted, try again
4348 		 * with the new cred.
4349 		 */
4350 		if (ncr != NULL) {
4351 			cred = ncr;
4352 			ncr = NULL;
4353 			goto tryagain;
4354 		}
4355 		if (ncrfree != NULL)
4356 			crfree(ncrfree);
4357 		return (EACCES);
4358 	}
4359 
4360 recov_retry:
4361 	/*
4362 	 * Don't take with r_statev4_lock here. r_deleg_type could
4363 	 * change as soon as lock is released.  Since it is an int,
4364 	 * there is no atomicity issue.
4365 	 */
4366 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4367 	num_ops = do_getattr ? 3 : 2;
4368 
4369 	args.ctag = TAG_ACCESS;
4370 
4371 	args.array_len = num_ops;
4372 	args.array = argop;
4373 
4374 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4375 	    &recov_state, NULL)) {
4376 		if (ncrfree != NULL)
4377 			crfree(ncrfree);
4378 		return (e.error);
4379 	}
4380 
4381 	/* putfh target fh */
4382 	argop[0].argop = OP_CPUTFH;
4383 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4384 
4385 	/* access */
4386 	argop[1].argop = OP_ACCESS;
4387 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4388 
4389 	/* getattr */
4390 	if (do_getattr) {
4391 		argop[2].argop = OP_GETATTR;
4392 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4393 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4394 	}
4395 
4396 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4397 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4398 	    rnode4info(VTOR4(vp))));
4399 
4400 	doqueue = 1;
4401 	t = gethrtime();
4402 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4403 	rpc_error = e.error;
4404 
4405 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4406 	if (needrecov) {
4407 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4408 		    "nfs4_access: initiating recovery\n"));
4409 
4410 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4411 		    NULL, OP_ACCESS, NULL, NULL, NULL) == FALSE) {
4412 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4413 			    &recov_state, needrecov);
4414 			if (!e.error)
4415 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4416 				    (caddr_t)&res);
4417 			goto recov_retry;
4418 		}
4419 	}
4420 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4421 
4422 	if (e.error)
4423 		goto out;
4424 
4425 	if (res.status) {
4426 		e.error = geterrno4(res.status);
4427 		/*
4428 		 * This might generate over the wire calls throught
4429 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4430 		 * here to avoid a deadlock.
4431 		 */
4432 		nfs4_purge_stale_fh(e.error, vp, cr);
4433 		goto out;
4434 	}
4435 	resop = &res.array[1];	/* access res */
4436 
4437 	resacc = resop->nfs_resop4_u.opaccess.access;
4438 
4439 	if (do_getattr) {
4440 		resop++;	/* getattr res */
4441 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4442 		    t, cr, FALSE, NULL);
4443 	}
4444 
4445 	if (!e.error) {
4446 		nfs4_access_cache(rp, argacc, resacc, cred);
4447 		/*
4448 		 * we just cached results with cred; if cred is the
4449 		 * adjusted credentials from crnetadjust, we do not want
4450 		 * to release them before exiting: hence setting ncrfree
4451 		 * to NULL
4452 		 */
4453 		if (cred != cr)
4454 			ncrfree = NULL;
4455 		/* XXX check the supported bits too? */
4456 		if ((acc & resacc) != acc) {
4457 			/*
4458 			 * The following code implements the semantic
4459 			 * that a setuid root program has *at least* the
4460 			 * permissions of the user that is running the
4461 			 * program.  See rfs3call() for more portions
4462 			 * of the implementation of this functionality.
4463 			 */
4464 			/* XXX-LP */
4465 			if (ncr != NULL) {
4466 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4467 				    (caddr_t)&res);
4468 				cred = ncr;
4469 				ncr = NULL;
4470 				goto tryagain;
4471 			}
4472 			e.error = EACCES;
4473 		}
4474 	}
4475 
4476 out:
4477 	if (!rpc_error)
4478 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4479 
4480 	if (ncrfree != NULL)
4481 		crfree(ncrfree);
4482 
4483 	return (e.error);
4484 }
4485 
4486 /* ARGSUSED */
4487 static int
4488 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr, caller_context_t *ct)
4489 {
4490 	COMPOUND4args_clnt args;
4491 	COMPOUND4res_clnt res;
4492 	int doqueue;
4493 	rnode4_t *rp;
4494 	nfs_argop4 argop[3];
4495 	nfs_resop4 *resop;
4496 	READLINK4res *lr_res;
4497 	nfs4_ga_res_t *garp;
4498 	uint_t len;
4499 	char *linkdata;
4500 	bool_t needrecov = FALSE;
4501 	nfs4_recov_state_t recov_state;
4502 	hrtime_t t;
4503 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4504 
4505 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4506 		return (EIO);
4507 	/*
4508 	 * Can't readlink anything other than a symbolic link.
4509 	 */
4510 	if (vp->v_type != VLNK)
4511 		return (EINVAL);
4512 
4513 	rp = VTOR4(vp);
4514 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4515 		e.error = nfs4_validate_caches(vp, cr);
4516 		if (e.error)
4517 			return (e.error);
4518 		mutex_enter(&rp->r_statelock);
4519 		if (rp->r_symlink.contents != NULL) {
4520 			e.error = uiomove(rp->r_symlink.contents,
4521 			    rp->r_symlink.len, UIO_READ, uiop);
4522 			mutex_exit(&rp->r_statelock);
4523 			return (e.error);
4524 		}
4525 		mutex_exit(&rp->r_statelock);
4526 	}
4527 	recov_state.rs_flags = 0;
4528 	recov_state.rs_num_retry_despite_err = 0;
4529 
4530 recov_retry:
4531 	args.array_len = 3;
4532 	args.array = argop;
4533 	args.ctag = TAG_READLINK;
4534 
4535 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4536 	if (e.error) {
4537 		return (e.error);
4538 	}
4539 
4540 	/* 0. putfh symlink fh */
4541 	argop[0].argop = OP_CPUTFH;
4542 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4543 
4544 	/* 1. readlink */
4545 	argop[1].argop = OP_READLINK;
4546 
4547 	/* 2. getattr */
4548 	argop[2].argop = OP_GETATTR;
4549 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4550 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4551 
4552 	doqueue = 1;
4553 
4554 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4555 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4556 	    rnode4info(VTOR4(vp))));
4557 
4558 	t = gethrtime();
4559 
4560 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4561 
4562 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4563 	if (needrecov) {
4564 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4565 		    "nfs4_readlink: initiating recovery\n"));
4566 
4567 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4568 		    NULL, OP_READLINK, NULL, NULL, NULL) == FALSE) {
4569 			if (!e.error)
4570 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4571 				    (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 		(void) 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 	(void) 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 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4932 				    (caddr_t)&res);
4933 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4934 			    &recov_state, TRUE);
4935 			goto recov_retry_remove;
4936 		}
4937 	}
4938 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4939 
4940 	/*
4941 	 * Release stuff held for the remove
4942 	 */
4943 	VN_RELE(unldvp);
4944 	if (!e.error && resp)
4945 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4946 
4947 	kmem_free(unlname, MAXNAMELEN);
4948 	crfree(unlcred);
4949 	goto redo;
4950 }
4951 
4952 /*
4953  * Remote file system operations having to do with directory manipulation.
4954  */
4955 /* ARGSUSED3 */
4956 int
4957 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4958     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
4959     int *direntflags, pathname_t *realpnp)
4960 {
4961 	int error;
4962 	vnode_t *vp, *avp = NULL;
4963 	rnode4_t *drp;
4964 
4965 	*vpp = NULL;
4966 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4967 		return (EPERM);
4968 	/*
4969 	 * if LOOKUP_XATTR, must replace dvp (object) with
4970 	 * object's attrdir before continuing with lookup
4971 	 */
4972 	if (flags & LOOKUP_XATTR) {
4973 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4974 		if (error)
4975 			return (error);
4976 
4977 		dvp = avp;
4978 
4979 		/*
4980 		 * If lookup is for "", just return dvp now.  The attrdir
4981 		 * has already been activated (from nfs4lookup_xattr), and
4982 		 * the caller will RELE the original dvp -- not
4983 		 * the attrdir.  So, set vpp and return.
4984 		 * Currently, when the LOOKUP_XATTR flag is
4985 		 * passed to VOP_LOOKUP, the name is always empty, and
4986 		 * shortcircuiting here avoids 3 unneeded lock/unlock
4987 		 * pairs.
4988 		 *
4989 		 * If a non-empty name was provided, then it is the
4990 		 * attribute name, and it will be looked up below.
4991 		 */
4992 		if (*nm == '\0') {
4993 			*vpp = dvp;
4994 			return (0);
4995 		}
4996 
4997 		/*
4998 		 * The vfs layer never sends a name when asking for the
4999 		 * attrdir, so we should never get here (unless of course
5000 		 * name is passed at some time in future -- at which time
5001 		 * we'll blow up here).
5002 		 */
5003 		ASSERT(0);
5004 	}
5005 
5006 	drp = VTOR4(dvp);
5007 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
5008 		return (EINTR);
5009 
5010 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
5011 	nfs_rw_exit(&drp->r_rwlock);
5012 
5013 	/*
5014 	 * If vnode is a device, create special vnode.
5015 	 */
5016 	if (!error && ISVDEV((*vpp)->v_type)) {
5017 		vp = *vpp;
5018 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
5019 		VN_RELE(vp);
5020 	}
5021 
5022 	return (error);
5023 }
5024 
5025 /* ARGSUSED */
5026 static int
5027 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
5028 {
5029 	int error;
5030 	rnode4_t *drp;
5031 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
5032 	mntinfo4_t *mi;
5033 
5034 	mi = VTOMI4(dvp);
5035 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR) &&
5036 	    !vfs_has_feature(mi->mi_vfsp, VFSFT_SYSATTR_VIEWS))
5037 		return (EINVAL);
5038 
5039 	drp = VTOR4(dvp);
5040 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
5041 		return (EINTR);
5042 
5043 	mutex_enter(&drp->r_statelock);
5044 	/*
5045 	 * If the server doesn't support xattrs just return EINVAL
5046 	 */
5047 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
5048 		mutex_exit(&drp->r_statelock);
5049 		nfs_rw_exit(&drp->r_rwlock);
5050 		return (EINVAL);
5051 	}
5052 
5053 	/*
5054 	 * If there is a cached xattr directory entry,
5055 	 * use it as long as the attributes are valid. If the
5056 	 * attributes are not valid, take the simple approach and
5057 	 * free the cached value and re-fetch a new value.
5058 	 *
5059 	 * We don't negative entry cache for now, if we did we
5060 	 * would need to check if the file has changed on every
5061 	 * lookup. But xattrs don't exist very often and failing
5062 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
5063 	 * so do an openattr over the wire for now.
5064 	 */
5065 	if (drp->r_xattr_dir != NULL) {
5066 		if (ATTRCACHE4_VALID(dvp)) {
5067 			VN_HOLD(drp->r_xattr_dir);
5068 			*vpp = drp->r_xattr_dir;
5069 			mutex_exit(&drp->r_statelock);
5070 			nfs_rw_exit(&drp->r_rwlock);
5071 			return (0);
5072 		}
5073 		VN_RELE(drp->r_xattr_dir);
5074 		drp->r_xattr_dir = NULL;
5075 	}
5076 	mutex_exit(&drp->r_statelock);
5077 
5078 	error = nfs4openattr(dvp, vpp, cflag, cr);
5079 
5080 	nfs_rw_exit(&drp->r_rwlock);
5081 
5082 	return (error);
5083 }
5084 
5085 static int
5086 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
5087 {
5088 	int error;
5089 	rnode4_t *drp;
5090 
5091 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5092 
5093 	/*
5094 	 * If lookup is for "", just return dvp.  Don't need
5095 	 * to send it over the wire, look it up in the dnlc,
5096 	 * or perform any access checks.
5097 	 */
5098 	if (*nm == '\0') {
5099 		VN_HOLD(dvp);
5100 		*vpp = dvp;
5101 		return (0);
5102 	}
5103 
5104 	/*
5105 	 * Can't do lookups in non-directories.
5106 	 */
5107 	if (dvp->v_type != VDIR)
5108 		return (ENOTDIR);
5109 
5110 	/*
5111 	 * If lookup is for ".", just return dvp.  Don't need
5112 	 * to send it over the wire or look it up in the dnlc,
5113 	 * just need to check access.
5114 	 */
5115 	if (nm[0] == '.' && nm[1] == '\0') {
5116 		error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5117 		if (error)
5118 			return (error);
5119 		VN_HOLD(dvp);
5120 		*vpp = dvp;
5121 		return (0);
5122 	}
5123 
5124 	drp = VTOR4(dvp);
5125 	if (!(drp->r_flags & R4LOOKUP)) {
5126 		mutex_enter(&drp->r_statelock);
5127 		drp->r_flags |= R4LOOKUP;
5128 		mutex_exit(&drp->r_statelock);
5129 	}
5130 
5131 	*vpp = NULL;
5132 	/*
5133 	 * Lookup this name in the DNLC.  If there is no entry
5134 	 * lookup over the wire.
5135 	 */
5136 	if (!skipdnlc)
5137 		*vpp = dnlc_lookup(dvp, nm);
5138 	if (*vpp == NULL) {
5139 		/*
5140 		 * We need to go over the wire to lookup the name.
5141 		 */
5142 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
5143 	}
5144 
5145 	/*
5146 	 * We hit on the dnlc
5147 	 */
5148 	if (*vpp != DNLC_NO_VNODE ||
5149 	    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
5150 		/*
5151 		 * But our attrs may not be valid.
5152 		 */
5153 		if (ATTRCACHE4_VALID(dvp)) {
5154 			error = nfs4_waitfor_purge_complete(dvp);
5155 			if (error) {
5156 				VN_RELE(*vpp);
5157 				*vpp = NULL;
5158 				return (error);
5159 			}
5160 
5161 			/*
5162 			 * If after the purge completes, check to make sure
5163 			 * our attrs are still valid.
5164 			 */
5165 			if (ATTRCACHE4_VALID(dvp)) {
5166 				/*
5167 				 * If we waited for a purge we may have
5168 				 * lost our vnode so look it up again.
5169 				 */
5170 				VN_RELE(*vpp);
5171 				*vpp = dnlc_lookup(dvp, nm);
5172 				if (*vpp == NULL)
5173 					return (nfs4lookupnew_otw(dvp,
5174 					    nm, vpp, cr));
5175 
5176 				/*
5177 				 * The access cache should almost always hit
5178 				 */
5179 				error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5180 
5181 				if (error) {
5182 					VN_RELE(*vpp);
5183 					*vpp = NULL;
5184 					return (error);
5185 				}
5186 				if (*vpp == DNLC_NO_VNODE) {
5187 					VN_RELE(*vpp);
5188 					*vpp = NULL;
5189 					return (ENOENT);
5190 				}
5191 				return (0);
5192 			}
5193 		}
5194 	}
5195 
5196 	ASSERT(*vpp != NULL);
5197 
5198 	/*
5199 	 * We may have gotten here we have one of the following cases:
5200 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5201 	 *		need to validate them.
5202 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5203 	 *		must validate.
5204 	 *
5205 	 * Go to the server and check if the directory has changed, if
5206 	 * it hasn't we are done and can use the dnlc entry.
5207 	 */
5208 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5209 }
5210 
5211 /*
5212  * Go to the server and check if the directory has changed, if
5213  * it hasn't we are done and can use the dnlc entry.  If it
5214  * has changed we get a new copy of its attributes and check
5215  * the access for VEXEC, then relookup the filename and
5216  * get its filehandle and attributes.
5217  *
5218  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5219  *	if the NVERIFY failed we must
5220  *		purge the caches
5221  *		cache new attributes (will set r_time_attr_inval)
5222  *		cache new access
5223  *		recheck VEXEC access
5224  *		add name to dnlc, possibly negative
5225  *		if LOOKUP succeeded
5226  *			cache new attributes
5227  *	else
5228  *		set a new r_time_attr_inval for dvp
5229  *		check to make sure we have access
5230  *
5231  * The vpp returned is the vnode passed in if the directory is valid,
5232  * a new vnode if successful lookup, or NULL on error.
5233  */
5234 static int
5235 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5236 {
5237 	COMPOUND4args_clnt args;
5238 	COMPOUND4res_clnt res;
5239 	fattr4 *ver_fattr;
5240 	fattr4_change dchange;
5241 	int32_t *ptr;
5242 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5243 	nfs_argop4 *argop;
5244 	int doqueue;
5245 	mntinfo4_t *mi;
5246 	nfs4_recov_state_t recov_state;
5247 	hrtime_t t;
5248 	int isdotdot;
5249 	vnode_t *nvp;
5250 	nfs_fh4 *fhp;
5251 	nfs4_sharedfh_t *sfhp;
5252 	nfs4_access_type_t cacc;
5253 	rnode4_t *nrp;
5254 	rnode4_t *drp = VTOR4(dvp);
5255 	nfs4_ga_res_t *garp = NULL;
5256 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5257 
5258 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5259 	ASSERT(nm != NULL);
5260 	ASSERT(nm[0] != '\0');
5261 	ASSERT(dvp->v_type == VDIR);
5262 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5263 	ASSERT(*vpp != NULL);
5264 
5265 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5266 		isdotdot = 1;
5267 		args.ctag = TAG_LOOKUP_VPARENT;
5268 	} else {
5269 		/*
5270 		 * If dvp were a stub, it should have triggered and caused
5271 		 * a mount for us to get this far.
5272 		 */
5273 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5274 
5275 		isdotdot = 0;
5276 		args.ctag = TAG_LOOKUP_VALID;
5277 	}
5278 
5279 	mi = VTOMI4(dvp);
5280 	recov_state.rs_flags = 0;
5281 	recov_state.rs_num_retry_despite_err = 0;
5282 
5283 	nvp = NULL;
5284 
5285 	/* Save the original mount point security information */
5286 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5287 
5288 recov_retry:
5289 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5290 	    &recov_state, NULL);
5291 	if (e.error) {
5292 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5293 		VN_RELE(*vpp);
5294 		*vpp = NULL;
5295 		return (e.error);
5296 	}
5297 
5298 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5299 
5300 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5301 	args.array_len = 7;
5302 	args.array = argop;
5303 
5304 	/* 0. putfh file */
5305 	argop[0].argop = OP_CPUTFH;
5306 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5307 
5308 	/* 1. nverify the change info */
5309 	argop[1].argop = OP_NVERIFY;
5310 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5311 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5312 	ver_fattr->attrlist4 = (char *)&dchange;
5313 	ptr = (int32_t *)&dchange;
5314 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5315 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5316 
5317 	/* 2. getattr directory */
5318 	argop[2].argop = OP_GETATTR;
5319 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5320 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5321 
5322 	/* 3. access directory */
5323 	argop[3].argop = OP_ACCESS;
5324 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5325 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5326 
5327 	/* 4. lookup name */
5328 	if (isdotdot) {
5329 		argop[4].argop = OP_LOOKUPP;
5330 	} else {
5331 		argop[4].argop = OP_CLOOKUP;
5332 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5333 	}
5334 
5335 	/* 5. resulting file handle */
5336 	argop[5].argop = OP_GETFH;
5337 
5338 	/* 6. resulting file attributes */
5339 	argop[6].argop = OP_GETATTR;
5340 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5341 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5342 
5343 	doqueue = 1;
5344 	t = gethrtime();
5345 
5346 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5347 
5348 	if (!isdotdot && res.status == NFS4ERR_MOVED) {
5349 		e.error = nfs4_setup_referral(dvp, nm, vpp, cr);
5350 		if (e.error != 0 && *vpp != NULL)
5351 			VN_RELE(*vpp);
5352 		nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5353 		    &recov_state, FALSE);
5354 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5355 		kmem_free(argop, argoplist_size);
5356 		return (e.error);
5357 	}
5358 
5359 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5360 		/*
5361 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5362 		 * from this thread, do not go thru the recovery thread since
5363 		 * we need the nm information.
5364 		 *
5365 		 * Not doing dotdot case because there is no specification
5366 		 * for (PUTFH, SECINFO "..") yet.
5367 		 */
5368 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5369 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5370 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5371 				    &recov_state, FALSE);
5372 			else
5373 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5374 				    &recov_state, TRUE);
5375 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5376 			kmem_free(argop, argoplist_size);
5377 			if (!e.error)
5378 				goto recov_retry;
5379 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5380 			VN_RELE(*vpp);
5381 			*vpp = NULL;
5382 			return (e.error);
5383 		}
5384 
5385 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5386 		    OP_LOOKUP, NULL, NULL, NULL) == FALSE) {
5387 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5388 			    &recov_state, TRUE);
5389 
5390 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5391 			kmem_free(argop, argoplist_size);
5392 			goto recov_retry;
5393 		}
5394 	}
5395 
5396 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5397 
5398 	if (e.error || res.array_len == 0) {
5399 		/*
5400 		 * If e.error isn't set, then reply has no ops (or we couldn't
5401 		 * be here).  The only legal way to reply without an op array
5402 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5403 		 * be in the reply for all other status values.
5404 		 *
5405 		 * For valid replies without an ops array, return ENOTSUP
5406 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5407 		 * return EIO -- don't trust status.
5408 		 */
5409 		if (e.error == 0)
5410 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5411 			    ENOTSUP : EIO;
5412 		VN_RELE(*vpp);
5413 		*vpp = NULL;
5414 		kmem_free(argop, argoplist_size);
5415 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5416 		return (e.error);
5417 	}
5418 
5419 	if (res.status != NFS4ERR_SAME) {
5420 		e.error = geterrno4(res.status);
5421 
5422 		/*
5423 		 * The NVERIFY "failed" so the directory has changed
5424 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5425 		 * cleanly.
5426 		 */
5427 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5428 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5429 			nfs4_purge_stale_fh(e.error, dvp, cr);
5430 			VN_RELE(*vpp);
5431 			*vpp = NULL;
5432 			goto exit;
5433 		}
5434 
5435 		/*
5436 		 * We know the NVERIFY "failed" so we must:
5437 		 *	purge the caches (access and indirectly dnlc if needed)
5438 		 */
5439 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5440 
5441 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5442 			nfs4_purge_stale_fh(e.error, dvp, cr);
5443 			VN_RELE(*vpp);
5444 			*vpp = NULL;
5445 			goto exit;
5446 		}
5447 
5448 		/*
5449 		 * Install new cached attributes for the directory
5450 		 */
5451 		nfs4_attr_cache(dvp,
5452 		    &res.array[2].nfs_resop4_u.opgetattr.ga_res,
5453 		    t, cr, FALSE, NULL);
5454 
5455 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5456 			nfs4_purge_stale_fh(e.error, dvp, cr);
5457 			VN_RELE(*vpp);
5458 			*vpp = NULL;
5459 			e.error = geterrno4(res.status);
5460 			goto exit;
5461 		}
5462 
5463 		/*
5464 		 * Now we know the directory is valid,
5465 		 * cache new directory access
5466 		 */
5467 		nfs4_access_cache(drp,
5468 		    args.array[3].nfs_argop4_u.opaccess.access,
5469 		    res.array[3].nfs_resop4_u.opaccess.access, cr);
5470 
5471 		/*
5472 		 * recheck VEXEC access
5473 		 */
5474 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5475 		if (cacc != NFS4_ACCESS_ALLOWED) {
5476 			/*
5477 			 * Directory permissions might have been revoked
5478 			 */
5479 			if (cacc == NFS4_ACCESS_DENIED) {
5480 				e.error = EACCES;
5481 				VN_RELE(*vpp);
5482 				*vpp = NULL;
5483 				goto exit;
5484 			}
5485 
5486 			/*
5487 			 * Somehow we must not have asked for enough
5488 			 * so try a singleton ACCESS, should never happen.
5489 			 */
5490 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5491 			if (e.error) {
5492 				VN_RELE(*vpp);
5493 				*vpp = NULL;
5494 				goto exit;
5495 			}
5496 		}
5497 
5498 		e.error = geterrno4(res.status);
5499 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5500 			/*
5501 			 * The lookup failed, probably no entry
5502 			 */
5503 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5504 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5505 			} else {
5506 				/*
5507 				 * Might be some other error, so remove
5508 				 * the dnlc entry to make sure we start all
5509 				 * over again, next time.
5510 				 */
5511 				dnlc_remove(dvp, nm);
5512 			}
5513 			VN_RELE(*vpp);
5514 			*vpp = NULL;
5515 			goto exit;
5516 		}
5517 
5518 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5519 			/*
5520 			 * The file exists but we can't get its fh for
5521 			 * some unknown reason.  Remove it from the dnlc
5522 			 * and error out to be safe.
5523 			 */
5524 			dnlc_remove(dvp, nm);
5525 			VN_RELE(*vpp);
5526 			*vpp = NULL;
5527 			goto exit;
5528 		}
5529 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5530 		if (fhp->nfs_fh4_len == 0) {
5531 			/*
5532 			 * The file exists but a bogus fh
5533 			 * some unknown reason.  Remove it from the dnlc
5534 			 * and error out to be safe.
5535 			 */
5536 			e.error = ENOENT;
5537 			dnlc_remove(dvp, nm);
5538 			VN_RELE(*vpp);
5539 			*vpp = NULL;
5540 			goto exit;
5541 		}
5542 		sfhp = sfh4_get(fhp, mi);
5543 
5544 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5545 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5546 
5547 		/*
5548 		 * Make the new rnode
5549 		 */
5550 		if (isdotdot) {
5551 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5552 			if (e.error) {
5553 				sfh4_rele(&sfhp);
5554 				VN_RELE(*vpp);
5555 				*vpp = NULL;
5556 				goto exit;
5557 			}
5558 			/*
5559 			 * XXX if nfs4_make_dotdot uses an existing rnode
5560 			 * XXX it doesn't update the attributes.
5561 			 * XXX for now just save them again to save an OTW
5562 			 */
5563 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5564 		} else {
5565 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5566 			    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
5567 			/*
5568 			 * If v_type == VNON, then garp was NULL because
5569 			 * the last op in the compound failed and makenfs4node
5570 			 * could not find the vnode for sfhp. It created
5571 			 * a new vnode, so we have nothing to purge here.
5572 			 */
5573 			if (nvp->v_type == VNON) {
5574 				vattr_t vattr;
5575 
5576 				vattr.va_mask = AT_TYPE;
5577 				/*
5578 				 * N.B. We've already called nfs4_end_fop above.
5579 				 */
5580 				e.error = nfs4getattr(nvp, &vattr, cr);
5581 				if (e.error) {
5582 					sfh4_rele(&sfhp);
5583 					VN_RELE(*vpp);
5584 					*vpp = NULL;
5585 					VN_RELE(nvp);
5586 					goto exit;
5587 				}
5588 				nvp->v_type = vattr.va_type;
5589 			}
5590 		}
5591 		sfh4_rele(&sfhp);
5592 
5593 		nrp = VTOR4(nvp);
5594 		mutex_enter(&nrp->r_statev4_lock);
5595 		if (!nrp->created_v4) {
5596 			mutex_exit(&nrp->r_statev4_lock);
5597 			dnlc_update(dvp, nm, nvp);
5598 		} else
5599 			mutex_exit(&nrp->r_statev4_lock);
5600 
5601 		VN_RELE(*vpp);
5602 		*vpp = nvp;
5603 	} else {
5604 		hrtime_t now;
5605 		hrtime_t delta = 0;
5606 
5607 		e.error = 0;
5608 
5609 		/*
5610 		 * Because the NVERIFY "succeeded" we know that the
5611 		 * directory attributes are still valid
5612 		 * so update r_time_attr_inval
5613 		 */
5614 		now = gethrtime();
5615 		mutex_enter(&drp->r_statelock);
5616 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5617 			delta = now - drp->r_time_attr_saved;
5618 			if (delta < mi->mi_acdirmin)
5619 				delta = mi->mi_acdirmin;
5620 			else if (delta > mi->mi_acdirmax)
5621 				delta = mi->mi_acdirmax;
5622 		}
5623 		drp->r_time_attr_inval = now + delta;
5624 		mutex_exit(&drp->r_statelock);
5625 		dnlc_update(dvp, nm, *vpp);
5626 
5627 		/*
5628 		 * Even though we have a valid directory attr cache
5629 		 * and dnlc entry, we may not have access.
5630 		 * This should almost always hit the cache.
5631 		 */
5632 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5633 		if (e.error) {
5634 			VN_RELE(*vpp);
5635 			*vpp = NULL;
5636 		}
5637 
5638 		if (*vpp == DNLC_NO_VNODE) {
5639 			VN_RELE(*vpp);
5640 			*vpp = NULL;
5641 			e.error = ENOENT;
5642 		}
5643 	}
5644 
5645 exit:
5646 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5647 	kmem_free(argop, argoplist_size);
5648 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5649 	return (e.error);
5650 }
5651 
5652 /*
5653  * We need to go over the wire to lookup the name, but
5654  * while we are there verify the directory has not
5655  * changed but if it has, get new attributes and check access
5656  *
5657  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5658  *					NVERIFY GETATTR ACCESS
5659  *
5660  * With the results:
5661  *	if the NVERIFY failed we must purge the caches, add new attributes,
5662  *		and cache new access.
5663  *	set a new r_time_attr_inval
5664  *	add name to dnlc, possibly negative
5665  *	if LOOKUP succeeded
5666  *		cache new attributes
5667  */
5668 static int
5669 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5670 {
5671 	COMPOUND4args_clnt args;
5672 	COMPOUND4res_clnt res;
5673 	fattr4 *ver_fattr;
5674 	fattr4_change dchange;
5675 	int32_t *ptr;
5676 	nfs4_ga_res_t *garp = NULL;
5677 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5678 	nfs_argop4 *argop;
5679 	int doqueue;
5680 	mntinfo4_t *mi;
5681 	nfs4_recov_state_t recov_state;
5682 	hrtime_t t;
5683 	int isdotdot;
5684 	vnode_t *nvp;
5685 	nfs_fh4 *fhp;
5686 	nfs4_sharedfh_t *sfhp;
5687 	nfs4_access_type_t cacc;
5688 	rnode4_t *nrp;
5689 	rnode4_t *drp = VTOR4(dvp);
5690 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5691 
5692 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5693 	ASSERT(nm != NULL);
5694 	ASSERT(nm[0] != '\0');
5695 	ASSERT(dvp->v_type == VDIR);
5696 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5697 	ASSERT(*vpp == NULL);
5698 
5699 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5700 		isdotdot = 1;
5701 		args.ctag = TAG_LOOKUP_PARENT;
5702 	} else {
5703 		/*
5704 		 * If dvp were a stub, it should have triggered and caused
5705 		 * a mount for us to get this far.
5706 		 */
5707 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5708 
5709 		isdotdot = 0;
5710 		args.ctag = TAG_LOOKUP;
5711 	}
5712 
5713 	mi = VTOMI4(dvp);
5714 	recov_state.rs_flags = 0;
5715 	recov_state.rs_num_retry_despite_err = 0;
5716 
5717 	nvp = NULL;
5718 
5719 	/* Save the original mount point security information */
5720 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5721 
5722 recov_retry:
5723 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5724 	    &recov_state, NULL);
5725 	if (e.error) {
5726 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5727 		return (e.error);
5728 	}
5729 
5730 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5731 
5732 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5733 	args.array_len = 9;
5734 	args.array = argop;
5735 
5736 	/* 0. putfh file */
5737 	argop[0].argop = OP_CPUTFH;
5738 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5739 
5740 	/* 1. savefh for the nverify */
5741 	argop[1].argop = OP_SAVEFH;
5742 
5743 	/* 2. lookup name */
5744 	if (isdotdot) {
5745 		argop[2].argop = OP_LOOKUPP;
5746 	} else {
5747 		argop[2].argop = OP_CLOOKUP;
5748 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5749 	}
5750 
5751 	/* 3. resulting file handle */
5752 	argop[3].argop = OP_GETFH;
5753 
5754 	/* 4. resulting file attributes */
5755 	argop[4].argop = OP_GETATTR;
5756 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5757 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5758 
5759 	/* 5. restorefh back the directory for the nverify */
5760 	argop[5].argop = OP_RESTOREFH;
5761 
5762 	/* 6. nverify the change info */
5763 	argop[6].argop = OP_NVERIFY;
5764 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5765 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5766 	ver_fattr->attrlist4 = (char *)&dchange;
5767 	ptr = (int32_t *)&dchange;
5768 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5769 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5770 
5771 	/* 7. getattr directory */
5772 	argop[7].argop = OP_GETATTR;
5773 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5774 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5775 
5776 	/* 8. access directory */
5777 	argop[8].argop = OP_ACCESS;
5778 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5779 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5780 
5781 	doqueue = 1;
5782 	t = gethrtime();
5783 
5784 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5785 
5786 	if (!isdotdot && res.status == NFS4ERR_MOVED) {
5787 		e.error = nfs4_setup_referral(dvp, nm, vpp, cr);
5788 		if (e.error != 0 && *vpp != NULL)
5789 			VN_RELE(*vpp);
5790 		nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5791 		    &recov_state, FALSE);
5792 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5793 		kmem_free(argop, argoplist_size);
5794 		return (e.error);
5795 	}
5796 
5797 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5798 		/*
5799 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5800 		 * from this thread, do not go thru the recovery thread since
5801 		 * we need the nm information.
5802 		 *
5803 		 * Not doing dotdot case because there is no specification
5804 		 * for (PUTFH, SECINFO "..") yet.
5805 		 */
5806 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5807 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5808 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5809 				    &recov_state, FALSE);
5810 			else
5811 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5812 				    &recov_state, TRUE);
5813 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5814 			kmem_free(argop, argoplist_size);
5815 			if (!e.error)
5816 				goto recov_retry;
5817 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5818 			return (e.error);
5819 		}
5820 
5821 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5822 		    OP_LOOKUP, NULL, NULL, NULL) == FALSE) {
5823 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5824 			    &recov_state, TRUE);
5825 
5826 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5827 			kmem_free(argop, argoplist_size);
5828 			goto recov_retry;
5829 		}
5830 	}
5831 
5832 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5833 
5834 	if (e.error || res.array_len == 0) {
5835 		/*
5836 		 * If e.error isn't set, then reply has no ops (or we couldn't
5837 		 * be here).  The only legal way to reply without an op array
5838 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5839 		 * be in the reply for all other status values.
5840 		 *
5841 		 * For valid replies without an ops array, return ENOTSUP
5842 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5843 		 * return EIO -- don't trust status.
5844 		 */
5845 		if (e.error == 0)
5846 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5847 			    ENOTSUP : EIO;
5848 
5849 		kmem_free(argop, argoplist_size);
5850 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5851 		return (e.error);
5852 	}
5853 
5854 	e.error = geterrno4(res.status);
5855 
5856 	/*
5857 	 * The PUTFH and SAVEFH may have failed.
5858 	 */
5859 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5860 	    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5861 		nfs4_purge_stale_fh(e.error, dvp, cr);
5862 		goto exit;
5863 	}
5864 
5865 	/*
5866 	 * Check if the file exists, if it does delay entering
5867 	 * into the dnlc until after we update the directory
5868 	 * attributes so we don't cause it to get purged immediately.
5869 	 */
5870 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5871 		/*
5872 		 * The lookup failed, probably no entry
5873 		 */
5874 		if (e.error == ENOENT && nfs4_lookup_neg_cache)
5875 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5876 		goto exit;
5877 	}
5878 
5879 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5880 		/*
5881 		 * The file exists but we can't get its fh for
5882 		 * some unknown reason. Error out to be safe.
5883 		 */
5884 		goto exit;
5885 	}
5886 
5887 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5888 	if (fhp->nfs_fh4_len == 0) {
5889 		/*
5890 		 * The file exists but a bogus fh
5891 		 * some unknown reason.  Error out to be safe.
5892 		 */
5893 		e.error = EIO;
5894 		goto exit;
5895 	}
5896 	sfhp = sfh4_get(fhp, mi);
5897 
5898 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5899 		sfh4_rele(&sfhp);
5900 		goto exit;
5901 	}
5902 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5903 
5904 	/*
5905 	 * The RESTOREFH may have failed
5906 	 */
5907 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5908 		sfh4_rele(&sfhp);
5909 		e.error = EIO;
5910 		goto exit;
5911 	}
5912 
5913 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5914 		/*
5915 		 * First make sure the NVERIFY failed as we expected,
5916 		 * if it didn't then be conservative and error out
5917 		 * as we can't trust the directory.
5918 		 */
5919 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5920 			sfh4_rele(&sfhp);
5921 			e.error = EIO;
5922 			goto exit;
5923 		}
5924 
5925 		/*
5926 		 * We know the NVERIFY "failed" so the directory has changed,
5927 		 * so we must:
5928 		 *	purge the caches (access and indirectly dnlc if needed)
5929 		 */
5930 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5931 
5932 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5933 			sfh4_rele(&sfhp);
5934 			goto exit;
5935 		}
5936 		nfs4_attr_cache(dvp,
5937 		    &res.array[7].nfs_resop4_u.opgetattr.ga_res,
5938 		    t, cr, FALSE, NULL);
5939 
5940 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5941 			nfs4_purge_stale_fh(e.error, dvp, cr);
5942 			sfh4_rele(&sfhp);
5943 			e.error = geterrno4(res.status);
5944 			goto exit;
5945 		}
5946 
5947 		/*
5948 		 * Now we know the directory is valid,
5949 		 * cache new directory access
5950 		 */
5951 		nfs4_access_cache(drp,
5952 		    args.array[8].nfs_argop4_u.opaccess.access,
5953 		    res.array[8].nfs_resop4_u.opaccess.access, cr);
5954 
5955 		/*
5956 		 * recheck VEXEC access
5957 		 */
5958 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5959 		if (cacc != NFS4_ACCESS_ALLOWED) {
5960 			/*
5961 			 * Directory permissions might have been revoked
5962 			 */
5963 			if (cacc == NFS4_ACCESS_DENIED) {
5964 				sfh4_rele(&sfhp);
5965 				e.error = EACCES;
5966 				goto exit;
5967 			}
5968 
5969 			/*
5970 			 * Somehow we must not have asked for enough
5971 			 * so try a singleton ACCESS should never happen
5972 			 */
5973 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5974 			if (e.error) {
5975 				sfh4_rele(&sfhp);
5976 				goto exit;
5977 			}
5978 		}
5979 
5980 		e.error = geterrno4(res.status);
5981 	} else {
5982 		hrtime_t now;
5983 		hrtime_t delta = 0;
5984 
5985 		e.error = 0;
5986 
5987 		/*
5988 		 * Because the NVERIFY "succeeded" we know that the
5989 		 * directory attributes are still valid
5990 		 * so update r_time_attr_inval
5991 		 */
5992 		now = gethrtime();
5993 		mutex_enter(&drp->r_statelock);
5994 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5995 			delta = now - drp->r_time_attr_saved;
5996 			if (delta < mi->mi_acdirmin)
5997 				delta = mi->mi_acdirmin;
5998 			else if (delta > mi->mi_acdirmax)
5999 				delta = mi->mi_acdirmax;
6000 		}
6001 		drp->r_time_attr_inval = now + delta;
6002 		mutex_exit(&drp->r_statelock);
6003 
6004 		/*
6005 		 * Even though we have a valid directory attr cache,
6006 		 * we may not have access.
6007 		 * This should almost always hit the cache.
6008 		 */
6009 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
6010 		if (e.error) {
6011 			sfh4_rele(&sfhp);
6012 			goto exit;
6013 		}
6014 	}
6015 
6016 	/*
6017 	 * Now we have successfully completed the lookup, if the
6018 	 * directory has changed we now have the valid attributes.
6019 	 * We also know we have directory access.
6020 	 * Create the new rnode and insert it in the dnlc.
6021 	 */
6022 	if (isdotdot) {
6023 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
6024 		if (e.error) {
6025 			sfh4_rele(&sfhp);
6026 			goto exit;
6027 		}
6028 		/*
6029 		 * XXX if nfs4_make_dotdot uses an existing rnode
6030 		 * XXX it doesn't update the attributes.
6031 		 * XXX for now just save them again to save an OTW
6032 		 */
6033 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
6034 	} else {
6035 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
6036 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
6037 	}
6038 	sfh4_rele(&sfhp);
6039 
6040 	nrp = VTOR4(nvp);
6041 	mutex_enter(&nrp->r_statev4_lock);
6042 	if (!nrp->created_v4) {
6043 		mutex_exit(&nrp->r_statev4_lock);
6044 		dnlc_update(dvp, nm, nvp);
6045 	} else
6046 		mutex_exit(&nrp->r_statev4_lock);
6047 
6048 	*vpp = nvp;
6049 
6050 exit:
6051 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6052 	kmem_free(argop, argoplist_size);
6053 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
6054 	return (e.error);
6055 }
6056 
6057 #ifdef DEBUG
6058 void
6059 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
6060 {
6061 	uint_t i, len;
6062 	zoneid_t zoneid = getzoneid();
6063 	char *s;
6064 
6065 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
6066 	for (i = 0; i < argcnt; i++) {
6067 		nfs_argop4 *op = &argbase[i];
6068 		switch (op->argop) {
6069 		case OP_CPUTFH:
6070 		case OP_PUTFH:
6071 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
6072 			break;
6073 		case OP_PUTROOTFH:
6074 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
6075 			break;
6076 		case OP_CLOOKUP:
6077 			s = op->nfs_argop4_u.opclookup.cname;
6078 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6079 			break;
6080 		case OP_LOOKUP:
6081 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
6082 			    &len, NULL);
6083 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6084 			kmem_free(s, len);
6085 			break;
6086 		case OP_LOOKUPP:
6087 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
6088 			break;
6089 		case OP_GETFH:
6090 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
6091 			break;
6092 		case OP_GETATTR:
6093 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
6094 			break;
6095 		case OP_OPENATTR:
6096 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
6097 			break;
6098 		default:
6099 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
6100 			    op->argop);
6101 			break;
6102 		}
6103 	}
6104 }
6105 #endif
6106 
6107 /*
6108  * nfs4lookup_setup - constructs a multi-lookup compound request.
6109  *
6110  * Given the path "nm1/nm2/.../nmn", the following compound requests
6111  * may be created:
6112  *
6113  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
6114  * is faster, for now.
6115  *
6116  * l4_getattrs indicates the type of compound requested.
6117  *
6118  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
6119  *
6120  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
6121  *
6122  *   total number of ops is n + 1.
6123  *
6124  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
6125  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
6126  *      before the last component, and only get attributes
6127  *      for the last component.  Note that the second-to-last
6128  *	pathname component is XATTR_RPATH, which does NOT go
6129  *	over-the-wire as a lookup.
6130  *
6131  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
6132  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
6133  *
6134  *   and total number of ops is n + 5.
6135  *
6136  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
6137  *      attribute directory: create lookups plus an OPENATTR
6138  *	replacing the last lookup.  Note that the last pathname
6139  *	component is XATTR_RPATH, which does NOT go over-the-wire
6140  *	as a lookup.
6141  *
6142  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
6143  *		Openattr; Getfh; Getattr }
6144  *
6145  *   and total number of ops is n + 5.
6146  *
6147  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6148  *	nodes too.
6149  *
6150  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6151  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6152  *
6153  *   and total number of ops is 3*n + 1.
6154  *
6155  * All cases: returns the index in the arg array of the final LOOKUP op, or
6156  * -1 if no LOOKUPs were used.
6157  */
6158 int
6159 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6160 {
6161 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6162 	nfs_argop4 *argbase, *argop;
6163 	int arglen, argcnt;
6164 	int n = 1;	/* number of components */
6165 	int nga = 1;	/* number of Getattr's in request */
6166 	char c = '\0', *s, *p;
6167 	int lookup_idx = -1;
6168 	int argoplist_size;
6169 
6170 	/* set lookuparg response result to 0 */
6171 	lookupargp->resp->status = NFS4_OK;
6172 
6173 	/* skip leading "/" or "." e.g. ".//./" if there is */
6174 	for (; ; nm++) {
6175 		if (*nm != '/' && *nm != '.')
6176 			break;
6177 
6178 		/* ".." is counted as 1 component */
6179 		if (*nm == '.' && *(nm + 1) != '/')
6180 			break;
6181 	}
6182 
6183 	/*
6184 	 * Find n = number of components - nm must be null terminated
6185 	 * Skip "." components.
6186 	 */
6187 	if (*nm != '\0')
6188 		for (n = 1, s = nm; *s != '\0'; s++) {
6189 			if ((*s == '/') && (*(s + 1) != '/') &&
6190 			    (*(s + 1) != '\0') &&
6191 			    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6192 			    *(s + 2) == '\0')))
6193 				n++;
6194 		}
6195 	else
6196 		n = 0;
6197 
6198 	/*
6199 	 * nga is number of components that need Getfh+Getattr
6200 	 */
6201 	switch (l4_getattrs) {
6202 	case LKP4_NO_ATTRIBUTES:
6203 		nga = 0;
6204 		break;
6205 	case LKP4_ALL_ATTRIBUTES:
6206 		nga = n;
6207 		/*
6208 		 * Always have at least 1 getfh, getattr pair
6209 		 */
6210 		if (nga == 0)
6211 			nga++;
6212 		break;
6213 	case LKP4_LAST_ATTRDIR:
6214 	case LKP4_LAST_NAMED_ATTR:
6215 		nga = n+1;
6216 		break;
6217 	}
6218 
6219 	/*
6220 	 * If change to use the filehandle attr instead of getfh
6221 	 * the following line can be deleted.
6222 	 */
6223 	nga *= 2;
6224 
6225 	/*
6226 	 * calculate number of ops in request as
6227 	 * header + trailer + lookups + getattrs
6228 	 */
6229 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6230 
6231 	argoplist_size = arglen * sizeof (nfs_argop4);
6232 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6233 	lookupargp->argsp->array = argop;
6234 
6235 	argcnt = lookupargp->header_len;
6236 	argop += argcnt;
6237 
6238 	/*
6239 	 * loop and create a lookup op and possibly getattr/getfh for
6240 	 * each component. Skip "." components.
6241 	 */
6242 	for (s = nm; *s != '\0'; s = p) {
6243 		/*
6244 		 * Set up a pathname struct for each component if needed
6245 		 */
6246 		while (*s == '/')
6247 			s++;
6248 		if (*s == '\0')
6249 			break;
6250 
6251 		for (p = s; (*p != '/') && (*p != '\0'); p++)
6252 			;
6253 		c = *p;
6254 		*p = '\0';
6255 
6256 		if (s[0] == '.' && s[1] == '\0') {
6257 			*p = c;
6258 			continue;
6259 		}
6260 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6261 		    strcmp(s, XATTR_RPATH) == 0) {
6262 			/* getfh XXX may not be needed in future */
6263 			argop->argop = OP_GETFH;
6264 			argop++;
6265 			argcnt++;
6266 
6267 			/* getattr */
6268 			argop->argop = OP_GETATTR;
6269 			argop->nfs_argop4_u.opgetattr.attr_request =
6270 			    lookupargp->ga_bits;
6271 			argop->nfs_argop4_u.opgetattr.mi =
6272 			    lookupargp->mi;
6273 			argop++;
6274 			argcnt++;
6275 
6276 			/* openattr */
6277 			argop->argop = OP_OPENATTR;
6278 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6279 		    strcmp(s, XATTR_RPATH) == 0) {
6280 			/* openattr */
6281 			argop->argop = OP_OPENATTR;
6282 			argop++;
6283 			argcnt++;
6284 
6285 			/* getfh XXX may not be needed in future */
6286 			argop->argop = OP_GETFH;
6287 			argop++;
6288 			argcnt++;
6289 
6290 			/* getattr */
6291 			argop->argop = OP_GETATTR;
6292 			argop->nfs_argop4_u.opgetattr.attr_request =
6293 			    lookupargp->ga_bits;
6294 			argop->nfs_argop4_u.opgetattr.mi =
6295 			    lookupargp->mi;
6296 			argop++;
6297 			argcnt++;
6298 			*p = c;
6299 			continue;
6300 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6301 			/* lookupp */
6302 			argop->argop = OP_LOOKUPP;
6303 		} else {
6304 			/* lookup */
6305 			argop->argop = OP_LOOKUP;
6306 			(void) str_to_utf8(s,
6307 			    &argop->nfs_argop4_u.oplookup.objname);
6308 		}
6309 		lookup_idx = argcnt;
6310 		argop++;
6311 		argcnt++;
6312 
6313 		*p = c;
6314 
6315 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6316 			/* getfh XXX may not be needed in future */
6317 			argop->argop = OP_GETFH;
6318 			argop++;
6319 			argcnt++;
6320 
6321 			/* getattr */
6322 			argop->argop = OP_GETATTR;
6323 			argop->nfs_argop4_u.opgetattr.attr_request =
6324 			    lookupargp->ga_bits;
6325 			argop->nfs_argop4_u.opgetattr.mi =
6326 			    lookupargp->mi;
6327 			argop++;
6328 			argcnt++;
6329 		}
6330 	}
6331 
6332 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6333 	    ((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6334 		if (needgetfh) {
6335 			/* stick in a post-lookup getfh */
6336 			argop->argop = OP_GETFH;
6337 			argcnt++;
6338 			argop++;
6339 		}
6340 		/* post-lookup getattr */
6341 		argop->argop = OP_GETATTR;
6342 		argop->nfs_argop4_u.opgetattr.attr_request =
6343 		    lookupargp->ga_bits;
6344 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6345 		argcnt++;
6346 	}
6347 	argcnt += lookupargp->trailer_len;	/* actual op count */
6348 	lookupargp->argsp->array_len = argcnt;
6349 	lookupargp->arglen = arglen;
6350 
6351 #ifdef DEBUG
6352 	if (nfs4_client_lookup_debug)
6353 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6354 #endif
6355 
6356 	return (lookup_idx);
6357 }
6358 
6359 static int
6360 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6361 {
6362 	COMPOUND4args_clnt	args;
6363 	COMPOUND4res_clnt	res;
6364 	GETFH4res	*gf_res = NULL;
6365 	nfs_argop4	argop[4];
6366 	nfs_resop4	*resop = NULL;
6367 	nfs4_sharedfh_t *sfhp;
6368 	hrtime_t t;
6369 	nfs4_error_t	e;
6370 
6371 	rnode4_t	*drp;
6372 	int		doqueue = 1;
6373 	vnode_t		*vp;
6374 	int		needrecov = 0;
6375 	nfs4_recov_state_t recov_state;
6376 
6377 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6378 
6379 	*avp = NULL;
6380 	recov_state.rs_flags = 0;
6381 	recov_state.rs_num_retry_despite_err = 0;
6382 
6383 recov_retry:
6384 	/* COMPOUND: putfh, openattr, getfh, getattr */
6385 	args.array_len = 4;
6386 	args.array = argop;
6387 	args.ctag = TAG_OPENATTR;
6388 
6389 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6390 	if (e.error)
6391 		return (e.error);
6392 
6393 	drp = VTOR4(dvp);
6394 
6395 	/* putfh */
6396 	argop[0].argop = OP_CPUTFH;
6397 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6398 
6399 	/* openattr */
6400 	argop[1].argop = OP_OPENATTR;
6401 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6402 
6403 	/* getfh */
6404 	argop[2].argop = OP_GETFH;
6405 
6406 	/* getattr */
6407 	argop[3].argop = OP_GETATTR;
6408 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6409 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6410 
6411 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6412 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6413 	    rnode4info(drp)));
6414 
6415 	t = gethrtime();
6416 
6417 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6418 
6419 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6420 	if (needrecov) {
6421 		bool_t abort;
6422 
6423 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6424 		    "nfs4openattr: initiating recovery\n"));
6425 
6426 		abort = nfs4_start_recovery(&e,
6427 		    VTOMI4(dvp), dvp, NULL, NULL, NULL,
6428 		    OP_OPENATTR, NULL, NULL, NULL);
6429 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6430 		if (!e.error) {
6431 			e.error = geterrno4(res.status);
6432 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6433 		}
6434 		if (abort == FALSE)
6435 			goto recov_retry;
6436 		return (e.error);
6437 	}
6438 
6439 	if (e.error) {
6440 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6441 		return (e.error);
6442 	}
6443 
6444 	if (res.status) {
6445 		/*
6446 		 * If OTW errro is NOTSUPP, then it should be
6447 		 * translated to EINVAL.  All Solaris file system
6448 		 * implementations return EINVAL to the syscall layer
6449 		 * when the attrdir cannot be created due to an
6450 		 * implementation restriction or noxattr mount option.
6451 		 */
6452 		if (res.status == NFS4ERR_NOTSUPP) {
6453 			mutex_enter(&drp->r_statelock);
6454 			if (drp->r_xattr_dir)
6455 				VN_RELE(drp->r_xattr_dir);
6456 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6457 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6458 			mutex_exit(&drp->r_statelock);
6459 
6460 			e.error = EINVAL;
6461 		} else {
6462 			e.error = geterrno4(res.status);
6463 		}
6464 
6465 		if (e.error) {
6466 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6467 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6468 			    needrecov);
6469 			return (e.error);
6470 		}
6471 	}
6472 
6473 	resop = &res.array[0];  /* putfh res */
6474 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6475 
6476 	resop = &res.array[1];  /* openattr res */
6477 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6478 
6479 	resop = &res.array[2];  /* getfh res */
6480 	gf_res = &resop->nfs_resop4_u.opgetfh;
6481 	if (gf_res->object.nfs_fh4_len == 0) {
6482 		*avp = NULL;
6483 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6484 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6485 		return (ENOENT);
6486 	}
6487 
6488 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6489 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6490 	    dvp->v_vfsp, t, cr, dvp,
6491 	    fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH, sfhp));
6492 	sfh4_rele(&sfhp);
6493 
6494 	if (e.error)
6495 		PURGE_ATTRCACHE4(vp);
6496 
6497 	mutex_enter(&vp->v_lock);
6498 	vp->v_flag |= V_XATTRDIR;
6499 	mutex_exit(&vp->v_lock);
6500 
6501 	*avp = vp;
6502 
6503 	mutex_enter(&drp->r_statelock);
6504 	if (drp->r_xattr_dir)
6505 		VN_RELE(drp->r_xattr_dir);
6506 	VN_HOLD(vp);
6507 	drp->r_xattr_dir = vp;
6508 
6509 	/*
6510 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6511 	 * NULL.  xattrs could be created at any time, and we have no
6512 	 * way to update pc4_xattr_exists in the base object if/when
6513 	 * it happens.
6514 	 */
6515 	drp->r_pathconf.pc4_xattr_valid = 0;
6516 
6517 	mutex_exit(&drp->r_statelock);
6518 
6519 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6520 
6521 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6522 
6523 	return (0);
6524 }
6525 
6526 /* ARGSUSED */
6527 static int
6528 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6529     int mode, vnode_t **vpp, cred_t *cr, int flags, caller_context_t *ct,
6530     vsecattr_t *vsecp)
6531 {
6532 	int error;
6533 	vnode_t *vp = NULL;
6534 	rnode4_t *rp;
6535 	struct vattr vattr;
6536 	rnode4_t *drp;
6537 	vnode_t *tempvp;
6538 	enum createmode4 createmode;
6539 	bool_t must_trunc = FALSE;
6540 	int	truncating = 0;
6541 
6542 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6543 		return (EPERM);
6544 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6545 		return (EINVAL);
6546 	}
6547 
6548 	/* . and .. have special meaning in the protocol, reject them. */
6549 
6550 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6551 		return (EISDIR);
6552 
6553 	drp = VTOR4(dvp);
6554 
6555 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6556 		return (EINTR);
6557 
6558 top:
6559 	/*
6560 	 * We make a copy of the attributes because the caller does not
6561 	 * expect us to change what va points to.
6562 	 */
6563 	vattr = *va;
6564 
6565 	/*
6566 	 * If the pathname is "", then dvp is the root vnode of
6567 	 * a remote file mounted over a local directory.
6568 	 * All that needs to be done is access
6569 	 * checking and truncation.  Note that we avoid doing
6570 	 * open w/ create because the parent directory might
6571 	 * be in pseudo-fs and the open would fail.
6572 	 */
6573 	if (*nm == '\0') {
6574 		error = 0;
6575 		VN_HOLD(dvp);
6576 		vp = dvp;
6577 		must_trunc = TRUE;
6578 	} else {
6579 		/*
6580 		 * We need to go over the wire, just to be sure whether the
6581 		 * file exists or not.  Using the DNLC can be dangerous in
6582 		 * this case when making a decision regarding existence.
6583 		 */
6584 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6585 	}
6586 
6587 	if (exclusive)
6588 		createmode = EXCLUSIVE4;
6589 	else
6590 		createmode = GUARDED4;
6591 
6592 	/*
6593 	 * error would be set if the file does not exist on the
6594 	 * server, so lets go create it.
6595 	 */
6596 	if (error) {
6597 		goto create_otw;
6598 	}
6599 
6600 	/*
6601 	 * File does exist on the server
6602 	 */
6603 	if (exclusive == EXCL)
6604 		error = EEXIST;
6605 	else if (vp->v_type == VDIR && (mode & VWRITE))
6606 		error = EISDIR;
6607 	else {
6608 		/*
6609 		 * If vnode is a device, create special vnode.
6610 		 */
6611 		if (ISVDEV(vp->v_type)) {
6612 			tempvp = vp;
6613 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6614 			VN_RELE(tempvp);
6615 		}
6616 		if (!(error = VOP_ACCESS(vp, mode, 0, cr, ct))) {
6617 			if ((vattr.va_mask & AT_SIZE) &&
6618 			    vp->v_type == VREG) {
6619 				rp = VTOR4(vp);
6620 				/*
6621 				 * Check here for large file handled
6622 				 * by LF-unaware process (as
6623 				 * ufs_create() does)
6624 				 */
6625 				if (!(flags & FOFFMAX)) {
6626 					mutex_enter(&rp->r_statelock);
6627 					if (rp->r_size > MAXOFF32_T)
6628 						error = EOVERFLOW;
6629 					mutex_exit(&rp->r_statelock);
6630 				}
6631 
6632 				/* if error is set then we need to return */
6633 				if (error) {
6634 					nfs_rw_exit(&drp->r_rwlock);
6635 					VN_RELE(vp);
6636 					return (error);
6637 				}
6638 
6639 				if (must_trunc) {
6640 					vattr.va_mask = AT_SIZE;
6641 					error = nfs4setattr(vp, &vattr, 0, cr,
6642 					    NULL);
6643 				} else {
6644 				/*
6645 				 * we know we have a regular file that already
6646 				 * exists and we may end up truncating the file
6647 				 * as a result of the open_otw, so flush out
6648 				 * any dirty pages for this file first.
6649 				 */
6650 					if (nfs4_has_pages(vp) &&
6651 					    ((rp->r_flags & R4DIRTY) ||
6652 					    rp->r_count > 0 ||
6653 					    rp->r_mapcnt > 0)) {
6654 						error = nfs4_putpage(vp,
6655 						    (offset_t)0, 0, 0, cr, ct);
6656 						if (error && (error == ENOSPC ||
6657 						    error == EDQUOT)) {
6658 							mutex_enter(
6659 							    &rp->r_statelock);
6660 							if (!rp->r_error)
6661 								rp->r_error =
6662 								    error;
6663 							mutex_exit(
6664 							    &rp->r_statelock);
6665 						}
6666 					}
6667 					vattr.va_mask = (AT_SIZE |
6668 					    AT_TYPE | AT_MODE);
6669 					vattr.va_type = VREG;
6670 					createmode = UNCHECKED4;
6671 					truncating = 1;
6672 					goto create_otw;
6673 				}
6674 			}
6675 		}
6676 	}
6677 	nfs_rw_exit(&drp->r_rwlock);
6678 	if (error) {
6679 		VN_RELE(vp);
6680 	} else {
6681 		vnode_t *tvp;
6682 		rnode4_t *trp;
6683 		tvp = vp;
6684 		if (vp->v_type == VREG) {
6685 			trp = VTOR4(vp);
6686 			if (IS_SHADOW(vp, trp))
6687 				tvp = RTOV4(trp);
6688 		}
6689 
6690 		if (must_trunc) {
6691 			/*
6692 			 * existing file got truncated, notify.
6693 			 */
6694 			vnevent_create(tvp, ct);
6695 		}
6696 
6697 		*vpp = vp;
6698 	}
6699 	return (error);
6700 
6701 create_otw:
6702 	dnlc_remove(dvp, nm);
6703 
6704 	ASSERT(vattr.va_mask & AT_TYPE);
6705 
6706 	/*
6707 	 * If not a regular file let nfs4mknod() handle it.
6708 	 */
6709 	if (vattr.va_type != VREG) {
6710 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6711 		nfs_rw_exit(&drp->r_rwlock);
6712 		return (error);
6713 	}
6714 
6715 	/*
6716 	 * It _is_ a regular file.
6717 	 */
6718 	ASSERT(vattr.va_mask & AT_MODE);
6719 	if (MANDMODE(vattr.va_mode)) {
6720 		nfs_rw_exit(&drp->r_rwlock);
6721 		return (EACCES);
6722 	}
6723 
6724 	/*
6725 	 * If this happens to be a mknod of a regular file, then flags will
6726 	 * have neither FREAD or FWRITE.  However, we must set at least one
6727 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6728 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6729 	 * set (based on openmode specified by app).
6730 	 */
6731 	if ((flags & (FREAD|FWRITE)) == 0)
6732 		flags |= (FREAD|FWRITE);
6733 
6734 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6735 
6736 	if (vp != NULL) {
6737 		/* if create was successful, throw away the file's pages */
6738 		if (!error && (vattr.va_mask & AT_SIZE))
6739 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6740 			    cr);
6741 		/* release the lookup hold */
6742 		VN_RELE(vp);
6743 		vp = NULL;
6744 	}
6745 
6746 	/*
6747 	 * validate that we opened a regular file. This handles a misbehaving
6748 	 * server that returns an incorrect FH.
6749 	 */
6750 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6751 		error = EISDIR;
6752 		VN_RELE(*vpp);
6753 	}
6754 
6755 	/*
6756 	 * If this is not an exclusive create, then the CREATE
6757 	 * request will be made with the GUARDED mode set.  This
6758 	 * means that the server will return EEXIST if the file
6759 	 * exists.  The file could exist because of a retransmitted
6760 	 * request.  In this case, we recover by starting over and
6761 	 * checking to see whether the file exists.  This second
6762 	 * time through it should and a CREATE request will not be
6763 	 * sent.
6764 	 *
6765 	 * This handles the problem of a dangling CREATE request
6766 	 * which contains attributes which indicate that the file
6767 	 * should be truncated.  This retransmitted request could
6768 	 * possibly truncate valid data in the file if not caught
6769 	 * by the duplicate request mechanism on the server or if
6770 	 * not caught by other means.  The scenario is:
6771 	 *
6772 	 * Client transmits CREATE request with size = 0
6773 	 * Client times out, retransmits request.
6774 	 * Response to the first request arrives from the server
6775 	 *  and the client proceeds on.
6776 	 * Client writes data to the file.
6777 	 * The server now processes retransmitted CREATE request
6778 	 *  and truncates file.
6779 	 *
6780 	 * The use of the GUARDED CREATE request prevents this from
6781 	 * happening because the retransmitted CREATE would fail
6782 	 * with EEXIST and would not truncate the file.
6783 	 */
6784 	if (error == EEXIST && exclusive == NONEXCL) {
6785 #ifdef DEBUG
6786 		nfs4_create_misses++;
6787 #endif
6788 		goto top;
6789 	}
6790 	nfs_rw_exit(&drp->r_rwlock);
6791 	if (truncating && !error && *vpp) {
6792 		vnode_t *tvp;
6793 		rnode4_t *trp;
6794 		/*
6795 		 * existing file got truncated, notify.
6796 		 */
6797 		tvp = *vpp;
6798 		trp = VTOR4(tvp);
6799 		if (IS_SHADOW(tvp, trp))
6800 			tvp = RTOV4(trp);
6801 		vnevent_create(tvp, ct);
6802 	}
6803 	return (error);
6804 }
6805 
6806 /*
6807  * Create compound (for mkdir, mknod, symlink):
6808  * { Putfh <dfh>; Create; Getfh; Getattr }
6809  * It's okay if setattr failed to set gid - this is not considered
6810  * an error, but purge attrs in that case.
6811  */
6812 static int
6813 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6814     vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6815 {
6816 	int need_end_op = FALSE;
6817 	COMPOUND4args_clnt args;
6818 	COMPOUND4res_clnt res, *resp = NULL;
6819 	nfs_argop4 *argop;
6820 	nfs_resop4 *resop;
6821 	int doqueue;
6822 	mntinfo4_t *mi;
6823 	rnode4_t *drp = VTOR4(dvp);
6824 	change_info4 *cinfo;
6825 	GETFH4res *gf_res;
6826 	struct vattr vattr;
6827 	vnode_t *vp;
6828 	fattr4 *crattr;
6829 	bool_t needrecov = FALSE;
6830 	nfs4_recov_state_t recov_state;
6831 	nfs4_sharedfh_t *sfhp = NULL;
6832 	hrtime_t t;
6833 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6834 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6835 	dirattr_info_t dinfo, *dinfop;
6836 	servinfo4_t *svp;
6837 	bitmap4 supp_attrs;
6838 
6839 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6840 	    type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6841 
6842 	mi = VTOMI4(dvp);
6843 
6844 	/*
6845 	 * Make sure we properly deal with setting the right gid
6846 	 * on a new directory to reflect the parent's setgid bit
6847 	 */
6848 	setgid_flag = 0;
6849 	if (type == NF4DIR) {
6850 		struct vattr dva;
6851 
6852 		va->va_mode &= ~VSGID;
6853 		dva.va_mask = AT_MODE | AT_GID;
6854 		if (VOP_GETATTR(dvp, &dva, 0, cr, NULL) == 0) {
6855 
6856 			/*
6857 			 * If the parent's directory has the setgid bit set
6858 			 * _and_ the client was able to get a valid mapping
6859 			 * for the parent dir's owner_group, we want to
6860 			 * append NVERIFY(owner_group == dva.va_gid) and
6861 			 * SETTATTR to the CREATE compound.
6862 			 */
6863 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6864 				setgid_flag = 1;
6865 				va->va_mode |= VSGID;
6866 				if (dva.va_gid != GID_NOBODY) {
6867 					va->va_mask |= AT_GID;
6868 					va->va_gid = dva.va_gid;
6869 				}
6870 			}
6871 		}
6872 	}
6873 
6874 	/*
6875 	 * Create ops:
6876 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6877 	 *	5:restorefh(dir) 6:getattr(dir)
6878 	 *
6879 	 * if (setgid)
6880 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6881 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6882 	 *	8:nverify 9:setattr
6883 	 */
6884 	if (setgid_flag) {
6885 		numops = 10;
6886 		idx_create = 1;
6887 		idx_fattr = 3;
6888 	} else {
6889 		numops = 7;
6890 		idx_create = 2;
6891 		idx_fattr = 4;
6892 	}
6893 
6894 	ASSERT(nfs_zone() == mi->mi_zone);
6895 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6896 		return (EINTR);
6897 	}
6898 	recov_state.rs_flags = 0;
6899 	recov_state.rs_num_retry_despite_err = 0;
6900 
6901 	argoplist_size = numops * sizeof (nfs_argop4);
6902 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6903 
6904 recov_retry:
6905 	if (type == NF4LNK)
6906 		args.ctag = TAG_SYMLINK;
6907 	else if (type == NF4DIR)
6908 		args.ctag = TAG_MKDIR;
6909 	else
6910 		args.ctag = TAG_MKNOD;
6911 
6912 	args.array_len = numops;
6913 	args.array = argop;
6914 
6915 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6916 		nfs_rw_exit(&drp->r_rwlock);
6917 		kmem_free(argop, argoplist_size);
6918 		return (e.error);
6919 	}
6920 	need_end_op = TRUE;
6921 
6922 
6923 	/* 0: putfh directory */
6924 	argop[0].argop = OP_CPUTFH;
6925 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6926 
6927 	/* 1/2: Create object */
6928 	argop[idx_create].argop = OP_CCREATE;
6929 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6930 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6931 	if (type == NF4LNK) {
6932 		/*
6933 		 * symlink, treat name as data
6934 		 */
6935 		ASSERT(data != NULL);
6936 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6937 		    (char *)data;
6938 	}
6939 	if (type == NF4BLK || type == NF4CHR) {
6940 		ASSERT(data != NULL);
6941 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6942 		    *((specdata4 *)data);
6943 	}
6944 
6945 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6946 
6947 	svp = drp->r_server;
6948 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6949 	supp_attrs = svp->sv_supp_attrs;
6950 	nfs_rw_exit(&svp->sv_lock);
6951 
6952 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6953 		nfs_rw_exit(&drp->r_rwlock);
6954 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6955 		e.error = EINVAL;
6956 		kmem_free(argop, argoplist_size);
6957 		return (e.error);
6958 	}
6959 
6960 	/* 2/3: getfh fh of created object */
6961 	ASSERT(idx_create + 1 == idx_fattr - 1);
6962 	argop[idx_create + 1].argop = OP_GETFH;
6963 
6964 	/* 3/4: getattr of new object */
6965 	argop[idx_fattr].argop = OP_GETATTR;
6966 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6967 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6968 
6969 	if (setgid_flag) {
6970 		vattr_t	_v;
6971 
6972 		argop[4].argop = OP_SAVEFH;
6973 
6974 		argop[5].argop = OP_CPUTFH;
6975 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6976 
6977 		argop[6].argop = OP_GETATTR;
6978 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6979 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6980 
6981 		argop[7].argop = OP_RESTOREFH;
6982 
6983 		/*
6984 		 * nverify
6985 		 *
6986 		 * XXX - Revisit the last argument to nfs4_end_op()
6987 		 *	 once 5020486 is fixed.
6988 		 */
6989 		_v.va_mask = AT_GID;
6990 		_v.va_gid = va->va_gid;
6991 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6992 		    supp_attrs)) {
6993 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6994 			nfs_rw_exit(&drp->r_rwlock);
6995 			nfs4_fattr4_free(crattr);
6996 			kmem_free(argop, argoplist_size);
6997 			return (e.error);
6998 		}
6999 
7000 		/*
7001 		 * setattr
7002 		 *
7003 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
7004 		 * so no need for stateid or flags. Also we specify NULL
7005 		 * rp since we're only interested in setting owner_group
7006 		 * attributes.
7007 		 */
7008 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
7009 		    &e.error, 0);
7010 
7011 		if (e.error) {
7012 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
7013 			nfs_rw_exit(&drp->r_rwlock);
7014 			nfs4_fattr4_free(crattr);
7015 			nfs4args_verify_free(&argop[8]);
7016 			kmem_free(argop, argoplist_size);
7017 			return (e.error);
7018 		}
7019 	} else {
7020 		argop[1].argop = OP_SAVEFH;
7021 
7022 		argop[5].argop = OP_RESTOREFH;
7023 
7024 		argop[6].argop = OP_GETATTR;
7025 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7026 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
7027 	}
7028 
7029 	dnlc_remove(dvp, nm);
7030 
7031 	doqueue = 1;
7032 	t = gethrtime();
7033 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7034 
7035 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7036 	if (e.error) {
7037 		PURGE_ATTRCACHE4(dvp);
7038 		if (!needrecov)
7039 			goto out;
7040 	}
7041 
7042 	if (needrecov) {
7043 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
7044 		    OP_CREATE, NULL, NULL, NULL) == FALSE) {
7045 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7046 			    needrecov);
7047 			need_end_op = FALSE;
7048 			nfs4_fattr4_free(crattr);
7049 			if (setgid_flag) {
7050 				nfs4args_verify_free(&argop[8]);
7051 				nfs4args_setattr_free(&argop[9]);
7052 			}
7053 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
7054 			goto recov_retry;
7055 		}
7056 	}
7057 
7058 	resp = &res;
7059 
7060 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
7061 
7062 		if (res.status == NFS4ERR_BADOWNER)
7063 			nfs4_log_badowner(mi, OP_CREATE);
7064 
7065 		e.error = geterrno4(res.status);
7066 
7067 		/*
7068 		 * This check is left over from when create was implemented
7069 		 * using a setattr op (instead of createattrs).  If the
7070 		 * putfh/create/getfh failed, the error was returned.  If
7071 		 * setattr/getattr failed, we keep going.
7072 		 *
7073 		 * It might be better to get rid of the GETFH also, and just
7074 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
7075 		 * Then if any of the operations failed, we could return the
7076 		 * error now, and remove much of the error code below.
7077 		 */
7078 		if (res.array_len <= idx_fattr) {
7079 			/*
7080 			 * Either Putfh, Create or Getfh failed.
7081 			 */
7082 			PURGE_ATTRCACHE4(dvp);
7083 			/*
7084 			 * nfs4_purge_stale_fh() may generate otw calls through
7085 			 * nfs4_invalidate_pages. Hence the need to call
7086 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
7087 			 */
7088 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7089 			    needrecov);
7090 			need_end_op = FALSE;
7091 			nfs4_purge_stale_fh(e.error, dvp, cr);
7092 			goto out;
7093 		}
7094 	}
7095 
7096 	resop = &res.array[idx_create];	/* create res */
7097 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
7098 
7099 	resop = &res.array[idx_create + 1]; /* getfh res */
7100 	gf_res = &resop->nfs_resop4_u.opgetfh;
7101 
7102 	sfhp = sfh4_get(&gf_res->object, mi);
7103 	if (e.error) {
7104 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
7105 		    fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7106 		if (vp->v_type == VNON) {
7107 			vattr.va_mask = AT_TYPE;
7108 			/*
7109 			 * Need to call nfs4_end_op before nfs4getattr to avoid
7110 			 * potential nfs4_start_op deadlock. See RFE 4777612.
7111 			 */
7112 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7113 			    needrecov);
7114 			need_end_op = FALSE;
7115 			e.error = nfs4getattr(vp, &vattr, cr);
7116 			if (e.error) {
7117 				VN_RELE(vp);
7118 				*vpp = NULL;
7119 				goto out;
7120 			}
7121 			vp->v_type = vattr.va_type;
7122 		}
7123 		e.error = 0;
7124 	} else {
7125 		*vpp = vp = makenfs4node(sfhp,
7126 		    &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
7127 		    dvp->v_vfsp, t, cr,
7128 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7129 	}
7130 
7131 	/*
7132 	 * If compound succeeded, then update dir attrs
7133 	 */
7134 	if (res.status == NFS4_OK) {
7135 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
7136 		dinfo.di_cred = cr;
7137 		dinfo.di_time_call = t;
7138 		dinfop = &dinfo;
7139 	} else
7140 		dinfop = NULL;
7141 
7142 	/* Update directory cache attribute, readdir and dnlc caches */
7143 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
7144 
7145 out:
7146 	if (sfhp != NULL)
7147 		sfh4_rele(&sfhp);
7148 	nfs_rw_exit(&drp->r_rwlock);
7149 	nfs4_fattr4_free(crattr);
7150 	if (setgid_flag) {
7151 		nfs4args_verify_free(&argop[8]);
7152 		nfs4args_setattr_free(&argop[9]);
7153 	}
7154 	if (resp)
7155 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7156 	if (need_end_op)
7157 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7158 
7159 	kmem_free(argop, argoplist_size);
7160 	return (e.error);
7161 }
7162 
7163 /* ARGSUSED */
7164 static int
7165 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7166     int mode, vnode_t **vpp, cred_t *cr)
7167 {
7168 	int error;
7169 	vnode_t *vp;
7170 	nfs_ftype4 type;
7171 	specdata4 spec, *specp = NULL;
7172 
7173 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7174 
7175 	switch (va->va_type) {
7176 	case VCHR:
7177 	case VBLK:
7178 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7179 		spec.specdata1 = getmajor(va->va_rdev);
7180 		spec.specdata2 = getminor(va->va_rdev);
7181 		specp = &spec;
7182 		break;
7183 
7184 	case VFIFO:
7185 		type = NF4FIFO;
7186 		break;
7187 	case VSOCK:
7188 		type = NF4SOCK;
7189 		break;
7190 
7191 	default:
7192 		return (EINVAL);
7193 	}
7194 
7195 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7196 	if (error) {
7197 		return (error);
7198 	}
7199 
7200 	/*
7201 	 * This might not be needed any more; special case to deal
7202 	 * with problematic v2/v3 servers.  Since create was unable
7203 	 * to set group correctly, not sure what hope setattr has.
7204 	 */
7205 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7206 		va->va_mask = AT_GID;
7207 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7208 	}
7209 
7210 	/*
7211 	 * If vnode is a device create special vnode
7212 	 */
7213 	if (ISVDEV(vp->v_type)) {
7214 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7215 		VN_RELE(vp);
7216 	} else {
7217 		*vpp = vp;
7218 	}
7219 	return (error);
7220 }
7221 
7222 /*
7223  * Remove requires that the current fh be the target directory.
7224  * After the operation, the current fh is unchanged.
7225  * The compound op structure is:
7226  *      PUTFH(targetdir), REMOVE
7227  *
7228  * Weirdness: if the vnode to be removed is open
7229  * we rename it instead of removing it and nfs_inactive
7230  * will remove the new name.
7231  */
7232 /* ARGSUSED */
7233 static int
7234 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr, caller_context_t *ct, int flags)
7235 {
7236 	COMPOUND4args_clnt args;
7237 	COMPOUND4res_clnt res, *resp = NULL;
7238 	REMOVE4res *rm_res;
7239 	nfs_argop4 argop[3];
7240 	nfs_resop4 *resop;
7241 	vnode_t *vp;
7242 	char *tmpname;
7243 	int doqueue;
7244 	mntinfo4_t *mi;
7245 	rnode4_t *rp;
7246 	rnode4_t *drp;
7247 	int needrecov = 0;
7248 	nfs4_recov_state_t recov_state;
7249 	int isopen;
7250 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7251 	dirattr_info_t dinfo;
7252 
7253 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7254 		return (EPERM);
7255 	drp = VTOR4(dvp);
7256 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7257 		return (EINTR);
7258 
7259 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7260 	if (e.error) {
7261 		nfs_rw_exit(&drp->r_rwlock);
7262 		return (e.error);
7263 	}
7264 
7265 	if (vp->v_type == VDIR) {
7266 		VN_RELE(vp);
7267 		nfs_rw_exit(&drp->r_rwlock);
7268 		return (EISDIR);
7269 	}
7270 
7271 	/*
7272 	 * First just remove the entry from the name cache, as it
7273 	 * is most likely the only entry for this vp.
7274 	 */
7275 	dnlc_remove(dvp, nm);
7276 
7277 	rp = VTOR4(vp);
7278 
7279 	/*
7280 	 * For regular file types, check to see if the file is open by looking
7281 	 * at the open streams.
7282 	 * For all other types, check the reference count on the vnode.  Since
7283 	 * they are not opened OTW they never have an open stream.
7284 	 *
7285 	 * If the file is open, rename it to .nfsXXXX.
7286 	 */
7287 	if (vp->v_type != VREG) {
7288 		/*
7289 		 * If the file has a v_count > 1 then there may be more than one
7290 		 * entry in the name cache due multiple links or an open file,
7291 		 * but we don't have the real reference count so flush all
7292 		 * possible entries.
7293 		 */
7294 		if (vp->v_count > 1)
7295 			dnlc_purge_vp(vp);
7296 
7297 		/*
7298 		 * Now we have the real reference count.
7299 		 */
7300 		isopen = vp->v_count > 1;
7301 	} else {
7302 		mutex_enter(&rp->r_os_lock);
7303 		isopen = list_head(&rp->r_open_streams) != NULL;
7304 		mutex_exit(&rp->r_os_lock);
7305 	}
7306 
7307 	mutex_enter(&rp->r_statelock);
7308 	if (isopen &&
7309 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7310 		mutex_exit(&rp->r_statelock);
7311 		tmpname = newname();
7312 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr, ct);
7313 		if (e.error)
7314 			kmem_free(tmpname, MAXNAMELEN);
7315 		else {
7316 			mutex_enter(&rp->r_statelock);
7317 			if (rp->r_unldvp == NULL) {
7318 				VN_HOLD(dvp);
7319 				rp->r_unldvp = dvp;
7320 				if (rp->r_unlcred != NULL)
7321 					crfree(rp->r_unlcred);
7322 				crhold(cr);
7323 				rp->r_unlcred = cr;
7324 				rp->r_unlname = tmpname;
7325 			} else {
7326 				kmem_free(rp->r_unlname, MAXNAMELEN);
7327 				rp->r_unlname = tmpname;
7328 			}
7329 			mutex_exit(&rp->r_statelock);
7330 		}
7331 		VN_RELE(vp);
7332 		nfs_rw_exit(&drp->r_rwlock);
7333 		return (e.error);
7334 	}
7335 	/*
7336 	 * Actually remove the file/dir
7337 	 */
7338 	mutex_exit(&rp->r_statelock);
7339 
7340 	/*
7341 	 * We need to flush any dirty pages which happen to
7342 	 * be hanging around before removing the file.
7343 	 * This shouldn't happen very often since in NFSv4
7344 	 * we should be close to open consistent.
7345 	 */
7346 	if (nfs4_has_pages(vp) &&
7347 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7348 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, ct);
7349 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7350 			mutex_enter(&rp->r_statelock);
7351 			if (!rp->r_error)
7352 				rp->r_error = e.error;
7353 			mutex_exit(&rp->r_statelock);
7354 		}
7355 	}
7356 
7357 	mi = VTOMI4(dvp);
7358 
7359 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7360 	recov_state.rs_flags = 0;
7361 	recov_state.rs_num_retry_despite_err = 0;
7362 
7363 recov_retry:
7364 	/*
7365 	 * Remove ops: putfh dir; remove
7366 	 */
7367 	args.ctag = TAG_REMOVE;
7368 	args.array_len = 3;
7369 	args.array = argop;
7370 
7371 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7372 	if (e.error) {
7373 		nfs_rw_exit(&drp->r_rwlock);
7374 		VN_RELE(vp);
7375 		return (e.error);
7376 	}
7377 
7378 	/* putfh directory */
7379 	argop[0].argop = OP_CPUTFH;
7380 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7381 
7382 	/* remove */
7383 	argop[1].argop = OP_CREMOVE;
7384 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7385 
7386 	/* getattr dir */
7387 	argop[2].argop = OP_GETATTR;
7388 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7389 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7390 
7391 	doqueue = 1;
7392 	dinfo.di_time_call = gethrtime();
7393 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7394 
7395 	PURGE_ATTRCACHE4(vp);
7396 
7397 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7398 	if (e.error)
7399 		PURGE_ATTRCACHE4(dvp);
7400 
7401 	if (needrecov) {
7402 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7403 		    NULL, NULL, NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
7404 			if (!e.error)
7405 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7406 				    (caddr_t)&res);
7407 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7408 			    needrecov);
7409 			goto recov_retry;
7410 		}
7411 	}
7412 
7413 	/*
7414 	 * Matching nfs4_end_op() for start_op() above.
7415 	 * There is a path in the code below which calls
7416 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7417 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7418 	 * here to avoid nfs4_start_op() deadlock.
7419 	 */
7420 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7421 
7422 	if (!e.error) {
7423 		resp = &res;
7424 
7425 		if (res.status) {
7426 			e.error = geterrno4(res.status);
7427 			PURGE_ATTRCACHE4(dvp);
7428 			nfs4_purge_stale_fh(e.error, dvp, cr);
7429 		} else {
7430 			resop = &res.array[1];	/* remove res */
7431 			rm_res = &resop->nfs_resop4_u.opremove;
7432 
7433 			dinfo.di_garp =
7434 			    &res.array[2].nfs_resop4_u.opgetattr.ga_res;
7435 			dinfo.di_cred = cr;
7436 
7437 			/* Update directory attr, readdir and dnlc caches */
7438 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7439 			    &dinfo);
7440 		}
7441 	}
7442 	nfs_rw_exit(&drp->r_rwlock);
7443 	if (resp)
7444 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7445 
7446 	if (e.error == 0) {
7447 		vnode_t *tvp;
7448 		rnode4_t *trp;
7449 		trp = VTOR4(vp);
7450 		tvp = vp;
7451 		if (IS_SHADOW(vp, trp))
7452 			tvp = RTOV4(trp);
7453 		vnevent_remove(tvp, dvp, nm, ct);
7454 	}
7455 	VN_RELE(vp);
7456 	return (e.error);
7457 }
7458 
7459 /*
7460  * Link requires that the current fh be the target directory and the
7461  * saved fh be the source fh. After the operation, the current fh is unchanged.
7462  * Thus the compound op structure is:
7463  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7464  *	GETATTR(file)
7465  */
7466 /* ARGSUSED */
7467 static int
7468 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr,
7469     caller_context_t *ct, int flags)
7470 {
7471 	COMPOUND4args_clnt args;
7472 	COMPOUND4res_clnt res, *resp = NULL;
7473 	LINK4res *ln_res;
7474 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7475 	nfs_argop4 *argop;
7476 	nfs_resop4 *resop;
7477 	vnode_t *realvp, *nvp;
7478 	int doqueue;
7479 	mntinfo4_t *mi;
7480 	rnode4_t *tdrp;
7481 	bool_t needrecov = FALSE;
7482 	nfs4_recov_state_t recov_state;
7483 	hrtime_t t;
7484 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7485 	dirattr_info_t dinfo;
7486 
7487 	ASSERT(*tnm != '\0');
7488 	ASSERT(tdvp->v_type == VDIR);
7489 	ASSERT(nfs4_consistent_type(tdvp));
7490 	ASSERT(nfs4_consistent_type(svp));
7491 
7492 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7493 		return (EPERM);
7494 	if (VOP_REALVP(svp, &realvp, ct) == 0) {
7495 		svp = realvp;
7496 		ASSERT(nfs4_consistent_type(svp));
7497 	}
7498 
7499 	tdrp = VTOR4(tdvp);
7500 	mi = VTOMI4(svp);
7501 
7502 	if (!(mi->mi_flags & MI4_LINK)) {
7503 		return (EOPNOTSUPP);
7504 	}
7505 	recov_state.rs_flags = 0;
7506 	recov_state.rs_num_retry_despite_err = 0;
7507 
7508 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7509 		return (EINTR);
7510 
7511 recov_retry:
7512 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7513 
7514 	args.ctag = TAG_LINK;
7515 
7516 	/*
7517 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7518 	 * restorefh; getattr(fl)
7519 	 */
7520 	args.array_len = 7;
7521 	args.array = argop;
7522 
7523 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7524 	if (e.error) {
7525 		kmem_free(argop, argoplist_size);
7526 		nfs_rw_exit(&tdrp->r_rwlock);
7527 		return (e.error);
7528 	}
7529 
7530 	/* 0. putfh file */
7531 	argop[0].argop = OP_CPUTFH;
7532 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7533 
7534 	/* 1. save current fh to free up the space for the dir */
7535 	argop[1].argop = OP_SAVEFH;
7536 
7537 	/* 2. putfh targetdir */
7538 	argop[2].argop = OP_CPUTFH;
7539 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7540 
7541 	/* 3. link: current_fh is targetdir, saved_fh is source */
7542 	argop[3].argop = OP_CLINK;
7543 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7544 
7545 	/* 4. Get attributes of dir */
7546 	argop[4].argop = OP_GETATTR;
7547 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7548 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7549 
7550 	/* 5. If link was successful, restore current vp to file */
7551 	argop[5].argop = OP_RESTOREFH;
7552 
7553 	/* 6. Get attributes of linked object */
7554 	argop[6].argop = OP_GETATTR;
7555 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7556 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7557 
7558 	dnlc_remove(tdvp, tnm);
7559 
7560 	doqueue = 1;
7561 	t = gethrtime();
7562 
7563 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7564 
7565 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7566 	if (e.error != 0 && !needrecov) {
7567 		PURGE_ATTRCACHE4(tdvp);
7568 		PURGE_ATTRCACHE4(svp);
7569 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7570 		goto out;
7571 	}
7572 
7573 	if (needrecov) {
7574 		bool_t abort;
7575 
7576 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7577 		    NULL, NULL, OP_LINK, NULL, NULL, NULL);
7578 		if (abort == FALSE) {
7579 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7580 			    needrecov);
7581 			kmem_free(argop, argoplist_size);
7582 			if (!e.error)
7583 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7584 				    (caddr_t)&res);
7585 			goto recov_retry;
7586 		} else {
7587 			if (e.error != 0) {
7588 				PURGE_ATTRCACHE4(tdvp);
7589 				PURGE_ATTRCACHE4(svp);
7590 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7591 				    &recov_state, needrecov);
7592 				goto out;
7593 			}
7594 			/* fall through for res.status case */
7595 		}
7596 	}
7597 
7598 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7599 
7600 	resp = &res;
7601 	if (res.status) {
7602 		/* If link succeeded, then don't return error */
7603 		e.error = geterrno4(res.status);
7604 		if (res.array_len <= 4) {
7605 			/*
7606 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7607 			 */
7608 			PURGE_ATTRCACHE4(svp);
7609 			PURGE_ATTRCACHE4(tdvp);
7610 			if (e.error == EOPNOTSUPP) {
7611 				mutex_enter(&mi->mi_lock);
7612 				mi->mi_flags &= ~MI4_LINK;
7613 				mutex_exit(&mi->mi_lock);
7614 			}
7615 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7616 			/* XXX-LP */
7617 			if (e.error == EISDIR && crgetuid(cr) != 0)
7618 				e.error = EPERM;
7619 			goto out;
7620 		}
7621 	}
7622 
7623 	/* either no error or one of the postop getattr failed */
7624 
7625 	/*
7626 	 * XXX - if LINK succeeded, but no attrs were returned for link
7627 	 * file, purge its cache.
7628 	 *
7629 	 * XXX Perform a simplified version of wcc checking. Instead of
7630 	 * have another getattr to get pre-op, just purge cache if
7631 	 * any of the ops prior to and including the getattr failed.
7632 	 * If the getattr succeeded then update the attrcache accordingly.
7633 	 */
7634 
7635 	/*
7636 	 * update cache with link file postattrs.
7637 	 * Note: at this point resop points to link res.
7638 	 */
7639 	resop = &res.array[3];	/* link res */
7640 	ln_res = &resop->nfs_resop4_u.oplink;
7641 	if (res.status == NFS4_OK)
7642 		e.error = nfs4_update_attrcache(res.status,
7643 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res,
7644 		    t, svp, cr);
7645 
7646 	/*
7647 	 * Call makenfs4node to create the new shadow vp for tnm.
7648 	 * We pass NULL attrs because we just cached attrs for
7649 	 * the src object.  All we're trying to accomplish is to
7650 	 * to create the new shadow vnode.
7651 	 */
7652 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7653 	    tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm, VTOR4(svp)->r_fh));
7654 
7655 	/* Update target cache attribute, readdir and dnlc caches */
7656 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7657 	dinfo.di_time_call = t;
7658 	dinfo.di_cred = cr;
7659 
7660 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7661 	ASSERT(nfs4_consistent_type(tdvp));
7662 	ASSERT(nfs4_consistent_type(svp));
7663 	ASSERT(nfs4_consistent_type(nvp));
7664 	VN_RELE(nvp);
7665 
7666 	if (!e.error) {
7667 		vnode_t *tvp;
7668 		rnode4_t *trp;
7669 		/*
7670 		 * Notify the source file of this link operation.
7671 		 */
7672 		trp = VTOR4(svp);
7673 		tvp = svp;
7674 		if (IS_SHADOW(svp, trp))
7675 			tvp = RTOV4(trp);
7676 		vnevent_link(tvp, ct);
7677 	}
7678 out:
7679 	kmem_free(argop, argoplist_size);
7680 	if (resp)
7681 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7682 
7683 	nfs_rw_exit(&tdrp->r_rwlock);
7684 
7685 	return (e.error);
7686 }
7687 
7688 /* ARGSUSED */
7689 static int
7690 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7691     caller_context_t *ct, int flags)
7692 {
7693 	vnode_t *realvp;
7694 
7695 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7696 		return (EPERM);
7697 	if (VOP_REALVP(ndvp, &realvp, ct) == 0)
7698 		ndvp = realvp;
7699 
7700 	return (nfs4rename(odvp, onm, ndvp, nnm, cr, ct));
7701 }
7702 
7703 /*
7704  * nfs4rename does the real work of renaming in NFS Version 4.
7705  *
7706  * A file handle is considered volatile for renaming purposes if either
7707  * of the volatile bits are turned on. However, the compound may differ
7708  * based on the likelihood of the filehandle to change during rename.
7709  */
7710 static int
7711 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7712     caller_context_t *ct)
7713 {
7714 	int error;
7715 	mntinfo4_t *mi;
7716 	vnode_t *nvp = NULL;
7717 	vnode_t *ovp = NULL;
7718 	char *tmpname = NULL;
7719 	rnode4_t *rp;
7720 	rnode4_t *odrp;
7721 	rnode4_t *ndrp;
7722 	int did_link = 0;
7723 	int do_link = 1;
7724 	nfsstat4 stat = NFS4_OK;
7725 
7726 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7727 	ASSERT(nfs4_consistent_type(odvp));
7728 	ASSERT(nfs4_consistent_type(ndvp));
7729 
7730 	if (onm[0] == '.' && (onm[1] == '\0' ||
7731 	    (onm[1] == '.' && onm[2] == '\0')))
7732 		return (EINVAL);
7733 
7734 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7735 	    (nnm[1] == '.' && nnm[2] == '\0')))
7736 		return (EINVAL);
7737 
7738 	odrp = VTOR4(odvp);
7739 	ndrp = VTOR4(ndvp);
7740 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7741 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7742 			return (EINTR);
7743 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7744 			nfs_rw_exit(&odrp->r_rwlock);
7745 			return (EINTR);
7746 		}
7747 	} else {
7748 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7749 			return (EINTR);
7750 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7751 			nfs_rw_exit(&ndrp->r_rwlock);
7752 			return (EINTR);
7753 		}
7754 	}
7755 
7756 	/*
7757 	 * Lookup the target file.  If it exists, it needs to be
7758 	 * checked to see whether it is a mount point and whether
7759 	 * it is active (open).
7760 	 */
7761 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7762 	if (!error) {
7763 		int	isactive;
7764 
7765 		ASSERT(nfs4_consistent_type(nvp));
7766 		/*
7767 		 * If this file has been mounted on, then just
7768 		 * return busy because renaming to it would remove
7769 		 * the mounted file system from the name space.
7770 		 */
7771 		if (vn_ismntpt(nvp)) {
7772 			VN_RELE(nvp);
7773 			nfs_rw_exit(&odrp->r_rwlock);
7774 			nfs_rw_exit(&ndrp->r_rwlock);
7775 			return (EBUSY);
7776 		}
7777 
7778 		/*
7779 		 * First just remove the entry from the name cache, as it
7780 		 * is most likely the only entry for this vp.
7781 		 */
7782 		dnlc_remove(ndvp, nnm);
7783 
7784 		rp = VTOR4(nvp);
7785 
7786 		if (nvp->v_type != VREG) {
7787 			/*
7788 			 * Purge the name cache of all references to this vnode
7789 			 * so that we can check the reference count to infer
7790 			 * whether it is active or not.
7791 			 */
7792 			if (nvp->v_count > 1)
7793 				dnlc_purge_vp(nvp);
7794 
7795 			isactive = nvp->v_count > 1;
7796 		} else {
7797 			mutex_enter(&rp->r_os_lock);
7798 			isactive = list_head(&rp->r_open_streams) != NULL;
7799 			mutex_exit(&rp->r_os_lock);
7800 		}
7801 
7802 		/*
7803 		 * If the vnode is active and is not a directory,
7804 		 * arrange to rename it to a
7805 		 * temporary file so that it will continue to be
7806 		 * accessible.  This implements the "unlink-open-file"
7807 		 * semantics for the target of a rename operation.
7808 		 * Before doing this though, make sure that the
7809 		 * source and target files are not already the same.
7810 		 */
7811 		if (isactive && nvp->v_type != VDIR) {
7812 			/*
7813 			 * Lookup the source name.
7814 			 */
7815 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7816 
7817 			/*
7818 			 * The source name *should* already exist.
7819 			 */
7820 			if (error) {
7821 				VN_RELE(nvp);
7822 				nfs_rw_exit(&odrp->r_rwlock);
7823 				nfs_rw_exit(&ndrp->r_rwlock);
7824 				return (error);
7825 			}
7826 
7827 			ASSERT(nfs4_consistent_type(ovp));
7828 
7829 			/*
7830 			 * Compare the two vnodes.  If they are the same,
7831 			 * just release all held vnodes and return success.
7832 			 */
7833 			if (VN_CMP(ovp, nvp)) {
7834 				VN_RELE(ovp);
7835 				VN_RELE(nvp);
7836 				nfs_rw_exit(&odrp->r_rwlock);
7837 				nfs_rw_exit(&ndrp->r_rwlock);
7838 				return (0);
7839 			}
7840 
7841 			/*
7842 			 * Can't mix and match directories and non-
7843 			 * directories in rename operations.  We already
7844 			 * know that the target is not a directory.  If
7845 			 * the source is a directory, return an error.
7846 			 */
7847 			if (ovp->v_type == VDIR) {
7848 				VN_RELE(ovp);
7849 				VN_RELE(nvp);
7850 				nfs_rw_exit(&odrp->r_rwlock);
7851 				nfs_rw_exit(&ndrp->r_rwlock);
7852 				return (ENOTDIR);
7853 			}
7854 link_call:
7855 			/*
7856 			 * The target file exists, is not the same as
7857 			 * the source file, and is active.  We first
7858 			 * try to Link it to a temporary filename to
7859 			 * avoid having the server removing the file
7860 			 * completely (which could cause data loss to
7861 			 * the user's POV in the event the Rename fails
7862 			 * -- see bug 1165874).
7863 			 */
7864 			/*
7865 			 * The do_link and did_link booleans are
7866 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7867 			 * returned for the Rename.  Some servers can
7868 			 * not Rename over an Open file, so they return
7869 			 * this error.  The client needs to Remove the
7870 			 * newly created Link and do two Renames, just
7871 			 * as if the server didn't support LINK.
7872 			 */
7873 			tmpname = newname();
7874 			error = 0;
7875 
7876 			if (do_link) {
7877 				error = nfs4_link(ndvp, nvp, tmpname, cr,
7878 				    NULL, 0);
7879 			}
7880 			if (error == EOPNOTSUPP || !do_link) {
7881 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7882 				    cr, NULL, 0);
7883 				did_link = 0;
7884 			} else {
7885 				did_link = 1;
7886 			}
7887 			if (error) {
7888 				kmem_free(tmpname, MAXNAMELEN);
7889 				VN_RELE(ovp);
7890 				VN_RELE(nvp);
7891 				nfs_rw_exit(&odrp->r_rwlock);
7892 				nfs_rw_exit(&ndrp->r_rwlock);
7893 				return (error);
7894 			}
7895 
7896 			mutex_enter(&rp->r_statelock);
7897 			if (rp->r_unldvp == NULL) {
7898 				VN_HOLD(ndvp);
7899 				rp->r_unldvp = ndvp;
7900 				if (rp->r_unlcred != NULL)
7901 					crfree(rp->r_unlcred);
7902 				crhold(cr);
7903 				rp->r_unlcred = cr;
7904 				rp->r_unlname = tmpname;
7905 			} else {
7906 				if (rp->r_unlname)
7907 					kmem_free(rp->r_unlname, MAXNAMELEN);
7908 				rp->r_unlname = tmpname;
7909 			}
7910 			mutex_exit(&rp->r_statelock);
7911 		}
7912 
7913 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7914 
7915 		ASSERT(nfs4_consistent_type(nvp));
7916 	}
7917 
7918 	if (ovp == NULL) {
7919 		/*
7920 		 * When renaming directories to be a subdirectory of a
7921 		 * different parent, the dnlc entry for ".." will no
7922 		 * longer be valid, so it must be removed.
7923 		 *
7924 		 * We do a lookup here to determine whether we are renaming
7925 		 * a directory and we need to check if we are renaming
7926 		 * an unlinked file.  This might have already been done
7927 		 * in previous code, so we check ovp == NULL to avoid
7928 		 * doing it twice.
7929 		 */
7930 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7931 		/*
7932 		 * The source name *should* already exist.
7933 		 */
7934 		if (error) {
7935 			nfs_rw_exit(&odrp->r_rwlock);
7936 			nfs_rw_exit(&ndrp->r_rwlock);
7937 			if (nvp) {
7938 				VN_RELE(nvp);
7939 			}
7940 			return (error);
7941 		}
7942 		ASSERT(ovp != NULL);
7943 		ASSERT(nfs4_consistent_type(ovp));
7944 	}
7945 
7946 	/*
7947 	 * Is the object being renamed a dir, and if so, is
7948 	 * it being renamed to a child of itself?  The underlying
7949 	 * fs should ultimately return EINVAL for this case;
7950 	 * however, buggy beta non-Solaris NFSv4 servers at
7951 	 * interop testing events have allowed this behavior,
7952 	 * and it caused our client to panic due to a recursive
7953 	 * mutex_enter in fn_move.
7954 	 *
7955 	 * The tedious locking in fn_move could be changed to
7956 	 * deal with this case, and the client could avoid the
7957 	 * panic; however, the client would just confuse itself
7958 	 * later and misbehave.  A better way to handle the broken
7959 	 * server is to detect this condition and return EINVAL
7960 	 * without ever sending the the bogus rename to the server.
7961 	 * We know the rename is invalid -- just fail it now.
7962 	 */
7963 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7964 		VN_RELE(ovp);
7965 		nfs_rw_exit(&odrp->r_rwlock);
7966 		nfs_rw_exit(&ndrp->r_rwlock);
7967 		if (nvp) {
7968 			VN_RELE(nvp);
7969 		}
7970 		return (EINVAL);
7971 	}
7972 
7973 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7974 
7975 	/*
7976 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7977 	 * possible for the filehandle to change due to the rename.
7978 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7979 	 * the fh will not change because of the rename, but we still need
7980 	 * to update its rnode entry with the new name for
7981 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7982 	 * has no effect on these for now, but for future improvements,
7983 	 * we might want to use it too to simplify handling of files
7984 	 * that are open with that flag on. (XXX)
7985 	 */
7986 	mi = VTOMI4(odvp);
7987 	if (NFS4_VOLATILE_FH(mi))
7988 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7989 		    &stat);
7990 	else
7991 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7992 		    &stat);
7993 
7994 	ASSERT(nfs4_consistent_type(odvp));
7995 	ASSERT(nfs4_consistent_type(ndvp));
7996 	ASSERT(nfs4_consistent_type(ovp));
7997 
7998 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
7999 		do_link = 0;
8000 		/*
8001 		 * Before the 'link_call' code, we did a nfs4_lookup
8002 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
8003 		 * call we call VN_RELE to match that hold.  We need
8004 		 * to place an additional VN_HOLD here since we will
8005 		 * be hitting that VN_RELE again.
8006 		 */
8007 		VN_HOLD(nvp);
8008 
8009 		(void) nfs4_remove(ndvp, tmpname, cr, NULL, 0);
8010 
8011 		/* Undo the unlinked file naming stuff we just did */
8012 		mutex_enter(&rp->r_statelock);
8013 		if (rp->r_unldvp) {
8014 			VN_RELE(ndvp);
8015 			rp->r_unldvp = NULL;
8016 			if (rp->r_unlcred != NULL)
8017 				crfree(rp->r_unlcred);
8018 			rp->r_unlcred = NULL;
8019 			/* rp->r_unlanme points to tmpname */
8020 			if (rp->r_unlname)
8021 				kmem_free(rp->r_unlname, MAXNAMELEN);
8022 			rp->r_unlname = NULL;
8023 		}
8024 		mutex_exit(&rp->r_statelock);
8025 
8026 		if (nvp) {
8027 			VN_RELE(nvp);
8028 		}
8029 		goto link_call;
8030 	}
8031 
8032 	if (error) {
8033 		VN_RELE(ovp);
8034 		nfs_rw_exit(&odrp->r_rwlock);
8035 		nfs_rw_exit(&ndrp->r_rwlock);
8036 		if (nvp) {
8037 			VN_RELE(nvp);
8038 		}
8039 		return (error);
8040 	}
8041 
8042 	/*
8043 	 * when renaming directories to be a subdirectory of a
8044 	 * different parent, the dnlc entry for ".." will no
8045 	 * longer be valid, so it must be removed
8046 	 */
8047 	rp = VTOR4(ovp);
8048 	if (ndvp != odvp) {
8049 		if (ovp->v_type == VDIR) {
8050 			dnlc_remove(ovp, "..");
8051 			if (rp->r_dir != NULL)
8052 				nfs4_purge_rddir_cache(ovp);
8053 		}
8054 	}
8055 
8056 	/*
8057 	 * If we are renaming the unlinked file, update the
8058 	 * r_unldvp and r_unlname as needed.
8059 	 */
8060 	mutex_enter(&rp->r_statelock);
8061 	if (rp->r_unldvp != NULL) {
8062 		if (strcmp(rp->r_unlname, onm) == 0) {
8063 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
8064 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
8065 			if (ndvp != rp->r_unldvp) {
8066 				VN_RELE(rp->r_unldvp);
8067 				rp->r_unldvp = ndvp;
8068 				VN_HOLD(ndvp);
8069 			}
8070 		}
8071 	}
8072 	mutex_exit(&rp->r_statelock);
8073 
8074 	/*
8075 	 * Notify the rename vnevents to source vnode, and to the target
8076 	 * vnode if it already existed.
8077 	 */
8078 	if (error == 0) {
8079 		vnode_t *tvp;
8080 		rnode4_t *trp;
8081 		/*
8082 		 * Notify the vnode. Each links is represented by
8083 		 * a different vnode, in nfsv4.
8084 		 */
8085 		if (nvp) {
8086 			trp = VTOR4(nvp);
8087 			tvp = nvp;
8088 			if (IS_SHADOW(nvp, trp))
8089 				tvp = RTOV4(trp);
8090 			vnevent_rename_dest(tvp, ndvp, nnm, ct);
8091 		}
8092 
8093 		/*
8094 		 * if the source and destination directory are not the
8095 		 * same notify the destination directory.
8096 		 */
8097 		if (VTOR4(odvp) != VTOR4(ndvp)) {
8098 			trp = VTOR4(ndvp);
8099 			tvp = ndvp;
8100 			if (IS_SHADOW(ndvp, trp))
8101 				tvp = RTOV4(trp);
8102 			vnevent_rename_dest_dir(tvp, ct);
8103 		}
8104 
8105 		trp = VTOR4(ovp);
8106 		tvp = ovp;
8107 		if (IS_SHADOW(ovp, trp))
8108 			tvp = RTOV4(trp);
8109 		vnevent_rename_src(tvp, odvp, onm, ct);
8110 	}
8111 
8112 	if (nvp) {
8113 		VN_RELE(nvp);
8114 	}
8115 	VN_RELE(ovp);
8116 
8117 	nfs_rw_exit(&odrp->r_rwlock);
8118 	nfs_rw_exit(&ndrp->r_rwlock);
8119 
8120 	return (error);
8121 }
8122 
8123 /*
8124  * When the parent directory has changed, sv_dfh must be updated
8125  */
8126 static void
8127 update_parentdir_sfh(vnode_t *vp, vnode_t *ndvp)
8128 {
8129 	svnode_t *sv = VTOSV(vp);
8130 	nfs4_sharedfh_t *old_dfh = sv->sv_dfh;
8131 	nfs4_sharedfh_t *new_dfh = VTOR4(ndvp)->r_fh;
8132 
8133 	sfh4_hold(new_dfh);
8134 	sv->sv_dfh = new_dfh;
8135 	sfh4_rele(&old_dfh);
8136 }
8137 
8138 /*
8139  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
8140  * when it is known that the filehandle is persistent through rename.
8141  *
8142  * Rename requires that the current fh be the target directory and the
8143  * saved fh be the source directory. After the operation, the current fh
8144  * is unchanged.
8145  * The compound op structure for persistent fh rename is:
8146  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
8147  * Rather than bother with the directory postop args, we'll simply
8148  * update that a change occurred in the cache, so no post-op getattrs.
8149  */
8150 static int
8151 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
8152     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8153 {
8154 	COMPOUND4args_clnt args;
8155 	COMPOUND4res_clnt res, *resp = NULL;
8156 	nfs_argop4 *argop;
8157 	nfs_resop4 *resop;
8158 	int doqueue, argoplist_size;
8159 	mntinfo4_t *mi;
8160 	rnode4_t *odrp = VTOR4(odvp);
8161 	rnode4_t *ndrp = VTOR4(ndvp);
8162 	RENAME4res *rn_res;
8163 	bool_t needrecov;
8164 	nfs4_recov_state_t recov_state;
8165 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8166 	dirattr_info_t dinfo, *dinfop;
8167 
8168 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8169 
8170 	recov_state.rs_flags = 0;
8171 	recov_state.rs_num_retry_despite_err = 0;
8172 
8173 	/*
8174 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
8175 	 *
8176 	 * If source/target are different dirs, then append putfh(src); getattr
8177 	 */
8178 	args.array_len = (odvp == ndvp) ? 5 : 7;
8179 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8180 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8181 
8182 recov_retry:
8183 	*statp = NFS4_OK;
8184 
8185 	/* No need to Lookup the file, persistent fh */
8186 	args.ctag = TAG_RENAME;
8187 
8188 	mi = VTOMI4(odvp);
8189 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8190 	if (e.error) {
8191 		kmem_free(argop, argoplist_size);
8192 		return (e.error);
8193 	}
8194 
8195 	/* 0: putfh source directory */
8196 	argop[0].argop = OP_CPUTFH;
8197 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8198 
8199 	/* 1: Save source fh to free up current for target */
8200 	argop[1].argop = OP_SAVEFH;
8201 
8202 	/* 2: putfh targetdir */
8203 	argop[2].argop = OP_CPUTFH;
8204 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8205 
8206 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8207 	argop[3].argop = OP_CRENAME;
8208 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8209 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8210 
8211 	/* 4: getattr (targetdir) */
8212 	argop[4].argop = OP_GETATTR;
8213 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8214 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8215 
8216 	if (ndvp != odvp) {
8217 
8218 		/* 5: putfh (sourcedir) */
8219 		argop[5].argop = OP_CPUTFH;
8220 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8221 
8222 		/* 6: getattr (sourcedir) */
8223 		argop[6].argop = OP_GETATTR;
8224 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8225 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8226 	}
8227 
8228 	dnlc_remove(odvp, onm);
8229 	dnlc_remove(ndvp, nnm);
8230 
8231 	doqueue = 1;
8232 	dinfo.di_time_call = gethrtime();
8233 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8234 
8235 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8236 	if (e.error) {
8237 		PURGE_ATTRCACHE4(odvp);
8238 		PURGE_ATTRCACHE4(ndvp);
8239 	} else {
8240 		*statp = res.status;
8241 	}
8242 
8243 	if (needrecov) {
8244 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8245 		    OP_RENAME, NULL, NULL, NULL) == FALSE) {
8246 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8247 			if (!e.error)
8248 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8249 				    (caddr_t)&res);
8250 			goto recov_retry;
8251 		}
8252 	}
8253 
8254 	if (!e.error) {
8255 		resp = &res;
8256 		/*
8257 		 * as long as OP_RENAME
8258 		 */
8259 		if (res.status != NFS4_OK && res.array_len <= 4) {
8260 			e.error = geterrno4(res.status);
8261 			PURGE_ATTRCACHE4(odvp);
8262 			PURGE_ATTRCACHE4(ndvp);
8263 			/*
8264 			 * System V defines rename to return EEXIST, not
8265 			 * ENOTEMPTY if the target directory is not empty.
8266 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8267 			 * which geterrno4 maps to ENOTEMPTY.
8268 			 */
8269 			if (e.error == ENOTEMPTY)
8270 				e.error = EEXIST;
8271 		} else {
8272 
8273 			resop = &res.array[3];	/* rename res */
8274 			rn_res = &resop->nfs_resop4_u.oprename;
8275 
8276 			if (res.status == NFS4_OK) {
8277 				/*
8278 				 * Update target attribute, readdir and dnlc
8279 				 * caches.
8280 				 */
8281 				dinfo.di_garp =
8282 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8283 				dinfo.di_cred = cr;
8284 				dinfop = &dinfo;
8285 			} else
8286 				dinfop = NULL;
8287 
8288 			nfs4_update_dircaches(&rn_res->target_cinfo,
8289 			    ndvp, NULL, NULL, dinfop);
8290 
8291 			/*
8292 			 * Update source attribute, readdir and dnlc caches
8293 			 *
8294 			 */
8295 			if (ndvp != odvp) {
8296 				update_parentdir_sfh(renvp, ndvp);
8297 
8298 				if (dinfop)
8299 					dinfo.di_garp =
8300 					    &(res.array[6].nfs_resop4_u.
8301 					    opgetattr.ga_res);
8302 
8303 				nfs4_update_dircaches(&rn_res->source_cinfo,
8304 				    odvp, NULL, NULL, dinfop);
8305 			}
8306 
8307 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8308 			    nnm);
8309 		}
8310 	}
8311 
8312 	if (resp)
8313 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8314 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8315 	kmem_free(argop, argoplist_size);
8316 
8317 	return (e.error);
8318 }
8319 
8320 /*
8321  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8322  * it is possible for the filehandle to change due to the rename.
8323  *
8324  * The compound req in this case includes a post-rename lookup and getattr
8325  * to ensure that we have the correct fh and attributes for the object.
8326  *
8327  * Rename requires that the current fh be the target directory and the
8328  * saved fh be the source directory. After the operation, the current fh
8329  * is unchanged.
8330  *
8331  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8332  * update the filehandle for the renamed object.  We also get the old
8333  * filehandle for historical reasons; this should be taken out sometime.
8334  * This results in a rather cumbersome compound...
8335  *
8336  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8337  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8338  *
8339  */
8340 static int
8341 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8342     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8343 {
8344 	COMPOUND4args_clnt args;
8345 	COMPOUND4res_clnt res, *resp = NULL;
8346 	int argoplist_size;
8347 	nfs_argop4 *argop;
8348 	nfs_resop4 *resop;
8349 	int doqueue;
8350 	mntinfo4_t *mi;
8351 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8352 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8353 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8354 	RENAME4res *rn_res;
8355 	GETFH4res *ngf_res;
8356 	bool_t needrecov;
8357 	nfs4_recov_state_t recov_state;
8358 	hrtime_t t;
8359 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8360 	dirattr_info_t dinfo, *dinfop = &dinfo;
8361 
8362 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8363 
8364 	recov_state.rs_flags = 0;
8365 	recov_state.rs_num_retry_despite_err = 0;
8366 
8367 recov_retry:
8368 	*statp = NFS4_OK;
8369 
8370 	/*
8371 	 * There is a window between the RPC and updating the path and
8372 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8373 	 * code, so that it doesn't try to use the old path during that
8374 	 * window.
8375 	 */
8376 	mutex_enter(&orp->r_statelock);
8377 	while (orp->r_flags & R4RECEXPFH) {
8378 		klwp_t *lwp = ttolwp(curthread);
8379 
8380 		if (lwp != NULL)
8381 			lwp->lwp_nostop++;
8382 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8383 			mutex_exit(&orp->r_statelock);
8384 			if (lwp != NULL)
8385 				lwp->lwp_nostop--;
8386 			return (EINTR);
8387 		}
8388 		if (lwp != NULL)
8389 			lwp->lwp_nostop--;
8390 	}
8391 	orp->r_flags |= R4RECEXPFH;
8392 	mutex_exit(&orp->r_statelock);
8393 
8394 	mi = VTOMI4(odvp);
8395 
8396 	args.ctag = TAG_RENAME_VFH;
8397 	args.array_len = (odvp == ndvp) ? 10 : 12;
8398 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8399 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8400 
8401 	/*
8402 	 * Rename ops:
8403 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8404 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8405 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8406 	 *
8407 	 *    if (odvp != ndvp)
8408 	 *	add putfh(sourcedir), getattr(sourcedir) }
8409 	 */
8410 	args.array = argop;
8411 
8412 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8413 	    &recov_state, NULL);
8414 	if (e.error) {
8415 		kmem_free(argop, argoplist_size);
8416 		mutex_enter(&orp->r_statelock);
8417 		orp->r_flags &= ~R4RECEXPFH;
8418 		cv_broadcast(&orp->r_cv);
8419 		mutex_exit(&orp->r_statelock);
8420 		return (e.error);
8421 	}
8422 
8423 	/* 0: putfh source directory */
8424 	argop[0].argop = OP_CPUTFH;
8425 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8426 
8427 	/* 1: Save source fh to free up current for target */
8428 	argop[1].argop = OP_SAVEFH;
8429 
8430 	/* 2: Lookup pre-rename fh of renamed object */
8431 	argop[2].argop = OP_CLOOKUP;
8432 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8433 
8434 	/* 3: getfh fh of renamed object (before rename) */
8435 	argop[3].argop = OP_GETFH;
8436 
8437 	/* 4: putfh targetdir */
8438 	argop[4].argop = OP_CPUTFH;
8439 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8440 
8441 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8442 	argop[5].argop = OP_CRENAME;
8443 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8444 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8445 
8446 	/* 6: getattr of target dir (post op attrs) */
8447 	argop[6].argop = OP_GETATTR;
8448 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8449 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8450 
8451 	/* 7: Lookup post-rename fh of renamed object */
8452 	argop[7].argop = OP_CLOOKUP;
8453 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8454 
8455 	/* 8: getfh fh of renamed object (after rename) */
8456 	argop[8].argop = OP_GETFH;
8457 
8458 	/* 9: getattr of renamed object */
8459 	argop[9].argop = OP_GETATTR;
8460 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8461 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8462 
8463 	/*
8464 	 * If source/target dirs are different, then get new post-op
8465 	 * attrs for source dir also.
8466 	 */
8467 	if (ndvp != odvp) {
8468 		/* 10: putfh (sourcedir) */
8469 		argop[10].argop = OP_CPUTFH;
8470 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8471 
8472 		/* 11: getattr (sourcedir) */
8473 		argop[11].argop = OP_GETATTR;
8474 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8475 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8476 	}
8477 
8478 	dnlc_remove(odvp, onm);
8479 	dnlc_remove(ndvp, nnm);
8480 
8481 	doqueue = 1;
8482 	t = gethrtime();
8483 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8484 
8485 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8486 	if (e.error) {
8487 		PURGE_ATTRCACHE4(odvp);
8488 		PURGE_ATTRCACHE4(ndvp);
8489 		if (!needrecov) {
8490 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8491 			    &recov_state, needrecov);
8492 			goto out;
8493 		}
8494 	} else {
8495 		*statp = res.status;
8496 	}
8497 
8498 	if (needrecov) {
8499 		bool_t abort;
8500 
8501 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8502 		    OP_RENAME, NULL, NULL, NULL);
8503 		if (abort == FALSE) {
8504 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8505 			    &recov_state, needrecov);
8506 			kmem_free(argop, argoplist_size);
8507 			if (!e.error)
8508 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8509 				    (caddr_t)&res);
8510 			mutex_enter(&orp->r_statelock);
8511 			orp->r_flags &= ~R4RECEXPFH;
8512 			cv_broadcast(&orp->r_cv);
8513 			mutex_exit(&orp->r_statelock);
8514 			goto recov_retry;
8515 		} else {
8516 			if (e.error != 0) {
8517 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8518 				    &recov_state, needrecov);
8519 				goto out;
8520 			}
8521 			/* fall through for res.status case */
8522 		}
8523 	}
8524 
8525 	resp = &res;
8526 	/*
8527 	 * If OP_RENAME (or any prev op) failed, then return an error.
8528 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8529 	 */
8530 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8531 		/*
8532 		 * Error in an op other than last Getattr
8533 		 */
8534 		e.error = geterrno4(res.status);
8535 		PURGE_ATTRCACHE4(odvp);
8536 		PURGE_ATTRCACHE4(ndvp);
8537 		/*
8538 		 * System V defines rename to return EEXIST, not
8539 		 * ENOTEMPTY if the target directory is not empty.
8540 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8541 		 * which geterrno4 maps to ENOTEMPTY.
8542 		 */
8543 		if (e.error == ENOTEMPTY)
8544 			e.error = EEXIST;
8545 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8546 		    needrecov);
8547 		goto out;
8548 	}
8549 
8550 	/* rename results */
8551 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8552 
8553 	if (res.status == NFS4_OK) {
8554 		/* Update target attribute, readdir and dnlc caches */
8555 		dinfo.di_garp =
8556 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
8557 		dinfo.di_cred = cr;
8558 		dinfo.di_time_call = t;
8559 	} else
8560 		dinfop = NULL;
8561 
8562 	/* Update source cache attribute, readdir and dnlc caches */
8563 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8564 
8565 	/* Update source cache attribute, readdir and dnlc caches */
8566 	if (ndvp != odvp) {
8567 		update_parentdir_sfh(ovp, ndvp);
8568 
8569 		/*
8570 		 * If dinfop is non-NULL, then compound succeded, so
8571 		 * set di_garp to attrs for source dir.  dinfop is only
8572 		 * set to NULL when compound fails.
8573 		 */
8574 		if (dinfop)
8575 			dinfo.di_garp =
8576 			    &res.array[11].nfs_resop4_u.opgetattr.ga_res;
8577 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8578 		    dinfop);
8579 	}
8580 
8581 	/*
8582 	 * Update the rnode with the new component name and args,
8583 	 * and if the file handle changed, also update it with the new fh.
8584 	 * This is only necessary if the target object has an rnode
8585 	 * entry and there is no need to create one for it.
8586 	 */
8587 	resop = &res.array[8];	/* getfh new res */
8588 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8589 
8590 	/*
8591 	 * Update the path and filehandle for the renamed object.
8592 	 */
8593 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8594 
8595 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8596 
8597 	if (res.status == NFS4_OK) {
8598 		resop++;	/* getattr res */
8599 		e.error = nfs4_update_attrcache(res.status,
8600 		    &resop->nfs_resop4_u.opgetattr.ga_res,
8601 		    t, ovp, cr);
8602 	}
8603 
8604 out:
8605 	kmem_free(argop, argoplist_size);
8606 	if (resp)
8607 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8608 	mutex_enter(&orp->r_statelock);
8609 	orp->r_flags &= ~R4RECEXPFH;
8610 	cv_broadcast(&orp->r_cv);
8611 	mutex_exit(&orp->r_statelock);
8612 
8613 	return (e.error);
8614 }
8615 
8616 /* ARGSUSED */
8617 static int
8618 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr,
8619     caller_context_t *ct, int flags, vsecattr_t *vsecp)
8620 {
8621 	int error;
8622 	vnode_t *vp;
8623 
8624 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8625 		return (EPERM);
8626 	/*
8627 	 * As ".." has special meaning and rather than send a mkdir
8628 	 * over the wire to just let the server freak out, we just
8629 	 * short circuit it here and return EEXIST
8630 	 */
8631 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8632 		return (EEXIST);
8633 
8634 	/*
8635 	 * Decision to get the right gid and setgid bit of the
8636 	 * new directory is now made in call_nfs4_create_req.
8637 	 */
8638 	va->va_mask |= AT_MODE;
8639 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8640 	if (error)
8641 		return (error);
8642 
8643 	*vpp = vp;
8644 	return (0);
8645 }
8646 
8647 
8648 /*
8649  * rmdir is using the same remove v4 op as does remove.
8650  * Remove requires that the current fh be the target directory.
8651  * After the operation, the current fh is unchanged.
8652  * The compound op structure is:
8653  *      PUTFH(targetdir), REMOVE
8654  */
8655 /*ARGSUSED4*/
8656 static int
8657 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr,
8658     caller_context_t *ct, int flags)
8659 {
8660 	int need_end_op = FALSE;
8661 	COMPOUND4args_clnt args;
8662 	COMPOUND4res_clnt res, *resp = NULL;
8663 	REMOVE4res *rm_res;
8664 	nfs_argop4 argop[3];
8665 	nfs_resop4 *resop;
8666 	vnode_t *vp;
8667 	int doqueue;
8668 	mntinfo4_t *mi;
8669 	rnode4_t *drp;
8670 	bool_t needrecov = FALSE;
8671 	nfs4_recov_state_t recov_state;
8672 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8673 	dirattr_info_t dinfo, *dinfop;
8674 
8675 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8676 		return (EPERM);
8677 	/*
8678 	 * As ".." has special meaning and rather than send a rmdir
8679 	 * over the wire to just let the server freak out, we just
8680 	 * short circuit it here and return EEXIST
8681 	 */
8682 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8683 		return (EEXIST);
8684 
8685 	drp = VTOR4(dvp);
8686 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8687 		return (EINTR);
8688 
8689 	/*
8690 	 * Attempt to prevent a rmdir(".") from succeeding.
8691 	 */
8692 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8693 	if (e.error) {
8694 		nfs_rw_exit(&drp->r_rwlock);
8695 		return (e.error);
8696 	}
8697 	if (vp == cdir) {
8698 		VN_RELE(vp);
8699 		nfs_rw_exit(&drp->r_rwlock);
8700 		return (EINVAL);
8701 	}
8702 
8703 	/*
8704 	 * Since nfsv4 remove op works on both files and directories,
8705 	 * check that the removed object is indeed a directory.
8706 	 */
8707 	if (vp->v_type != VDIR) {
8708 		VN_RELE(vp);
8709 		nfs_rw_exit(&drp->r_rwlock);
8710 		return (ENOTDIR);
8711 	}
8712 
8713 	/*
8714 	 * First just remove the entry from the name cache, as it
8715 	 * is most likely an entry for this vp.
8716 	 */
8717 	dnlc_remove(dvp, nm);
8718 
8719 	/*
8720 	 * If there vnode reference count is greater than one, then
8721 	 * there may be additional references in the DNLC which will
8722 	 * need to be purged.  First, trying removing the entry for
8723 	 * the parent directory and see if that removes the additional
8724 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8725 	 * to completely remove any references to the directory which
8726 	 * might still exist in the DNLC.
8727 	 */
8728 	if (vp->v_count > 1) {
8729 		dnlc_remove(vp, "..");
8730 		if (vp->v_count > 1)
8731 			dnlc_purge_vp(vp);
8732 	}
8733 
8734 	mi = VTOMI4(dvp);
8735 	recov_state.rs_flags = 0;
8736 	recov_state.rs_num_retry_despite_err = 0;
8737 
8738 recov_retry:
8739 	args.ctag = TAG_RMDIR;
8740 
8741 	/*
8742 	 * Rmdir ops: putfh dir; remove
8743 	 */
8744 	args.array_len = 3;
8745 	args.array = argop;
8746 
8747 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8748 	if (e.error) {
8749 		nfs_rw_exit(&drp->r_rwlock);
8750 		return (e.error);
8751 	}
8752 	need_end_op = TRUE;
8753 
8754 	/* putfh directory */
8755 	argop[0].argop = OP_CPUTFH;
8756 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8757 
8758 	/* remove */
8759 	argop[1].argop = OP_CREMOVE;
8760 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8761 
8762 	/* getattr (postop attrs for dir that contained removed dir) */
8763 	argop[2].argop = OP_GETATTR;
8764 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8765 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8766 
8767 	dinfo.di_time_call = gethrtime();
8768 	doqueue = 1;
8769 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8770 
8771 	PURGE_ATTRCACHE4(vp);
8772 
8773 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8774 	if (e.error) {
8775 		PURGE_ATTRCACHE4(dvp);
8776 	}
8777 
8778 	if (needrecov) {
8779 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8780 		    NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
8781 			if (!e.error)
8782 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8783 				    (caddr_t)&res);
8784 
8785 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8786 			    needrecov);
8787 			need_end_op = FALSE;
8788 			goto recov_retry;
8789 		}
8790 	}
8791 
8792 	if (!e.error) {
8793 		resp = &res;
8794 
8795 		/*
8796 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8797 		 * failed.
8798 		 */
8799 		if (res.status != NFS4_OK && res.array_len <= 2) {
8800 			e.error = geterrno4(res.status);
8801 			PURGE_ATTRCACHE4(dvp);
8802 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8803 			    &recov_state, needrecov);
8804 			need_end_op = FALSE;
8805 			nfs4_purge_stale_fh(e.error, dvp, cr);
8806 			/*
8807 			 * System V defines rmdir to return EEXIST, not
8808 			 * ENOTEMPTY if the directory is not empty.  Over
8809 			 * the wire, the error is NFSERR_ENOTEMPTY which
8810 			 * geterrno4 maps to ENOTEMPTY.
8811 			 */
8812 			if (e.error == ENOTEMPTY)
8813 				e.error = EEXIST;
8814 		} else {
8815 			resop = &res.array[1];	/* remove res */
8816 			rm_res = &resop->nfs_resop4_u.opremove;
8817 
8818 			if (res.status == NFS4_OK) {
8819 				resop = &res.array[2];	/* dir attrs */
8820 				dinfo.di_garp =
8821 				    &resop->nfs_resop4_u.opgetattr.ga_res;
8822 				dinfo.di_cred = cr;
8823 				dinfop = &dinfo;
8824 			} else
8825 				dinfop = NULL;
8826 
8827 			/* Update dir attribute, readdir and dnlc caches */
8828 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8829 			    dinfop);
8830 
8831 			/* destroy rddir cache for dir that was removed */
8832 			if (VTOR4(vp)->r_dir != NULL)
8833 				nfs4_purge_rddir_cache(vp);
8834 		}
8835 	}
8836 
8837 	if (need_end_op)
8838 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8839 
8840 	nfs_rw_exit(&drp->r_rwlock);
8841 
8842 	if (resp)
8843 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8844 
8845 	if (e.error == 0) {
8846 		vnode_t *tvp;
8847 		rnode4_t *trp;
8848 		trp = VTOR4(vp);
8849 		tvp = vp;
8850 		if (IS_SHADOW(vp, trp))
8851 			tvp = RTOV4(trp);
8852 		vnevent_rmdir(tvp, dvp, nm, ct);
8853 	}
8854 
8855 	VN_RELE(vp);
8856 
8857 	return (e.error);
8858 }
8859 
8860 /* ARGSUSED */
8861 static int
8862 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr,
8863     caller_context_t *ct, int flags)
8864 {
8865 	int error;
8866 	vnode_t *vp;
8867 	rnode4_t *rp;
8868 	char *contents;
8869 	mntinfo4_t *mi = VTOMI4(dvp);
8870 
8871 	if (nfs_zone() != mi->mi_zone)
8872 		return (EPERM);
8873 	if (!(mi->mi_flags & MI4_SYMLINK))
8874 		return (EOPNOTSUPP);
8875 
8876 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8877 	if (error)
8878 		return (error);
8879 
8880 	ASSERT(nfs4_consistent_type(vp));
8881 	rp = VTOR4(vp);
8882 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8883 
8884 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8885 
8886 		if (contents != NULL) {
8887 			mutex_enter(&rp->r_statelock);
8888 			if (rp->r_symlink.contents == NULL) {
8889 				rp->r_symlink.len = strlen(tnm);
8890 				bcopy(tnm, contents, rp->r_symlink.len);
8891 				rp->r_symlink.contents = contents;
8892 				rp->r_symlink.size = MAXPATHLEN;
8893 				mutex_exit(&rp->r_statelock);
8894 			} else {
8895 				mutex_exit(&rp->r_statelock);
8896 				kmem_free((void *)contents, MAXPATHLEN);
8897 			}
8898 		}
8899 	}
8900 	VN_RELE(vp);
8901 
8902 	return (error);
8903 }
8904 
8905 
8906 /*
8907  * Read directory entries.
8908  * There are some weird things to look out for here.  The uio_loffset
8909  * field is either 0 or it is the offset returned from a previous
8910  * readdir.  It is an opaque value used by the server to find the
8911  * correct directory block to read. The count field is the number
8912  * of blocks to read on the server.  This is advisory only, the server
8913  * may return only one block's worth of entries.  Entries may be compressed
8914  * on the server.
8915  */
8916 /* ARGSUSED */
8917 static int
8918 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp,
8919     caller_context_t *ct, int flags)
8920 {
8921 	int error;
8922 	uint_t count;
8923 	rnode4_t *rp;
8924 	rddir4_cache *rdc;
8925 	rddir4_cache *rrdc;
8926 
8927 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8928 		return (EIO);
8929 	rp = VTOR4(vp);
8930 
8931 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8932 
8933 	/*
8934 	 * Make sure that the directory cache is valid.
8935 	 */
8936 	if (rp->r_dir != NULL) {
8937 		if (nfs_disable_rddir_cache != 0) {
8938 			/*
8939 			 * Setting nfs_disable_rddir_cache in /etc/system
8940 			 * allows interoperability with servers that do not
8941 			 * properly update the attributes of directories.
8942 			 * Any cached information gets purged before an
8943 			 * access is made to it.
8944 			 */
8945 			nfs4_purge_rddir_cache(vp);
8946 		}
8947 
8948 		error = nfs4_validate_caches(vp, cr);
8949 		if (error)
8950 			return (error);
8951 	}
8952 
8953 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8954 
8955 	/*
8956 	 * Short circuit last readdir which always returns 0 bytes.
8957 	 * This can be done after the directory has been read through
8958 	 * completely at least once.  This will set r_direof which
8959 	 * can be used to find the value of the last cookie.
8960 	 */
8961 	mutex_enter(&rp->r_statelock);
8962 	if (rp->r_direof != NULL &&
8963 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8964 		mutex_exit(&rp->r_statelock);
8965 #ifdef DEBUG
8966 		nfs4_readdir_cache_shorts++;
8967 #endif
8968 		if (eofp)
8969 			*eofp = 1;
8970 		return (0);
8971 	}
8972 
8973 	/*
8974 	 * Look for a cache entry.  Cache entries are identified
8975 	 * by the NFS cookie value and the byte count requested.
8976 	 */
8977 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8978 
8979 	/*
8980 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8981 	 */
8982 	if (rdc == NULL) {
8983 		mutex_exit(&rp->r_statelock);
8984 		return (EINTR);
8985 	}
8986 
8987 	/*
8988 	 * Check to see if we need to fill this entry in.
8989 	 */
8990 	if (rdc->flags & RDDIRREQ) {
8991 		rdc->flags &= ~RDDIRREQ;
8992 		rdc->flags |= RDDIR;
8993 		mutex_exit(&rp->r_statelock);
8994 
8995 		/*
8996 		 * Do the readdir.
8997 		 */
8998 		nfs4readdir(vp, rdc, cr);
8999 
9000 		/*
9001 		 * Reacquire the lock, so that we can continue
9002 		 */
9003 		mutex_enter(&rp->r_statelock);
9004 		/*
9005 		 * The entry is now complete
9006 		 */
9007 		rdc->flags &= ~RDDIR;
9008 	}
9009 
9010 	ASSERT(!(rdc->flags & RDDIR));
9011 
9012 	/*
9013 	 * If an error occurred while attempting
9014 	 * to fill the cache entry, mark the entry invalid and
9015 	 * just return the error.
9016 	 */
9017 	if (rdc->error) {
9018 		error = rdc->error;
9019 		rdc->flags |= RDDIRREQ;
9020 		rddir4_cache_rele(rp, rdc);
9021 		mutex_exit(&rp->r_statelock);
9022 		return (error);
9023 	}
9024 
9025 	/*
9026 	 * The cache entry is complete and good,
9027 	 * copyout the dirent structs to the calling
9028 	 * thread.
9029 	 */
9030 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
9031 
9032 	/*
9033 	 * If no error occurred during the copyout,
9034 	 * update the offset in the uio struct to
9035 	 * contain the value of the next NFS 4 cookie
9036 	 * and set the eof value appropriately.
9037 	 */
9038 	if (!error) {
9039 		uiop->uio_loffset = rdc->nfs4_ncookie;
9040 		if (eofp)
9041 			*eofp = rdc->eof;
9042 	}
9043 
9044 	/*
9045 	 * Decide whether to do readahead.  Don't if we
9046 	 * have already read to the end of directory.
9047 	 */
9048 	if (rdc->eof) {
9049 		/*
9050 		 * Make the entry the direof only if it is cached
9051 		 */
9052 		if (rdc->flags & RDDIRCACHED)
9053 			rp->r_direof = rdc;
9054 		rddir4_cache_rele(rp, rdc);
9055 		mutex_exit(&rp->r_statelock);
9056 		return (error);
9057 	}
9058 
9059 	/* Determine if a readdir readahead should be done */
9060 	if (!(rp->r_flags & R4LOOKUP)) {
9061 		rddir4_cache_rele(rp, rdc);
9062 		mutex_exit(&rp->r_statelock);
9063 		return (error);
9064 	}
9065 
9066 	/*
9067 	 * Now look for a readahead entry.
9068 	 *
9069 	 * Check to see whether we found an entry for the readahead.
9070 	 * If so, we don't need to do anything further, so free the new
9071 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
9072 	 * it to the cache, and then initiate an asynchronous readdir
9073 	 * operation to fill it.
9074 	 */
9075 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
9076 
9077 	/*
9078 	 * A readdir cache entry could not be obtained for the readahead.  In
9079 	 * this case we skip the readahead and return.
9080 	 */
9081 	if (rrdc == NULL) {
9082 		rddir4_cache_rele(rp, rdc);
9083 		mutex_exit(&rp->r_statelock);
9084 		return (error);
9085 	}
9086 
9087 	/*
9088 	 * Check to see if we need to fill this entry in.
9089 	 */
9090 	if (rrdc->flags & RDDIRREQ) {
9091 		rrdc->flags &= ~RDDIRREQ;
9092 		rrdc->flags |= RDDIR;
9093 		rddir4_cache_rele(rp, rdc);
9094 		mutex_exit(&rp->r_statelock);
9095 #ifdef DEBUG
9096 		nfs4_readdir_readahead++;
9097 #endif
9098 		/*
9099 		 * Do the readdir.
9100 		 */
9101 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
9102 		return (error);
9103 	}
9104 
9105 	rddir4_cache_rele(rp, rrdc);
9106 	rddir4_cache_rele(rp, rdc);
9107 	mutex_exit(&rp->r_statelock);
9108 	return (error);
9109 }
9110 
9111 static int
9112 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9113 {
9114 	int error;
9115 	rnode4_t *rp;
9116 
9117 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9118 
9119 	rp = VTOR4(vp);
9120 
9121 	/*
9122 	 * Obtain the readdir results for the caller.
9123 	 */
9124 	nfs4readdir(vp, rdc, cr);
9125 
9126 	mutex_enter(&rp->r_statelock);
9127 	/*
9128 	 * The entry is now complete
9129 	 */
9130 	rdc->flags &= ~RDDIR;
9131 
9132 	error = rdc->error;
9133 	if (error)
9134 		rdc->flags |= RDDIRREQ;
9135 	rddir4_cache_rele(rp, rdc);
9136 	mutex_exit(&rp->r_statelock);
9137 
9138 	return (error);
9139 }
9140 
9141 /*
9142  * Read directory entries.
9143  * There are some weird things to look out for here.  The uio_loffset
9144  * field is either 0 or it is the offset returned from a previous
9145  * readdir.  It is an opaque value used by the server to find the
9146  * correct directory block to read. The count field is the number
9147  * of blocks to read on the server.  This is advisory only, the server
9148  * may return only one block's worth of entries.  Entries may be compressed
9149  * on the server.
9150  *
9151  * Generates the following compound request:
9152  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9153  *    must include a Lookupp as well. In this case, send:
9154  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9155  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9156  *
9157  * Get complete attributes and filehandles for entries if this is the
9158  * first read of the directory. Otherwise, just get fileid's.
9159  */
9160 static void
9161 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9162 {
9163 	COMPOUND4args_clnt args;
9164 	COMPOUND4res_clnt res;
9165 	READDIR4args *rargs;
9166 	READDIR4res_clnt *rd_res;
9167 	bitmap4 rd_bitsval;
9168 	nfs_argop4 argop[5];
9169 	nfs_resop4 *resop;
9170 	rnode4_t *rp = VTOR4(vp);
9171 	mntinfo4_t *mi = VTOMI4(vp);
9172 	int doqueue;
9173 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9174 	vnode_t *dvp;
9175 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9176 	int num_ops, res_opcnt;
9177 	bool_t needrecov = FALSE;
9178 	nfs4_recov_state_t recov_state;
9179 	hrtime_t t;
9180 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9181 
9182 	ASSERT(nfs_zone() == mi->mi_zone);
9183 	ASSERT(rdc->flags & RDDIR);
9184 	ASSERT(rdc->entries == NULL);
9185 
9186 	/*
9187 	 * If rp were a stub, it should have triggered and caused
9188 	 * a mount for us to get this far.
9189 	 */
9190 	ASSERT(!RP_ISSTUB(rp));
9191 
9192 	num_ops = 2;
9193 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9194 		/*
9195 		 * Since nfsv4 readdir may not return entries for "." and "..",
9196 		 * the client must recreate them:
9197 		 * To find the correct nodeid, do the following:
9198 		 * For current node, get nodeid from dnlc.
9199 		 * - if current node is rootvp, set pnodeid to nodeid.
9200 		 * - else if parent is in the dnlc, get its nodeid from there.
9201 		 * - else add LOOKUPP+GETATTR to compound.
9202 		 */
9203 		nodeid = rp->r_attr.va_nodeid;
9204 		if (vp->v_flag & VROOT) {
9205 			pnodeid = nodeid;	/* root of mount point */
9206 		} else {
9207 			dvp = dnlc_lookup(vp, "..");
9208 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9209 				/* parent in dnlc cache - no need for otw */
9210 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9211 			} else {
9212 				/*
9213 				 * parent not in dnlc cache,
9214 				 * do lookupp to get its id
9215 				 */
9216 				num_ops = 5;
9217 				pnodeid = 0; /* set later by getattr parent */
9218 			}
9219 			if (dvp)
9220 				VN_RELE(dvp);
9221 		}
9222 	}
9223 	recov_state.rs_flags = 0;
9224 	recov_state.rs_num_retry_despite_err = 0;
9225 
9226 	/* Save the original mount point security flavor */
9227 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9228 
9229 recov_retry:
9230 	args.ctag = TAG_READDIR;
9231 
9232 	args.array = argop;
9233 	args.array_len = num_ops;
9234 
9235 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9236 	    &recov_state, NULL)) {
9237 		/*
9238 		 * If readdir a node that is a stub for a crossed mount point,
9239 		 * keep the original secinfo flavor for the current file
9240 		 * system, not the crossed one.
9241 		 */
9242 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9243 		rdc->error = e.error;
9244 		return;
9245 	}
9246 
9247 	/*
9248 	 * Determine which attrs to request for dirents.  This code
9249 	 * must be protected by nfs4_start/end_fop because of r_server
9250 	 * (which will change during failover recovery).
9251 	 *
9252 	 */
9253 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9254 		/*
9255 		 * Get all vattr attrs plus filehandle and rdattr_error
9256 		 */
9257 		rd_bitsval = NFS4_VATTR_MASK |
9258 		    FATTR4_RDATTR_ERROR_MASK |
9259 		    FATTR4_FILEHANDLE_MASK;
9260 
9261 		if (rp->r_flags & R4READDIRWATTR) {
9262 			mutex_enter(&rp->r_statelock);
9263 			rp->r_flags &= ~R4READDIRWATTR;
9264 			mutex_exit(&rp->r_statelock);
9265 		}
9266 	} else {
9267 		servinfo4_t *svp = rp->r_server;
9268 
9269 		/*
9270 		 * Already read directory. Use readdir with
9271 		 * no attrs (except for mounted_on_fileid) for updates.
9272 		 */
9273 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9274 
9275 		/*
9276 		 * request mounted on fileid if supported, else request
9277 		 * fileid.  maybe we should verify that fileid is supported
9278 		 * and request something else if not.
9279 		 */
9280 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9281 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9282 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9283 		nfs_rw_exit(&svp->sv_lock);
9284 	}
9285 
9286 	/* putfh directory fh */
9287 	argop[0].argop = OP_CPUTFH;
9288 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9289 
9290 	argop[1].argop = OP_READDIR;
9291 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9292 	/*
9293 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9294 	 * cookie 0 should be used over-the-wire to start reading at
9295 	 * the beginning of the directory excluding "." and "..".
9296 	 */
9297 	if (rdc->nfs4_cookie == 0 ||
9298 	    rdc->nfs4_cookie == 1 ||
9299 	    rdc->nfs4_cookie == 2) {
9300 		rargs->cookie = (nfs_cookie4)0;
9301 		rargs->cookieverf = 0;
9302 	} else {
9303 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9304 		mutex_enter(&rp->r_statelock);
9305 		rargs->cookieverf = rp->r_cookieverf4;
9306 		mutex_exit(&rp->r_statelock);
9307 	}
9308 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9309 	rargs->maxcount = mi->mi_tsize;
9310 	rargs->attr_request = rd_bitsval;
9311 	rargs->rdc = rdc;
9312 	rargs->dvp = vp;
9313 	rargs->mi = mi;
9314 	rargs->cr = cr;
9315 
9316 
9317 	/*
9318 	 * If count < than the minimum required, we return no entries
9319 	 * and fail with EINVAL
9320 	 */
9321 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9322 		rdc->error = EINVAL;
9323 		goto out;
9324 	}
9325 
9326 	if (args.array_len == 5) {
9327 		/*
9328 		 * Add lookupp and getattr for parent nodeid.
9329 		 */
9330 		argop[2].argop = OP_LOOKUPP;
9331 
9332 		argop[3].argop = OP_GETFH;
9333 
9334 		/* getattr parent */
9335 		argop[4].argop = OP_GETATTR;
9336 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9337 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9338 	}
9339 
9340 	doqueue = 1;
9341 
9342 	if (mi->mi_io_kstats) {
9343 		mutex_enter(&mi->mi_lock);
9344 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9345 		mutex_exit(&mi->mi_lock);
9346 	}
9347 
9348 	/* capture the time of this call */
9349 	rargs->t = t = gethrtime();
9350 
9351 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9352 
9353 	if (mi->mi_io_kstats) {
9354 		mutex_enter(&mi->mi_lock);
9355 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9356 		mutex_exit(&mi->mi_lock);
9357 	}
9358 
9359 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9360 
9361 	/*
9362 	 * If RPC error occurred and it isn't an error that
9363 	 * triggers recovery, then go ahead and fail now.
9364 	 */
9365 	if (e.error != 0 && !needrecov) {
9366 		rdc->error = e.error;
9367 		goto out;
9368 	}
9369 
9370 	if (needrecov) {
9371 		bool_t abort;
9372 
9373 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9374 		    "nfs4readdir: initiating recovery.\n"));
9375 
9376 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9377 		    NULL, OP_READDIR, NULL, NULL, NULL);
9378 		if (abort == FALSE) {
9379 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9380 			    &recov_state, needrecov);
9381 			if (!e.error)
9382 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9383 				    (caddr_t)&res);
9384 			if (rdc->entries != NULL) {
9385 				kmem_free(rdc->entries, rdc->entlen);
9386 				rdc->entries = NULL;
9387 			}
9388 			goto recov_retry;
9389 		}
9390 
9391 		if (e.error != 0) {
9392 			rdc->error = e.error;
9393 			goto out;
9394 		}
9395 
9396 		/* fall through for res.status case */
9397 	}
9398 
9399 	res_opcnt = res.array_len;
9400 
9401 	/*
9402 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9403 	 * failure here.  Subsequent ops are for filling out dot-dot
9404 	 * dirent, and if they fail, we still want to give the caller
9405 	 * the dirents returned by (the successful) READDIR op, so we need
9406 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9407 	 *
9408 	 * One example where PUTFH+READDIR ops would succeed but
9409 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9410 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9411 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9412 	 * x perm.  We need to come up with a non-vendor-specific way
9413 	 * for a POSIX server to return d_ino from dotdot's dirent if
9414 	 * client only requests mounted_on_fileid, and just say the
9415 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9416 	 * client requested any mandatory attrs, server would be required
9417 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9418 	 * for dotdot.
9419 	 */
9420 
9421 	if (res.status) {
9422 		if (res_opcnt <= 2) {
9423 			e.error = geterrno4(res.status);
9424 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9425 			    &recov_state, needrecov);
9426 			nfs4_purge_stale_fh(e.error, vp, cr);
9427 			rdc->error = e.error;
9428 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9429 			if (rdc->entries != NULL) {
9430 				kmem_free(rdc->entries, rdc->entlen);
9431 				rdc->entries = NULL;
9432 			}
9433 			/*
9434 			 * If readdir a node that is a stub for a
9435 			 * crossed mount point, keep the original
9436 			 * secinfo flavor for the current file system,
9437 			 * not the crossed one.
9438 			 */
9439 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9440 			return;
9441 		}
9442 	}
9443 
9444 	resop = &res.array[1];	/* readdir res */
9445 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9446 
9447 	mutex_enter(&rp->r_statelock);
9448 	rp->r_cookieverf4 = rd_res->cookieverf;
9449 	mutex_exit(&rp->r_statelock);
9450 
9451 	/*
9452 	 * For "." and ".." entries
9453 	 * e.g.
9454 	 *	seek(cookie=0) -> "." entry with d_off = 1
9455 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9456 	 */
9457 	if (cookie == (nfs_cookie4) 0) {
9458 		if (rd_res->dotp)
9459 			rd_res->dotp->d_ino = nodeid;
9460 		if (rd_res->dotdotp)
9461 			rd_res->dotdotp->d_ino = pnodeid;
9462 	}
9463 	if (cookie == (nfs_cookie4) 1) {
9464 		if (rd_res->dotdotp)
9465 			rd_res->dotdotp->d_ino = pnodeid;
9466 	}
9467 
9468 
9469 	/* LOOKUPP+GETATTR attemped */
9470 	if (args.array_len == 5 && rd_res->dotdotp) {
9471 		if (res.status == NFS4_OK && res_opcnt == 5) {
9472 			nfs_fh4 *fhp;
9473 			nfs4_sharedfh_t *sfhp;
9474 			vnode_t *pvp;
9475 			nfs4_ga_res_t *garp;
9476 
9477 			resop++;	/* lookupp */
9478 			resop++;	/* getfh   */
9479 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9480 
9481 			resop++;	/* getattr of parent */
9482 
9483 			/*
9484 			 * First, take care of finishing the
9485 			 * readdir results.
9486 			 */
9487 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9488 			/*
9489 			 * The d_ino of .. must be the inode number
9490 			 * of the mounted filesystem.
9491 			 */
9492 			if (garp->n4g_va.va_mask & AT_NODEID)
9493 				rd_res->dotdotp->d_ino =
9494 				    garp->n4g_va.va_nodeid;
9495 
9496 
9497 			/*
9498 			 * Next, create the ".." dnlc entry
9499 			 */
9500 			sfhp = sfh4_get(fhp, mi);
9501 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9502 				dnlc_update(vp, "..", pvp);
9503 				VN_RELE(pvp);
9504 			}
9505 			sfh4_rele(&sfhp);
9506 		}
9507 	}
9508 
9509 	if (mi->mi_io_kstats) {
9510 		mutex_enter(&mi->mi_lock);
9511 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9512 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9513 		mutex_exit(&mi->mi_lock);
9514 	}
9515 
9516 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9517 
9518 out:
9519 	/*
9520 	 * If readdir a node that is a stub for a crossed mount point,
9521 	 * keep the original secinfo flavor for the current file system,
9522 	 * not the crossed one.
9523 	 */
9524 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9525 
9526 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9527 }
9528 
9529 
9530 static int
9531 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9532 {
9533 	rnode4_t *rp = VTOR4(bp->b_vp);
9534 	int count;
9535 	int error;
9536 	cred_t *cred_otw = NULL;
9537 	offset_t offset;
9538 	nfs4_open_stream_t *osp = NULL;
9539 	bool_t first_time = TRUE;	/* first time getting otw cred */
9540 	bool_t last_time = FALSE;	/* last time getting otw cred */
9541 
9542 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9543 
9544 	DTRACE_IO1(start, struct buf *, bp);
9545 	offset = ldbtob(bp->b_lblkno);
9546 
9547 	if (bp->b_flags & B_READ) {
9548 	read_again:
9549 		/*
9550 		 * Releases the osp, if it is provided.
9551 		 * Puts a hold on the cred_otw and the new osp (if found).
9552 		 */
9553 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9554 		    &first_time, &last_time);
9555 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9556 		    offset, bp->b_bcount, &bp->b_resid, cred_otw,
9557 		    readahead, NULL);
9558 		crfree(cred_otw);
9559 		if (!error) {
9560 			if (bp->b_resid) {
9561 				/*
9562 				 * Didn't get it all because we hit EOF,
9563 				 * zero all the memory beyond the EOF.
9564 				 */
9565 				/* bzero(rdaddr + */
9566 				bzero(bp->b_un.b_addr +
9567 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9568 			}
9569 			mutex_enter(&rp->r_statelock);
9570 			if (bp->b_resid == bp->b_bcount &&
9571 			    offset >= rp->r_size) {
9572 				/*
9573 				 * We didn't read anything at all as we are
9574 				 * past EOF.  Return an error indicator back
9575 				 * but don't destroy the pages (yet).
9576 				 */
9577 				error = NFS_EOF;
9578 			}
9579 			mutex_exit(&rp->r_statelock);
9580 		} else if (error == EACCES && last_time == FALSE) {
9581 				goto read_again;
9582 		}
9583 	} else {
9584 		if (!(rp->r_flags & R4STALE)) {
9585 write_again:
9586 			/*
9587 			 * Releases the osp, if it is provided.
9588 			 * Puts a hold on the cred_otw and the new
9589 			 * osp (if found).
9590 			 */
9591 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9592 			    &first_time, &last_time);
9593 			mutex_enter(&rp->r_statelock);
9594 			count = MIN(bp->b_bcount, rp->r_size - offset);
9595 			mutex_exit(&rp->r_statelock);
9596 			if (count < 0)
9597 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9598 #ifdef DEBUG
9599 			if (count == 0) {
9600 				zoneid_t zoneid = getzoneid();
9601 
9602 				zcmn_err(zoneid, CE_WARN,
9603 				    "nfs4_bio: zero length write at %lld",
9604 				    offset);
9605 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9606 				    "b_bcount=%ld, file size=%lld",
9607 				    rp->r_flags, (long)bp->b_bcount,
9608 				    rp->r_size);
9609 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9610 				if (nfs4_bio_do_stop)
9611 					debug_enter("nfs4_bio");
9612 			}
9613 #endif
9614 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9615 			    count, cred_otw, stab_comm);
9616 			if (error == EACCES && last_time == FALSE) {
9617 				crfree(cred_otw);
9618 				goto write_again;
9619 			}
9620 			bp->b_error = error;
9621 			if (error && error != EINTR &&
9622 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9623 				/*
9624 				 * Don't print EDQUOT errors on the console.
9625 				 * Don't print asynchronous EACCES errors.
9626 				 * Don't print EFBIG errors.
9627 				 * Print all other write errors.
9628 				 */
9629 				if (error != EDQUOT && error != EFBIG &&
9630 				    (error != EACCES ||
9631 				    !(bp->b_flags & B_ASYNC)))
9632 					nfs4_write_error(bp->b_vp,
9633 					    error, cred_otw);
9634 				/*
9635 				 * Update r_error and r_flags as appropriate.
9636 				 * If the error was ESTALE, then mark the
9637 				 * rnode as not being writeable and save
9638 				 * the error status.  Otherwise, save any
9639 				 * errors which occur from asynchronous
9640 				 * page invalidations.  Any errors occurring
9641 				 * from other operations should be saved
9642 				 * by the caller.
9643 				 */
9644 				mutex_enter(&rp->r_statelock);
9645 				if (error == ESTALE) {
9646 					rp->r_flags |= R4STALE;
9647 					if (!rp->r_error)
9648 						rp->r_error = error;
9649 				} else if (!rp->r_error &&
9650 				    (bp->b_flags &
9651 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9652 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9653 					rp->r_error = error;
9654 				}
9655 				mutex_exit(&rp->r_statelock);
9656 			}
9657 			crfree(cred_otw);
9658 		} else {
9659 			error = rp->r_error;
9660 			/*
9661 			 * A close may have cleared r_error, if so,
9662 			 * propagate ESTALE error return properly
9663 			 */
9664 			if (error == 0)
9665 				error = ESTALE;
9666 		}
9667 	}
9668 
9669 	if (error != 0 && error != NFS_EOF)
9670 		bp->b_flags |= B_ERROR;
9671 
9672 	if (osp)
9673 		open_stream_rele(osp, rp);
9674 
9675 	DTRACE_IO1(done, struct buf *, bp);
9676 
9677 	return (error);
9678 }
9679 
9680 /* ARGSUSED */
9681 int
9682 nfs4_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
9683 {
9684 	return (EREMOTE);
9685 }
9686 
9687 /* ARGSUSED2 */
9688 int
9689 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9690 {
9691 	rnode4_t *rp = VTOR4(vp);
9692 
9693 	if (!write_lock) {
9694 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9695 		return (V_WRITELOCK_FALSE);
9696 	}
9697 
9698 	if ((rp->r_flags & R4DIRECTIO) ||
9699 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9700 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9701 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9702 			return (V_WRITELOCK_FALSE);
9703 		nfs_rw_exit(&rp->r_rwlock);
9704 	}
9705 
9706 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9707 	return (V_WRITELOCK_TRUE);
9708 }
9709 
9710 /* ARGSUSED */
9711 void
9712 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9713 {
9714 	rnode4_t *rp = VTOR4(vp);
9715 
9716 	nfs_rw_exit(&rp->r_rwlock);
9717 }
9718 
9719 /* ARGSUSED */
9720 static int
9721 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp, caller_context_t *ct)
9722 {
9723 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9724 		return (EIO);
9725 
9726 	/*
9727 	 * Because we stuff the readdir cookie into the offset field
9728 	 * someone may attempt to do an lseek with the cookie which
9729 	 * we want to succeed.
9730 	 */
9731 	if (vp->v_type == VDIR)
9732 		return (0);
9733 	if (*noffp < 0)
9734 		return (EINVAL);
9735 	return (0);
9736 }
9737 
9738 
9739 /*
9740  * Return all the pages from [off..off+len) in file
9741  */
9742 /* ARGSUSED */
9743 static int
9744 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9745     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9746     enum seg_rw rw, cred_t *cr, caller_context_t *ct)
9747 {
9748 	rnode4_t *rp;
9749 	int error;
9750 	mntinfo4_t *mi;
9751 
9752 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9753 		return (EIO);
9754 	rp = VTOR4(vp);
9755 	if (IS_SHADOW(vp, rp))
9756 		vp = RTOV4(rp);
9757 
9758 	if (vp->v_flag & VNOMAP)
9759 		return (ENOSYS);
9760 
9761 	if (protp != NULL)
9762 		*protp = PROT_ALL;
9763 
9764 	/*
9765 	 * Now validate that the caches are up to date.
9766 	 */
9767 	if (error = nfs4_validate_caches(vp, cr))
9768 		return (error);
9769 
9770 	mi = VTOMI4(vp);
9771 retry:
9772 	mutex_enter(&rp->r_statelock);
9773 
9774 	/*
9775 	 * Don't create dirty pages faster than they
9776 	 * can be cleaned so that the system doesn't
9777 	 * get imbalanced.  If the async queue is
9778 	 * maxed out, then wait for it to drain before
9779 	 * creating more dirty pages.  Also, wait for
9780 	 * any threads doing pagewalks in the vop_getattr
9781 	 * entry points so that they don't block for
9782 	 * long periods.
9783 	 */
9784 	if (rw == S_CREATE) {
9785 		while ((mi->mi_max_threads != 0 &&
9786 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
9787 		    rp->r_gcount > 0)
9788 			cv_wait(&rp->r_cv, &rp->r_statelock);
9789 	}
9790 
9791 	/*
9792 	 * If we are getting called as a side effect of an nfs_write()
9793 	 * operation the local file size might not be extended yet.
9794 	 * In this case we want to be able to return pages of zeroes.
9795 	 */
9796 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9797 		NFS4_DEBUG(nfs4_pageio_debug,
9798 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9799 		    "len=%llu, size=%llu, attrsize =%llu", off,
9800 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9801 		mutex_exit(&rp->r_statelock);
9802 		return (EFAULT);		/* beyond EOF */
9803 	}
9804 
9805 	mutex_exit(&rp->r_statelock);
9806 
9807 	error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9808 	    pl, plsz, seg, addr, rw, cr);
9809 	NFS4_DEBUG(nfs4_pageio_debug && error,
9810 	    (CE_NOTE, "getpages error %d; off=%lld, len=%lld",
9811 	    error, off, (u_longlong_t)len));
9812 
9813 	switch (error) {
9814 	case NFS_EOF:
9815 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9816 		goto retry;
9817 	case ESTALE:
9818 		nfs4_purge_stale_fh(error, vp, cr);
9819 	}
9820 
9821 	return (error);
9822 }
9823 
9824 /*
9825  * Called from pvn_getpages to get a particular page.
9826  */
9827 /* ARGSUSED */
9828 static int
9829 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9830     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9831     enum seg_rw rw, cred_t *cr)
9832 {
9833 	rnode4_t *rp;
9834 	uint_t bsize;
9835 	struct buf *bp;
9836 	page_t *pp;
9837 	u_offset_t lbn;
9838 	u_offset_t io_off;
9839 	u_offset_t blkoff;
9840 	u_offset_t rablkoff;
9841 	size_t io_len;
9842 	uint_t blksize;
9843 	int error;
9844 	int readahead;
9845 	int readahead_issued = 0;
9846 	int ra_window; /* readahead window */
9847 	page_t *pagefound;
9848 	page_t *savepp;
9849 
9850 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9851 		return (EIO);
9852 
9853 	rp = VTOR4(vp);
9854 	ASSERT(!IS_SHADOW(vp, rp));
9855 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9856 
9857 reread:
9858 	bp = NULL;
9859 	pp = NULL;
9860 	pagefound = NULL;
9861 
9862 	if (pl != NULL)
9863 		pl[0] = NULL;
9864 
9865 	error = 0;
9866 	lbn = off / bsize;
9867 	blkoff = lbn * bsize;
9868 
9869 	/*
9870 	 * Queueing up the readahead before doing the synchronous read
9871 	 * results in a significant increase in read throughput because
9872 	 * of the increased parallelism between the async threads and
9873 	 * the process context.
9874 	 */
9875 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9876 	    rw != S_CREATE &&
9877 	    !(vp->v_flag & VNOCACHE)) {
9878 		mutex_enter(&rp->r_statelock);
9879 
9880 		/*
9881 		 * Calculate the number of readaheads to do.
9882 		 * a) No readaheads at offset = 0.
9883 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9884 		 *    window is closed.
9885 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9886 		 *    upon how far the readahead window is open or close.
9887 		 * d) No readaheads if rp->r_nextr is not within the scope
9888 		 *    of the readahead window (random i/o).
9889 		 */
9890 
9891 		if (off == 0)
9892 			readahead = 0;
9893 		else if (blkoff == rp->r_nextr)
9894 			readahead = nfs4_nra;
9895 		else if (rp->r_nextr > blkoff &&
9896 		    ((ra_window = (rp->r_nextr - blkoff) / bsize)
9897 		    <= (nfs4_nra - 1)))
9898 			readahead = nfs4_nra - ra_window;
9899 		else
9900 			readahead = 0;
9901 
9902 		rablkoff = rp->r_nextr;
9903 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9904 			mutex_exit(&rp->r_statelock);
9905 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9906 			    addr + (rablkoff + bsize - off),
9907 			    seg, cr, nfs4_readahead) < 0) {
9908 				mutex_enter(&rp->r_statelock);
9909 				break;
9910 			}
9911 			readahead--;
9912 			rablkoff += bsize;
9913 			/*
9914 			 * Indicate that we did a readahead so
9915 			 * readahead offset is not updated
9916 			 * by the synchronous read below.
9917 			 */
9918 			readahead_issued = 1;
9919 			mutex_enter(&rp->r_statelock);
9920 			/*
9921 			 * set readahead offset to
9922 			 * offset of last async readahead
9923 			 * request.
9924 			 */
9925 			rp->r_nextr = rablkoff;
9926 		}
9927 		mutex_exit(&rp->r_statelock);
9928 	}
9929 
9930 again:
9931 	if ((pagefound = page_exists(vp, off)) == NULL) {
9932 		if (pl == NULL) {
9933 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9934 			    nfs4_readahead);
9935 		} else if (rw == S_CREATE) {
9936 			/*
9937 			 * Block for this page is not allocated, or the offset
9938 			 * is beyond the current allocation size, or we're
9939 			 * allocating a swap slot and the page was not found,
9940 			 * so allocate it and return a zero page.
9941 			 */
9942 			if ((pp = page_create_va(vp, off,
9943 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9944 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9945 			io_len = PAGESIZE;
9946 			mutex_enter(&rp->r_statelock);
9947 			rp->r_nextr = off + PAGESIZE;
9948 			mutex_exit(&rp->r_statelock);
9949 		} else {
9950 			/*
9951 			 * Need to go to server to get a block
9952 			 */
9953 			mutex_enter(&rp->r_statelock);
9954 			if (blkoff < rp->r_size &&
9955 			    blkoff + bsize > rp->r_size) {
9956 				/*
9957 				 * If less than a block left in
9958 				 * file read less than a block.
9959 				 */
9960 				if (rp->r_size <= off) {
9961 					/*
9962 					 * Trying to access beyond EOF,
9963 					 * set up to get at least one page.
9964 					 */
9965 					blksize = off + PAGESIZE - blkoff;
9966 				} else
9967 					blksize = rp->r_size - blkoff;
9968 			} else if ((off == 0) ||
9969 			    (off != rp->r_nextr && !readahead_issued)) {
9970 				blksize = PAGESIZE;
9971 				blkoff = off; /* block = page here */
9972 			} else
9973 				blksize = bsize;
9974 			mutex_exit(&rp->r_statelock);
9975 
9976 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9977 			    &io_len, blkoff, blksize, 0);
9978 
9979 			/*
9980 			 * Some other thread has entered the page,
9981 			 * so just use it.
9982 			 */
9983 			if (pp == NULL)
9984 				goto again;
9985 
9986 			/*
9987 			 * Now round the request size up to page boundaries.
9988 			 * This ensures that the entire page will be
9989 			 * initialized to zeroes if EOF is encountered.
9990 			 */
9991 			io_len = ptob(btopr(io_len));
9992 
9993 			bp = pageio_setup(pp, io_len, vp, B_READ);
9994 			ASSERT(bp != NULL);
9995 
9996 			/*
9997 			 * pageio_setup should have set b_addr to 0.  This
9998 			 * is correct since we want to do I/O on a page
9999 			 * boundary.  bp_mapin will use this addr to calculate
10000 			 * an offset, and then set b_addr to the kernel virtual
10001 			 * address it allocated for us.
10002 			 */
10003 			ASSERT(bp->b_un.b_addr == 0);
10004 
10005 			bp->b_edev = 0;
10006 			bp->b_dev = 0;
10007 			bp->b_lblkno = lbtodb(io_off);
10008 			bp->b_file = vp;
10009 			bp->b_offset = (offset_t)off;
10010 			bp_mapin(bp);
10011 
10012 			/*
10013 			 * If doing a write beyond what we believe is EOF,
10014 			 * don't bother trying to read the pages from the
10015 			 * server, we'll just zero the pages here.  We
10016 			 * don't check that the rw flag is S_WRITE here
10017 			 * because some implementations may attempt a
10018 			 * read access to the buffer before copying data.
10019 			 */
10020 			mutex_enter(&rp->r_statelock);
10021 			if (io_off >= rp->r_size && seg == segkmap) {
10022 				mutex_exit(&rp->r_statelock);
10023 				bzero(bp->b_un.b_addr, io_len);
10024 			} else {
10025 				mutex_exit(&rp->r_statelock);
10026 				error = nfs4_bio(bp, NULL, cr, FALSE);
10027 			}
10028 
10029 			/*
10030 			 * Unmap the buffer before freeing it.
10031 			 */
10032 			bp_mapout(bp);
10033 			pageio_done(bp);
10034 
10035 			savepp = pp;
10036 			do {
10037 				pp->p_fsdata = C_NOCOMMIT;
10038 			} while ((pp = pp->p_next) != savepp);
10039 
10040 			if (error == NFS_EOF) {
10041 				/*
10042 				 * If doing a write system call just return
10043 				 * zeroed pages, else user tried to get pages
10044 				 * beyond EOF, return error.  We don't check
10045 				 * that the rw flag is S_WRITE here because
10046 				 * some implementations may attempt a read
10047 				 * access to the buffer before copying data.
10048 				 */
10049 				if (seg == segkmap)
10050 					error = 0;
10051 				else
10052 					error = EFAULT;
10053 			}
10054 
10055 			if (!readahead_issued && !error) {
10056 				mutex_enter(&rp->r_statelock);
10057 				rp->r_nextr = io_off + io_len;
10058 				mutex_exit(&rp->r_statelock);
10059 			}
10060 		}
10061 	}
10062 
10063 out:
10064 	if (pl == NULL)
10065 		return (error);
10066 
10067 	if (error) {
10068 		if (pp != NULL)
10069 			pvn_read_done(pp, B_ERROR);
10070 		return (error);
10071 	}
10072 
10073 	if (pagefound) {
10074 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
10075 
10076 		/*
10077 		 * Page exists in the cache, acquire the appropriate lock.
10078 		 * If this fails, start all over again.
10079 		 */
10080 		if ((pp = page_lookup(vp, off, se)) == NULL) {
10081 #ifdef DEBUG
10082 			nfs4_lostpage++;
10083 #endif
10084 			goto reread;
10085 		}
10086 		pl[0] = pp;
10087 		pl[1] = NULL;
10088 		return (0);
10089 	}
10090 
10091 	if (pp != NULL)
10092 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
10093 
10094 	return (error);
10095 }
10096 
10097 static void
10098 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
10099     cred_t *cr)
10100 {
10101 	int error;
10102 	page_t *pp;
10103 	u_offset_t io_off;
10104 	size_t io_len;
10105 	struct buf *bp;
10106 	uint_t bsize, blksize;
10107 	rnode4_t *rp = VTOR4(vp);
10108 	page_t *savepp;
10109 
10110 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10111 
10112 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10113 
10114 	mutex_enter(&rp->r_statelock);
10115 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
10116 		/*
10117 		 * If less than a block left in file read less
10118 		 * than a block.
10119 		 */
10120 		blksize = rp->r_size - blkoff;
10121 	} else
10122 		blksize = bsize;
10123 	mutex_exit(&rp->r_statelock);
10124 
10125 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
10126 	    &io_off, &io_len, blkoff, blksize, 1);
10127 	/*
10128 	 * The isra flag passed to the kluster function is 1, we may have
10129 	 * gotten a return value of NULL for a variety of reasons (# of free
10130 	 * pages < minfree, someone entered the page on the vnode etc). In all
10131 	 * cases, we want to punt on the readahead.
10132 	 */
10133 	if (pp == NULL)
10134 		return;
10135 
10136 	/*
10137 	 * Now round the request size up to page boundaries.
10138 	 * This ensures that the entire page will be
10139 	 * initialized to zeroes if EOF is encountered.
10140 	 */
10141 	io_len = ptob(btopr(io_len));
10142 
10143 	bp = pageio_setup(pp, io_len, vp, B_READ);
10144 	ASSERT(bp != NULL);
10145 
10146 	/*
10147 	 * pageio_setup should have set b_addr to 0.  This is correct since
10148 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10149 	 * to calculate an offset, and then set b_addr to the kernel virtual
10150 	 * address it allocated for us.
10151 	 */
10152 	ASSERT(bp->b_un.b_addr == 0);
10153 
10154 	bp->b_edev = 0;
10155 	bp->b_dev = 0;
10156 	bp->b_lblkno = lbtodb(io_off);
10157 	bp->b_file = vp;
10158 	bp->b_offset = (offset_t)blkoff;
10159 	bp_mapin(bp);
10160 
10161 	/*
10162 	 * If doing a write beyond what we believe is EOF, don't bother trying
10163 	 * to read the pages from the server, we'll just zero the pages here.
10164 	 * We don't check that the rw flag is S_WRITE here because some
10165 	 * implementations may attempt a read access to the buffer before
10166 	 * copying data.
10167 	 */
10168 	mutex_enter(&rp->r_statelock);
10169 	if (io_off >= rp->r_size && seg == segkmap) {
10170 		mutex_exit(&rp->r_statelock);
10171 		bzero(bp->b_un.b_addr, io_len);
10172 		error = 0;
10173 	} else {
10174 		mutex_exit(&rp->r_statelock);
10175 		error = nfs4_bio(bp, NULL, cr, TRUE);
10176 		if (error == NFS_EOF)
10177 			error = 0;
10178 	}
10179 
10180 	/*
10181 	 * Unmap the buffer before freeing it.
10182 	 */
10183 	bp_mapout(bp);
10184 	pageio_done(bp);
10185 
10186 	savepp = pp;
10187 	do {
10188 		pp->p_fsdata = C_NOCOMMIT;
10189 	} while ((pp = pp->p_next) != savepp);
10190 
10191 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10192 
10193 	/*
10194 	 * In case of error set readahead offset
10195 	 * to the lowest offset.
10196 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10197 	 */
10198 	if (error && rp->r_nextr > io_off) {
10199 		mutex_enter(&rp->r_statelock);
10200 		if (rp->r_nextr > io_off)
10201 			rp->r_nextr = io_off;
10202 		mutex_exit(&rp->r_statelock);
10203 	}
10204 }
10205 
10206 /*
10207  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10208  * If len == 0, do from off to EOF.
10209  *
10210  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10211  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10212  * (from pageout).
10213  */
10214 /* ARGSUSED */
10215 static int
10216 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
10217     caller_context_t *ct)
10218 {
10219 	int error;
10220 	rnode4_t *rp;
10221 
10222 	ASSERT(cr != NULL);
10223 
10224 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10225 		return (EIO);
10226 
10227 	rp = VTOR4(vp);
10228 	if (IS_SHADOW(vp, rp))
10229 		vp = RTOV4(rp);
10230 
10231 	/*
10232 	 * XXX - Why should this check be made here?
10233 	 */
10234 	if (vp->v_flag & VNOMAP)
10235 		return (ENOSYS);
10236 
10237 	if (len == 0 && !(flags & B_INVAL) &&
10238 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10239 		return (0);
10240 
10241 	mutex_enter(&rp->r_statelock);
10242 	rp->r_count++;
10243 	mutex_exit(&rp->r_statelock);
10244 	error = nfs4_putpages(vp, off, len, flags, cr);
10245 	mutex_enter(&rp->r_statelock);
10246 	rp->r_count--;
10247 	cv_broadcast(&rp->r_cv);
10248 	mutex_exit(&rp->r_statelock);
10249 
10250 	return (error);
10251 }
10252 
10253 /*
10254  * Write out a single page, possibly klustering adjacent dirty pages.
10255  */
10256 int
10257 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10258     int flags, cred_t *cr)
10259 {
10260 	u_offset_t io_off;
10261 	u_offset_t lbn_off;
10262 	u_offset_t lbn;
10263 	size_t io_len;
10264 	uint_t bsize;
10265 	int error;
10266 	rnode4_t *rp;
10267 
10268 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10269 	ASSERT(pp != NULL);
10270 	ASSERT(cr != NULL);
10271 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10272 
10273 	rp = VTOR4(vp);
10274 	ASSERT(rp->r_count > 0);
10275 	ASSERT(!IS_SHADOW(vp, rp));
10276 
10277 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10278 	lbn = pp->p_offset / bsize;
10279 	lbn_off = lbn * bsize;
10280 
10281 	/*
10282 	 * Find a kluster that fits in one block, or in
10283 	 * one page if pages are bigger than blocks.  If
10284 	 * there is less file space allocated than a whole
10285 	 * page, we'll shorten the i/o request below.
10286 	 */
10287 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10288 	    roundup(bsize, PAGESIZE), flags);
10289 
10290 	/*
10291 	 * pvn_write_kluster shouldn't have returned a page with offset
10292 	 * behind the original page we were given.  Verify that.
10293 	 */
10294 	ASSERT((pp->p_offset / bsize) >= lbn);
10295 
10296 	/*
10297 	 * Now pp will have the list of kept dirty pages marked for
10298 	 * write back.  It will also handle invalidation and freeing
10299 	 * of pages that are not dirty.  Check for page length rounding
10300 	 * problems.
10301 	 */
10302 	if (io_off + io_len > lbn_off + bsize) {
10303 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10304 		io_len = lbn_off + bsize - io_off;
10305 	}
10306 	/*
10307 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10308 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10309 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10310 	 * progress and the r_size has not been made consistent with the
10311 	 * new size of the file. When the uiomove() completes the r_size is
10312 	 * updated and the R4MODINPROGRESS flag is cleared.
10313 	 *
10314 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10315 	 * consistent value of r_size. Without this handshaking, it is
10316 	 * possible that nfs4_bio() picks  up the old value of r_size
10317 	 * before the uiomove() in writerp4() completes. This will result
10318 	 * in the write through nfs4_bio() being dropped.
10319 	 *
10320 	 * More precisely, there is a window between the time the uiomove()
10321 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10322 	 * operation intervenes in this window, the page will be picked up,
10323 	 * because it is dirty (it will be unlocked, unless it was
10324 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10325 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10326 	 * checked. This will still be the old size. Therefore the page will
10327 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10328 	 * the page will be found to be clean and the write will be dropped.
10329 	 */
10330 	if (rp->r_flags & R4MODINPROGRESS) {
10331 		mutex_enter(&rp->r_statelock);
10332 		if ((rp->r_flags & R4MODINPROGRESS) &&
10333 		    rp->r_modaddr + MAXBSIZE > io_off &&
10334 		    rp->r_modaddr < io_off + io_len) {
10335 			page_t *plist;
10336 			/*
10337 			 * A write is in progress for this region of the file.
10338 			 * If we did not detect R4MODINPROGRESS here then this
10339 			 * path through nfs_putapage() would eventually go to
10340 			 * nfs4_bio() and may not write out all of the data
10341 			 * in the pages. We end up losing data. So we decide
10342 			 * to set the modified bit on each page in the page
10343 			 * list and mark the rnode with R4DIRTY. This write
10344 			 * will be restarted at some later time.
10345 			 */
10346 			plist = pp;
10347 			while (plist != NULL) {
10348 				pp = plist;
10349 				page_sub(&plist, pp);
10350 				hat_setmod(pp);
10351 				page_io_unlock(pp);
10352 				page_unlock(pp);
10353 			}
10354 			rp->r_flags |= R4DIRTY;
10355 			mutex_exit(&rp->r_statelock);
10356 			if (offp)
10357 				*offp = io_off;
10358 			if (lenp)
10359 				*lenp = io_len;
10360 			return (0);
10361 		}
10362 		mutex_exit(&rp->r_statelock);
10363 	}
10364 
10365 	if (flags & B_ASYNC) {
10366 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10367 		    nfs4_sync_putapage);
10368 	} else
10369 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10370 
10371 	if (offp)
10372 		*offp = io_off;
10373 	if (lenp)
10374 		*lenp = io_len;
10375 	return (error);
10376 }
10377 
10378 static int
10379 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10380     int flags, cred_t *cr)
10381 {
10382 	int error;
10383 	rnode4_t *rp;
10384 
10385 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10386 
10387 	flags |= B_WRITE;
10388 
10389 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10390 
10391 	rp = VTOR4(vp);
10392 
10393 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10394 	    error == EACCES) &&
10395 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10396 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10397 			mutex_enter(&rp->r_statelock);
10398 			rp->r_flags |= R4OUTOFSPACE;
10399 			mutex_exit(&rp->r_statelock);
10400 		}
10401 		flags |= B_ERROR;
10402 		pvn_write_done(pp, flags);
10403 		/*
10404 		 * If this was not an async thread, then try again to
10405 		 * write out the pages, but this time, also destroy
10406 		 * them whether or not the write is successful.  This
10407 		 * will prevent memory from filling up with these
10408 		 * pages and destroying them is the only alternative
10409 		 * if they can't be written out.
10410 		 *
10411 		 * Don't do this if this is an async thread because
10412 		 * when the pages are unlocked in pvn_write_done,
10413 		 * some other thread could have come along, locked
10414 		 * them, and queued for an async thread.  It would be
10415 		 * possible for all of the async threads to be tied
10416 		 * up waiting to lock the pages again and they would
10417 		 * all already be locked and waiting for an async
10418 		 * thread to handle them.  Deadlock.
10419 		 */
10420 		if (!(flags & B_ASYNC)) {
10421 			error = nfs4_putpage(vp, io_off, io_len,
10422 			    B_INVAL | B_FORCE, cr, NULL);
10423 		}
10424 	} else {
10425 		if (error)
10426 			flags |= B_ERROR;
10427 		else if (rp->r_flags & R4OUTOFSPACE) {
10428 			mutex_enter(&rp->r_statelock);
10429 			rp->r_flags &= ~R4OUTOFSPACE;
10430 			mutex_exit(&rp->r_statelock);
10431 		}
10432 		pvn_write_done(pp, flags);
10433 		if (freemem < desfree)
10434 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10435 			    NFS4_WRITE_NOWAIT);
10436 	}
10437 
10438 	return (error);
10439 }
10440 
10441 #ifdef DEBUG
10442 int nfs4_force_open_before_mmap = 0;
10443 #endif
10444 
10445 /* ARGSUSED */
10446 static int
10447 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10448     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10449     caller_context_t *ct)
10450 {
10451 	struct segvn_crargs vn_a;
10452 	int error = 0;
10453 	rnode4_t *rp = VTOR4(vp);
10454 	mntinfo4_t *mi = VTOMI4(vp);
10455 
10456 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10457 		return (EIO);
10458 
10459 	if (vp->v_flag & VNOMAP)
10460 		return (ENOSYS);
10461 
10462 	if (off < 0 || (off + len) < 0)
10463 		return (ENXIO);
10464 
10465 	if (vp->v_type != VREG)
10466 		return (ENODEV);
10467 
10468 	/*
10469 	 * If the file is delegated to the client don't do anything.
10470 	 * If the file is not delegated, then validate the data cache.
10471 	 */
10472 	mutex_enter(&rp->r_statev4_lock);
10473 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10474 		mutex_exit(&rp->r_statev4_lock);
10475 		error = nfs4_validate_caches(vp, cr);
10476 		if (error)
10477 			return (error);
10478 	} else {
10479 		mutex_exit(&rp->r_statev4_lock);
10480 	}
10481 
10482 	/*
10483 	 * Check to see if the vnode is currently marked as not cachable.
10484 	 * This means portions of the file are locked (through VOP_FRLOCK).
10485 	 * In this case the map request must be refused.  We use
10486 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10487 	 *
10488 	 * Atomically increment r_inmap after acquiring r_rwlock. The
10489 	 * idea here is to acquire r_rwlock to block read/write and
10490 	 * not to protect r_inmap. r_inmap will inform nfs4_read/write()
10491 	 * that we are in nfs4_map(). Now, r_rwlock is acquired in order
10492 	 * and we can prevent the deadlock that would have occurred
10493 	 * when nfs4_addmap() would have acquired it out of order.
10494 	 *
10495 	 * Since we are not protecting r_inmap by any lock, we do not
10496 	 * hold any lock when we decrement it. We atomically decrement
10497 	 * r_inmap after we release r_lkserlock.
10498 	 */
10499 
10500 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR4(vp)))
10501 		return (EINTR);
10502 	atomic_inc_uint(&rp->r_inmap);
10503 	nfs_rw_exit(&rp->r_rwlock);
10504 
10505 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp))) {
10506 		atomic_dec_uint(&rp->r_inmap);
10507 		return (EINTR);
10508 	}
10509 
10510 	if (vp->v_flag & VNOCACHE) {
10511 		error = EAGAIN;
10512 		goto done;
10513 	}
10514 
10515 	/*
10516 	 * Don't allow concurrent locks and mapping if mandatory locking is
10517 	 * enabled.
10518 	 */
10519 	if (flk_has_remote_locks(vp)) {
10520 		struct vattr va;
10521 		va.va_mask = AT_MODE;
10522 		error = nfs4getattr(vp, &va, cr);
10523 		if (error != 0)
10524 			goto done;
10525 		if (MANDLOCK(vp, va.va_mode)) {
10526 			error = EAGAIN;
10527 			goto done;
10528 		}
10529 	}
10530 
10531 	/*
10532 	 * It is possible that the rnode has a lost lock request that we
10533 	 * are still trying to recover, and that the request conflicts with
10534 	 * this map request.
10535 	 *
10536 	 * An alternative approach would be for nfs4_safemap() to consider
10537 	 * queued lock requests when deciding whether to set or clear
10538 	 * VNOCACHE.  This would require the frlock code path to call
10539 	 * nfs4_safemap() after enqueing a lost request.
10540 	 */
10541 	if (nfs4_map_lost_lock_conflict(vp)) {
10542 		error = EAGAIN;
10543 		goto done;
10544 	}
10545 
10546 	as_rangelock(as);
10547 	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
10548 	if (error != 0) {
10549 		as_rangeunlock(as);
10550 		goto done;
10551 	}
10552 
10553 	if (vp->v_type == VREG) {
10554 		/*
10555 		 * We need to retrieve the open stream
10556 		 */
10557 		nfs4_open_stream_t	*osp = NULL;
10558 		nfs4_open_owner_t	*oop = NULL;
10559 
10560 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10561 		if (oop != NULL) {
10562 			/* returns with 'os_sync_lock' held */
10563 			osp = find_open_stream(oop, rp);
10564 			open_owner_rele(oop);
10565 		}
10566 		if (osp == NULL) {
10567 #ifdef DEBUG
10568 			if (nfs4_force_open_before_mmap) {
10569 				error = EIO;
10570 				goto done;
10571 			}
10572 #endif
10573 			/* returns with 'os_sync_lock' held */
10574 			error = open_and_get_osp(vp, cr, &osp);
10575 			if (osp == NULL) {
10576 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10577 				    "nfs4_map: we tried to OPEN the file "
10578 				    "but again no osp, so fail with EIO"));
10579 				goto done;
10580 			}
10581 		}
10582 
10583 		if (osp->os_failed_reopen) {
10584 			mutex_exit(&osp->os_sync_lock);
10585 			open_stream_rele(osp, rp);
10586 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10587 			    "nfs4_map: os_failed_reopen set on "
10588 			    "osp %p, cr %p, rp %s", (void *)osp,
10589 			    (void *)cr, rnode4info(rp)));
10590 			error = EIO;
10591 			goto done;
10592 		}
10593 		mutex_exit(&osp->os_sync_lock);
10594 		open_stream_rele(osp, rp);
10595 	}
10596 
10597 	vn_a.vp = vp;
10598 	vn_a.offset = off;
10599 	vn_a.type = (flags & MAP_TYPE);
10600 	vn_a.prot = (uchar_t)prot;
10601 	vn_a.maxprot = (uchar_t)maxprot;
10602 	vn_a.flags = (flags & ~MAP_TYPE);
10603 	vn_a.cred = cr;
10604 	vn_a.amp = NULL;
10605 	vn_a.szc = 0;
10606 	vn_a.lgrp_mem_policy_flags = 0;
10607 
10608 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10609 	as_rangeunlock(as);
10610 
10611 done:
10612 	nfs_rw_exit(&rp->r_lkserlock);
10613 	atomic_dec_uint(&rp->r_inmap);
10614 	return (error);
10615 }
10616 
10617 /*
10618  * We're most likely dealing with a kernel module that likes to READ
10619  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10620  * officially OPEN the file to create the necessary client state
10621  * for bookkeeping of os_mmap_read/write counts.
10622  *
10623  * Since VOP_MAP only passes in a pointer to the vnode rather than
10624  * a double pointer, we can't handle the case where nfs4open_otw()
10625  * returns a different vnode than the one passed into VOP_MAP (since
10626  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10627  * we return NULL and let nfs4_map() fail.  Note: the only case where
10628  * this should happen is if the file got removed and replaced with the
10629  * same name on the server (in addition to the fact that we're trying
10630  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10631  */
10632 static int
10633 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10634 {
10635 	rnode4_t		*rp, *drp;
10636 	vnode_t			*dvp, *open_vp;
10637 	char			file_name[MAXNAMELEN];
10638 	int			just_created;
10639 	nfs4_open_stream_t	*osp;
10640 	nfs4_open_owner_t	*oop;
10641 	int			error;
10642 
10643 	*ospp = NULL;
10644 	open_vp = map_vp;
10645 
10646 	rp = VTOR4(open_vp);
10647 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10648 		return (error);
10649 	drp = VTOR4(dvp);
10650 
10651 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10652 		VN_RELE(dvp);
10653 		return (EINTR);
10654 	}
10655 
10656 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10657 		nfs_rw_exit(&drp->r_rwlock);
10658 		VN_RELE(dvp);
10659 		return (error);
10660 	}
10661 
10662 	mutex_enter(&rp->r_statev4_lock);
10663 	if (rp->created_v4) {
10664 		rp->created_v4 = 0;
10665 		mutex_exit(&rp->r_statev4_lock);
10666 
10667 		dnlc_update(dvp, file_name, open_vp);
10668 		/* This is needed so we don't bump the open ref count */
10669 		just_created = 1;
10670 	} else {
10671 		mutex_exit(&rp->r_statev4_lock);
10672 		just_created = 0;
10673 	}
10674 
10675 	VN_HOLD(map_vp);
10676 
10677 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10678 	    just_created);
10679 	if (error) {
10680 		nfs_rw_exit(&drp->r_rwlock);
10681 		VN_RELE(dvp);
10682 		VN_RELE(map_vp);
10683 		return (error);
10684 	}
10685 
10686 	nfs_rw_exit(&drp->r_rwlock);
10687 	VN_RELE(dvp);
10688 
10689 	/*
10690 	 * If nfs4open_otw() returned a different vnode then "undo"
10691 	 * the open and return failure to the caller.
10692 	 */
10693 	if (!VN_CMP(open_vp, map_vp)) {
10694 		nfs4_error_t e;
10695 
10696 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10697 		    "open returned a different vnode"));
10698 		/*
10699 		 * If there's an error, ignore it,
10700 		 * and let VOP_INACTIVE handle it.
10701 		 */
10702 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10703 		    CLOSE_NORM, 0, 0, 0);
10704 		VN_RELE(map_vp);
10705 		return (EIO);
10706 	}
10707 
10708 	VN_RELE(map_vp);
10709 
10710 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10711 	if (!oop) {
10712 		nfs4_error_t e;
10713 
10714 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10715 		    "no open owner"));
10716 		/*
10717 		 * If there's an error, ignore it,
10718 		 * and let VOP_INACTIVE handle it.
10719 		 */
10720 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10721 		    CLOSE_NORM, 0, 0, 0);
10722 		return (EIO);
10723 	}
10724 	osp = find_open_stream(oop, rp);
10725 	open_owner_rele(oop);
10726 	*ospp = osp;
10727 	return (0);
10728 }
10729 
10730 /*
10731  * Please be aware that when this function is called, the address space write
10732  * a_lock is held.  Do not put over the wire calls in this function.
10733  */
10734 /* ARGSUSED */
10735 static int
10736 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10737     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10738     caller_context_t *ct)
10739 {
10740 	rnode4_t		*rp;
10741 	int			error = 0;
10742 	mntinfo4_t		*mi;
10743 
10744 	mi = VTOMI4(vp);
10745 	rp = VTOR4(vp);
10746 
10747 	if (nfs_zone() != mi->mi_zone)
10748 		return (EIO);
10749 	if (vp->v_flag & VNOMAP)
10750 		return (ENOSYS);
10751 
10752 	/*
10753 	 * Don't need to update the open stream first, since this
10754 	 * mmap can't add any additional share access that isn't
10755 	 * already contained in the open stream (for the case where we
10756 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10757 	 * take into account os_mmap_read[write] counts).
10758 	 */
10759 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10760 
10761 	if (vp->v_type == VREG) {
10762 		/*
10763 		 * We need to retrieve the open stream and update the counts.
10764 		 * If there is no open stream here, something is wrong.
10765 		 */
10766 		nfs4_open_stream_t	*osp = NULL;
10767 		nfs4_open_owner_t	*oop = NULL;
10768 
10769 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10770 		if (oop != NULL) {
10771 			/* returns with 'os_sync_lock' held */
10772 			osp = find_open_stream(oop, rp);
10773 			open_owner_rele(oop);
10774 		}
10775 		if (osp == NULL) {
10776 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10777 			    "nfs4_addmap: we should have an osp"
10778 			    "but we don't, so fail with EIO"));
10779 			error = EIO;
10780 			goto out;
10781 		}
10782 
10783 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10784 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10785 
10786 		/*
10787 		 * Update the map count in the open stream.
10788 		 * This is necessary in the case where we
10789 		 * open/mmap/close/, then the server reboots, and we
10790 		 * attempt to reopen.  If the mmap doesn't add share
10791 		 * access then we send an invalid reopen with
10792 		 * access = NONE.
10793 		 *
10794 		 * We need to specifically check each PROT_* so a mmap
10795 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10796 		 * read and write access.  A simple comparison of prot
10797 		 * to ~PROT_WRITE to determine read access is insufficient
10798 		 * since prot can be |= with PROT_USER, etc.
10799 		 */
10800 
10801 		/*
10802 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10803 		 */
10804 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10805 			osp->os_mmap_write += btopr(len);
10806 		if (maxprot & PROT_READ)
10807 			osp->os_mmap_read += btopr(len);
10808 		if (maxprot & PROT_EXEC)
10809 			osp->os_mmap_read += btopr(len);
10810 		/*
10811 		 * Ensure that os_mmap_read gets incremented, even if
10812 		 * maxprot were to look like PROT_NONE.
10813 		 */
10814 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10815 		    !(maxprot & PROT_EXEC))
10816 			osp->os_mmap_read += btopr(len);
10817 		osp->os_mapcnt += btopr(len);
10818 		mutex_exit(&osp->os_sync_lock);
10819 		open_stream_rele(osp, rp);
10820 	}
10821 
10822 out:
10823 	/*
10824 	 * If we got an error, then undo our
10825 	 * incrementing of 'r_mapcnt'.
10826 	 */
10827 
10828 	if (error) {
10829 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10830 		ASSERT(rp->r_mapcnt >= 0);
10831 	}
10832 	return (error);
10833 }
10834 
10835 /* ARGSUSED */
10836 static int
10837 nfs4_cmp(vnode_t *vp1, vnode_t *vp2, caller_context_t *ct)
10838 {
10839 
10840 	return (VTOR4(vp1) == VTOR4(vp2));
10841 }
10842 
10843 /* ARGSUSED */
10844 static int
10845 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10846     offset_t offset, struct flk_callback *flk_cbp, cred_t *cr,
10847     caller_context_t *ct)
10848 {
10849 	int rc;
10850 	u_offset_t start, end;
10851 	rnode4_t *rp;
10852 	int error = 0, intr = INTR4(vp);
10853 	nfs4_error_t e;
10854 
10855 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10856 		return (EIO);
10857 
10858 	/* check for valid cmd parameter */
10859 	if (cmd != F_GETLK && cmd != F_SETLK && cmd != F_SETLKW)
10860 		return (EINVAL);
10861 
10862 	/* Verify l_type. */
10863 	switch (bfp->l_type) {
10864 	case F_RDLCK:
10865 		if (cmd != F_GETLK && !(flag & FREAD))
10866 			return (EBADF);
10867 		break;
10868 	case F_WRLCK:
10869 		if (cmd != F_GETLK && !(flag & FWRITE))
10870 			return (EBADF);
10871 		break;
10872 	case F_UNLCK:
10873 		intr = 0;
10874 		break;
10875 
10876 	default:
10877 		return (EINVAL);
10878 	}
10879 
10880 	/* check the validity of the lock range */
10881 	if (rc = flk_convert_lock_data(vp, bfp, &start, &end, offset))
10882 		return (rc);
10883 	if (rc = flk_check_lock_data(start, end, MAXEND))
10884 		return (rc);
10885 
10886 	/*
10887 	 * If the filesystem is mounted using local locking, pass the
10888 	 * request off to the local locking code.
10889 	 */
10890 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10891 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10892 			/*
10893 			 * For complete safety, we should be holding
10894 			 * r_lkserlock.  However, we can't call
10895 			 * nfs4_safelock and then fs_frlock while
10896 			 * holding r_lkserlock, so just invoke
10897 			 * nfs4_safelock and expect that this will
10898 			 * catch enough of the cases.
10899 			 */
10900 			if (!nfs4_safelock(vp, bfp, cr))
10901 				return (EAGAIN);
10902 		}
10903 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
10904 	}
10905 
10906 	rp = VTOR4(vp);
10907 
10908 	/*
10909 	 * Check whether the given lock request can proceed, given the
10910 	 * current file mappings.
10911 	 */
10912 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr))
10913 		return (EINTR);
10914 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10915 		if (!nfs4_safelock(vp, bfp, cr)) {
10916 			rc = EAGAIN;
10917 			goto done;
10918 		}
10919 	}
10920 
10921 	/*
10922 	 * Flush the cache after waiting for async I/O to finish.  For new
10923 	 * locks, this is so that the process gets the latest bits from the
10924 	 * server.  For unlocks, this is so that other clients see the
10925 	 * latest bits once the file has been unlocked.  If currently dirty
10926 	 * pages can't be flushed, then don't allow a lock to be set.  But
10927 	 * allow unlocks to succeed, to avoid having orphan locks on the
10928 	 * server.
10929 	 */
10930 	if (cmd != F_GETLK) {
10931 		mutex_enter(&rp->r_statelock);
10932 		while (rp->r_count > 0) {
10933 			if (intr) {
10934 				klwp_t *lwp = ttolwp(curthread);
10935 
10936 				if (lwp != NULL)
10937 					lwp->lwp_nostop++;
10938 				if (cv_wait_sig(&rp->r_cv,
10939 				    &rp->r_statelock) == 0) {
10940 					if (lwp != NULL)
10941 						lwp->lwp_nostop--;
10942 					rc = EINTR;
10943 					break;
10944 				}
10945 				if (lwp != NULL)
10946 					lwp->lwp_nostop--;
10947 			} else {
10948 				cv_wait(&rp->r_cv, &rp->r_statelock);
10949 			}
10950 		}
10951 		mutex_exit(&rp->r_statelock);
10952 		if (rc != 0)
10953 			goto done;
10954 		error = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr, ct);
10955 		if (error) {
10956 			if (error == ENOSPC || error == EDQUOT) {
10957 				mutex_enter(&rp->r_statelock);
10958 				if (!rp->r_error)
10959 					rp->r_error = error;
10960 				mutex_exit(&rp->r_statelock);
10961 			}
10962 			if (bfp->l_type != F_UNLCK) {
10963 				rc = ENOLCK;
10964 				goto done;
10965 			}
10966 		}
10967 	}
10968 
10969 	/*
10970 	 * Call the lock manager to do the real work of contacting
10971 	 * the server and obtaining the lock.
10972 	 */
10973 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, flag, offset,
10974 	    cr, &e, NULL, NULL);
10975 	rc = e.error;
10976 
10977 	if (rc == 0)
10978 		nfs4_lockcompletion(vp, cmd);
10979 
10980 done:
10981 	nfs_rw_exit(&rp->r_lkserlock);
10982 
10983 	return (rc);
10984 }
10985 
10986 /*
10987  * Free storage space associated with the specified vnode.  The portion
10988  * to be freed is specified by bfp->l_start and bfp->l_len (already
10989  * normalized to a "whence" of 0).
10990  *
10991  * This is an experimental facility whose continued existence is not
10992  * guaranteed.  Currently, we only support the special case
10993  * of l_len == 0, meaning free to end of file.
10994  */
10995 /* ARGSUSED */
10996 static int
10997 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10998     offset_t offset, cred_t *cr, caller_context_t *ct)
10999 {
11000 	int error;
11001 
11002 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11003 		return (EIO);
11004 	ASSERT(vp->v_type == VREG);
11005 	if (cmd != F_FREESP)
11006 		return (EINVAL);
11007 
11008 	error = convoff(vp, bfp, 0, offset);
11009 	if (!error) {
11010 		ASSERT(bfp->l_start >= 0);
11011 		if (bfp->l_len == 0) {
11012 			struct vattr va;
11013 
11014 			va.va_mask = AT_SIZE;
11015 			va.va_size = bfp->l_start;
11016 			error = nfs4setattr(vp, &va, 0, cr, NULL);
11017 
11018 			if (error == 0 && bfp->l_start == 0)
11019 				vnevent_truncate(vp, ct);
11020 		} else
11021 			error = EINVAL;
11022 	}
11023 
11024 	return (error);
11025 }
11026 
11027 /* ARGSUSED */
11028 int
11029 nfs4_realvp(vnode_t *vp, vnode_t **vpp, caller_context_t *ct)
11030 {
11031 	rnode4_t *rp;
11032 	rp = VTOR4(vp);
11033 
11034 	if (vp->v_type == VREG && IS_SHADOW(vp, rp)) {
11035 		vp = RTOV4(rp);
11036 	}
11037 	*vpp = vp;
11038 	return (0);
11039 }
11040 
11041 /*
11042  * Setup and add an address space callback to do the work of the delmap call.
11043  * The callback will (and must be) deleted in the actual callback function.
11044  *
11045  * This is done in order to take care of the problem that we have with holding
11046  * the address space's a_lock for a long period of time (e.g. if the NFS server
11047  * is down).  Callbacks will be executed in the address space code while the
11048  * a_lock is not held.  Holding the address space's a_lock causes things such
11049  * as ps and fork to hang because they are trying to acquire this lock as well.
11050  */
11051 /* ARGSUSED */
11052 static int
11053 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
11054     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
11055     caller_context_t *ct)
11056 {
11057 	int			caller_found;
11058 	int			error;
11059 	rnode4_t		*rp;
11060 	nfs4_delmap_args_t	*dmapp;
11061 	nfs4_delmapcall_t	*delmap_call;
11062 
11063 	if (vp->v_flag & VNOMAP)
11064 		return (ENOSYS);
11065 
11066 	/*
11067 	 * A process may not change zones if it has NFS pages mmap'ed
11068 	 * in, so we can't legitimately get here from the wrong zone.
11069 	 */
11070 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11071 
11072 	rp = VTOR4(vp);
11073 
11074 	/*
11075 	 * The way that the address space of this process deletes its mapping
11076 	 * of this file is via the following call chains:
11077 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11078 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11079 	 *
11080 	 * With the use of address space callbacks we are allowed to drop the
11081 	 * address space lock, a_lock, while executing the NFS operations that
11082 	 * need to go over the wire.  Returning EAGAIN to the caller of this
11083 	 * function is what drives the execution of the callback that we add
11084 	 * below.  The callback will be executed by the address space code
11085 	 * after dropping the a_lock.  When the callback is finished, since
11086 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
11087 	 * is called again on the same segment to finish the rest of the work
11088 	 * that needs to happen during unmapping.
11089 	 *
11090 	 * This action of calling back into the segment driver causes
11091 	 * nfs4_delmap() to get called again, but since the callback was
11092 	 * already executed at this point, it already did the work and there
11093 	 * is nothing left for us to do.
11094 	 *
11095 	 * To Summarize:
11096 	 * - The first time nfs4_delmap is called by the current thread is when
11097 	 * we add the caller associated with this delmap to the delmap caller
11098 	 * list, add the callback, and return EAGAIN.
11099 	 * - The second time in this call chain when nfs4_delmap is called we
11100 	 * will find this caller in the delmap caller list and realize there
11101 	 * is no more work to do thus removing this caller from the list and
11102 	 * returning the error that was set in the callback execution.
11103 	 */
11104 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
11105 	if (caller_found) {
11106 		/*
11107 		 * 'error' is from the actual delmap operations.  To avoid
11108 		 * hangs, we need to handle the return of EAGAIN differently
11109 		 * since this is what drives the callback execution.
11110 		 * In this case, we don't want to return EAGAIN and do the
11111 		 * callback execution because there are none to execute.
11112 		 */
11113 		if (error == EAGAIN)
11114 			return (0);
11115 		else
11116 			return (error);
11117 	}
11118 
11119 	/* current caller was not in the list */
11120 	delmap_call = nfs4_init_delmapcall();
11121 
11122 	mutex_enter(&rp->r_statelock);
11123 	list_insert_tail(&rp->r_indelmap, delmap_call);
11124 	mutex_exit(&rp->r_statelock);
11125 
11126 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
11127 
11128 	dmapp->vp = vp;
11129 	dmapp->off = off;
11130 	dmapp->addr = addr;
11131 	dmapp->len = len;
11132 	dmapp->prot = prot;
11133 	dmapp->maxprot = maxprot;
11134 	dmapp->flags = flags;
11135 	dmapp->cr = cr;
11136 	dmapp->caller = delmap_call;
11137 
11138 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
11139 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
11140 
11141 	return (error ? error : EAGAIN);
11142 }
11143 
11144 static nfs4_delmapcall_t *
11145 nfs4_init_delmapcall()
11146 {
11147 	nfs4_delmapcall_t	*delmap_call;
11148 
11149 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
11150 	delmap_call->call_id = curthread;
11151 	delmap_call->error = 0;
11152 
11153 	return (delmap_call);
11154 }
11155 
11156 static void
11157 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11158 {
11159 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11160 }
11161 
11162 /*
11163  * Searches for the current delmap caller (based on curthread) in the list of
11164  * callers.  If it is found, we remove it and free the delmap caller.
11165  * Returns:
11166  *      0 if the caller wasn't found
11167  *      1 if the caller was found, removed and freed.  *errp will be set
11168  *	to what the result of the delmap was.
11169  */
11170 static int
11171 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11172 {
11173 	nfs4_delmapcall_t	*delmap_call;
11174 
11175 	/*
11176 	 * If the list doesn't exist yet, we create it and return
11177 	 * that the caller wasn't found.  No list = no callers.
11178 	 */
11179 	mutex_enter(&rp->r_statelock);
11180 	if (!(rp->r_flags & R4DELMAPLIST)) {
11181 		/* The list does not exist */
11182 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11183 		    offsetof(nfs4_delmapcall_t, call_node));
11184 		rp->r_flags |= R4DELMAPLIST;
11185 		mutex_exit(&rp->r_statelock);
11186 		return (0);
11187 	} else {
11188 		/* The list exists so search it */
11189 		for (delmap_call = list_head(&rp->r_indelmap);
11190 		    delmap_call != NULL;
11191 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11192 			if (delmap_call->call_id == curthread) {
11193 				/* current caller is in the list */
11194 				*errp = delmap_call->error;
11195 				list_remove(&rp->r_indelmap, delmap_call);
11196 				mutex_exit(&rp->r_statelock);
11197 				nfs4_free_delmapcall(delmap_call);
11198 				return (1);
11199 			}
11200 		}
11201 	}
11202 	mutex_exit(&rp->r_statelock);
11203 	return (0);
11204 }
11205 
11206 /*
11207  * Remove some pages from an mmap'd vnode.  Just update the
11208  * count of pages.  If doing close-to-open, then flush and
11209  * commit all of the pages associated with this file.
11210  * Otherwise, start an asynchronous page flush to write out
11211  * any dirty pages.  This will also associate a credential
11212  * with the rnode which can be used to write the pages.
11213  */
11214 /* ARGSUSED */
11215 static void
11216 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11217 {
11218 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11219 	rnode4_t		*rp;
11220 	mntinfo4_t		*mi;
11221 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11222 
11223 	rp = VTOR4(dmapp->vp);
11224 	mi = VTOMI4(dmapp->vp);
11225 
11226 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11227 	ASSERT(rp->r_mapcnt >= 0);
11228 
11229 	/*
11230 	 * Initiate a page flush and potential commit if there are
11231 	 * pages, the file system was not mounted readonly, the segment
11232 	 * was mapped shared, and the pages themselves were writeable.
11233 	 */
11234 	if (nfs4_has_pages(dmapp->vp) &&
11235 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11236 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11237 		mutex_enter(&rp->r_statelock);
11238 		rp->r_flags |= R4DIRTY;
11239 		mutex_exit(&rp->r_statelock);
11240 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11241 		    dmapp->len, dmapp->cr);
11242 		if (!e.error) {
11243 			mutex_enter(&rp->r_statelock);
11244 			e.error = rp->r_error;
11245 			rp->r_error = 0;
11246 			mutex_exit(&rp->r_statelock);
11247 		}
11248 	} else
11249 		e.error = 0;
11250 
11251 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11252 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11253 		    B_INVAL, dmapp->cr, NULL);
11254 
11255 	if (e.error) {
11256 		e.stat = puterrno4(e.error);
11257 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11258 		    OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11259 		dmapp->caller->error = e.error;
11260 	}
11261 
11262 	/* Check to see if we need to close the file */
11263 
11264 	if (dmapp->vp->v_type == VREG) {
11265 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11266 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11267 
11268 		if (e.error != 0 || e.stat != NFS4_OK) {
11269 			/*
11270 			 * Since it is possible that e.error == 0 and
11271 			 * e.stat != NFS4_OK (and vice versa),
11272 			 * we do the proper checking in order to get both
11273 			 * e.error and e.stat reporting the correct info.
11274 			 */
11275 			if (e.stat == NFS4_OK)
11276 				e.stat = puterrno4(e.error);
11277 			if (e.error == 0)
11278 				e.error = geterrno4(e.stat);
11279 
11280 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11281 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11282 			dmapp->caller->error = e.error;
11283 		}
11284 	}
11285 
11286 	(void) as_delete_callback(as, arg);
11287 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11288 }
11289 
11290 
11291 static uint_t
11292 fattr4_maxfilesize_to_bits(uint64_t ll)
11293 {
11294 	uint_t l = 1;
11295 
11296 	if (ll == 0) {
11297 		return (0);
11298 	}
11299 
11300 	if (ll & 0xffffffff00000000) {
11301 		l += 32; ll >>= 32;
11302 	}
11303 	if (ll & 0xffff0000) {
11304 		l += 16; ll >>= 16;
11305 	}
11306 	if (ll & 0xff00) {
11307 		l += 8; ll >>= 8;
11308 	}
11309 	if (ll & 0xf0) {
11310 		l += 4; ll >>= 4;
11311 	}
11312 	if (ll & 0xc) {
11313 		l += 2; ll >>= 2;
11314 	}
11315 	if (ll & 0x2) {
11316 		l += 1;
11317 	}
11318 	return (l);
11319 }
11320 
11321 static int
11322 nfs4_have_xattrs(vnode_t *vp, ulong_t *valp, cred_t *cr)
11323 {
11324 	vnode_t *avp = NULL;
11325 	int error;
11326 
11327 	if ((error = nfs4lookup_xattr(vp, "", &avp,
11328 	    LOOKUP_XATTR, cr)) == 0)
11329 		error = do_xattr_exists_check(avp, valp, cr);
11330 	if (avp)
11331 		VN_RELE(avp);
11332 
11333 	return (error);
11334 }
11335 
11336 /* ARGSUSED */
11337 int
11338 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
11339     caller_context_t *ct)
11340 {
11341 	int error;
11342 	hrtime_t t;
11343 	rnode4_t *rp;
11344 	nfs4_ga_res_t gar;
11345 	nfs4_ga_ext_res_t ger;
11346 
11347 	gar.n4g_ext_res = &ger;
11348 
11349 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11350 		return (EIO);
11351 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11352 		*valp = MAXPATHLEN;
11353 		return (0);
11354 	}
11355 	if (cmd == _PC_ACL_ENABLED) {
11356 		*valp = _ACL_ACE_ENABLED;
11357 		return (0);
11358 	}
11359 
11360 	rp = VTOR4(vp);
11361 	if (cmd == _PC_XATTR_EXISTS) {
11362 		/*
11363 		 * The existence of the xattr directory is not sufficient
11364 		 * for determining whether generic user attributes exists.
11365 		 * The attribute directory could only be a transient directory
11366 		 * used for Solaris sysattr support.  Do a small readdir
11367 		 * to verify if the only entries are sysattrs or not.
11368 		 *
11369 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11370 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11371 		 * and we don't have any way to update the "base" object's
11372 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11373 		 * could help out.
11374 		 */
11375 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11376 		    rp->r_xattr_dir == NULL) {
11377 			return (nfs4_have_xattrs(vp, valp, cr));
11378 		}
11379 	} else {  /* OLD CODE */
11380 		if (ATTRCACHE4_VALID(vp)) {
11381 			mutex_enter(&rp->r_statelock);
11382 			if (rp->r_pathconf.pc4_cache_valid) {
11383 				error = 0;
11384 				switch (cmd) {
11385 				case _PC_FILESIZEBITS:
11386 					*valp =
11387 					    rp->r_pathconf.pc4_filesizebits;
11388 					break;
11389 				case _PC_LINK_MAX:
11390 					*valp =
11391 					    rp->r_pathconf.pc4_link_max;
11392 					break;
11393 				case _PC_NAME_MAX:
11394 					*valp =
11395 					    rp->r_pathconf.pc4_name_max;
11396 					break;
11397 				case _PC_CHOWN_RESTRICTED:
11398 					*valp =
11399 					    rp->r_pathconf.pc4_chown_restricted;
11400 					break;
11401 				case _PC_NO_TRUNC:
11402 					*valp =
11403 					    rp->r_pathconf.pc4_no_trunc;
11404 					break;
11405 				default:
11406 					error = EINVAL;
11407 					break;
11408 				}
11409 				mutex_exit(&rp->r_statelock);
11410 #ifdef DEBUG
11411 				nfs4_pathconf_cache_hits++;
11412 #endif
11413 				return (error);
11414 			}
11415 			mutex_exit(&rp->r_statelock);
11416 		}
11417 	}
11418 #ifdef DEBUG
11419 	nfs4_pathconf_cache_misses++;
11420 #endif
11421 
11422 	t = gethrtime();
11423 
11424 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11425 
11426 	if (error) {
11427 		mutex_enter(&rp->r_statelock);
11428 		rp->r_pathconf.pc4_cache_valid = FALSE;
11429 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11430 		mutex_exit(&rp->r_statelock);
11431 		return (error);
11432 	}
11433 
11434 	/* interpret the max filesize */
11435 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11436 	    fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11437 
11438 	/* Store the attributes we just received */
11439 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11440 
11441 	switch (cmd) {
11442 	case _PC_FILESIZEBITS:
11443 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11444 		break;
11445 	case _PC_LINK_MAX:
11446 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11447 		break;
11448 	case _PC_NAME_MAX:
11449 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11450 		break;
11451 	case _PC_CHOWN_RESTRICTED:
11452 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11453 		break;
11454 	case _PC_NO_TRUNC:
11455 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11456 		break;
11457 	case _PC_XATTR_EXISTS:
11458 		if (gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists) {
11459 			if (error = nfs4_have_xattrs(vp, valp, cr))
11460 				return (error);
11461 		}
11462 		break;
11463 	default:
11464 		return (EINVAL);
11465 	}
11466 
11467 	return (0);
11468 }
11469 
11470 /*
11471  * Called by async thread to do synchronous pageio. Do the i/o, wait
11472  * for it to complete, and cleanup the page list when done.
11473  */
11474 static int
11475 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11476     int flags, cred_t *cr)
11477 {
11478 	int error;
11479 
11480 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11481 
11482 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11483 	if (flags & B_READ)
11484 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11485 	else
11486 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11487 	return (error);
11488 }
11489 
11490 /* ARGSUSED */
11491 static int
11492 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11493     int flags, cred_t *cr, caller_context_t *ct)
11494 {
11495 	int error;
11496 	rnode4_t *rp;
11497 
11498 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11499 		return (EIO);
11500 
11501 	if (pp == NULL)
11502 		return (EINVAL);
11503 
11504 	rp = VTOR4(vp);
11505 	mutex_enter(&rp->r_statelock);
11506 	rp->r_count++;
11507 	mutex_exit(&rp->r_statelock);
11508 
11509 	if (flags & B_ASYNC) {
11510 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11511 		    nfs4_sync_pageio);
11512 	} else
11513 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11514 	mutex_enter(&rp->r_statelock);
11515 	rp->r_count--;
11516 	cv_broadcast(&rp->r_cv);
11517 	mutex_exit(&rp->r_statelock);
11518 	return (error);
11519 }
11520 
11521 /* ARGSUSED */
11522 static void
11523 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr,
11524     caller_context_t *ct)
11525 {
11526 	int error;
11527 	rnode4_t *rp;
11528 	page_t *plist;
11529 	page_t *pptr;
11530 	offset3 offset;
11531 	count3 len;
11532 	k_sigset_t smask;
11533 
11534 	/*
11535 	 * We should get called with fl equal to either B_FREE or
11536 	 * B_INVAL.  Any other value is illegal.
11537 	 *
11538 	 * The page that we are either supposed to free or destroy
11539 	 * should be exclusive locked and its io lock should not
11540 	 * be held.
11541 	 */
11542 	ASSERT(fl == B_FREE || fl == B_INVAL);
11543 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11544 
11545 	rp = VTOR4(vp);
11546 
11547 	/*
11548 	 * If the page doesn't need to be committed or we shouldn't
11549 	 * even bother attempting to commit it, then just make sure
11550 	 * that the p_fsdata byte is clear and then either free or
11551 	 * destroy the page as appropriate.
11552 	 */
11553 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11554 		pp->p_fsdata = C_NOCOMMIT;
11555 		if (fl == B_FREE)
11556 			page_free(pp, dn);
11557 		else
11558 			page_destroy(pp, dn);
11559 		return;
11560 	}
11561 
11562 	/*
11563 	 * If there is a page invalidation operation going on, then
11564 	 * if this is one of the pages being destroyed, then just
11565 	 * clear the p_fsdata byte and then either free or destroy
11566 	 * the page as appropriate.
11567 	 */
11568 	mutex_enter(&rp->r_statelock);
11569 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11570 		mutex_exit(&rp->r_statelock);
11571 		pp->p_fsdata = C_NOCOMMIT;
11572 		if (fl == B_FREE)
11573 			page_free(pp, dn);
11574 		else
11575 			page_destroy(pp, dn);
11576 		return;
11577 	}
11578 
11579 	/*
11580 	 * If we are freeing this page and someone else is already
11581 	 * waiting to do a commit, then just unlock the page and
11582 	 * return.  That other thread will take care of commiting
11583 	 * this page.  The page can be freed sometime after the
11584 	 * commit has finished.  Otherwise, if the page is marked
11585 	 * as delay commit, then we may be getting called from
11586 	 * pvn_write_done, one page at a time.   This could result
11587 	 * in one commit per page, so we end up doing lots of small
11588 	 * commits instead of fewer larger commits.  This is bad,
11589 	 * we want do as few commits as possible.
11590 	 */
11591 	if (fl == B_FREE) {
11592 		if (rp->r_flags & R4COMMITWAIT) {
11593 			page_unlock(pp);
11594 			mutex_exit(&rp->r_statelock);
11595 			return;
11596 		}
11597 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11598 			pp->p_fsdata = C_COMMIT;
11599 			page_unlock(pp);
11600 			mutex_exit(&rp->r_statelock);
11601 			return;
11602 		}
11603 	}
11604 
11605 	/*
11606 	 * Check to see if there is a signal which would prevent an
11607 	 * attempt to commit the pages from being successful.  If so,
11608 	 * then don't bother with all of the work to gather pages and
11609 	 * generate the unsuccessful RPC.  Just return from here and
11610 	 * let the page be committed at some later time.
11611 	 */
11612 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11613 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11614 		sigunintr(&smask);
11615 		page_unlock(pp);
11616 		mutex_exit(&rp->r_statelock);
11617 		return;
11618 	}
11619 	sigunintr(&smask);
11620 
11621 	/*
11622 	 * We are starting to need to commit pages, so let's try
11623 	 * to commit as many as possible at once to reduce the
11624 	 * overhead.
11625 	 *
11626 	 * Set the `commit inprogress' state bit.  We must
11627 	 * first wait until any current one finishes.  Then
11628 	 * we initialize the c_pages list with this page.
11629 	 */
11630 	while (rp->r_flags & R4COMMIT) {
11631 		rp->r_flags |= R4COMMITWAIT;
11632 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11633 		rp->r_flags &= ~R4COMMITWAIT;
11634 	}
11635 	rp->r_flags |= R4COMMIT;
11636 	mutex_exit(&rp->r_statelock);
11637 	ASSERT(rp->r_commit.c_pages == NULL);
11638 	rp->r_commit.c_pages = pp;
11639 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11640 	rp->r_commit.c_commlen = PAGESIZE;
11641 
11642 	/*
11643 	 * Gather together all other pages which can be committed.
11644 	 * They will all be chained off r_commit.c_pages.
11645 	 */
11646 	nfs4_get_commit(vp);
11647 
11648 	/*
11649 	 * Clear the `commit inprogress' status and disconnect
11650 	 * the list of pages to be committed from the rnode.
11651 	 * At this same time, we also save the starting offset
11652 	 * and length of data to be committed on the server.
11653 	 */
11654 	plist = rp->r_commit.c_pages;
11655 	rp->r_commit.c_pages = NULL;
11656 	offset = rp->r_commit.c_commbase;
11657 	len = rp->r_commit.c_commlen;
11658 	mutex_enter(&rp->r_statelock);
11659 	rp->r_flags &= ~R4COMMIT;
11660 	cv_broadcast(&rp->r_commit.c_cv);
11661 	mutex_exit(&rp->r_statelock);
11662 
11663 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11664 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11665 		nfs4_async_commit(vp, plist, offset, len,
11666 		    cr, do_nfs4_async_commit);
11667 		return;
11668 	}
11669 
11670 	/*
11671 	 * Actually generate the COMMIT op over the wire operation.
11672 	 */
11673 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11674 
11675 	/*
11676 	 * If we got an error during the commit, just unlock all
11677 	 * of the pages.  The pages will get retransmitted to the
11678 	 * server during a putpage operation.
11679 	 */
11680 	if (error) {
11681 		while (plist != NULL) {
11682 			pptr = plist;
11683 			page_sub(&plist, pptr);
11684 			page_unlock(pptr);
11685 		}
11686 		return;
11687 	}
11688 
11689 	/*
11690 	 * We've tried as hard as we can to commit the data to stable
11691 	 * storage on the server.  We just unlock the rest of the pages
11692 	 * and clear the commit required state.  They will be put
11693 	 * onto the tail of the cachelist if they are nolonger
11694 	 * mapped.
11695 	 */
11696 	while (plist != pp) {
11697 		pptr = plist;
11698 		page_sub(&plist, pptr);
11699 		pptr->p_fsdata = C_NOCOMMIT;
11700 		page_unlock(pptr);
11701 	}
11702 
11703 	/*
11704 	 * It is possible that nfs4_commit didn't return error but
11705 	 * some other thread has modified the page we are going
11706 	 * to free/destroy.
11707 	 *    In this case we need to rewrite the page. Do an explicit check
11708 	 * before attempting to free/destroy the page. If modified, needs to
11709 	 * be rewritten so unlock the page and return.
11710 	 */
11711 	if (hat_ismod(pp)) {
11712 		pp->p_fsdata = C_NOCOMMIT;
11713 		page_unlock(pp);
11714 		return;
11715 	}
11716 
11717 	/*
11718 	 * Now, as appropriate, either free or destroy the page
11719 	 * that we were called with.
11720 	 */
11721 	pp->p_fsdata = C_NOCOMMIT;
11722 	if (fl == B_FREE)
11723 		page_free(pp, dn);
11724 	else
11725 		page_destroy(pp, dn);
11726 }
11727 
11728 /*
11729  * Commit requires that the current fh be the file written to.
11730  * The compound op structure is:
11731  *      PUTFH(file), COMMIT
11732  */
11733 static int
11734 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11735 {
11736 	COMPOUND4args_clnt args;
11737 	COMPOUND4res_clnt res;
11738 	COMMIT4res *cm_res;
11739 	nfs_argop4 argop[2];
11740 	nfs_resop4 *resop;
11741 	int doqueue;
11742 	mntinfo4_t *mi;
11743 	rnode4_t *rp;
11744 	cred_t *cred_otw = NULL;
11745 	bool_t needrecov = FALSE;
11746 	nfs4_recov_state_t recov_state;
11747 	nfs4_open_stream_t *osp = NULL;
11748 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11749 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11750 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11751 
11752 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11753 
11754 	rp = VTOR4(vp);
11755 
11756 	mi = VTOMI4(vp);
11757 	recov_state.rs_flags = 0;
11758 	recov_state.rs_num_retry_despite_err = 0;
11759 get_commit_cred:
11760 	/*
11761 	 * Releases the osp, if a valid open stream is provided.
11762 	 * Puts a hold on the cred_otw and the new osp (if found).
11763 	 */
11764 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11765 	    &first_time, &last_time);
11766 	args.ctag = TAG_COMMIT;
11767 recov_retry:
11768 	/*
11769 	 * Commit ops: putfh file; commit
11770 	 */
11771 	args.array_len = 2;
11772 	args.array = argop;
11773 
11774 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11775 	    &recov_state, NULL);
11776 	if (e.error) {
11777 		crfree(cred_otw);
11778 		if (osp != NULL)
11779 			open_stream_rele(osp, rp);
11780 		return (e.error);
11781 	}
11782 
11783 	/* putfh directory */
11784 	argop[0].argop = OP_CPUTFH;
11785 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11786 
11787 	/* commit */
11788 	argop[1].argop = OP_COMMIT;
11789 	argop[1].nfs_argop4_u.opcommit.offset = offset;
11790 	argop[1].nfs_argop4_u.opcommit.count = count;
11791 
11792 	doqueue = 1;
11793 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
11794 
11795 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
11796 	if (!needrecov && e.error) {
11797 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
11798 		    needrecov);
11799 		crfree(cred_otw);
11800 		if (e.error == EACCES && last_time == FALSE)
11801 			goto get_commit_cred;
11802 		if (osp != NULL)
11803 			open_stream_rele(osp, rp);
11804 		return (e.error);
11805 	}
11806 
11807 	if (needrecov) {
11808 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
11809 		    NULL, OP_COMMIT, NULL, NULL, NULL) == FALSE) {
11810 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11811 			    &recov_state, needrecov);
11812 			if (!e.error)
11813 				(void) xdr_free(xdr_COMPOUND4res_clnt,
11814 				    (caddr_t)&res);
11815 			goto recov_retry;
11816 		}
11817 		if (e.error) {
11818 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11819 			    &recov_state, needrecov);
11820 			crfree(cred_otw);
11821 			if (osp != NULL)
11822 				open_stream_rele(osp, rp);
11823 			return (e.error);
11824 		}
11825 		/* fall through for res.status case */
11826 	}
11827 
11828 	if (res.status) {
11829 		e.error = geterrno4(res.status);
11830 		if (e.error == EACCES && last_time == FALSE) {
11831 			crfree(cred_otw);
11832 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11833 			    &recov_state, needrecov);
11834 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11835 			goto get_commit_cred;
11836 		}
11837 		/*
11838 		 * Can't do a nfs4_purge_stale_fh here because this
11839 		 * can cause a deadlock.  nfs4_commit can
11840 		 * be called from nfs4_dispose which can be called
11841 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
11842 		 * can call back to pvn_vplist_dirty.
11843 		 */
11844 		if (e.error == ESTALE) {
11845 			mutex_enter(&rp->r_statelock);
11846 			rp->r_flags |= R4STALE;
11847 			if (!rp->r_error)
11848 				rp->r_error = e.error;
11849 			mutex_exit(&rp->r_statelock);
11850 			PURGE_ATTRCACHE4(vp);
11851 		} else {
11852 			mutex_enter(&rp->r_statelock);
11853 			if (!rp->r_error)
11854 				rp->r_error = e.error;
11855 			mutex_exit(&rp->r_statelock);
11856 		}
11857 	} else {
11858 		ASSERT(rp->r_flags & R4HAVEVERF);
11859 		resop = &res.array[1];	/* commit res */
11860 		cm_res = &resop->nfs_resop4_u.opcommit;
11861 		mutex_enter(&rp->r_statelock);
11862 		if (cm_res->writeverf == rp->r_writeverf) {
11863 			mutex_exit(&rp->r_statelock);
11864 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11865 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11866 			    &recov_state, needrecov);
11867 			crfree(cred_otw);
11868 			if (osp != NULL)
11869 				open_stream_rele(osp, rp);
11870 			return (0);
11871 		}
11872 		nfs4_set_mod(vp);
11873 		rp->r_writeverf = cm_res->writeverf;
11874 		mutex_exit(&rp->r_statelock);
11875 		e.error = NFS_VERF_MISMATCH;
11876 	}
11877 
11878 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11879 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
11880 	crfree(cred_otw);
11881 	if (osp != NULL)
11882 		open_stream_rele(osp, rp);
11883 
11884 	return (e.error);
11885 }
11886 
11887 static void
11888 nfs4_set_mod(vnode_t *vp)
11889 {
11890 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11891 
11892 	/* make sure we're looking at the master vnode, not a shadow */
11893 	pvn_vplist_setdirty(RTOV4(VTOR4(vp)), nfs_setmod_check);
11894 }
11895 
11896 /*
11897  * This function is used to gather a page list of the pages which
11898  * can be committed on the server.
11899  *
11900  * The calling thread must have set R4COMMIT.  This bit is used to
11901  * serialize access to the commit structure in the rnode.  As long
11902  * as the thread has set R4COMMIT, then it can manipulate the commit
11903  * structure without requiring any other locks.
11904  *
11905  * When this function is called from nfs4_dispose() the page passed
11906  * into nfs4_dispose() will be SE_EXCL locked, and so this function
11907  * will skip it. This is not a problem since we initially add the
11908  * page to the r_commit page list.
11909  *
11910  */
11911 static void
11912 nfs4_get_commit(vnode_t *vp)
11913 {
11914 	rnode4_t *rp;
11915 	page_t *pp;
11916 	kmutex_t *vphm;
11917 
11918 	rp = VTOR4(vp);
11919 
11920 	ASSERT(rp->r_flags & R4COMMIT);
11921 
11922 	/* make sure we're looking at the master vnode, not a shadow */
11923 
11924 	if (IS_SHADOW(vp, rp))
11925 		vp = RTOV4(rp);
11926 
11927 	vphm = page_vnode_mutex(vp);
11928 	mutex_enter(vphm);
11929 
11930 	/*
11931 	 * If there are no pages associated with this vnode, then
11932 	 * just return.
11933 	 */
11934 	if ((pp = vp->v_pages) == NULL) {
11935 		mutex_exit(vphm);
11936 		return;
11937 	}
11938 
11939 	/*
11940 	 * Step through all of the pages associated with this vnode
11941 	 * looking for pages which need to be committed.
11942 	 */
11943 	do {
11944 		/* Skip marker pages. */
11945 		if (pp->p_hash == PVN_VPLIST_HASH_TAG)
11946 			continue;
11947 
11948 		/*
11949 		 * First short-cut everything (without the page_lock)
11950 		 * and see if this page does not need to be committed
11951 		 * or is modified if so then we'll just skip it.
11952 		 */
11953 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
11954 			continue;
11955 
11956 		/*
11957 		 * Attempt to lock the page.  If we can't, then
11958 		 * someone else is messing with it or we have been
11959 		 * called from nfs4_dispose and this is the page that
11960 		 * nfs4_dispose was called with.. anyway just skip it.
11961 		 */
11962 		if (!page_trylock(pp, SE_EXCL))
11963 			continue;
11964 
11965 		/*
11966 		 * Lets check again now that we have the page lock.
11967 		 */
11968 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11969 			page_unlock(pp);
11970 			continue;
11971 		}
11972 
11973 		/* this had better not be a free page */
11974 		ASSERT(PP_ISFREE(pp) == 0);
11975 
11976 		/*
11977 		 * The page needs to be committed and we locked it.
11978 		 * Update the base and length parameters and add it
11979 		 * to r_pages.
11980 		 */
11981 		if (rp->r_commit.c_pages == NULL) {
11982 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11983 			rp->r_commit.c_commlen = PAGESIZE;
11984 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
11985 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
11986 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
11987 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11988 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
11989 		    <= pp->p_offset) {
11990 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11991 			    rp->r_commit.c_commbase + PAGESIZE;
11992 		}
11993 		page_add(&rp->r_commit.c_pages, pp);
11994 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11995 
11996 	mutex_exit(vphm);
11997 }
11998 
11999 /*
12000  * This routine is used to gather together a page list of the pages
12001  * which are to be committed on the server.  This routine must not
12002  * be called if the calling thread holds any locked pages.
12003  *
12004  * The calling thread must have set R4COMMIT.  This bit is used to
12005  * serialize access to the commit structure in the rnode.  As long
12006  * as the thread has set R4COMMIT, then it can manipulate the commit
12007  * structure without requiring any other locks.
12008  */
12009 static void
12010 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
12011 {
12012 
12013 	rnode4_t *rp;
12014 	page_t *pp;
12015 	u_offset_t end;
12016 	u_offset_t off;
12017 	ASSERT(len != 0);
12018 	rp = VTOR4(vp);
12019 	ASSERT(rp->r_flags & R4COMMIT);
12020 
12021 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12022 
12023 	/* make sure we're looking at the master vnode, not a shadow */
12024 
12025 	if (IS_SHADOW(vp, rp))
12026 		vp = RTOV4(rp);
12027 
12028 	/*
12029 	 * If there are no pages associated with this vnode, then
12030 	 * just return.
12031 	 */
12032 	if ((pp = vp->v_pages) == NULL)
12033 		return;
12034 	/*
12035 	 * Calculate the ending offset.
12036 	 */
12037 	end = soff + len;
12038 	for (off = soff; off < end; off += PAGESIZE) {
12039 		/*
12040 		 * Lookup each page by vp, offset.
12041 		 */
12042 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
12043 			continue;
12044 		/*
12045 		 * If this page does not need to be committed or is
12046 		 * modified, then just skip it.
12047 		 */
12048 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
12049 			page_unlock(pp);
12050 			continue;
12051 		}
12052 
12053 		ASSERT(PP_ISFREE(pp) == 0);
12054 		/*
12055 		 * The page needs to be committed and we locked it.
12056 		 * Update the base and length parameters and add it
12057 		 * to r_pages.
12058 		 */
12059 		if (rp->r_commit.c_pages == NULL) {
12060 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
12061 			rp->r_commit.c_commlen = PAGESIZE;
12062 		} else {
12063 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
12064 			    rp->r_commit.c_commbase + PAGESIZE;
12065 		}
12066 		page_add(&rp->r_commit.c_pages, pp);
12067 	}
12068 }
12069 
12070 /*
12071  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
12072  * Flushes and commits data to the server.
12073  */
12074 static int
12075 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
12076 {
12077 	int error;
12078 	verifier4 write_verf;
12079 	rnode4_t *rp = VTOR4(vp);
12080 
12081 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12082 
12083 	/*
12084 	 * Flush the data portion of the file and then commit any
12085 	 * portions which need to be committed.  This may need to
12086 	 * be done twice if the server has changed state since
12087 	 * data was last written.  The data will need to be
12088 	 * rewritten to the server and then a new commit done.
12089 	 *
12090 	 * In fact, this may need to be done several times if the
12091 	 * server is having problems and crashing while we are
12092 	 * attempting to do this.
12093 	 */
12094 
12095 top:
12096 	/*
12097 	 * Do a flush based on the poff and plen arguments.  This
12098 	 * will synchronously write out any modified pages in the
12099 	 * range specified by (poff, plen). This starts all of the
12100 	 * i/o operations which will be waited for in the next
12101 	 * call to nfs4_putpage
12102 	 */
12103 
12104 	mutex_enter(&rp->r_statelock);
12105 	write_verf = rp->r_writeverf;
12106 	mutex_exit(&rp->r_statelock);
12107 
12108 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr, NULL);
12109 	if (error == EAGAIN)
12110 		error = 0;
12111 
12112 	/*
12113 	 * Do a flush based on the poff and plen arguments.  This
12114 	 * will synchronously write out any modified pages in the
12115 	 * range specified by (poff, plen) and wait until all of
12116 	 * the asynchronous i/o's in that range are done as well.
12117 	 */
12118 	if (!error)
12119 		error = nfs4_putpage(vp, poff, plen, 0, cr, NULL);
12120 
12121 	if (error)
12122 		return (error);
12123 
12124 	mutex_enter(&rp->r_statelock);
12125 	if (rp->r_writeverf != write_verf) {
12126 		mutex_exit(&rp->r_statelock);
12127 		goto top;
12128 	}
12129 	mutex_exit(&rp->r_statelock);
12130 
12131 	/*
12132 	 * Now commit any pages which might need to be committed.
12133 	 * If the error, NFS_VERF_MISMATCH, is returned, then
12134 	 * start over with the flush operation.
12135 	 */
12136 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
12137 
12138 	if (error == NFS_VERF_MISMATCH)
12139 		goto top;
12140 
12141 	return (error);
12142 }
12143 
12144 /*
12145  * nfs4_commit_vp()  will wait for other pending commits and
12146  * will either commit the whole file or a range, plen dictates
12147  * if we commit whole file. a value of zero indicates the whole
12148  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
12149  */
12150 static int
12151 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12152     cred_t *cr, int wait_on_writes)
12153 {
12154 	rnode4_t *rp;
12155 	page_t *plist;
12156 	offset3 offset;
12157 	count3 len;
12158 
12159 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12160 
12161 	rp = VTOR4(vp);
12162 
12163 	/*
12164 	 *  before we gather commitable pages make
12165 	 *  sure there are no outstanding async writes
12166 	 */
12167 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12168 		mutex_enter(&rp->r_statelock);
12169 		while (rp->r_count > 0) {
12170 			cv_wait(&rp->r_cv, &rp->r_statelock);
12171 		}
12172 		mutex_exit(&rp->r_statelock);
12173 	}
12174 
12175 	/*
12176 	 * Set the `commit inprogress' state bit.  We must
12177 	 * first wait until any current one finishes.
12178 	 */
12179 	mutex_enter(&rp->r_statelock);
12180 	while (rp->r_flags & R4COMMIT) {
12181 		rp->r_flags |= R4COMMITWAIT;
12182 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12183 		rp->r_flags &= ~R4COMMITWAIT;
12184 	}
12185 	rp->r_flags |= R4COMMIT;
12186 	mutex_exit(&rp->r_statelock);
12187 
12188 	/*
12189 	 * Gather all of the pages which need to be
12190 	 * committed.
12191 	 */
12192 	if (plen == 0)
12193 		nfs4_get_commit(vp);
12194 	else
12195 		nfs4_get_commit_range(vp, poff, plen);
12196 
12197 	/*
12198 	 * Clear the `commit inprogress' bit and disconnect the
12199 	 * page list which was gathered by nfs4_get_commit.
12200 	 */
12201 	plist = rp->r_commit.c_pages;
12202 	rp->r_commit.c_pages = NULL;
12203 	offset = rp->r_commit.c_commbase;
12204 	len = rp->r_commit.c_commlen;
12205 	mutex_enter(&rp->r_statelock);
12206 	rp->r_flags &= ~R4COMMIT;
12207 	cv_broadcast(&rp->r_commit.c_cv);
12208 	mutex_exit(&rp->r_statelock);
12209 
12210 	/*
12211 	 * If any pages need to be committed, commit them and
12212 	 * then unlock them so that they can be freed some
12213 	 * time later.
12214 	 */
12215 	if (plist == NULL)
12216 		return (0);
12217 
12218 	/*
12219 	 * No error occurred during the flush portion
12220 	 * of this operation, so now attempt to commit
12221 	 * the data to stable storage on the server.
12222 	 *
12223 	 * This will unlock all of the pages on the list.
12224 	 */
12225 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12226 }
12227 
12228 static int
12229 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12230     cred_t *cr)
12231 {
12232 	int error;
12233 	page_t *pp;
12234 
12235 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12236 
12237 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12238 
12239 	/*
12240 	 * If we got an error, then just unlock all of the pages
12241 	 * on the list.
12242 	 */
12243 	if (error) {
12244 		while (plist != NULL) {
12245 			pp = plist;
12246 			page_sub(&plist, pp);
12247 			page_unlock(pp);
12248 		}
12249 		return (error);
12250 	}
12251 	/*
12252 	 * We've tried as hard as we can to commit the data to stable
12253 	 * storage on the server.  We just unlock the pages and clear
12254 	 * the commit required state.  They will get freed later.
12255 	 */
12256 	while (plist != NULL) {
12257 		pp = plist;
12258 		page_sub(&plist, pp);
12259 		pp->p_fsdata = C_NOCOMMIT;
12260 		page_unlock(pp);
12261 	}
12262 
12263 	return (error);
12264 }
12265 
12266 static void
12267 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12268     cred_t *cr)
12269 {
12270 
12271 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12272 }
12273 
12274 /*ARGSUSED*/
12275 static int
12276 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12277     caller_context_t *ct)
12278 {
12279 	int		error = 0;
12280 	mntinfo4_t	*mi;
12281 	vattr_t		va;
12282 	vsecattr_t	nfsace4_vsap;
12283 
12284 	mi = VTOMI4(vp);
12285 	if (nfs_zone() != mi->mi_zone)
12286 		return (EIO);
12287 	if (mi->mi_flags & MI4_ACL) {
12288 		/* if we have a delegation, return it */
12289 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12290 			(void) nfs4delegreturn(VTOR4(vp),
12291 			    NFS4_DR_REOPEN|NFS4_DR_PUSH);
12292 
12293 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12294 		    NFS4_ACL_SET);
12295 		if (error) /* EINVAL */
12296 			return (error);
12297 
12298 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12299 			/*
12300 			 * These are aclent_t type entries.
12301 			 */
12302 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12303 			    vp->v_type == VDIR, FALSE);
12304 			if (error)
12305 				return (error);
12306 		} else {
12307 			/*
12308 			 * These are ace_t type entries.
12309 			 */
12310 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12311 			    FALSE);
12312 			if (error)
12313 				return (error);
12314 		}
12315 		bzero(&va, sizeof (va));
12316 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12317 		vs_ace4_destroy(&nfsace4_vsap);
12318 		return (error);
12319 	}
12320 	return (ENOSYS);
12321 }
12322 
12323 /* ARGSUSED */
12324 int
12325 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12326     caller_context_t *ct)
12327 {
12328 	int		error;
12329 	mntinfo4_t	*mi;
12330 	nfs4_ga_res_t	gar;
12331 	rnode4_t	*rp = VTOR4(vp);
12332 
12333 	mi = VTOMI4(vp);
12334 	if (nfs_zone() != mi->mi_zone)
12335 		return (EIO);
12336 
12337 	bzero(&gar, sizeof (gar));
12338 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12339 
12340 	/*
12341 	 * vsecattr->vsa_mask holds the original acl request mask.
12342 	 * This is needed when determining what to return.
12343 	 * (See: nfs4_create_getsecattr_return())
12344 	 */
12345 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12346 	if (error) /* EINVAL */
12347 		return (error);
12348 
12349 	/*
12350 	 * If this is a referral stub, don't try to go OTW for an ACL
12351 	 */
12352 	if (RP_ISSTUB_REFERRAL(VTOR4(vp)))
12353 		return (fs_fab_acl(vp, vsecattr, flag, cr, ct));
12354 
12355 	if (mi->mi_flags & MI4_ACL) {
12356 		/*
12357 		 * Check if the data is cached and the cache is valid.  If it
12358 		 * is we don't go over the wire.
12359 		 */
12360 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12361 			mutex_enter(&rp->r_statelock);
12362 			if (rp->r_secattr != NULL) {
12363 				error = nfs4_create_getsecattr_return(
12364 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12365 				    rp->r_attr.va_gid,
12366 				    vp->v_type == VDIR);
12367 				if (!error) { /* error == 0 - Success! */
12368 					mutex_exit(&rp->r_statelock);
12369 					return (error);
12370 				}
12371 			}
12372 			mutex_exit(&rp->r_statelock);
12373 		}
12374 
12375 		/*
12376 		 * The getattr otw call will always get both the acl, in
12377 		 * the form of a list of nfsace4's, and the number of acl
12378 		 * entries; independent of the value of gar.n4g_va.va_mask.
12379 		 */
12380 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12381 		if (error) {
12382 			vs_ace4_destroy(&gar.n4g_vsa);
12383 			if (error == ENOTSUP || error == EOPNOTSUPP)
12384 				error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12385 			return (error);
12386 		}
12387 
12388 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12389 			/*
12390 			 * No error was returned, but according to the response
12391 			 * bitmap, neither was an acl.
12392 			 */
12393 			vs_ace4_destroy(&gar.n4g_vsa);
12394 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12395 			return (error);
12396 		}
12397 
12398 		/*
12399 		 * Update the cache with the ACL.
12400 		 */
12401 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12402 
12403 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12404 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12405 		    vp->v_type == VDIR);
12406 		vs_ace4_destroy(&gar.n4g_vsa);
12407 		if ((error) && (vsecattr->vsa_mask &
12408 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12409 		    (error != EACCES)) {
12410 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12411 		}
12412 		return (error);
12413 	}
12414 	error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12415 	return (error);
12416 }
12417 
12418 /*
12419  * The function returns:
12420  * 	- 0 (zero) if the passed in "acl_mask" is a valid request.
12421  * 	- EINVAL if the passed in "acl_mask" is an invalid request.
12422  *
12423  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12424  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12425  *
12426  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12427  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12428  * - We have a count field set without the corresponding acl field set. (e.g. -
12429  * VSA_ACECNT is set, but VSA_ACE is not)
12430  */
12431 static int
12432 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12433 {
12434 	/* Shortcut the masks that are always valid. */
12435 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12436 		return (0);
12437 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12438 		return (0);
12439 
12440 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12441 		/*
12442 		 * We can't have any VSA_ACL type stuff in the mask now.
12443 		 */
12444 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12445 		    VSA_DFACLCNT))
12446 			return (EINVAL);
12447 
12448 		if (op == NFS4_ACL_SET) {
12449 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12450 				return (EINVAL);
12451 		}
12452 	}
12453 
12454 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12455 		/*
12456 		 * We can't have any VSA_ACE type stuff in the mask now.
12457 		 */
12458 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12459 			return (EINVAL);
12460 
12461 		if (op == NFS4_ACL_SET) {
12462 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12463 				return (EINVAL);
12464 
12465 			if ((acl_mask & VSA_DFACLCNT) &&
12466 			    !(acl_mask & VSA_DFACL))
12467 				return (EINVAL);
12468 		}
12469 	}
12470 	return (0);
12471 }
12472 
12473 /*
12474  * The theory behind creating the correct getsecattr return is simply this:
12475  * "Don't return anything that the caller is not expecting to have to free."
12476  */
12477 static int
12478 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12479     uid_t uid, gid_t gid, int isdir)
12480 {
12481 	int error = 0;
12482 	/* Save the mask since the translators modify it. */
12483 	uint_t	orig_mask = vsap->vsa_mask;
12484 
12485 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12486 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid, FALSE);
12487 
12488 		if (error)
12489 			return (error);
12490 
12491 		/*
12492 		 * If the caller only asked for the ace count (VSA_ACECNT)
12493 		 * don't give them the full acl (VSA_ACE), free it.
12494 		 */
12495 		if (!orig_mask & VSA_ACE) {
12496 			if (vsap->vsa_aclentp != NULL) {
12497 				kmem_free(vsap->vsa_aclentp,
12498 				    vsap->vsa_aclcnt * sizeof (ace_t));
12499 				vsap->vsa_aclentp = NULL;
12500 			}
12501 		}
12502 		vsap->vsa_mask = orig_mask;
12503 
12504 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12505 	    VSA_DFACLCNT)) {
12506 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12507 		    isdir, FALSE);
12508 
12509 		if (error)
12510 			return (error);
12511 
12512 		/*
12513 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12514 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12515 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12516 		 */
12517 		if (!orig_mask & VSA_ACL) {
12518 			if (vsap->vsa_aclentp != NULL) {
12519 				kmem_free(vsap->vsa_aclentp,
12520 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12521 				vsap->vsa_aclentp = NULL;
12522 			}
12523 		}
12524 
12525 		if (!orig_mask & VSA_DFACL) {
12526 			if (vsap->vsa_dfaclentp != NULL) {
12527 				kmem_free(vsap->vsa_dfaclentp,
12528 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12529 				vsap->vsa_dfaclentp = NULL;
12530 			}
12531 		}
12532 		vsap->vsa_mask = orig_mask;
12533 	}
12534 	return (0);
12535 }
12536 
12537 /* ARGSUSED */
12538 int
12539 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr,
12540     caller_context_t *ct)
12541 {
12542 	int error;
12543 
12544 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12545 		return (EIO);
12546 	/*
12547 	 * check for valid cmd parameter
12548 	 */
12549 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12550 		return (EINVAL);
12551 
12552 	/*
12553 	 * Check access permissions
12554 	 */
12555 	if ((cmd & F_SHARE) &&
12556 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12557 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12558 		return (EBADF);
12559 
12560 	/*
12561 	 * If the filesystem is mounted using local locking, pass the
12562 	 * request off to the local share code.
12563 	 */
12564 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12565 		return (fs_shrlock(vp, cmd, shr, flag, cr, ct));
12566 
12567 	switch (cmd) {
12568 	case F_SHARE:
12569 	case F_UNSHARE:
12570 		/*
12571 		 * This will be properly implemented later,
12572 		 * see RFE: 4823948 .
12573 		 */
12574 		error = EAGAIN;
12575 		break;
12576 
12577 	case F_HASREMOTELOCKS:
12578 		/*
12579 		 * NFS client can't store remote locks itself
12580 		 */
12581 		shr->s_access = 0;
12582 		error = 0;
12583 		break;
12584 
12585 	default:
12586 		error = EINVAL;
12587 		break;
12588 	}
12589 
12590 	return (error);
12591 }
12592 
12593 /*
12594  * Common code called by directory ops to update the attrcache
12595  */
12596 static int
12597 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12598     hrtime_t t, vnode_t *vp, cred_t *cr)
12599 {
12600 	int error = 0;
12601 
12602 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12603 
12604 	if (status != NFS4_OK) {
12605 		/* getattr not done or failed */
12606 		PURGE_ATTRCACHE4(vp);
12607 		return (error);
12608 	}
12609 
12610 	if (garp) {
12611 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12612 	} else {
12613 		PURGE_ATTRCACHE4(vp);
12614 	}
12615 	return (error);
12616 }
12617 
12618 /*
12619  * Update directory caches for directory modification ops (link, rename, etc.)
12620  * When dinfo is NULL, manage dircaches in the old way.
12621  */
12622 static void
12623 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12624     dirattr_info_t *dinfo)
12625 {
12626 	rnode4_t	*drp = VTOR4(dvp);
12627 
12628 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12629 
12630 	/* Purge rddir cache for dir since it changed */
12631 	if (drp->r_dir != NULL)
12632 		nfs4_purge_rddir_cache(dvp);
12633 
12634 	/*
12635 	 * If caller provided dinfo, then use it to manage dir caches.
12636 	 */
12637 	if (dinfo != NULL) {
12638 		if (vp != NULL) {
12639 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12640 			if (!VTOR4(vp)->created_v4) {
12641 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12642 				dnlc_update(dvp, nm, vp);
12643 			} else {
12644 				/*
12645 				 * XXX don't update if the created_v4 flag is
12646 				 * set
12647 				 */
12648 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12649 				NFS4_DEBUG(nfs4_client_state_debug,
12650 				    (CE_NOTE, "nfs4_update_dircaches: "
12651 				    "don't update dnlc: created_v4 flag"));
12652 			}
12653 		}
12654 
12655 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12656 		    dinfo->di_cred, FALSE, cinfo);
12657 
12658 		return;
12659 	}
12660 
12661 	/*
12662 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12663 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12664 	 * attrs, the dir's attrs must be purged.
12665 	 *
12666 	 * XXX this check and dnlc update/purge should really be atomic,
12667 	 * XXX but can't use rnode statelock because it'll deadlock in
12668 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12669 	 * XXX does occur.
12670 	 *
12671 	 * XXX We also may want to check that atomic is true in the
12672 	 * XXX change_info struct. If it is not, the change_info may
12673 	 * XXX reflect changes by more than one clients which means that
12674 	 * XXX our cache may not be valid.
12675 	 */
12676 	PURGE_ATTRCACHE4(dvp);
12677 	if (drp->r_change == cinfo->before) {
12678 		/* no changes took place in the directory prior to our link */
12679 		if (vp != NULL) {
12680 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12681 			if (!VTOR4(vp)->created_v4) {
12682 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12683 				dnlc_update(dvp, nm, vp);
12684 			} else {
12685 				/*
12686 				 * XXX dont' update if the created_v4 flag
12687 				 * is set
12688 				 */
12689 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12690 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12691 				    "nfs4_update_dircaches: don't"
12692 				    " update dnlc: created_v4 flag"));
12693 			}
12694 		}
12695 	} else {
12696 		/* Another client modified directory - purge its dnlc cache */
12697 		dnlc_purge_vp(dvp);
12698 	}
12699 }
12700 
12701 /*
12702  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12703  * file.
12704  *
12705  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12706  * file (ie: client recovery) and otherwise set to FALSE.
12707  *
12708  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12709  * initiated) calling functions.
12710  *
12711  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12712  * of resending a 'lost' open request.
12713  *
12714  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12715  * server that hands out BAD_SEQID on open confirm.
12716  *
12717  * Errors are returned via the nfs4_error_t parameter.
12718  */
12719 void
12720 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12721     bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12722     bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12723 {
12724 	COMPOUND4args_clnt args;
12725 	COMPOUND4res_clnt res;
12726 	nfs_argop4 argop[2];
12727 	nfs_resop4 *resop;
12728 	int doqueue = 1;
12729 	mntinfo4_t *mi;
12730 	OPEN_CONFIRM4args *open_confirm_args;
12731 	int needrecov;
12732 
12733 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12734 #if DEBUG
12735 	mutex_enter(&oop->oo_lock);
12736 	ASSERT(oop->oo_seqid_inuse);
12737 	mutex_exit(&oop->oo_lock);
12738 #endif
12739 
12740 recov_retry_confirm:
12741 	nfs4_error_zinit(ep);
12742 	*retry_open = FALSE;
12743 
12744 	if (resend)
12745 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12746 	else
12747 		args.ctag = TAG_OPEN_CONFIRM;
12748 
12749 	args.array_len = 2;
12750 	args.array = argop;
12751 
12752 	/* putfh target fh */
12753 	argop[0].argop = OP_CPUTFH;
12754 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12755 
12756 	argop[1].argop = OP_OPEN_CONFIRM;
12757 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12758 
12759 	(*seqid) += 1;
12760 	open_confirm_args->seqid = *seqid;
12761 	open_confirm_args->open_stateid = *stateid;
12762 
12763 	mi = VTOMI4(vp);
12764 
12765 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12766 
12767 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12768 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12769 	}
12770 
12771 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12772 	if (!needrecov && ep->error)
12773 		return;
12774 
12775 	if (needrecov) {
12776 		bool_t abort = FALSE;
12777 
12778 		if (reopening_file == FALSE) {
12779 			nfs4_bseqid_entry_t *bsep = NULL;
12780 
12781 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12782 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12783 				    vp, 0, args.ctag,
12784 				    open_confirm_args->seqid);
12785 
12786 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
12787 			    NULL, NULL, OP_OPEN_CONFIRM, bsep, NULL, NULL);
12788 			if (bsep) {
12789 				kmem_free(bsep, sizeof (*bsep));
12790 				if (num_bseqid_retryp &&
12791 				    --(*num_bseqid_retryp) == 0)
12792 					abort = TRUE;
12793 			}
12794 		}
12795 		if ((ep->error == ETIMEDOUT ||
12796 		    res.status == NFS4ERR_RESOURCE) &&
12797 		    abort == FALSE && resend == FALSE) {
12798 			if (!ep->error)
12799 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12800 				    (caddr_t)&res);
12801 
12802 			delay(SEC_TO_TICK(confirm_retry_sec));
12803 			goto recov_retry_confirm;
12804 		}
12805 		/* State may have changed so retry the entire OPEN op */
12806 		if (abort == FALSE)
12807 			*retry_open = TRUE;
12808 		else
12809 			*retry_open = FALSE;
12810 		if (!ep->error)
12811 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12812 		return;
12813 	}
12814 
12815 	if (res.status) {
12816 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12817 		return;
12818 	}
12819 
12820 	resop = &res.array[1];  /* open confirm res */
12821 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
12822 	    stateid, sizeof (*stateid));
12823 
12824 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12825 }
12826 
12827 /*
12828  * Return the credentials associated with a client state object.  The
12829  * caller is responsible for freeing the credentials.
12830  */
12831 
12832 static cred_t *
12833 state_to_cred(nfs4_open_stream_t *osp)
12834 {
12835 	cred_t *cr;
12836 
12837 	/*
12838 	 * It's ok to not lock the open stream and open owner to get
12839 	 * the oo_cred since this is only written once (upon creation)
12840 	 * and will not change.
12841 	 */
12842 	cr = osp->os_open_owner->oo_cred;
12843 	crhold(cr);
12844 
12845 	return (cr);
12846 }
12847 
12848 /*
12849  * nfs4_find_sysid
12850  *
12851  * Find the sysid for the knetconfig associated with the given mi.
12852  */
12853 static struct lm_sysid *
12854 nfs4_find_sysid(mntinfo4_t *mi)
12855 {
12856 	ASSERT(nfs_zone() == mi->mi_zone);
12857 
12858 	/*
12859 	 * Switch from RDMA knconf to original mount knconf
12860 	 */
12861 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
12862 	    mi->mi_curr_serv->sv_hostname, NULL));
12863 }
12864 
12865 #ifdef DEBUG
12866 /*
12867  * Return a string version of the call type for easy reading.
12868  */
12869 static char *
12870 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
12871 {
12872 	switch (ctype) {
12873 	case NFS4_LCK_CTYPE_NORM:
12874 		return ("NORMAL");
12875 	case NFS4_LCK_CTYPE_RECLAIM:
12876 		return ("RECLAIM");
12877 	case NFS4_LCK_CTYPE_RESEND:
12878 		return ("RESEND");
12879 	case NFS4_LCK_CTYPE_REINSTATE:
12880 		return ("REINSTATE");
12881 	default:
12882 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
12883 		    "type %d", ctype);
12884 		return ("");
12885 	}
12886 }
12887 #endif
12888 
12889 /*
12890  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
12891  * Unlock requests don't have an over-the-wire locktype, so we just return
12892  * something non-threatening.
12893  */
12894 
12895 static nfs_lock_type4
12896 flk_to_locktype(int cmd, int l_type)
12897 {
12898 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
12899 
12900 	switch (l_type) {
12901 	case F_UNLCK:
12902 		return (READ_LT);
12903 	case F_RDLCK:
12904 		if (cmd == F_SETLK)
12905 			return (READ_LT);
12906 		else
12907 			return (READW_LT);
12908 	case F_WRLCK:
12909 		if (cmd == F_SETLK)
12910 			return (WRITE_LT);
12911 		else
12912 			return (WRITEW_LT);
12913 	}
12914 	panic("flk_to_locktype");
12915 	/*NOTREACHED*/
12916 }
12917 
12918 /*
12919  * Do some preliminary checks for nfs4frlock.
12920  */
12921 static int
12922 nfs4frlock_validate_args(int cmd, flock64_t *flk, int flag, vnode_t *vp,
12923     u_offset_t offset)
12924 {
12925 	int error = 0;
12926 
12927 	/*
12928 	 * If we are setting a lock, check that the file is opened
12929 	 * with the correct mode.
12930 	 */
12931 	if (cmd == F_SETLK || cmd == F_SETLKW) {
12932 		if ((flk->l_type == F_RDLCK && (flag & FREAD) == 0) ||
12933 		    (flk->l_type == F_WRLCK && (flag & FWRITE) == 0)) {
12934 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12935 			    "nfs4frlock_validate_args: file was opened with "
12936 			    "incorrect mode"));
12937 			return (EBADF);
12938 		}
12939 	}
12940 
12941 	/* Convert the offset. It may need to be restored before returning. */
12942 	if (error = convoff(vp, flk, 0, offset)) {
12943 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12944 		    "nfs4frlock_validate_args: convoff  =>  error= %d\n",
12945 		    error));
12946 		return (error);
12947 	}
12948 
12949 	return (error);
12950 }
12951 
12952 /*
12953  * Set the flock64's lm_sysid for nfs4frlock.
12954  */
12955 static int
12956 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
12957 {
12958 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12959 
12960 	/* Find the lm_sysid */
12961 	*lspp = nfs4_find_sysid(VTOMI4(vp));
12962 
12963 	if (*lspp == NULL) {
12964 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12965 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
12966 		return (ENOLCK);
12967 	}
12968 
12969 	flk->l_sysid = lm_sysidt(*lspp);
12970 
12971 	return (0);
12972 }
12973 
12974 /*
12975  * Do the remaining preliminary setup for nfs4frlock.
12976  */
12977 static void
12978 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
12979     flock64_t *flk, short *whencep, vnode_t *vp, cred_t *search_cr,
12980     cred_t **cred_otw)
12981 {
12982 	/*
12983 	 * set tick_delay to the base delay time.
12984 	 * (NFS4_BASE_WAIT_TIME is in secs)
12985 	 */
12986 
12987 	*tick_delayp = drv_usectohz(NFS4_BASE_WAIT_TIME * 1000 * 1000);
12988 
12989 	/*
12990 	 * If lock is relative to EOF, we need the newest length of the
12991 	 * file. Therefore invalidate the ATTR_CACHE.
12992 	 */
12993 
12994 	*whencep = flk->l_whence;
12995 
12996 	if (*whencep == 2)		/* SEEK_END */
12997 		PURGE_ATTRCACHE4(vp);
12998 
12999 	recov_statep->rs_flags = 0;
13000 	recov_statep->rs_num_retry_despite_err = 0;
13001 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
13002 }
13003 
13004 /*
13005  * Initialize and allocate the data structures necessary for
13006  * the nfs4frlock call.
13007  * Allocates argsp's op array.
13008  */
13009 static void
13010 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
13011     nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
13012     bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
13013     bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
13014 {
13015 	int		argoplist_size;
13016 	int		num_ops = 2;
13017 
13018 	*retry = FALSE;
13019 	*did_start_fop = FALSE;
13020 	*skip_get_err = FALSE;
13021 	lost_rqstp->lr_op = 0;
13022 	argoplist_size  = num_ops * sizeof (nfs_argop4);
13023 	/* fill array with zero */
13024 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
13025 
13026 	*argspp = argsp;
13027 	*respp = NULL;
13028 
13029 	argsp->array_len = num_ops;
13030 	argsp->array = *argopp;
13031 
13032 	/* initialize in case of error; will get real value down below */
13033 	argsp->ctag = TAG_NONE;
13034 
13035 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
13036 		*op_hintp = OH_LOCKU;
13037 	else
13038 		*op_hintp = OH_OTHER;
13039 }
13040 
13041 /*
13042  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
13043  * the proper nfs4_server_t for this instance of nfs4frlock.
13044  * Returns 0 (success) or an errno value.
13045  */
13046 static int
13047 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
13048     nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
13049     bool_t *did_start_fop, bool_t *startrecovp)
13050 {
13051 	int error = 0;
13052 	rnode4_t *rp;
13053 
13054 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13055 
13056 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13057 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
13058 		    recov_statep, startrecovp);
13059 		if (error)
13060 			return (error);
13061 		*did_start_fop = TRUE;
13062 	} else {
13063 		*did_start_fop = FALSE;
13064 		*startrecovp = FALSE;
13065 	}
13066 
13067 	if (!error) {
13068 		rp = VTOR4(vp);
13069 
13070 		/* If the file failed recovery, just quit. */
13071 		mutex_enter(&rp->r_statelock);
13072 		if (rp->r_flags & R4RECOVERR) {
13073 			error = EIO;
13074 		}
13075 		mutex_exit(&rp->r_statelock);
13076 	}
13077 
13078 	return (error);
13079 }
13080 
13081 /*
13082  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
13083  * resend nfs4frlock call is initiated by the recovery framework.
13084  * Acquires the lop and oop seqid synchronization.
13085  */
13086 static void
13087 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
13088     COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
13089     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13090     LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
13091 {
13092 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
13093 	int error;
13094 
13095 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
13096 	    (CE_NOTE,
13097 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
13098 	ASSERT(resend_rqstp != NULL);
13099 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
13100 	    resend_rqstp->lr_op == OP_LOCKU);
13101 
13102 	*oopp = resend_rqstp->lr_oop;
13103 	if (resend_rqstp->lr_oop) {
13104 		open_owner_hold(resend_rqstp->lr_oop);
13105 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
13106 		ASSERT(error == 0);	/* recov thread always succeeds */
13107 	}
13108 
13109 	/* Must resend this lost lock/locku request. */
13110 	ASSERT(resend_rqstp->lr_lop != NULL);
13111 	*lopp = resend_rqstp->lr_lop;
13112 	lock_owner_hold(resend_rqstp->lr_lop);
13113 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
13114 	ASSERT(error == 0);	/* recov thread always succeeds */
13115 
13116 	*ospp = resend_rqstp->lr_osp;
13117 	if (*ospp)
13118 		open_stream_hold(resend_rqstp->lr_osp);
13119 
13120 	if (resend_rqstp->lr_op == OP_LOCK) {
13121 		LOCK4args *lock_args;
13122 
13123 		argop->argop = OP_LOCK;
13124 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
13125 		lock_args->locktype = resend_rqstp->lr_locktype;
13126 		lock_args->reclaim =
13127 		    (resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
13128 		lock_args->offset = resend_rqstp->lr_flk->l_start;
13129 		lock_args->length = resend_rqstp->lr_flk->l_len;
13130 		if (lock_args->length == 0)
13131 			lock_args->length = ~lock_args->length;
13132 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
13133 		    mi2clientid(mi), &lock_args->locker);
13134 
13135 		switch (resend_rqstp->lr_ctype) {
13136 		case NFS4_LCK_CTYPE_RESEND:
13137 			argsp->ctag = TAG_LOCK_RESEND;
13138 			break;
13139 		case NFS4_LCK_CTYPE_REINSTATE:
13140 			argsp->ctag = TAG_LOCK_REINSTATE;
13141 			break;
13142 		case NFS4_LCK_CTYPE_RECLAIM:
13143 			argsp->ctag = TAG_LOCK_RECLAIM;
13144 			break;
13145 		default:
13146 			argsp->ctag = TAG_LOCK_UNKNOWN;
13147 			break;
13148 		}
13149 	} else {
13150 		LOCKU4args *locku_args;
13151 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
13152 
13153 		argop->argop = OP_LOCKU;
13154 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
13155 		locku_args->locktype = READ_LT;
13156 		locku_args->seqid = lop->lock_seqid + 1;
13157 		mutex_enter(&lop->lo_lock);
13158 		locku_args->lock_stateid = lop->lock_stateid;
13159 		mutex_exit(&lop->lo_lock);
13160 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13161 		locku_args->length = resend_rqstp->lr_flk->l_len;
13162 		if (locku_args->length == 0)
13163 			locku_args->length = ~locku_args->length;
13164 
13165 		switch (resend_rqstp->lr_ctype) {
13166 		case NFS4_LCK_CTYPE_RESEND:
13167 			argsp->ctag = TAG_LOCKU_RESEND;
13168 			break;
13169 		case NFS4_LCK_CTYPE_REINSTATE:
13170 			argsp->ctag = TAG_LOCKU_REINSTATE;
13171 			break;
13172 		default:
13173 			argsp->ctag = TAG_LOCK_UNKNOWN;
13174 			break;
13175 		}
13176 	}
13177 }
13178 
13179 /*
13180  * Setup the LOCKT4 arguments.
13181  */
13182 static void
13183 nfs4frlock_setup_lockt_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13184     LOCKT4args **lockt_argsp, COMPOUND4args_clnt *argsp, flock64_t *flk,
13185     rnode4_t *rp)
13186 {
13187 	LOCKT4args *lockt_args;
13188 
13189 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13190 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13191 	argop->argop = OP_LOCKT;
13192 	argsp->ctag = TAG_LOCKT;
13193 	lockt_args = &argop->nfs_argop4_u.oplockt;
13194 
13195 	/*
13196 	 * The locktype will be READ_LT unless it's
13197 	 * a write lock. We do this because the Solaris
13198 	 * system call allows the combination of
13199 	 * F_UNLCK and F_GETLK* and so in that case the
13200 	 * unlock is mapped to a read.
13201 	 */
13202 	if (flk->l_type == F_WRLCK)
13203 		lockt_args->locktype = WRITE_LT;
13204 	else
13205 		lockt_args->locktype = READ_LT;
13206 
13207 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13208 	/* set the lock owner4 args */
13209 	nfs4_setlockowner_args(&lockt_args->owner, rp,
13210 	    ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13211 	    flk->l_pid);
13212 	lockt_args->offset = flk->l_start;
13213 	lockt_args->length = flk->l_len;
13214 	if (flk->l_len == 0)
13215 		lockt_args->length = ~lockt_args->length;
13216 
13217 	*lockt_argsp = lockt_args;
13218 }
13219 
13220 /*
13221  * If the client is holding a delegation, and the open stream to be used
13222  * with this lock request is a delegation open stream, then re-open the stream.
13223  * Sets the nfs4_error_t to all zeros unless the open stream has already
13224  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13225  * means the caller should retry (like a recovery retry).
13226  */
13227 static void
13228 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13229 {
13230 	open_delegation_type4	dt;
13231 	bool_t			reopen_needed, force;
13232 	nfs4_open_stream_t	*osp;
13233 	open_claim_type4 	oclaim;
13234 	rnode4_t		*rp = VTOR4(vp);
13235 	mntinfo4_t		*mi = VTOMI4(vp);
13236 
13237 	ASSERT(nfs_zone() == mi->mi_zone);
13238 
13239 	nfs4_error_zinit(ep);
13240 
13241 	mutex_enter(&rp->r_statev4_lock);
13242 	dt = rp->r_deleg_type;
13243 	mutex_exit(&rp->r_statev4_lock);
13244 
13245 	if (dt != OPEN_DELEGATE_NONE) {
13246 		nfs4_open_owner_t	*oop;
13247 
13248 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13249 		if (!oop) {
13250 			ep->stat = NFS4ERR_IO;
13251 			return;
13252 		}
13253 		/* returns with 'os_sync_lock' held */
13254 		osp = find_open_stream(oop, rp);
13255 		if (!osp) {
13256 			open_owner_rele(oop);
13257 			ep->stat = NFS4ERR_IO;
13258 			return;
13259 		}
13260 
13261 		if (osp->os_failed_reopen) {
13262 			NFS4_DEBUG((nfs4_open_stream_debug ||
13263 			    nfs4_client_lock_debug), (CE_NOTE,
13264 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13265 			    "for osp %p, cr %p, rp %s", (void *)osp,
13266 			    (void *)cr, rnode4info(rp)));
13267 			mutex_exit(&osp->os_sync_lock);
13268 			open_stream_rele(osp, rp);
13269 			open_owner_rele(oop);
13270 			ep->stat = NFS4ERR_IO;
13271 			return;
13272 		}
13273 
13274 		/*
13275 		 * Determine whether a reopen is needed.  If this
13276 		 * is a delegation open stream, then send the open
13277 		 * to the server to give visibility to the open owner.
13278 		 * Even if it isn't a delegation open stream, we need
13279 		 * to check if the previous open CLAIM_DELEGATE_CUR
13280 		 * was sufficient.
13281 		 */
13282 
13283 		reopen_needed = osp->os_delegation ||
13284 		    ((lt == F_RDLCK &&
13285 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13286 		    (lt == F_WRLCK &&
13287 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13288 
13289 		mutex_exit(&osp->os_sync_lock);
13290 		open_owner_rele(oop);
13291 
13292 		if (reopen_needed) {
13293 			/*
13294 			 * Always use CLAIM_PREVIOUS after server reboot.
13295 			 * The server will reject CLAIM_DELEGATE_CUR if
13296 			 * it is used during the grace period.
13297 			 */
13298 			mutex_enter(&mi->mi_lock);
13299 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13300 				oclaim = CLAIM_PREVIOUS;
13301 				force = TRUE;
13302 			} else {
13303 				oclaim = CLAIM_DELEGATE_CUR;
13304 				force = FALSE;
13305 			}
13306 			mutex_exit(&mi->mi_lock);
13307 
13308 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13309 			if (ep->error == EAGAIN) {
13310 				nfs4_error_zinit(ep);
13311 				ep->stat = NFS4ERR_DELAY;
13312 			}
13313 		}
13314 		open_stream_rele(osp, rp);
13315 		osp = NULL;
13316 	}
13317 }
13318 
13319 /*
13320  * Setup the LOCKU4 arguments.
13321  * Returns errors via the nfs4_error_t.
13322  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13323  *			over-the-wire.  The caller must release the
13324  *			reference on *lopp.
13325  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13326  * (other)		unrecoverable error.
13327  */
13328 static void
13329 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13330     LOCKU4args **locku_argsp, flock64_t *flk,
13331     nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13332     vnode_t *vp, int flag, u_offset_t offset, cred_t *cr,
13333     bool_t *skip_get_err, bool_t *go_otwp)
13334 {
13335 	nfs4_lock_owner_t	*lop = NULL;
13336 	LOCKU4args		*locku_args;
13337 	pid_t			pid;
13338 	bool_t			is_spec = FALSE;
13339 	rnode4_t		*rp = VTOR4(vp);
13340 
13341 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13342 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13343 
13344 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13345 	if (ep->error || ep->stat)
13346 		return;
13347 
13348 	argop->argop = OP_LOCKU;
13349 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13350 		argsp->ctag = TAG_LOCKU_REINSTATE;
13351 	else
13352 		argsp->ctag = TAG_LOCKU;
13353 	locku_args = &argop->nfs_argop4_u.oplocku;
13354 	*locku_argsp = locku_args;
13355 
13356 	/* locktype should be set to any legal value */
13357 	locku_args->locktype = READ_LT;
13358 
13359 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13360 	    flk->l_pid;
13361 
13362 	/*
13363 	 * Get the lock owner stateid.  If no lock owner
13364 	 * exists, return success.
13365 	 */
13366 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13367 	*lopp = lop;
13368 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13369 		is_spec = TRUE;
13370 	if (!lop || is_spec) {
13371 		/*
13372 		 * No lock owner so no locks to unlock.
13373 		 * Return success.  If there was a failed
13374 		 * reclaim earlier, the lock might still be
13375 		 * registered with the local locking code,
13376 		 * so notify it of the unlock.
13377 		 *
13378 		 * If the lockowner is using a special stateid,
13379 		 * then the original lock request (that created
13380 		 * this lockowner) was never successful, so we
13381 		 * have no lock to undo OTW.
13382 		 */
13383 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13384 		    "nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13385 		    "(%ld) so return success", (long)pid));
13386 
13387 		if (ctype == NFS4_LCK_CTYPE_NORM)
13388 			flk->l_pid = curproc->p_pid;
13389 		nfs4_register_lock_locally(vp, flk, flag, offset);
13390 		/*
13391 		 * Release our hold and NULL out so final_cleanup
13392 		 * doesn't try to end a lock seqid sync we
13393 		 * never started.
13394 		 */
13395 		if (is_spec) {
13396 			lock_owner_rele(lop);
13397 			*lopp = NULL;
13398 		}
13399 		*skip_get_err = TRUE;
13400 		*go_otwp = FALSE;
13401 		return;
13402 	}
13403 
13404 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13405 	if (ep->error == EAGAIN) {
13406 		lock_owner_rele(lop);
13407 		*lopp = NULL;
13408 		return;
13409 	}
13410 
13411 	mutex_enter(&lop->lo_lock);
13412 	locku_args->lock_stateid = lop->lock_stateid;
13413 	mutex_exit(&lop->lo_lock);
13414 	locku_args->seqid = lop->lock_seqid + 1;
13415 
13416 	/* leave the ref count on lop, rele after RPC call */
13417 
13418 	locku_args->offset = flk->l_start;
13419 	locku_args->length = flk->l_len;
13420 	if (flk->l_len == 0)
13421 		locku_args->length = ~locku_args->length;
13422 
13423 	*go_otwp = TRUE;
13424 }
13425 
13426 /*
13427  * Setup the LOCK4 arguments.
13428  *
13429  * Returns errors via the nfs4_error_t.
13430  * NFS4_OK		no problems
13431  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13432  * (other)		unrecoverable error
13433  */
13434 static void
13435 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13436     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13437     nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13438     flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13439 {
13440 	LOCK4args		*lock_args;
13441 	nfs4_open_owner_t	*oop = NULL;
13442 	nfs4_open_stream_t	*osp = NULL;
13443 	nfs4_lock_owner_t	*lop = NULL;
13444 	pid_t			pid;
13445 	rnode4_t		*rp = VTOR4(vp);
13446 
13447 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13448 
13449 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13450 	if (ep->error || ep->stat != NFS4_OK)
13451 		return;
13452 
13453 	argop->argop = OP_LOCK;
13454 	if (ctype == NFS4_LCK_CTYPE_NORM)
13455 		argsp->ctag = TAG_LOCK;
13456 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13457 		argsp->ctag = TAG_RELOCK;
13458 	else
13459 		argsp->ctag = TAG_LOCK_REINSTATE;
13460 	lock_args = &argop->nfs_argop4_u.oplock;
13461 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13462 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13463 	/*
13464 	 * Get the lock owner.  If no lock owner exists,
13465 	 * create a 'temporary' one and grab the open seqid
13466 	 * synchronization (which puts a hold on the open
13467 	 * owner and open stream).
13468 	 * This also grabs the lock seqid synchronization.
13469 	 */
13470 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid : flk->l_pid;
13471 	ep->stat =
13472 	    nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13473 
13474 	if (ep->stat != NFS4_OK)
13475 		goto out;
13476 
13477 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13478 	    &lock_args->locker);
13479 
13480 	lock_args->offset = flk->l_start;
13481 	lock_args->length = flk->l_len;
13482 	if (flk->l_len == 0)
13483 		lock_args->length = ~lock_args->length;
13484 	*lock_argsp = lock_args;
13485 out:
13486 	*oopp = oop;
13487 	*ospp = osp;
13488 	*lopp = lop;
13489 }
13490 
13491 /*
13492  * After we get the reply from the server, record the proper information
13493  * for possible resend lock requests.
13494  */
13495 static void
13496 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13497     nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13498     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13499     nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13500 {
13501 	bool_t unlock = (flk->l_type == F_UNLCK);
13502 
13503 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13504 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13505 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13506 
13507 	if (error != 0 && !unlock) {
13508 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13509 		    nfs4_client_lock_debug), (CE_NOTE,
13510 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13511 		    " for lop %p", (void *)lop));
13512 		ASSERT(lop != NULL);
13513 		mutex_enter(&lop->lo_lock);
13514 		lop->lo_pending_rqsts = 1;
13515 		mutex_exit(&lop->lo_lock);
13516 	}
13517 
13518 	lost_rqstp->lr_putfirst = FALSE;
13519 	lost_rqstp->lr_op = 0;
13520 
13521 	/*
13522 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13523 	 * recovery purposes so that the lock request that was sent
13524 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13525 	 * unmount.  This is done to have the client's local locking state
13526 	 * match the v4 server's state; that is, the request was
13527 	 * potentially received and accepted by the server but the client
13528 	 * thinks it was not.
13529 	 */
13530 	if (error == ETIMEDOUT || error == EINTR ||
13531 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13532 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13533 		    nfs4_client_lock_debug), (CE_NOTE,
13534 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13535 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13536 		    (void *)lop, (void *)oop, (void *)osp));
13537 		if (unlock)
13538 			lost_rqstp->lr_op = OP_LOCKU;
13539 		else {
13540 			lost_rqstp->lr_op = OP_LOCK;
13541 			lost_rqstp->lr_locktype = locktype;
13542 		}
13543 		/*
13544 		 * Objects are held and rele'd via the recovery code.
13545 		 * See nfs4_save_lost_rqst.
13546 		 */
13547 		lost_rqstp->lr_vp = vp;
13548 		lost_rqstp->lr_dvp = NULL;
13549 		lost_rqstp->lr_oop = oop;
13550 		lost_rqstp->lr_osp = osp;
13551 		lost_rqstp->lr_lop = lop;
13552 		lost_rqstp->lr_cr = cr;
13553 		switch (ctype) {
13554 		case NFS4_LCK_CTYPE_NORM:
13555 			flk->l_pid = ttoproc(curthread)->p_pid;
13556 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13557 			break;
13558 		case NFS4_LCK_CTYPE_REINSTATE:
13559 			lost_rqstp->lr_putfirst = TRUE;
13560 			lost_rqstp->lr_ctype = ctype;
13561 			break;
13562 		default:
13563 			break;
13564 		}
13565 		lost_rqstp->lr_flk = flk;
13566 	}
13567 }
13568 
13569 /*
13570  * Update lop's seqid.  Also update the seqid stored in a resend request,
13571  * if any.  (Some recovery errors increment the seqid, and we may have to
13572  * send the resend request again.)
13573  */
13574 
13575 static void
13576 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13577     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13578 {
13579 	if (lock_args) {
13580 		if (lock_args->locker.new_lock_owner == TRUE)
13581 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13582 		else {
13583 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13584 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13585 		}
13586 	} else if (locku_args) {
13587 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13588 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13589 	}
13590 }
13591 
13592 /*
13593  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13594  * COMPOUND4 args/res for calls that need to retry.
13595  * Switches the *cred_otwp to base_cr.
13596  */
13597 static void
13598 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13599     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13600     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13601     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13602     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13603 {
13604 	nfs4_open_owner_t	*oop = *oopp;
13605 	nfs4_open_stream_t	*osp = *ospp;
13606 	nfs4_lock_owner_t	*lop = *lopp;
13607 	nfs_argop4		*argop = (*argspp)->array;
13608 
13609 	if (*did_start_fop) {
13610 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13611 		    needrecov);
13612 		*did_start_fop = FALSE;
13613 	}
13614 	ASSERT((*argspp)->array_len == 2);
13615 	if (argop[1].argop == OP_LOCK)
13616 		nfs4args_lock_free(&argop[1]);
13617 	else if (argop[1].argop == OP_LOCKT)
13618 		nfs4args_lockt_free(&argop[1]);
13619 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13620 	if (!error)
13621 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13622 	*argspp = NULL;
13623 	*respp = NULL;
13624 
13625 	if (lop) {
13626 		nfs4_end_lock_seqid_sync(lop);
13627 		lock_owner_rele(lop);
13628 		*lopp = NULL;
13629 	}
13630 
13631 	/* need to free up the reference on osp for lock args */
13632 	if (osp != NULL) {
13633 		open_stream_rele(osp, VTOR4(vp));
13634 		*ospp = NULL;
13635 	}
13636 
13637 	/* need to free up the reference on oop for lock args */
13638 	if (oop != NULL) {
13639 		nfs4_end_open_seqid_sync(oop);
13640 		open_owner_rele(oop);
13641 		*oopp = NULL;
13642 	}
13643 
13644 	crfree(*cred_otwp);
13645 	*cred_otwp = base_cr;
13646 	crhold(*cred_otwp);
13647 }
13648 
13649 /*
13650  * Function to process the client's recovery for nfs4frlock.
13651  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13652  *
13653  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13654  * COMPOUND4 args/res for calls that need to retry.
13655  *
13656  * Note: the rp's r_lkserlock is *not* dropped during this path.
13657  */
13658 static bool_t
13659 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13660     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13661     LOCK4args *lock_args, LOCKU4args *locku_args,
13662     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13663     nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13664     nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13665     bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13666 {
13667 	nfs4_open_owner_t	*oop = *oopp;
13668 	nfs4_open_stream_t	*osp = *ospp;
13669 	nfs4_lock_owner_t	*lop = *lopp;
13670 
13671 	bool_t abort, retry;
13672 
13673 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13674 	ASSERT((*argspp) != NULL);
13675 	ASSERT((*respp) != NULL);
13676 	if (lock_args || locku_args)
13677 		ASSERT(lop != NULL);
13678 
13679 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13680 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13681 
13682 	retry = TRUE;
13683 	abort = FALSE;
13684 	if (needrecov) {
13685 		nfs4_bseqid_entry_t *bsep = NULL;
13686 		nfs_opnum4 op;
13687 
13688 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13689 
13690 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13691 			seqid4 seqid;
13692 
13693 			if (lock_args) {
13694 				if (lock_args->locker.new_lock_owner == TRUE)
13695 					seqid = lock_args->locker.locker4_u.
13696 					    open_owner.open_seqid;
13697 				else
13698 					seqid = lock_args->locker.locker4_u.
13699 					    lock_owner.lock_seqid;
13700 			} else if (locku_args) {
13701 				seqid = locku_args->seqid;
13702 			} else {
13703 				seqid = 0;
13704 			}
13705 
13706 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13707 			    flk->l_pid, (*argspp)->ctag, seqid);
13708 		}
13709 
13710 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13711 		    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13712 		    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13713 		    NULL, op, bsep, NULL, NULL);
13714 
13715 		if (bsep)
13716 			kmem_free(bsep, sizeof (*bsep));
13717 	}
13718 
13719 	/*
13720 	 * Return that we do not want to retry the request for 3 cases:
13721 	 * 1. If we received EINTR or are bailing out because of a forced
13722 	 *    unmount, we came into this code path just for the sake of
13723 	 *    initiating recovery, we now need to return the error.
13724 	 * 2. If we have aborted recovery.
13725 	 * 3. We received NFS4ERR_BAD_SEQID.
13726 	 */
13727 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13728 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13729 		retry = FALSE;
13730 
13731 	if (*did_start_fop == TRUE) {
13732 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13733 		    needrecov);
13734 		*did_start_fop = FALSE;
13735 	}
13736 
13737 	if (retry == TRUE) {
13738 		nfs_argop4	*argop;
13739 
13740 		argop = (*argspp)->array;
13741 		ASSERT((*argspp)->array_len == 2);
13742 
13743 		if (argop[1].argop == OP_LOCK)
13744 			nfs4args_lock_free(&argop[1]);
13745 		else if (argop[1].argop == OP_LOCKT)
13746 			nfs4args_lockt_free(&argop[1]);
13747 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13748 		if (!ep->error)
13749 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13750 		*respp = NULL;
13751 		*argspp = NULL;
13752 	}
13753 
13754 	if (lop != NULL) {
13755 		nfs4_end_lock_seqid_sync(lop);
13756 		lock_owner_rele(lop);
13757 	}
13758 
13759 	*lopp = NULL;
13760 
13761 	/* need to free up the reference on osp for lock args */
13762 	if (osp != NULL) {
13763 		open_stream_rele(osp, rp);
13764 		*ospp = NULL;
13765 	}
13766 
13767 	/* need to free up the reference on oop for lock args */
13768 	if (oop != NULL) {
13769 		nfs4_end_open_seqid_sync(oop);
13770 		open_owner_rele(oop);
13771 		*oopp = NULL;
13772 	}
13773 
13774 	return (retry);
13775 }
13776 
13777 /*
13778  * Handles the successful reply from the server for nfs4frlock.
13779  */
13780 static void
13781 nfs4frlock_results_ok(nfs4_lock_call_type_t ctype, int cmd, flock64_t *flk,
13782     vnode_t *vp, int flag, u_offset_t offset,
13783     nfs4_lost_rqst_t *resend_rqstp)
13784 {
13785 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13786 	if ((cmd == F_SETLK || cmd == F_SETLKW) &&
13787 	    (flk->l_type == F_RDLCK || flk->l_type == F_WRLCK)) {
13788 		if (ctype == NFS4_LCK_CTYPE_NORM) {
13789 			flk->l_pid = ttoproc(curthread)->p_pid;
13790 			/*
13791 			 * We do not register lost locks locally in
13792 			 * the 'resend' case since the user/application
13793 			 * doesn't think we have the lock.
13794 			 */
13795 			ASSERT(!resend_rqstp);
13796 			nfs4_register_lock_locally(vp, flk, flag, offset);
13797 		}
13798 	}
13799 }
13800 
13801 /*
13802  * Handle the DENIED reply from the server for nfs4frlock.
13803  * Returns TRUE if we should retry the request; FALSE otherwise.
13804  *
13805  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13806  * COMPOUND4 args/res for calls that need to retry.  Can also
13807  * drop and regrab the r_lkserlock.
13808  */
13809 static bool_t
13810 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13811     LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13812     nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13813     vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13814     nfs4_recov_state_t *recov_statep, int needrecov,
13815     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13816     clock_t *tick_delayp, short *whencep, int *errorp,
13817     nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13818     bool_t *skip_get_err)
13819 {
13820 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13821 
13822 	if (lock_args) {
13823 		nfs4_open_owner_t	*oop = *oopp;
13824 		nfs4_open_stream_t	*osp = *ospp;
13825 		nfs4_lock_owner_t	*lop = *lopp;
13826 		int			intr;
13827 
13828 		/*
13829 		 * Blocking lock needs to sleep and retry from the request.
13830 		 *
13831 		 * Do not block and wait for 'resend' or 'reinstate'
13832 		 * lock requests, just return the error.
13833 		 *
13834 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13835 		 */
13836 		if (cmd == F_SETLKW) {
13837 			rnode4_t *rp = VTOR4(vp);
13838 			nfs_argop4 *argop = (*argspp)->array;
13839 
13840 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13841 
13842 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13843 			    recov_statep, needrecov);
13844 			*did_start_fop = FALSE;
13845 			ASSERT((*argspp)->array_len == 2);
13846 			if (argop[1].argop == OP_LOCK)
13847 				nfs4args_lock_free(&argop[1]);
13848 			else if (argop[1].argop == OP_LOCKT)
13849 				nfs4args_lockt_free(&argop[1]);
13850 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13851 			if (*respp)
13852 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13853 				    (caddr_t)*respp);
13854 			*argspp = NULL;
13855 			*respp = NULL;
13856 			nfs4_end_lock_seqid_sync(lop);
13857 			lock_owner_rele(lop);
13858 			*lopp = NULL;
13859 			if (osp != NULL) {
13860 				open_stream_rele(osp, rp);
13861 				*ospp = NULL;
13862 			}
13863 			if (oop != NULL) {
13864 				nfs4_end_open_seqid_sync(oop);
13865 				open_owner_rele(oop);
13866 				*oopp = NULL;
13867 			}
13868 
13869 			nfs_rw_exit(&rp->r_lkserlock);
13870 
13871 			intr = nfs4_block_and_wait(tick_delayp, rp);
13872 
13873 			if (intr) {
13874 				(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13875 				    RW_WRITER, FALSE);
13876 				*errorp = EINTR;
13877 				return (FALSE);
13878 			}
13879 
13880 			(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13881 			    RW_WRITER, FALSE);
13882 
13883 			/*
13884 			 * Make sure we are still safe to lock with
13885 			 * regards to mmapping.
13886 			 */
13887 			if (!nfs4_safelock(vp, flk, cr)) {
13888 				*errorp = EAGAIN;
13889 				return (FALSE);
13890 			}
13891 
13892 			return (TRUE);
13893 		}
13894 		if (ctype == NFS4_LCK_CTYPE_NORM)
13895 			*errorp = EAGAIN;
13896 		*skip_get_err = TRUE;
13897 		flk->l_whence = 0;
13898 		*whencep = 0;
13899 		return (FALSE);
13900 	} else if (lockt_args) {
13901 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13902 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
13903 
13904 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
13905 		    flk, lockt_args);
13906 
13907 		/* according to NLM code */
13908 		*errorp = 0;
13909 		*whencep = 0;
13910 		*skip_get_err = TRUE;
13911 		return (FALSE);
13912 	}
13913 	return (FALSE);
13914 }
13915 
13916 /*
13917  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
13918  */
13919 static void
13920 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
13921 {
13922 	switch (resp->status) {
13923 	case NFS4ERR_ACCESS:
13924 	case NFS4ERR_ADMIN_REVOKED:
13925 	case NFS4ERR_BADHANDLE:
13926 	case NFS4ERR_BAD_RANGE:
13927 	case NFS4ERR_BAD_SEQID:
13928 	case NFS4ERR_BAD_STATEID:
13929 	case NFS4ERR_BADXDR:
13930 	case NFS4ERR_DEADLOCK:
13931 	case NFS4ERR_DELAY:
13932 	case NFS4ERR_EXPIRED:
13933 	case NFS4ERR_FHEXPIRED:
13934 	case NFS4ERR_GRACE:
13935 	case NFS4ERR_INVAL:
13936 	case NFS4ERR_ISDIR:
13937 	case NFS4ERR_LEASE_MOVED:
13938 	case NFS4ERR_LOCK_NOTSUPP:
13939 	case NFS4ERR_LOCK_RANGE:
13940 	case NFS4ERR_MOVED:
13941 	case NFS4ERR_NOFILEHANDLE:
13942 	case NFS4ERR_NO_GRACE:
13943 	case NFS4ERR_OLD_STATEID:
13944 	case NFS4ERR_OPENMODE:
13945 	case NFS4ERR_RECLAIM_BAD:
13946 	case NFS4ERR_RECLAIM_CONFLICT:
13947 	case NFS4ERR_RESOURCE:
13948 	case NFS4ERR_SERVERFAULT:
13949 	case NFS4ERR_STALE:
13950 	case NFS4ERR_STALE_CLIENTID:
13951 	case NFS4ERR_STALE_STATEID:
13952 		return;
13953 	default:
13954 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13955 		    "nfs4frlock_results_default: got unrecognizable "
13956 		    "res.status %d", resp->status));
13957 		*errorp = NFS4ERR_INVAL;
13958 	}
13959 }
13960 
13961 /*
13962  * The lock request was successful, so update the client's state.
13963  */
13964 static void
13965 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
13966     LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
13967     vnode_t *vp, flock64_t *flk, cred_t *cr,
13968     nfs4_lost_rqst_t *resend_rqstp)
13969 {
13970 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13971 
13972 	if (lock_args) {
13973 		LOCK4res *lock_res;
13974 
13975 		lock_res = &resop->nfs_resop4_u.oplock;
13976 		/* update the stateid with server's response */
13977 
13978 		if (lock_args->locker.new_lock_owner == TRUE) {
13979 			mutex_enter(&lop->lo_lock);
13980 			lop->lo_just_created = NFS4_PERM_CREATED;
13981 			mutex_exit(&lop->lo_lock);
13982 		}
13983 
13984 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
13985 
13986 		/*
13987 		 * If the lock was the result of a resending a lost
13988 		 * request, we've synched up the stateid and seqid
13989 		 * with the server, but now the server might be out of sync
13990 		 * with what the application thinks it has for locks.
13991 		 * Clean that up here.  It's unclear whether we should do
13992 		 * this even if the filesystem has been forcibly unmounted.
13993 		 * For most servers, it's probably wasted effort, but
13994 		 * RFC 7530 lets servers require that unlocks exactly match
13995 		 * the locks that are held.
13996 		 */
13997 		if (resend_rqstp != NULL &&
13998 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
13999 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
14000 		} else {
14001 			flk->l_whence = 0;
14002 		}
14003 	} else if (locku_args) {
14004 		LOCKU4res *locku_res;
14005 
14006 		locku_res = &resop->nfs_resop4_u.oplocku;
14007 
14008 		/* Update the stateid with the server's response */
14009 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
14010 	} else if (lockt_args) {
14011 		/* Switch the lock type to express success, see fcntl */
14012 		flk->l_type = F_UNLCK;
14013 		flk->l_whence = 0;
14014 	}
14015 }
14016 
14017 /*
14018  * Do final cleanup before exiting nfs4frlock.
14019  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
14020  * COMPOUND4 args/res for calls that haven't already.
14021  */
14022 static void
14023 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
14024     COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
14025     nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
14026     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
14027     short whence, u_offset_t offset, struct lm_sysid *ls,
14028     int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
14029     bool_t did_start_fop, bool_t skip_get_err,
14030     cred_t *cred_otw, cred_t *cred)
14031 {
14032 	mntinfo4_t	*mi = VTOMI4(vp);
14033 	rnode4_t	*rp = VTOR4(vp);
14034 	int		error = *errorp;
14035 	nfs_argop4	*argop;
14036 	int	do_flush_pages = 0;
14037 
14038 	ASSERT(nfs_zone() == mi->mi_zone);
14039 	/*
14040 	 * The client recovery code wants the raw status information,
14041 	 * so don't map the NFS status code to an errno value for
14042 	 * non-normal call types.
14043 	 */
14044 	if (ctype == NFS4_LCK_CTYPE_NORM) {
14045 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
14046 			*errorp = geterrno4(resp->status);
14047 		if (did_start_fop == TRUE)
14048 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
14049 			    needrecov);
14050 
14051 		/*
14052 		 * We've established a new lock on the server, so invalidate
14053 		 * the pages associated with the vnode to get the most up to
14054 		 * date pages from the server after acquiring the lock. We
14055 		 * want to be sure that the read operation gets the newest data.
14056 		 * N.B.
14057 		 * We used to do this in nfs4frlock_results_ok but that doesn't
14058 		 * work since VOP_PUTPAGE can call nfs4_commit which calls
14059 		 * nfs4_start_fop. We flush the pages below after calling
14060 		 * nfs4_end_fop above
14061 		 * The flush of the page cache must be done after
14062 		 * nfs4_end_open_seqid_sync() to avoid a 4-way hang.
14063 		 */
14064 		if (!error && resp && resp->status == NFS4_OK)
14065 			do_flush_pages = 1;
14066 	}
14067 	if (argsp) {
14068 		ASSERT(argsp->array_len == 2);
14069 		argop = argsp->array;
14070 		if (argop[1].argop == OP_LOCK)
14071 			nfs4args_lock_free(&argop[1]);
14072 		else if (argop[1].argop == OP_LOCKT)
14073 			nfs4args_lockt_free(&argop[1]);
14074 		kmem_free(argop, 2 * sizeof (nfs_argop4));
14075 		if (resp)
14076 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
14077 	}
14078 
14079 	/* free the reference on the lock owner */
14080 	if (lop != NULL) {
14081 		nfs4_end_lock_seqid_sync(lop);
14082 		lock_owner_rele(lop);
14083 	}
14084 
14085 	/* need to free up the reference on osp for lock args */
14086 	if (osp != NULL)
14087 		open_stream_rele(osp, rp);
14088 
14089 	/* need to free up the reference on oop for lock args */
14090 	if (oop != NULL) {
14091 		nfs4_end_open_seqid_sync(oop);
14092 		open_owner_rele(oop);
14093 	}
14094 
14095 	if (do_flush_pages)
14096 		nfs4_flush_pages(vp, cred);
14097 
14098 	(void) convoff(vp, flk, whence, offset);
14099 
14100 	lm_rel_sysid(ls);
14101 
14102 	/*
14103 	 * Record debug information in the event we get EINVAL.
14104 	 */
14105 	mutex_enter(&mi->mi_lock);
14106 	if (*errorp == EINVAL && (lock_args || locku_args) &&
14107 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
14108 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
14109 			zcmn_err(getzoneid(), CE_NOTE,
14110 			    "%s operation failed with "
14111 			    "EINVAL probably since the server, %s,"
14112 			    " doesn't support POSIX style locking",
14113 			    lock_args ? "LOCK" : "LOCKU",
14114 			    mi->mi_curr_serv->sv_hostname);
14115 			mi->mi_flags |= MI4_LOCK_DEBUG;
14116 		}
14117 	}
14118 	mutex_exit(&mi->mi_lock);
14119 
14120 	if (cred_otw)
14121 		crfree(cred_otw);
14122 }
14123 
14124 /*
14125  * This calls the server and the local locking code.
14126  *
14127  * Client locks are registerred locally by oring the sysid with
14128  * LM_SYSID_CLIENT. The server registers locks locally using just the sysid.
14129  * We need to distinguish between the two to avoid collision in case one
14130  * machine is used as both client and server.
14131  *
14132  * Blocking lock requests will continually retry to acquire the lock
14133  * forever.
14134  *
14135  * The ctype is defined as follows:
14136  * NFS4_LCK_CTYPE_NORM: normal lock request.
14137  *
14138  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
14139  * recovery, get the pid from flk instead of curproc, and don't reregister
14140  * the lock locally.
14141  *
14142  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
14143  * that we will use the information passed in via resend_rqstp to setup the
14144  * lock/locku request.  This resend is the exact same request as the 'lost
14145  * lock', and is initiated by the recovery framework. A successful resend
14146  * request can initiate one or more reinstate requests.
14147  *
14148  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14149  * does not trigger additional reinstate requests.  This lock call type is
14150  * set for setting the v4 server's locking state back to match what the
14151  * client's local locking state is in the event of a received 'lost lock'.
14152  *
14153  * Errors are returned via the nfs4_error_t parameter.
14154  */
14155 void
14156 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14157     int flag, u_offset_t offset, cred_t *cr, nfs4_error_t *ep,
14158     nfs4_lost_rqst_t *resend_rqstp, int *did_reclaimp)
14159 {
14160 	COMPOUND4args_clnt	args, *argsp = NULL;
14161 	COMPOUND4res_clnt	res, *resp = NULL;
14162 	nfs_argop4	*argop;
14163 	nfs_resop4	*resop;
14164 	rnode4_t	*rp;
14165 	int		doqueue = 1;
14166 	clock_t		tick_delay;  /* delay in clock ticks */
14167 	struct lm_sysid	*ls;
14168 	LOCK4args	*lock_args = NULL;
14169 	LOCKU4args	*locku_args = NULL;
14170 	LOCKT4args	*lockt_args = NULL;
14171 	nfs4_open_owner_t *oop = NULL;
14172 	nfs4_open_stream_t *osp = NULL;
14173 	nfs4_lock_owner_t *lop = NULL;
14174 	bool_t		needrecov = FALSE;
14175 	nfs4_recov_state_t recov_state;
14176 	short		whence;
14177 	nfs4_op_hint_t	op_hint;
14178 	nfs4_lost_rqst_t lost_rqst;
14179 	bool_t		retry = FALSE;
14180 	bool_t		did_start_fop = FALSE;
14181 	bool_t		skip_get_err = FALSE;
14182 	cred_t		*cred_otw = NULL;
14183 	bool_t		recovonly;	/* just queue request */
14184 	int		frc_no_reclaim = 0;
14185 #ifdef DEBUG
14186 	char *name;
14187 #endif
14188 
14189 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14190 
14191 #ifdef DEBUG
14192 	name = fn_name(VTOSV(vp)->sv_name);
14193 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14194 	    "%s: cmd %d, type %d, offset %llu, start %"PRIx64", "
14195 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14196 	    "resend request %s", name, cmd, flk->l_type, offset, flk->l_start,
14197 	    flk->l_len, ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid :
14198 	    flk->l_pid, flk->l_sysid, nfs4frlock_get_call_type(ctype),
14199 	    resend_rqstp ? "TRUE" : "FALSE"));
14200 	kmem_free(name, MAXNAMELEN);
14201 #endif
14202 
14203 	nfs4_error_zinit(ep);
14204 	ep->error = nfs4frlock_validate_args(cmd, flk, flag, vp, offset);
14205 	if (ep->error)
14206 		return;
14207 	ep->error = nfs4frlock_get_sysid(&ls, vp, flk);
14208 	if (ep->error)
14209 		return;
14210 	nfs4frlock_pre_setup(&tick_delay, &recov_state, flk, &whence,
14211 	    vp, cr, &cred_otw);
14212 
14213 recov_retry:
14214 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14215 	    &retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14216 	rp = VTOR4(vp);
14217 
14218 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14219 	    &did_start_fop, &recovonly);
14220 
14221 	if (ep->error)
14222 		goto out;
14223 
14224 	if (recovonly) {
14225 		/*
14226 		 * Leave the request for the recovery system to deal with.
14227 		 */
14228 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14229 		ASSERT(cmd != F_GETLK);
14230 		ASSERT(flk->l_type == F_UNLCK);
14231 
14232 		nfs4_error_init(ep, EINTR);
14233 		needrecov = TRUE;
14234 		lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14235 		if (lop != NULL) {
14236 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14237 			    NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14238 			(void) nfs4_start_recovery(ep,
14239 			    VTOMI4(vp), vp, NULL, NULL,
14240 			    (lost_rqst.lr_op == OP_LOCK ||
14241 			    lost_rqst.lr_op == OP_LOCKU) ?
14242 			    &lost_rqst : NULL, OP_LOCKU, NULL, NULL, NULL);
14243 			lock_owner_rele(lop);
14244 			lop = NULL;
14245 		}
14246 		flk->l_pid = curproc->p_pid;
14247 		nfs4_register_lock_locally(vp, flk, flag, offset);
14248 		goto out;
14249 	}
14250 
14251 	/* putfh directory fh */
14252 	argop[0].argop = OP_CPUTFH;
14253 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14254 
14255 	/*
14256 	 * Set up the over-the-wire arguments and get references to the
14257 	 * open owner, etc.
14258 	 */
14259 
14260 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14261 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14262 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14263 		    &argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14264 	} else {
14265 		bool_t go_otw = TRUE;
14266 
14267 		ASSERT(resend_rqstp == NULL);
14268 
14269 		switch (cmd) {
14270 		case F_GETLK:
14271 			nfs4frlock_setup_lockt_args(ctype, &argop[1],
14272 			    &lockt_args, argsp, flk, rp);
14273 			break;
14274 		case F_SETLKW:
14275 		case F_SETLK:
14276 			if (flk->l_type == F_UNLCK)
14277 				nfs4frlock_setup_locku_args(ctype,
14278 				    &argop[1], &locku_args, flk,
14279 				    &lop, ep, argsp,
14280 				    vp, flag, offset, cr,
14281 				    &skip_get_err, &go_otw);
14282 			else
14283 				nfs4frlock_setup_lock_args(ctype,
14284 				    &lock_args, &oop, &osp, &lop, &argop[1],
14285 				    argsp, flk, cmd, vp, cr, ep);
14286 
14287 			if (ep->error)
14288 				goto out;
14289 
14290 			switch (ep->stat) {
14291 			case NFS4_OK:
14292 				break;
14293 			case NFS4ERR_DELAY:
14294 				/* recov thread never gets this error */
14295 				ASSERT(resend_rqstp == NULL);
14296 				ASSERT(did_start_fop);
14297 
14298 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14299 				    &recov_state, TRUE);
14300 				did_start_fop = FALSE;
14301 				if (argop[1].argop == OP_LOCK)
14302 					nfs4args_lock_free(&argop[1]);
14303 				else if (argop[1].argop == OP_LOCKT)
14304 					nfs4args_lockt_free(&argop[1]);
14305 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14306 				argsp = NULL;
14307 				goto recov_retry;
14308 			default:
14309 				ep->error = EIO;
14310 				goto out;
14311 			}
14312 			break;
14313 		default:
14314 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14315 			    "nfs4_frlock: invalid cmd %d", cmd));
14316 			ep->error = EINVAL;
14317 			goto out;
14318 		}
14319 
14320 		if (!go_otw)
14321 			goto out;
14322 	}
14323 
14324 	/* XXX should we use the local reclock as a cache ? */
14325 	/*
14326 	 * Unregister the lock with the local locking code before
14327 	 * contacting the server.  This avoids a potential race where
14328 	 * another process gets notified that it has been granted a lock
14329 	 * before we can unregister ourselves locally.
14330 	 */
14331 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK) {
14332 		if (ctype == NFS4_LCK_CTYPE_NORM)
14333 			flk->l_pid = ttoproc(curthread)->p_pid;
14334 		nfs4_register_lock_locally(vp, flk, flag, offset);
14335 	}
14336 
14337 	/*
14338 	 * Send the server the lock request.  Continually loop with a delay
14339 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14340 	 */
14341 	resp = &res;
14342 
14343 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14344 	    (CE_NOTE,
14345 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14346 	    rnode4info(rp)));
14347 
14348 	if (lock_args && frc_no_reclaim) {
14349 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14350 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14351 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14352 		lock_args->reclaim = FALSE;
14353 		if (did_reclaimp)
14354 			*did_reclaimp = 0;
14355 	}
14356 
14357 	/*
14358 	 * Do the OTW call.
14359 	 */
14360 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14361 
14362 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14363 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14364 
14365 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14366 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14367 	    "nfs4frlock: needrecov %d", needrecov));
14368 
14369 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14370 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14371 		    args.ctag);
14372 
14373 	/*
14374 	 * Check if one of these mutually exclusive error cases has
14375 	 * happened:
14376 	 *   need to swap credentials due to access error
14377 	 *   recovery is needed
14378 	 *   different error (only known case is missing Kerberos ticket)
14379 	 */
14380 
14381 	if ((ep->error == EACCES ||
14382 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14383 	    cred_otw != cr) {
14384 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14385 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14386 		    cr, &cred_otw);
14387 		goto recov_retry;
14388 	}
14389 
14390 	if (needrecov) {
14391 		/*
14392 		 * LOCKT requests don't need to recover from lost
14393 		 * requests since they don't create/modify state.
14394 		 */
14395 		if ((ep->error == EINTR ||
14396 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14397 		    lockt_args)
14398 			goto out;
14399 		/*
14400 		 * Do not attempt recovery for requests initiated by
14401 		 * the recovery framework.  Let the framework redrive them.
14402 		 */
14403 		if (ctype != NFS4_LCK_CTYPE_NORM)
14404 			goto out;
14405 		else {
14406 			ASSERT(resend_rqstp == NULL);
14407 		}
14408 
14409 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14410 		    flk_to_locktype(cmd, flk->l_type),
14411 		    oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14412 
14413 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14414 		    &resp, lock_args, locku_args, &oop, &osp, &lop,
14415 		    rp, vp, &recov_state, op_hint, &did_start_fop,
14416 		    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14417 
14418 		if (retry) {
14419 			ASSERT(oop == NULL);
14420 			ASSERT(osp == NULL);
14421 			ASSERT(lop == NULL);
14422 			goto recov_retry;
14423 		}
14424 		goto out;
14425 	}
14426 
14427 	/*
14428 	 * Bail out if have reached this point with ep->error set. Can
14429 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14430 	 * This happens if Kerberos ticket has expired or has been
14431 	 * destroyed.
14432 	 */
14433 	if (ep->error != 0)
14434 		goto out;
14435 
14436 	/*
14437 	 * Process the reply.
14438 	 */
14439 	switch (resp->status) {
14440 	case NFS4_OK:
14441 		resop = &resp->array[1];
14442 		nfs4frlock_results_ok(ctype, cmd, flk, vp, flag, offset,
14443 		    resend_rqstp);
14444 		/*
14445 		 * Have a successful lock operation, now update state.
14446 		 */
14447 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14448 		    resop, lop, vp, flk, cr, resend_rqstp);
14449 		break;
14450 
14451 	case NFS4ERR_DENIED:
14452 		resop = &resp->array[1];
14453 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14454 		    &oop, &osp, &lop, cmd, vp, flk, op_hint,
14455 		    &recov_state, needrecov, &argsp, &resp,
14456 		    &tick_delay, &whence, &ep->error, resop, cr,
14457 		    &did_start_fop, &skip_get_err);
14458 
14459 		if (retry) {
14460 			ASSERT(oop == NULL);
14461 			ASSERT(osp == NULL);
14462 			ASSERT(lop == NULL);
14463 			goto recov_retry;
14464 		}
14465 		break;
14466 	/*
14467 	 * If the server won't let us reclaim, fall-back to trying to lock
14468 	 * the file from scratch. Code elsewhere will check the changeinfo
14469 	 * to ensure the file hasn't been changed.
14470 	 */
14471 	case NFS4ERR_NO_GRACE:
14472 		if (lock_args && lock_args->reclaim == TRUE) {
14473 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14474 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14475 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14476 			frc_no_reclaim = 1;
14477 			/* clean up before retrying */
14478 			needrecov = 0;
14479 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14480 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14481 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14482 			goto recov_retry;
14483 		}
14484 		/* FALLTHROUGH */
14485 
14486 	default:
14487 		nfs4frlock_results_default(resp, &ep->error);
14488 		break;
14489 	}
14490 out:
14491 	/*
14492 	 * Process and cleanup from error.  Make interrupted unlock
14493 	 * requests look successful, since they will be handled by the
14494 	 * client recovery code.
14495 	 */
14496 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14497 	    needrecov, oop, osp, lop, flk, whence, offset, ls, &ep->error,
14498 	    lock_args, locku_args, did_start_fop,
14499 	    skip_get_err, cred_otw, cr);
14500 
14501 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14502 	    (cmd == F_SETLK || cmd == F_SETLKW))
14503 		ep->error = 0;
14504 }
14505 
14506 /*
14507  * nfs4_safelock:
14508  *
14509  * Return non-zero if the given lock request can be handled without
14510  * violating the constraints on concurrent mapping and locking.
14511  */
14512 
14513 static int
14514 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14515 {
14516 	rnode4_t *rp = VTOR4(vp);
14517 	struct vattr va;
14518 	int error;
14519 
14520 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14521 	ASSERT(rp->r_mapcnt >= 0);
14522 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14523 	    "(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14524 	    "write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14525 	    bfp->l_start, bfp->l_len, rp->r_mapcnt));
14526 
14527 	if (rp->r_mapcnt == 0)
14528 		return (1);		/* always safe if not mapped */
14529 
14530 	/*
14531 	 * If the file is already mapped and there are locks, then they
14532 	 * should be all safe locks.  So adding or removing a lock is safe
14533 	 * as long as the new request is safe (i.e., whole-file, meaning
14534 	 * length and starting offset are both zero).
14535 	 */
14536 
14537 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14538 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14539 		    "cannot lock a memory mapped file unless locking the "
14540 		    "entire file: start %"PRIx64", len %"PRIx64,
14541 		    bfp->l_start, bfp->l_len));
14542 		return (0);
14543 	}
14544 
14545 	/* mandatory locking and mapping don't mix */
14546 	va.va_mask = AT_MODE;
14547 	error = VOP_GETATTR(vp, &va, 0, cr, NULL);
14548 	if (error != 0) {
14549 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14550 		    "getattr error %d", error));
14551 		return (0);		/* treat errors conservatively */
14552 	}
14553 	if (MANDLOCK(vp, va.va_mode)) {
14554 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14555 		    "cannot mandatory lock and mmap a file"));
14556 		return (0);
14557 	}
14558 
14559 	return (1);
14560 }
14561 
14562 
14563 /*
14564  * Register the lock locally within Solaris.
14565  * As the client, we "or" the sysid with LM_SYSID_CLIENT when
14566  * recording locks locally.
14567  *
14568  * This should handle conflicts/cooperation with NFS v2/v3 since all locks
14569  * are registered locally.
14570  */
14571 void
14572 nfs4_register_lock_locally(vnode_t *vp, struct flock64 *flk, int flag,
14573     u_offset_t offset)
14574 {
14575 	int oldsysid;
14576 	int error;
14577 #ifdef DEBUG
14578 	char *name;
14579 #endif
14580 
14581 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14582 
14583 #ifdef DEBUG
14584 	name = fn_name(VTOSV(vp)->sv_name);
14585 	NFS4_DEBUG(nfs4_client_lock_debug,
14586 	    (CE_NOTE, "nfs4_register_lock_locally: %s: type %d, "
14587 	    "start %"PRIx64", length %"PRIx64", pid %ld, sysid %d",
14588 	    name, flk->l_type, flk->l_start, flk->l_len, (long)flk->l_pid,
14589 	    flk->l_sysid));
14590 	kmem_free(name, MAXNAMELEN);
14591 #endif
14592 
14593 	/* register the lock with local locking */
14594 	oldsysid = flk->l_sysid;
14595 	flk->l_sysid |= LM_SYSID_CLIENT;
14596 	error = reclock(vp, flk, SETFLCK, flag, offset, NULL);
14597 #ifdef DEBUG
14598 	if (error != 0) {
14599 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14600 		    "nfs4_register_lock_locally: could not register with"
14601 		    " local locking"));
14602 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14603 		    "error %d, vp 0x%p, pid %d, sysid 0x%x",
14604 		    error, (void *)vp, flk->l_pid, flk->l_sysid));
14605 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14606 		    "type %d off 0x%" PRIx64 " len 0x%" PRIx64,
14607 		    flk->l_type, flk->l_start, flk->l_len));
14608 		(void) reclock(vp, flk, 0, flag, offset, NULL);
14609 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14610 		    "blocked by pid %d sysid 0x%x type %d "
14611 		    "off 0x%" PRIx64 " len 0x%" PRIx64,
14612 		    flk->l_pid, flk->l_sysid, flk->l_type, flk->l_start,
14613 		    flk->l_len));
14614 	}
14615 #endif
14616 	flk->l_sysid = oldsysid;
14617 }
14618 
14619 /*
14620  * nfs4_lockrelease:
14621  *
14622  * Release any locks on the given vnode that are held by the current
14623  * process.  Also removes the lock owner (if one exists) from the rnode's
14624  * list.
14625  */
14626 static int
14627 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14628 {
14629 	flock64_t ld;
14630 	int ret, error;
14631 	rnode4_t *rp;
14632 	nfs4_lock_owner_t *lop;
14633 	nfs4_recov_state_t recov_state;
14634 	mntinfo4_t *mi;
14635 	bool_t possible_orphan = FALSE;
14636 	bool_t recovonly;
14637 
14638 	ASSERT((uintptr_t)vp > KERNELBASE);
14639 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14640 
14641 	rp = VTOR4(vp);
14642 	mi = VTOMI4(vp);
14643 
14644 	/*
14645 	 * If we have not locked anything then we can
14646 	 * just return since we have no work to do.
14647 	 */
14648 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14649 		return (0);
14650 	}
14651 
14652 	/*
14653 	 * We need to comprehend that another thread may
14654 	 * kick off recovery and the lock_owner we have stashed
14655 	 * in lop might be invalid so we should NOT cache it
14656 	 * locally!
14657 	 */
14658 	recov_state.rs_flags = 0;
14659 	recov_state.rs_num_retry_despite_err = 0;
14660 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14661 	    &recovonly);
14662 	if (error) {
14663 		mutex_enter(&rp->r_statelock);
14664 		rp->r_flags |= R4LODANGLERS;
14665 		mutex_exit(&rp->r_statelock);
14666 		return (error);
14667 	}
14668 
14669 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14670 
14671 	/*
14672 	 * Check if the lock owner might have a lock (request was sent but
14673 	 * no response was received).  Also check if there are any remote
14674 	 * locks on the file.  (In theory we shouldn't have to make this
14675 	 * second check if there's no lock owner, but for now we'll be
14676 	 * conservative and do it anyway.)  If either condition is true,
14677 	 * send an unlock for the entire file to the server.
14678 	 *
14679 	 * Note that no explicit synchronization is needed here.  At worst,
14680 	 * flk_has_remote_locks() will return a false positive, in which case
14681 	 * the unlock call wastes time but doesn't harm correctness.
14682 	 */
14683 
14684 	if (lop) {
14685 		mutex_enter(&lop->lo_lock);
14686 		possible_orphan = lop->lo_pending_rqsts;
14687 		mutex_exit(&lop->lo_lock);
14688 		lock_owner_rele(lop);
14689 	}
14690 
14691 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14692 
14693 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14694 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14695 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14696 	    (void *)lop));
14697 
14698 	if (possible_orphan || flk_has_remote_locks(vp)) {
14699 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14700 		ld.l_whence = 0;	/* unlock from start of file */
14701 		ld.l_start = 0;
14702 		ld.l_len = 0;		/* do entire file */
14703 
14704 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL,
14705 		    cr, NULL);
14706 
14707 		if (ret != 0) {
14708 			/*
14709 			 * If VOP_FRLOCK fails, make sure we unregister
14710 			 * local locks before we continue.
14711 			 */
14712 			ld.l_pid = ttoproc(curthread)->p_pid;
14713 			nfs4_register_lock_locally(vp, &ld, flag, offset);
14714 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14715 			    "nfs4_lockrelease: lock release error on vp"
14716 			    " %p: error %d.\n", (void *)vp, ret));
14717 		}
14718 	}
14719 
14720 	recov_state.rs_flags = 0;
14721 	recov_state.rs_num_retry_despite_err = 0;
14722 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14723 	    &recovonly);
14724 	if (error) {
14725 		mutex_enter(&rp->r_statelock);
14726 		rp->r_flags |= R4LODANGLERS;
14727 		mutex_exit(&rp->r_statelock);
14728 		return (error);
14729 	}
14730 
14731 	/*
14732 	 * So, here we're going to need to retrieve the lock-owner
14733 	 * again (in case recovery has done a switch-a-roo) and
14734 	 * remove it because we can.
14735 	 */
14736 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14737 
14738 	if (lop) {
14739 		nfs4_rnode_remove_lock_owner(rp, lop);
14740 		lock_owner_rele(lop);
14741 	}
14742 
14743 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14744 	return (0);
14745 }
14746 
14747 /*
14748  * Wait for 'tick_delay' clock ticks.
14749  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14750  * NOTE: lock_lease_time is in seconds.
14751  *
14752  * XXX For future improvements, should implement a waiting queue scheme.
14753  */
14754 static int
14755 nfs4_block_and_wait(clock_t *tick_delay, rnode4_t *rp)
14756 {
14757 	long milliseconds_delay;
14758 	time_t lock_lease_time;
14759 
14760 	/* wait tick_delay clock ticks or siginteruptus */
14761 	if (delay_sig(*tick_delay)) {
14762 		return (EINTR);
14763 	}
14764 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14765 	    "reissue the lock request: blocked for %ld clock ticks: %ld "
14766 	    "milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14767 
14768 	/* get the lease time */
14769 	lock_lease_time = r2lease_time(rp);
14770 
14771 	/* drv_hztousec converts ticks to microseconds */
14772 	milliseconds_delay = drv_hztousec(*tick_delay) / 1000;
14773 	if (milliseconds_delay < lock_lease_time * 1000) {
14774 		*tick_delay = 2 * *tick_delay;
14775 		if (drv_hztousec(*tick_delay) > lock_lease_time * 1000 * 1000)
14776 			*tick_delay = drv_usectohz(lock_lease_time*1000*1000);
14777 	}
14778 	return (0);
14779 }
14780 
14781 
14782 void
14783 nfs4_vnops_init(void)
14784 {
14785 }
14786 
14787 void
14788 nfs4_vnops_fini(void)
14789 {
14790 }
14791 
14792 /*
14793  * Return a reference to the directory (parent) vnode for a given vnode,
14794  * using the saved pathname information and the directory file handle.  The
14795  * caller is responsible for disposing of the reference.
14796  * Returns zero or an errno value.
14797  *
14798  * Caller should set need_start_op to FALSE if it is the recovery
14799  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14800  */
14801 int
14802 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14803 {
14804 	svnode_t *svnp;
14805 	vnode_t *dvp = NULL;
14806 	servinfo4_t *svp;
14807 	nfs4_fname_t *mfname;
14808 	int error;
14809 
14810 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14811 
14812 	if (vp->v_flag & VROOT) {
14813 		nfs4_sharedfh_t *sfh;
14814 		nfs_fh4 fh;
14815 		mntinfo4_t *mi;
14816 
14817 		ASSERT(vp->v_type == VREG);
14818 
14819 		mi = VTOMI4(vp);
14820 		svp = mi->mi_curr_serv;
14821 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14822 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14823 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14824 		sfh = sfh4_get(&fh, VTOMI4(vp));
14825 		nfs_rw_exit(&svp->sv_lock);
14826 		mfname = mi->mi_fname;
14827 		fn_hold(mfname);
14828 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14829 		sfh4_rele(&sfh);
14830 
14831 		if (dvp->v_type == VNON)
14832 			dvp->v_type = VDIR;
14833 		*dvpp = dvp;
14834 		return (0);
14835 	}
14836 
14837 	svnp = VTOSV(vp);
14838 
14839 	if (svnp == NULL) {
14840 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14841 		    "shadow node is NULL"));
14842 		return (EINVAL);
14843 	}
14844 
14845 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14846 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14847 		    "shadow node name or dfh val == NULL"));
14848 		return (EINVAL);
14849 	}
14850 
14851 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14852 	    (int)need_start_op);
14853 	if (error != 0) {
14854 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14855 		    "nfs4_make_dotdot returned %d", error));
14856 		return (error);
14857 	}
14858 	if (!dvp) {
14859 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14860 		    "nfs4_make_dotdot returned a NULL dvp"));
14861 		return (EIO);
14862 	}
14863 	if (dvp->v_type == VNON)
14864 		dvp->v_type = VDIR;
14865 	ASSERT(dvp->v_type == VDIR);
14866 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14867 		mutex_enter(&dvp->v_lock);
14868 		dvp->v_flag |= V_XATTRDIR;
14869 		mutex_exit(&dvp->v_lock);
14870 	}
14871 	*dvpp = dvp;
14872 	return (0);
14873 }
14874 
14875 /*
14876  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14877  * length that fnamep can accept, including the trailing null.
14878  * Returns 0 if okay, returns an errno value if there was a problem.
14879  */
14880 
14881 int
14882 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14883 {
14884 	char *fn;
14885 	int err = 0;
14886 	servinfo4_t *svp;
14887 	svnode_t *shvp;
14888 
14889 	/*
14890 	 * If the file being opened has VROOT set, then this is
14891 	 * a "file" mount.  sv_name will not be interesting, so
14892 	 * go back to the servinfo4 to get the original mount
14893 	 * path and strip off all but the final edge.  Otherwise
14894 	 * just return the name from the shadow vnode.
14895 	 */
14896 
14897 	if (vp->v_flag & VROOT) {
14898 
14899 		svp = VTOMI4(vp)->mi_curr_serv;
14900 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14901 
14902 		fn = strrchr(svp->sv_path, '/');
14903 		if (fn == NULL)
14904 			err = EINVAL;
14905 		else
14906 			fn++;
14907 	} else {
14908 		shvp = VTOSV(vp);
14909 		fn = fn_name(shvp->sv_name);
14910 	}
14911 
14912 	if (err == 0)
14913 		if (strlen(fn) < maxlen)
14914 			(void) strcpy(fnamep, fn);
14915 		else
14916 			err = ENAMETOOLONG;
14917 
14918 	if (vp->v_flag & VROOT)
14919 		nfs_rw_exit(&svp->sv_lock);
14920 	else
14921 		kmem_free(fn, MAXNAMELEN);
14922 
14923 	return (err);
14924 }
14925 
14926 /*
14927  * Bookkeeping for a close that doesn't need to go over the wire.
14928  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14929  * it is left at 1.
14930  */
14931 void
14932 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14933 {
14934 	rnode4_t		*rp;
14935 	mntinfo4_t		*mi;
14936 
14937 	mi = VTOMI4(vp);
14938 	rp = VTOR4(vp);
14939 
14940 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14941 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14942 	ASSERT(nfs_zone() == mi->mi_zone);
14943 	ASSERT(mutex_owned(&osp->os_sync_lock));
14944 	ASSERT(*have_lockp);
14945 
14946 	if (!osp->os_valid ||
14947 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14948 		return;
14949 	}
14950 
14951 	/*
14952 	 * This removes the reference obtained at OPEN; ie,
14953 	 * when the open stream structure was created.
14954 	 *
14955 	 * We don't have to worry about calling 'open_stream_rele'
14956 	 * since we our currently holding a reference to this
14957 	 * open stream which means the count can not go to 0 with
14958 	 * this decrement.
14959 	 */
14960 	ASSERT(osp->os_ref_count >= 2);
14961 	osp->os_ref_count--;
14962 	osp->os_valid = 0;
14963 	mutex_exit(&osp->os_sync_lock);
14964 	*have_lockp = 0;
14965 
14966 	nfs4_dec_state_ref_count(mi);
14967 }
14968 
14969 /*
14970  * Close all remaining open streams on the rnode.  These open streams
14971  * could be here because:
14972  * - The close attempted at either close or delmap failed
14973  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
14974  * - Someone did mknod on a regular file but never opened it
14975  */
14976 int
14977 nfs4close_all(vnode_t *vp, cred_t *cr)
14978 {
14979 	nfs4_open_stream_t *osp;
14980 	int error;
14981 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
14982 	rnode4_t *rp;
14983 
14984 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14985 
14986 	error = 0;
14987 	rp = VTOR4(vp);
14988 
14989 	/*
14990 	 * At this point, all we know is that the last time
14991 	 * someone called vn_rele, the count was 1.  Since then,
14992 	 * the vnode could have been re-activated.  We want to
14993 	 * loop through the open streams and close each one, but
14994 	 * we have to be careful since once we release the rnode
14995 	 * hash bucket lock, someone else is free to come in and
14996 	 * re-activate the rnode and add new open streams.  The
14997 	 * strategy is take the rnode hash bucket lock, verify that
14998 	 * the count is still 1, grab the open stream off the
14999 	 * head of the list and mark it invalid, then release the
15000 	 * rnode hash bucket lock and proceed with that open stream.
15001 	 * This is ok because nfs4close_one() will acquire the proper
15002 	 * open/create to close/destroy synchronization for open
15003 	 * streams, and will ensure that if someone has reopened
15004 	 * the open stream after we've dropped the hash bucket lock
15005 	 * then we'll just simply return without destroying the
15006 	 * open stream.
15007 	 * Repeat until the list is empty.
15008 	 */
15009 
15010 	for (;;) {
15011 
15012 		/* make sure vnode hasn't been reactivated */
15013 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
15014 		mutex_enter(&vp->v_lock);
15015 		if (vp->v_count > 1) {
15016 			mutex_exit(&vp->v_lock);
15017 			rw_exit(&rp->r_hashq->r_lock);
15018 			break;
15019 		}
15020 		/*
15021 		 * Grabbing r_os_lock before releasing v_lock prevents
15022 		 * a window where the rnode/open stream could get
15023 		 * reactivated (and os_force_close set to 0) before we
15024 		 * had a chance to set os_force_close to 1.
15025 		 */
15026 		mutex_enter(&rp->r_os_lock);
15027 		mutex_exit(&vp->v_lock);
15028 
15029 		osp = list_head(&rp->r_open_streams);
15030 		if (!osp) {
15031 			/* nothing left to CLOSE OTW, so return */
15032 			mutex_exit(&rp->r_os_lock);
15033 			rw_exit(&rp->r_hashq->r_lock);
15034 			break;
15035 		}
15036 
15037 		mutex_enter(&rp->r_statev4_lock);
15038 		/* the file can't still be mem mapped */
15039 		ASSERT(rp->r_mapcnt == 0);
15040 		if (rp->created_v4)
15041 			rp->created_v4 = 0;
15042 		mutex_exit(&rp->r_statev4_lock);
15043 
15044 		/*
15045 		 * Grab a ref on this open stream; nfs4close_one
15046 		 * will mark it as invalid
15047 		 */
15048 		mutex_enter(&osp->os_sync_lock);
15049 		osp->os_ref_count++;
15050 		osp->os_force_close = 1;
15051 		mutex_exit(&osp->os_sync_lock);
15052 		mutex_exit(&rp->r_os_lock);
15053 		rw_exit(&rp->r_hashq->r_lock);
15054 
15055 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
15056 
15057 		/* Update error if it isn't already non-zero */
15058 		if (error == 0) {
15059 			if (e.error)
15060 				error = e.error;
15061 			else if (e.stat)
15062 				error = geterrno4(e.stat);
15063 		}
15064 
15065 #ifdef	DEBUG
15066 		nfs4close_all_cnt++;
15067 #endif
15068 		/* Release the ref on osp acquired above. */
15069 		open_stream_rele(osp, rp);
15070 
15071 		/* Proceed to the next open stream, if any */
15072 	}
15073 	return (error);
15074 }
15075 
15076 /*
15077  * nfs4close_one - close one open stream for a file if needed.
15078  *
15079  * "close_type" indicates which close path this is:
15080  * CLOSE_NORM: close initiated via VOP_CLOSE.
15081  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
15082  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
15083  *	the close and release of client state for this open stream
15084  *	(unless someone else has the open stream open).
15085  * CLOSE_RESEND: indicates the request is a replay of an earlier request
15086  *	(e.g., due to abort because of a signal).
15087  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
15088  *
15089  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
15090  * recovery.  Instead, the caller is expected to deal with retries.
15091  *
15092  * The caller can either pass in the osp ('provided_osp') or not.
15093  *
15094  * 'access_bits' represents the access we are closing/downgrading.
15095  *
15096  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
15097  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
15098  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
15099  *
15100  * Errors are returned via the nfs4_error_t.
15101  */
15102 void
15103 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
15104     int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
15105     nfs4_close_type_t close_type, size_t len, uint_t maxprot,
15106     uint_t mmap_flags)
15107 {
15108 	nfs4_open_owner_t *oop;
15109 	nfs4_open_stream_t *osp = NULL;
15110 	int retry = 0;
15111 	int num_retries = NFS4_NUM_RECOV_RETRIES;
15112 	rnode4_t *rp;
15113 	mntinfo4_t *mi;
15114 	nfs4_recov_state_t recov_state;
15115 	cred_t *cred_otw = NULL;
15116 	bool_t recovonly = FALSE;
15117 	int isrecov;
15118 	int force_close;
15119 	int close_failed = 0;
15120 	int did_dec_count = 0;
15121 	int did_start_op = 0;
15122 	int did_force_recovlock = 0;
15123 	int did_start_seqid_sync = 0;
15124 	int have_sync_lock = 0;
15125 
15126 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15127 
15128 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
15129 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
15130 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
15131 	    len, maxprot, mmap_flags, access_bits));
15132 
15133 	nfs4_error_zinit(ep);
15134 	rp = VTOR4(vp);
15135 	mi = VTOMI4(vp);
15136 	isrecov = (close_type == CLOSE_RESEND ||
15137 	    close_type == CLOSE_AFTER_RESEND);
15138 
15139 	/*
15140 	 * First get the open owner.
15141 	 */
15142 	if (!provided_osp) {
15143 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
15144 	} else {
15145 		oop = provided_osp->os_open_owner;
15146 		ASSERT(oop != NULL);
15147 		open_owner_hold(oop);
15148 	}
15149 
15150 	if (!oop) {
15151 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15152 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15153 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15154 		    (void *)provided_osp, close_type));
15155 		ep->error = EIO;
15156 		goto out;
15157 	}
15158 
15159 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15160 recov_retry:
15161 	osp = NULL;
15162 	close_failed = 0;
15163 	force_close = (close_type == CLOSE_FORCE);
15164 	retry = 0;
15165 	did_start_op = 0;
15166 	did_force_recovlock = 0;
15167 	did_start_seqid_sync = 0;
15168 	have_sync_lock = 0;
15169 	recovonly = FALSE;
15170 	recov_state.rs_flags = 0;
15171 	recov_state.rs_num_retry_despite_err = 0;
15172 
15173 	/*
15174 	 * Second synchronize with recovery.
15175 	 */
15176 	if (!isrecov) {
15177 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15178 		    &recov_state, &recovonly);
15179 		if (!ep->error) {
15180 			did_start_op = 1;
15181 		} else {
15182 			close_failed = 1;
15183 			/*
15184 			 * If we couldn't get start_fop, but have to
15185 			 * cleanup state, then at least acquire the
15186 			 * mi_recovlock so we can synchronize with
15187 			 * recovery.
15188 			 */
15189 			if (close_type == CLOSE_FORCE) {
15190 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15191 				    RW_READER, FALSE);
15192 				did_force_recovlock = 1;
15193 			} else
15194 				goto out;
15195 		}
15196 	}
15197 
15198 	/*
15199 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15200 	 * set 'recovonly' to TRUE since most likely this is due to
15201 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15202 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15203 	 * to retry, causing us to loop until recovery finishes.  Plus we
15204 	 * don't need protection over the open seqid since we're not going
15205 	 * OTW, hence don't need to use the seqid.
15206 	 */
15207 	if (recovonly == FALSE) {
15208 		/* need to grab the open owner sync before 'os_sync_lock' */
15209 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15210 		if (ep->error == EAGAIN) {
15211 			ASSERT(!isrecov);
15212 			if (did_start_op)
15213 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15214 				    &recov_state, TRUE);
15215 			if (did_force_recovlock)
15216 				nfs_rw_exit(&mi->mi_recovlock);
15217 			goto recov_retry;
15218 		}
15219 		did_start_seqid_sync = 1;
15220 	}
15221 
15222 	/*
15223 	 * Third get an open stream and acquire 'os_sync_lock' to
15224 	 * sychronize the opening/creating of an open stream with the
15225 	 * closing/destroying of an open stream.
15226 	 */
15227 	if (!provided_osp) {
15228 		/* returns with 'os_sync_lock' held */
15229 		osp = find_open_stream(oop, rp);
15230 		if (!osp) {
15231 			ep->error = EIO;
15232 			goto out;
15233 		}
15234 	} else {
15235 		osp = provided_osp;
15236 		open_stream_hold(osp);
15237 		mutex_enter(&osp->os_sync_lock);
15238 	}
15239 	have_sync_lock = 1;
15240 
15241 	ASSERT(oop == osp->os_open_owner);
15242 
15243 	/*
15244 	 * Fourth, do any special pre-OTW CLOSE processing
15245 	 * based on the specific close type.
15246 	 */
15247 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15248 	    !did_dec_count) {
15249 		ASSERT(osp->os_open_ref_count > 0);
15250 		osp->os_open_ref_count--;
15251 		did_dec_count = 1;
15252 		if (osp->os_open_ref_count == 0)
15253 			osp->os_final_close = 1;
15254 	}
15255 
15256 	if (close_type == CLOSE_FORCE) {
15257 		/* see if somebody reopened the open stream. */
15258 		if (!osp->os_force_close) {
15259 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15260 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15261 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15262 			ep->error = 0;
15263 			ep->stat = NFS4_OK;
15264 			goto out;
15265 		}
15266 
15267 		if (!osp->os_final_close && !did_dec_count) {
15268 			osp->os_open_ref_count--;
15269 			did_dec_count = 1;
15270 		}
15271 
15272 		/*
15273 		 * We can't depend on os_open_ref_count being 0 due to the
15274 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15275 		 */
15276 #ifdef	NOTYET
15277 		ASSERT(osp->os_open_ref_count == 0);
15278 #endif
15279 		if (osp->os_open_ref_count != 0) {
15280 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15281 			    "nfs4close_one: should panic here on an "
15282 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15283 			    "since this is probably the exec problem."));
15284 
15285 			osp->os_open_ref_count = 0;
15286 		}
15287 
15288 		/*
15289 		 * There is the possibility that nfs4close_one()
15290 		 * for close_type == CLOSE_DELMAP couldn't find the
15291 		 * open stream, thus couldn't decrement its os_mapcnt;
15292 		 * therefore we can't use this ASSERT yet.
15293 		 */
15294 #ifdef	NOTYET
15295 		ASSERT(osp->os_mapcnt == 0);
15296 #endif
15297 		osp->os_mapcnt = 0;
15298 	}
15299 
15300 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15301 		ASSERT(osp->os_mapcnt >= btopr(len));
15302 
15303 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15304 			osp->os_mmap_write -= btopr(len);
15305 		if (maxprot & PROT_READ)
15306 			osp->os_mmap_read -= btopr(len);
15307 		if (maxprot & PROT_EXEC)
15308 			osp->os_mmap_read -= btopr(len);
15309 		/* mirror the PROT_NONE check in nfs4_addmap() */
15310 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15311 		    !(maxprot & PROT_EXEC))
15312 			osp->os_mmap_read -= btopr(len);
15313 		osp->os_mapcnt -= btopr(len);
15314 		did_dec_count = 1;
15315 	}
15316 
15317 	if (recovonly) {
15318 		nfs4_lost_rqst_t lost_rqst;
15319 
15320 		/* request should not already be in recovery queue */
15321 		ASSERT(lrp == NULL);
15322 		nfs4_error_init(ep, EINTR);
15323 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15324 		    osp, cred_otw, vp);
15325 		mutex_exit(&osp->os_sync_lock);
15326 		have_sync_lock = 0;
15327 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15328 		    lost_rqst.lr_op == OP_CLOSE ?
15329 		    &lost_rqst : NULL, OP_CLOSE, NULL, NULL, NULL);
15330 		close_failed = 1;
15331 		force_close = 0;
15332 		goto close_cleanup;
15333 	}
15334 
15335 	/*
15336 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15337 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15338 	 * space, which means we stopped operating on the open stream
15339 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15340 	 * stateid could be stale, potentially triggering a false
15341 	 * setclientid), and just clean up the client's internal state.
15342 	 */
15343 	if (osp->os_orig_oo_name != oop->oo_name) {
15344 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15345 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15346 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15347 		    "oo_name %" PRIx64")",
15348 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15349 		    oop->oo_name));
15350 		close_failed = 1;
15351 	}
15352 
15353 	/* If the file failed recovery, just quit. */
15354 	mutex_enter(&rp->r_statelock);
15355 	if (rp->r_flags & R4RECOVERR) {
15356 		close_failed = 1;
15357 	}
15358 	mutex_exit(&rp->r_statelock);
15359 
15360 	/*
15361 	 * If the force close path failed to obtain start_fop
15362 	 * then skip the OTW close and just remove the state.
15363 	 */
15364 	if (close_failed)
15365 		goto close_cleanup;
15366 
15367 	/*
15368 	 * Fifth, check to see if there are still mapped pages or other
15369 	 * opens using this open stream.  If there are then we can't
15370 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15371 	 */
15372 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15373 		nfs4_lost_rqst_t	new_lost_rqst;
15374 		bool_t			needrecov = FALSE;
15375 		cred_t			*odg_cred_otw = NULL;
15376 		seqid4			open_dg_seqid = 0;
15377 
15378 		if (osp->os_delegation) {
15379 			/*
15380 			 * If this open stream was never OPENed OTW then we
15381 			 * surely can't DOWNGRADE it (especially since the
15382 			 * osp->open_stateid is really a delegation stateid
15383 			 * when os_delegation is 1).
15384 			 */
15385 			if (access_bits & FREAD)
15386 				osp->os_share_acc_read--;
15387 			if (access_bits & FWRITE)
15388 				osp->os_share_acc_write--;
15389 			osp->os_share_deny_none--;
15390 			nfs4_error_zinit(ep);
15391 			goto out;
15392 		}
15393 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15394 		    lrp, ep, &odg_cred_otw, &open_dg_seqid);
15395 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15396 		if (needrecov && !isrecov) {
15397 			bool_t abort;
15398 			nfs4_bseqid_entry_t *bsep = NULL;
15399 
15400 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15401 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15402 				    vp, 0,
15403 				    lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15404 				    open_dg_seqid);
15405 
15406 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15407 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15408 			mutex_exit(&osp->os_sync_lock);
15409 			have_sync_lock = 0;
15410 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15411 			    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15412 			    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15413 			    bsep, NULL, NULL);
15414 			if (odg_cred_otw)
15415 				crfree(odg_cred_otw);
15416 			if (bsep)
15417 				kmem_free(bsep, sizeof (*bsep));
15418 
15419 			if (abort == TRUE)
15420 				goto out;
15421 
15422 			if (did_start_seqid_sync) {
15423 				nfs4_end_open_seqid_sync(oop);
15424 				did_start_seqid_sync = 0;
15425 			}
15426 			open_stream_rele(osp, rp);
15427 
15428 			if (did_start_op)
15429 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15430 				    &recov_state, FALSE);
15431 			if (did_force_recovlock)
15432 				nfs_rw_exit(&mi->mi_recovlock);
15433 
15434 			goto recov_retry;
15435 		} else {
15436 			if (odg_cred_otw)
15437 				crfree(odg_cred_otw);
15438 		}
15439 		goto out;
15440 	}
15441 
15442 	/*
15443 	 * If this open stream was created as the results of an open
15444 	 * while holding a delegation, then just release it; no need
15445 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15446 	 */
15447 	if (osp->os_delegation) {
15448 		nfs4close_notw(vp, osp, &have_sync_lock);
15449 		nfs4_error_zinit(ep);
15450 		goto out;
15451 	}
15452 
15453 	/*
15454 	 * If this stream is not valid, we're done.
15455 	 */
15456 	if (!osp->os_valid) {
15457 		nfs4_error_zinit(ep);
15458 		goto out;
15459 	}
15460 
15461 	/*
15462 	 * Last open or mmap ref has vanished, need to do an OTW close.
15463 	 * First check to see if a close is still necessary.
15464 	 */
15465 	if (osp->os_failed_reopen) {
15466 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15467 		    "don't close OTW osp %p since reopen failed.",
15468 		    (void *)osp));
15469 		/*
15470 		 * Reopen of the open stream failed, hence the
15471 		 * stateid of the open stream is invalid/stale, and
15472 		 * sending this OTW would incorrectly cause another
15473 		 * round of recovery.  In this case, we need to set
15474 		 * the 'os_valid' bit to 0 so another thread doesn't
15475 		 * come in and re-open this open stream before
15476 		 * this "closing" thread cleans up state (decrementing
15477 		 * the nfs4_server_t's state_ref_count and decrementing
15478 		 * the os_ref_count).
15479 		 */
15480 		osp->os_valid = 0;
15481 		/*
15482 		 * This removes the reference obtained at OPEN; ie,
15483 		 * when the open stream structure was created.
15484 		 *
15485 		 * We don't have to worry about calling 'open_stream_rele'
15486 		 * since we our currently holding a reference to this
15487 		 * open stream which means the count can not go to 0 with
15488 		 * this decrement.
15489 		 */
15490 		ASSERT(osp->os_ref_count >= 2);
15491 		osp->os_ref_count--;
15492 		nfs4_error_zinit(ep);
15493 		close_failed = 0;
15494 		goto close_cleanup;
15495 	}
15496 
15497 	ASSERT(osp->os_ref_count > 1);
15498 
15499 	/*
15500 	 * Sixth, try the CLOSE OTW.
15501 	 */
15502 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15503 	    close_type, ep, &have_sync_lock);
15504 
15505 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15506 		/*
15507 		 * Let the recovery thread be responsible for
15508 		 * removing the state for CLOSE.
15509 		 */
15510 		close_failed = 1;
15511 		force_close = 0;
15512 		retry = 0;
15513 	}
15514 
15515 	/* See if we need to retry with a different cred */
15516 	if ((ep->error == EACCES ||
15517 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15518 	    cred_otw != cr) {
15519 		crfree(cred_otw);
15520 		cred_otw = cr;
15521 		crhold(cred_otw);
15522 		retry = 1;
15523 	}
15524 
15525 	if (ep->error || ep->stat)
15526 		close_failed = 1;
15527 
15528 	if (retry && !isrecov && num_retries-- > 0) {
15529 		if (have_sync_lock) {
15530 			mutex_exit(&osp->os_sync_lock);
15531 			have_sync_lock = 0;
15532 		}
15533 		if (did_start_seqid_sync) {
15534 			nfs4_end_open_seqid_sync(oop);
15535 			did_start_seqid_sync = 0;
15536 		}
15537 		open_stream_rele(osp, rp);
15538 
15539 		if (did_start_op)
15540 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15541 			    &recov_state, FALSE);
15542 		if (did_force_recovlock)
15543 			nfs_rw_exit(&mi->mi_recovlock);
15544 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15545 		    "nfs4close_one: need to retry the close "
15546 		    "operation"));
15547 		goto recov_retry;
15548 	}
15549 close_cleanup:
15550 	/*
15551 	 * Seventh and lastly, process our results.
15552 	 */
15553 	if (close_failed && force_close) {
15554 		/*
15555 		 * It's ok to drop and regrab the 'os_sync_lock' since
15556 		 * nfs4close_notw() will recheck to make sure the
15557 		 * "close"/removal of state should happen.
15558 		 */
15559 		if (!have_sync_lock) {
15560 			mutex_enter(&osp->os_sync_lock);
15561 			have_sync_lock = 1;
15562 		}
15563 		/*
15564 		 * This is last call, remove the ref on the open
15565 		 * stream created by open and clean everything up.
15566 		 */
15567 		osp->os_pending_close = 0;
15568 		nfs4close_notw(vp, osp, &have_sync_lock);
15569 		nfs4_error_zinit(ep);
15570 	}
15571 
15572 	if (!close_failed) {
15573 		if (have_sync_lock) {
15574 			osp->os_pending_close = 0;
15575 			mutex_exit(&osp->os_sync_lock);
15576 			have_sync_lock = 0;
15577 		} else {
15578 			mutex_enter(&osp->os_sync_lock);
15579 			osp->os_pending_close = 0;
15580 			mutex_exit(&osp->os_sync_lock);
15581 		}
15582 		if (did_start_op && recov_state.rs_sp != NULL) {
15583 			mutex_enter(&recov_state.rs_sp->s_lock);
15584 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15585 			mutex_exit(&recov_state.rs_sp->s_lock);
15586 		} else {
15587 			nfs4_dec_state_ref_count(mi);
15588 		}
15589 		nfs4_error_zinit(ep);
15590 	}
15591 
15592 out:
15593 	if (have_sync_lock)
15594 		mutex_exit(&osp->os_sync_lock);
15595 	if (did_start_op)
15596 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15597 		    recovonly ? TRUE : FALSE);
15598 	if (did_force_recovlock)
15599 		nfs_rw_exit(&mi->mi_recovlock);
15600 	if (cred_otw)
15601 		crfree(cred_otw);
15602 	if (osp)
15603 		open_stream_rele(osp, rp);
15604 	if (oop) {
15605 		if (did_start_seqid_sync)
15606 			nfs4_end_open_seqid_sync(oop);
15607 		open_owner_rele(oop);
15608 	}
15609 }
15610 
15611 /*
15612  * Convert information returned by the server in the LOCK4denied
15613  * structure to the form required by fcntl.
15614  */
15615 static void
15616 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15617 {
15618 	nfs4_lo_name_t *lo;
15619 
15620 #ifdef	DEBUG
15621 	if (denied_to_flk_debug) {
15622 		lockt_denied_debug = lockt_denied;
15623 		debug_enter("lockt_denied");
15624 	}
15625 #endif
15626 
15627 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15628 	flk->l_whence = 0;	/* aka SEEK_SET */
15629 	flk->l_start = lockt_denied->offset;
15630 	flk->l_len = lockt_denied->length;
15631 
15632 	/*
15633 	 * If the blocking clientid matches our client id, then we can
15634 	 * interpret the lockowner (since we built it).  If not, then
15635 	 * fabricate a sysid and pid.  Note that the l_sysid field
15636 	 * in *flk already has the local sysid.
15637 	 */
15638 
15639 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15640 
15641 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15642 			lo = (nfs4_lo_name_t *)
15643 			    lockt_denied->owner.owner_val;
15644 
15645 			flk->l_pid = lo->ln_pid;
15646 		} else {
15647 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15648 			    "denied_to_flk: bad lock owner length\n"));
15649 
15650 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15651 		}
15652 	} else {
15653 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15654 		"denied_to_flk: foreign clientid\n"));
15655 
15656 		/*
15657 		 * Construct a new sysid which should be different from
15658 		 * sysids of other systems.
15659 		 */
15660 
15661 		flk->l_sysid++;
15662 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15663 	}
15664 }
15665 
15666 static pid_t
15667 lo_to_pid(lock_owner4 *lop)
15668 {
15669 	pid_t pid = 0;
15670 	uchar_t *cp;
15671 	int i;
15672 
15673 	cp = (uchar_t *)&lop->clientid;
15674 
15675 	for (i = 0; i < sizeof (lop->clientid); i++)
15676 		pid += (pid_t)*cp++;
15677 
15678 	cp = (uchar_t *)lop->owner_val;
15679 
15680 	for (i = 0; i < lop->owner_len; i++)
15681 		pid += (pid_t)*cp++;
15682 
15683 	return (pid);
15684 }
15685 
15686 /*
15687  * Given a lock pointer, returns the length of that lock.
15688  * "end" is the last locked offset the "l_len" covers from
15689  * the start of the lock.
15690  */
15691 static off64_t
15692 lock_to_end(flock64_t *lock)
15693 {
15694 	off64_t lock_end;
15695 
15696 	if (lock->l_len == 0)
15697 		lock_end = (off64_t)MAXEND;
15698 	else
15699 		lock_end = lock->l_start + lock->l_len - 1;
15700 
15701 	return (lock_end);
15702 }
15703 
15704 /*
15705  * Given the end of a lock, it will return you the length "l_len" for that lock.
15706  */
15707 static off64_t
15708 end_to_len(off64_t start, off64_t end)
15709 {
15710 	off64_t lock_len;
15711 
15712 	ASSERT(end >= start);
15713 	if (end == MAXEND)
15714 		lock_len = 0;
15715 	else
15716 		lock_len = end - start + 1;
15717 
15718 	return (lock_len);
15719 }
15720 
15721 /*
15722  * On given end for a lock it determines if it is the last locked offset
15723  * or not, if so keeps it as is, else adds one to return the length for
15724  * valid start.
15725  */
15726 static off64_t
15727 start_check(off64_t x)
15728 {
15729 	if (x == MAXEND)
15730 		return (x);
15731 	else
15732 		return (x + 1);
15733 }
15734 
15735 /*
15736  * See if these two locks overlap, and if so return 1;
15737  * otherwise, return 0.
15738  */
15739 static int
15740 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15741 {
15742 	off64_t llfp_end, curfp_end;
15743 
15744 	llfp_end = lock_to_end(llfp);
15745 	curfp_end = lock_to_end(curfp);
15746 
15747 	if (((llfp_end >= curfp->l_start) &&
15748 	    (llfp->l_start <= curfp->l_start)) ||
15749 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15750 		return (1);
15751 	return (0);
15752 }
15753 
15754 /*
15755  * Determine what the intersecting lock region is, and add that to the
15756  * 'nl_llpp' locklist in increasing order (by l_start).
15757  */
15758 static void
15759 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15760     locklist_t **nl_llpp, vnode_t *vp)
15761 {
15762 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15763 	off64_t lost_flp_end, local_flp_end, len, start;
15764 
15765 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15766 
15767 	if (!locks_intersect(lost_flp, local_flp))
15768 		return;
15769 
15770 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15771 	    "locks intersect"));
15772 
15773 	lost_flp_end = lock_to_end(lost_flp);
15774 	local_flp_end = lock_to_end(local_flp);
15775 
15776 	/* Find the starting point of the intersecting region */
15777 	if (local_flp->l_start > lost_flp->l_start)
15778 		start = local_flp->l_start;
15779 	else
15780 		start = lost_flp->l_start;
15781 
15782 	/* Find the lenght of the intersecting region */
15783 	if (lost_flp_end < local_flp_end)
15784 		len = end_to_len(start, lost_flp_end);
15785 	else
15786 		len = end_to_len(start, local_flp_end);
15787 
15788 	/*
15789 	 * Prepare the flock structure for the intersection found and insert
15790 	 * it into the new list in increasing l_start order. This list contains
15791 	 * intersections of locks registered by the client with the local host
15792 	 * and the lost lock.
15793 	 * The lock type of this lock is the same as that of the local_flp.
15794 	 */
15795 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15796 	intersect_llp->ll_flock.l_start = start;
15797 	intersect_llp->ll_flock.l_len = len;
15798 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15799 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15800 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15801 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15802 	intersect_llp->ll_vp = vp;
15803 
15804 	tmp_fllp = *nl_llpp;
15805 	cur_fllp = NULL;
15806 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15807 	    intersect_llp->ll_flock.l_start) {
15808 			cur_fllp = tmp_fllp;
15809 			tmp_fllp = tmp_fllp->ll_next;
15810 	}
15811 	if (cur_fllp == NULL) {
15812 		/* first on the list */
15813 		intersect_llp->ll_next = *nl_llpp;
15814 		*nl_llpp = intersect_llp;
15815 	} else {
15816 		intersect_llp->ll_next = cur_fllp->ll_next;
15817 		cur_fllp->ll_next = intersect_llp;
15818 	}
15819 
15820 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15821 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15822 	    intersect_llp->ll_flock.l_start,
15823 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15824 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15825 }
15826 
15827 /*
15828  * Our local locking current state is potentially different than
15829  * what the NFSv4 server thinks we have due to a lost lock that was
15830  * resent and then received.  We need to reset our "NFSv4" locking
15831  * state to match the current local locking state for this pid since
15832  * that is what the user/application sees as what the world is.
15833  *
15834  * We cannot afford to drop the open/lock seqid sync since then we can
15835  * get confused about what the current local locking state "is" versus
15836  * "was".
15837  *
15838  * If we are unable to fix up the locks, we send SIGLOST to the affected
15839  * process.  This is not done if the filesystem has been forcibly
15840  * unmounted, in case the process has already exited and a new process
15841  * exists with the same pid.
15842  */
15843 static void
15844 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15845     nfs4_lock_owner_t *lop)
15846 {
15847 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15848 	mntinfo4_t *mi = VTOMI4(vp);
15849 	const int cmd = F_SETLK;
15850 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15851 	flock64_t ul_fl;
15852 
15853 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15854 	    "nfs4_reinstitute_local_lock_state"));
15855 
15856 	/*
15857 	 * Find active locks for this vp from the local locking code.
15858 	 * Scan through this list and find out the locks that intersect with
15859 	 * the lost lock. Once we find the lock that intersects, add the
15860 	 * intersection area as a new lock to a new list "ri_llp". The lock
15861 	 * type of the intersection region lock added to ri_llp is the same
15862 	 * as that found in the active lock list, "list". The intersecting
15863 	 * region locks are added to ri_llp in increasing l_start order.
15864 	 */
15865 	ASSERT(nfs_zone() == mi->mi_zone);
15866 
15867 	locks = flk_active_locks_for_vp(vp);
15868 	ri_llp = NULL;
15869 
15870 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15871 		ASSERT(llp->ll_vp == vp);
15872 		/*
15873 		 * Pick locks that belong to this pid/lockowner
15874 		 */
15875 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15876 			continue;
15877 
15878 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15879 	}
15880 
15881 	/*
15882 	 * Now we have the list of intersections with the lost lock. These are
15883 	 * the locks that were/are active before the server replied to the
15884 	 * last/lost lock. Issue these locks to the server here. Playing these
15885 	 * locks to the server will re-establish our current local locking state
15886 	 * with the v4 server.
15887 	 * If we get an error, send SIGLOST to the application for that lock.
15888 	 */
15889 
15890 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15891 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15892 		    "nfs4_reinstitute_local_lock_state: need to issue "
15893 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15894 		    llp->ll_flock.l_start,
15895 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15896 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15897 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15898 		/*
15899 		 * No need to relock what we already have
15900 		 */
15901 		if (llp->ll_flock.l_type == lost_flp->l_type)
15902 			continue;
15903 
15904 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15905 	}
15906 
15907 	/*
15908 	 * Now keeping the start of the lost lock as our reference parse the
15909 	 * newly created ri_llp locklist to find the ranges that we have locked
15910 	 * with the v4 server but not in the current local locking. We need
15911 	 * to unlock these ranges.
15912 	 * These ranges can also be reffered to as those ranges, where the lost
15913 	 * lock does not overlap with the locks in the ri_llp but are locked
15914 	 * since the server replied to the lost lock.
15915 	 */
15916 	cur_start = lost_flp->l_start;
15917 	lost_flp_end = lock_to_end(lost_flp);
15918 
15919 	ul_fl.l_type = F_UNLCK;
15920 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15921 	ul_fl.l_sysid = lost_flp->l_sysid;
15922 	ul_fl.l_pid = lost_flp->l_pid;
15923 
15924 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15925 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15926 
15927 		if (llp->ll_flock.l_start <= cur_start) {
15928 			cur_start = start_check(llp_ll_flock_end);
15929 			continue;
15930 		}
15931 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15932 		    "nfs4_reinstitute_local_lock_state: "
15933 		    "UNLOCK [%"PRIx64" - %"PRIx64"]",
15934 		    cur_start, llp->ll_flock.l_start));
15935 
15936 		ul_fl.l_start = cur_start;
15937 		ul_fl.l_len = end_to_len(cur_start,
15938 		    (llp->ll_flock.l_start - 1));
15939 
15940 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15941 		cur_start = start_check(llp_ll_flock_end);
15942 	}
15943 
15944 	/*
15945 	 * In the case where the lost lock ends after all intersecting locks,
15946 	 * unlock the last part of the lost lock range.
15947 	 */
15948 	if (cur_start != start_check(lost_flp_end)) {
15949 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15950 		    "nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15951 		    "lost lock region [%"PRIx64" - %"PRIx64"]",
15952 		    cur_start, lost_flp->l_start + lost_flp->l_len));
15953 
15954 		ul_fl.l_start = cur_start;
15955 		/*
15956 		 * Is it an to-EOF lock? if so unlock till the end
15957 		 */
15958 		if (lost_flp->l_len == 0)
15959 			ul_fl.l_len = 0;
15960 		else
15961 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15962 
15963 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15964 	}
15965 
15966 	if (locks != NULL)
15967 		flk_free_locklist(locks);
15968 
15969 	/* Free up our newly created locklist */
15970 	for (llp = ri_llp; llp != NULL; ) {
15971 		tmp_llp = llp->ll_next;
15972 		kmem_free(llp, sizeof (locklist_t));
15973 		llp = tmp_llp;
15974 	}
15975 
15976 	/*
15977 	 * Now return back to the original calling nfs4frlock()
15978 	 * and let us naturally drop our seqid syncs.
15979 	 */
15980 }
15981 
15982 /*
15983  * Create a lost state record for the given lock reinstantiation request
15984  * and push it onto the lost state queue.
15985  */
15986 static void
15987 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
15988     nfs4_lock_owner_t *lop)
15989 {
15990 	nfs4_lost_rqst_t req;
15991 	nfs_lock_type4 locktype;
15992 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
15993 
15994 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15995 
15996 	locktype = flk_to_locktype(cmd, flk->l_type);
15997 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
15998 	    NULL, NULL, lop, flk, &req, cr, vp);
15999 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
16000 	    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
16001 	    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
16002 	    NULL, NULL, NULL);
16003 }
16004