xref: /titanic_50/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision 880d797826457b77414b37d531cc3e1aa166ecbe)
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 2015 Nexenta Systems, Inc.  All rights reserved.
24  */
25 
26 /*
27  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
28  * Use is subject to license terms.
29  */
30 
31 /*
32  *	Copyright 1983,1984,1985,1986,1987,1988,1989 AT&T.
33  *	All Rights Reserved
34  */
35 
36 /*
37  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
38  */
39 
40 /*
41  * Copyright (c) 2014, STRATO AG. 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 *mi);
120 static int nfs4frlock_get_sysid(struct lm_sysid **, vnode_t *, flock64_t *);
121 
122 static void	nfs4_update_dircaches(change_info4 *, vnode_t *, vnode_t *,
123 			char *, dirattr_info_t *);
124 
125 static void	nfs4close_otw(rnode4_t *, cred_t *, nfs4_open_owner_t *,
126 		    nfs4_open_stream_t *, int *, int *, nfs4_close_type_t,
127 		    nfs4_error_t *, int *);
128 static int	nfs4_rdwrlbn(vnode_t *, page_t *, u_offset_t, size_t, int,
129 			cred_t *);
130 static int	nfs4write(vnode_t *, caddr_t, u_offset_t, int, cred_t *,
131 			stable_how4 *);
132 static int	nfs4read(vnode_t *, caddr_t, offset_t, int, size_t *,
133 			cred_t *, bool_t, struct uio *);
134 static int	nfs4setattr(vnode_t *, struct vattr *, int, cred_t *,
135 			vsecattr_t *);
136 static int	nfs4openattr(vnode_t *, vnode_t **, int, cred_t *);
137 static int	nfs4lookup(vnode_t *, char *, vnode_t **, cred_t *, int);
138 static int	nfs4lookup_xattr(vnode_t *, char *, vnode_t **, int, cred_t *);
139 static int	nfs4lookupvalidate_otw(vnode_t *, char *, vnode_t **, cred_t *);
140 static int	nfs4lookupnew_otw(vnode_t *, char *, vnode_t **, cred_t *);
141 static int	nfs4mknod(vnode_t *, char *, struct vattr *, enum vcexcl,
142 			int, vnode_t **, cred_t *);
143 static int	nfs4open_otw(vnode_t *, char *, struct vattr *, vnode_t **,
144 			cred_t *, int, int, enum createmode4, int);
145 static int	nfs4rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
146 			caller_context_t *);
147 static int	nfs4rename_persistent_fh(vnode_t *, char *, vnode_t *,
148 			vnode_t *, char *, cred_t *, nfsstat4 *);
149 static int	nfs4rename_volatile_fh(vnode_t *, char *, vnode_t *,
150 			vnode_t *, char *, cred_t *, nfsstat4 *);
151 static int	do_nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
152 static void	nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
153 static int	nfs4_bio(struct buf *, stable_how4 *, cred_t *, bool_t);
154 static int	nfs4_getapage(vnode_t *, u_offset_t, size_t, uint_t *,
155 			page_t *[], size_t, struct seg *, caddr_t,
156 			enum seg_rw, cred_t *);
157 static void	nfs4_readahead(vnode_t *, u_offset_t, caddr_t, struct seg *,
158 			cred_t *);
159 static int	nfs4_sync_putapage(vnode_t *, page_t *, u_offset_t, size_t,
160 			int, cred_t *);
161 static int	nfs4_sync_pageio(vnode_t *, page_t *, u_offset_t, size_t,
162 			int, cred_t *);
163 static int	nfs4_commit(vnode_t *, offset4, count4, cred_t *);
164 static void	nfs4_set_mod(vnode_t *);
165 static void	nfs4_get_commit(vnode_t *);
166 static void	nfs4_get_commit_range(vnode_t *, u_offset_t, size_t);
167 static int	nfs4_putpage_commit(vnode_t *, offset_t, size_t, cred_t *);
168 static int	nfs4_commit_vp(vnode_t *, u_offset_t, size_t, cred_t *, int);
169 static int	nfs4_sync_commit(vnode_t *, page_t *, offset3, count3,
170 			cred_t *);
171 static void	do_nfs4_async_commit(vnode_t *, page_t *, offset3, count3,
172 			cred_t *);
173 static int	nfs4_update_attrcache(nfsstat4, nfs4_ga_res_t *,
174 			hrtime_t, vnode_t *, cred_t *);
175 static int	nfs4_open_non_reg_file(vnode_t **, int, cred_t *);
176 static int	nfs4_safelock(vnode_t *, const struct flock64 *, cred_t *);
177 static int	nfs4_lockrelease(vnode_t *, int, offset_t, cred_t *);
178 static int	nfs4_block_and_wait(clock_t *);
179 static cred_t  *state_to_cred(nfs4_open_stream_t *);
180 static void	denied_to_flk(LOCK4denied *, flock64_t *, LOCKT4args *);
181 static pid_t	lo_to_pid(lock_owner4 *);
182 static void	nfs4_reinstitute_local_lock_state(vnode_t *, flock64_t *,
183 			cred_t *, nfs4_lock_owner_t *);
184 static void	push_reinstate(vnode_t *, int, flock64_t *, cred_t *,
185 			nfs4_lock_owner_t *);
186 static int	open_and_get_osp(vnode_t *, cred_t *, nfs4_open_stream_t **);
187 static void	nfs4_delmap_callback(struct as *, void *, uint_t);
188 static void	nfs4_free_delmapcall(nfs4_delmapcall_t *);
189 static nfs4_delmapcall_t	*nfs4_init_delmapcall();
190 static int	nfs4_find_and_delete_delmapcall(rnode4_t *, int *);
191 static int	nfs4_is_acl_mask_valid(uint_t, nfs4_acl_op_t);
192 static int	nfs4_create_getsecattr_return(vsecattr_t *, vsecattr_t *,
193 			uid_t, gid_t, int);
194 
195 /*
196  * Routines that implement the setting of v4 args for the misc. ops
197  */
198 static void	nfs4args_lock_free(nfs_argop4 *);
199 static void	nfs4args_lockt_free(nfs_argop4 *);
200 static void	nfs4args_setattr(nfs_argop4 *, vattr_t *, vsecattr_t *,
201 			int, rnode4_t *, cred_t *, bitmap4, int *,
202 			nfs4_stateid_types_t *);
203 static void	nfs4args_setattr_free(nfs_argop4 *);
204 static int	nfs4args_verify(nfs_argop4 *, vattr_t *, enum nfs_opnum4,
205 			bitmap4);
206 static void	nfs4args_verify_free(nfs_argop4 *);
207 static void	nfs4args_write(nfs_argop4 *, stable_how4, rnode4_t *, cred_t *,
208 			WRITE4args **, nfs4_stateid_types_t *);
209 
210 /*
211  * These are the vnode ops functions that implement the vnode interface to
212  * the networked file system.  See more comments below at nfs4_vnodeops.
213  */
214 static int	nfs4_open(vnode_t **, int, cred_t *, caller_context_t *);
215 static int	nfs4_close(vnode_t *, int, int, offset_t, cred_t *,
216 			caller_context_t *);
217 static int	nfs4_read(vnode_t *, struct uio *, int, cred_t *,
218 			caller_context_t *);
219 static int	nfs4_write(vnode_t *, struct uio *, int, cred_t *,
220 			caller_context_t *);
221 static int	nfs4_ioctl(vnode_t *, int, intptr_t, int, cred_t *, int *,
222 			caller_context_t *);
223 static int	nfs4_setattr(vnode_t *, struct vattr *, int, cred_t *,
224 			caller_context_t *);
225 static int	nfs4_access(vnode_t *, int, int, cred_t *, caller_context_t *);
226 static int	nfs4_readlink(vnode_t *, struct uio *, cred_t *,
227 			caller_context_t *);
228 static int	nfs4_fsync(vnode_t *, int, cred_t *, caller_context_t *);
229 static int	nfs4_create(vnode_t *, char *, struct vattr *, enum vcexcl,
230 			int, vnode_t **, cred_t *, int, caller_context_t *,
231 			vsecattr_t *);
232 static int	nfs4_remove(vnode_t *, char *, cred_t *, caller_context_t *,
233 			int);
234 static int	nfs4_link(vnode_t *, vnode_t *, char *, cred_t *,
235 			caller_context_t *, int);
236 static int	nfs4_rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
237 			caller_context_t *, int);
238 static int	nfs4_mkdir(vnode_t *, char *, struct vattr *, vnode_t **,
239 			cred_t *, caller_context_t *, int, vsecattr_t *);
240 static int	nfs4_rmdir(vnode_t *, char *, vnode_t *, cred_t *,
241 			caller_context_t *, int);
242 static int	nfs4_symlink(vnode_t *, char *, struct vattr *, char *,
243 			cred_t *, caller_context_t *, int);
244 static int	nfs4_readdir(vnode_t *, struct uio *, cred_t *, int *,
245 			caller_context_t *, int);
246 static int	nfs4_seek(vnode_t *, offset_t, offset_t *, caller_context_t *);
247 static int	nfs4_getpage(vnode_t *, offset_t, size_t, uint_t *,
248 			page_t *[], size_t, struct seg *, caddr_t,
249 			enum seg_rw, cred_t *, caller_context_t *);
250 static int	nfs4_putpage(vnode_t *, offset_t, size_t, int, cred_t *,
251 			caller_context_t *);
252 static int	nfs4_map(vnode_t *, offset_t, struct as *, caddr_t *, size_t,
253 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
254 static int	nfs4_addmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
255 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
256 static int	nfs4_cmp(vnode_t *, vnode_t *, caller_context_t *);
257 static int	nfs4_frlock(vnode_t *, int, struct flock64 *, int, offset_t,
258 			struct flk_callback *, cred_t *, caller_context_t *);
259 static int	nfs4_space(vnode_t *, int, struct flock64 *, int, offset_t,
260 			cred_t *, caller_context_t *);
261 static int	nfs4_delmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
262 			uint_t, uint_t, uint_t, cred_t *, caller_context_t *);
263 static int	nfs4_pageio(vnode_t *, page_t *, u_offset_t, size_t, int,
264 			cred_t *, caller_context_t *);
265 static void	nfs4_dispose(vnode_t *, page_t *, int, int, cred_t *,
266 			caller_context_t *);
267 static int	nfs4_setsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
268 			caller_context_t *);
269 /*
270  * These vnode ops are required to be called from outside this source file,
271  * e.g. by ephemeral mount stub vnode ops, and so may not be declared
272  * as static.
273  */
274 int	nfs4_getattr(vnode_t *, struct vattr *, int, cred_t *,
275 	    caller_context_t *);
276 void	nfs4_inactive(vnode_t *, cred_t *, caller_context_t *);
277 int	nfs4_lookup(vnode_t *, char *, vnode_t **,
278 	    struct pathname *, int, vnode_t *, cred_t *,
279 	    caller_context_t *, int *, pathname_t *);
280 int	nfs4_fid(vnode_t *, fid_t *, caller_context_t *);
281 int	nfs4_rwlock(vnode_t *, int, caller_context_t *);
282 void	nfs4_rwunlock(vnode_t *, int, caller_context_t *);
283 int	nfs4_realvp(vnode_t *, vnode_t **, caller_context_t *);
284 int	nfs4_pathconf(vnode_t *, int, ulong_t *, cred_t *,
285 	    caller_context_t *);
286 int	nfs4_getsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
287 	    caller_context_t *);
288 int	nfs4_shrlock(vnode_t *, int, struct shrlock *, int, cred_t *,
289 	    caller_context_t *);
290 
291 /*
292  * Used for nfs4_commit_vp() to indicate if we should
293  * wait on pending writes.
294  */
295 #define	NFS4_WRITE_NOWAIT	0
296 #define	NFS4_WRITE_WAIT		1
297 
298 /*
299  * Error flags used to pass information about certain special errors
300  * which need to be handled specially.
301  */
302 #define	NFS_EOF			-98
303 #define	NFS_VERF_MISMATCH	-97
304 
305 /*
306  * Flags used to differentiate between which operation drove the
307  * potential CLOSE OTW. (see nfs4_close_otw_if_necessary)
308  */
309 #define	NFS4_CLOSE_OP		0x1
310 #define	NFS4_DELMAP_OP		0x2
311 #define	NFS4_INACTIVE_OP	0x3
312 
313 #define	ISVDEV(t) ((t == VBLK) || (t == VCHR) || (t == VFIFO))
314 
315 /* ALIGN64 aligns the given buffer and adjust buffer size to 64 bit */
316 #define	ALIGN64(x, ptr, sz)						\
317 	x = ((uintptr_t)(ptr)) & (sizeof (uint64_t) - 1);		\
318 	if (x) {							\
319 		x = sizeof (uint64_t) - (x);				\
320 		sz -= (x);						\
321 		ptr += (x);						\
322 	}
323 
324 #ifdef DEBUG
325 int nfs4_client_attr_debug = 0;
326 int nfs4_client_state_debug = 0;
327 int nfs4_client_shadow_debug = 0;
328 int nfs4_client_lock_debug = 0;
329 int nfs4_seqid_sync = 0;
330 int nfs4_client_map_debug = 0;
331 static int nfs4_pageio_debug = 0;
332 int nfs4_client_inactive_debug = 0;
333 int nfs4_client_recov_debug = 0;
334 int nfs4_client_failover_debug = 0;
335 int nfs4_client_call_debug = 0;
336 int nfs4_client_lookup_debug = 0;
337 int nfs4_client_zone_debug = 0;
338 int nfs4_lost_rqst_debug = 0;
339 int nfs4_rdattrerr_debug = 0;
340 int nfs4_open_stream_debug = 0;
341 
342 int nfs4read_error_inject;
343 
344 static int nfs4_create_misses = 0;
345 
346 static int nfs4_readdir_cache_shorts = 0;
347 static int nfs4_readdir_readahead = 0;
348 
349 static int nfs4_bio_do_stop = 0;
350 
351 static int nfs4_lostpage = 0;	/* number of times we lost original page */
352 
353 int nfs4_mmap_debug = 0;
354 
355 static int nfs4_pathconf_cache_hits = 0;
356 static int nfs4_pathconf_cache_misses = 0;
357 
358 int nfs4close_all_cnt;
359 int nfs4close_one_debug = 0;
360 int nfs4close_notw_debug = 0;
361 
362 int denied_to_flk_debug = 0;
363 void *lockt_denied_debug;
364 
365 #endif
366 
367 /*
368  * In milliseconds. Should be less than half of the lease time or better,
369  * less than one second.
370  */
371 int nfs4_base_wait_time = 20;
372 int nfs4_max_base_wait_time = 1 * 1000;	/* 1 sec */
373 
374 /*
375  * How long to wait before trying again if OPEN_CONFIRM gets ETIMEDOUT
376  * or NFS4ERR_RESOURCE.
377  */
378 static int confirm_retry_sec = 30;
379 
380 static int nfs4_lookup_neg_cache = 1;
381 
382 /*
383  * number of pages to read ahead
384  * optimized for 100 base-T.
385  */
386 static int nfs4_nra = 4;
387 
388 static int nfs4_do_symlink_cache = 1;
389 
390 static int nfs4_pathconf_disable_cache = 0;
391 
392 /*
393  * These are the vnode ops routines which implement the vnode interface to
394  * the networked file system.  These routines just take their parameters,
395  * make them look networkish by putting the right info into interface structs,
396  * and then calling the appropriate remote routine(s) to do the work.
397  *
398  * Note on directory name lookup cacheing:  If we detect a stale fhandle,
399  * we purge the directory cache relative to that vnode.  This way, the
400  * user won't get burned by the cache repeatedly.  See <nfs/rnode4.h> for
401  * more details on rnode locking.
402  */
403 
404 struct vnodeops *nfs4_vnodeops;
405 
406 const fs_operation_def_t nfs4_vnodeops_template[] = {
407 	VOPNAME_OPEN,		{ .vop_open = nfs4_open },
408 	VOPNAME_CLOSE,		{ .vop_close = nfs4_close },
409 	VOPNAME_READ,		{ .vop_read = nfs4_read },
410 	VOPNAME_WRITE,		{ .vop_write = nfs4_write },
411 	VOPNAME_IOCTL,		{ .vop_ioctl = nfs4_ioctl },
412 	VOPNAME_GETATTR,	{ .vop_getattr = nfs4_getattr },
413 	VOPNAME_SETATTR,	{ .vop_setattr = nfs4_setattr },
414 	VOPNAME_ACCESS,		{ .vop_access = nfs4_access },
415 	VOPNAME_LOOKUP,		{ .vop_lookup = nfs4_lookup },
416 	VOPNAME_CREATE,		{ .vop_create = nfs4_create },
417 	VOPNAME_REMOVE,		{ .vop_remove = nfs4_remove },
418 	VOPNAME_LINK,		{ .vop_link = nfs4_link },
419 	VOPNAME_RENAME,		{ .vop_rename = nfs4_rename },
420 	VOPNAME_MKDIR,		{ .vop_mkdir = nfs4_mkdir },
421 	VOPNAME_RMDIR,		{ .vop_rmdir = nfs4_rmdir },
422 	VOPNAME_READDIR,	{ .vop_readdir = nfs4_readdir },
423 	VOPNAME_SYMLINK,	{ .vop_symlink = nfs4_symlink },
424 	VOPNAME_READLINK,	{ .vop_readlink = nfs4_readlink },
425 	VOPNAME_FSYNC,		{ .vop_fsync = nfs4_fsync },
426 	VOPNAME_INACTIVE,	{ .vop_inactive = nfs4_inactive },
427 	VOPNAME_FID,		{ .vop_fid = nfs4_fid },
428 	VOPNAME_RWLOCK,		{ .vop_rwlock = nfs4_rwlock },
429 	VOPNAME_RWUNLOCK,	{ .vop_rwunlock = nfs4_rwunlock },
430 	VOPNAME_SEEK,		{ .vop_seek = nfs4_seek },
431 	VOPNAME_FRLOCK,		{ .vop_frlock = nfs4_frlock },
432 	VOPNAME_SPACE,		{ .vop_space = nfs4_space },
433 	VOPNAME_REALVP,		{ .vop_realvp = nfs4_realvp },
434 	VOPNAME_GETPAGE,	{ .vop_getpage = nfs4_getpage },
435 	VOPNAME_PUTPAGE,	{ .vop_putpage = nfs4_putpage },
436 	VOPNAME_MAP,		{ .vop_map = nfs4_map },
437 	VOPNAME_ADDMAP,		{ .vop_addmap = nfs4_addmap },
438 	VOPNAME_DELMAP,		{ .vop_delmap = nfs4_delmap },
439 	/* no separate nfs4_dump */
440 	VOPNAME_DUMP,		{ .vop_dump = nfs_dump },
441 	VOPNAME_PATHCONF,	{ .vop_pathconf = nfs4_pathconf },
442 	VOPNAME_PAGEIO,		{ .vop_pageio = nfs4_pageio },
443 	VOPNAME_DISPOSE,	{ .vop_dispose = nfs4_dispose },
444 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = nfs4_setsecattr },
445 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = nfs4_getsecattr },
446 	VOPNAME_SHRLOCK,	{ .vop_shrlock = nfs4_shrlock },
447 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
448 	NULL,			NULL
449 };
450 
451 /*
452  * The following are subroutines and definitions to set args or get res
453  * for the different nfsv4 ops
454  */
455 
456 void
457 nfs4args_lookup_free(nfs_argop4 *argop, int arglen)
458 {
459 	int		i;
460 
461 	for (i = 0; i < arglen; i++) {
462 		if (argop[i].argop == OP_LOOKUP) {
463 			kmem_free(
464 			    argop[i].nfs_argop4_u.oplookup.
465 			    objname.utf8string_val,
466 			    argop[i].nfs_argop4_u.oplookup.
467 			    objname.utf8string_len);
468 		}
469 	}
470 }
471 
472 static void
473 nfs4args_lock_free(nfs_argop4 *argop)
474 {
475 	locker4 *locker = &argop->nfs_argop4_u.oplock.locker;
476 
477 	if (locker->new_lock_owner == TRUE) {
478 		open_to_lock_owner4 *open_owner;
479 
480 		open_owner = &locker->locker4_u.open_owner;
481 		if (open_owner->lock_owner.owner_val != NULL) {
482 			kmem_free(open_owner->lock_owner.owner_val,
483 			    open_owner->lock_owner.owner_len);
484 		}
485 	}
486 }
487 
488 static void
489 nfs4args_lockt_free(nfs_argop4 *argop)
490 {
491 	lock_owner4 *lowner = &argop->nfs_argop4_u.oplockt.owner;
492 
493 	if (lowner->owner_val != NULL) {
494 		kmem_free(lowner->owner_val, lowner->owner_len);
495 	}
496 }
497 
498 static void
499 nfs4args_setattr(nfs_argop4 *argop, vattr_t *vap, vsecattr_t *vsap, int flags,
500     rnode4_t *rp, cred_t *cr, bitmap4 supp, int *error,
501     nfs4_stateid_types_t *sid_types)
502 {
503 	fattr4		*attr = &argop->nfs_argop4_u.opsetattr.obj_attributes;
504 	mntinfo4_t	*mi;
505 
506 	argop->argop = OP_SETATTR;
507 	/*
508 	 * The stateid is set to 0 if client is not modifying the size
509 	 * and otherwise to whatever nfs4_get_stateid() returns.
510 	 *
511 	 * XXX Note: nfs4_get_stateid() returns 0 if no lockowner and/or no
512 	 * state struct could be found for the process/file pair.  We may
513 	 * want to change this in the future (by OPENing the file).  See
514 	 * bug # 4474852.
515 	 */
516 	if (vap->va_mask & AT_SIZE) {
517 
518 		ASSERT(rp != NULL);
519 		mi = VTOMI4(RTOV4(rp));
520 
521 		argop->nfs_argop4_u.opsetattr.stateid =
522 		    nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
523 		    OP_SETATTR, sid_types, FALSE);
524 	} else {
525 		bzero(&argop->nfs_argop4_u.opsetattr.stateid,
526 		    sizeof (stateid4));
527 	}
528 
529 	*error = vattr_to_fattr4(vap, vsap, attr, flags, OP_SETATTR, supp);
530 	if (*error)
531 		bzero(attr, sizeof (*attr));
532 }
533 
534 static void
535 nfs4args_setattr_free(nfs_argop4 *argop)
536 {
537 	nfs4_fattr4_free(&argop->nfs_argop4_u.opsetattr.obj_attributes);
538 }
539 
540 static int
541 nfs4args_verify(nfs_argop4 *argop, vattr_t *vap, enum nfs_opnum4 op,
542     bitmap4 supp)
543 {
544 	fattr4 *attr;
545 	int error = 0;
546 
547 	argop->argop = op;
548 	switch (op) {
549 	case OP_VERIFY:
550 		attr = &argop->nfs_argop4_u.opverify.obj_attributes;
551 		break;
552 	case OP_NVERIFY:
553 		attr = &argop->nfs_argop4_u.opnverify.obj_attributes;
554 		break;
555 	default:
556 		return (EINVAL);
557 	}
558 	if (!error)
559 		error = vattr_to_fattr4(vap, NULL, attr, 0, op, supp);
560 	if (error)
561 		bzero(attr, sizeof (*attr));
562 	return (error);
563 }
564 
565 static void
566 nfs4args_verify_free(nfs_argop4 *argop)
567 {
568 	switch (argop->argop) {
569 	case OP_VERIFY:
570 		nfs4_fattr4_free(&argop->nfs_argop4_u.opverify.obj_attributes);
571 		break;
572 	case OP_NVERIFY:
573 		nfs4_fattr4_free(&argop->nfs_argop4_u.opnverify.obj_attributes);
574 		break;
575 	default:
576 		break;
577 	}
578 }
579 
580 static void
581 nfs4args_write(nfs_argop4 *argop, stable_how4 stable, rnode4_t *rp, cred_t *cr,
582     WRITE4args **wargs_pp, nfs4_stateid_types_t *sid_tp)
583 {
584 	WRITE4args *wargs = &argop->nfs_argop4_u.opwrite;
585 	mntinfo4_t *mi = VTOMI4(RTOV4(rp));
586 
587 	argop->argop = OP_WRITE;
588 	wargs->stable = stable;
589 	wargs->stateid = nfs4_get_w_stateid(cr, rp, curproc->p_pidp->pid_id,
590 	    mi, OP_WRITE, sid_tp);
591 	wargs->mblk = NULL;
592 	*wargs_pp = wargs;
593 }
594 
595 void
596 nfs4args_copen_free(OPEN4cargs *open_args)
597 {
598 	if (open_args->owner.owner_val) {
599 		kmem_free(open_args->owner.owner_val,
600 		    open_args->owner.owner_len);
601 	}
602 	if ((open_args->opentype == OPEN4_CREATE) &&
603 	    (open_args->mode != EXCLUSIVE4)) {
604 		nfs4_fattr4_free(&open_args->createhow4_u.createattrs);
605 	}
606 }
607 
608 /*
609  * XXX:  This is referenced in modstubs.s
610  */
611 struct vnodeops *
612 nfs4_getvnodeops(void)
613 {
614 	return (nfs4_vnodeops);
615 }
616 
617 /*
618  * The OPEN operation opens a regular file.
619  */
620 /*ARGSUSED3*/
621 static int
622 nfs4_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
623 {
624 	vnode_t *dvp = NULL;
625 	rnode4_t *rp, *drp;
626 	int error;
627 	int just_been_created;
628 	char fn[MAXNAMELEN];
629 
630 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4_open: "));
631 	if (nfs_zone() != VTOMI4(*vpp)->mi_zone)
632 		return (EIO);
633 	rp = VTOR4(*vpp);
634 
635 	/*
636 	 * Check to see if opening something besides a regular file;
637 	 * if so skip the OTW call
638 	 */
639 	if ((*vpp)->v_type != VREG) {
640 		error = nfs4_open_non_reg_file(vpp, flag, cr);
641 		return (error);
642 	}
643 
644 	/*
645 	 * XXX - would like a check right here to know if the file is
646 	 * executable or not, so as to skip OTW
647 	 */
648 
649 	if ((error = vtodv(*vpp, &dvp, cr, TRUE)) != 0)
650 		return (error);
651 
652 	drp = VTOR4(dvp);
653 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
654 		return (EINTR);
655 
656 	if ((error = vtoname(*vpp, fn, MAXNAMELEN)) != 0) {
657 		nfs_rw_exit(&drp->r_rwlock);
658 		return (error);
659 	}
660 
661 	/*
662 	 * See if this file has just been CREATEd.
663 	 * If so, clear the flag and update the dnlc, which was previously
664 	 * skipped in nfs4_create.
665 	 * XXX need better serilization on this.
666 	 * XXX move this into the nf4open_otw call, after we have
667 	 * XXX acquired the open owner seqid sync.
668 	 */
669 	mutex_enter(&rp->r_statev4_lock);
670 	if (rp->created_v4) {
671 		rp->created_v4 = 0;
672 		mutex_exit(&rp->r_statev4_lock);
673 
674 		dnlc_update(dvp, fn, *vpp);
675 		/* This is needed so we don't bump the open ref count */
676 		just_been_created = 1;
677 	} else {
678 		mutex_exit(&rp->r_statev4_lock);
679 		just_been_created = 0;
680 	}
681 
682 	/*
683 	 * If caller specified O_TRUNC/FTRUNC, then be sure to set
684 	 * FWRITE (to drive successful setattr(size=0) after open)
685 	 */
686 	if (flag & FTRUNC)
687 		flag |= FWRITE;
688 
689 	error = nfs4open_otw(dvp, fn, NULL, vpp, cr, 0, flag, 0,
690 	    just_been_created);
691 
692 	if (!error && !((*vpp)->v_flag & VROOT))
693 		dnlc_update(dvp, fn, *vpp);
694 
695 	nfs_rw_exit(&drp->r_rwlock);
696 
697 	/* release the hold from vtodv */
698 	VN_RELE(dvp);
699 
700 	/* exchange the shadow for the master vnode, if needed */
701 
702 	if (error == 0 && IS_SHADOW(*vpp, rp))
703 		sv_exchange(vpp);
704 
705 	return (error);
706 }
707 
708 /*
709  * See if there's a "lost open" request to be saved and recovered.
710  */
711 static void
712 nfs4open_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
713     nfs4_open_owner_t *oop, cred_t *cr, vnode_t *vp,
714     vnode_t *dvp, OPEN4cargs *open_args)
715 {
716 	vfs_t *vfsp;
717 	char *srccfp;
718 
719 	vfsp = (dvp ? dvp->v_vfsp : vp->v_vfsp);
720 
721 	if (error != ETIMEDOUT && error != EINTR &&
722 	    !NFS4_FRC_UNMT_ERR(error, vfsp)) {
723 		lost_rqstp->lr_op = 0;
724 		return;
725 	}
726 
727 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
728 	    "nfs4open_save_lost_rqst: error %d", error));
729 
730 	lost_rqstp->lr_op = OP_OPEN;
731 
732 	/*
733 	 * The vp (if it is not NULL) and dvp are held and rele'd via
734 	 * the recovery code.  See nfs4_save_lost_rqst.
735 	 */
736 	lost_rqstp->lr_vp = vp;
737 	lost_rqstp->lr_dvp = dvp;
738 	lost_rqstp->lr_oop = oop;
739 	lost_rqstp->lr_osp = NULL;
740 	lost_rqstp->lr_lop = NULL;
741 	lost_rqstp->lr_cr = cr;
742 	lost_rqstp->lr_flk = NULL;
743 	lost_rqstp->lr_oacc = open_args->share_access;
744 	lost_rqstp->lr_odeny = open_args->share_deny;
745 	lost_rqstp->lr_oclaim = open_args->claim;
746 	if (open_args->claim == CLAIM_DELEGATE_CUR) {
747 		lost_rqstp->lr_ostateid =
748 		    open_args->open_claim4_u.delegate_cur_info.delegate_stateid;
749 		srccfp = open_args->open_claim4_u.delegate_cur_info.cfile;
750 	} else {
751 		srccfp = open_args->open_claim4_u.cfile;
752 	}
753 	lost_rqstp->lr_ofile.utf8string_len = 0;
754 	lost_rqstp->lr_ofile.utf8string_val = NULL;
755 	(void) str_to_utf8(srccfp, &lost_rqstp->lr_ofile);
756 	lost_rqstp->lr_putfirst = FALSE;
757 }
758 
759 struct nfs4_excl_time {
760 	uint32 seconds;
761 	uint32 nseconds;
762 };
763 
764 /*
765  * The OPEN operation creates and/or opens a regular file
766  *
767  * ARGSUSED
768  */
769 static int
770 nfs4open_otw(vnode_t *dvp, char *file_name, struct vattr *in_va,
771     vnode_t **vpp, cred_t *cr, int create_flag, int open_flag,
772     enum createmode4 createmode, int file_just_been_created)
773 {
774 	rnode4_t *rp;
775 	rnode4_t *drp = VTOR4(dvp);
776 	vnode_t *vp = NULL;
777 	vnode_t *vpi = *vpp;
778 	bool_t needrecov = FALSE;
779 
780 	int doqueue = 1;
781 
782 	COMPOUND4args_clnt args;
783 	COMPOUND4res_clnt res;
784 	nfs_argop4 *argop;
785 	nfs_resop4 *resop;
786 	int argoplist_size;
787 	int idx_open, idx_fattr;
788 
789 	GETFH4res *gf_res = NULL;
790 	OPEN4res *op_res = NULL;
791 	nfs4_ga_res_t *garp;
792 	fattr4 *attr = NULL;
793 	struct nfs4_excl_time verf;
794 	bool_t did_excl_setup = FALSE;
795 	int created_osp;
796 
797 	OPEN4cargs *open_args;
798 	nfs4_open_owner_t	*oop = NULL;
799 	nfs4_open_stream_t	*osp = NULL;
800 	seqid4 seqid = 0;
801 	bool_t retry_open = FALSE;
802 	nfs4_recov_state_t recov_state;
803 	nfs4_lost_rqst_t lost_rqst;
804 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
805 	hrtime_t t;
806 	int acc = 0;
807 	cred_t *cred_otw = NULL;	/* cred used to do the RPC call */
808 	cred_t *ncr = NULL;
809 
810 	nfs4_sharedfh_t *otw_sfh;
811 	nfs4_sharedfh_t *orig_sfh;
812 	int fh_differs = 0;
813 	int numops, setgid_flag;
814 	int num_bseqid_retry = NFS4_NUM_RETRY_BAD_SEQID + 1;
815 
816 	/*
817 	 * Make sure we properly deal with setting the right gid on
818 	 * a newly created file to reflect the parent's setgid bit
819 	 */
820 	setgid_flag = 0;
821 	if (create_flag && in_va) {
822 
823 		/*
824 		 * If there is grpid mount flag used or
825 		 * the parent's directory has the setgid bit set
826 		 * _and_ the client was able to get a valid mapping
827 		 * for the parent dir's owner_group, we want to
828 		 * append NVERIFY(owner_group == dva.va_gid) and
829 		 * SETATTR to the CREATE compound.
830 		 */
831 		mutex_enter(&drp->r_statelock);
832 		if ((VTOMI4(dvp)->mi_flags & MI4_GRPID ||
833 		    drp->r_attr.va_mode & VSGID) &&
834 		    drp->r_attr.va_gid != GID_NOBODY) {
835 			in_va->va_mask |= AT_GID;
836 			in_va->va_gid = drp->r_attr.va_gid;
837 			setgid_flag = 1;
838 		}
839 		mutex_exit(&drp->r_statelock);
840 	}
841 
842 	/*
843 	 * Normal/non-create compound:
844 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new)
845 	 *
846 	 * Open(create) compound no setgid:
847 	 * PUTFH(dfh) + SAVEFH + OPEN(create) + GETFH + GETATTR(new) +
848 	 * RESTOREFH + GETATTR
849 	 *
850 	 * Open(create) setgid:
851 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new) +
852 	 * SAVEFH + PUTFH(dfh) + GETATTR(dvp) + RESTOREFH +
853 	 * NVERIFY(grp) + SETATTR
854 	 */
855 	if (setgid_flag) {
856 		numops = 10;
857 		idx_open = 1;
858 		idx_fattr = 3;
859 	} else if (create_flag) {
860 		numops = 7;
861 		idx_open = 2;
862 		idx_fattr = 4;
863 	} else {
864 		numops = 4;
865 		idx_open = 1;
866 		idx_fattr = 3;
867 	}
868 
869 	args.array_len = numops;
870 	argoplist_size = numops * sizeof (nfs_argop4);
871 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
872 
873 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw: "
874 	    "open %s open flag 0x%x cred %p", file_name, open_flag,
875 	    (void *)cr));
876 
877 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
878 	if (create_flag) {
879 		/*
880 		 * We are to create a file.  Initialize the passed in vnode
881 		 * pointer.
882 		 */
883 		vpi = NULL;
884 	} else {
885 		/*
886 		 * Check to see if the client owns a read delegation and is
887 		 * trying to open for write.  If so, then return the delegation
888 		 * to avoid the server doing a cb_recall and returning DELAY.
889 		 * NB - we don't use the statev4_lock here because we'd have
890 		 * to drop the lock anyway and the result would be stale.
891 		 */
892 		if ((open_flag & FWRITE) &&
893 		    VTOR4(vpi)->r_deleg_type == OPEN_DELEGATE_READ)
894 			(void) nfs4delegreturn(VTOR4(vpi), NFS4_DR_REOPEN);
895 
896 		/*
897 		 * If the file has a delegation, then do an access check up
898 		 * front.  This avoids having to an access check later after
899 		 * we've already done start_op, which could deadlock.
900 		 */
901 		if (VTOR4(vpi)->r_deleg_type != OPEN_DELEGATE_NONE) {
902 			if (open_flag & FREAD &&
903 			    nfs4_access(vpi, VREAD, 0, cr, NULL) == 0)
904 				acc |= VREAD;
905 			if (open_flag & FWRITE &&
906 			    nfs4_access(vpi, VWRITE, 0, cr, NULL) == 0)
907 				acc |= VWRITE;
908 		}
909 	}
910 
911 	drp = VTOR4(dvp);
912 
913 	recov_state.rs_flags = 0;
914 	recov_state.rs_num_retry_despite_err = 0;
915 	cred_otw = cr;
916 
917 recov_retry:
918 	fh_differs = 0;
919 	nfs4_error_zinit(&e);
920 
921 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, vpi, &recov_state);
922 	if (e.error) {
923 		if (ncr != NULL)
924 			crfree(ncr);
925 		kmem_free(argop, argoplist_size);
926 		return (e.error);
927 	}
928 
929 	args.ctag = TAG_OPEN;
930 	args.array_len = numops;
931 	args.array = argop;
932 
933 	/* putfh directory fh */
934 	argop[0].argop = OP_CPUTFH;
935 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
936 
937 	/* OPEN: either op 1 or op 2 depending upon create/setgid flags */
938 	argop[idx_open].argop = OP_COPEN;
939 	open_args = &argop[idx_open].nfs_argop4_u.opcopen;
940 	open_args->claim = CLAIM_NULL;
941 
942 	/* name of file */
943 	open_args->open_claim4_u.cfile = file_name;
944 	open_args->owner.owner_len = 0;
945 	open_args->owner.owner_val = NULL;
946 
947 	if (create_flag) {
948 		/* CREATE a file */
949 		open_args->opentype = OPEN4_CREATE;
950 		open_args->mode = createmode;
951 		if (createmode == EXCLUSIVE4) {
952 			if (did_excl_setup == FALSE) {
953 				verf.seconds = zone_get_hostid(NULL);
954 				if (verf.seconds != 0)
955 					verf.nseconds = newnum();
956 				else {
957 					timestruc_t now;
958 
959 					gethrestime(&now);
960 					verf.seconds = now.tv_sec;
961 					verf.nseconds = now.tv_nsec;
962 				}
963 				/*
964 				 * Since the server will use this value for the
965 				 * mtime, make sure that it can't overflow. Zero
966 				 * out the MSB. The actual value does not matter
967 				 * here, only its uniqeness.
968 				 */
969 				verf.seconds &= INT32_MAX;
970 				did_excl_setup = TRUE;
971 			}
972 
973 			/* Now copy over verifier to OPEN4args. */
974 			open_args->createhow4_u.createverf = *(uint64_t *)&verf;
975 		} else {
976 			int v_error;
977 			bitmap4 supp_attrs;
978 			servinfo4_t *svp;
979 
980 			attr = &open_args->createhow4_u.createattrs;
981 
982 			svp = drp->r_server;
983 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
984 			supp_attrs = svp->sv_supp_attrs;
985 			nfs_rw_exit(&svp->sv_lock);
986 
987 			/* GUARDED4 or UNCHECKED4 */
988 			v_error = vattr_to_fattr4(in_va, NULL, attr, 0, OP_OPEN,
989 			    supp_attrs);
990 			if (v_error) {
991 				bzero(attr, sizeof (*attr));
992 				nfs4args_copen_free(open_args);
993 				nfs4_end_op(VTOMI4(dvp), dvp, vpi,
994 				    &recov_state, FALSE);
995 				if (ncr != NULL)
996 					crfree(ncr);
997 				kmem_free(argop, argoplist_size);
998 				return (v_error);
999 			}
1000 		}
1001 	} else {
1002 		/* NO CREATE */
1003 		open_args->opentype = OPEN4_NOCREATE;
1004 	}
1005 
1006 	if (recov_state.rs_sp != NULL) {
1007 		mutex_enter(&recov_state.rs_sp->s_lock);
1008 		open_args->owner.clientid = recov_state.rs_sp->clientid;
1009 		mutex_exit(&recov_state.rs_sp->s_lock);
1010 	} else {
1011 		/* XXX should we just fail here? */
1012 		open_args->owner.clientid = 0;
1013 	}
1014 
1015 	/*
1016 	 * This increments oop's ref count or creates a temporary 'just_created'
1017 	 * open owner that will become valid when this OPEN/OPEN_CONFIRM call
1018 	 * completes.
1019 	 */
1020 	mutex_enter(&VTOMI4(dvp)->mi_lock);
1021 
1022 	/* See if a permanent or just created open owner exists */
1023 	oop = find_open_owner_nolock(cr, NFS4_JUST_CREATED, VTOMI4(dvp));
1024 	if (!oop) {
1025 		/*
1026 		 * This open owner does not exist so create a temporary
1027 		 * just created one.
1028 		 */
1029 		oop = create_open_owner(cr, VTOMI4(dvp));
1030 		ASSERT(oop != NULL);
1031 	}
1032 	mutex_exit(&VTOMI4(dvp)->mi_lock);
1033 
1034 	/* this length never changes, do alloc before seqid sync */
1035 	open_args->owner.owner_len = sizeof (oop->oo_name);
1036 	open_args->owner.owner_val =
1037 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1038 
1039 	e.error = nfs4_start_open_seqid_sync(oop, VTOMI4(dvp));
1040 	if (e.error == EAGAIN) {
1041 		open_owner_rele(oop);
1042 		nfs4args_copen_free(open_args);
1043 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1044 		if (ncr != NULL) {
1045 			crfree(ncr);
1046 			ncr = NULL;
1047 		}
1048 		goto recov_retry;
1049 	}
1050 
1051 	/* Check to see if we need to do the OTW call */
1052 	if (!create_flag) {
1053 		if (!nfs4_is_otw_open_necessary(oop, open_flag, vpi,
1054 		    file_just_been_created, &e.error, acc, &recov_state)) {
1055 
1056 			/*
1057 			 * The OTW open is not necessary.  Either
1058 			 * the open can succeed without it (eg.
1059 			 * delegation, error == 0) or the open
1060 			 * must fail due to an access failure
1061 			 * (error != 0).  In either case, tidy
1062 			 * up and return.
1063 			 */
1064 
1065 			nfs4_end_open_seqid_sync(oop);
1066 			open_owner_rele(oop);
1067 			nfs4args_copen_free(open_args);
1068 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, FALSE);
1069 			if (ncr != NULL)
1070 				crfree(ncr);
1071 			kmem_free(argop, argoplist_size);
1072 			return (e.error);
1073 		}
1074 	}
1075 
1076 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1077 	    open_args->owner.owner_len);
1078 
1079 	seqid = nfs4_get_open_seqid(oop) + 1;
1080 	open_args->seqid = seqid;
1081 	open_args->share_access = 0;
1082 	if (open_flag & FREAD)
1083 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1084 	if (open_flag & FWRITE)
1085 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1086 	open_args->share_deny = OPEN4_SHARE_DENY_NONE;
1087 
1088 
1089 
1090 	/*
1091 	 * getfh w/sanity check for idx_open/idx_fattr
1092 	 */
1093 	ASSERT((idx_open + 1) == (idx_fattr - 1));
1094 	argop[idx_open + 1].argop = OP_GETFH;
1095 
1096 	/* getattr */
1097 	argop[idx_fattr].argop = OP_GETATTR;
1098 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1099 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1100 
1101 	if (setgid_flag) {
1102 		vattr_t	_v;
1103 		servinfo4_t *svp;
1104 		bitmap4	supp_attrs;
1105 
1106 		svp = drp->r_server;
1107 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1108 		supp_attrs = svp->sv_supp_attrs;
1109 		nfs_rw_exit(&svp->sv_lock);
1110 
1111 		/*
1112 		 * For setgid case, we need to:
1113 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1114 		 */
1115 		argop[4].argop = OP_SAVEFH;
1116 
1117 		argop[5].argop = OP_CPUTFH;
1118 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
1119 
1120 		argop[6].argop = OP_GETATTR;
1121 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1122 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1123 
1124 		argop[7].argop = OP_RESTOREFH;
1125 
1126 		/*
1127 		 * nverify
1128 		 */
1129 		_v.va_mask = AT_GID;
1130 		_v.va_gid = in_va->va_gid;
1131 		if (!(e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
1132 		    supp_attrs))) {
1133 
1134 			/*
1135 			 * setattr
1136 			 *
1137 			 * We _know_ we're not messing with AT_SIZE or
1138 			 * AT_XTIME, so no need for stateid or flags.
1139 			 * Also we specify NULL rp since we're only
1140 			 * interested in setting owner_group attributes.
1141 			 */
1142 			nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr,
1143 			    supp_attrs, &e.error, 0);
1144 			if (e.error)
1145 				nfs4args_verify_free(&argop[8]);
1146 		}
1147 
1148 		if (e.error) {
1149 			/*
1150 			 * XXX - Revisit the last argument to nfs4_end_op()
1151 			 *	 once 5020486 is fixed.
1152 			 */
1153 			nfs4_end_open_seqid_sync(oop);
1154 			open_owner_rele(oop);
1155 			nfs4args_copen_free(open_args);
1156 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1157 			if (ncr != NULL)
1158 				crfree(ncr);
1159 			kmem_free(argop, argoplist_size);
1160 			return (e.error);
1161 		}
1162 	} else if (create_flag) {
1163 		argop[1].argop = OP_SAVEFH;
1164 
1165 		argop[5].argop = OP_RESTOREFH;
1166 
1167 		argop[6].argop = OP_GETATTR;
1168 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1169 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1170 	}
1171 
1172 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1173 	    "nfs4open_otw: %s call, nm %s, rp %s",
1174 	    needrecov ? "recov" : "first", file_name,
1175 	    rnode4info(VTOR4(dvp))));
1176 
1177 	t = gethrtime();
1178 
1179 	rfs4call(VTOMI4(dvp), &args, &res, cred_otw, &doqueue, 0, &e);
1180 
1181 	if (!e.error && nfs4_need_to_bump_seqid(&res))
1182 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1183 
1184 	needrecov = nfs4_needs_recovery(&e, TRUE, dvp->v_vfsp);
1185 
1186 	if (e.error || needrecov) {
1187 		bool_t abort = FALSE;
1188 
1189 		if (needrecov) {
1190 			nfs4_bseqid_entry_t *bsep = NULL;
1191 
1192 			nfs4open_save_lost_rqst(e.error, &lost_rqst, oop,
1193 			    cred_otw, vpi, dvp, open_args);
1194 
1195 			if (!e.error && res.status == NFS4ERR_BAD_SEQID) {
1196 				bsep = nfs4_create_bseqid_entry(oop, NULL,
1197 				    vpi, 0, args.ctag, open_args->seqid);
1198 				num_bseqid_retry--;
1199 			}
1200 
1201 			abort = nfs4_start_recovery(&e, VTOMI4(dvp), dvp, vpi,
1202 			    NULL, lost_rqst.lr_op == OP_OPEN ?
1203 			    &lost_rqst : NULL, OP_OPEN, bsep, NULL, NULL);
1204 
1205 			if (bsep)
1206 				kmem_free(bsep, sizeof (*bsep));
1207 			/* give up if we keep getting BAD_SEQID */
1208 			if (num_bseqid_retry == 0)
1209 				abort = TRUE;
1210 			if (abort == TRUE && e.error == 0)
1211 				e.error = geterrno4(res.status);
1212 		}
1213 		nfs4_end_open_seqid_sync(oop);
1214 		open_owner_rele(oop);
1215 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1216 		nfs4args_copen_free(open_args);
1217 		if (setgid_flag) {
1218 			nfs4args_verify_free(&argop[8]);
1219 			nfs4args_setattr_free(&argop[9]);
1220 		}
1221 		if (!e.error)
1222 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1223 		if (ncr != NULL) {
1224 			crfree(ncr);
1225 			ncr = NULL;
1226 		}
1227 		if (!needrecov || abort == TRUE || e.error == EINTR ||
1228 		    NFS4_FRC_UNMT_ERR(e.error, dvp->v_vfsp)) {
1229 			kmem_free(argop, argoplist_size);
1230 			return (e.error);
1231 		}
1232 		goto recov_retry;
1233 	}
1234 
1235 	/*
1236 	 * Will check and update lease after checking the rflag for
1237 	 * OPEN_CONFIRM in the successful OPEN call.
1238 	 */
1239 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
1240 
1241 		/*
1242 		 * XXX what if we're crossing mount points from server1:/drp
1243 		 * to server2:/drp/rp.
1244 		 */
1245 
1246 		/* Signal our end of use of the open seqid */
1247 		nfs4_end_open_seqid_sync(oop);
1248 
1249 		/*
1250 		 * This will destroy the open owner if it was just created,
1251 		 * and no one else has put a reference on it.
1252 		 */
1253 		open_owner_rele(oop);
1254 		if (create_flag && (createmode != EXCLUSIVE4) &&
1255 		    res.status == NFS4ERR_BADOWNER)
1256 			nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1257 
1258 		e.error = geterrno4(res.status);
1259 		nfs4args_copen_free(open_args);
1260 		if (setgid_flag) {
1261 			nfs4args_verify_free(&argop[8]);
1262 			nfs4args_setattr_free(&argop[9]);
1263 		}
1264 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1265 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1266 		/*
1267 		 * If the reply is NFS4ERR_ACCESS, it may be because
1268 		 * we are root (no root net access).  If the real uid
1269 		 * is not root, then retry with the real uid instead.
1270 		 */
1271 		if (ncr != NULL) {
1272 			crfree(ncr);
1273 			ncr = NULL;
1274 		}
1275 		if (res.status == NFS4ERR_ACCESS &&
1276 		    (ncr = crnetadjust(cred_otw)) != NULL) {
1277 			cred_otw = ncr;
1278 			goto recov_retry;
1279 		}
1280 		kmem_free(argop, argoplist_size);
1281 		return (e.error);
1282 	}
1283 
1284 	resop = &res.array[idx_open];  /* open res */
1285 	op_res = &resop->nfs_resop4_u.opopen;
1286 
1287 #ifdef DEBUG
1288 	/*
1289 	 * verify attrset bitmap
1290 	 */
1291 	if (create_flag &&
1292 	    (createmode == UNCHECKED4 || createmode == GUARDED4)) {
1293 		/* make sure attrset returned is what we asked for */
1294 		/* XXX Ignore this 'error' for now */
1295 		if (attr->attrmask != op_res->attrset)
1296 			/* EMPTY */;
1297 	}
1298 #endif
1299 
1300 	if (op_res->rflags & OPEN4_RESULT_LOCKTYPE_POSIX) {
1301 		mutex_enter(&VTOMI4(dvp)->mi_lock);
1302 		VTOMI4(dvp)->mi_flags |= MI4_POSIX_LOCK;
1303 		mutex_exit(&VTOMI4(dvp)->mi_lock);
1304 	}
1305 
1306 	resop = &res.array[idx_open + 1];  /* getfh res */
1307 	gf_res = &resop->nfs_resop4_u.opgetfh;
1308 
1309 	otw_sfh = sfh4_get(&gf_res->object, VTOMI4(dvp));
1310 
1311 	/*
1312 	 * The open stateid has been updated on the server but not
1313 	 * on the client yet.  There is a path: makenfs4node->nfs4_attr_cache->
1314 	 * flush_pages->VOP_PUTPAGE->...->nfs4write where we will issue an OTW
1315 	 * WRITE call.  That, however, will use the old stateid, so go ahead
1316 	 * and upate the open stateid now, before any call to makenfs4node.
1317 	 */
1318 	if (vpi) {
1319 		nfs4_open_stream_t	*tmp_osp;
1320 		rnode4_t		*tmp_rp = VTOR4(vpi);
1321 
1322 		tmp_osp = find_open_stream(oop, tmp_rp);
1323 		if (tmp_osp) {
1324 			tmp_osp->open_stateid = op_res->stateid;
1325 			mutex_exit(&tmp_osp->os_sync_lock);
1326 			open_stream_rele(tmp_osp, tmp_rp);
1327 		}
1328 
1329 		/*
1330 		 * We must determine if the file handle given by the otw open
1331 		 * is the same as the file handle which was passed in with
1332 		 * *vpp.  This case can be reached if the file we are trying
1333 		 * to open has been removed and another file has been created
1334 		 * having the same file name.  The passed in vnode is released
1335 		 * later.
1336 		 */
1337 		orig_sfh = VTOR4(vpi)->r_fh;
1338 		fh_differs = nfs4cmpfh(&orig_sfh->sfh_fh, &otw_sfh->sfh_fh);
1339 	}
1340 
1341 	garp = &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res;
1342 
1343 	if (create_flag || fh_differs) {
1344 		int rnode_err = 0;
1345 
1346 		vp = makenfs4node(otw_sfh, garp, dvp->v_vfsp, t, cr,
1347 		    dvp, fn_get(VTOSV(dvp)->sv_name, file_name, otw_sfh));
1348 
1349 		if (e.error)
1350 			PURGE_ATTRCACHE4(vp);
1351 		/*
1352 		 * For the newly created vp case, make sure the rnode
1353 		 * isn't bad before using it.
1354 		 */
1355 		mutex_enter(&(VTOR4(vp))->r_statelock);
1356 		if (VTOR4(vp)->r_flags & R4RECOVERR)
1357 			rnode_err = EIO;
1358 		mutex_exit(&(VTOR4(vp))->r_statelock);
1359 
1360 		if (rnode_err) {
1361 			nfs4_end_open_seqid_sync(oop);
1362 			nfs4args_copen_free(open_args);
1363 			if (setgid_flag) {
1364 				nfs4args_verify_free(&argop[8]);
1365 				nfs4args_setattr_free(&argop[9]);
1366 			}
1367 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1368 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1369 			    needrecov);
1370 			open_owner_rele(oop);
1371 			VN_RELE(vp);
1372 			if (ncr != NULL)
1373 				crfree(ncr);
1374 			sfh4_rele(&otw_sfh);
1375 			kmem_free(argop, argoplist_size);
1376 			return (EIO);
1377 		}
1378 	} else {
1379 		vp = vpi;
1380 	}
1381 	sfh4_rele(&otw_sfh);
1382 
1383 	/*
1384 	 * It seems odd to get a full set of attrs and then not update
1385 	 * the object's attrcache in the non-create case.  Create case uses
1386 	 * the attrs since makenfs4node checks to see if the attrs need to
1387 	 * be updated (and then updates them).  The non-create case should
1388 	 * update attrs also.
1389 	 */
1390 	if (! create_flag && ! fh_differs && !e.error) {
1391 		nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
1392 	}
1393 
1394 	nfs4_error_zinit(&e);
1395 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
1396 		/* This does not do recovery for vp explicitly. */
1397 		nfs4open_confirm(vp, &seqid, &op_res->stateid, cred_otw, FALSE,
1398 		    &retry_open, oop, FALSE, &e, &num_bseqid_retry);
1399 
1400 		if (e.error || e.stat) {
1401 			nfs4_end_open_seqid_sync(oop);
1402 			nfs4args_copen_free(open_args);
1403 			if (setgid_flag) {
1404 				nfs4args_verify_free(&argop[8]);
1405 				nfs4args_setattr_free(&argop[9]);
1406 			}
1407 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1408 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1409 			    needrecov);
1410 			open_owner_rele(oop);
1411 			if (create_flag || fh_differs) {
1412 				/* rele the makenfs4node */
1413 				VN_RELE(vp);
1414 			}
1415 			if (ncr != NULL) {
1416 				crfree(ncr);
1417 				ncr = NULL;
1418 			}
1419 			if (retry_open == TRUE) {
1420 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1421 				    "nfs4open_otw: retry the open since OPEN "
1422 				    "CONFIRM failed with error %d stat %d",
1423 				    e.error, e.stat));
1424 				if (create_flag && createmode == GUARDED4) {
1425 					NFS4_DEBUG(nfs4_client_recov_debug,
1426 					    (CE_NOTE, "nfs4open_otw: switch "
1427 					    "createmode from GUARDED4 to "
1428 					    "UNCHECKED4"));
1429 					createmode = UNCHECKED4;
1430 				}
1431 				goto recov_retry;
1432 			}
1433 			if (!e.error) {
1434 				if (create_flag && (createmode != EXCLUSIVE4) &&
1435 				    e.stat == NFS4ERR_BADOWNER)
1436 					nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1437 
1438 				e.error = geterrno4(e.stat);
1439 			}
1440 			kmem_free(argop, argoplist_size);
1441 			return (e.error);
1442 		}
1443 	}
1444 
1445 	rp = VTOR4(vp);
1446 
1447 	mutex_enter(&rp->r_statev4_lock);
1448 	if (create_flag)
1449 		rp->created_v4 = 1;
1450 	mutex_exit(&rp->r_statev4_lock);
1451 
1452 	mutex_enter(&oop->oo_lock);
1453 	/* Doesn't matter if 'oo_just_created' already was set as this */
1454 	oop->oo_just_created = NFS4_PERM_CREATED;
1455 	if (oop->oo_cred_otw)
1456 		crfree(oop->oo_cred_otw);
1457 	oop->oo_cred_otw = cred_otw;
1458 	crhold(oop->oo_cred_otw);
1459 	mutex_exit(&oop->oo_lock);
1460 
1461 	/* returns with 'os_sync_lock' held */
1462 	osp = find_or_create_open_stream(oop, rp, &created_osp);
1463 	if (!osp) {
1464 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1465 		    "nfs4open_otw: failed to create an open stream"));
1466 		NFS4_DEBUG(nfs4_seqid_sync, (CE_NOTE, "nfs4open_otw: "
1467 		    "signal our end of use of the open seqid"));
1468 
1469 		nfs4_end_open_seqid_sync(oop);
1470 		open_owner_rele(oop);
1471 		nfs4args_copen_free(open_args);
1472 		if (setgid_flag) {
1473 			nfs4args_verify_free(&argop[8]);
1474 			nfs4args_setattr_free(&argop[9]);
1475 		}
1476 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1477 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1478 		if (create_flag || fh_differs)
1479 			VN_RELE(vp);
1480 		if (ncr != NULL)
1481 			crfree(ncr);
1482 
1483 		kmem_free(argop, argoplist_size);
1484 		return (EINVAL);
1485 
1486 	}
1487 
1488 	osp->open_stateid = op_res->stateid;
1489 
1490 	if (open_flag & FREAD)
1491 		osp->os_share_acc_read++;
1492 	if (open_flag & FWRITE)
1493 		osp->os_share_acc_write++;
1494 	osp->os_share_deny_none++;
1495 
1496 	/*
1497 	 * Need to reset this bitfield for the possible case where we were
1498 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
1499 	 * we could retry the CLOSE, OPENed the file again.
1500 	 */
1501 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
1502 	osp->os_final_close = 0;
1503 	osp->os_force_close = 0;
1504 #ifdef DEBUG
1505 	if (osp->os_failed_reopen)
1506 		NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE, "nfs4open_otw:"
1507 		    " clearing os_failed_reopen for osp %p, cr %p, rp %s",
1508 		    (void *)osp, (void *)cr, rnode4info(rp)));
1509 #endif
1510 	osp->os_failed_reopen = 0;
1511 
1512 	mutex_exit(&osp->os_sync_lock);
1513 
1514 	nfs4_end_open_seqid_sync(oop);
1515 
1516 	if (created_osp && recov_state.rs_sp != NULL) {
1517 		mutex_enter(&recov_state.rs_sp->s_lock);
1518 		nfs4_inc_state_ref_count_nolock(recov_state.rs_sp, VTOMI4(dvp));
1519 		mutex_exit(&recov_state.rs_sp->s_lock);
1520 	}
1521 
1522 	/* get rid of our reference to find oop */
1523 	open_owner_rele(oop);
1524 
1525 	open_stream_rele(osp, rp);
1526 
1527 	/* accept delegation, if any */
1528 	nfs4_delegation_accept(rp, CLAIM_NULL, op_res, garp, cred_otw);
1529 
1530 	nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1531 
1532 	if (createmode == EXCLUSIVE4 &&
1533 	    (in_va->va_mask & ~(AT_GID | AT_SIZE))) {
1534 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw:"
1535 		    " EXCLUSIVE4: sending a SETATTR"));
1536 		/*
1537 		 * If doing an exclusive create, then generate
1538 		 * a SETATTR to set the initial attributes.
1539 		 * Try to set the mtime and the atime to the
1540 		 * server's current time.  It is somewhat
1541 		 * expected that these fields will be used to
1542 		 * store the exclusive create cookie.  If not,
1543 		 * server implementors will need to know that
1544 		 * a SETATTR will follow an exclusive create
1545 		 * and the cookie should be destroyed if
1546 		 * appropriate.
1547 		 *
1548 		 * The AT_GID and AT_SIZE bits are turned off
1549 		 * so that the SETATTR request will not attempt
1550 		 * to process these.  The gid will be set
1551 		 * separately if appropriate.  The size is turned
1552 		 * off because it is assumed that a new file will
1553 		 * be created empty and if the file wasn't empty,
1554 		 * then the exclusive create will have failed
1555 		 * because the file must have existed already.
1556 		 * Therefore, no truncate operation is needed.
1557 		 */
1558 		in_va->va_mask &= ~(AT_GID | AT_SIZE);
1559 		in_va->va_mask |= (AT_MTIME | AT_ATIME);
1560 
1561 		e.error = nfs4setattr(vp, in_va, 0, cr, NULL);
1562 		if (e.error) {
1563 			nfs4_error_t err;
1564 
1565 			/*
1566 			 * Couldn't correct the attributes of
1567 			 * the newly created file and the
1568 			 * attributes are wrong.  Remove the
1569 			 * file and return an error to the
1570 			 * application.
1571 			 */
1572 			/* XXX will this take care of client state ? */
1573 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1574 			    "nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1575 			    " remove file", e.error));
1576 
1577 			/*
1578 			 * The file is currently open so try to close it first.
1579 			 *
1580 			 * If we do not close the file explicitly here then the
1581 			 * VN_RELE() would do an (implicit and asynchronous)
1582 			 * close for us.  But such async close could race with
1583 			 * the nfs4_remove() below.  If the async close is
1584 			 * slower than nfs4_remove() then nfs4_remove()
1585 			 * wouldn't remove the file but rename it to .nfsXXXX
1586 			 * instead.
1587 			 */
1588 			nfs4close_one(vp, NULL, cr, open_flag, NULL, &err,
1589 			    CLOSE_NORM, 0, 0, 0);
1590 			VN_RELE(vp);
1591 			(void) nfs4_remove(dvp, file_name, cr, NULL, 0);
1592 
1593 			/*
1594 			 * Since we've reled the vnode and removed
1595 			 * the file we now need to return the error.
1596 			 * At this point we don't want to update the
1597 			 * dircaches, call nfs4_waitfor_purge_complete
1598 			 * or set vpp to vp so we need to skip these
1599 			 * as well.
1600 			 */
1601 			goto skip_update_dircaches;
1602 		}
1603 	}
1604 
1605 	/*
1606 	 * If we created or found the correct vnode, due to create_flag or
1607 	 * fh_differs being set, then update directory cache attribute, readdir
1608 	 * and dnlc caches.
1609 	 */
1610 	if (create_flag || fh_differs) {
1611 		dirattr_info_t dinfo, *dinfop;
1612 
1613 		/*
1614 		 * Make sure getattr succeeded before using results.
1615 		 * note: op 7 is getattr(dir) for both flavors of
1616 		 * open(create).
1617 		 */
1618 		if (create_flag && res.status == NFS4_OK) {
1619 			dinfo.di_time_call = t;
1620 			dinfo.di_cred = cr;
1621 			dinfo.di_garp =
1622 			    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
1623 			dinfop = &dinfo;
1624 		} else {
1625 			dinfop = NULL;
1626 		}
1627 
1628 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1629 		    dinfop);
1630 	}
1631 
1632 	/*
1633 	 * If the page cache for this file was flushed from actions
1634 	 * above, it was done asynchronously and if that is true,
1635 	 * there is a need to wait here for it to complete.  This must
1636 	 * be done outside of start_fop/end_fop.
1637 	 */
1638 	(void) nfs4_waitfor_purge_complete(vp);
1639 
1640 	/*
1641 	 * It is implicit that we are in the open case (create_flag == 0) since
1642 	 * fh_differs can only be set to a non-zero value in the open case.
1643 	 */
1644 	if (fh_differs != 0 && vpi != NULL)
1645 		VN_RELE(vpi);
1646 
1647 	/*
1648 	 * Be sure to set *vpp to the correct value before returning.
1649 	 */
1650 	*vpp = vp;
1651 
1652 skip_update_dircaches:
1653 
1654 	nfs4args_copen_free(open_args);
1655 	if (setgid_flag) {
1656 		nfs4args_verify_free(&argop[8]);
1657 		nfs4args_setattr_free(&argop[9]);
1658 	}
1659 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1660 
1661 	if (ncr)
1662 		crfree(ncr);
1663 	kmem_free(argop, argoplist_size);
1664 	return (e.error);
1665 }
1666 
1667 /*
1668  * Reopen an open instance.  cf. nfs4open_otw().
1669  *
1670  * Errors are returned by the nfs4_error_t parameter.
1671  * - ep->error contains an errno value or zero.
1672  * - if it is zero, ep->stat is set to an NFS status code, if any.
1673  *   If the file could not be reopened, but the caller should continue, the
1674  *   file is marked dead and no error values are returned.  If the caller
1675  *   should stop recovering open files and start over, either the ep->error
1676  *   value or ep->stat will indicate an error (either something that requires
1677  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1678  *   filehandles) may be handled silently by this routine.
1679  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1680  *   will be started, so the caller should not do it.
1681  *
1682  * Gotos:
1683  * - kill_file : reopen failed in such a fashion to constitute marking the
1684  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1685  *   is for cases where recovery is not possible.
1686  * - failed_reopen : same as above, except that the file has already been
1687  *   marked dead, so no need to do it again.
1688  * - bailout : reopen failed but we are able to recover and retry the reopen -
1689  *   either within this function immediately or via the calling function.
1690  */
1691 
1692 void
1693 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1694     open_claim_type4 claim, bool_t frc_use_claim_previous,
1695     bool_t is_recov)
1696 {
1697 	COMPOUND4args_clnt args;
1698 	COMPOUND4res_clnt res;
1699 	nfs_argop4 argop[4];
1700 	nfs_resop4 *resop;
1701 	OPEN4res *op_res = NULL;
1702 	OPEN4cargs *open_args;
1703 	GETFH4res *gf_res;
1704 	rnode4_t *rp = VTOR4(vp);
1705 	int doqueue = 1;
1706 	cred_t *cr = NULL, *cred_otw = NULL;
1707 	nfs4_open_owner_t *oop = NULL;
1708 	seqid4 seqid;
1709 	nfs4_ga_res_t *garp;
1710 	char fn[MAXNAMELEN];
1711 	nfs4_recov_state_t recov = {NULL, 0};
1712 	nfs4_lost_rqst_t lost_rqst;
1713 	mntinfo4_t *mi = VTOMI4(vp);
1714 	bool_t abort;
1715 	char *failed_msg = "";
1716 	int fh_different;
1717 	hrtime_t t;
1718 	nfs4_bseqid_entry_t *bsep = NULL;
1719 
1720 	ASSERT(nfs4_consistent_type(vp));
1721 	ASSERT(nfs_zone() == mi->mi_zone);
1722 
1723 	nfs4_error_zinit(ep);
1724 
1725 	/* this is the cred used to find the open owner */
1726 	cr = state_to_cred(osp);
1727 	if (cr == NULL) {
1728 		failed_msg = "Couldn't reopen: no cred";
1729 		goto kill_file;
1730 	}
1731 	/* use this cred for OTW operations */
1732 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1733 
1734 top:
1735 	nfs4_error_zinit(ep);
1736 
1737 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1738 		/* File system has been unmounted, quit */
1739 		ep->error = EIO;
1740 		failed_msg = "Couldn't reopen: file system has been unmounted";
1741 		goto kill_file;
1742 	}
1743 
1744 	oop = osp->os_open_owner;
1745 
1746 	ASSERT(oop != NULL);
1747 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1748 		failed_msg = "can't reopen: no open owner";
1749 		goto kill_file;
1750 	}
1751 	open_owner_hold(oop);
1752 
1753 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1754 	if (ep->error) {
1755 		open_owner_rele(oop);
1756 		oop = NULL;
1757 		goto bailout;
1758 	}
1759 
1760 	/*
1761 	 * If the rnode has a delegation and the delegation has been
1762 	 * recovered and the server didn't request a recall and the caller
1763 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1764 	 * recovery) and the rnode hasn't been marked dead, then install
1765 	 * the delegation stateid in the open stream.  Otherwise, proceed
1766 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1767 	 */
1768 	mutex_enter(&rp->r_statev4_lock);
1769 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1770 	    !rp->r_deleg_return_pending &&
1771 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1772 	    !rp->r_deleg_needs_recall &&
1773 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1774 	    !(rp->r_flags & R4RECOVERR)) {
1775 		mutex_enter(&osp->os_sync_lock);
1776 		osp->os_delegation = 1;
1777 		osp->open_stateid = rp->r_deleg_stateid;
1778 		mutex_exit(&osp->os_sync_lock);
1779 		mutex_exit(&rp->r_statev4_lock);
1780 		goto bailout;
1781 	}
1782 	mutex_exit(&rp->r_statev4_lock);
1783 
1784 	/*
1785 	 * If the file failed recovery, just quit.  This failure need not
1786 	 * affect other reopens, so don't return an error.
1787 	 */
1788 	mutex_enter(&rp->r_statelock);
1789 	if (rp->r_flags & R4RECOVERR) {
1790 		mutex_exit(&rp->r_statelock);
1791 		ep->error = 0;
1792 		goto failed_reopen;
1793 	}
1794 	mutex_exit(&rp->r_statelock);
1795 
1796 	/*
1797 	 * argop is empty here
1798 	 *
1799 	 * PUTFH, OPEN, GETATTR
1800 	 */
1801 	args.ctag = TAG_REOPEN;
1802 	args.array_len = 4;
1803 	args.array = argop;
1804 
1805 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1806 	    "nfs4_reopen: file is type %d, id %s",
1807 	    vp->v_type, rnode4info(VTOR4(vp))));
1808 
1809 	argop[0].argop = OP_CPUTFH;
1810 
1811 	if (claim != CLAIM_PREVIOUS) {
1812 		/*
1813 		 * if this is a file mount then
1814 		 * use the mntinfo parentfh
1815 		 */
1816 		argop[0].nfs_argop4_u.opcputfh.sfh =
1817 		    (vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1818 		    VTOSV(vp)->sv_dfh;
1819 	} else {
1820 		/* putfh fh to reopen */
1821 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1822 	}
1823 
1824 	argop[1].argop = OP_COPEN;
1825 	open_args = &argop[1].nfs_argop4_u.opcopen;
1826 	open_args->claim = claim;
1827 
1828 	if (claim == CLAIM_NULL) {
1829 
1830 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1831 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1832 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1833 			    (void *)vp);
1834 			failed_msg = "Couldn't reopen: vtoname failed for "
1835 			    "CLAIM_NULL";
1836 			/* nothing allocated yet */
1837 			goto kill_file;
1838 		}
1839 
1840 		open_args->open_claim4_u.cfile = fn;
1841 	} else if (claim == CLAIM_PREVIOUS) {
1842 
1843 		/*
1844 		 * We have two cases to deal with here:
1845 		 * 1) We're being called to reopen files in order to satisfy
1846 		 *    a lock operation request which requires us to explicitly
1847 		 *    reopen files which were opened under a delegation.  If
1848 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1849 		 *    that case, frc_use_claim_previous is TRUE and we must
1850 		 *    use the rnode's current delegation type (r_deleg_type).
1851 		 * 2) We're reopening files during some form of recovery.
1852 		 *    In this case, frc_use_claim_previous is FALSE and we
1853 		 *    use the delegation type appropriate for recovery
1854 		 *    (r_deleg_needs_recovery).
1855 		 */
1856 		mutex_enter(&rp->r_statev4_lock);
1857 		open_args->open_claim4_u.delegate_type =
1858 		    frc_use_claim_previous ?
1859 		    rp->r_deleg_type :
1860 		    rp->r_deleg_needs_recovery;
1861 		mutex_exit(&rp->r_statev4_lock);
1862 
1863 	} else if (claim == CLAIM_DELEGATE_CUR) {
1864 
1865 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1866 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1867 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1868 			    "with %m", (void *)vp);
1869 			failed_msg = "Couldn't reopen: vtoname failed for "
1870 			    "CLAIM_DELEGATE_CUR";
1871 			/* nothing allocated yet */
1872 			goto kill_file;
1873 		}
1874 
1875 		mutex_enter(&rp->r_statev4_lock);
1876 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1877 		    rp->r_deleg_stateid;
1878 		mutex_exit(&rp->r_statev4_lock);
1879 
1880 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1881 	}
1882 	open_args->opentype = OPEN4_NOCREATE;
1883 	open_args->owner.clientid = mi2clientid(mi);
1884 	open_args->owner.owner_len = sizeof (oop->oo_name);
1885 	open_args->owner.owner_val =
1886 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1887 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1888 	    open_args->owner.owner_len);
1889 	open_args->share_access = 0;
1890 	open_args->share_deny = 0;
1891 
1892 	mutex_enter(&osp->os_sync_lock);
1893 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1894 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1895 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1896 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1897 	    osp->os_share_acc_write, osp->os_open_ref_count,
1898 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1899 
1900 	if (osp->os_share_acc_read || osp->os_mmap_read)
1901 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1902 	if (osp->os_share_acc_write || osp->os_mmap_write)
1903 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1904 	if (osp->os_share_deny_read)
1905 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1906 	if (osp->os_share_deny_write)
1907 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1908 	mutex_exit(&osp->os_sync_lock);
1909 
1910 	seqid = nfs4_get_open_seqid(oop) + 1;
1911 	open_args->seqid = seqid;
1912 
1913 	/* Construct the getfh part of the compound */
1914 	argop[2].argop = OP_GETFH;
1915 
1916 	/* Construct the getattr part of the compound */
1917 	argop[3].argop = OP_GETATTR;
1918 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1919 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1920 
1921 	t = gethrtime();
1922 
1923 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1924 
1925 	if (ep->error) {
1926 		if (!is_recov && !frc_use_claim_previous &&
1927 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1928 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1929 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1930 			    cred_otw, vp, NULL, open_args);
1931 			abort = nfs4_start_recovery(ep,
1932 			    VTOMI4(vp), vp, NULL, NULL,
1933 			    lost_rqst.lr_op == OP_OPEN ?
1934 			    &lost_rqst : NULL, OP_OPEN, NULL, NULL, NULL);
1935 			nfs4args_copen_free(open_args);
1936 			goto bailout;
1937 		}
1938 
1939 		nfs4args_copen_free(open_args);
1940 
1941 		if (ep->error == EACCES && cred_otw != cr) {
1942 			crfree(cred_otw);
1943 			cred_otw = cr;
1944 			crhold(cred_otw);
1945 			nfs4_end_open_seqid_sync(oop);
1946 			open_owner_rele(oop);
1947 			oop = NULL;
1948 			goto top;
1949 		}
1950 		if (ep->error == ETIMEDOUT)
1951 			goto bailout;
1952 		failed_msg = "Couldn't reopen: rpc error";
1953 		goto kill_file;
1954 	}
1955 
1956 	if (nfs4_need_to_bump_seqid(&res))
1957 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1958 
1959 	switch (res.status) {
1960 	case NFS4_OK:
1961 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1962 			mutex_enter(&rp->r_statelock);
1963 			rp->r_delay_interval = 0;
1964 			mutex_exit(&rp->r_statelock);
1965 		}
1966 		break;
1967 	case NFS4ERR_BAD_SEQID:
1968 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1969 		    args.ctag, open_args->seqid);
1970 
1971 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1972 		    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1973 		    NULL, OP_OPEN, bsep, NULL, NULL);
1974 
1975 		nfs4args_copen_free(open_args);
1976 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1977 		nfs4_end_open_seqid_sync(oop);
1978 		open_owner_rele(oop);
1979 		oop = NULL;
1980 		kmem_free(bsep, sizeof (*bsep));
1981 
1982 		goto kill_file;
1983 	case NFS4ERR_NO_GRACE:
1984 		nfs4args_copen_free(open_args);
1985 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1986 		nfs4_end_open_seqid_sync(oop);
1987 		open_owner_rele(oop);
1988 		oop = NULL;
1989 		if (claim == CLAIM_PREVIOUS) {
1990 			/*
1991 			 * Retry as a plain open. We don't need to worry about
1992 			 * checking the changeinfo: it is acceptable for a
1993 			 * client to re-open a file and continue processing
1994 			 * (in the absence of locks).
1995 			 */
1996 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1997 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1998 			    "will retry as CLAIM_NULL"));
1999 			claim = CLAIM_NULL;
2000 			nfs4_mi_kstat_inc_no_grace(mi);
2001 			goto top;
2002 		}
2003 		failed_msg =
2004 		    "Couldn't reopen: tried reclaim outside grace period. ";
2005 		goto kill_file;
2006 	case NFS4ERR_GRACE:
2007 		nfs4_set_grace_wait(mi);
2008 		nfs4args_copen_free(open_args);
2009 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2010 		nfs4_end_open_seqid_sync(oop);
2011 		open_owner_rele(oop);
2012 		oop = NULL;
2013 		ep->error = nfs4_wait_for_grace(mi, &recov);
2014 		if (ep->error != 0)
2015 			goto bailout;
2016 		goto top;
2017 	case NFS4ERR_DELAY:
2018 		nfs4_set_delay_wait(vp);
2019 		nfs4args_copen_free(open_args);
2020 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2021 		nfs4_end_open_seqid_sync(oop);
2022 		open_owner_rele(oop);
2023 		oop = NULL;
2024 		ep->error = nfs4_wait_for_delay(vp, &recov);
2025 		nfs4_mi_kstat_inc_delay(mi);
2026 		if (ep->error != 0)
2027 			goto bailout;
2028 		goto top;
2029 	case NFS4ERR_FHEXPIRED:
2030 		/* recover filehandle and retry */
2031 		abort = nfs4_start_recovery(ep,
2032 		    mi, vp, NULL, NULL, NULL, OP_OPEN, NULL, NULL, NULL);
2033 		nfs4args_copen_free(open_args);
2034 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2035 		nfs4_end_open_seqid_sync(oop);
2036 		open_owner_rele(oop);
2037 		oop = NULL;
2038 		if (abort == FALSE)
2039 			goto top;
2040 		failed_msg = "Couldn't reopen: recovery aborted";
2041 		goto kill_file;
2042 	case NFS4ERR_RESOURCE:
2043 	case NFS4ERR_STALE_CLIENTID:
2044 	case NFS4ERR_WRONGSEC:
2045 	case NFS4ERR_EXPIRED:
2046 		/*
2047 		 * Do not mark the file dead and let the calling
2048 		 * function initiate recovery.
2049 		 */
2050 		nfs4args_copen_free(open_args);
2051 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2052 		nfs4_end_open_seqid_sync(oop);
2053 		open_owner_rele(oop);
2054 		oop = NULL;
2055 		goto bailout;
2056 	case NFS4ERR_ACCESS:
2057 		if (cred_otw != cr) {
2058 			crfree(cred_otw);
2059 			cred_otw = cr;
2060 			crhold(cred_otw);
2061 			nfs4args_copen_free(open_args);
2062 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2063 			nfs4_end_open_seqid_sync(oop);
2064 			open_owner_rele(oop);
2065 			oop = NULL;
2066 			goto top;
2067 		}
2068 		/* fall through */
2069 	default:
2070 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2071 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2072 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2073 		    rnode4info(VTOR4(vp))));
2074 		failed_msg = "Couldn't reopen: NFSv4 error";
2075 		nfs4args_copen_free(open_args);
2076 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2077 		goto kill_file;
2078 	}
2079 
2080 	resop = &res.array[1];  /* open res */
2081 	op_res = &resop->nfs_resop4_u.opopen;
2082 
2083 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2084 
2085 	/*
2086 	 * Check if the path we reopened really is the same
2087 	 * file. We could end up in a situation where the file
2088 	 * was removed and a new file created with the same name.
2089 	 */
2090 	resop = &res.array[2];
2091 	gf_res = &resop->nfs_resop4_u.opgetfh;
2092 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2093 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2094 	if (fh_different) {
2095 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2096 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2097 			/* Oops, we don't have the same file */
2098 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2099 				failed_msg = "Couldn't reopen: Persistent "
2100 				    "file handle changed";
2101 			else
2102 				failed_msg = "Couldn't reopen: Volatile "
2103 				    "(no expire on open) file handle changed";
2104 
2105 			nfs4args_copen_free(open_args);
2106 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2107 			nfs_rw_exit(&mi->mi_fh_lock);
2108 			goto kill_file;
2109 
2110 		} else {
2111 			/*
2112 			 * We have volatile file handles that don't compare.
2113 			 * If the fids are the same then we assume that the
2114 			 * file handle expired but the rnode still refers to
2115 			 * the same file object.
2116 			 *
2117 			 * First check that we have fids or not.
2118 			 * If we don't we have a dumb server so we will
2119 			 * just assume every thing is ok for now.
2120 			 */
2121 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2122 			    rp->r_attr.va_mask & AT_NODEID &&
2123 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2124 				/*
2125 				 * We have fids, but they don't
2126 				 * compare. So kill the file.
2127 				 */
2128 				failed_msg =
2129 				    "Couldn't reopen: file handle changed"
2130 				    " due to mismatched fids";
2131 				nfs4args_copen_free(open_args);
2132 				(void) xdr_free(xdr_COMPOUND4res_clnt,
2133 				    (caddr_t)&res);
2134 				nfs_rw_exit(&mi->mi_fh_lock);
2135 				goto kill_file;
2136 			} else {
2137 				/*
2138 				 * We have volatile file handles that refers
2139 				 * to the same file (at least they have the
2140 				 * same fid) or we don't have fids so we
2141 				 * can't tell. :(. We'll be a kind and accepting
2142 				 * client so we'll update the rnode's file
2143 				 * handle with the otw handle.
2144 				 *
2145 				 * We need to drop mi->mi_fh_lock since
2146 				 * sh4_update acquires it. Since there is
2147 				 * only one recovery thread there is no
2148 				 * race.
2149 				 */
2150 				nfs_rw_exit(&mi->mi_fh_lock);
2151 				sfh4_update(rp->r_fh, &gf_res->object);
2152 			}
2153 		}
2154 	} else {
2155 		nfs_rw_exit(&mi->mi_fh_lock);
2156 	}
2157 
2158 	ASSERT(nfs4_consistent_type(vp));
2159 
2160 	/*
2161 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2162 	 * over.  Presumably if there is a persistent error it will show up
2163 	 * when we resend the OPEN.
2164 	 */
2165 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2166 		bool_t retry_open = FALSE;
2167 
2168 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2169 		    cred_otw, is_recov, &retry_open,
2170 		    oop, FALSE, ep, NULL);
2171 		if (ep->error || ep->stat) {
2172 			nfs4args_copen_free(open_args);
2173 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2174 			nfs4_end_open_seqid_sync(oop);
2175 			open_owner_rele(oop);
2176 			oop = NULL;
2177 			goto top;
2178 		}
2179 	}
2180 
2181 	mutex_enter(&osp->os_sync_lock);
2182 	osp->open_stateid = op_res->stateid;
2183 	osp->os_delegation = 0;
2184 	/*
2185 	 * Need to reset this bitfield for the possible case where we were
2186 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2187 	 * we could retry the CLOSE, OPENed the file again.
2188 	 */
2189 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2190 	osp->os_final_close = 0;
2191 	osp->os_force_close = 0;
2192 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2193 		osp->os_dc_openacc = open_args->share_access;
2194 	mutex_exit(&osp->os_sync_lock);
2195 
2196 	nfs4_end_open_seqid_sync(oop);
2197 
2198 	/* accept delegation, if any */
2199 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2200 
2201 	nfs4args_copen_free(open_args);
2202 
2203 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2204 
2205 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2206 
2207 	ASSERT(nfs4_consistent_type(vp));
2208 
2209 	open_owner_rele(oop);
2210 	crfree(cr);
2211 	crfree(cred_otw);
2212 	return;
2213 
2214 kill_file:
2215 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2216 failed_reopen:
2217 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2218 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2219 	    (void *)osp, (void *)cr, rnode4info(rp)));
2220 	mutex_enter(&osp->os_sync_lock);
2221 	osp->os_failed_reopen = 1;
2222 	mutex_exit(&osp->os_sync_lock);
2223 bailout:
2224 	if (oop != NULL) {
2225 		nfs4_end_open_seqid_sync(oop);
2226 		open_owner_rele(oop);
2227 	}
2228 	if (cr != NULL)
2229 		crfree(cr);
2230 	if (cred_otw != NULL)
2231 		crfree(cred_otw);
2232 }
2233 
2234 /* for . and .. OPENs */
2235 /* ARGSUSED */
2236 static int
2237 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2238 {
2239 	rnode4_t *rp;
2240 	nfs4_ga_res_t gar;
2241 
2242 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2243 
2244 	/*
2245 	 * If close-to-open consistency checking is turned off or
2246 	 * if there is no cached data, we can avoid
2247 	 * the over the wire getattr.  Otherwise, force a
2248 	 * call to the server to get fresh attributes and to
2249 	 * check caches. This is required for close-to-open
2250 	 * consistency.
2251 	 */
2252 	rp = VTOR4(*vpp);
2253 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2254 	    (rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2255 		return (0);
2256 
2257 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2258 }
2259 
2260 /*
2261  * CLOSE a file
2262  */
2263 /* ARGSUSED */
2264 static int
2265 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
2266     caller_context_t *ct)
2267 {
2268 	rnode4_t	*rp;
2269 	int		 error = 0;
2270 	int		 r_error = 0;
2271 	int		 n4error = 0;
2272 	nfs4_error_t	 e = { 0, NFS4_OK, RPC_SUCCESS };
2273 
2274 	/*
2275 	 * Remove client state for this (lockowner, file) pair.
2276 	 * Issue otw v4 call to have the server do the same.
2277 	 */
2278 
2279 	rp = VTOR4(vp);
2280 
2281 	/*
2282 	 * zone_enter(2) prevents processes from changing zones with NFS files
2283 	 * open; if we happen to get here from the wrong zone we can't do
2284 	 * anything over the wire.
2285 	 */
2286 	if (VTOMI4(vp)->mi_zone != nfs_zone()) {
2287 		/*
2288 		 * We could attempt to clean up locks, except we're sure
2289 		 * that the current process didn't acquire any locks on
2290 		 * the file: any attempt to lock a file belong to another zone
2291 		 * will fail, and one can't lock an NFS file and then change
2292 		 * zones, as that fails too.
2293 		 *
2294 		 * Returning an error here is the sane thing to do.  A
2295 		 * subsequent call to VN_RELE() which translates to a
2296 		 * nfs4_inactive() will clean up state: if the zone of the
2297 		 * vnode's origin is still alive and kicking, the inactive
2298 		 * thread will handle the request (from the correct zone), and
2299 		 * everything (minus the OTW close call) should be OK.  If the
2300 		 * zone is going away nfs4_async_inactive() will throw away
2301 		 * delegations, open streams and cached pages inline.
2302 		 */
2303 		return (EIO);
2304 	}
2305 
2306 	/*
2307 	 * If we are using local locking for this filesystem, then
2308 	 * release all of the SYSV style record locks.  Otherwise,
2309 	 * we are doing network locking and we need to release all
2310 	 * of the network locks.  All of the locks held by this
2311 	 * process on this file are released no matter what the
2312 	 * incoming reference count is.
2313 	 */
2314 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK) {
2315 		cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
2316 		cleanshares(vp, ttoproc(curthread)->p_pid);
2317 	} else
2318 		e.error = nfs4_lockrelease(vp, flag, offset, cr);
2319 
2320 	if (e.error) {
2321 		struct lm_sysid *lmsid;
2322 		lmsid = nfs4_find_sysid(VTOMI4(vp));
2323 		if (lmsid == NULL) {
2324 			DTRACE_PROBE2(unknown__sysid, int, e.error,
2325 			    vnode_t *, vp);
2326 		} else {
2327 			cleanlocks(vp, ttoproc(curthread)->p_pid,
2328 			    (lm_sysidt(lmsid) | LM_SYSID_CLIENT));
2329 
2330 			lm_rel_sysid(lmsid);
2331 		}
2332 		return (e.error);
2333 	}
2334 
2335 	if (count > 1)
2336 		return (0);
2337 
2338 	/*
2339 	 * If the file has been `unlinked', then purge the
2340 	 * DNLC so that this vnode will get reycled quicker
2341 	 * and the .nfs* file on the server will get removed.
2342 	 */
2343 	if (rp->r_unldvp != NULL)
2344 		dnlc_purge_vp(vp);
2345 
2346 	/*
2347 	 * If the file was open for write and there are pages,
2348 	 * do a synchronous flush and commit of all of the
2349 	 * dirty and uncommitted pages.
2350 	 */
2351 	ASSERT(!e.error);
2352 	if ((flag & FWRITE) && nfs4_has_pages(vp))
2353 		error = nfs4_putpage_commit(vp, 0, 0, cr);
2354 
2355 	mutex_enter(&rp->r_statelock);
2356 	r_error = rp->r_error;
2357 	rp->r_error = 0;
2358 	mutex_exit(&rp->r_statelock);
2359 
2360 	/*
2361 	 * If this file type is one for which no explicit 'open' was
2362 	 * done, then bail now (ie. no need for protocol 'close'). If
2363 	 * there was an error w/the vm subsystem, return _that_ error,
2364 	 * otherwise, return any errors that may've been reported via
2365 	 * the rnode.
2366 	 */
2367 	if (vp->v_type != VREG)
2368 		return (error ? error : r_error);
2369 
2370 	/*
2371 	 * The sync putpage commit may have failed above, but since
2372 	 * we're working w/a regular file, we need to do the protocol
2373 	 * 'close' (nfs4close_one will figure out if an otw close is
2374 	 * needed or not). Report any errors _after_ doing the protocol
2375 	 * 'close'.
2376 	 */
2377 	nfs4close_one(vp, NULL, cr, flag, NULL, &e, CLOSE_NORM, 0, 0, 0);
2378 	n4error = e.error ? e.error : geterrno4(e.stat);
2379 
2380 	/*
2381 	 * Error reporting prio (Hi -> Lo)
2382 	 *
2383 	 *   i) nfs4_putpage_commit (error)
2384 	 *  ii) rnode's (r_error)
2385 	 * iii) nfs4close_one (n4error)
2386 	 */
2387 	return (error ? error : (r_error ? r_error : n4error));
2388 }
2389 
2390 /*
2391  * Initialize *lost_rqstp.
2392  */
2393 
2394 static void
2395 nfs4close_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
2396     nfs4_open_owner_t *oop, nfs4_open_stream_t *osp, cred_t *cr,
2397     vnode_t *vp)
2398 {
2399 	if (error != ETIMEDOUT && error != EINTR &&
2400 	    !NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
2401 		lost_rqstp->lr_op = 0;
2402 		return;
2403 	}
2404 
2405 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
2406 	    "nfs4close_save_lost_rqst: error %d", error));
2407 
2408 	lost_rqstp->lr_op = OP_CLOSE;
2409 	/*
2410 	 * The vp is held and rele'd via the recovery code.
2411 	 * See nfs4_save_lost_rqst.
2412 	 */
2413 	lost_rqstp->lr_vp = vp;
2414 	lost_rqstp->lr_dvp = NULL;
2415 	lost_rqstp->lr_oop = oop;
2416 	lost_rqstp->lr_osp = osp;
2417 	ASSERT(osp != NULL);
2418 	ASSERT(mutex_owned(&osp->os_sync_lock));
2419 	osp->os_pending_close = 1;
2420 	lost_rqstp->lr_lop = NULL;
2421 	lost_rqstp->lr_cr = cr;
2422 	lost_rqstp->lr_flk = NULL;
2423 	lost_rqstp->lr_putfirst = FALSE;
2424 }
2425 
2426 /*
2427  * Assumes you already have the open seqid sync grabbed as well as the
2428  * 'os_sync_lock'.  Note: this will release the open seqid sync and
2429  * 'os_sync_lock' if client recovery starts.  Calling functions have to
2430  * be prepared to handle this.
2431  *
2432  * 'recov' is returned as 1 if the CLOSE operation detected client recovery
2433  * was needed and was started, and that the calling function should retry
2434  * this function; otherwise it is returned as 0.
2435  *
2436  * Errors are returned via the nfs4_error_t parameter.
2437  */
2438 static void
2439 nfs4close_otw(rnode4_t *rp, cred_t *cred_otw, nfs4_open_owner_t *oop,
2440     nfs4_open_stream_t *osp, int *recov, int *did_start_seqid_syncp,
2441     nfs4_close_type_t close_type, nfs4_error_t *ep, int *have_sync_lockp)
2442 {
2443 	COMPOUND4args_clnt args;
2444 	COMPOUND4res_clnt res;
2445 	CLOSE4args *close_args;
2446 	nfs_resop4 *resop;
2447 	nfs_argop4 argop[3];
2448 	int doqueue = 1;
2449 	mntinfo4_t *mi;
2450 	seqid4 seqid;
2451 	vnode_t *vp;
2452 	bool_t needrecov = FALSE;
2453 	nfs4_lost_rqst_t lost_rqst;
2454 	hrtime_t t;
2455 
2456 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
2457 
2458 	ASSERT(MUTEX_HELD(&osp->os_sync_lock));
2459 
2460 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw"));
2461 
2462 	/* Only set this to 1 if recovery is started */
2463 	*recov = 0;
2464 
2465 	/* do the OTW call to close the file */
2466 
2467 	if (close_type == CLOSE_RESEND)
2468 		args.ctag = TAG_CLOSE_LOST;
2469 	else if (close_type == CLOSE_AFTER_RESEND)
2470 		args.ctag = TAG_CLOSE_UNDO;
2471 	else
2472 		args.ctag = TAG_CLOSE;
2473 
2474 	args.array_len = 3;
2475 	args.array = argop;
2476 
2477 	vp = RTOV4(rp);
2478 
2479 	mi = VTOMI4(vp);
2480 
2481 	/* putfh target fh */
2482 	argop[0].argop = OP_CPUTFH;
2483 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
2484 
2485 	argop[1].argop = OP_GETATTR;
2486 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
2487 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
2488 
2489 	argop[2].argop = OP_CLOSE;
2490 	close_args = &argop[2].nfs_argop4_u.opclose;
2491 
2492 	seqid = nfs4_get_open_seqid(oop) + 1;
2493 
2494 	close_args->seqid = seqid;
2495 	close_args->open_stateid = osp->open_stateid;
2496 
2497 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
2498 	    "nfs4close_otw: %s call, rp %s", needrecov ? "recov" : "first",
2499 	    rnode4info(rp)));
2500 
2501 	t = gethrtime();
2502 
2503 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
2504 
2505 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
2506 		nfs4_set_open_seqid(seqid, oop, args.ctag);
2507 	}
2508 
2509 	needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
2510 	if (ep->error && !needrecov) {
2511 		/*
2512 		 * if there was an error and no recovery is to be done
2513 		 * then then set up the file to flush its cache if
2514 		 * needed for the next caller.
2515 		 */
2516 		mutex_enter(&rp->r_statelock);
2517 		PURGE_ATTRCACHE4_LOCKED(rp);
2518 		rp->r_flags &= ~R4WRITEMODIFIED;
2519 		mutex_exit(&rp->r_statelock);
2520 		return;
2521 	}
2522 
2523 	if (needrecov) {
2524 		bool_t abort;
2525 		nfs4_bseqid_entry_t *bsep = NULL;
2526 
2527 		if (close_type != CLOSE_RESEND)
2528 			nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
2529 			    osp, cred_otw, vp);
2530 
2531 		if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
2532 			bsep = nfs4_create_bseqid_entry(oop, NULL, vp,
2533 			    0, args.ctag, close_args->seqid);
2534 
2535 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
2536 		    "nfs4close_otw: initiating recovery. error %d "
2537 		    "res.status %d", ep->error, res.status));
2538 
2539 		/*
2540 		 * Drop the 'os_sync_lock' here so we don't hit
2541 		 * a potential recursive mutex_enter via an
2542 		 * 'open_stream_hold()'.
2543 		 */
2544 		mutex_exit(&osp->os_sync_lock);
2545 		*have_sync_lockp = 0;
2546 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
2547 		    (close_type != CLOSE_RESEND &&
2548 		    lost_rqst.lr_op == OP_CLOSE) ? &lost_rqst : NULL,
2549 		    OP_CLOSE, bsep, NULL, NULL);
2550 
2551 		/* drop open seq sync, and let the calling function regrab it */
2552 		nfs4_end_open_seqid_sync(oop);
2553 		*did_start_seqid_syncp = 0;
2554 
2555 		if (bsep)
2556 			kmem_free(bsep, sizeof (*bsep));
2557 		/*
2558 		 * For signals, the caller wants to quit, so don't say to
2559 		 * retry.  For forced unmount, if it's a user thread, it
2560 		 * wants to quit.  If it's a recovery thread, the retry
2561 		 * will happen higher-up on the call stack.  Either way,
2562 		 * don't say to retry.
2563 		 */
2564 		if (abort == FALSE && ep->error != EINTR &&
2565 		    !NFS4_FRC_UNMT_ERR(ep->error, mi->mi_vfsp) &&
2566 		    close_type != CLOSE_RESEND &&
2567 		    close_type != CLOSE_AFTER_RESEND)
2568 			*recov = 1;
2569 		else
2570 			*recov = 0;
2571 
2572 		if (!ep->error)
2573 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2574 		return;
2575 	}
2576 
2577 	if (res.status) {
2578 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2579 		return;
2580 	}
2581 
2582 	mutex_enter(&rp->r_statev4_lock);
2583 	rp->created_v4 = 0;
2584 	mutex_exit(&rp->r_statev4_lock);
2585 
2586 	resop = &res.array[2];
2587 	osp->open_stateid = resop->nfs_resop4_u.opclose.open_stateid;
2588 	osp->os_valid = 0;
2589 
2590 	/*
2591 	 * This removes the reference obtained at OPEN; ie, when the
2592 	 * open stream structure was created.
2593 	 *
2594 	 * We don't have to worry about calling 'open_stream_rele'
2595 	 * since we our currently holding a reference to the open
2596 	 * stream which means the count cannot go to 0 with this
2597 	 * decrement.
2598 	 */
2599 	ASSERT(osp->os_ref_count >= 2);
2600 	osp->os_ref_count--;
2601 
2602 	if (ep->error == 0) {
2603 		mutex_exit(&osp->os_sync_lock);
2604 		*have_sync_lockp = 0;
2605 
2606 		nfs4_attr_cache(vp,
2607 		    &res.array[1].nfs_resop4_u.opgetattr.ga_res,
2608 		    t, cred_otw, TRUE, NULL);
2609 	}
2610 
2611 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw:"
2612 	    " returning %d", ep->error));
2613 
2614 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2615 }
2616 
2617 /* ARGSUSED */
2618 static int
2619 nfs4_read(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2620     caller_context_t *ct)
2621 {
2622 	rnode4_t *rp;
2623 	u_offset_t off;
2624 	offset_t diff;
2625 	uint_t on;
2626 	uint_t n;
2627 	caddr_t base;
2628 	uint_t flags;
2629 	int error;
2630 	mntinfo4_t *mi;
2631 
2632 	rp = VTOR4(vp);
2633 
2634 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2635 
2636 	if (IS_SHADOW(vp, rp))
2637 		vp = RTOV4(rp);
2638 
2639 	if (vp->v_type != VREG)
2640 		return (EISDIR);
2641 
2642 	mi = VTOMI4(vp);
2643 
2644 	if (nfs_zone() != mi->mi_zone)
2645 		return (EIO);
2646 
2647 	if (uiop->uio_resid == 0)
2648 		return (0);
2649 
2650 	if (uiop->uio_loffset < 0 || uiop->uio_loffset + uiop->uio_resid < 0)
2651 		return (EINVAL);
2652 
2653 	mutex_enter(&rp->r_statelock);
2654 	if (rp->r_flags & R4RECOVERRP)
2655 		error = (rp->r_error ? rp->r_error : EIO);
2656 	else
2657 		error = 0;
2658 	mutex_exit(&rp->r_statelock);
2659 	if (error)
2660 		return (error);
2661 
2662 	/*
2663 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2664 	 * using client-side direct I/O and the file is not mmap'd and
2665 	 * there are no cached pages.
2666 	 */
2667 	if ((vp->v_flag & VNOCACHE) ||
2668 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2669 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2670 		size_t resid = 0;
2671 
2672 		return (nfs4read(vp, NULL, uiop->uio_loffset,
2673 		    uiop->uio_resid, &resid, cr, FALSE, uiop));
2674 	}
2675 
2676 	error = 0;
2677 
2678 	do {
2679 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2680 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2681 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2682 
2683 		if (error = nfs4_validate_caches(vp, cr))
2684 			break;
2685 
2686 		mutex_enter(&rp->r_statelock);
2687 		while (rp->r_flags & R4INCACHEPURGE) {
2688 			if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2689 				mutex_exit(&rp->r_statelock);
2690 				return (EINTR);
2691 			}
2692 		}
2693 		diff = rp->r_size - uiop->uio_loffset;
2694 		mutex_exit(&rp->r_statelock);
2695 		if (diff <= 0)
2696 			break;
2697 		if (diff < n)
2698 			n = (uint_t)diff;
2699 
2700 		if (vpm_enable) {
2701 			/*
2702 			 * Copy data.
2703 			 */
2704 			error = vpm_data_copy(vp, off + on, n, uiop,
2705 			    1, NULL, 0, S_READ);
2706 		} else {
2707 			base = segmap_getmapflt(segkmap, vp, off + on, n, 1,
2708 			    S_READ);
2709 
2710 			error = uiomove(base + on, n, UIO_READ, uiop);
2711 		}
2712 
2713 		if (!error) {
2714 			/*
2715 			 * If read a whole block or read to eof,
2716 			 * won't need this buffer again soon.
2717 			 */
2718 			mutex_enter(&rp->r_statelock);
2719 			if (n + on == MAXBSIZE ||
2720 			    uiop->uio_loffset == rp->r_size)
2721 				flags = SM_DONTNEED;
2722 			else
2723 				flags = 0;
2724 			mutex_exit(&rp->r_statelock);
2725 			if (vpm_enable) {
2726 				error = vpm_sync_pages(vp, off, n, flags);
2727 			} else {
2728 				error = segmap_release(segkmap, base, flags);
2729 			}
2730 		} else {
2731 			if (vpm_enable) {
2732 				(void) vpm_sync_pages(vp, off, n, 0);
2733 			} else {
2734 				(void) segmap_release(segkmap, base, 0);
2735 			}
2736 		}
2737 	} while (!error && uiop->uio_resid > 0);
2738 
2739 	return (error);
2740 }
2741 
2742 /* ARGSUSED */
2743 static int
2744 nfs4_write(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2745     caller_context_t *ct)
2746 {
2747 	rlim64_t limit = uiop->uio_llimit;
2748 	rnode4_t *rp;
2749 	u_offset_t off;
2750 	caddr_t base;
2751 	uint_t flags;
2752 	int remainder;
2753 	size_t n;
2754 	int on;
2755 	int error;
2756 	int resid;
2757 	u_offset_t offset;
2758 	mntinfo4_t *mi;
2759 	uint_t bsize;
2760 
2761 	rp = VTOR4(vp);
2762 
2763 	if (IS_SHADOW(vp, rp))
2764 		vp = RTOV4(rp);
2765 
2766 	if (vp->v_type != VREG)
2767 		return (EISDIR);
2768 
2769 	mi = VTOMI4(vp);
2770 
2771 	if (nfs_zone() != mi->mi_zone)
2772 		return (EIO);
2773 
2774 	if (uiop->uio_resid == 0)
2775 		return (0);
2776 
2777 	mutex_enter(&rp->r_statelock);
2778 	if (rp->r_flags & R4RECOVERRP)
2779 		error = (rp->r_error ? rp->r_error : EIO);
2780 	else
2781 		error = 0;
2782 	mutex_exit(&rp->r_statelock);
2783 	if (error)
2784 		return (error);
2785 
2786 	if (ioflag & FAPPEND) {
2787 		struct vattr va;
2788 
2789 		/*
2790 		 * Must serialize if appending.
2791 		 */
2792 		if (nfs_rw_lock_held(&rp->r_rwlock, RW_READER)) {
2793 			nfs_rw_exit(&rp->r_rwlock);
2794 			if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER,
2795 			    INTR4(vp)))
2796 				return (EINTR);
2797 		}
2798 
2799 		va.va_mask = AT_SIZE;
2800 		error = nfs4getattr(vp, &va, cr);
2801 		if (error)
2802 			return (error);
2803 		uiop->uio_loffset = va.va_size;
2804 	}
2805 
2806 	offset = uiop->uio_loffset + uiop->uio_resid;
2807 
2808 	if (uiop->uio_loffset < (offset_t)0 || offset < 0)
2809 		return (EINVAL);
2810 
2811 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
2812 		limit = MAXOFFSET_T;
2813 
2814 	/*
2815 	 * Check to make sure that the process will not exceed
2816 	 * its limit on file size.  It is okay to write up to
2817 	 * the limit, but not beyond.  Thus, the write which
2818 	 * reaches the limit will be short and the next write
2819 	 * will return an error.
2820 	 */
2821 	remainder = 0;
2822 	if (offset > uiop->uio_llimit) {
2823 		remainder = offset - uiop->uio_llimit;
2824 		uiop->uio_resid = uiop->uio_llimit - uiop->uio_loffset;
2825 		if (uiop->uio_resid <= 0) {
2826 			proc_t *p = ttoproc(curthread);
2827 
2828 			uiop->uio_resid += remainder;
2829 			mutex_enter(&p->p_lock);
2830 			(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE],
2831 			    p->p_rctls, p, RCA_UNSAFE_SIGINFO);
2832 			mutex_exit(&p->p_lock);
2833 			return (EFBIG);
2834 		}
2835 	}
2836 
2837 	/* update the change attribute, if we have a write delegation */
2838 
2839 	mutex_enter(&rp->r_statev4_lock);
2840 	if (rp->r_deleg_type == OPEN_DELEGATE_WRITE)
2841 		rp->r_deleg_change++;
2842 
2843 	mutex_exit(&rp->r_statev4_lock);
2844 
2845 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, INTR4(vp)))
2846 		return (EINTR);
2847 
2848 	/*
2849 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2850 	 * using client-side direct I/O and the file is not mmap'd and
2851 	 * there are no cached pages.
2852 	 */
2853 	if ((vp->v_flag & VNOCACHE) ||
2854 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2855 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2856 		size_t bufsize;
2857 		int count;
2858 		u_offset_t org_offset;
2859 		stable_how4 stab_comm;
2860 nfs4_fwrite:
2861 		if (rp->r_flags & R4STALE) {
2862 			resid = uiop->uio_resid;
2863 			offset = uiop->uio_loffset;
2864 			error = rp->r_error;
2865 			/*
2866 			 * A close may have cleared r_error, if so,
2867 			 * propagate ESTALE error return properly
2868 			 */
2869 			if (error == 0)
2870 				error = ESTALE;
2871 			goto bottom;
2872 		}
2873 
2874 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2875 		base = kmem_alloc(bufsize, KM_SLEEP);
2876 		do {
2877 			if (ioflag & FDSYNC)
2878 				stab_comm = DATA_SYNC4;
2879 			else
2880 				stab_comm = FILE_SYNC4;
2881 			resid = uiop->uio_resid;
2882 			offset = uiop->uio_loffset;
2883 			count = MIN(uiop->uio_resid, bufsize);
2884 			org_offset = uiop->uio_loffset;
2885 			error = uiomove(base, count, UIO_WRITE, uiop);
2886 			if (!error) {
2887 				error = nfs4write(vp, base, org_offset,
2888 				    count, cr, &stab_comm);
2889 				if (!error) {
2890 					mutex_enter(&rp->r_statelock);
2891 					if (rp->r_size < uiop->uio_loffset)
2892 						rp->r_size = uiop->uio_loffset;
2893 					mutex_exit(&rp->r_statelock);
2894 				}
2895 			}
2896 		} while (!error && uiop->uio_resid > 0);
2897 		kmem_free(base, bufsize);
2898 		goto bottom;
2899 	}
2900 
2901 	bsize = vp->v_vfsp->vfs_bsize;
2902 
2903 	do {
2904 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2905 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2906 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2907 
2908 		resid = uiop->uio_resid;
2909 		offset = uiop->uio_loffset;
2910 
2911 		if (rp->r_flags & R4STALE) {
2912 			error = rp->r_error;
2913 			/*
2914 			 * A close may have cleared r_error, if so,
2915 			 * propagate ESTALE error return properly
2916 			 */
2917 			if (error == 0)
2918 				error = ESTALE;
2919 			break;
2920 		}
2921 
2922 		/*
2923 		 * Don't create dirty pages faster than they
2924 		 * can be cleaned so that the system doesn't
2925 		 * get imbalanced.  If the async queue is
2926 		 * maxed out, then wait for it to drain before
2927 		 * creating more dirty pages.  Also, wait for
2928 		 * any threads doing pagewalks in the vop_getattr
2929 		 * entry points so that they don't block for
2930 		 * long periods.
2931 		 */
2932 		mutex_enter(&rp->r_statelock);
2933 		while ((mi->mi_max_threads != 0 &&
2934 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2935 		    rp->r_gcount > 0) {
2936 			if (INTR4(vp)) {
2937 				klwp_t *lwp = ttolwp(curthread);
2938 
2939 				if (lwp != NULL)
2940 					lwp->lwp_nostop++;
2941 				if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2942 					mutex_exit(&rp->r_statelock);
2943 					if (lwp != NULL)
2944 						lwp->lwp_nostop--;
2945 					error = EINTR;
2946 					goto bottom;
2947 				}
2948 				if (lwp != NULL)
2949 					lwp->lwp_nostop--;
2950 			} else
2951 				cv_wait(&rp->r_cv, &rp->r_statelock);
2952 		}
2953 		mutex_exit(&rp->r_statelock);
2954 
2955 		/*
2956 		 * Touch the page and fault it in if it is not in core
2957 		 * before segmap_getmapflt or vpm_data_copy can lock it.
2958 		 * This is to avoid the deadlock if the buffer is mapped
2959 		 * to the same file through mmap which we want to write.
2960 		 */
2961 		uio_prefaultpages((long)n, uiop);
2962 
2963 		if (vpm_enable) {
2964 			/*
2965 			 * It will use kpm mappings, so no need to
2966 			 * pass an address.
2967 			 */
2968 			error = writerp4(rp, NULL, n, uiop, 0);
2969 		} else  {
2970 			if (segmap_kpm) {
2971 				int pon = uiop->uio_loffset & PAGEOFFSET;
2972 				size_t pn = MIN(PAGESIZE - pon,
2973 				    uiop->uio_resid);
2974 				int pagecreate;
2975 
2976 				mutex_enter(&rp->r_statelock);
2977 				pagecreate = (pon == 0) && (pn == PAGESIZE ||
2978 				    uiop->uio_loffset + pn >= rp->r_size);
2979 				mutex_exit(&rp->r_statelock);
2980 
2981 				base = segmap_getmapflt(segkmap, vp, off + on,
2982 				    pn, !pagecreate, S_WRITE);
2983 
2984 				error = writerp4(rp, base + pon, n, uiop,
2985 				    pagecreate);
2986 
2987 			} else {
2988 				base = segmap_getmapflt(segkmap, vp, off + on,
2989 				    n, 0, S_READ);
2990 				error = writerp4(rp, base + on, n, uiop, 0);
2991 			}
2992 		}
2993 
2994 		if (!error) {
2995 			if (mi->mi_flags & MI4_NOAC)
2996 				flags = SM_WRITE;
2997 			else if ((uiop->uio_loffset % bsize) == 0 ||
2998 			    IS_SWAPVP(vp)) {
2999 				/*
3000 				 * Have written a whole block.
3001 				 * Start an asynchronous write
3002 				 * and mark the buffer to
3003 				 * indicate that it won't be
3004 				 * needed again soon.
3005 				 */
3006 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
3007 			} else
3008 				flags = 0;
3009 			if ((ioflag & (FSYNC|FDSYNC)) ||
3010 			    (rp->r_flags & R4OUTOFSPACE)) {
3011 				flags &= ~SM_ASYNC;
3012 				flags |= SM_WRITE;
3013 			}
3014 			if (vpm_enable) {
3015 				error = vpm_sync_pages(vp, off, n, flags);
3016 			} else {
3017 				error = segmap_release(segkmap, base, flags);
3018 			}
3019 		} else {
3020 			if (vpm_enable) {
3021 				(void) vpm_sync_pages(vp, off, n, 0);
3022 			} else {
3023 				(void) segmap_release(segkmap, base, 0);
3024 			}
3025 			/*
3026 			 * In the event that we got an access error while
3027 			 * faulting in a page for a write-only file just
3028 			 * force a write.
3029 			 */
3030 			if (error == EACCES)
3031 				goto nfs4_fwrite;
3032 		}
3033 	} while (!error && uiop->uio_resid > 0);
3034 
3035 bottom:
3036 	if (error) {
3037 		uiop->uio_resid = resid + remainder;
3038 		uiop->uio_loffset = offset;
3039 	} else {
3040 		uiop->uio_resid += remainder;
3041 
3042 		mutex_enter(&rp->r_statev4_lock);
3043 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
3044 			gethrestime(&rp->r_attr.va_mtime);
3045 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3046 		}
3047 		mutex_exit(&rp->r_statev4_lock);
3048 	}
3049 
3050 	nfs_rw_exit(&rp->r_lkserlock);
3051 
3052 	return (error);
3053 }
3054 
3055 /*
3056  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
3057  */
3058 static int
3059 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
3060     int flags, cred_t *cr)
3061 {
3062 	struct buf *bp;
3063 	int error;
3064 	page_t *savepp;
3065 	uchar_t fsdata;
3066 	stable_how4 stab_comm;
3067 
3068 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3069 	bp = pageio_setup(pp, len, vp, flags);
3070 	ASSERT(bp != NULL);
3071 
3072 	/*
3073 	 * pageio_setup should have set b_addr to 0.  This
3074 	 * is correct since we want to do I/O on a page
3075 	 * boundary.  bp_mapin will use this addr to calculate
3076 	 * an offset, and then set b_addr to the kernel virtual
3077 	 * address it allocated for us.
3078 	 */
3079 	ASSERT(bp->b_un.b_addr == 0);
3080 
3081 	bp->b_edev = 0;
3082 	bp->b_dev = 0;
3083 	bp->b_lblkno = lbtodb(off);
3084 	bp->b_file = vp;
3085 	bp->b_offset = (offset_t)off;
3086 	bp_mapin(bp);
3087 
3088 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
3089 	    freemem > desfree)
3090 		stab_comm = UNSTABLE4;
3091 	else
3092 		stab_comm = FILE_SYNC4;
3093 
3094 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
3095 
3096 	bp_mapout(bp);
3097 	pageio_done(bp);
3098 
3099 	if (stab_comm == UNSTABLE4)
3100 		fsdata = C_DELAYCOMMIT;
3101 	else
3102 		fsdata = C_NOCOMMIT;
3103 
3104 	savepp = pp;
3105 	do {
3106 		pp->p_fsdata = fsdata;
3107 	} while ((pp = pp->p_next) != savepp);
3108 
3109 	return (error);
3110 }
3111 
3112 /*
3113  */
3114 static int
3115 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
3116 {
3117 	nfs4_open_owner_t	*oop;
3118 	nfs4_open_stream_t	*osp;
3119 	rnode4_t		*rp = VTOR4(vp);
3120 	mntinfo4_t		*mi = VTOMI4(vp);
3121 	int			reopen_needed;
3122 
3123 	ASSERT(nfs_zone() == mi->mi_zone);
3124 
3125 
3126 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
3127 	if (!oop)
3128 		return (EIO);
3129 
3130 	/* returns with 'os_sync_lock' held */
3131 	osp = find_open_stream(oop, rp);
3132 	if (!osp) {
3133 		open_owner_rele(oop);
3134 		return (EIO);
3135 	}
3136 
3137 	if (osp->os_failed_reopen) {
3138 		mutex_exit(&osp->os_sync_lock);
3139 		open_stream_rele(osp, rp);
3140 		open_owner_rele(oop);
3141 		return (EIO);
3142 	}
3143 
3144 	/*
3145 	 * Determine whether a reopen is needed.  If this
3146 	 * is a delegation open stream, then the os_delegation bit
3147 	 * should be set.
3148 	 */
3149 
3150 	reopen_needed = osp->os_delegation;
3151 
3152 	mutex_exit(&osp->os_sync_lock);
3153 	open_owner_rele(oop);
3154 
3155 	if (reopen_needed) {
3156 		nfs4_error_zinit(ep);
3157 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
3158 		mutex_enter(&osp->os_sync_lock);
3159 		if (ep->error || ep->stat || osp->os_failed_reopen) {
3160 			mutex_exit(&osp->os_sync_lock);
3161 			open_stream_rele(osp, rp);
3162 			return (EIO);
3163 		}
3164 		mutex_exit(&osp->os_sync_lock);
3165 	}
3166 	open_stream_rele(osp, rp);
3167 
3168 	return (0);
3169 }
3170 
3171 /*
3172  * Write to file.  Writes to remote server in largest size
3173  * chunks that the server can handle.  Write is synchronous.
3174  */
3175 static int
3176 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3177     stable_how4 *stab_comm)
3178 {
3179 	mntinfo4_t *mi;
3180 	COMPOUND4args_clnt args;
3181 	COMPOUND4res_clnt res;
3182 	WRITE4args *wargs;
3183 	WRITE4res *wres;
3184 	nfs_argop4 argop[2];
3185 	nfs_resop4 *resop;
3186 	int tsize;
3187 	stable_how4 stable;
3188 	rnode4_t *rp;
3189 	int doqueue = 1;
3190 	bool_t needrecov;
3191 	nfs4_recov_state_t recov_state;
3192 	nfs4_stateid_types_t sid_types;
3193 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3194 	int recov;
3195 
3196 	rp = VTOR4(vp);
3197 	mi = VTOMI4(vp);
3198 
3199 	ASSERT(nfs_zone() == mi->mi_zone);
3200 
3201 	stable = *stab_comm;
3202 	*stab_comm = FILE_SYNC4;
3203 
3204 	needrecov = FALSE;
3205 	recov_state.rs_flags = 0;
3206 	recov_state.rs_num_retry_despite_err = 0;
3207 	nfs4_init_stateid_types(&sid_types);
3208 
3209 	/* Is curthread the recovery thread? */
3210 	mutex_enter(&mi->mi_lock);
3211 	recov = (mi->mi_recovthread == curthread);
3212 	mutex_exit(&mi->mi_lock);
3213 
3214 recov_retry:
3215 	args.ctag = TAG_WRITE;
3216 	args.array_len = 2;
3217 	args.array = argop;
3218 
3219 	if (!recov) {
3220 		e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3221 		    &recov_state, NULL);
3222 		if (e.error)
3223 			return (e.error);
3224 	}
3225 
3226 	/* 0. putfh target fh */
3227 	argop[0].argop = OP_CPUTFH;
3228 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3229 
3230 	/* 1. write */
3231 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3232 
3233 	do {
3234 
3235 		wargs->offset = (offset4)offset;
3236 		wargs->data_val = base;
3237 
3238 		if (mi->mi_io_kstats) {
3239 			mutex_enter(&mi->mi_lock);
3240 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3241 			mutex_exit(&mi->mi_lock);
3242 		}
3243 
3244 		if ((vp->v_flag & VNOCACHE) ||
3245 		    (rp->r_flags & R4DIRECTIO) ||
3246 		    (mi->mi_flags & MI4_DIRECTIO))
3247 			tsize = MIN(mi->mi_stsize, count);
3248 		else
3249 			tsize = MIN(mi->mi_curwrite, count);
3250 		wargs->data_len = (uint_t)tsize;
3251 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3252 
3253 		if (mi->mi_io_kstats) {
3254 			mutex_enter(&mi->mi_lock);
3255 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3256 			mutex_exit(&mi->mi_lock);
3257 		}
3258 
3259 		if (!recov) {
3260 			needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3261 			if (e.error && !needrecov) {
3262 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3263 				    &recov_state, needrecov);
3264 				return (e.error);
3265 			}
3266 		} else {
3267 			if (e.error)
3268 				return (e.error);
3269 		}
3270 
3271 		/*
3272 		 * Do handling of OLD_STATEID outside
3273 		 * of the normal recovery framework.
3274 		 *
3275 		 * If write receives a BAD stateid error while using a
3276 		 * delegation stateid, retry using the open stateid (if it
3277 		 * exists).  If it doesn't have an open stateid, reopen the
3278 		 * file first, then retry.
3279 		 */
3280 		if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3281 		    sid_types.cur_sid_type != SPEC_SID) {
3282 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3283 			if (!recov)
3284 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3285 				    &recov_state, needrecov);
3286 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3287 			goto recov_retry;
3288 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3289 		    sid_types.cur_sid_type == DEL_SID) {
3290 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3291 			mutex_enter(&rp->r_statev4_lock);
3292 			rp->r_deleg_return_pending = TRUE;
3293 			mutex_exit(&rp->r_statev4_lock);
3294 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3295 				if (!recov)
3296 					nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3297 					    &recov_state, needrecov);
3298 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3299 				    (caddr_t)&res);
3300 				return (EIO);
3301 			}
3302 			if (!recov)
3303 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3304 				    &recov_state, needrecov);
3305 			/* hold needed for nfs4delegreturn_thread */
3306 			VN_HOLD(vp);
3307 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3308 			    NFS4_DR_DISCARD), FALSE);
3309 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3310 			goto recov_retry;
3311 		}
3312 
3313 		if (needrecov) {
3314 			bool_t abort;
3315 
3316 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3317 			    "nfs4write: client got error %d, res.status %d"
3318 			    ", so start recovery", e.error, res.status));
3319 
3320 			abort = nfs4_start_recovery(&e,
3321 			    VTOMI4(vp), vp, NULL, &wargs->stateid,
3322 			    NULL, OP_WRITE, NULL, NULL, NULL);
3323 			if (!e.error) {
3324 				e.error = geterrno4(res.status);
3325 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3326 				    (caddr_t)&res);
3327 			}
3328 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3329 			    &recov_state, needrecov);
3330 			if (abort == FALSE)
3331 				goto recov_retry;
3332 			return (e.error);
3333 		}
3334 
3335 		if (res.status) {
3336 			e.error = geterrno4(res.status);
3337 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3338 			if (!recov)
3339 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3340 				    &recov_state, needrecov);
3341 			return (e.error);
3342 		}
3343 
3344 		resop = &res.array[1];	/* write res */
3345 		wres = &resop->nfs_resop4_u.opwrite;
3346 
3347 		if ((int)wres->count > tsize) {
3348 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3349 
3350 			zcmn_err(getzoneid(), CE_WARN,
3351 			    "nfs4write: server wrote %u, requested was %u",
3352 			    (int)wres->count, tsize);
3353 			if (!recov)
3354 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3355 				    &recov_state, needrecov);
3356 			return (EIO);
3357 		}
3358 		if (wres->committed == UNSTABLE4) {
3359 			*stab_comm = UNSTABLE4;
3360 			if (wargs->stable == DATA_SYNC4 ||
3361 			    wargs->stable == FILE_SYNC4) {
3362 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3363 				    (caddr_t)&res);
3364 				zcmn_err(getzoneid(), CE_WARN,
3365 				    "nfs4write: server %s did not commit "
3366 				    "to stable storage",
3367 				    rp->r_server->sv_hostname);
3368 				if (!recov)
3369 					nfs4_end_fop(VTOMI4(vp), vp, NULL,
3370 					    OH_WRITE, &recov_state, needrecov);
3371 				return (EIO);
3372 			}
3373 		}
3374 
3375 		tsize = (int)wres->count;
3376 		count -= tsize;
3377 		base += tsize;
3378 		offset += tsize;
3379 		if (mi->mi_io_kstats) {
3380 			mutex_enter(&mi->mi_lock);
3381 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3382 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3383 			    tsize;
3384 			mutex_exit(&mi->mi_lock);
3385 		}
3386 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3387 		mutex_enter(&rp->r_statelock);
3388 		if (rp->r_flags & R4HAVEVERF) {
3389 			if (rp->r_writeverf != wres->writeverf) {
3390 				nfs4_set_mod(vp);
3391 				rp->r_writeverf = wres->writeverf;
3392 			}
3393 		} else {
3394 			rp->r_writeverf = wres->writeverf;
3395 			rp->r_flags |= R4HAVEVERF;
3396 		}
3397 		PURGE_ATTRCACHE4_LOCKED(rp);
3398 		rp->r_flags |= R4WRITEMODIFIED;
3399 		gethrestime(&rp->r_attr.va_mtime);
3400 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3401 		mutex_exit(&rp->r_statelock);
3402 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3403 	} while (count);
3404 
3405 	if (!recov)
3406 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state,
3407 		    needrecov);
3408 
3409 	return (e.error);
3410 }
3411 
3412 /*
3413  * Read from a file.  Reads data in largest chunks our interface can handle.
3414  */
3415 static int
3416 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3417     size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3418 {
3419 	mntinfo4_t *mi;
3420 	COMPOUND4args_clnt args;
3421 	COMPOUND4res_clnt res;
3422 	READ4args *rargs;
3423 	nfs_argop4 argop[2];
3424 	int tsize;
3425 	int doqueue;
3426 	rnode4_t *rp;
3427 	int data_len;
3428 	bool_t is_eof;
3429 	bool_t needrecov = FALSE;
3430 	nfs4_recov_state_t recov_state;
3431 	nfs4_stateid_types_t sid_types;
3432 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3433 
3434 	rp = VTOR4(vp);
3435 	mi = VTOMI4(vp);
3436 	doqueue = 1;
3437 
3438 	ASSERT(nfs_zone() == mi->mi_zone);
3439 
3440 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3441 
3442 	args.array_len = 2;
3443 	args.array = argop;
3444 
3445 	nfs4_init_stateid_types(&sid_types);
3446 
3447 	recov_state.rs_flags = 0;
3448 	recov_state.rs_num_retry_despite_err = 0;
3449 
3450 recov_retry:
3451 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3452 	    &recov_state, NULL);
3453 	if (e.error)
3454 		return (e.error);
3455 
3456 	/* putfh target fh */
3457 	argop[0].argop = OP_CPUTFH;
3458 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3459 
3460 	/* read */
3461 	argop[1].argop = OP_READ;
3462 	rargs = &argop[1].nfs_argop4_u.opread;
3463 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3464 	    OP_READ, &sid_types, async);
3465 
3466 	do {
3467 		if (mi->mi_io_kstats) {
3468 			mutex_enter(&mi->mi_lock);
3469 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3470 			mutex_exit(&mi->mi_lock);
3471 		}
3472 
3473 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3474 		    "nfs4read: %s call, rp %s",
3475 		    needrecov ? "recov" : "first",
3476 		    rnode4info(rp)));
3477 
3478 		if ((vp->v_flag & VNOCACHE) ||
3479 		    (rp->r_flags & R4DIRECTIO) ||
3480 		    (mi->mi_flags & MI4_DIRECTIO))
3481 			tsize = MIN(mi->mi_tsize, count);
3482 		else
3483 			tsize = MIN(mi->mi_curread, count);
3484 
3485 		rargs->offset = (offset4)offset;
3486 		rargs->count = (count4)tsize;
3487 		rargs->res_data_val_alt = NULL;
3488 		rargs->res_mblk = NULL;
3489 		rargs->res_uiop = NULL;
3490 		rargs->res_maxsize = 0;
3491 		rargs->wlist = NULL;
3492 
3493 		if (uiop)
3494 			rargs->res_uiop = uiop;
3495 		else
3496 			rargs->res_data_val_alt = base;
3497 		rargs->res_maxsize = tsize;
3498 
3499 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3500 #ifdef	DEBUG
3501 		if (nfs4read_error_inject) {
3502 			res.status = nfs4read_error_inject;
3503 			nfs4read_error_inject = 0;
3504 		}
3505 #endif
3506 
3507 		if (mi->mi_io_kstats) {
3508 			mutex_enter(&mi->mi_lock);
3509 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3510 			mutex_exit(&mi->mi_lock);
3511 		}
3512 
3513 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3514 		if (e.error != 0 && !needrecov) {
3515 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3516 			    &recov_state, needrecov);
3517 			return (e.error);
3518 		}
3519 
3520 		/*
3521 		 * Do proper retry for OLD and BAD stateid errors outside
3522 		 * of the normal recovery framework.  There are two differences
3523 		 * between async and sync reads.  The first is that we allow
3524 		 * retry on BAD_STATEID for async reads, but not sync reads.
3525 		 * The second is that we mark the file dead for a failed
3526 		 * attempt with a special stateid for sync reads, but just
3527 		 * return EIO for async reads.
3528 		 *
3529 		 * If a sync read receives a BAD stateid error while using a
3530 		 * delegation stateid, retry using the open stateid (if it
3531 		 * exists).  If it doesn't have an open stateid, reopen the
3532 		 * file first, then retry.
3533 		 */
3534 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3535 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3536 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3537 			    &recov_state, needrecov);
3538 			if (sid_types.cur_sid_type == SPEC_SID) {
3539 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3540 				    (caddr_t)&res);
3541 				return (EIO);
3542 			}
3543 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3544 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3545 			goto recov_retry;
3546 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3547 		    !async && sid_types.cur_sid_type != SPEC_SID) {
3548 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3549 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3550 			    &recov_state, needrecov);
3551 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3552 			goto recov_retry;
3553 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3554 		    sid_types.cur_sid_type == DEL_SID) {
3555 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3556 			mutex_enter(&rp->r_statev4_lock);
3557 			rp->r_deleg_return_pending = TRUE;
3558 			mutex_exit(&rp->r_statev4_lock);
3559 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3560 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3561 				    &recov_state, needrecov);
3562 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3563 				    (caddr_t)&res);
3564 				return (EIO);
3565 			}
3566 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3567 			    &recov_state, needrecov);
3568 			/* hold needed for nfs4delegreturn_thread */
3569 			VN_HOLD(vp);
3570 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3571 			    NFS4_DR_DISCARD), FALSE);
3572 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3573 			goto recov_retry;
3574 		}
3575 		if (needrecov) {
3576 			bool_t abort;
3577 
3578 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3579 			    "nfs4read: initiating recovery\n"));
3580 			abort = nfs4_start_recovery(&e,
3581 			    mi, vp, NULL, &rargs->stateid,
3582 			    NULL, OP_READ, NULL, NULL, NULL);
3583 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3584 			    &recov_state, needrecov);
3585 			/*
3586 			 * Do not retry if we got OLD_STATEID using a special
3587 			 * stateid.  This avoids looping with a broken server.
3588 			 */
3589 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3590 			    sid_types.cur_sid_type == SPEC_SID)
3591 				abort = TRUE;
3592 
3593 			if (abort == FALSE) {
3594 				/*
3595 				 * Need to retry all possible stateids in
3596 				 * case the recovery error wasn't stateid
3597 				 * related or the stateids have become
3598 				 * stale (server reboot).
3599 				 */
3600 				nfs4_init_stateid_types(&sid_types);
3601 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3602 				    (caddr_t)&res);
3603 				goto recov_retry;
3604 			}
3605 
3606 			if (!e.error) {
3607 				e.error = geterrno4(res.status);
3608 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3609 				    (caddr_t)&res);
3610 			}
3611 			return (e.error);
3612 		}
3613 
3614 		if (res.status) {
3615 			e.error = geterrno4(res.status);
3616 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3617 			    &recov_state, needrecov);
3618 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3619 			return (e.error);
3620 		}
3621 
3622 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3623 		count -= data_len;
3624 		if (base)
3625 			base += data_len;
3626 		offset += data_len;
3627 		if (mi->mi_io_kstats) {
3628 			mutex_enter(&mi->mi_lock);
3629 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3630 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3631 			mutex_exit(&mi->mi_lock);
3632 		}
3633 		lwp_stat_update(LWP_STAT_INBLK, 1);
3634 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3635 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3636 
3637 	} while (count && !is_eof);
3638 
3639 	*residp = count;
3640 
3641 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3642 
3643 	return (e.error);
3644 }
3645 
3646 /* ARGSUSED */
3647 static int
3648 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp,
3649     caller_context_t *ct)
3650 {
3651 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3652 		return (EIO);
3653 	switch (cmd) {
3654 		case _FIODIRECTIO:
3655 			return (nfs4_directio(vp, (int)arg, cr));
3656 		default:
3657 			return (ENOTTY);
3658 	}
3659 }
3660 
3661 /* ARGSUSED */
3662 int
3663 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3664     caller_context_t *ct)
3665 {
3666 	int error;
3667 	rnode4_t *rp = VTOR4(vp);
3668 
3669 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3670 		return (EIO);
3671 	/*
3672 	 * If it has been specified that the return value will
3673 	 * just be used as a hint, and we are only being asked
3674 	 * for size, fsid or rdevid, then return the client's
3675 	 * notion of these values without checking to make sure
3676 	 * that the attribute cache is up to date.
3677 	 * The whole point is to avoid an over the wire GETATTR
3678 	 * call.
3679 	 */
3680 	if (flags & ATTR_HINT) {
3681 		if (!(vap->va_mask & ~(AT_SIZE | AT_FSID | AT_RDEV))) {
3682 			mutex_enter(&rp->r_statelock);
3683 			if (vap->va_mask & AT_SIZE)
3684 				vap->va_size = rp->r_size;
3685 			if (vap->va_mask & AT_FSID)
3686 				vap->va_fsid = rp->r_attr.va_fsid;
3687 			if (vap->va_mask & AT_RDEV)
3688 				vap->va_rdev = rp->r_attr.va_rdev;
3689 			mutex_exit(&rp->r_statelock);
3690 			return (0);
3691 		}
3692 	}
3693 
3694 	/*
3695 	 * Only need to flush pages if asking for the mtime
3696 	 * and if there any dirty pages or any outstanding
3697 	 * asynchronous (write) requests for this file.
3698 	 */
3699 	if (vap->va_mask & AT_MTIME) {
3700 		rp = VTOR4(vp);
3701 		if (nfs4_has_pages(vp)) {
3702 			mutex_enter(&rp->r_statev4_lock);
3703 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3704 				mutex_exit(&rp->r_statev4_lock);
3705 				if (rp->r_flags & R4DIRTY ||
3706 				    rp->r_awcount > 0) {
3707 					mutex_enter(&rp->r_statelock);
3708 					rp->r_gcount++;
3709 					mutex_exit(&rp->r_statelock);
3710 					error =
3711 					    nfs4_putpage(vp, (u_offset_t)0,
3712 					    0, 0, cr, NULL);
3713 					mutex_enter(&rp->r_statelock);
3714 					if (error && (error == ENOSPC ||
3715 					    error == EDQUOT)) {
3716 						if (!rp->r_error)
3717 							rp->r_error = error;
3718 					}
3719 					if (--rp->r_gcount == 0)
3720 						cv_broadcast(&rp->r_cv);
3721 					mutex_exit(&rp->r_statelock);
3722 				}
3723 			} else {
3724 				mutex_exit(&rp->r_statev4_lock);
3725 			}
3726 		}
3727 	}
3728 	return (nfs4getattr(vp, vap, cr));
3729 }
3730 
3731 int
3732 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3733 {
3734 	/*
3735 	 * If these are the only two bits cleared
3736 	 * on the server then return 0 (OK) else
3737 	 * return 1 (BAD).
3738 	 */
3739 	on_client &= ~(S_ISUID|S_ISGID);
3740 	if (on_client == from_server)
3741 		return (0);
3742 	else
3743 		return (1);
3744 }
3745 
3746 /*ARGSUSED4*/
3747 static int
3748 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3749     caller_context_t *ct)
3750 {
3751 	int error;
3752 
3753 	if (vap->va_mask & AT_NOSET)
3754 		return (EINVAL);
3755 
3756 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3757 		return (EIO);
3758 
3759 	/*
3760 	 * Don't call secpolicy_vnode_setattr, the client cannot
3761 	 * use its cached attributes to make security decisions
3762 	 * as the server may be faking mode bits or mapping uid/gid.
3763 	 * Always just let the server to the checking.
3764 	 * If we provide the ability to remove basic priviledges
3765 	 * to setattr (e.g. basic without chmod) then we will
3766 	 * need to add a check here before calling the server.
3767 	 */
3768 	error = nfs4setattr(vp, vap, flags, cr, NULL);
3769 
3770 	if (error == 0 && (vap->va_mask & AT_SIZE) && vap->va_size == 0)
3771 		vnevent_truncate(vp, ct);
3772 
3773 	return (error);
3774 }
3775 
3776 /*
3777  * To replace the "guarded" version 3 setattr, we use two types of compound
3778  * setattr requests:
3779  * 1. The "normal" setattr, used when the size of the file isn't being
3780  *    changed - { Putfh <fh>; Setattr; Getattr }/
3781  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3782  *    with only ctime as the argument. If the server ctime differs from
3783  *    what is cached on the client, the verify will fail, but we would
3784  *    already have the ctime from the preceding getattr, so just set it
3785  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3786  *	Setattr; Getattr }.
3787  *
3788  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3789  * this setattr and NULL if they are not.
3790  */
3791 static int
3792 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3793     vsecattr_t *vsap)
3794 {
3795 	COMPOUND4args_clnt args;
3796 	COMPOUND4res_clnt res, *resp = NULL;
3797 	nfs4_ga_res_t *garp = NULL;
3798 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3799 	nfs_argop4 argop[5];
3800 	int verify_argop = -1;
3801 	int setattr_argop = 1;
3802 	nfs_resop4 *resop;
3803 	vattr_t va;
3804 	rnode4_t *rp;
3805 	int doqueue = 1;
3806 	uint_t mask = vap->va_mask;
3807 	mode_t omode;
3808 	vsecattr_t *vsp;
3809 	timestruc_t ctime;
3810 	bool_t needrecov = FALSE;
3811 	nfs4_recov_state_t recov_state;
3812 	nfs4_stateid_types_t sid_types;
3813 	stateid4 stateid;
3814 	hrtime_t t;
3815 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3816 	servinfo4_t *svp;
3817 	bitmap4 supp_attrs;
3818 
3819 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3820 	rp = VTOR4(vp);
3821 	nfs4_init_stateid_types(&sid_types);
3822 
3823 	/*
3824 	 * Only need to flush pages if there are any pages and
3825 	 * if the file is marked as dirty in some fashion.  The
3826 	 * file must be flushed so that we can accurately
3827 	 * determine the size of the file and the cached data
3828 	 * after the SETATTR returns.  A file is considered to
3829 	 * be dirty if it is either marked with R4DIRTY, has
3830 	 * outstanding i/o's active, or is mmap'd.  In this
3831 	 * last case, we can't tell whether there are dirty
3832 	 * pages, so we flush just to be sure.
3833 	 */
3834 	if (nfs4_has_pages(vp) &&
3835 	    ((rp->r_flags & R4DIRTY) ||
3836 	    rp->r_count > 0 ||
3837 	    rp->r_mapcnt > 0)) {
3838 		ASSERT(vp->v_type != VCHR);
3839 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr, NULL);
3840 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3841 			mutex_enter(&rp->r_statelock);
3842 			if (!rp->r_error)
3843 				rp->r_error = e.error;
3844 			mutex_exit(&rp->r_statelock);
3845 		}
3846 	}
3847 
3848 	if (mask & AT_SIZE) {
3849 		/*
3850 		 * Verification setattr compound for non-deleg AT_SIZE:
3851 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3852 		 * Set ctime local here (outside the do_again label)
3853 		 * so that subsequent retries (after failed VERIFY)
3854 		 * will use ctime from GETATTR results (from failed
3855 		 * verify compound) as VERIFY arg.
3856 		 * If file has delegation, then VERIFY(time_metadata)
3857 		 * is of little added value, so don't bother.
3858 		 */
3859 		mutex_enter(&rp->r_statev4_lock);
3860 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3861 		    rp->r_deleg_return_pending) {
3862 			numops = 5;
3863 			ctime = rp->r_attr.va_ctime;
3864 		}
3865 		mutex_exit(&rp->r_statev4_lock);
3866 	}
3867 
3868 	recov_state.rs_flags = 0;
3869 	recov_state.rs_num_retry_despite_err = 0;
3870 
3871 	args.ctag = TAG_SETATTR;
3872 do_again:
3873 recov_retry:
3874 	setattr_argop = numops - 2;
3875 
3876 	args.array = argop;
3877 	args.array_len = numops;
3878 
3879 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3880 	if (e.error)
3881 		return (e.error);
3882 
3883 
3884 	/* putfh target fh */
3885 	argop[0].argop = OP_CPUTFH;
3886 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3887 
3888 	if (numops == 5) {
3889 		/*
3890 		 * We only care about the ctime, but need to get mtime
3891 		 * and size for proper cache update.
3892 		 */
3893 		/* getattr */
3894 		argop[1].argop = OP_GETATTR;
3895 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3896 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3897 
3898 		/* verify - set later in loop */
3899 		verify_argop = 2;
3900 	}
3901 
3902 	/* setattr */
3903 	svp = rp->r_server;
3904 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3905 	supp_attrs = svp->sv_supp_attrs;
3906 	nfs_rw_exit(&svp->sv_lock);
3907 
3908 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3909 	    supp_attrs, &e.error, &sid_types);
3910 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3911 	if (e.error) {
3912 		/* req time field(s) overflow - return immediately */
3913 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3914 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3915 		    opsetattr.obj_attributes);
3916 		return (e.error);
3917 	}
3918 	omode = rp->r_attr.va_mode;
3919 
3920 	/* getattr */
3921 	argop[numops-1].argop = OP_GETATTR;
3922 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3923 	/*
3924 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3925 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3926 	 * used in updating the ACL cache.
3927 	 */
3928 	if (vsap != NULL)
3929 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3930 		    FATTR4_ACL_MASK;
3931 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3932 
3933 	/*
3934 	 * setattr iterates if the object size is set and the cached ctime
3935 	 * does not match the file ctime. In that case, verify the ctime first.
3936 	 */
3937 
3938 	do {
3939 		if (verify_argop != -1) {
3940 			/*
3941 			 * Verify that the ctime match before doing setattr.
3942 			 */
3943 			va.va_mask = AT_CTIME;
3944 			va.va_ctime = ctime;
3945 			svp = rp->r_server;
3946 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3947 			supp_attrs = svp->sv_supp_attrs;
3948 			nfs_rw_exit(&svp->sv_lock);
3949 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3950 			    OP_VERIFY, supp_attrs);
3951 			if (e.error) {
3952 				/* req time field(s) overflow - return */
3953 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3954 				    needrecov);
3955 				break;
3956 			}
3957 		}
3958 
3959 		doqueue = 1;
3960 
3961 		t = gethrtime();
3962 
3963 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3964 
3965 		/*
3966 		 * Purge the access cache and ACL cache if changing either the
3967 		 * owner of the file, the group owner, or the mode.  These may
3968 		 * change the access permissions of the file, so purge old
3969 		 * information and start over again.
3970 		 */
3971 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3972 			(void) nfs4_access_purge_rp(rp);
3973 			if (rp->r_secattr != NULL) {
3974 				mutex_enter(&rp->r_statelock);
3975 				vsp = rp->r_secattr;
3976 				rp->r_secattr = NULL;
3977 				mutex_exit(&rp->r_statelock);
3978 				if (vsp != NULL)
3979 					nfs4_acl_free_cache(vsp);
3980 			}
3981 		}
3982 
3983 		/*
3984 		 * If res.array_len == numops, then everything succeeded,
3985 		 * except for possibly the final getattr.  If only the
3986 		 * last getattr failed, give up, and don't try recovery.
3987 		 */
3988 		if (res.array_len == numops) {
3989 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3990 			    needrecov);
3991 			if (! e.error)
3992 				resp = &res;
3993 			break;
3994 		}
3995 
3996 		/*
3997 		 * if either rpc call failed or completely succeeded - done
3998 		 */
3999 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4000 		if (e.error) {
4001 			PURGE_ATTRCACHE4(vp);
4002 			if (!needrecov) {
4003 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4004 				    needrecov);
4005 				break;
4006 			}
4007 		}
4008 
4009 		/*
4010 		 * Do proper retry for OLD_STATEID outside of the normal
4011 		 * recovery framework.
4012 		 */
4013 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
4014 		    sid_types.cur_sid_type != SPEC_SID &&
4015 		    sid_types.cur_sid_type != NO_SID) {
4016 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4017 			    needrecov);
4018 			nfs4_save_stateid(&stateid, &sid_types);
4019 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4020 			    opsetattr.obj_attributes);
4021 			if (verify_argop != -1) {
4022 				nfs4args_verify_free(&argop[verify_argop]);
4023 				verify_argop = -1;
4024 			}
4025 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4026 			goto recov_retry;
4027 		}
4028 
4029 		if (needrecov) {
4030 			bool_t abort;
4031 
4032 			abort = nfs4_start_recovery(&e,
4033 			    VTOMI4(vp), vp, NULL, NULL, NULL,
4034 			    OP_SETATTR, NULL, NULL, NULL);
4035 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4036 			    needrecov);
4037 			/*
4038 			 * Do not retry if we failed with OLD_STATEID using
4039 			 * a special stateid.  This is done to avoid looping
4040 			 * with a broken server.
4041 			 */
4042 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
4043 			    (sid_types.cur_sid_type == SPEC_SID ||
4044 			    sid_types.cur_sid_type == NO_SID))
4045 				abort = TRUE;
4046 			if (!e.error) {
4047 				if (res.status == NFS4ERR_BADOWNER)
4048 					nfs4_log_badowner(VTOMI4(vp),
4049 					    OP_SETATTR);
4050 
4051 				e.error = geterrno4(res.status);
4052 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4053 				    (caddr_t)&res);
4054 			}
4055 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4056 			    opsetattr.obj_attributes);
4057 			if (verify_argop != -1) {
4058 				nfs4args_verify_free(&argop[verify_argop]);
4059 				verify_argop = -1;
4060 			}
4061 			if (abort == FALSE) {
4062 				/*
4063 				 * Need to retry all possible stateids in
4064 				 * case the recovery error wasn't stateid
4065 				 * related or the stateids have become
4066 				 * stale (server reboot).
4067 				 */
4068 				nfs4_init_stateid_types(&sid_types);
4069 				goto recov_retry;
4070 			}
4071 			return (e.error);
4072 		}
4073 
4074 		/*
4075 		 * Need to call nfs4_end_op before nfs4getattr to
4076 		 * avoid potential nfs4_start_op deadlock. See RFE
4077 		 * 4777612.  Calls to nfs4_invalidate_pages() and
4078 		 * nfs4_purge_stale_fh() might also generate over the
4079 		 * wire calls which my cause nfs4_start_op() deadlock.
4080 		 */
4081 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4082 
4083 		/*
4084 		 * Check to update lease.
4085 		 */
4086 		resp = &res;
4087 		if (res.status == NFS4_OK) {
4088 			break;
4089 		}
4090 
4091 		/*
4092 		 * Check if verify failed to see if try again
4093 		 */
4094 		if ((verify_argop == -1) || (res.array_len != 3)) {
4095 			/*
4096 			 * can't continue...
4097 			 */
4098 			if (res.status == NFS4ERR_BADOWNER)
4099 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
4100 
4101 			e.error = geterrno4(res.status);
4102 		} else {
4103 			/*
4104 			 * When the verify request fails, the client ctime is
4105 			 * not in sync with the server. This is the same as
4106 			 * the version 3 "not synchronized" error, and we
4107 			 * handle it in a similar manner (XXX do we need to???).
4108 			 * Use the ctime returned in the first getattr for
4109 			 * the input to the next verify.
4110 			 * If we couldn't get the attributes, then we give up
4111 			 * because we can't complete the operation as required.
4112 			 */
4113 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
4114 		}
4115 		if (e.error) {
4116 			PURGE_ATTRCACHE4(vp);
4117 			nfs4_purge_stale_fh(e.error, vp, cr);
4118 		} else {
4119 			/*
4120 			 * retry with a new verify value
4121 			 */
4122 			ctime = garp->n4g_va.va_ctime;
4123 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4124 			resp = NULL;
4125 		}
4126 		if (!e.error) {
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 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4134 			goto do_again;
4135 		}
4136 	} while (!e.error);
4137 
4138 	if (e.error) {
4139 		/*
4140 		 * If we are here, rfs4call has an irrecoverable error - return
4141 		 */
4142 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4143 		    opsetattr.obj_attributes);
4144 		if (verify_argop != -1) {
4145 			nfs4args_verify_free(&argop[verify_argop]);
4146 			verify_argop = -1;
4147 		}
4148 		if (resp)
4149 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4150 		return (e.error);
4151 	}
4152 
4153 
4154 
4155 	/*
4156 	 * If changing the size of the file, invalidate
4157 	 * any local cached data which is no longer part
4158 	 * of the file.  We also possibly invalidate the
4159 	 * last page in the file.  We could use
4160 	 * pvn_vpzero(), but this would mark the page as
4161 	 * modified and require it to be written back to
4162 	 * the server for no particularly good reason.
4163 	 * This way, if we access it, then we bring it
4164 	 * back in.  A read should be cheaper than a
4165 	 * write.
4166 	 */
4167 	if (mask & AT_SIZE) {
4168 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
4169 	}
4170 
4171 	/* either no error or one of the postop getattr failed */
4172 
4173 	/*
4174 	 * XXX Perform a simplified version of wcc checking. Instead of
4175 	 * have another getattr to get pre-op, just purge cache if
4176 	 * any of the ops prior to and including the getattr failed.
4177 	 * If the getattr succeeded then update the attrcache accordingly.
4178 	 */
4179 
4180 	garp = NULL;
4181 	if (res.status == NFS4_OK) {
4182 		/*
4183 		 * Last getattr
4184 		 */
4185 		resop = &res.array[numops - 1];
4186 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4187 	}
4188 	/*
4189 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
4190 	 * rather than filling it.  See the function itself for details.
4191 	 */
4192 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4193 	if (garp != NULL) {
4194 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
4195 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
4196 			vs_ace4_destroy(&garp->n4g_vsa);
4197 		} else {
4198 			if (vsap != NULL) {
4199 				/*
4200 				 * The ACL was supposed to be set and to be
4201 				 * returned in the last getattr of this
4202 				 * compound, but for some reason the getattr
4203 				 * result doesn't contain the ACL.  In this
4204 				 * case, purge the ACL cache.
4205 				 */
4206 				if (rp->r_secattr != NULL) {
4207 					mutex_enter(&rp->r_statelock);
4208 					vsp = rp->r_secattr;
4209 					rp->r_secattr = NULL;
4210 					mutex_exit(&rp->r_statelock);
4211 					if (vsp != NULL)
4212 						nfs4_acl_free_cache(vsp);
4213 				}
4214 			}
4215 		}
4216 	}
4217 
4218 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4219 		/*
4220 		 * Set the size, rather than relying on getting it updated
4221 		 * via a GETATTR.  With delegations the client tries to
4222 		 * suppress GETATTR calls.
4223 		 */
4224 		mutex_enter(&rp->r_statelock);
4225 		rp->r_size = vap->va_size;
4226 		mutex_exit(&rp->r_statelock);
4227 	}
4228 
4229 	/*
4230 	 * Can free up request args and res
4231 	 */
4232 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4233 	    opsetattr.obj_attributes);
4234 	if (verify_argop != -1) {
4235 		nfs4args_verify_free(&argop[verify_argop]);
4236 		verify_argop = -1;
4237 	}
4238 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4239 
4240 	/*
4241 	 * Some servers will change the mode to clear the setuid
4242 	 * and setgid bits when changing the uid or gid.  The
4243 	 * client needs to compensate appropriately.
4244 	 */
4245 	if (mask & (AT_UID | AT_GID)) {
4246 		int terror, do_setattr;
4247 
4248 		do_setattr = 0;
4249 		va.va_mask = AT_MODE;
4250 		terror = nfs4getattr(vp, &va, cr);
4251 		if (!terror &&
4252 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4253 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4254 			va.va_mask = AT_MODE;
4255 			if (mask & AT_MODE) {
4256 				/*
4257 				 * We asked the mode to be changed and what
4258 				 * we just got from the server in getattr is
4259 				 * not what we wanted it to be, so set it now.
4260 				 */
4261 				va.va_mode = vap->va_mode;
4262 				do_setattr = 1;
4263 			} else {
4264 				/*
4265 				 * We did not ask the mode to be changed,
4266 				 * Check to see that the server just cleared
4267 				 * I_SUID and I_GUID from it. If not then
4268 				 * set mode to omode with UID/GID cleared.
4269 				 */
4270 				if (nfs4_compare_modes(va.va_mode, omode)) {
4271 					omode &= ~(S_ISUID|S_ISGID);
4272 					va.va_mode = omode;
4273 					do_setattr = 1;
4274 				}
4275 			}
4276 
4277 			if (do_setattr)
4278 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4279 		}
4280 	}
4281 
4282 	return (e.error);
4283 }
4284 
4285 /* ARGSUSED */
4286 static int
4287 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr, caller_context_t *ct)
4288 {
4289 	COMPOUND4args_clnt args;
4290 	COMPOUND4res_clnt res;
4291 	int doqueue;
4292 	uint32_t acc, resacc, argacc;
4293 	rnode4_t *rp;
4294 	cred_t *cred, *ncr, *ncrfree = NULL;
4295 	nfs4_access_type_t cacc;
4296 	int num_ops;
4297 	nfs_argop4 argop[3];
4298 	nfs_resop4 *resop;
4299 	bool_t needrecov = FALSE, do_getattr;
4300 	nfs4_recov_state_t recov_state;
4301 	int rpc_error;
4302 	hrtime_t t;
4303 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4304 	mntinfo4_t *mi = VTOMI4(vp);
4305 
4306 	if (nfs_zone() != mi->mi_zone)
4307 		return (EIO);
4308 
4309 	acc = 0;
4310 	if (mode & VREAD)
4311 		acc |= ACCESS4_READ;
4312 	if (mode & VWRITE) {
4313 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4314 			return (EROFS);
4315 		if (vp->v_type == VDIR)
4316 			acc |= ACCESS4_DELETE;
4317 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4318 	}
4319 	if (mode & VEXEC) {
4320 		if (vp->v_type == VDIR)
4321 			acc |= ACCESS4_LOOKUP;
4322 		else
4323 			acc |= ACCESS4_EXECUTE;
4324 	}
4325 
4326 	if (VTOR4(vp)->r_acache != NULL) {
4327 		e.error = nfs4_validate_caches(vp, cr);
4328 		if (e.error)
4329 			return (e.error);
4330 	}
4331 
4332 	rp = VTOR4(vp);
4333 	if (vp->v_type == VDIR)
4334 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4335 		    ACCESS4_EXTEND | ACCESS4_LOOKUP;
4336 	else
4337 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4338 		    ACCESS4_EXECUTE;
4339 	recov_state.rs_flags = 0;
4340 	recov_state.rs_num_retry_despite_err = 0;
4341 
4342 	cred = cr;
4343 	/*
4344 	 * ncr and ncrfree both initially
4345 	 * point to the memory area returned
4346 	 * by crnetadjust();
4347 	 * ncrfree not NULL when exiting means
4348 	 * that we need to release it
4349 	 */
4350 	ncr = crnetadjust(cred);
4351 	ncrfree = ncr;
4352 
4353 tryagain:
4354 	cacc = nfs4_access_check(rp, acc, cred);
4355 	if (cacc == NFS4_ACCESS_ALLOWED) {
4356 		if (ncrfree != NULL)
4357 			crfree(ncrfree);
4358 		return (0);
4359 	}
4360 	if (cacc == NFS4_ACCESS_DENIED) {
4361 		/*
4362 		 * If the cred can be adjusted, try again
4363 		 * with the new cred.
4364 		 */
4365 		if (ncr != NULL) {
4366 			cred = ncr;
4367 			ncr = NULL;
4368 			goto tryagain;
4369 		}
4370 		if (ncrfree != NULL)
4371 			crfree(ncrfree);
4372 		return (EACCES);
4373 	}
4374 
4375 recov_retry:
4376 	/*
4377 	 * Don't take with r_statev4_lock here. r_deleg_type could
4378 	 * change as soon as lock is released.  Since it is an int,
4379 	 * there is no atomicity issue.
4380 	 */
4381 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4382 	num_ops = do_getattr ? 3 : 2;
4383 
4384 	args.ctag = TAG_ACCESS;
4385 
4386 	args.array_len = num_ops;
4387 	args.array = argop;
4388 
4389 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4390 	    &recov_state, NULL)) {
4391 		if (ncrfree != NULL)
4392 			crfree(ncrfree);
4393 		return (e.error);
4394 	}
4395 
4396 	/* putfh target fh */
4397 	argop[0].argop = OP_CPUTFH;
4398 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4399 
4400 	/* access */
4401 	argop[1].argop = OP_ACCESS;
4402 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4403 
4404 	/* getattr */
4405 	if (do_getattr) {
4406 		argop[2].argop = OP_GETATTR;
4407 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4408 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4409 	}
4410 
4411 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4412 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4413 	    rnode4info(VTOR4(vp))));
4414 
4415 	doqueue = 1;
4416 	t = gethrtime();
4417 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4418 	rpc_error = e.error;
4419 
4420 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4421 	if (needrecov) {
4422 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4423 		    "nfs4_access: initiating recovery\n"));
4424 
4425 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4426 		    NULL, OP_ACCESS, NULL, NULL, NULL) == FALSE) {
4427 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4428 			    &recov_state, needrecov);
4429 			if (!e.error)
4430 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4431 				    (caddr_t)&res);
4432 			goto recov_retry;
4433 		}
4434 	}
4435 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4436 
4437 	if (e.error)
4438 		goto out;
4439 
4440 	if (res.status) {
4441 		e.error = geterrno4(res.status);
4442 		/*
4443 		 * This might generate over the wire calls throught
4444 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4445 		 * here to avoid a deadlock.
4446 		 */
4447 		nfs4_purge_stale_fh(e.error, vp, cr);
4448 		goto out;
4449 	}
4450 	resop = &res.array[1];	/* access res */
4451 
4452 	resacc = resop->nfs_resop4_u.opaccess.access;
4453 
4454 	if (do_getattr) {
4455 		resop++;	/* getattr res */
4456 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4457 		    t, cr, FALSE, NULL);
4458 	}
4459 
4460 	if (!e.error) {
4461 		nfs4_access_cache(rp, argacc, resacc, cred);
4462 		/*
4463 		 * we just cached results with cred; if cred is the
4464 		 * adjusted credentials from crnetadjust, we do not want
4465 		 * to release them before exiting: hence setting ncrfree
4466 		 * to NULL
4467 		 */
4468 		if (cred != cr)
4469 			ncrfree = NULL;
4470 		/* XXX check the supported bits too? */
4471 		if ((acc & resacc) != acc) {
4472 			/*
4473 			 * The following code implements the semantic
4474 			 * that a setuid root program has *at least* the
4475 			 * permissions of the user that is running the
4476 			 * program.  See rfs3call() for more portions
4477 			 * of the implementation of this functionality.
4478 			 */
4479 			/* XXX-LP */
4480 			if (ncr != NULL) {
4481 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4482 				    (caddr_t)&res);
4483 				cred = ncr;
4484 				ncr = NULL;
4485 				goto tryagain;
4486 			}
4487 			e.error = EACCES;
4488 		}
4489 	}
4490 
4491 out:
4492 	if (!rpc_error)
4493 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4494 
4495 	if (ncrfree != NULL)
4496 		crfree(ncrfree);
4497 
4498 	return (e.error);
4499 }
4500 
4501 /* ARGSUSED */
4502 static int
4503 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr, caller_context_t *ct)
4504 {
4505 	COMPOUND4args_clnt args;
4506 	COMPOUND4res_clnt res;
4507 	int doqueue;
4508 	rnode4_t *rp;
4509 	nfs_argop4 argop[3];
4510 	nfs_resop4 *resop;
4511 	READLINK4res *lr_res;
4512 	nfs4_ga_res_t *garp;
4513 	uint_t len;
4514 	char *linkdata;
4515 	bool_t needrecov = FALSE;
4516 	nfs4_recov_state_t recov_state;
4517 	hrtime_t t;
4518 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4519 
4520 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4521 		return (EIO);
4522 	/*
4523 	 * Can't readlink anything other than a symbolic link.
4524 	 */
4525 	if (vp->v_type != VLNK)
4526 		return (EINVAL);
4527 
4528 	rp = VTOR4(vp);
4529 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4530 		e.error = nfs4_validate_caches(vp, cr);
4531 		if (e.error)
4532 			return (e.error);
4533 		mutex_enter(&rp->r_statelock);
4534 		if (rp->r_symlink.contents != NULL) {
4535 			e.error = uiomove(rp->r_symlink.contents,
4536 			    rp->r_symlink.len, UIO_READ, uiop);
4537 			mutex_exit(&rp->r_statelock);
4538 			return (e.error);
4539 		}
4540 		mutex_exit(&rp->r_statelock);
4541 	}
4542 	recov_state.rs_flags = 0;
4543 	recov_state.rs_num_retry_despite_err = 0;
4544 
4545 recov_retry:
4546 	args.array_len = 3;
4547 	args.array = argop;
4548 	args.ctag = TAG_READLINK;
4549 
4550 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4551 	if (e.error) {
4552 		return (e.error);
4553 	}
4554 
4555 	/* 0. putfh symlink fh */
4556 	argop[0].argop = OP_CPUTFH;
4557 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4558 
4559 	/* 1. readlink */
4560 	argop[1].argop = OP_READLINK;
4561 
4562 	/* 2. getattr */
4563 	argop[2].argop = OP_GETATTR;
4564 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4565 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4566 
4567 	doqueue = 1;
4568 
4569 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4570 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4571 	    rnode4info(VTOR4(vp))));
4572 
4573 	t = gethrtime();
4574 
4575 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4576 
4577 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4578 	if (needrecov) {
4579 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4580 		    "nfs4_readlink: initiating recovery\n"));
4581 
4582 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4583 		    NULL, OP_READLINK, NULL, NULL, NULL) == FALSE) {
4584 			if (!e.error)
4585 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4586 				    (caddr_t)&res);
4587 
4588 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4589 			    needrecov);
4590 			goto recov_retry;
4591 		}
4592 	}
4593 
4594 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4595 
4596 	if (e.error)
4597 		return (e.error);
4598 
4599 	/*
4600 	 * There is an path in the code below which calls
4601 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4602 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4603 	 * here to avoid nfs4_start_op() deadlock.
4604 	 */
4605 
4606 	if (res.status && (res.array_len < args.array_len)) {
4607 		/*
4608 		 * either Putfh or Link failed
4609 		 */
4610 		e.error = geterrno4(res.status);
4611 		nfs4_purge_stale_fh(e.error, vp, cr);
4612 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4613 		return (e.error);
4614 	}
4615 
4616 	resop = &res.array[1];	/* readlink res */
4617 	lr_res = &resop->nfs_resop4_u.opreadlink;
4618 
4619 	/*
4620 	 * treat symlink names as data
4621 	 */
4622 	linkdata = utf8_to_str((utf8string *)&lr_res->link, &len, NULL);
4623 	if (linkdata != NULL) {
4624 		int uio_len = len - 1;
4625 		/* len includes null byte, which we won't uiomove */
4626 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4627 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4628 			mutex_enter(&rp->r_statelock);
4629 			if (rp->r_symlink.contents == NULL) {
4630 				rp->r_symlink.contents = linkdata;
4631 				rp->r_symlink.len = uio_len;
4632 				rp->r_symlink.size = len;
4633 				mutex_exit(&rp->r_statelock);
4634 			} else {
4635 				mutex_exit(&rp->r_statelock);
4636 				kmem_free(linkdata, len);
4637 			}
4638 		} else {
4639 			kmem_free(linkdata, len);
4640 		}
4641 	}
4642 	if (res.status == NFS4_OK) {
4643 		resop++;	/* getattr res */
4644 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4645 	}
4646 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4647 
4648 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4649 
4650 	/*
4651 	 * The over the wire error for attempting to readlink something
4652 	 * other than a symbolic link is ENXIO.  However, we need to
4653 	 * return EINVAL instead of ENXIO, so we map it here.
4654 	 */
4655 	return (e.error == ENXIO ? EINVAL : e.error);
4656 }
4657 
4658 /*
4659  * Flush local dirty pages to stable storage on the server.
4660  *
4661  * If FNODSYNC is specified, then there is nothing to do because
4662  * metadata changes are not cached on the client before being
4663  * sent to the server.
4664  */
4665 /* ARGSUSED */
4666 static int
4667 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
4668 {
4669 	int error;
4670 
4671 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4672 		return (0);
4673 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4674 		return (EIO);
4675 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4676 	if (!error)
4677 		error = VTOR4(vp)->r_error;
4678 	return (error);
4679 }
4680 
4681 /*
4682  * Weirdness: if the file was removed or the target of a rename
4683  * operation while it was open, it got renamed instead.  Here we
4684  * remove the renamed file.
4685  */
4686 /* ARGSUSED */
4687 void
4688 nfs4_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4689 {
4690 	rnode4_t *rp;
4691 
4692 	ASSERT(vp != DNLC_NO_VNODE);
4693 
4694 	rp = VTOR4(vp);
4695 
4696 	if (IS_SHADOW(vp, rp)) {
4697 		sv_inactive(vp);
4698 		return;
4699 	}
4700 
4701 	/*
4702 	 * If this is coming from the wrong zone, we let someone in the right
4703 	 * zone take care of it asynchronously.  We can get here due to
4704 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4705 	 * potentially turn into an expensive no-op if, for instance, v_count
4706 	 * gets incremented in the meantime, but it's still correct.
4707 	 */
4708 	if (nfs_zone() != VTOMI4(vp)->mi_zone) {
4709 		nfs4_async_inactive(vp, cr);
4710 		return;
4711 	}
4712 
4713 	/*
4714 	 * Some of the cleanup steps might require over-the-wire
4715 	 * operations.  Since VOP_INACTIVE can get called as a result of
4716 	 * other over-the-wire operations (e.g., an attribute cache update
4717 	 * can lead to a DNLC purge), doing those steps now would lead to a
4718 	 * nested call to the recovery framework, which can deadlock.  So
4719 	 * do any over-the-wire cleanups asynchronously, in a separate
4720 	 * thread.
4721 	 */
4722 
4723 	mutex_enter(&rp->r_os_lock);
4724 	mutex_enter(&rp->r_statelock);
4725 	mutex_enter(&rp->r_statev4_lock);
4726 
4727 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4728 		mutex_exit(&rp->r_statev4_lock);
4729 		mutex_exit(&rp->r_statelock);
4730 		mutex_exit(&rp->r_os_lock);
4731 		nfs4_async_inactive(vp, cr);
4732 		return;
4733 	}
4734 
4735 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4736 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4737 		mutex_exit(&rp->r_statev4_lock);
4738 		mutex_exit(&rp->r_statelock);
4739 		mutex_exit(&rp->r_os_lock);
4740 		nfs4_async_inactive(vp, cr);
4741 		return;
4742 	}
4743 
4744 	if (rp->r_unldvp != NULL) {
4745 		mutex_exit(&rp->r_statev4_lock);
4746 		mutex_exit(&rp->r_statelock);
4747 		mutex_exit(&rp->r_os_lock);
4748 		nfs4_async_inactive(vp, cr);
4749 		return;
4750 	}
4751 	mutex_exit(&rp->r_statev4_lock);
4752 	mutex_exit(&rp->r_statelock);
4753 	mutex_exit(&rp->r_os_lock);
4754 
4755 	rp4_addfree(rp, cr);
4756 }
4757 
4758 /*
4759  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4760  * various bits of state.  The caller must not refer to vp after this call.
4761  */
4762 
4763 void
4764 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4765 {
4766 	rnode4_t *rp = VTOR4(vp);
4767 	nfs4_recov_state_t recov_state;
4768 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4769 	vnode_t *unldvp;
4770 	char *unlname;
4771 	cred_t *unlcred;
4772 	COMPOUND4args_clnt args;
4773 	COMPOUND4res_clnt res, *resp;
4774 	nfs_argop4 argop[2];
4775 	int doqueue;
4776 #ifdef DEBUG
4777 	char *name;
4778 #endif
4779 
4780 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
4781 	ASSERT(!IS_SHADOW(vp, rp));
4782 
4783 #ifdef DEBUG
4784 	name = fn_name(VTOSV(vp)->sv_name);
4785 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4786 	    "release vnode %s", name));
4787 	kmem_free(name, MAXNAMELEN);
4788 #endif
4789 
4790 	if (vp->v_type == VREG) {
4791 		bool_t recov_failed = FALSE;
4792 
4793 		e.error = nfs4close_all(vp, cr);
4794 		if (e.error) {
4795 			/* Check to see if recovery failed */
4796 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4797 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4798 				recov_failed = TRUE;
4799 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4800 			if (!recov_failed) {
4801 				mutex_enter(&rp->r_statelock);
4802 				if (rp->r_flags & R4RECOVERR)
4803 					recov_failed = TRUE;
4804 				mutex_exit(&rp->r_statelock);
4805 			}
4806 			if (recov_failed) {
4807 				NFS4_DEBUG(nfs4_client_recov_debug,
4808 				    (CE_NOTE, "nfs4_inactive_otw: "
4809 				    "close failed (recovery failure)"));
4810 			}
4811 		}
4812 	}
4813 
4814 redo:
4815 	if (rp->r_unldvp == NULL) {
4816 		rp4_addfree(rp, cr);
4817 		return;
4818 	}
4819 
4820 	/*
4821 	 * Save the vnode pointer for the directory where the
4822 	 * unlinked-open file got renamed, then set it to NULL
4823 	 * to prevent another thread from getting here before
4824 	 * we're done with the remove.  While we have the
4825 	 * statelock, make local copies of the pertinent rnode
4826 	 * fields.  If we weren't to do this in an atomic way, the
4827 	 * the unl* fields could become inconsistent with respect
4828 	 * to each other due to a race condition between this
4829 	 * code and nfs_remove().  See bug report 1034328.
4830 	 */
4831 	mutex_enter(&rp->r_statelock);
4832 	if (rp->r_unldvp == NULL) {
4833 		mutex_exit(&rp->r_statelock);
4834 		rp4_addfree(rp, cr);
4835 		return;
4836 	}
4837 
4838 	unldvp = rp->r_unldvp;
4839 	rp->r_unldvp = NULL;
4840 	unlname = rp->r_unlname;
4841 	rp->r_unlname = NULL;
4842 	unlcred = rp->r_unlcred;
4843 	rp->r_unlcred = NULL;
4844 	mutex_exit(&rp->r_statelock);
4845 
4846 	/*
4847 	 * If there are any dirty pages left, then flush
4848 	 * them.  This is unfortunate because they just
4849 	 * may get thrown away during the remove operation,
4850 	 * but we have to do this for correctness.
4851 	 */
4852 	if (nfs4_has_pages(vp) &&
4853 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4854 		ASSERT(vp->v_type != VCHR);
4855 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, NULL);
4856 		if (e.error) {
4857 			mutex_enter(&rp->r_statelock);
4858 			if (!rp->r_error)
4859 				rp->r_error = e.error;
4860 			mutex_exit(&rp->r_statelock);
4861 		}
4862 	}
4863 
4864 	recov_state.rs_flags = 0;
4865 	recov_state.rs_num_retry_despite_err = 0;
4866 recov_retry_remove:
4867 	/*
4868 	 * Do the remove operation on the renamed file
4869 	 */
4870 	args.ctag = TAG_INACTIVE;
4871 
4872 	/*
4873 	 * Remove ops: putfh dir; remove
4874 	 */
4875 	args.array_len = 2;
4876 	args.array = argop;
4877 
4878 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4879 	if (e.error) {
4880 		kmem_free(unlname, MAXNAMELEN);
4881 		crfree(unlcred);
4882 		VN_RELE(unldvp);
4883 		/*
4884 		 * Try again; this time around r_unldvp will be NULL, so we'll
4885 		 * just call rp4_addfree() and return.
4886 		 */
4887 		goto redo;
4888 	}
4889 
4890 	/* putfh directory */
4891 	argop[0].argop = OP_CPUTFH;
4892 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4893 
4894 	/* remove */
4895 	argop[1].argop = OP_CREMOVE;
4896 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4897 
4898 	doqueue = 1;
4899 	resp = &res;
4900 
4901 #if 0 /* notyet */
4902 	/*
4903 	 * Can't do this yet.  We may be being called from
4904 	 * dnlc_purge_XXX while that routine is holding a
4905 	 * mutex lock to the nc_rele list.  The calls to
4906 	 * nfs3_cache_wcc_data may result in calls to
4907 	 * dnlc_purge_XXX.  This will result in a deadlock.
4908 	 */
4909 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4910 	if (e.error) {
4911 		PURGE_ATTRCACHE4(unldvp);
4912 		resp = NULL;
4913 	} else if (res.status) {
4914 		e.error = geterrno4(res.status);
4915 		PURGE_ATTRCACHE4(unldvp);
4916 		/*
4917 		 * This code is inactive right now
4918 		 * but if made active there should
4919 		 * be a nfs4_end_op() call before
4920 		 * nfs4_purge_stale_fh to avoid start_op()
4921 		 * deadlock. See BugId: 4948726
4922 		 */
4923 		nfs4_purge_stale_fh(error, unldvp, cr);
4924 	} else {
4925 		nfs_resop4 *resop;
4926 		REMOVE4res *rm_res;
4927 
4928 		resop = &res.array[1];
4929 		rm_res = &resop->nfs_resop4_u.opremove;
4930 		/*
4931 		 * Update directory cache attribute,
4932 		 * readdir and dnlc caches.
4933 		 */
4934 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4935 	}
4936 #else
4937 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4938 
4939 	PURGE_ATTRCACHE4(unldvp);
4940 #endif
4941 
4942 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4943 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4944 		    NULL, NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
4945 			if (!e.error)
4946 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4947 				    (caddr_t)&res);
4948 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4949 			    &recov_state, TRUE);
4950 			goto recov_retry_remove;
4951 		}
4952 	}
4953 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4954 
4955 	/*
4956 	 * Release stuff held for the remove
4957 	 */
4958 	VN_RELE(unldvp);
4959 	if (!e.error && resp)
4960 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4961 
4962 	kmem_free(unlname, MAXNAMELEN);
4963 	crfree(unlcred);
4964 	goto redo;
4965 }
4966 
4967 /*
4968  * Remote file system operations having to do with directory manipulation.
4969  */
4970 /* ARGSUSED3 */
4971 int
4972 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4973     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
4974     int *direntflags, pathname_t *realpnp)
4975 {
4976 	int error;
4977 	vnode_t *vp, *avp = NULL;
4978 	rnode4_t *drp;
4979 
4980 	*vpp = NULL;
4981 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4982 		return (EPERM);
4983 	/*
4984 	 * if LOOKUP_XATTR, must replace dvp (object) with
4985 	 * object's attrdir before continuing with lookup
4986 	 */
4987 	if (flags & LOOKUP_XATTR) {
4988 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4989 		if (error)
4990 			return (error);
4991 
4992 		dvp = avp;
4993 
4994 		/*
4995 		 * If lookup is for "", just return dvp now.  The attrdir
4996 		 * has already been activated (from nfs4lookup_xattr), and
4997 		 * the caller will RELE the original dvp -- not
4998 		 * the attrdir.  So, set vpp and return.
4999 		 * Currently, when the LOOKUP_XATTR flag is
5000 		 * passed to VOP_LOOKUP, the name is always empty, and
5001 		 * shortcircuiting here avoids 3 unneeded lock/unlock
5002 		 * pairs.
5003 		 *
5004 		 * If a non-empty name was provided, then it is the
5005 		 * attribute name, and it will be looked up below.
5006 		 */
5007 		if (*nm == '\0') {
5008 			*vpp = dvp;
5009 			return (0);
5010 		}
5011 
5012 		/*
5013 		 * The vfs layer never sends a name when asking for the
5014 		 * attrdir, so we should never get here (unless of course
5015 		 * name is passed at some time in future -- at which time
5016 		 * we'll blow up here).
5017 		 */
5018 		ASSERT(0);
5019 	}
5020 
5021 	drp = VTOR4(dvp);
5022 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
5023 		return (EINTR);
5024 
5025 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
5026 	nfs_rw_exit(&drp->r_rwlock);
5027 
5028 	/*
5029 	 * If vnode is a device, create special vnode.
5030 	 */
5031 	if (!error && ISVDEV((*vpp)->v_type)) {
5032 		vp = *vpp;
5033 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
5034 		VN_RELE(vp);
5035 	}
5036 
5037 	return (error);
5038 }
5039 
5040 /* ARGSUSED */
5041 static int
5042 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
5043 {
5044 	int error;
5045 	rnode4_t *drp;
5046 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
5047 	mntinfo4_t *mi;
5048 
5049 	mi = VTOMI4(dvp);
5050 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR) &&
5051 	    !vfs_has_feature(mi->mi_vfsp, VFSFT_SYSATTR_VIEWS))
5052 		return (EINVAL);
5053 
5054 	drp = VTOR4(dvp);
5055 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
5056 		return (EINTR);
5057 
5058 	mutex_enter(&drp->r_statelock);
5059 	/*
5060 	 * If the server doesn't support xattrs just return EINVAL
5061 	 */
5062 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
5063 		mutex_exit(&drp->r_statelock);
5064 		nfs_rw_exit(&drp->r_rwlock);
5065 		return (EINVAL);
5066 	}
5067 
5068 	/*
5069 	 * If there is a cached xattr directory entry,
5070 	 * use it as long as the attributes are valid. If the
5071 	 * attributes are not valid, take the simple approach and
5072 	 * free the cached value and re-fetch a new value.
5073 	 *
5074 	 * We don't negative entry cache for now, if we did we
5075 	 * would need to check if the file has changed on every
5076 	 * lookup. But xattrs don't exist very often and failing
5077 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
5078 	 * so do an openattr over the wire for now.
5079 	 */
5080 	if (drp->r_xattr_dir != NULL) {
5081 		if (ATTRCACHE4_VALID(dvp)) {
5082 			VN_HOLD(drp->r_xattr_dir);
5083 			*vpp = drp->r_xattr_dir;
5084 			mutex_exit(&drp->r_statelock);
5085 			nfs_rw_exit(&drp->r_rwlock);
5086 			return (0);
5087 		}
5088 		VN_RELE(drp->r_xattr_dir);
5089 		drp->r_xattr_dir = NULL;
5090 	}
5091 	mutex_exit(&drp->r_statelock);
5092 
5093 	error = nfs4openattr(dvp, vpp, cflag, cr);
5094 
5095 	nfs_rw_exit(&drp->r_rwlock);
5096 
5097 	return (error);
5098 }
5099 
5100 static int
5101 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
5102 {
5103 	int error;
5104 	rnode4_t *drp;
5105 
5106 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5107 
5108 	/*
5109 	 * If lookup is for "", just return dvp.  Don't need
5110 	 * to send it over the wire, look it up in the dnlc,
5111 	 * or perform any access checks.
5112 	 */
5113 	if (*nm == '\0') {
5114 		VN_HOLD(dvp);
5115 		*vpp = dvp;
5116 		return (0);
5117 	}
5118 
5119 	/*
5120 	 * Can't do lookups in non-directories.
5121 	 */
5122 	if (dvp->v_type != VDIR)
5123 		return (ENOTDIR);
5124 
5125 	/*
5126 	 * If lookup is for ".", just return dvp.  Don't need
5127 	 * to send it over the wire or look it up in the dnlc,
5128 	 * just need to check access.
5129 	 */
5130 	if (nm[0] == '.' && nm[1] == '\0') {
5131 		error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5132 		if (error)
5133 			return (error);
5134 		VN_HOLD(dvp);
5135 		*vpp = dvp;
5136 		return (0);
5137 	}
5138 
5139 	drp = VTOR4(dvp);
5140 	if (!(drp->r_flags & R4LOOKUP)) {
5141 		mutex_enter(&drp->r_statelock);
5142 		drp->r_flags |= R4LOOKUP;
5143 		mutex_exit(&drp->r_statelock);
5144 	}
5145 
5146 	*vpp = NULL;
5147 	/*
5148 	 * Lookup this name in the DNLC.  If there is no entry
5149 	 * lookup over the wire.
5150 	 */
5151 	if (!skipdnlc)
5152 		*vpp = dnlc_lookup(dvp, nm);
5153 	if (*vpp == NULL) {
5154 		/*
5155 		 * We need to go over the wire to lookup the name.
5156 		 */
5157 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
5158 	}
5159 
5160 	/*
5161 	 * We hit on the dnlc
5162 	 */
5163 	if (*vpp != DNLC_NO_VNODE ||
5164 	    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
5165 		/*
5166 		 * But our attrs may not be valid.
5167 		 */
5168 		if (ATTRCACHE4_VALID(dvp)) {
5169 			error = nfs4_waitfor_purge_complete(dvp);
5170 			if (error) {
5171 				VN_RELE(*vpp);
5172 				*vpp = NULL;
5173 				return (error);
5174 			}
5175 
5176 			/*
5177 			 * If after the purge completes, check to make sure
5178 			 * our attrs are still valid.
5179 			 */
5180 			if (ATTRCACHE4_VALID(dvp)) {
5181 				/*
5182 				 * If we waited for a purge we may have
5183 				 * lost our vnode so look it up again.
5184 				 */
5185 				VN_RELE(*vpp);
5186 				*vpp = dnlc_lookup(dvp, nm);
5187 				if (*vpp == NULL)
5188 					return (nfs4lookupnew_otw(dvp,
5189 					    nm, vpp, cr));
5190 
5191 				/*
5192 				 * The access cache should almost always hit
5193 				 */
5194 				error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5195 
5196 				if (error) {
5197 					VN_RELE(*vpp);
5198 					*vpp = NULL;
5199 					return (error);
5200 				}
5201 				if (*vpp == DNLC_NO_VNODE) {
5202 					VN_RELE(*vpp);
5203 					*vpp = NULL;
5204 					return (ENOENT);
5205 				}
5206 				return (0);
5207 			}
5208 		}
5209 	}
5210 
5211 	ASSERT(*vpp != NULL);
5212 
5213 	/*
5214 	 * We may have gotten here we have one of the following cases:
5215 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5216 	 *		need to validate them.
5217 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5218 	 *		must validate.
5219 	 *
5220 	 * Go to the server and check if the directory has changed, if
5221 	 * it hasn't we are done and can use the dnlc entry.
5222 	 */
5223 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5224 }
5225 
5226 /*
5227  * Go to the server and check if the directory has changed, if
5228  * it hasn't we are done and can use the dnlc entry.  If it
5229  * has changed we get a new copy of its attributes and check
5230  * the access for VEXEC, then relookup the filename and
5231  * get its filehandle and attributes.
5232  *
5233  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5234  *	if the NVERIFY failed we must
5235  *		purge the caches
5236  *		cache new attributes (will set r_time_attr_inval)
5237  *		cache new access
5238  *		recheck VEXEC access
5239  *		add name to dnlc, possibly negative
5240  *		if LOOKUP succeeded
5241  *			cache new attributes
5242  *	else
5243  *		set a new r_time_attr_inval for dvp
5244  *		check to make sure we have access
5245  *
5246  * The vpp returned is the vnode passed in if the directory is valid,
5247  * a new vnode if successful lookup, or NULL on error.
5248  */
5249 static int
5250 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5251 {
5252 	COMPOUND4args_clnt args;
5253 	COMPOUND4res_clnt res;
5254 	fattr4 *ver_fattr;
5255 	fattr4_change dchange;
5256 	int32_t *ptr;
5257 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5258 	nfs_argop4 *argop;
5259 	int doqueue;
5260 	mntinfo4_t *mi;
5261 	nfs4_recov_state_t recov_state;
5262 	hrtime_t t;
5263 	int isdotdot;
5264 	vnode_t *nvp;
5265 	nfs_fh4 *fhp;
5266 	nfs4_sharedfh_t *sfhp;
5267 	nfs4_access_type_t cacc;
5268 	rnode4_t *nrp;
5269 	rnode4_t *drp = VTOR4(dvp);
5270 	nfs4_ga_res_t *garp = NULL;
5271 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5272 
5273 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5274 	ASSERT(nm != NULL);
5275 	ASSERT(nm[0] != '\0');
5276 	ASSERT(dvp->v_type == VDIR);
5277 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5278 	ASSERT(*vpp != NULL);
5279 
5280 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5281 		isdotdot = 1;
5282 		args.ctag = TAG_LOOKUP_VPARENT;
5283 	} else {
5284 		/*
5285 		 * If dvp were a stub, it should have triggered and caused
5286 		 * a mount for us to get this far.
5287 		 */
5288 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5289 
5290 		isdotdot = 0;
5291 		args.ctag = TAG_LOOKUP_VALID;
5292 	}
5293 
5294 	mi = VTOMI4(dvp);
5295 	recov_state.rs_flags = 0;
5296 	recov_state.rs_num_retry_despite_err = 0;
5297 
5298 	nvp = NULL;
5299 
5300 	/* Save the original mount point security information */
5301 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5302 
5303 recov_retry:
5304 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5305 	    &recov_state, NULL);
5306 	if (e.error) {
5307 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5308 		VN_RELE(*vpp);
5309 		*vpp = NULL;
5310 		return (e.error);
5311 	}
5312 
5313 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5314 
5315 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5316 	args.array_len = 7;
5317 	args.array = argop;
5318 
5319 	/* 0. putfh file */
5320 	argop[0].argop = OP_CPUTFH;
5321 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5322 
5323 	/* 1. nverify the change info */
5324 	argop[1].argop = OP_NVERIFY;
5325 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5326 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5327 	ver_fattr->attrlist4 = (char *)&dchange;
5328 	ptr = (int32_t *)&dchange;
5329 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5330 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5331 
5332 	/* 2. getattr directory */
5333 	argop[2].argop = OP_GETATTR;
5334 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5335 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5336 
5337 	/* 3. access directory */
5338 	argop[3].argop = OP_ACCESS;
5339 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5340 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5341 
5342 	/* 4. lookup name */
5343 	if (isdotdot) {
5344 		argop[4].argop = OP_LOOKUPP;
5345 	} else {
5346 		argop[4].argop = OP_CLOOKUP;
5347 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5348 	}
5349 
5350 	/* 5. resulting file handle */
5351 	argop[5].argop = OP_GETFH;
5352 
5353 	/* 6. resulting file attributes */
5354 	argop[6].argop = OP_GETATTR;
5355 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5356 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5357 
5358 	doqueue = 1;
5359 	t = gethrtime();
5360 
5361 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5362 
5363 	if (!isdotdot && res.status == NFS4ERR_MOVED) {
5364 		e.error = nfs4_setup_referral(dvp, nm, vpp, cr);
5365 		if (e.error != 0 && *vpp != NULL)
5366 			VN_RELE(*vpp);
5367 		nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5368 		    &recov_state, FALSE);
5369 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5370 		kmem_free(argop, argoplist_size);
5371 		return (e.error);
5372 	}
5373 
5374 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5375 		/*
5376 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5377 		 * from this thread, do not go thru the recovery thread since
5378 		 * we need the nm information.
5379 		 *
5380 		 * Not doing dotdot case because there is no specification
5381 		 * for (PUTFH, SECINFO "..") yet.
5382 		 */
5383 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5384 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5385 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5386 				    &recov_state, FALSE);
5387 			else
5388 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5389 				    &recov_state, TRUE);
5390 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5391 			kmem_free(argop, argoplist_size);
5392 			if (!e.error)
5393 				goto recov_retry;
5394 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5395 			VN_RELE(*vpp);
5396 			*vpp = NULL;
5397 			return (e.error);
5398 		}
5399 
5400 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5401 		    OP_LOOKUP, NULL, NULL, NULL) == FALSE) {
5402 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5403 			    &recov_state, TRUE);
5404 
5405 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5406 			kmem_free(argop, argoplist_size);
5407 			goto recov_retry;
5408 		}
5409 	}
5410 
5411 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5412 
5413 	if (e.error || res.array_len == 0) {
5414 		/*
5415 		 * If e.error isn't set, then reply has no ops (or we couldn't
5416 		 * be here).  The only legal way to reply without an op array
5417 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5418 		 * be in the reply for all other status values.
5419 		 *
5420 		 * For valid replies without an ops array, return ENOTSUP
5421 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5422 		 * return EIO -- don't trust status.
5423 		 */
5424 		if (e.error == 0)
5425 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5426 			    ENOTSUP : EIO;
5427 		VN_RELE(*vpp);
5428 		*vpp = NULL;
5429 		kmem_free(argop, argoplist_size);
5430 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5431 		return (e.error);
5432 	}
5433 
5434 	if (res.status != NFS4ERR_SAME) {
5435 		e.error = geterrno4(res.status);
5436 
5437 		/*
5438 		 * The NVERIFY "failed" so the directory has changed
5439 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5440 		 * cleanly.
5441 		 */
5442 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5443 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5444 			nfs4_purge_stale_fh(e.error, dvp, cr);
5445 			VN_RELE(*vpp);
5446 			*vpp = NULL;
5447 			goto exit;
5448 		}
5449 
5450 		/*
5451 		 * We know the NVERIFY "failed" so we must:
5452 		 *	purge the caches (access and indirectly dnlc if needed)
5453 		 */
5454 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5455 
5456 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5457 			nfs4_purge_stale_fh(e.error, dvp, cr);
5458 			VN_RELE(*vpp);
5459 			*vpp = NULL;
5460 			goto exit;
5461 		}
5462 
5463 		/*
5464 		 * Install new cached attributes for the directory
5465 		 */
5466 		nfs4_attr_cache(dvp,
5467 		    &res.array[2].nfs_resop4_u.opgetattr.ga_res,
5468 		    t, cr, FALSE, NULL);
5469 
5470 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5471 			nfs4_purge_stale_fh(e.error, dvp, cr);
5472 			VN_RELE(*vpp);
5473 			*vpp = NULL;
5474 			e.error = geterrno4(res.status);
5475 			goto exit;
5476 		}
5477 
5478 		/*
5479 		 * Now we know the directory is valid,
5480 		 * cache new directory access
5481 		 */
5482 		nfs4_access_cache(drp,
5483 		    args.array[3].nfs_argop4_u.opaccess.access,
5484 		    res.array[3].nfs_resop4_u.opaccess.access, cr);
5485 
5486 		/*
5487 		 * recheck VEXEC access
5488 		 */
5489 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5490 		if (cacc != NFS4_ACCESS_ALLOWED) {
5491 			/*
5492 			 * Directory permissions might have been revoked
5493 			 */
5494 			if (cacc == NFS4_ACCESS_DENIED) {
5495 				e.error = EACCES;
5496 				VN_RELE(*vpp);
5497 				*vpp = NULL;
5498 				goto exit;
5499 			}
5500 
5501 			/*
5502 			 * Somehow we must not have asked for enough
5503 			 * so try a singleton ACCESS, should never happen.
5504 			 */
5505 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5506 			if (e.error) {
5507 				VN_RELE(*vpp);
5508 				*vpp = NULL;
5509 				goto exit;
5510 			}
5511 		}
5512 
5513 		e.error = geterrno4(res.status);
5514 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5515 			/*
5516 			 * The lookup failed, probably no entry
5517 			 */
5518 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5519 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5520 			} else {
5521 				/*
5522 				 * Might be some other error, so remove
5523 				 * the dnlc entry to make sure we start all
5524 				 * over again, next time.
5525 				 */
5526 				dnlc_remove(dvp, nm);
5527 			}
5528 			VN_RELE(*vpp);
5529 			*vpp = NULL;
5530 			goto exit;
5531 		}
5532 
5533 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5534 			/*
5535 			 * The file exists but we can't get its fh for
5536 			 * some unknown reason.  Remove it from the dnlc
5537 			 * and error out to be safe.
5538 			 */
5539 			dnlc_remove(dvp, nm);
5540 			VN_RELE(*vpp);
5541 			*vpp = NULL;
5542 			goto exit;
5543 		}
5544 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5545 		if (fhp->nfs_fh4_len == 0) {
5546 			/*
5547 			 * The file exists but a bogus fh
5548 			 * some unknown reason.  Remove it from the dnlc
5549 			 * and error out to be safe.
5550 			 */
5551 			e.error = ENOENT;
5552 			dnlc_remove(dvp, nm);
5553 			VN_RELE(*vpp);
5554 			*vpp = NULL;
5555 			goto exit;
5556 		}
5557 		sfhp = sfh4_get(fhp, mi);
5558 
5559 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5560 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5561 
5562 		/*
5563 		 * Make the new rnode
5564 		 */
5565 		if (isdotdot) {
5566 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5567 			if (e.error) {
5568 				sfh4_rele(&sfhp);
5569 				VN_RELE(*vpp);
5570 				*vpp = NULL;
5571 				goto exit;
5572 			}
5573 			/*
5574 			 * XXX if nfs4_make_dotdot uses an existing rnode
5575 			 * XXX it doesn't update the attributes.
5576 			 * XXX for now just save them again to save an OTW
5577 			 */
5578 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5579 		} else {
5580 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5581 			    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
5582 			/*
5583 			 * If v_type == VNON, then garp was NULL because
5584 			 * the last op in the compound failed and makenfs4node
5585 			 * could not find the vnode for sfhp. It created
5586 			 * a new vnode, so we have nothing to purge here.
5587 			 */
5588 			if (nvp->v_type == VNON) {
5589 				vattr_t vattr;
5590 
5591 				vattr.va_mask = AT_TYPE;
5592 				/*
5593 				 * N.B. We've already called nfs4_end_fop above.
5594 				 */
5595 				e.error = nfs4getattr(nvp, &vattr, cr);
5596 				if (e.error) {
5597 					sfh4_rele(&sfhp);
5598 					VN_RELE(*vpp);
5599 					*vpp = NULL;
5600 					VN_RELE(nvp);
5601 					goto exit;
5602 				}
5603 				nvp->v_type = vattr.va_type;
5604 			}
5605 		}
5606 		sfh4_rele(&sfhp);
5607 
5608 		nrp = VTOR4(nvp);
5609 		mutex_enter(&nrp->r_statev4_lock);
5610 		if (!nrp->created_v4) {
5611 			mutex_exit(&nrp->r_statev4_lock);
5612 			dnlc_update(dvp, nm, nvp);
5613 		} else
5614 			mutex_exit(&nrp->r_statev4_lock);
5615 
5616 		VN_RELE(*vpp);
5617 		*vpp = nvp;
5618 	} else {
5619 		hrtime_t now;
5620 		hrtime_t delta = 0;
5621 
5622 		e.error = 0;
5623 
5624 		/*
5625 		 * Because the NVERIFY "succeeded" we know that the
5626 		 * directory attributes are still valid
5627 		 * so update r_time_attr_inval
5628 		 */
5629 		now = gethrtime();
5630 		mutex_enter(&drp->r_statelock);
5631 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5632 			delta = now - drp->r_time_attr_saved;
5633 			if (delta < mi->mi_acdirmin)
5634 				delta = mi->mi_acdirmin;
5635 			else if (delta > mi->mi_acdirmax)
5636 				delta = mi->mi_acdirmax;
5637 		}
5638 		drp->r_time_attr_inval = now + delta;
5639 		mutex_exit(&drp->r_statelock);
5640 		dnlc_update(dvp, nm, *vpp);
5641 
5642 		/*
5643 		 * Even though we have a valid directory attr cache
5644 		 * and dnlc entry, we may not have access.
5645 		 * This should almost always hit the cache.
5646 		 */
5647 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5648 		if (e.error) {
5649 			VN_RELE(*vpp);
5650 			*vpp = NULL;
5651 		}
5652 
5653 		if (*vpp == DNLC_NO_VNODE) {
5654 			VN_RELE(*vpp);
5655 			*vpp = NULL;
5656 			e.error = ENOENT;
5657 		}
5658 	}
5659 
5660 exit:
5661 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5662 	kmem_free(argop, argoplist_size);
5663 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5664 	return (e.error);
5665 }
5666 
5667 /*
5668  * We need to go over the wire to lookup the name, but
5669  * while we are there verify the directory has not
5670  * changed but if it has, get new attributes and check access
5671  *
5672  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5673  *					NVERIFY GETATTR ACCESS
5674  *
5675  * With the results:
5676  *	if the NVERIFY failed we must purge the caches, add new attributes,
5677  *		and cache new access.
5678  *	set a new r_time_attr_inval
5679  *	add name to dnlc, possibly negative
5680  *	if LOOKUP succeeded
5681  *		cache new attributes
5682  */
5683 static int
5684 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5685 {
5686 	COMPOUND4args_clnt args;
5687 	COMPOUND4res_clnt res;
5688 	fattr4 *ver_fattr;
5689 	fattr4_change dchange;
5690 	int32_t *ptr;
5691 	nfs4_ga_res_t *garp = NULL;
5692 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5693 	nfs_argop4 *argop;
5694 	int doqueue;
5695 	mntinfo4_t *mi;
5696 	nfs4_recov_state_t recov_state;
5697 	hrtime_t t;
5698 	int isdotdot;
5699 	vnode_t *nvp;
5700 	nfs_fh4 *fhp;
5701 	nfs4_sharedfh_t *sfhp;
5702 	nfs4_access_type_t cacc;
5703 	rnode4_t *nrp;
5704 	rnode4_t *drp = VTOR4(dvp);
5705 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5706 
5707 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5708 	ASSERT(nm != NULL);
5709 	ASSERT(nm[0] != '\0');
5710 	ASSERT(dvp->v_type == VDIR);
5711 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5712 	ASSERT(*vpp == NULL);
5713 
5714 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5715 		isdotdot = 1;
5716 		args.ctag = TAG_LOOKUP_PARENT;
5717 	} else {
5718 		/*
5719 		 * If dvp were a stub, it should have triggered and caused
5720 		 * a mount for us to get this far.
5721 		 */
5722 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5723 
5724 		isdotdot = 0;
5725 		args.ctag = TAG_LOOKUP;
5726 	}
5727 
5728 	mi = VTOMI4(dvp);
5729 	recov_state.rs_flags = 0;
5730 	recov_state.rs_num_retry_despite_err = 0;
5731 
5732 	nvp = NULL;
5733 
5734 	/* Save the original mount point security information */
5735 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5736 
5737 recov_retry:
5738 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5739 	    &recov_state, NULL);
5740 	if (e.error) {
5741 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5742 		return (e.error);
5743 	}
5744 
5745 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5746 
5747 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5748 	args.array_len = 9;
5749 	args.array = argop;
5750 
5751 	/* 0. putfh file */
5752 	argop[0].argop = OP_CPUTFH;
5753 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5754 
5755 	/* 1. savefh for the nverify */
5756 	argop[1].argop = OP_SAVEFH;
5757 
5758 	/* 2. lookup name */
5759 	if (isdotdot) {
5760 		argop[2].argop = OP_LOOKUPP;
5761 	} else {
5762 		argop[2].argop = OP_CLOOKUP;
5763 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5764 	}
5765 
5766 	/* 3. resulting file handle */
5767 	argop[3].argop = OP_GETFH;
5768 
5769 	/* 4. resulting file attributes */
5770 	argop[4].argop = OP_GETATTR;
5771 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5772 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5773 
5774 	/* 5. restorefh back the directory for the nverify */
5775 	argop[5].argop = OP_RESTOREFH;
5776 
5777 	/* 6. nverify the change info */
5778 	argop[6].argop = OP_NVERIFY;
5779 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5780 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5781 	ver_fattr->attrlist4 = (char *)&dchange;
5782 	ptr = (int32_t *)&dchange;
5783 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5784 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5785 
5786 	/* 7. getattr directory */
5787 	argop[7].argop = OP_GETATTR;
5788 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5789 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5790 
5791 	/* 8. access directory */
5792 	argop[8].argop = OP_ACCESS;
5793 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5794 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5795 
5796 	doqueue = 1;
5797 	t = gethrtime();
5798 
5799 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5800 
5801 	if (!isdotdot && res.status == NFS4ERR_MOVED) {
5802 		e.error = nfs4_setup_referral(dvp, nm, vpp, cr);
5803 		if (e.error != 0 && *vpp != NULL)
5804 			VN_RELE(*vpp);
5805 		nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5806 		    &recov_state, FALSE);
5807 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5808 		kmem_free(argop, argoplist_size);
5809 		return (e.error);
5810 	}
5811 
5812 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5813 		/*
5814 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5815 		 * from this thread, do not go thru the recovery thread since
5816 		 * we need the nm information.
5817 		 *
5818 		 * Not doing dotdot case because there is no specification
5819 		 * for (PUTFH, SECINFO "..") yet.
5820 		 */
5821 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5822 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5823 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5824 				    &recov_state, FALSE);
5825 			else
5826 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5827 				    &recov_state, TRUE);
5828 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5829 			kmem_free(argop, argoplist_size);
5830 			if (!e.error)
5831 				goto recov_retry;
5832 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5833 			return (e.error);
5834 		}
5835 
5836 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5837 		    OP_LOOKUP, NULL, NULL, NULL) == FALSE) {
5838 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5839 			    &recov_state, TRUE);
5840 
5841 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5842 			kmem_free(argop, argoplist_size);
5843 			goto recov_retry;
5844 		}
5845 	}
5846 
5847 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5848 
5849 	if (e.error || res.array_len == 0) {
5850 		/*
5851 		 * If e.error isn't set, then reply has no ops (or we couldn't
5852 		 * be here).  The only legal way to reply without an op array
5853 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5854 		 * be in the reply for all other status values.
5855 		 *
5856 		 * For valid replies without an ops array, return ENOTSUP
5857 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5858 		 * return EIO -- don't trust status.
5859 		 */
5860 		if (e.error == 0)
5861 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5862 			    ENOTSUP : EIO;
5863 
5864 		kmem_free(argop, argoplist_size);
5865 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5866 		return (e.error);
5867 	}
5868 
5869 	e.error = geterrno4(res.status);
5870 
5871 	/*
5872 	 * The PUTFH and SAVEFH may have failed.
5873 	 */
5874 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5875 	    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5876 		nfs4_purge_stale_fh(e.error, dvp, cr);
5877 		goto exit;
5878 	}
5879 
5880 	/*
5881 	 * Check if the file exists, if it does delay entering
5882 	 * into the dnlc until after we update the directory
5883 	 * attributes so we don't cause it to get purged immediately.
5884 	 */
5885 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5886 		/*
5887 		 * The lookup failed, probably no entry
5888 		 */
5889 		if (e.error == ENOENT && nfs4_lookup_neg_cache)
5890 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5891 		goto exit;
5892 	}
5893 
5894 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5895 		/*
5896 		 * The file exists but we can't get its fh for
5897 		 * some unknown reason. Error out to be safe.
5898 		 */
5899 		goto exit;
5900 	}
5901 
5902 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5903 	if (fhp->nfs_fh4_len == 0) {
5904 		/*
5905 		 * The file exists but a bogus fh
5906 		 * some unknown reason.  Error out to be safe.
5907 		 */
5908 		e.error = EIO;
5909 		goto exit;
5910 	}
5911 	sfhp = sfh4_get(fhp, mi);
5912 
5913 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5914 		sfh4_rele(&sfhp);
5915 		goto exit;
5916 	}
5917 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5918 
5919 	/*
5920 	 * The RESTOREFH may have failed
5921 	 */
5922 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5923 		sfh4_rele(&sfhp);
5924 		e.error = EIO;
5925 		goto exit;
5926 	}
5927 
5928 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5929 		/*
5930 		 * First make sure the NVERIFY failed as we expected,
5931 		 * if it didn't then be conservative and error out
5932 		 * as we can't trust the directory.
5933 		 */
5934 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5935 			sfh4_rele(&sfhp);
5936 			e.error = EIO;
5937 			goto exit;
5938 		}
5939 
5940 		/*
5941 		 * We know the NVERIFY "failed" so the directory has changed,
5942 		 * so we must:
5943 		 *	purge the caches (access and indirectly dnlc if needed)
5944 		 */
5945 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5946 
5947 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5948 			sfh4_rele(&sfhp);
5949 			goto exit;
5950 		}
5951 		nfs4_attr_cache(dvp,
5952 		    &res.array[7].nfs_resop4_u.opgetattr.ga_res,
5953 		    t, cr, FALSE, NULL);
5954 
5955 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5956 			nfs4_purge_stale_fh(e.error, dvp, cr);
5957 			sfh4_rele(&sfhp);
5958 			e.error = geterrno4(res.status);
5959 			goto exit;
5960 		}
5961 
5962 		/*
5963 		 * Now we know the directory is valid,
5964 		 * cache new directory access
5965 		 */
5966 		nfs4_access_cache(drp,
5967 		    args.array[8].nfs_argop4_u.opaccess.access,
5968 		    res.array[8].nfs_resop4_u.opaccess.access, cr);
5969 
5970 		/*
5971 		 * recheck VEXEC access
5972 		 */
5973 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5974 		if (cacc != NFS4_ACCESS_ALLOWED) {
5975 			/*
5976 			 * Directory permissions might have been revoked
5977 			 */
5978 			if (cacc == NFS4_ACCESS_DENIED) {
5979 				sfh4_rele(&sfhp);
5980 				e.error = EACCES;
5981 				goto exit;
5982 			}
5983 
5984 			/*
5985 			 * Somehow we must not have asked for enough
5986 			 * so try a singleton ACCESS should never happen
5987 			 */
5988 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5989 			if (e.error) {
5990 				sfh4_rele(&sfhp);
5991 				goto exit;
5992 			}
5993 		}
5994 
5995 		e.error = geterrno4(res.status);
5996 	} else {
5997 		hrtime_t now;
5998 		hrtime_t delta = 0;
5999 
6000 		e.error = 0;
6001 
6002 		/*
6003 		 * Because the NVERIFY "succeeded" we know that the
6004 		 * directory attributes are still valid
6005 		 * so update r_time_attr_inval
6006 		 */
6007 		now = gethrtime();
6008 		mutex_enter(&drp->r_statelock);
6009 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
6010 			delta = now - drp->r_time_attr_saved;
6011 			if (delta < mi->mi_acdirmin)
6012 				delta = mi->mi_acdirmin;
6013 			else if (delta > mi->mi_acdirmax)
6014 				delta = mi->mi_acdirmax;
6015 		}
6016 		drp->r_time_attr_inval = now + delta;
6017 		mutex_exit(&drp->r_statelock);
6018 
6019 		/*
6020 		 * Even though we have a valid directory attr cache,
6021 		 * we may not have access.
6022 		 * This should almost always hit the cache.
6023 		 */
6024 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
6025 		if (e.error) {
6026 			sfh4_rele(&sfhp);
6027 			goto exit;
6028 		}
6029 	}
6030 
6031 	/*
6032 	 * Now we have successfully completed the lookup, if the
6033 	 * directory has changed we now have the valid attributes.
6034 	 * We also know we have directory access.
6035 	 * Create the new rnode and insert it in the dnlc.
6036 	 */
6037 	if (isdotdot) {
6038 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
6039 		if (e.error) {
6040 			sfh4_rele(&sfhp);
6041 			goto exit;
6042 		}
6043 		/*
6044 		 * XXX if nfs4_make_dotdot uses an existing rnode
6045 		 * XXX it doesn't update the attributes.
6046 		 * XXX for now just save them again to save an OTW
6047 		 */
6048 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
6049 	} else {
6050 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
6051 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
6052 	}
6053 	sfh4_rele(&sfhp);
6054 
6055 	nrp = VTOR4(nvp);
6056 	mutex_enter(&nrp->r_statev4_lock);
6057 	if (!nrp->created_v4) {
6058 		mutex_exit(&nrp->r_statev4_lock);
6059 		dnlc_update(dvp, nm, nvp);
6060 	} else
6061 		mutex_exit(&nrp->r_statev4_lock);
6062 
6063 	*vpp = nvp;
6064 
6065 exit:
6066 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6067 	kmem_free(argop, argoplist_size);
6068 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
6069 	return (e.error);
6070 }
6071 
6072 #ifdef DEBUG
6073 void
6074 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
6075 {
6076 	uint_t i, len;
6077 	zoneid_t zoneid = getzoneid();
6078 	char *s;
6079 
6080 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
6081 	for (i = 0; i < argcnt; i++) {
6082 		nfs_argop4 *op = &argbase[i];
6083 		switch (op->argop) {
6084 		case OP_CPUTFH:
6085 		case OP_PUTFH:
6086 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
6087 			break;
6088 		case OP_PUTROOTFH:
6089 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
6090 			break;
6091 		case OP_CLOOKUP:
6092 			s = op->nfs_argop4_u.opclookup.cname;
6093 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6094 			break;
6095 		case OP_LOOKUP:
6096 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
6097 			    &len, NULL);
6098 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6099 			kmem_free(s, len);
6100 			break;
6101 		case OP_LOOKUPP:
6102 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
6103 			break;
6104 		case OP_GETFH:
6105 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
6106 			break;
6107 		case OP_GETATTR:
6108 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
6109 			break;
6110 		case OP_OPENATTR:
6111 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
6112 			break;
6113 		default:
6114 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
6115 			    op->argop);
6116 			break;
6117 		}
6118 	}
6119 }
6120 #endif
6121 
6122 /*
6123  * nfs4lookup_setup - constructs a multi-lookup compound request.
6124  *
6125  * Given the path "nm1/nm2/.../nmn", the following compound requests
6126  * may be created:
6127  *
6128  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
6129  * is faster, for now.
6130  *
6131  * l4_getattrs indicates the type of compound requested.
6132  *
6133  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
6134  *
6135  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
6136  *
6137  *   total number of ops is n + 1.
6138  *
6139  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
6140  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
6141  *      before the last component, and only get attributes
6142  *      for the last component.  Note that the second-to-last
6143  *	pathname component is XATTR_RPATH, which does NOT go
6144  *	over-the-wire as a lookup.
6145  *
6146  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
6147  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
6148  *
6149  *   and total number of ops is n + 5.
6150  *
6151  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
6152  *      attribute directory: create lookups plus an OPENATTR
6153  *	replacing the last lookup.  Note that the last pathname
6154  *	component is XATTR_RPATH, which does NOT go over-the-wire
6155  *	as a lookup.
6156  *
6157  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
6158  *		Openattr; Getfh; Getattr }
6159  *
6160  *   and total number of ops is n + 5.
6161  *
6162  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6163  *	nodes too.
6164  *
6165  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6166  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6167  *
6168  *   and total number of ops is 3*n + 1.
6169  *
6170  * All cases: returns the index in the arg array of the final LOOKUP op, or
6171  * -1 if no LOOKUPs were used.
6172  */
6173 int
6174 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6175 {
6176 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6177 	nfs_argop4 *argbase, *argop;
6178 	int arglen, argcnt;
6179 	int n = 1;	/* number of components */
6180 	int nga = 1;	/* number of Getattr's in request */
6181 	char c = '\0', *s, *p;
6182 	int lookup_idx = -1;
6183 	int argoplist_size;
6184 
6185 	/* set lookuparg response result to 0 */
6186 	lookupargp->resp->status = NFS4_OK;
6187 
6188 	/* skip leading "/" or "." e.g. ".//./" if there is */
6189 	for (; ; nm++) {
6190 		if (*nm != '/' && *nm != '.')
6191 			break;
6192 
6193 		/* ".." is counted as 1 component */
6194 		if (*nm == '.' && *(nm + 1) != '/')
6195 			break;
6196 	}
6197 
6198 	/*
6199 	 * Find n = number of components - nm must be null terminated
6200 	 * Skip "." components.
6201 	 */
6202 	if (*nm != '\0')
6203 		for (n = 1, s = nm; *s != '\0'; s++) {
6204 			if ((*s == '/') && (*(s + 1) != '/') &&
6205 			    (*(s + 1) != '\0') &&
6206 			    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6207 			    *(s + 2) == '\0')))
6208 				n++;
6209 		}
6210 	else
6211 		n = 0;
6212 
6213 	/*
6214 	 * nga is number of components that need Getfh+Getattr
6215 	 */
6216 	switch (l4_getattrs) {
6217 	case LKP4_NO_ATTRIBUTES:
6218 		nga = 0;
6219 		break;
6220 	case LKP4_ALL_ATTRIBUTES:
6221 		nga = n;
6222 		/*
6223 		 * Always have at least 1 getfh, getattr pair
6224 		 */
6225 		if (nga == 0)
6226 			nga++;
6227 		break;
6228 	case LKP4_LAST_ATTRDIR:
6229 	case LKP4_LAST_NAMED_ATTR:
6230 		nga = n+1;
6231 		break;
6232 	}
6233 
6234 	/*
6235 	 * If change to use the filehandle attr instead of getfh
6236 	 * the following line can be deleted.
6237 	 */
6238 	nga *= 2;
6239 
6240 	/*
6241 	 * calculate number of ops in request as
6242 	 * header + trailer + lookups + getattrs
6243 	 */
6244 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6245 
6246 	argoplist_size = arglen * sizeof (nfs_argop4);
6247 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6248 	lookupargp->argsp->array = argop;
6249 
6250 	argcnt = lookupargp->header_len;
6251 	argop += argcnt;
6252 
6253 	/*
6254 	 * loop and create a lookup op and possibly getattr/getfh for
6255 	 * each component. Skip "." components.
6256 	 */
6257 	for (s = nm; *s != '\0'; s = p) {
6258 		/*
6259 		 * Set up a pathname struct for each component if needed
6260 		 */
6261 		while (*s == '/')
6262 			s++;
6263 		if (*s == '\0')
6264 			break;
6265 
6266 		for (p = s; (*p != '/') && (*p != '\0'); p++)
6267 			;
6268 		c = *p;
6269 		*p = '\0';
6270 
6271 		if (s[0] == '.' && s[1] == '\0') {
6272 			*p = c;
6273 			continue;
6274 		}
6275 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6276 		    strcmp(s, XATTR_RPATH) == 0) {
6277 			/* getfh XXX may not be needed in future */
6278 			argop->argop = OP_GETFH;
6279 			argop++;
6280 			argcnt++;
6281 
6282 			/* getattr */
6283 			argop->argop = OP_GETATTR;
6284 			argop->nfs_argop4_u.opgetattr.attr_request =
6285 			    lookupargp->ga_bits;
6286 			argop->nfs_argop4_u.opgetattr.mi =
6287 			    lookupargp->mi;
6288 			argop++;
6289 			argcnt++;
6290 
6291 			/* openattr */
6292 			argop->argop = OP_OPENATTR;
6293 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6294 		    strcmp(s, XATTR_RPATH) == 0) {
6295 			/* openattr */
6296 			argop->argop = OP_OPENATTR;
6297 			argop++;
6298 			argcnt++;
6299 
6300 			/* getfh XXX may not be needed in future */
6301 			argop->argop = OP_GETFH;
6302 			argop++;
6303 			argcnt++;
6304 
6305 			/* getattr */
6306 			argop->argop = OP_GETATTR;
6307 			argop->nfs_argop4_u.opgetattr.attr_request =
6308 			    lookupargp->ga_bits;
6309 			argop->nfs_argop4_u.opgetattr.mi =
6310 			    lookupargp->mi;
6311 			argop++;
6312 			argcnt++;
6313 			*p = c;
6314 			continue;
6315 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6316 			/* lookupp */
6317 			argop->argop = OP_LOOKUPP;
6318 		} else {
6319 			/* lookup */
6320 			argop->argop = OP_LOOKUP;
6321 			(void) str_to_utf8(s,
6322 			    &argop->nfs_argop4_u.oplookup.objname);
6323 		}
6324 		lookup_idx = argcnt;
6325 		argop++;
6326 		argcnt++;
6327 
6328 		*p = c;
6329 
6330 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6331 			/* getfh XXX may not be needed in future */
6332 			argop->argop = OP_GETFH;
6333 			argop++;
6334 			argcnt++;
6335 
6336 			/* getattr */
6337 			argop->argop = OP_GETATTR;
6338 			argop->nfs_argop4_u.opgetattr.attr_request =
6339 			    lookupargp->ga_bits;
6340 			argop->nfs_argop4_u.opgetattr.mi =
6341 			    lookupargp->mi;
6342 			argop++;
6343 			argcnt++;
6344 		}
6345 	}
6346 
6347 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6348 	    ((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6349 		if (needgetfh) {
6350 			/* stick in a post-lookup getfh */
6351 			argop->argop = OP_GETFH;
6352 			argcnt++;
6353 			argop++;
6354 		}
6355 		/* post-lookup getattr */
6356 		argop->argop = OP_GETATTR;
6357 		argop->nfs_argop4_u.opgetattr.attr_request =
6358 		    lookupargp->ga_bits;
6359 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6360 		argcnt++;
6361 	}
6362 	argcnt += lookupargp->trailer_len;	/* actual op count */
6363 	lookupargp->argsp->array_len = argcnt;
6364 	lookupargp->arglen = arglen;
6365 
6366 #ifdef DEBUG
6367 	if (nfs4_client_lookup_debug)
6368 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6369 #endif
6370 
6371 	return (lookup_idx);
6372 }
6373 
6374 static int
6375 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6376 {
6377 	COMPOUND4args_clnt	args;
6378 	COMPOUND4res_clnt	res;
6379 	GETFH4res	*gf_res = NULL;
6380 	nfs_argop4	argop[4];
6381 	nfs_resop4	*resop = NULL;
6382 	nfs4_sharedfh_t *sfhp;
6383 	hrtime_t t;
6384 	nfs4_error_t	e;
6385 
6386 	rnode4_t	*drp;
6387 	int		doqueue = 1;
6388 	vnode_t		*vp;
6389 	int		needrecov = 0;
6390 	nfs4_recov_state_t recov_state;
6391 
6392 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6393 
6394 	*avp = NULL;
6395 	recov_state.rs_flags = 0;
6396 	recov_state.rs_num_retry_despite_err = 0;
6397 
6398 recov_retry:
6399 	/* COMPOUND: putfh, openattr, getfh, getattr */
6400 	args.array_len = 4;
6401 	args.array = argop;
6402 	args.ctag = TAG_OPENATTR;
6403 
6404 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6405 	if (e.error)
6406 		return (e.error);
6407 
6408 	drp = VTOR4(dvp);
6409 
6410 	/* putfh */
6411 	argop[0].argop = OP_CPUTFH;
6412 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6413 
6414 	/* openattr */
6415 	argop[1].argop = OP_OPENATTR;
6416 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6417 
6418 	/* getfh */
6419 	argop[2].argop = OP_GETFH;
6420 
6421 	/* getattr */
6422 	argop[3].argop = OP_GETATTR;
6423 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6424 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6425 
6426 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6427 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6428 	    rnode4info(drp)));
6429 
6430 	t = gethrtime();
6431 
6432 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6433 
6434 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6435 	if (needrecov) {
6436 		bool_t abort;
6437 
6438 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6439 		    "nfs4openattr: initiating recovery\n"));
6440 
6441 		abort = nfs4_start_recovery(&e,
6442 		    VTOMI4(dvp), dvp, NULL, NULL, NULL,
6443 		    OP_OPENATTR, NULL, NULL, NULL);
6444 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6445 		if (!e.error) {
6446 			e.error = geterrno4(res.status);
6447 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6448 		}
6449 		if (abort == FALSE)
6450 			goto recov_retry;
6451 		return (e.error);
6452 	}
6453 
6454 	if (e.error) {
6455 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6456 		return (e.error);
6457 	}
6458 
6459 	if (res.status) {
6460 		/*
6461 		 * If OTW errro is NOTSUPP, then it should be
6462 		 * translated to EINVAL.  All Solaris file system
6463 		 * implementations return EINVAL to the syscall layer
6464 		 * when the attrdir cannot be created due to an
6465 		 * implementation restriction or noxattr mount option.
6466 		 */
6467 		if (res.status == NFS4ERR_NOTSUPP) {
6468 			mutex_enter(&drp->r_statelock);
6469 			if (drp->r_xattr_dir)
6470 				VN_RELE(drp->r_xattr_dir);
6471 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6472 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6473 			mutex_exit(&drp->r_statelock);
6474 
6475 			e.error = EINVAL;
6476 		} else {
6477 			e.error = geterrno4(res.status);
6478 		}
6479 
6480 		if (e.error) {
6481 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6482 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6483 			    needrecov);
6484 			return (e.error);
6485 		}
6486 	}
6487 
6488 	resop = &res.array[0];  /* putfh res */
6489 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6490 
6491 	resop = &res.array[1];  /* openattr res */
6492 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6493 
6494 	resop = &res.array[2];  /* getfh res */
6495 	gf_res = &resop->nfs_resop4_u.opgetfh;
6496 	if (gf_res->object.nfs_fh4_len == 0) {
6497 		*avp = NULL;
6498 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6499 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6500 		return (ENOENT);
6501 	}
6502 
6503 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6504 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6505 	    dvp->v_vfsp, t, cr, dvp,
6506 	    fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH, sfhp));
6507 	sfh4_rele(&sfhp);
6508 
6509 	if (e.error)
6510 		PURGE_ATTRCACHE4(vp);
6511 
6512 	mutex_enter(&vp->v_lock);
6513 	vp->v_flag |= V_XATTRDIR;
6514 	mutex_exit(&vp->v_lock);
6515 
6516 	*avp = vp;
6517 
6518 	mutex_enter(&drp->r_statelock);
6519 	if (drp->r_xattr_dir)
6520 		VN_RELE(drp->r_xattr_dir);
6521 	VN_HOLD(vp);
6522 	drp->r_xattr_dir = vp;
6523 
6524 	/*
6525 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6526 	 * NULL.  xattrs could be created at any time, and we have no
6527 	 * way to update pc4_xattr_exists in the base object if/when
6528 	 * it happens.
6529 	 */
6530 	drp->r_pathconf.pc4_xattr_valid = 0;
6531 
6532 	mutex_exit(&drp->r_statelock);
6533 
6534 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6535 
6536 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6537 
6538 	return (0);
6539 }
6540 
6541 /* ARGSUSED */
6542 static int
6543 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6544     int mode, vnode_t **vpp, cred_t *cr, int flags, caller_context_t *ct,
6545     vsecattr_t *vsecp)
6546 {
6547 	int error;
6548 	vnode_t *vp = NULL;
6549 	rnode4_t *rp;
6550 	struct vattr vattr;
6551 	rnode4_t *drp;
6552 	vnode_t *tempvp;
6553 	enum createmode4 createmode;
6554 	bool_t must_trunc = FALSE;
6555 	int	truncating = 0;
6556 
6557 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6558 		return (EPERM);
6559 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6560 		return (EINVAL);
6561 	}
6562 
6563 	/* . and .. have special meaning in the protocol, reject them. */
6564 
6565 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6566 		return (EISDIR);
6567 
6568 	drp = VTOR4(dvp);
6569 
6570 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6571 		return (EINTR);
6572 
6573 top:
6574 	/*
6575 	 * We make a copy of the attributes because the caller does not
6576 	 * expect us to change what va points to.
6577 	 */
6578 	vattr = *va;
6579 
6580 	/*
6581 	 * If the pathname is "", then dvp is the root vnode of
6582 	 * a remote file mounted over a local directory.
6583 	 * All that needs to be done is access
6584 	 * checking and truncation.  Note that we avoid doing
6585 	 * open w/ create because the parent directory might
6586 	 * be in pseudo-fs and the open would fail.
6587 	 */
6588 	if (*nm == '\0') {
6589 		error = 0;
6590 		VN_HOLD(dvp);
6591 		vp = dvp;
6592 		must_trunc = TRUE;
6593 	} else {
6594 		/*
6595 		 * We need to go over the wire, just to be sure whether the
6596 		 * file exists or not.  Using the DNLC can be dangerous in
6597 		 * this case when making a decision regarding existence.
6598 		 */
6599 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6600 	}
6601 
6602 	if (exclusive)
6603 		createmode = EXCLUSIVE4;
6604 	else
6605 		createmode = GUARDED4;
6606 
6607 	/*
6608 	 * error would be set if the file does not exist on the
6609 	 * server, so lets go create it.
6610 	 */
6611 	if (error) {
6612 		goto create_otw;
6613 	}
6614 
6615 	/*
6616 	 * File does exist on the server
6617 	 */
6618 	if (exclusive == EXCL)
6619 		error = EEXIST;
6620 	else if (vp->v_type == VDIR && (mode & VWRITE))
6621 		error = EISDIR;
6622 	else {
6623 		/*
6624 		 * If vnode is a device, create special vnode.
6625 		 */
6626 		if (ISVDEV(vp->v_type)) {
6627 			tempvp = vp;
6628 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6629 			VN_RELE(tempvp);
6630 		}
6631 		if (!(error = VOP_ACCESS(vp, mode, 0, cr, ct))) {
6632 			if ((vattr.va_mask & AT_SIZE) &&
6633 			    vp->v_type == VREG) {
6634 				rp = VTOR4(vp);
6635 				/*
6636 				 * Check here for large file handled
6637 				 * by LF-unaware process (as
6638 				 * ufs_create() does)
6639 				 */
6640 				if (!(flags & FOFFMAX)) {
6641 					mutex_enter(&rp->r_statelock);
6642 					if (rp->r_size > MAXOFF32_T)
6643 						error = EOVERFLOW;
6644 					mutex_exit(&rp->r_statelock);
6645 				}
6646 
6647 				/* if error is set then we need to return */
6648 				if (error) {
6649 					nfs_rw_exit(&drp->r_rwlock);
6650 					VN_RELE(vp);
6651 					return (error);
6652 				}
6653 
6654 				if (must_trunc) {
6655 					vattr.va_mask = AT_SIZE;
6656 					error = nfs4setattr(vp, &vattr, 0, cr,
6657 					    NULL);
6658 				} else {
6659 				/*
6660 				 * we know we have a regular file that already
6661 				 * exists and we may end up truncating the file
6662 				 * as a result of the open_otw, so flush out
6663 				 * any dirty pages for this file first.
6664 				 */
6665 					if (nfs4_has_pages(vp) &&
6666 					    ((rp->r_flags & R4DIRTY) ||
6667 					    rp->r_count > 0 ||
6668 					    rp->r_mapcnt > 0)) {
6669 						error = nfs4_putpage(vp,
6670 						    (offset_t)0, 0, 0, cr, ct);
6671 						if (error && (error == ENOSPC ||
6672 						    error == EDQUOT)) {
6673 							mutex_enter(
6674 							    &rp->r_statelock);
6675 							if (!rp->r_error)
6676 								rp->r_error =
6677 								    error;
6678 							mutex_exit(
6679 							    &rp->r_statelock);
6680 						}
6681 					}
6682 					vattr.va_mask = (AT_SIZE |
6683 					    AT_TYPE | AT_MODE);
6684 					vattr.va_type = VREG;
6685 					createmode = UNCHECKED4;
6686 					truncating = 1;
6687 					goto create_otw;
6688 				}
6689 			}
6690 		}
6691 	}
6692 	nfs_rw_exit(&drp->r_rwlock);
6693 	if (error) {
6694 		VN_RELE(vp);
6695 	} else {
6696 		vnode_t *tvp;
6697 		rnode4_t *trp;
6698 		tvp = vp;
6699 		if (vp->v_type == VREG) {
6700 			trp = VTOR4(vp);
6701 			if (IS_SHADOW(vp, trp))
6702 				tvp = RTOV4(trp);
6703 		}
6704 
6705 		if (must_trunc) {
6706 			/*
6707 			 * existing file got truncated, notify.
6708 			 */
6709 			vnevent_create(tvp, ct);
6710 		}
6711 
6712 		*vpp = vp;
6713 	}
6714 	return (error);
6715 
6716 create_otw:
6717 	dnlc_remove(dvp, nm);
6718 
6719 	ASSERT(vattr.va_mask & AT_TYPE);
6720 
6721 	/*
6722 	 * If not a regular file let nfs4mknod() handle it.
6723 	 */
6724 	if (vattr.va_type != VREG) {
6725 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6726 		nfs_rw_exit(&drp->r_rwlock);
6727 		return (error);
6728 	}
6729 
6730 	/*
6731 	 * It _is_ a regular file.
6732 	 */
6733 	ASSERT(vattr.va_mask & AT_MODE);
6734 	if (MANDMODE(vattr.va_mode)) {
6735 		nfs_rw_exit(&drp->r_rwlock);
6736 		return (EACCES);
6737 	}
6738 
6739 	/*
6740 	 * If this happens to be a mknod of a regular file, then flags will
6741 	 * have neither FREAD or FWRITE.  However, we must set at least one
6742 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6743 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6744 	 * set (based on openmode specified by app).
6745 	 */
6746 	if ((flags & (FREAD|FWRITE)) == 0)
6747 		flags |= (FREAD|FWRITE);
6748 
6749 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6750 
6751 	if (vp != NULL) {
6752 		/* if create was successful, throw away the file's pages */
6753 		if (!error && (vattr.va_mask & AT_SIZE))
6754 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6755 			    cr);
6756 		/* release the lookup hold */
6757 		VN_RELE(vp);
6758 		vp = NULL;
6759 	}
6760 
6761 	/*
6762 	 * validate that we opened a regular file. This handles a misbehaving
6763 	 * server that returns an incorrect FH.
6764 	 */
6765 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6766 		error = EISDIR;
6767 		VN_RELE(*vpp);
6768 	}
6769 
6770 	/*
6771 	 * If this is not an exclusive create, then the CREATE
6772 	 * request will be made with the GUARDED mode set.  This
6773 	 * means that the server will return EEXIST if the file
6774 	 * exists.  The file could exist because of a retransmitted
6775 	 * request.  In this case, we recover by starting over and
6776 	 * checking to see whether the file exists.  This second
6777 	 * time through it should and a CREATE request will not be
6778 	 * sent.
6779 	 *
6780 	 * This handles the problem of a dangling CREATE request
6781 	 * which contains attributes which indicate that the file
6782 	 * should be truncated.  This retransmitted request could
6783 	 * possibly truncate valid data in the file if not caught
6784 	 * by the duplicate request mechanism on the server or if
6785 	 * not caught by other means.  The scenario is:
6786 	 *
6787 	 * Client transmits CREATE request with size = 0
6788 	 * Client times out, retransmits request.
6789 	 * Response to the first request arrives from the server
6790 	 *  and the client proceeds on.
6791 	 * Client writes data to the file.
6792 	 * The server now processes retransmitted CREATE request
6793 	 *  and truncates file.
6794 	 *
6795 	 * The use of the GUARDED CREATE request prevents this from
6796 	 * happening because the retransmitted CREATE would fail
6797 	 * with EEXIST and would not truncate the file.
6798 	 */
6799 	if (error == EEXIST && exclusive == NONEXCL) {
6800 #ifdef DEBUG
6801 		nfs4_create_misses++;
6802 #endif
6803 		goto top;
6804 	}
6805 	nfs_rw_exit(&drp->r_rwlock);
6806 	if (truncating && !error && *vpp) {
6807 		vnode_t *tvp;
6808 		rnode4_t *trp;
6809 		/*
6810 		 * existing file got truncated, notify.
6811 		 */
6812 		tvp = *vpp;
6813 		trp = VTOR4(tvp);
6814 		if (IS_SHADOW(tvp, trp))
6815 			tvp = RTOV4(trp);
6816 		vnevent_create(tvp, ct);
6817 	}
6818 	return (error);
6819 }
6820 
6821 /*
6822  * Create compound (for mkdir, mknod, symlink):
6823  * { Putfh <dfh>; Create; Getfh; Getattr }
6824  * It's okay if setattr failed to set gid - this is not considered
6825  * an error, but purge attrs in that case.
6826  */
6827 static int
6828 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6829     vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6830 {
6831 	int need_end_op = FALSE;
6832 	COMPOUND4args_clnt args;
6833 	COMPOUND4res_clnt res, *resp = NULL;
6834 	nfs_argop4 *argop;
6835 	nfs_resop4 *resop;
6836 	int doqueue;
6837 	mntinfo4_t *mi;
6838 	rnode4_t *drp = VTOR4(dvp);
6839 	change_info4 *cinfo;
6840 	GETFH4res *gf_res;
6841 	struct vattr vattr;
6842 	vnode_t *vp;
6843 	fattr4 *crattr;
6844 	bool_t needrecov = FALSE;
6845 	nfs4_recov_state_t recov_state;
6846 	nfs4_sharedfh_t *sfhp = NULL;
6847 	hrtime_t t;
6848 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6849 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6850 	dirattr_info_t dinfo, *dinfop;
6851 	servinfo4_t *svp;
6852 	bitmap4 supp_attrs;
6853 
6854 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6855 	    type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6856 
6857 	mi = VTOMI4(dvp);
6858 
6859 	/*
6860 	 * Make sure we properly deal with setting the right gid
6861 	 * on a new directory to reflect the parent's setgid bit
6862 	 */
6863 	setgid_flag = 0;
6864 	if (type == NF4DIR) {
6865 		struct vattr dva;
6866 
6867 		va->va_mode &= ~VSGID;
6868 		dva.va_mask = AT_MODE | AT_GID;
6869 		if (VOP_GETATTR(dvp, &dva, 0, cr, NULL) == 0) {
6870 
6871 			/*
6872 			 * If the parent's directory has the setgid bit set
6873 			 * _and_ the client was able to get a valid mapping
6874 			 * for the parent dir's owner_group, we want to
6875 			 * append NVERIFY(owner_group == dva.va_gid) and
6876 			 * SETTATTR to the CREATE compound.
6877 			 */
6878 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6879 				setgid_flag = 1;
6880 				va->va_mode |= VSGID;
6881 				if (dva.va_gid != GID_NOBODY) {
6882 					va->va_mask |= AT_GID;
6883 					va->va_gid = dva.va_gid;
6884 				}
6885 			}
6886 		}
6887 	}
6888 
6889 	/*
6890 	 * Create ops:
6891 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6892 	 *	5:restorefh(dir) 6:getattr(dir)
6893 	 *
6894 	 * if (setgid)
6895 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6896 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6897 	 *	8:nverify 9:setattr
6898 	 */
6899 	if (setgid_flag) {
6900 		numops = 10;
6901 		idx_create = 1;
6902 		idx_fattr = 3;
6903 	} else {
6904 		numops = 7;
6905 		idx_create = 2;
6906 		idx_fattr = 4;
6907 	}
6908 
6909 	ASSERT(nfs_zone() == mi->mi_zone);
6910 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6911 		return (EINTR);
6912 	}
6913 	recov_state.rs_flags = 0;
6914 	recov_state.rs_num_retry_despite_err = 0;
6915 
6916 	argoplist_size = numops * sizeof (nfs_argop4);
6917 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6918 
6919 recov_retry:
6920 	if (type == NF4LNK)
6921 		args.ctag = TAG_SYMLINK;
6922 	else if (type == NF4DIR)
6923 		args.ctag = TAG_MKDIR;
6924 	else
6925 		args.ctag = TAG_MKNOD;
6926 
6927 	args.array_len = numops;
6928 	args.array = argop;
6929 
6930 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6931 		nfs_rw_exit(&drp->r_rwlock);
6932 		kmem_free(argop, argoplist_size);
6933 		return (e.error);
6934 	}
6935 	need_end_op = TRUE;
6936 
6937 
6938 	/* 0: putfh directory */
6939 	argop[0].argop = OP_CPUTFH;
6940 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6941 
6942 	/* 1/2: Create object */
6943 	argop[idx_create].argop = OP_CCREATE;
6944 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6945 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6946 	if (type == NF4LNK) {
6947 		/*
6948 		 * symlink, treat name as data
6949 		 */
6950 		ASSERT(data != NULL);
6951 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6952 		    (char *)data;
6953 	}
6954 	if (type == NF4BLK || type == NF4CHR) {
6955 		ASSERT(data != NULL);
6956 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6957 		    *((specdata4 *)data);
6958 	}
6959 
6960 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6961 
6962 	svp = drp->r_server;
6963 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6964 	supp_attrs = svp->sv_supp_attrs;
6965 	nfs_rw_exit(&svp->sv_lock);
6966 
6967 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6968 		nfs_rw_exit(&drp->r_rwlock);
6969 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6970 		e.error = EINVAL;
6971 		kmem_free(argop, argoplist_size);
6972 		return (e.error);
6973 	}
6974 
6975 	/* 2/3: getfh fh of created object */
6976 	ASSERT(idx_create + 1 == idx_fattr - 1);
6977 	argop[idx_create + 1].argop = OP_GETFH;
6978 
6979 	/* 3/4: getattr of new object */
6980 	argop[idx_fattr].argop = OP_GETATTR;
6981 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6982 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6983 
6984 	if (setgid_flag) {
6985 		vattr_t	_v;
6986 
6987 		argop[4].argop = OP_SAVEFH;
6988 
6989 		argop[5].argop = OP_CPUTFH;
6990 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6991 
6992 		argop[6].argop = OP_GETATTR;
6993 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6994 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6995 
6996 		argop[7].argop = OP_RESTOREFH;
6997 
6998 		/*
6999 		 * nverify
7000 		 *
7001 		 * XXX - Revisit the last argument to nfs4_end_op()
7002 		 *	 once 5020486 is fixed.
7003 		 */
7004 		_v.va_mask = AT_GID;
7005 		_v.va_gid = va->va_gid;
7006 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
7007 		    supp_attrs)) {
7008 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
7009 			nfs_rw_exit(&drp->r_rwlock);
7010 			nfs4_fattr4_free(crattr);
7011 			kmem_free(argop, argoplist_size);
7012 			return (e.error);
7013 		}
7014 
7015 		/*
7016 		 * setattr
7017 		 *
7018 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
7019 		 * so no need for stateid or flags. Also we specify NULL
7020 		 * rp since we're only interested in setting owner_group
7021 		 * attributes.
7022 		 */
7023 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
7024 		    &e.error, 0);
7025 
7026 		if (e.error) {
7027 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
7028 			nfs_rw_exit(&drp->r_rwlock);
7029 			nfs4_fattr4_free(crattr);
7030 			nfs4args_verify_free(&argop[8]);
7031 			kmem_free(argop, argoplist_size);
7032 			return (e.error);
7033 		}
7034 	} else {
7035 		argop[1].argop = OP_SAVEFH;
7036 
7037 		argop[5].argop = OP_RESTOREFH;
7038 
7039 		argop[6].argop = OP_GETATTR;
7040 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7041 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
7042 	}
7043 
7044 	dnlc_remove(dvp, nm);
7045 
7046 	doqueue = 1;
7047 	t = gethrtime();
7048 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7049 
7050 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7051 	if (e.error) {
7052 		PURGE_ATTRCACHE4(dvp);
7053 		if (!needrecov)
7054 			goto out;
7055 	}
7056 
7057 	if (needrecov) {
7058 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
7059 		    OP_CREATE, NULL, NULL, NULL) == FALSE) {
7060 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7061 			    needrecov);
7062 			need_end_op = FALSE;
7063 			nfs4_fattr4_free(crattr);
7064 			if (setgid_flag) {
7065 				nfs4args_verify_free(&argop[8]);
7066 				nfs4args_setattr_free(&argop[9]);
7067 			}
7068 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
7069 			goto recov_retry;
7070 		}
7071 	}
7072 
7073 	resp = &res;
7074 
7075 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
7076 
7077 		if (res.status == NFS4ERR_BADOWNER)
7078 			nfs4_log_badowner(mi, OP_CREATE);
7079 
7080 		e.error = geterrno4(res.status);
7081 
7082 		/*
7083 		 * This check is left over from when create was implemented
7084 		 * using a setattr op (instead of createattrs).  If the
7085 		 * putfh/create/getfh failed, the error was returned.  If
7086 		 * setattr/getattr failed, we keep going.
7087 		 *
7088 		 * It might be better to get rid of the GETFH also, and just
7089 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
7090 		 * Then if any of the operations failed, we could return the
7091 		 * error now, and remove much of the error code below.
7092 		 */
7093 		if (res.array_len <= idx_fattr) {
7094 			/*
7095 			 * Either Putfh, Create or Getfh failed.
7096 			 */
7097 			PURGE_ATTRCACHE4(dvp);
7098 			/*
7099 			 * nfs4_purge_stale_fh() may generate otw calls through
7100 			 * nfs4_invalidate_pages. Hence the need to call
7101 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
7102 			 */
7103 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7104 			    needrecov);
7105 			need_end_op = FALSE;
7106 			nfs4_purge_stale_fh(e.error, dvp, cr);
7107 			goto out;
7108 		}
7109 	}
7110 
7111 	resop = &res.array[idx_create];	/* create res */
7112 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
7113 
7114 	resop = &res.array[idx_create + 1]; /* getfh res */
7115 	gf_res = &resop->nfs_resop4_u.opgetfh;
7116 
7117 	sfhp = sfh4_get(&gf_res->object, mi);
7118 	if (e.error) {
7119 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
7120 		    fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7121 		if (vp->v_type == VNON) {
7122 			vattr.va_mask = AT_TYPE;
7123 			/*
7124 			 * Need to call nfs4_end_op before nfs4getattr to avoid
7125 			 * potential nfs4_start_op deadlock. See RFE 4777612.
7126 			 */
7127 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7128 			    needrecov);
7129 			need_end_op = FALSE;
7130 			e.error = nfs4getattr(vp, &vattr, cr);
7131 			if (e.error) {
7132 				VN_RELE(vp);
7133 				*vpp = NULL;
7134 				goto out;
7135 			}
7136 			vp->v_type = vattr.va_type;
7137 		}
7138 		e.error = 0;
7139 	} else {
7140 		*vpp = vp = makenfs4node(sfhp,
7141 		    &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
7142 		    dvp->v_vfsp, t, cr,
7143 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7144 	}
7145 
7146 	/*
7147 	 * If compound succeeded, then update dir attrs
7148 	 */
7149 	if (res.status == NFS4_OK) {
7150 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
7151 		dinfo.di_cred = cr;
7152 		dinfo.di_time_call = t;
7153 		dinfop = &dinfo;
7154 	} else
7155 		dinfop = NULL;
7156 
7157 	/* Update directory cache attribute, readdir and dnlc caches */
7158 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
7159 
7160 out:
7161 	if (sfhp != NULL)
7162 		sfh4_rele(&sfhp);
7163 	nfs_rw_exit(&drp->r_rwlock);
7164 	nfs4_fattr4_free(crattr);
7165 	if (setgid_flag) {
7166 		nfs4args_verify_free(&argop[8]);
7167 		nfs4args_setattr_free(&argop[9]);
7168 	}
7169 	if (resp)
7170 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7171 	if (need_end_op)
7172 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7173 
7174 	kmem_free(argop, argoplist_size);
7175 	return (e.error);
7176 }
7177 
7178 /* ARGSUSED */
7179 static int
7180 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7181     int mode, vnode_t **vpp, cred_t *cr)
7182 {
7183 	int error;
7184 	vnode_t *vp;
7185 	nfs_ftype4 type;
7186 	specdata4 spec, *specp = NULL;
7187 
7188 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7189 
7190 	switch (va->va_type) {
7191 	case VCHR:
7192 	case VBLK:
7193 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7194 		spec.specdata1 = getmajor(va->va_rdev);
7195 		spec.specdata2 = getminor(va->va_rdev);
7196 		specp = &spec;
7197 		break;
7198 
7199 	case VFIFO:
7200 		type = NF4FIFO;
7201 		break;
7202 	case VSOCK:
7203 		type = NF4SOCK;
7204 		break;
7205 
7206 	default:
7207 		return (EINVAL);
7208 	}
7209 
7210 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7211 	if (error) {
7212 		return (error);
7213 	}
7214 
7215 	/*
7216 	 * This might not be needed any more; special case to deal
7217 	 * with problematic v2/v3 servers.  Since create was unable
7218 	 * to set group correctly, not sure what hope setattr has.
7219 	 */
7220 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7221 		va->va_mask = AT_GID;
7222 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7223 	}
7224 
7225 	/*
7226 	 * If vnode is a device create special vnode
7227 	 */
7228 	if (ISVDEV(vp->v_type)) {
7229 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7230 		VN_RELE(vp);
7231 	} else {
7232 		*vpp = vp;
7233 	}
7234 	return (error);
7235 }
7236 
7237 /*
7238  * Remove requires that the current fh be the target directory.
7239  * After the operation, the current fh is unchanged.
7240  * The compound op structure is:
7241  *      PUTFH(targetdir), REMOVE
7242  *
7243  * Weirdness: if the vnode to be removed is open
7244  * we rename it instead of removing it and nfs_inactive
7245  * will remove the new name.
7246  */
7247 /* ARGSUSED */
7248 static int
7249 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr, caller_context_t *ct, int flags)
7250 {
7251 	COMPOUND4args_clnt args;
7252 	COMPOUND4res_clnt res, *resp = NULL;
7253 	REMOVE4res *rm_res;
7254 	nfs_argop4 argop[3];
7255 	nfs_resop4 *resop;
7256 	vnode_t *vp;
7257 	char *tmpname;
7258 	int doqueue;
7259 	mntinfo4_t *mi;
7260 	rnode4_t *rp;
7261 	rnode4_t *drp;
7262 	int needrecov = 0;
7263 	nfs4_recov_state_t recov_state;
7264 	int isopen;
7265 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7266 	dirattr_info_t dinfo;
7267 
7268 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7269 		return (EPERM);
7270 	drp = VTOR4(dvp);
7271 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7272 		return (EINTR);
7273 
7274 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7275 	if (e.error) {
7276 		nfs_rw_exit(&drp->r_rwlock);
7277 		return (e.error);
7278 	}
7279 
7280 	if (vp->v_type == VDIR) {
7281 		VN_RELE(vp);
7282 		nfs_rw_exit(&drp->r_rwlock);
7283 		return (EISDIR);
7284 	}
7285 
7286 	/*
7287 	 * First just remove the entry from the name cache, as it
7288 	 * is most likely the only entry for this vp.
7289 	 */
7290 	dnlc_remove(dvp, nm);
7291 
7292 	rp = VTOR4(vp);
7293 
7294 	/*
7295 	 * For regular file types, check to see if the file is open by looking
7296 	 * at the open streams.
7297 	 * For all other types, check the reference count on the vnode.  Since
7298 	 * they are not opened OTW they never have an open stream.
7299 	 *
7300 	 * If the file is open, rename it to .nfsXXXX.
7301 	 */
7302 	if (vp->v_type != VREG) {
7303 		/*
7304 		 * If the file has a v_count > 1 then there may be more than one
7305 		 * entry in the name cache due multiple links or an open file,
7306 		 * but we don't have the real reference count so flush all
7307 		 * possible entries.
7308 		 */
7309 		if (vp->v_count > 1)
7310 			dnlc_purge_vp(vp);
7311 
7312 		/*
7313 		 * Now we have the real reference count.
7314 		 */
7315 		isopen = vp->v_count > 1;
7316 	} else {
7317 		mutex_enter(&rp->r_os_lock);
7318 		isopen = list_head(&rp->r_open_streams) != NULL;
7319 		mutex_exit(&rp->r_os_lock);
7320 	}
7321 
7322 	mutex_enter(&rp->r_statelock);
7323 	if (isopen &&
7324 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7325 		mutex_exit(&rp->r_statelock);
7326 		tmpname = newname();
7327 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr, ct);
7328 		if (e.error)
7329 			kmem_free(tmpname, MAXNAMELEN);
7330 		else {
7331 			mutex_enter(&rp->r_statelock);
7332 			if (rp->r_unldvp == NULL) {
7333 				VN_HOLD(dvp);
7334 				rp->r_unldvp = dvp;
7335 				if (rp->r_unlcred != NULL)
7336 					crfree(rp->r_unlcred);
7337 				crhold(cr);
7338 				rp->r_unlcred = cr;
7339 				rp->r_unlname = tmpname;
7340 			} else {
7341 				kmem_free(rp->r_unlname, MAXNAMELEN);
7342 				rp->r_unlname = tmpname;
7343 			}
7344 			mutex_exit(&rp->r_statelock);
7345 		}
7346 		VN_RELE(vp);
7347 		nfs_rw_exit(&drp->r_rwlock);
7348 		return (e.error);
7349 	}
7350 	/*
7351 	 * Actually remove the file/dir
7352 	 */
7353 	mutex_exit(&rp->r_statelock);
7354 
7355 	/*
7356 	 * We need to flush any dirty pages which happen to
7357 	 * be hanging around before removing the file.
7358 	 * This shouldn't happen very often since in NFSv4
7359 	 * we should be close to open consistent.
7360 	 */
7361 	if (nfs4_has_pages(vp) &&
7362 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7363 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, ct);
7364 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7365 			mutex_enter(&rp->r_statelock);
7366 			if (!rp->r_error)
7367 				rp->r_error = e.error;
7368 			mutex_exit(&rp->r_statelock);
7369 		}
7370 	}
7371 
7372 	mi = VTOMI4(dvp);
7373 
7374 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7375 	recov_state.rs_flags = 0;
7376 	recov_state.rs_num_retry_despite_err = 0;
7377 
7378 recov_retry:
7379 	/*
7380 	 * Remove ops: putfh dir; remove
7381 	 */
7382 	args.ctag = TAG_REMOVE;
7383 	args.array_len = 3;
7384 	args.array = argop;
7385 
7386 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7387 	if (e.error) {
7388 		nfs_rw_exit(&drp->r_rwlock);
7389 		VN_RELE(vp);
7390 		return (e.error);
7391 	}
7392 
7393 	/* putfh directory */
7394 	argop[0].argop = OP_CPUTFH;
7395 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7396 
7397 	/* remove */
7398 	argop[1].argop = OP_CREMOVE;
7399 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7400 
7401 	/* getattr dir */
7402 	argop[2].argop = OP_GETATTR;
7403 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7404 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7405 
7406 	doqueue = 1;
7407 	dinfo.di_time_call = gethrtime();
7408 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7409 
7410 	PURGE_ATTRCACHE4(vp);
7411 
7412 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7413 	if (e.error)
7414 		PURGE_ATTRCACHE4(dvp);
7415 
7416 	if (needrecov) {
7417 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7418 		    NULL, NULL, NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
7419 			if (!e.error)
7420 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7421 				    (caddr_t)&res);
7422 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7423 			    needrecov);
7424 			goto recov_retry;
7425 		}
7426 	}
7427 
7428 	/*
7429 	 * Matching nfs4_end_op() for start_op() above.
7430 	 * There is a path in the code below which calls
7431 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7432 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7433 	 * here to avoid nfs4_start_op() deadlock.
7434 	 */
7435 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7436 
7437 	if (!e.error) {
7438 		resp = &res;
7439 
7440 		if (res.status) {
7441 			e.error = geterrno4(res.status);
7442 			PURGE_ATTRCACHE4(dvp);
7443 			nfs4_purge_stale_fh(e.error, dvp, cr);
7444 		} else {
7445 			resop = &res.array[1];	/* remove res */
7446 			rm_res = &resop->nfs_resop4_u.opremove;
7447 
7448 			dinfo.di_garp =
7449 			    &res.array[2].nfs_resop4_u.opgetattr.ga_res;
7450 			dinfo.di_cred = cr;
7451 
7452 			/* Update directory attr, readdir and dnlc caches */
7453 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7454 			    &dinfo);
7455 		}
7456 	}
7457 	nfs_rw_exit(&drp->r_rwlock);
7458 	if (resp)
7459 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7460 
7461 	if (e.error == 0) {
7462 		vnode_t *tvp;
7463 		rnode4_t *trp;
7464 		trp = VTOR4(vp);
7465 		tvp = vp;
7466 		if (IS_SHADOW(vp, trp))
7467 			tvp = RTOV4(trp);
7468 		vnevent_remove(tvp, dvp, nm, ct);
7469 	}
7470 	VN_RELE(vp);
7471 	return (e.error);
7472 }
7473 
7474 /*
7475  * Link requires that the current fh be the target directory and the
7476  * saved fh be the source fh. After the operation, the current fh is unchanged.
7477  * Thus the compound op structure is:
7478  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7479  *	GETATTR(file)
7480  */
7481 /* ARGSUSED */
7482 static int
7483 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr,
7484     caller_context_t *ct, int flags)
7485 {
7486 	COMPOUND4args_clnt args;
7487 	COMPOUND4res_clnt res, *resp = NULL;
7488 	LINK4res *ln_res;
7489 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7490 	nfs_argop4 *argop;
7491 	nfs_resop4 *resop;
7492 	vnode_t *realvp, *nvp;
7493 	int doqueue;
7494 	mntinfo4_t *mi;
7495 	rnode4_t *tdrp;
7496 	bool_t needrecov = FALSE;
7497 	nfs4_recov_state_t recov_state;
7498 	hrtime_t t;
7499 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7500 	dirattr_info_t dinfo;
7501 
7502 	ASSERT(*tnm != '\0');
7503 	ASSERT(tdvp->v_type == VDIR);
7504 	ASSERT(nfs4_consistent_type(tdvp));
7505 	ASSERT(nfs4_consistent_type(svp));
7506 
7507 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7508 		return (EPERM);
7509 	if (VOP_REALVP(svp, &realvp, ct) == 0) {
7510 		svp = realvp;
7511 		ASSERT(nfs4_consistent_type(svp));
7512 	}
7513 
7514 	tdrp = VTOR4(tdvp);
7515 	mi = VTOMI4(svp);
7516 
7517 	if (!(mi->mi_flags & MI4_LINK)) {
7518 		return (EOPNOTSUPP);
7519 	}
7520 	recov_state.rs_flags = 0;
7521 	recov_state.rs_num_retry_despite_err = 0;
7522 
7523 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7524 		return (EINTR);
7525 
7526 recov_retry:
7527 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7528 
7529 	args.ctag = TAG_LINK;
7530 
7531 	/*
7532 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7533 	 * restorefh; getattr(fl)
7534 	 */
7535 	args.array_len = 7;
7536 	args.array = argop;
7537 
7538 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7539 	if (e.error) {
7540 		kmem_free(argop, argoplist_size);
7541 		nfs_rw_exit(&tdrp->r_rwlock);
7542 		return (e.error);
7543 	}
7544 
7545 	/* 0. putfh file */
7546 	argop[0].argop = OP_CPUTFH;
7547 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7548 
7549 	/* 1. save current fh to free up the space for the dir */
7550 	argop[1].argop = OP_SAVEFH;
7551 
7552 	/* 2. putfh targetdir */
7553 	argop[2].argop = OP_CPUTFH;
7554 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7555 
7556 	/* 3. link: current_fh is targetdir, saved_fh is source */
7557 	argop[3].argop = OP_CLINK;
7558 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7559 
7560 	/* 4. Get attributes of dir */
7561 	argop[4].argop = OP_GETATTR;
7562 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7563 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7564 
7565 	/* 5. If link was successful, restore current vp to file */
7566 	argop[5].argop = OP_RESTOREFH;
7567 
7568 	/* 6. Get attributes of linked object */
7569 	argop[6].argop = OP_GETATTR;
7570 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7571 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7572 
7573 	dnlc_remove(tdvp, tnm);
7574 
7575 	doqueue = 1;
7576 	t = gethrtime();
7577 
7578 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7579 
7580 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7581 	if (e.error != 0 && !needrecov) {
7582 		PURGE_ATTRCACHE4(tdvp);
7583 		PURGE_ATTRCACHE4(svp);
7584 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7585 		goto out;
7586 	}
7587 
7588 	if (needrecov) {
7589 		bool_t abort;
7590 
7591 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7592 		    NULL, NULL, OP_LINK, NULL, NULL, NULL);
7593 		if (abort == FALSE) {
7594 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7595 			    needrecov);
7596 			kmem_free(argop, argoplist_size);
7597 			if (!e.error)
7598 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7599 				    (caddr_t)&res);
7600 			goto recov_retry;
7601 		} else {
7602 			if (e.error != 0) {
7603 				PURGE_ATTRCACHE4(tdvp);
7604 				PURGE_ATTRCACHE4(svp);
7605 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7606 				    &recov_state, needrecov);
7607 				goto out;
7608 			}
7609 			/* fall through for res.status case */
7610 		}
7611 	}
7612 
7613 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7614 
7615 	resp = &res;
7616 	if (res.status) {
7617 		/* If link succeeded, then don't return error */
7618 		e.error = geterrno4(res.status);
7619 		if (res.array_len <= 4) {
7620 			/*
7621 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7622 			 */
7623 			PURGE_ATTRCACHE4(svp);
7624 			PURGE_ATTRCACHE4(tdvp);
7625 			if (e.error == EOPNOTSUPP) {
7626 				mutex_enter(&mi->mi_lock);
7627 				mi->mi_flags &= ~MI4_LINK;
7628 				mutex_exit(&mi->mi_lock);
7629 			}
7630 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7631 			/* XXX-LP */
7632 			if (e.error == EISDIR && crgetuid(cr) != 0)
7633 				e.error = EPERM;
7634 			goto out;
7635 		}
7636 	}
7637 
7638 	/* either no error or one of the postop getattr failed */
7639 
7640 	/*
7641 	 * XXX - if LINK succeeded, but no attrs were returned for link
7642 	 * file, purge its cache.
7643 	 *
7644 	 * XXX Perform a simplified version of wcc checking. Instead of
7645 	 * have another getattr to get pre-op, just purge cache if
7646 	 * any of the ops prior to and including the getattr failed.
7647 	 * If the getattr succeeded then update the attrcache accordingly.
7648 	 */
7649 
7650 	/*
7651 	 * update cache with link file postattrs.
7652 	 * Note: at this point resop points to link res.
7653 	 */
7654 	resop = &res.array[3];	/* link res */
7655 	ln_res = &resop->nfs_resop4_u.oplink;
7656 	if (res.status == NFS4_OK)
7657 		e.error = nfs4_update_attrcache(res.status,
7658 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res,
7659 		    t, svp, cr);
7660 
7661 	/*
7662 	 * Call makenfs4node to create the new shadow vp for tnm.
7663 	 * We pass NULL attrs because we just cached attrs for
7664 	 * the src object.  All we're trying to accomplish is to
7665 	 * to create the new shadow vnode.
7666 	 */
7667 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7668 	    tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm, VTOR4(svp)->r_fh));
7669 
7670 	/* Update target cache attribute, readdir and dnlc caches */
7671 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7672 	dinfo.di_time_call = t;
7673 	dinfo.di_cred = cr;
7674 
7675 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7676 	ASSERT(nfs4_consistent_type(tdvp));
7677 	ASSERT(nfs4_consistent_type(svp));
7678 	ASSERT(nfs4_consistent_type(nvp));
7679 	VN_RELE(nvp);
7680 
7681 	if (!e.error) {
7682 		vnode_t *tvp;
7683 		rnode4_t *trp;
7684 		/*
7685 		 * Notify the source file of this link operation.
7686 		 */
7687 		trp = VTOR4(svp);
7688 		tvp = svp;
7689 		if (IS_SHADOW(svp, trp))
7690 			tvp = RTOV4(trp);
7691 		vnevent_link(tvp, ct);
7692 	}
7693 out:
7694 	kmem_free(argop, argoplist_size);
7695 	if (resp)
7696 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7697 
7698 	nfs_rw_exit(&tdrp->r_rwlock);
7699 
7700 	return (e.error);
7701 }
7702 
7703 /* ARGSUSED */
7704 static int
7705 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7706     caller_context_t *ct, int flags)
7707 {
7708 	vnode_t *realvp;
7709 
7710 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7711 		return (EPERM);
7712 	if (VOP_REALVP(ndvp, &realvp, ct) == 0)
7713 		ndvp = realvp;
7714 
7715 	return (nfs4rename(odvp, onm, ndvp, nnm, cr, ct));
7716 }
7717 
7718 /*
7719  * nfs4rename does the real work of renaming in NFS Version 4.
7720  *
7721  * A file handle is considered volatile for renaming purposes if either
7722  * of the volatile bits are turned on. However, the compound may differ
7723  * based on the likelihood of the filehandle to change during rename.
7724  */
7725 static int
7726 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7727     caller_context_t *ct)
7728 {
7729 	int error;
7730 	mntinfo4_t *mi;
7731 	vnode_t *nvp = NULL;
7732 	vnode_t *ovp = NULL;
7733 	char *tmpname = NULL;
7734 	rnode4_t *rp;
7735 	rnode4_t *odrp;
7736 	rnode4_t *ndrp;
7737 	int did_link = 0;
7738 	int do_link = 1;
7739 	nfsstat4 stat = NFS4_OK;
7740 
7741 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7742 	ASSERT(nfs4_consistent_type(odvp));
7743 	ASSERT(nfs4_consistent_type(ndvp));
7744 
7745 	if (onm[0] == '.' && (onm[1] == '\0' ||
7746 	    (onm[1] == '.' && onm[2] == '\0')))
7747 		return (EINVAL);
7748 
7749 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7750 	    (nnm[1] == '.' && nnm[2] == '\0')))
7751 		return (EINVAL);
7752 
7753 	odrp = VTOR4(odvp);
7754 	ndrp = VTOR4(ndvp);
7755 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7756 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7757 			return (EINTR);
7758 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7759 			nfs_rw_exit(&odrp->r_rwlock);
7760 			return (EINTR);
7761 		}
7762 	} else {
7763 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7764 			return (EINTR);
7765 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7766 			nfs_rw_exit(&ndrp->r_rwlock);
7767 			return (EINTR);
7768 		}
7769 	}
7770 
7771 	/*
7772 	 * Lookup the target file.  If it exists, it needs to be
7773 	 * checked to see whether it is a mount point and whether
7774 	 * it is active (open).
7775 	 */
7776 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7777 	if (!error) {
7778 		int	isactive;
7779 
7780 		ASSERT(nfs4_consistent_type(nvp));
7781 		/*
7782 		 * If this file has been mounted on, then just
7783 		 * return busy because renaming to it would remove
7784 		 * the mounted file system from the name space.
7785 		 */
7786 		if (vn_ismntpt(nvp)) {
7787 			VN_RELE(nvp);
7788 			nfs_rw_exit(&odrp->r_rwlock);
7789 			nfs_rw_exit(&ndrp->r_rwlock);
7790 			return (EBUSY);
7791 		}
7792 
7793 		/*
7794 		 * First just remove the entry from the name cache, as it
7795 		 * is most likely the only entry for this vp.
7796 		 */
7797 		dnlc_remove(ndvp, nnm);
7798 
7799 		rp = VTOR4(nvp);
7800 
7801 		if (nvp->v_type != VREG) {
7802 			/*
7803 			 * Purge the name cache of all references to this vnode
7804 			 * so that we can check the reference count to infer
7805 			 * whether it is active or not.
7806 			 */
7807 			if (nvp->v_count > 1)
7808 				dnlc_purge_vp(nvp);
7809 
7810 			isactive = nvp->v_count > 1;
7811 		} else {
7812 			mutex_enter(&rp->r_os_lock);
7813 			isactive = list_head(&rp->r_open_streams) != NULL;
7814 			mutex_exit(&rp->r_os_lock);
7815 		}
7816 
7817 		/*
7818 		 * If the vnode is active and is not a directory,
7819 		 * arrange to rename it to a
7820 		 * temporary file so that it will continue to be
7821 		 * accessible.  This implements the "unlink-open-file"
7822 		 * semantics for the target of a rename operation.
7823 		 * Before doing this though, make sure that the
7824 		 * source and target files are not already the same.
7825 		 */
7826 		if (isactive && nvp->v_type != VDIR) {
7827 			/*
7828 			 * Lookup the source name.
7829 			 */
7830 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7831 
7832 			/*
7833 			 * The source name *should* already exist.
7834 			 */
7835 			if (error) {
7836 				VN_RELE(nvp);
7837 				nfs_rw_exit(&odrp->r_rwlock);
7838 				nfs_rw_exit(&ndrp->r_rwlock);
7839 				return (error);
7840 			}
7841 
7842 			ASSERT(nfs4_consistent_type(ovp));
7843 
7844 			/*
7845 			 * Compare the two vnodes.  If they are the same,
7846 			 * just release all held vnodes and return success.
7847 			 */
7848 			if (VN_CMP(ovp, nvp)) {
7849 				VN_RELE(ovp);
7850 				VN_RELE(nvp);
7851 				nfs_rw_exit(&odrp->r_rwlock);
7852 				nfs_rw_exit(&ndrp->r_rwlock);
7853 				return (0);
7854 			}
7855 
7856 			/*
7857 			 * Can't mix and match directories and non-
7858 			 * directories in rename operations.  We already
7859 			 * know that the target is not a directory.  If
7860 			 * the source is a directory, return an error.
7861 			 */
7862 			if (ovp->v_type == VDIR) {
7863 				VN_RELE(ovp);
7864 				VN_RELE(nvp);
7865 				nfs_rw_exit(&odrp->r_rwlock);
7866 				nfs_rw_exit(&ndrp->r_rwlock);
7867 				return (ENOTDIR);
7868 			}
7869 link_call:
7870 			/*
7871 			 * The target file exists, is not the same as
7872 			 * the source file, and is active.  We first
7873 			 * try to Link it to a temporary filename to
7874 			 * avoid having the server removing the file
7875 			 * completely (which could cause data loss to
7876 			 * the user's POV in the event the Rename fails
7877 			 * -- see bug 1165874).
7878 			 */
7879 			/*
7880 			 * The do_link and did_link booleans are
7881 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7882 			 * returned for the Rename.  Some servers can
7883 			 * not Rename over an Open file, so they return
7884 			 * this error.  The client needs to Remove the
7885 			 * newly created Link and do two Renames, just
7886 			 * as if the server didn't support LINK.
7887 			 */
7888 			tmpname = newname();
7889 			error = 0;
7890 
7891 			if (do_link) {
7892 				error = nfs4_link(ndvp, nvp, tmpname, cr,
7893 				    NULL, 0);
7894 			}
7895 			if (error == EOPNOTSUPP || !do_link) {
7896 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7897 				    cr, NULL, 0);
7898 				did_link = 0;
7899 			} else {
7900 				did_link = 1;
7901 			}
7902 			if (error) {
7903 				kmem_free(tmpname, MAXNAMELEN);
7904 				VN_RELE(ovp);
7905 				VN_RELE(nvp);
7906 				nfs_rw_exit(&odrp->r_rwlock);
7907 				nfs_rw_exit(&ndrp->r_rwlock);
7908 				return (error);
7909 			}
7910 
7911 			mutex_enter(&rp->r_statelock);
7912 			if (rp->r_unldvp == NULL) {
7913 				VN_HOLD(ndvp);
7914 				rp->r_unldvp = ndvp;
7915 				if (rp->r_unlcred != NULL)
7916 					crfree(rp->r_unlcred);
7917 				crhold(cr);
7918 				rp->r_unlcred = cr;
7919 				rp->r_unlname = tmpname;
7920 			} else {
7921 				if (rp->r_unlname)
7922 					kmem_free(rp->r_unlname, MAXNAMELEN);
7923 				rp->r_unlname = tmpname;
7924 			}
7925 			mutex_exit(&rp->r_statelock);
7926 		}
7927 
7928 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7929 
7930 		ASSERT(nfs4_consistent_type(nvp));
7931 	}
7932 
7933 	if (ovp == NULL) {
7934 		/*
7935 		 * When renaming directories to be a subdirectory of a
7936 		 * different parent, the dnlc entry for ".." will no
7937 		 * longer be valid, so it must be removed.
7938 		 *
7939 		 * We do a lookup here to determine whether we are renaming
7940 		 * a directory and we need to check if we are renaming
7941 		 * an unlinked file.  This might have already been done
7942 		 * in previous code, so we check ovp == NULL to avoid
7943 		 * doing it twice.
7944 		 */
7945 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7946 		/*
7947 		 * The source name *should* already exist.
7948 		 */
7949 		if (error) {
7950 			nfs_rw_exit(&odrp->r_rwlock);
7951 			nfs_rw_exit(&ndrp->r_rwlock);
7952 			if (nvp) {
7953 				VN_RELE(nvp);
7954 			}
7955 			return (error);
7956 		}
7957 		ASSERT(ovp != NULL);
7958 		ASSERT(nfs4_consistent_type(ovp));
7959 	}
7960 
7961 	/*
7962 	 * Is the object being renamed a dir, and if so, is
7963 	 * it being renamed to a child of itself?  The underlying
7964 	 * fs should ultimately return EINVAL for this case;
7965 	 * however, buggy beta non-Solaris NFSv4 servers at
7966 	 * interop testing events have allowed this behavior,
7967 	 * and it caused our client to panic due to a recursive
7968 	 * mutex_enter in fn_move.
7969 	 *
7970 	 * The tedious locking in fn_move could be changed to
7971 	 * deal with this case, and the client could avoid the
7972 	 * panic; however, the client would just confuse itself
7973 	 * later and misbehave.  A better way to handle the broken
7974 	 * server is to detect this condition and return EINVAL
7975 	 * without ever sending the the bogus rename to the server.
7976 	 * We know the rename is invalid -- just fail it now.
7977 	 */
7978 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7979 		VN_RELE(ovp);
7980 		nfs_rw_exit(&odrp->r_rwlock);
7981 		nfs_rw_exit(&ndrp->r_rwlock);
7982 		if (nvp) {
7983 			VN_RELE(nvp);
7984 		}
7985 		return (EINVAL);
7986 	}
7987 
7988 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7989 
7990 	/*
7991 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7992 	 * possible for the filehandle to change due to the rename.
7993 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7994 	 * the fh will not change because of the rename, but we still need
7995 	 * to update its rnode entry with the new name for
7996 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7997 	 * has no effect on these for now, but for future improvements,
7998 	 * we might want to use it too to simplify handling of files
7999 	 * that are open with that flag on. (XXX)
8000 	 */
8001 	mi = VTOMI4(odvp);
8002 	if (NFS4_VOLATILE_FH(mi))
8003 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
8004 		    &stat);
8005 	else
8006 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
8007 		    &stat);
8008 
8009 	ASSERT(nfs4_consistent_type(odvp));
8010 	ASSERT(nfs4_consistent_type(ndvp));
8011 	ASSERT(nfs4_consistent_type(ovp));
8012 
8013 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
8014 		do_link = 0;
8015 		/*
8016 		 * Before the 'link_call' code, we did a nfs4_lookup
8017 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
8018 		 * call we call VN_RELE to match that hold.  We need
8019 		 * to place an additional VN_HOLD here since we will
8020 		 * be hitting that VN_RELE again.
8021 		 */
8022 		VN_HOLD(nvp);
8023 
8024 		(void) nfs4_remove(ndvp, tmpname, cr, NULL, 0);
8025 
8026 		/* Undo the unlinked file naming stuff we just did */
8027 		mutex_enter(&rp->r_statelock);
8028 		if (rp->r_unldvp) {
8029 			VN_RELE(ndvp);
8030 			rp->r_unldvp = NULL;
8031 			if (rp->r_unlcred != NULL)
8032 				crfree(rp->r_unlcred);
8033 			rp->r_unlcred = NULL;
8034 			/* rp->r_unlanme points to tmpname */
8035 			if (rp->r_unlname)
8036 				kmem_free(rp->r_unlname, MAXNAMELEN);
8037 			rp->r_unlname = NULL;
8038 		}
8039 		mutex_exit(&rp->r_statelock);
8040 
8041 		if (nvp) {
8042 			VN_RELE(nvp);
8043 		}
8044 		goto link_call;
8045 	}
8046 
8047 	if (error) {
8048 		VN_RELE(ovp);
8049 		nfs_rw_exit(&odrp->r_rwlock);
8050 		nfs_rw_exit(&ndrp->r_rwlock);
8051 		if (nvp) {
8052 			VN_RELE(nvp);
8053 		}
8054 		return (error);
8055 	}
8056 
8057 	/*
8058 	 * when renaming directories to be a subdirectory of a
8059 	 * different parent, the dnlc entry for ".." will no
8060 	 * longer be valid, so it must be removed
8061 	 */
8062 	rp = VTOR4(ovp);
8063 	if (ndvp != odvp) {
8064 		if (ovp->v_type == VDIR) {
8065 			dnlc_remove(ovp, "..");
8066 			if (rp->r_dir != NULL)
8067 				nfs4_purge_rddir_cache(ovp);
8068 		}
8069 	}
8070 
8071 	/*
8072 	 * If we are renaming the unlinked file, update the
8073 	 * r_unldvp and r_unlname as needed.
8074 	 */
8075 	mutex_enter(&rp->r_statelock);
8076 	if (rp->r_unldvp != NULL) {
8077 		if (strcmp(rp->r_unlname, onm) == 0) {
8078 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
8079 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
8080 			if (ndvp != rp->r_unldvp) {
8081 				VN_RELE(rp->r_unldvp);
8082 				rp->r_unldvp = ndvp;
8083 				VN_HOLD(ndvp);
8084 			}
8085 		}
8086 	}
8087 	mutex_exit(&rp->r_statelock);
8088 
8089 	/*
8090 	 * Notify the rename vnevents to source vnode, and to the target
8091 	 * vnode if it already existed.
8092 	 */
8093 	if (error == 0) {
8094 		vnode_t *tvp;
8095 		rnode4_t *trp;
8096 		/*
8097 		 * Notify the vnode. Each links is represented by
8098 		 * a different vnode, in nfsv4.
8099 		 */
8100 		if (nvp) {
8101 			trp = VTOR4(nvp);
8102 			tvp = nvp;
8103 			if (IS_SHADOW(nvp, trp))
8104 				tvp = RTOV4(trp);
8105 			vnevent_rename_dest(tvp, ndvp, nnm, ct);
8106 		}
8107 
8108 		/*
8109 		 * if the source and destination directory are not the
8110 		 * same notify the destination directory.
8111 		 */
8112 		if (VTOR4(odvp) != VTOR4(ndvp)) {
8113 			trp = VTOR4(ndvp);
8114 			tvp = ndvp;
8115 			if (IS_SHADOW(ndvp, trp))
8116 				tvp = RTOV4(trp);
8117 			vnevent_rename_dest_dir(tvp, ct);
8118 		}
8119 
8120 		trp = VTOR4(ovp);
8121 		tvp = ovp;
8122 		if (IS_SHADOW(ovp, trp))
8123 			tvp = RTOV4(trp);
8124 		vnevent_rename_src(tvp, odvp, onm, ct);
8125 	}
8126 
8127 	if (nvp) {
8128 		VN_RELE(nvp);
8129 	}
8130 	VN_RELE(ovp);
8131 
8132 	nfs_rw_exit(&odrp->r_rwlock);
8133 	nfs_rw_exit(&ndrp->r_rwlock);
8134 
8135 	return (error);
8136 }
8137 
8138 /*
8139  * When the parent directory has changed, sv_dfh must be updated
8140  */
8141 static void
8142 update_parentdir_sfh(vnode_t *vp, vnode_t *ndvp)
8143 {
8144 	svnode_t *sv = VTOSV(vp);
8145 	nfs4_sharedfh_t *old_dfh = sv->sv_dfh;
8146 	nfs4_sharedfh_t *new_dfh = VTOR4(ndvp)->r_fh;
8147 
8148 	sfh4_hold(new_dfh);
8149 	sv->sv_dfh = new_dfh;
8150 	sfh4_rele(&old_dfh);
8151 }
8152 
8153 /*
8154  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
8155  * when it is known that the filehandle is persistent through rename.
8156  *
8157  * Rename requires that the current fh be the target directory and the
8158  * saved fh be the source directory. After the operation, the current fh
8159  * is unchanged.
8160  * The compound op structure for persistent fh rename is:
8161  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
8162  * Rather than bother with the directory postop args, we'll simply
8163  * update that a change occurred in the cache, so no post-op getattrs.
8164  */
8165 static int
8166 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
8167     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8168 {
8169 	COMPOUND4args_clnt args;
8170 	COMPOUND4res_clnt res, *resp = NULL;
8171 	nfs_argop4 *argop;
8172 	nfs_resop4 *resop;
8173 	int doqueue, argoplist_size;
8174 	mntinfo4_t *mi;
8175 	rnode4_t *odrp = VTOR4(odvp);
8176 	rnode4_t *ndrp = VTOR4(ndvp);
8177 	RENAME4res *rn_res;
8178 	bool_t needrecov;
8179 	nfs4_recov_state_t recov_state;
8180 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8181 	dirattr_info_t dinfo, *dinfop;
8182 
8183 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8184 
8185 	recov_state.rs_flags = 0;
8186 	recov_state.rs_num_retry_despite_err = 0;
8187 
8188 	/*
8189 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
8190 	 *
8191 	 * If source/target are different dirs, then append putfh(src); getattr
8192 	 */
8193 	args.array_len = (odvp == ndvp) ? 5 : 7;
8194 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8195 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8196 
8197 recov_retry:
8198 	*statp = NFS4_OK;
8199 
8200 	/* No need to Lookup the file, persistent fh */
8201 	args.ctag = TAG_RENAME;
8202 
8203 	mi = VTOMI4(odvp);
8204 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8205 	if (e.error) {
8206 		kmem_free(argop, argoplist_size);
8207 		return (e.error);
8208 	}
8209 
8210 	/* 0: putfh source directory */
8211 	argop[0].argop = OP_CPUTFH;
8212 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8213 
8214 	/* 1: Save source fh to free up current for target */
8215 	argop[1].argop = OP_SAVEFH;
8216 
8217 	/* 2: putfh targetdir */
8218 	argop[2].argop = OP_CPUTFH;
8219 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8220 
8221 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8222 	argop[3].argop = OP_CRENAME;
8223 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8224 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8225 
8226 	/* 4: getattr (targetdir) */
8227 	argop[4].argop = OP_GETATTR;
8228 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8229 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8230 
8231 	if (ndvp != odvp) {
8232 
8233 		/* 5: putfh (sourcedir) */
8234 		argop[5].argop = OP_CPUTFH;
8235 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8236 
8237 		/* 6: getattr (sourcedir) */
8238 		argop[6].argop = OP_GETATTR;
8239 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8240 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8241 	}
8242 
8243 	dnlc_remove(odvp, onm);
8244 	dnlc_remove(ndvp, nnm);
8245 
8246 	doqueue = 1;
8247 	dinfo.di_time_call = gethrtime();
8248 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8249 
8250 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8251 	if (e.error) {
8252 		PURGE_ATTRCACHE4(odvp);
8253 		PURGE_ATTRCACHE4(ndvp);
8254 	} else {
8255 		*statp = res.status;
8256 	}
8257 
8258 	if (needrecov) {
8259 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8260 		    OP_RENAME, NULL, NULL, NULL) == FALSE) {
8261 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8262 			if (!e.error)
8263 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8264 				    (caddr_t)&res);
8265 			goto recov_retry;
8266 		}
8267 	}
8268 
8269 	if (!e.error) {
8270 		resp = &res;
8271 		/*
8272 		 * as long as OP_RENAME
8273 		 */
8274 		if (res.status != NFS4_OK && res.array_len <= 4) {
8275 			e.error = geterrno4(res.status);
8276 			PURGE_ATTRCACHE4(odvp);
8277 			PURGE_ATTRCACHE4(ndvp);
8278 			/*
8279 			 * System V defines rename to return EEXIST, not
8280 			 * ENOTEMPTY if the target directory is not empty.
8281 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8282 			 * which geterrno4 maps to ENOTEMPTY.
8283 			 */
8284 			if (e.error == ENOTEMPTY)
8285 				e.error = EEXIST;
8286 		} else {
8287 
8288 			resop = &res.array[3];	/* rename res */
8289 			rn_res = &resop->nfs_resop4_u.oprename;
8290 
8291 			if (res.status == NFS4_OK) {
8292 				/*
8293 				 * Update target attribute, readdir and dnlc
8294 				 * caches.
8295 				 */
8296 				dinfo.di_garp =
8297 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8298 				dinfo.di_cred = cr;
8299 				dinfop = &dinfo;
8300 			} else
8301 				dinfop = NULL;
8302 
8303 			nfs4_update_dircaches(&rn_res->target_cinfo,
8304 			    ndvp, NULL, NULL, dinfop);
8305 
8306 			/*
8307 			 * Update source attribute, readdir and dnlc caches
8308 			 *
8309 			 */
8310 			if (ndvp != odvp) {
8311 				update_parentdir_sfh(renvp, ndvp);
8312 
8313 				if (dinfop)
8314 					dinfo.di_garp =
8315 					    &(res.array[6].nfs_resop4_u.
8316 					    opgetattr.ga_res);
8317 
8318 				nfs4_update_dircaches(&rn_res->source_cinfo,
8319 				    odvp, NULL, NULL, dinfop);
8320 			}
8321 
8322 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8323 			    nnm);
8324 		}
8325 	}
8326 
8327 	if (resp)
8328 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8329 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8330 	kmem_free(argop, argoplist_size);
8331 
8332 	return (e.error);
8333 }
8334 
8335 /*
8336  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8337  * it is possible for the filehandle to change due to the rename.
8338  *
8339  * The compound req in this case includes a post-rename lookup and getattr
8340  * to ensure that we have the correct fh and attributes for the object.
8341  *
8342  * Rename requires that the current fh be the target directory and the
8343  * saved fh be the source directory. After the operation, the current fh
8344  * is unchanged.
8345  *
8346  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8347  * update the filehandle for the renamed object.  We also get the old
8348  * filehandle for historical reasons; this should be taken out sometime.
8349  * This results in a rather cumbersome compound...
8350  *
8351  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8352  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8353  *
8354  */
8355 static int
8356 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8357     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8358 {
8359 	COMPOUND4args_clnt args;
8360 	COMPOUND4res_clnt res, *resp = NULL;
8361 	int argoplist_size;
8362 	nfs_argop4 *argop;
8363 	nfs_resop4 *resop;
8364 	int doqueue;
8365 	mntinfo4_t *mi;
8366 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8367 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8368 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8369 	RENAME4res *rn_res;
8370 	GETFH4res *ngf_res;
8371 	bool_t needrecov;
8372 	nfs4_recov_state_t recov_state;
8373 	hrtime_t t;
8374 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8375 	dirattr_info_t dinfo, *dinfop = &dinfo;
8376 
8377 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8378 
8379 	recov_state.rs_flags = 0;
8380 	recov_state.rs_num_retry_despite_err = 0;
8381 
8382 recov_retry:
8383 	*statp = NFS4_OK;
8384 
8385 	/*
8386 	 * There is a window between the RPC and updating the path and
8387 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8388 	 * code, so that it doesn't try to use the old path during that
8389 	 * window.
8390 	 */
8391 	mutex_enter(&orp->r_statelock);
8392 	while (orp->r_flags & R4RECEXPFH) {
8393 		klwp_t *lwp = ttolwp(curthread);
8394 
8395 		if (lwp != NULL)
8396 			lwp->lwp_nostop++;
8397 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8398 			mutex_exit(&orp->r_statelock);
8399 			if (lwp != NULL)
8400 				lwp->lwp_nostop--;
8401 			return (EINTR);
8402 		}
8403 		if (lwp != NULL)
8404 			lwp->lwp_nostop--;
8405 	}
8406 	orp->r_flags |= R4RECEXPFH;
8407 	mutex_exit(&orp->r_statelock);
8408 
8409 	mi = VTOMI4(odvp);
8410 
8411 	args.ctag = TAG_RENAME_VFH;
8412 	args.array_len = (odvp == ndvp) ? 10 : 12;
8413 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8414 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8415 
8416 	/*
8417 	 * Rename ops:
8418 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8419 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8420 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8421 	 *
8422 	 *    if (odvp != ndvp)
8423 	 *	add putfh(sourcedir), getattr(sourcedir) }
8424 	 */
8425 	args.array = argop;
8426 
8427 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8428 	    &recov_state, NULL);
8429 	if (e.error) {
8430 		kmem_free(argop, argoplist_size);
8431 		mutex_enter(&orp->r_statelock);
8432 		orp->r_flags &= ~R4RECEXPFH;
8433 		cv_broadcast(&orp->r_cv);
8434 		mutex_exit(&orp->r_statelock);
8435 		return (e.error);
8436 	}
8437 
8438 	/* 0: putfh source directory */
8439 	argop[0].argop = OP_CPUTFH;
8440 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8441 
8442 	/* 1: Save source fh to free up current for target */
8443 	argop[1].argop = OP_SAVEFH;
8444 
8445 	/* 2: Lookup pre-rename fh of renamed object */
8446 	argop[2].argop = OP_CLOOKUP;
8447 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8448 
8449 	/* 3: getfh fh of renamed object (before rename) */
8450 	argop[3].argop = OP_GETFH;
8451 
8452 	/* 4: putfh targetdir */
8453 	argop[4].argop = OP_CPUTFH;
8454 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8455 
8456 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8457 	argop[5].argop = OP_CRENAME;
8458 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8459 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8460 
8461 	/* 6: getattr of target dir (post op attrs) */
8462 	argop[6].argop = OP_GETATTR;
8463 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8464 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8465 
8466 	/* 7: Lookup post-rename fh of renamed object */
8467 	argop[7].argop = OP_CLOOKUP;
8468 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8469 
8470 	/* 8: getfh fh of renamed object (after rename) */
8471 	argop[8].argop = OP_GETFH;
8472 
8473 	/* 9: getattr of renamed object */
8474 	argop[9].argop = OP_GETATTR;
8475 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8476 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8477 
8478 	/*
8479 	 * If source/target dirs are different, then get new post-op
8480 	 * attrs for source dir also.
8481 	 */
8482 	if (ndvp != odvp) {
8483 		/* 10: putfh (sourcedir) */
8484 		argop[10].argop = OP_CPUTFH;
8485 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8486 
8487 		/* 11: getattr (sourcedir) */
8488 		argop[11].argop = OP_GETATTR;
8489 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8490 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8491 	}
8492 
8493 	dnlc_remove(odvp, onm);
8494 	dnlc_remove(ndvp, nnm);
8495 
8496 	doqueue = 1;
8497 	t = gethrtime();
8498 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8499 
8500 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8501 	if (e.error) {
8502 		PURGE_ATTRCACHE4(odvp);
8503 		PURGE_ATTRCACHE4(ndvp);
8504 		if (!needrecov) {
8505 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8506 			    &recov_state, needrecov);
8507 			goto out;
8508 		}
8509 	} else {
8510 		*statp = res.status;
8511 	}
8512 
8513 	if (needrecov) {
8514 		bool_t abort;
8515 
8516 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8517 		    OP_RENAME, NULL, NULL, NULL);
8518 		if (abort == FALSE) {
8519 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8520 			    &recov_state, needrecov);
8521 			kmem_free(argop, argoplist_size);
8522 			if (!e.error)
8523 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8524 				    (caddr_t)&res);
8525 			mutex_enter(&orp->r_statelock);
8526 			orp->r_flags &= ~R4RECEXPFH;
8527 			cv_broadcast(&orp->r_cv);
8528 			mutex_exit(&orp->r_statelock);
8529 			goto recov_retry;
8530 		} else {
8531 			if (e.error != 0) {
8532 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8533 				    &recov_state, needrecov);
8534 				goto out;
8535 			}
8536 			/* fall through for res.status case */
8537 		}
8538 	}
8539 
8540 	resp = &res;
8541 	/*
8542 	 * If OP_RENAME (or any prev op) failed, then return an error.
8543 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8544 	 */
8545 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8546 		/*
8547 		 * Error in an op other than last Getattr
8548 		 */
8549 		e.error = geterrno4(res.status);
8550 		PURGE_ATTRCACHE4(odvp);
8551 		PURGE_ATTRCACHE4(ndvp);
8552 		/*
8553 		 * System V defines rename to return EEXIST, not
8554 		 * ENOTEMPTY if the target directory is not empty.
8555 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8556 		 * which geterrno4 maps to ENOTEMPTY.
8557 		 */
8558 		if (e.error == ENOTEMPTY)
8559 			e.error = EEXIST;
8560 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8561 		    needrecov);
8562 		goto out;
8563 	}
8564 
8565 	/* rename results */
8566 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8567 
8568 	if (res.status == NFS4_OK) {
8569 		/* Update target attribute, readdir and dnlc caches */
8570 		dinfo.di_garp =
8571 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
8572 		dinfo.di_cred = cr;
8573 		dinfo.di_time_call = t;
8574 	} else
8575 		dinfop = NULL;
8576 
8577 	/* Update source cache attribute, readdir and dnlc caches */
8578 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8579 
8580 	/* Update source cache attribute, readdir and dnlc caches */
8581 	if (ndvp != odvp) {
8582 		update_parentdir_sfh(ovp, ndvp);
8583 
8584 		/*
8585 		 * If dinfop is non-NULL, then compound succeded, so
8586 		 * set di_garp to attrs for source dir.  dinfop is only
8587 		 * set to NULL when compound fails.
8588 		 */
8589 		if (dinfop)
8590 			dinfo.di_garp =
8591 			    &res.array[11].nfs_resop4_u.opgetattr.ga_res;
8592 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8593 		    dinfop);
8594 	}
8595 
8596 	/*
8597 	 * Update the rnode with the new component name and args,
8598 	 * and if the file handle changed, also update it with the new fh.
8599 	 * This is only necessary if the target object has an rnode
8600 	 * entry and there is no need to create one for it.
8601 	 */
8602 	resop = &res.array[8];	/* getfh new res */
8603 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8604 
8605 	/*
8606 	 * Update the path and filehandle for the renamed object.
8607 	 */
8608 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8609 
8610 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8611 
8612 	if (res.status == NFS4_OK) {
8613 		resop++;	/* getattr res */
8614 		e.error = nfs4_update_attrcache(res.status,
8615 		    &resop->nfs_resop4_u.opgetattr.ga_res,
8616 		    t, ovp, cr);
8617 	}
8618 
8619 out:
8620 	kmem_free(argop, argoplist_size);
8621 	if (resp)
8622 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8623 	mutex_enter(&orp->r_statelock);
8624 	orp->r_flags &= ~R4RECEXPFH;
8625 	cv_broadcast(&orp->r_cv);
8626 	mutex_exit(&orp->r_statelock);
8627 
8628 	return (e.error);
8629 }
8630 
8631 /* ARGSUSED */
8632 static int
8633 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr,
8634     caller_context_t *ct, int flags, vsecattr_t *vsecp)
8635 {
8636 	int error;
8637 	vnode_t *vp;
8638 
8639 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8640 		return (EPERM);
8641 	/*
8642 	 * As ".." has special meaning and rather than send a mkdir
8643 	 * over the wire to just let the server freak out, we just
8644 	 * short circuit it here and return EEXIST
8645 	 */
8646 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8647 		return (EEXIST);
8648 
8649 	/*
8650 	 * Decision to get the right gid and setgid bit of the
8651 	 * new directory is now made in call_nfs4_create_req.
8652 	 */
8653 	va->va_mask |= AT_MODE;
8654 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8655 	if (error)
8656 		return (error);
8657 
8658 	*vpp = vp;
8659 	return (0);
8660 }
8661 
8662 
8663 /*
8664  * rmdir is using the same remove v4 op as does remove.
8665  * Remove requires that the current fh be the target directory.
8666  * After the operation, the current fh is unchanged.
8667  * The compound op structure is:
8668  *      PUTFH(targetdir), REMOVE
8669  */
8670 /*ARGSUSED4*/
8671 static int
8672 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr,
8673     caller_context_t *ct, int flags)
8674 {
8675 	int need_end_op = FALSE;
8676 	COMPOUND4args_clnt args;
8677 	COMPOUND4res_clnt res, *resp = NULL;
8678 	REMOVE4res *rm_res;
8679 	nfs_argop4 argop[3];
8680 	nfs_resop4 *resop;
8681 	vnode_t *vp;
8682 	int doqueue;
8683 	mntinfo4_t *mi;
8684 	rnode4_t *drp;
8685 	bool_t needrecov = FALSE;
8686 	nfs4_recov_state_t recov_state;
8687 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8688 	dirattr_info_t dinfo, *dinfop;
8689 
8690 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8691 		return (EPERM);
8692 	/*
8693 	 * As ".." has special meaning and rather than send a rmdir
8694 	 * over the wire to just let the server freak out, we just
8695 	 * short circuit it here and return EEXIST
8696 	 */
8697 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8698 		return (EEXIST);
8699 
8700 	drp = VTOR4(dvp);
8701 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8702 		return (EINTR);
8703 
8704 	/*
8705 	 * Attempt to prevent a rmdir(".") from succeeding.
8706 	 */
8707 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8708 	if (e.error) {
8709 		nfs_rw_exit(&drp->r_rwlock);
8710 		return (e.error);
8711 	}
8712 	if (vp == cdir) {
8713 		VN_RELE(vp);
8714 		nfs_rw_exit(&drp->r_rwlock);
8715 		return (EINVAL);
8716 	}
8717 
8718 	/*
8719 	 * Since nfsv4 remove op works on both files and directories,
8720 	 * check that the removed object is indeed a directory.
8721 	 */
8722 	if (vp->v_type != VDIR) {
8723 		VN_RELE(vp);
8724 		nfs_rw_exit(&drp->r_rwlock);
8725 		return (ENOTDIR);
8726 	}
8727 
8728 	/*
8729 	 * First just remove the entry from the name cache, as it
8730 	 * is most likely an entry for this vp.
8731 	 */
8732 	dnlc_remove(dvp, nm);
8733 
8734 	/*
8735 	 * If there vnode reference count is greater than one, then
8736 	 * there may be additional references in the DNLC which will
8737 	 * need to be purged.  First, trying removing the entry for
8738 	 * the parent directory and see if that removes the additional
8739 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8740 	 * to completely remove any references to the directory which
8741 	 * might still exist in the DNLC.
8742 	 */
8743 	if (vp->v_count > 1) {
8744 		dnlc_remove(vp, "..");
8745 		if (vp->v_count > 1)
8746 			dnlc_purge_vp(vp);
8747 	}
8748 
8749 	mi = VTOMI4(dvp);
8750 	recov_state.rs_flags = 0;
8751 	recov_state.rs_num_retry_despite_err = 0;
8752 
8753 recov_retry:
8754 	args.ctag = TAG_RMDIR;
8755 
8756 	/*
8757 	 * Rmdir ops: putfh dir; remove
8758 	 */
8759 	args.array_len = 3;
8760 	args.array = argop;
8761 
8762 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8763 	if (e.error) {
8764 		nfs_rw_exit(&drp->r_rwlock);
8765 		return (e.error);
8766 	}
8767 	need_end_op = TRUE;
8768 
8769 	/* putfh directory */
8770 	argop[0].argop = OP_CPUTFH;
8771 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8772 
8773 	/* remove */
8774 	argop[1].argop = OP_CREMOVE;
8775 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8776 
8777 	/* getattr (postop attrs for dir that contained removed dir) */
8778 	argop[2].argop = OP_GETATTR;
8779 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8780 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8781 
8782 	dinfo.di_time_call = gethrtime();
8783 	doqueue = 1;
8784 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8785 
8786 	PURGE_ATTRCACHE4(vp);
8787 
8788 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8789 	if (e.error) {
8790 		PURGE_ATTRCACHE4(dvp);
8791 	}
8792 
8793 	if (needrecov) {
8794 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8795 		    NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
8796 			if (!e.error)
8797 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8798 				    (caddr_t)&res);
8799 
8800 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8801 			    needrecov);
8802 			need_end_op = FALSE;
8803 			goto recov_retry;
8804 		}
8805 	}
8806 
8807 	if (!e.error) {
8808 		resp = &res;
8809 
8810 		/*
8811 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8812 		 * failed.
8813 		 */
8814 		if (res.status != NFS4_OK && res.array_len <= 2) {
8815 			e.error = geterrno4(res.status);
8816 			PURGE_ATTRCACHE4(dvp);
8817 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8818 			    &recov_state, needrecov);
8819 			need_end_op = FALSE;
8820 			nfs4_purge_stale_fh(e.error, dvp, cr);
8821 			/*
8822 			 * System V defines rmdir to return EEXIST, not
8823 			 * ENOTEMPTY if the directory is not empty.  Over
8824 			 * the wire, the error is NFSERR_ENOTEMPTY which
8825 			 * geterrno4 maps to ENOTEMPTY.
8826 			 */
8827 			if (e.error == ENOTEMPTY)
8828 				e.error = EEXIST;
8829 		} else {
8830 			resop = &res.array[1];	/* remove res */
8831 			rm_res = &resop->nfs_resop4_u.opremove;
8832 
8833 			if (res.status == NFS4_OK) {
8834 				resop = &res.array[2];	/* dir attrs */
8835 				dinfo.di_garp =
8836 				    &resop->nfs_resop4_u.opgetattr.ga_res;
8837 				dinfo.di_cred = cr;
8838 				dinfop = &dinfo;
8839 			} else
8840 				dinfop = NULL;
8841 
8842 			/* Update dir attribute, readdir and dnlc caches */
8843 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8844 			    dinfop);
8845 
8846 			/* destroy rddir cache for dir that was removed */
8847 			if (VTOR4(vp)->r_dir != NULL)
8848 				nfs4_purge_rddir_cache(vp);
8849 		}
8850 	}
8851 
8852 	if (need_end_op)
8853 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8854 
8855 	nfs_rw_exit(&drp->r_rwlock);
8856 
8857 	if (resp)
8858 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8859 
8860 	if (e.error == 0) {
8861 		vnode_t *tvp;
8862 		rnode4_t *trp;
8863 		trp = VTOR4(vp);
8864 		tvp = vp;
8865 		if (IS_SHADOW(vp, trp))
8866 			tvp = RTOV4(trp);
8867 		vnevent_rmdir(tvp, dvp, nm, ct);
8868 	}
8869 
8870 	VN_RELE(vp);
8871 
8872 	return (e.error);
8873 }
8874 
8875 /* ARGSUSED */
8876 static int
8877 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr,
8878     caller_context_t *ct, int flags)
8879 {
8880 	int error;
8881 	vnode_t *vp;
8882 	rnode4_t *rp;
8883 	char *contents;
8884 	mntinfo4_t *mi = VTOMI4(dvp);
8885 
8886 	if (nfs_zone() != mi->mi_zone)
8887 		return (EPERM);
8888 	if (!(mi->mi_flags & MI4_SYMLINK))
8889 		return (EOPNOTSUPP);
8890 
8891 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8892 	if (error)
8893 		return (error);
8894 
8895 	ASSERT(nfs4_consistent_type(vp));
8896 	rp = VTOR4(vp);
8897 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8898 
8899 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8900 
8901 		if (contents != NULL) {
8902 			mutex_enter(&rp->r_statelock);
8903 			if (rp->r_symlink.contents == NULL) {
8904 				rp->r_symlink.len = strlen(tnm);
8905 				bcopy(tnm, contents, rp->r_symlink.len);
8906 				rp->r_symlink.contents = contents;
8907 				rp->r_symlink.size = MAXPATHLEN;
8908 				mutex_exit(&rp->r_statelock);
8909 			} else {
8910 				mutex_exit(&rp->r_statelock);
8911 				kmem_free((void *)contents, MAXPATHLEN);
8912 			}
8913 		}
8914 	}
8915 	VN_RELE(vp);
8916 
8917 	return (error);
8918 }
8919 
8920 
8921 /*
8922  * Read directory entries.
8923  * There are some weird things to look out for here.  The uio_loffset
8924  * field is either 0 or it is the offset returned from a previous
8925  * readdir.  It is an opaque value used by the server to find the
8926  * correct directory block to read. The count field is the number
8927  * of blocks to read on the server.  This is advisory only, the server
8928  * may return only one block's worth of entries.  Entries may be compressed
8929  * on the server.
8930  */
8931 /* ARGSUSED */
8932 static int
8933 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp,
8934     caller_context_t *ct, int flags)
8935 {
8936 	int error;
8937 	uint_t count;
8938 	rnode4_t *rp;
8939 	rddir4_cache *rdc;
8940 	rddir4_cache *rrdc;
8941 
8942 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8943 		return (EIO);
8944 	rp = VTOR4(vp);
8945 
8946 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8947 
8948 	/*
8949 	 * Make sure that the directory cache is valid.
8950 	 */
8951 	if (rp->r_dir != NULL) {
8952 		if (nfs_disable_rddir_cache != 0) {
8953 			/*
8954 			 * Setting nfs_disable_rddir_cache in /etc/system
8955 			 * allows interoperability with servers that do not
8956 			 * properly update the attributes of directories.
8957 			 * Any cached information gets purged before an
8958 			 * access is made to it.
8959 			 */
8960 			nfs4_purge_rddir_cache(vp);
8961 		}
8962 
8963 		error = nfs4_validate_caches(vp, cr);
8964 		if (error)
8965 			return (error);
8966 	}
8967 
8968 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8969 
8970 	/*
8971 	 * Short circuit last readdir which always returns 0 bytes.
8972 	 * This can be done after the directory has been read through
8973 	 * completely at least once.  This will set r_direof which
8974 	 * can be used to find the value of the last cookie.
8975 	 */
8976 	mutex_enter(&rp->r_statelock);
8977 	if (rp->r_direof != NULL &&
8978 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8979 		mutex_exit(&rp->r_statelock);
8980 #ifdef DEBUG
8981 		nfs4_readdir_cache_shorts++;
8982 #endif
8983 		if (eofp)
8984 			*eofp = 1;
8985 		return (0);
8986 	}
8987 
8988 	/*
8989 	 * Look for a cache entry.  Cache entries are identified
8990 	 * by the NFS cookie value and the byte count requested.
8991 	 */
8992 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8993 
8994 	/*
8995 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8996 	 */
8997 	if (rdc == NULL) {
8998 		mutex_exit(&rp->r_statelock);
8999 		return (EINTR);
9000 	}
9001 
9002 	/*
9003 	 * Check to see if we need to fill this entry in.
9004 	 */
9005 	if (rdc->flags & RDDIRREQ) {
9006 		rdc->flags &= ~RDDIRREQ;
9007 		rdc->flags |= RDDIR;
9008 		mutex_exit(&rp->r_statelock);
9009 
9010 		/*
9011 		 * Do the readdir.
9012 		 */
9013 		nfs4readdir(vp, rdc, cr);
9014 
9015 		/*
9016 		 * Reacquire the lock, so that we can continue
9017 		 */
9018 		mutex_enter(&rp->r_statelock);
9019 		/*
9020 		 * The entry is now complete
9021 		 */
9022 		rdc->flags &= ~RDDIR;
9023 	}
9024 
9025 	ASSERT(!(rdc->flags & RDDIR));
9026 
9027 	/*
9028 	 * If an error occurred while attempting
9029 	 * to fill the cache entry, mark the entry invalid and
9030 	 * just return the error.
9031 	 */
9032 	if (rdc->error) {
9033 		error = rdc->error;
9034 		rdc->flags |= RDDIRREQ;
9035 		rddir4_cache_rele(rp, rdc);
9036 		mutex_exit(&rp->r_statelock);
9037 		return (error);
9038 	}
9039 
9040 	/*
9041 	 * The cache entry is complete and good,
9042 	 * copyout the dirent structs to the calling
9043 	 * thread.
9044 	 */
9045 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
9046 
9047 	/*
9048 	 * If no error occurred during the copyout,
9049 	 * update the offset in the uio struct to
9050 	 * contain the value of the next NFS 4 cookie
9051 	 * and set the eof value appropriately.
9052 	 */
9053 	if (!error) {
9054 		uiop->uio_loffset = rdc->nfs4_ncookie;
9055 		if (eofp)
9056 			*eofp = rdc->eof;
9057 	}
9058 
9059 	/*
9060 	 * Decide whether to do readahead.  Don't if we
9061 	 * have already read to the end of directory.
9062 	 */
9063 	if (rdc->eof) {
9064 		/*
9065 		 * Make the entry the direof only if it is cached
9066 		 */
9067 		if (rdc->flags & RDDIRCACHED)
9068 			rp->r_direof = rdc;
9069 		rddir4_cache_rele(rp, rdc);
9070 		mutex_exit(&rp->r_statelock);
9071 		return (error);
9072 	}
9073 
9074 	/* Determine if a readdir readahead should be done */
9075 	if (!(rp->r_flags & R4LOOKUP)) {
9076 		rddir4_cache_rele(rp, rdc);
9077 		mutex_exit(&rp->r_statelock);
9078 		return (error);
9079 	}
9080 
9081 	/*
9082 	 * Now look for a readahead entry.
9083 	 *
9084 	 * Check to see whether we found an entry for the readahead.
9085 	 * If so, we don't need to do anything further, so free the new
9086 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
9087 	 * it to the cache, and then initiate an asynchronous readdir
9088 	 * operation to fill it.
9089 	 */
9090 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
9091 
9092 	/*
9093 	 * A readdir cache entry could not be obtained for the readahead.  In
9094 	 * this case we skip the readahead and return.
9095 	 */
9096 	if (rrdc == NULL) {
9097 		rddir4_cache_rele(rp, rdc);
9098 		mutex_exit(&rp->r_statelock);
9099 		return (error);
9100 	}
9101 
9102 	/*
9103 	 * Check to see if we need to fill this entry in.
9104 	 */
9105 	if (rrdc->flags & RDDIRREQ) {
9106 		rrdc->flags &= ~RDDIRREQ;
9107 		rrdc->flags |= RDDIR;
9108 		rddir4_cache_rele(rp, rdc);
9109 		mutex_exit(&rp->r_statelock);
9110 #ifdef DEBUG
9111 		nfs4_readdir_readahead++;
9112 #endif
9113 		/*
9114 		 * Do the readdir.
9115 		 */
9116 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
9117 		return (error);
9118 	}
9119 
9120 	rddir4_cache_rele(rp, rrdc);
9121 	rddir4_cache_rele(rp, rdc);
9122 	mutex_exit(&rp->r_statelock);
9123 	return (error);
9124 }
9125 
9126 static int
9127 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9128 {
9129 	int error;
9130 	rnode4_t *rp;
9131 
9132 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9133 
9134 	rp = VTOR4(vp);
9135 
9136 	/*
9137 	 * Obtain the readdir results for the caller.
9138 	 */
9139 	nfs4readdir(vp, rdc, cr);
9140 
9141 	mutex_enter(&rp->r_statelock);
9142 	/*
9143 	 * The entry is now complete
9144 	 */
9145 	rdc->flags &= ~RDDIR;
9146 
9147 	error = rdc->error;
9148 	if (error)
9149 		rdc->flags |= RDDIRREQ;
9150 	rddir4_cache_rele(rp, rdc);
9151 	mutex_exit(&rp->r_statelock);
9152 
9153 	return (error);
9154 }
9155 
9156 /*
9157  * Read directory entries.
9158  * There are some weird things to look out for here.  The uio_loffset
9159  * field is either 0 or it is the offset returned from a previous
9160  * readdir.  It is an opaque value used by the server to find the
9161  * correct directory block to read. The count field is the number
9162  * of blocks to read on the server.  This is advisory only, the server
9163  * may return only one block's worth of entries.  Entries may be compressed
9164  * on the server.
9165  *
9166  * Generates the following compound request:
9167  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9168  *    must include a Lookupp as well. In this case, send:
9169  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9170  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9171  *
9172  * Get complete attributes and filehandles for entries if this is the
9173  * first read of the directory. Otherwise, just get fileid's.
9174  */
9175 static void
9176 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9177 {
9178 	COMPOUND4args_clnt args;
9179 	COMPOUND4res_clnt res;
9180 	READDIR4args *rargs;
9181 	READDIR4res_clnt *rd_res;
9182 	bitmap4 rd_bitsval;
9183 	nfs_argop4 argop[5];
9184 	nfs_resop4 *resop;
9185 	rnode4_t *rp = VTOR4(vp);
9186 	mntinfo4_t *mi = VTOMI4(vp);
9187 	int doqueue;
9188 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9189 	vnode_t *dvp;
9190 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9191 	int num_ops, res_opcnt;
9192 	bool_t needrecov = FALSE;
9193 	nfs4_recov_state_t recov_state;
9194 	hrtime_t t;
9195 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9196 
9197 	ASSERT(nfs_zone() == mi->mi_zone);
9198 	ASSERT(rdc->flags & RDDIR);
9199 	ASSERT(rdc->entries == NULL);
9200 
9201 	/*
9202 	 * If rp were a stub, it should have triggered and caused
9203 	 * a mount for us to get this far.
9204 	 */
9205 	ASSERT(!RP_ISSTUB(rp));
9206 
9207 	num_ops = 2;
9208 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9209 		/*
9210 		 * Since nfsv4 readdir may not return entries for "." and "..",
9211 		 * the client must recreate them:
9212 		 * To find the correct nodeid, do the following:
9213 		 * For current node, get nodeid from dnlc.
9214 		 * - if current node is rootvp, set pnodeid to nodeid.
9215 		 * - else if parent is in the dnlc, get its nodeid from there.
9216 		 * - else add LOOKUPP+GETATTR to compound.
9217 		 */
9218 		nodeid = rp->r_attr.va_nodeid;
9219 		if (vp->v_flag & VROOT) {
9220 			pnodeid = nodeid;	/* root of mount point */
9221 		} else {
9222 			dvp = dnlc_lookup(vp, "..");
9223 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9224 				/* parent in dnlc cache - no need for otw */
9225 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9226 			} else {
9227 				/*
9228 				 * parent not in dnlc cache,
9229 				 * do lookupp to get its id
9230 				 */
9231 				num_ops = 5;
9232 				pnodeid = 0; /* set later by getattr parent */
9233 			}
9234 			if (dvp)
9235 				VN_RELE(dvp);
9236 		}
9237 	}
9238 	recov_state.rs_flags = 0;
9239 	recov_state.rs_num_retry_despite_err = 0;
9240 
9241 	/* Save the original mount point security flavor */
9242 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9243 
9244 recov_retry:
9245 	args.ctag = TAG_READDIR;
9246 
9247 	args.array = argop;
9248 	args.array_len = num_ops;
9249 
9250 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9251 	    &recov_state, NULL)) {
9252 		/*
9253 		 * If readdir a node that is a stub for a crossed mount point,
9254 		 * keep the original secinfo flavor for the current file
9255 		 * system, not the crossed one.
9256 		 */
9257 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9258 		rdc->error = e.error;
9259 		return;
9260 	}
9261 
9262 	/*
9263 	 * Determine which attrs to request for dirents.  This code
9264 	 * must be protected by nfs4_start/end_fop because of r_server
9265 	 * (which will change during failover recovery).
9266 	 *
9267 	 */
9268 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9269 		/*
9270 		 * Get all vattr attrs plus filehandle and rdattr_error
9271 		 */
9272 		rd_bitsval = NFS4_VATTR_MASK |
9273 		    FATTR4_RDATTR_ERROR_MASK |
9274 		    FATTR4_FILEHANDLE_MASK;
9275 
9276 		if (rp->r_flags & R4READDIRWATTR) {
9277 			mutex_enter(&rp->r_statelock);
9278 			rp->r_flags &= ~R4READDIRWATTR;
9279 			mutex_exit(&rp->r_statelock);
9280 		}
9281 	} else {
9282 		servinfo4_t *svp = rp->r_server;
9283 
9284 		/*
9285 		 * Already read directory. Use readdir with
9286 		 * no attrs (except for mounted_on_fileid) for updates.
9287 		 */
9288 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9289 
9290 		/*
9291 		 * request mounted on fileid if supported, else request
9292 		 * fileid.  maybe we should verify that fileid is supported
9293 		 * and request something else if not.
9294 		 */
9295 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9296 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9297 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9298 		nfs_rw_exit(&svp->sv_lock);
9299 	}
9300 
9301 	/* putfh directory fh */
9302 	argop[0].argop = OP_CPUTFH;
9303 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9304 
9305 	argop[1].argop = OP_READDIR;
9306 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9307 	/*
9308 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9309 	 * cookie 0 should be used over-the-wire to start reading at
9310 	 * the beginning of the directory excluding "." and "..".
9311 	 */
9312 	if (rdc->nfs4_cookie == 0 ||
9313 	    rdc->nfs4_cookie == 1 ||
9314 	    rdc->nfs4_cookie == 2) {
9315 		rargs->cookie = (nfs_cookie4)0;
9316 		rargs->cookieverf = 0;
9317 	} else {
9318 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9319 		mutex_enter(&rp->r_statelock);
9320 		rargs->cookieverf = rp->r_cookieverf4;
9321 		mutex_exit(&rp->r_statelock);
9322 	}
9323 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9324 	rargs->maxcount = mi->mi_tsize;
9325 	rargs->attr_request = rd_bitsval;
9326 	rargs->rdc = rdc;
9327 	rargs->dvp = vp;
9328 	rargs->mi = mi;
9329 	rargs->cr = cr;
9330 
9331 
9332 	/*
9333 	 * If count < than the minimum required, we return no entries
9334 	 * and fail with EINVAL
9335 	 */
9336 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9337 		rdc->error = EINVAL;
9338 		goto out;
9339 	}
9340 
9341 	if (args.array_len == 5) {
9342 		/*
9343 		 * Add lookupp and getattr for parent nodeid.
9344 		 */
9345 		argop[2].argop = OP_LOOKUPP;
9346 
9347 		argop[3].argop = OP_GETFH;
9348 
9349 		/* getattr parent */
9350 		argop[4].argop = OP_GETATTR;
9351 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9352 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9353 	}
9354 
9355 	doqueue = 1;
9356 
9357 	if (mi->mi_io_kstats) {
9358 		mutex_enter(&mi->mi_lock);
9359 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9360 		mutex_exit(&mi->mi_lock);
9361 	}
9362 
9363 	/* capture the time of this call */
9364 	rargs->t = t = gethrtime();
9365 
9366 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9367 
9368 	if (mi->mi_io_kstats) {
9369 		mutex_enter(&mi->mi_lock);
9370 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9371 		mutex_exit(&mi->mi_lock);
9372 	}
9373 
9374 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9375 
9376 	/*
9377 	 * If RPC error occurred and it isn't an error that
9378 	 * triggers recovery, then go ahead and fail now.
9379 	 */
9380 	if (e.error != 0 && !needrecov) {
9381 		rdc->error = e.error;
9382 		goto out;
9383 	}
9384 
9385 	if (needrecov) {
9386 		bool_t abort;
9387 
9388 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9389 		    "nfs4readdir: initiating recovery.\n"));
9390 
9391 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9392 		    NULL, OP_READDIR, NULL, NULL, NULL);
9393 		if (abort == FALSE) {
9394 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9395 			    &recov_state, needrecov);
9396 			if (!e.error)
9397 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9398 				    (caddr_t)&res);
9399 			if (rdc->entries != NULL) {
9400 				kmem_free(rdc->entries, rdc->entlen);
9401 				rdc->entries = NULL;
9402 			}
9403 			goto recov_retry;
9404 		}
9405 
9406 		if (e.error != 0) {
9407 			rdc->error = e.error;
9408 			goto out;
9409 		}
9410 
9411 		/* fall through for res.status case */
9412 	}
9413 
9414 	res_opcnt = res.array_len;
9415 
9416 	/*
9417 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9418 	 * failure here.  Subsequent ops are for filling out dot-dot
9419 	 * dirent, and if they fail, we still want to give the caller
9420 	 * the dirents returned by (the successful) READDIR op, so we need
9421 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9422 	 *
9423 	 * One example where PUTFH+READDIR ops would succeed but
9424 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9425 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9426 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9427 	 * x perm.  We need to come up with a non-vendor-specific way
9428 	 * for a POSIX server to return d_ino from dotdot's dirent if
9429 	 * client only requests mounted_on_fileid, and just say the
9430 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9431 	 * client requested any mandatory attrs, server would be required
9432 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9433 	 * for dotdot.
9434 	 */
9435 
9436 	if (res.status) {
9437 		if (res_opcnt <= 2) {
9438 			e.error = geterrno4(res.status);
9439 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9440 			    &recov_state, needrecov);
9441 			nfs4_purge_stale_fh(e.error, vp, cr);
9442 			rdc->error = e.error;
9443 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9444 			if (rdc->entries != NULL) {
9445 				kmem_free(rdc->entries, rdc->entlen);
9446 				rdc->entries = NULL;
9447 			}
9448 			/*
9449 			 * If readdir a node that is a stub for a
9450 			 * crossed mount point, keep the original
9451 			 * secinfo flavor for the current file system,
9452 			 * not the crossed one.
9453 			 */
9454 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9455 			return;
9456 		}
9457 	}
9458 
9459 	resop = &res.array[1];	/* readdir res */
9460 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9461 
9462 	mutex_enter(&rp->r_statelock);
9463 	rp->r_cookieverf4 = rd_res->cookieverf;
9464 	mutex_exit(&rp->r_statelock);
9465 
9466 	/*
9467 	 * For "." and ".." entries
9468 	 * e.g.
9469 	 *	seek(cookie=0) -> "." entry with d_off = 1
9470 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9471 	 */
9472 	if (cookie == (nfs_cookie4) 0) {
9473 		if (rd_res->dotp)
9474 			rd_res->dotp->d_ino = nodeid;
9475 		if (rd_res->dotdotp)
9476 			rd_res->dotdotp->d_ino = pnodeid;
9477 	}
9478 	if (cookie == (nfs_cookie4) 1) {
9479 		if (rd_res->dotdotp)
9480 			rd_res->dotdotp->d_ino = pnodeid;
9481 	}
9482 
9483 
9484 	/* LOOKUPP+GETATTR attemped */
9485 	if (args.array_len == 5 && rd_res->dotdotp) {
9486 		if (res.status == NFS4_OK && res_opcnt == 5) {
9487 			nfs_fh4 *fhp;
9488 			nfs4_sharedfh_t *sfhp;
9489 			vnode_t *pvp;
9490 			nfs4_ga_res_t *garp;
9491 
9492 			resop++;	/* lookupp */
9493 			resop++;	/* getfh   */
9494 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9495 
9496 			resop++;	/* getattr of parent */
9497 
9498 			/*
9499 			 * First, take care of finishing the
9500 			 * readdir results.
9501 			 */
9502 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9503 			/*
9504 			 * The d_ino of .. must be the inode number
9505 			 * of the mounted filesystem.
9506 			 */
9507 			if (garp->n4g_va.va_mask & AT_NODEID)
9508 				rd_res->dotdotp->d_ino =
9509 				    garp->n4g_va.va_nodeid;
9510 
9511 
9512 			/*
9513 			 * Next, create the ".." dnlc entry
9514 			 */
9515 			sfhp = sfh4_get(fhp, mi);
9516 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9517 				dnlc_update(vp, "..", pvp);
9518 				VN_RELE(pvp);
9519 			}
9520 			sfh4_rele(&sfhp);
9521 		}
9522 	}
9523 
9524 	if (mi->mi_io_kstats) {
9525 		mutex_enter(&mi->mi_lock);
9526 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9527 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9528 		mutex_exit(&mi->mi_lock);
9529 	}
9530 
9531 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9532 
9533 out:
9534 	/*
9535 	 * If readdir a node that is a stub for a crossed mount point,
9536 	 * keep the original secinfo flavor for the current file system,
9537 	 * not the crossed one.
9538 	 */
9539 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9540 
9541 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9542 }
9543 
9544 
9545 static int
9546 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9547 {
9548 	rnode4_t *rp = VTOR4(bp->b_vp);
9549 	int count;
9550 	int error;
9551 	cred_t *cred_otw = NULL;
9552 	offset_t offset;
9553 	nfs4_open_stream_t *osp = NULL;
9554 	bool_t first_time = TRUE;	/* first time getting otw cred */
9555 	bool_t last_time = FALSE;	/* last time getting otw cred */
9556 
9557 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9558 
9559 	DTRACE_IO1(start, struct buf *, bp);
9560 	offset = ldbtob(bp->b_lblkno);
9561 
9562 	if (bp->b_flags & B_READ) {
9563 	read_again:
9564 		/*
9565 		 * Releases the osp, if it is provided.
9566 		 * Puts a hold on the cred_otw and the new osp (if found).
9567 		 */
9568 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9569 		    &first_time, &last_time);
9570 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9571 		    offset, bp->b_bcount, &bp->b_resid, cred_otw,
9572 		    readahead, NULL);
9573 		crfree(cred_otw);
9574 		if (!error) {
9575 			if (bp->b_resid) {
9576 				/*
9577 				 * Didn't get it all because we hit EOF,
9578 				 * zero all the memory beyond the EOF.
9579 				 */
9580 				/* bzero(rdaddr + */
9581 				bzero(bp->b_un.b_addr +
9582 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9583 			}
9584 			mutex_enter(&rp->r_statelock);
9585 			if (bp->b_resid == bp->b_bcount &&
9586 			    offset >= rp->r_size) {
9587 				/*
9588 				 * We didn't read anything at all as we are
9589 				 * past EOF.  Return an error indicator back
9590 				 * but don't destroy the pages (yet).
9591 				 */
9592 				error = NFS_EOF;
9593 			}
9594 			mutex_exit(&rp->r_statelock);
9595 		} else if (error == EACCES && last_time == FALSE) {
9596 				goto read_again;
9597 		}
9598 	} else {
9599 		if (!(rp->r_flags & R4STALE)) {
9600 write_again:
9601 			/*
9602 			 * Releases the osp, if it is provided.
9603 			 * Puts a hold on the cred_otw and the new
9604 			 * osp (if found).
9605 			 */
9606 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9607 			    &first_time, &last_time);
9608 			mutex_enter(&rp->r_statelock);
9609 			count = MIN(bp->b_bcount, rp->r_size - offset);
9610 			mutex_exit(&rp->r_statelock);
9611 			if (count < 0)
9612 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9613 #ifdef DEBUG
9614 			if (count == 0) {
9615 				zoneid_t zoneid = getzoneid();
9616 
9617 				zcmn_err(zoneid, CE_WARN,
9618 				    "nfs4_bio: zero length write at %lld",
9619 				    offset);
9620 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9621 				    "b_bcount=%ld, file size=%lld",
9622 				    rp->r_flags, (long)bp->b_bcount,
9623 				    rp->r_size);
9624 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9625 				if (nfs4_bio_do_stop)
9626 					debug_enter("nfs4_bio");
9627 			}
9628 #endif
9629 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9630 			    count, cred_otw, stab_comm);
9631 			if (error == EACCES && last_time == FALSE) {
9632 				crfree(cred_otw);
9633 				goto write_again;
9634 			}
9635 			bp->b_error = error;
9636 			if (error && error != EINTR &&
9637 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9638 				/*
9639 				 * Don't print EDQUOT errors on the console.
9640 				 * Don't print asynchronous EACCES errors.
9641 				 * Don't print EFBIG errors.
9642 				 * Print all other write errors.
9643 				 */
9644 				if (error != EDQUOT && error != EFBIG &&
9645 				    (error != EACCES ||
9646 				    !(bp->b_flags & B_ASYNC)))
9647 					nfs4_write_error(bp->b_vp,
9648 					    error, cred_otw);
9649 				/*
9650 				 * Update r_error and r_flags as appropriate.
9651 				 * If the error was ESTALE, then mark the
9652 				 * rnode as not being writeable and save
9653 				 * the error status.  Otherwise, save any
9654 				 * errors which occur from asynchronous
9655 				 * page invalidations.  Any errors occurring
9656 				 * from other operations should be saved
9657 				 * by the caller.
9658 				 */
9659 				mutex_enter(&rp->r_statelock);
9660 				if (error == ESTALE) {
9661 					rp->r_flags |= R4STALE;
9662 					if (!rp->r_error)
9663 						rp->r_error = error;
9664 				} else if (!rp->r_error &&
9665 				    (bp->b_flags &
9666 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9667 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9668 					rp->r_error = error;
9669 				}
9670 				mutex_exit(&rp->r_statelock);
9671 			}
9672 			crfree(cred_otw);
9673 		} else {
9674 			error = rp->r_error;
9675 			/*
9676 			 * A close may have cleared r_error, if so,
9677 			 * propagate ESTALE error return properly
9678 			 */
9679 			if (error == 0)
9680 				error = ESTALE;
9681 		}
9682 	}
9683 
9684 	if (error != 0 && error != NFS_EOF)
9685 		bp->b_flags |= B_ERROR;
9686 
9687 	if (osp)
9688 		open_stream_rele(osp, rp);
9689 
9690 	DTRACE_IO1(done, struct buf *, bp);
9691 
9692 	return (error);
9693 }
9694 
9695 /* ARGSUSED */
9696 int
9697 nfs4_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
9698 {
9699 	return (EREMOTE);
9700 }
9701 
9702 /* ARGSUSED2 */
9703 int
9704 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9705 {
9706 	rnode4_t *rp = VTOR4(vp);
9707 
9708 	if (!write_lock) {
9709 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9710 		return (V_WRITELOCK_FALSE);
9711 	}
9712 
9713 	if ((rp->r_flags & R4DIRECTIO) ||
9714 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9715 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9716 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9717 			return (V_WRITELOCK_FALSE);
9718 		nfs_rw_exit(&rp->r_rwlock);
9719 	}
9720 
9721 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9722 	return (V_WRITELOCK_TRUE);
9723 }
9724 
9725 /* ARGSUSED */
9726 void
9727 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9728 {
9729 	rnode4_t *rp = VTOR4(vp);
9730 
9731 	nfs_rw_exit(&rp->r_rwlock);
9732 }
9733 
9734 /* ARGSUSED */
9735 static int
9736 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp, caller_context_t *ct)
9737 {
9738 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9739 		return (EIO);
9740 
9741 	/*
9742 	 * Because we stuff the readdir cookie into the offset field
9743 	 * someone may attempt to do an lseek with the cookie which
9744 	 * we want to succeed.
9745 	 */
9746 	if (vp->v_type == VDIR)
9747 		return (0);
9748 	if (*noffp < 0)
9749 		return (EINVAL);
9750 	return (0);
9751 }
9752 
9753 
9754 /*
9755  * Return all the pages from [off..off+len) in file
9756  */
9757 /* ARGSUSED */
9758 static int
9759 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9760     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9761     enum seg_rw rw, cred_t *cr, caller_context_t *ct)
9762 {
9763 	rnode4_t *rp;
9764 	int error;
9765 	mntinfo4_t *mi;
9766 
9767 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9768 		return (EIO);
9769 	rp = VTOR4(vp);
9770 	if (IS_SHADOW(vp, rp))
9771 		vp = RTOV4(rp);
9772 
9773 	if (vp->v_flag & VNOMAP)
9774 		return (ENOSYS);
9775 
9776 	if (protp != NULL)
9777 		*protp = PROT_ALL;
9778 
9779 	/*
9780 	 * Now validate that the caches are up to date.
9781 	 */
9782 	if (error = nfs4_validate_caches(vp, cr))
9783 		return (error);
9784 
9785 	mi = VTOMI4(vp);
9786 retry:
9787 	mutex_enter(&rp->r_statelock);
9788 
9789 	/*
9790 	 * Don't create dirty pages faster than they
9791 	 * can be cleaned so that the system doesn't
9792 	 * get imbalanced.  If the async queue is
9793 	 * maxed out, then wait for it to drain before
9794 	 * creating more dirty pages.  Also, wait for
9795 	 * any threads doing pagewalks in the vop_getattr
9796 	 * entry points so that they don't block for
9797 	 * long periods.
9798 	 */
9799 	if (rw == S_CREATE) {
9800 		while ((mi->mi_max_threads != 0 &&
9801 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
9802 		    rp->r_gcount > 0)
9803 			cv_wait(&rp->r_cv, &rp->r_statelock);
9804 	}
9805 
9806 	/*
9807 	 * If we are getting called as a side effect of an nfs_write()
9808 	 * operation the local file size might not be extended yet.
9809 	 * In this case we want to be able to return pages of zeroes.
9810 	 */
9811 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9812 		NFS4_DEBUG(nfs4_pageio_debug,
9813 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9814 		    "len=%llu, size=%llu, attrsize =%llu", off,
9815 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9816 		mutex_exit(&rp->r_statelock);
9817 		return (EFAULT);		/* beyond EOF */
9818 	}
9819 
9820 	mutex_exit(&rp->r_statelock);
9821 
9822 	error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9823 	    pl, plsz, seg, addr, rw, cr);
9824 	NFS4_DEBUG(nfs4_pageio_debug && error,
9825 	    (CE_NOTE, "getpages error %d; off=%lld, len=%lld",
9826 	    error, off, (u_longlong_t)len));
9827 
9828 	switch (error) {
9829 	case NFS_EOF:
9830 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9831 		goto retry;
9832 	case ESTALE:
9833 		nfs4_purge_stale_fh(error, vp, cr);
9834 	}
9835 
9836 	return (error);
9837 }
9838 
9839 /*
9840  * Called from pvn_getpages to get a particular page.
9841  */
9842 /* ARGSUSED */
9843 static int
9844 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9845     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9846     enum seg_rw rw, cred_t *cr)
9847 {
9848 	rnode4_t *rp;
9849 	uint_t bsize;
9850 	struct buf *bp;
9851 	page_t *pp;
9852 	u_offset_t lbn;
9853 	u_offset_t io_off;
9854 	u_offset_t blkoff;
9855 	u_offset_t rablkoff;
9856 	size_t io_len;
9857 	uint_t blksize;
9858 	int error;
9859 	int readahead;
9860 	int readahead_issued = 0;
9861 	int ra_window; /* readahead window */
9862 	page_t *pagefound;
9863 	page_t *savepp;
9864 
9865 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9866 		return (EIO);
9867 
9868 	rp = VTOR4(vp);
9869 	ASSERT(!IS_SHADOW(vp, rp));
9870 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9871 
9872 reread:
9873 	bp = NULL;
9874 	pp = NULL;
9875 	pagefound = NULL;
9876 
9877 	if (pl != NULL)
9878 		pl[0] = NULL;
9879 
9880 	error = 0;
9881 	lbn = off / bsize;
9882 	blkoff = lbn * bsize;
9883 
9884 	/*
9885 	 * Queueing up the readahead before doing the synchronous read
9886 	 * results in a significant increase in read throughput because
9887 	 * of the increased parallelism between the async threads and
9888 	 * the process context.
9889 	 */
9890 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9891 	    rw != S_CREATE &&
9892 	    !(vp->v_flag & VNOCACHE)) {
9893 		mutex_enter(&rp->r_statelock);
9894 
9895 		/*
9896 		 * Calculate the number of readaheads to do.
9897 		 * a) No readaheads at offset = 0.
9898 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9899 		 *    window is closed.
9900 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9901 		 *    upon how far the readahead window is open or close.
9902 		 * d) No readaheads if rp->r_nextr is not within the scope
9903 		 *    of the readahead window (random i/o).
9904 		 */
9905 
9906 		if (off == 0)
9907 			readahead = 0;
9908 		else if (blkoff == rp->r_nextr)
9909 			readahead = nfs4_nra;
9910 		else if (rp->r_nextr > blkoff &&
9911 		    ((ra_window = (rp->r_nextr - blkoff) / bsize)
9912 		    <= (nfs4_nra - 1)))
9913 			readahead = nfs4_nra - ra_window;
9914 		else
9915 			readahead = 0;
9916 
9917 		rablkoff = rp->r_nextr;
9918 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9919 			mutex_exit(&rp->r_statelock);
9920 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9921 			    addr + (rablkoff + bsize - off),
9922 			    seg, cr, nfs4_readahead) < 0) {
9923 				mutex_enter(&rp->r_statelock);
9924 				break;
9925 			}
9926 			readahead--;
9927 			rablkoff += bsize;
9928 			/*
9929 			 * Indicate that we did a readahead so
9930 			 * readahead offset is not updated
9931 			 * by the synchronous read below.
9932 			 */
9933 			readahead_issued = 1;
9934 			mutex_enter(&rp->r_statelock);
9935 			/*
9936 			 * set readahead offset to
9937 			 * offset of last async readahead
9938 			 * request.
9939 			 */
9940 			rp->r_nextr = rablkoff;
9941 		}
9942 		mutex_exit(&rp->r_statelock);
9943 	}
9944 
9945 again:
9946 	if ((pagefound = page_exists(vp, off)) == NULL) {
9947 		if (pl == NULL) {
9948 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9949 			    nfs4_readahead);
9950 		} else if (rw == S_CREATE) {
9951 			/*
9952 			 * Block for this page is not allocated, or the offset
9953 			 * is beyond the current allocation size, or we're
9954 			 * allocating a swap slot and the page was not found,
9955 			 * so allocate it and return a zero page.
9956 			 */
9957 			if ((pp = page_create_va(vp, off,
9958 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9959 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9960 			io_len = PAGESIZE;
9961 			mutex_enter(&rp->r_statelock);
9962 			rp->r_nextr = off + PAGESIZE;
9963 			mutex_exit(&rp->r_statelock);
9964 		} else {
9965 			/*
9966 			 * Need to go to server to get a block
9967 			 */
9968 			mutex_enter(&rp->r_statelock);
9969 			if (blkoff < rp->r_size &&
9970 			    blkoff + bsize > rp->r_size) {
9971 				/*
9972 				 * If less than a block left in
9973 				 * file read less than a block.
9974 				 */
9975 				if (rp->r_size <= off) {
9976 					/*
9977 					 * Trying to access beyond EOF,
9978 					 * set up to get at least one page.
9979 					 */
9980 					blksize = off + PAGESIZE - blkoff;
9981 				} else
9982 					blksize = rp->r_size - blkoff;
9983 			} else if ((off == 0) ||
9984 			    (off != rp->r_nextr && !readahead_issued)) {
9985 				blksize = PAGESIZE;
9986 				blkoff = off; /* block = page here */
9987 			} else
9988 				blksize = bsize;
9989 			mutex_exit(&rp->r_statelock);
9990 
9991 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9992 			    &io_len, blkoff, blksize, 0);
9993 
9994 			/*
9995 			 * Some other thread has entered the page,
9996 			 * so just use it.
9997 			 */
9998 			if (pp == NULL)
9999 				goto again;
10000 
10001 			/*
10002 			 * Now round the request size up to page boundaries.
10003 			 * This ensures that the entire page will be
10004 			 * initialized to zeroes if EOF is encountered.
10005 			 */
10006 			io_len = ptob(btopr(io_len));
10007 
10008 			bp = pageio_setup(pp, io_len, vp, B_READ);
10009 			ASSERT(bp != NULL);
10010 
10011 			/*
10012 			 * pageio_setup should have set b_addr to 0.  This
10013 			 * is correct since we want to do I/O on a page
10014 			 * boundary.  bp_mapin will use this addr to calculate
10015 			 * an offset, and then set b_addr to the kernel virtual
10016 			 * address it allocated for us.
10017 			 */
10018 			ASSERT(bp->b_un.b_addr == 0);
10019 
10020 			bp->b_edev = 0;
10021 			bp->b_dev = 0;
10022 			bp->b_lblkno = lbtodb(io_off);
10023 			bp->b_file = vp;
10024 			bp->b_offset = (offset_t)off;
10025 			bp_mapin(bp);
10026 
10027 			/*
10028 			 * If doing a write beyond what we believe is EOF,
10029 			 * don't bother trying to read the pages from the
10030 			 * server, we'll just zero the pages here.  We
10031 			 * don't check that the rw flag is S_WRITE here
10032 			 * because some implementations may attempt a
10033 			 * read access to the buffer before copying data.
10034 			 */
10035 			mutex_enter(&rp->r_statelock);
10036 			if (io_off >= rp->r_size && seg == segkmap) {
10037 				mutex_exit(&rp->r_statelock);
10038 				bzero(bp->b_un.b_addr, io_len);
10039 			} else {
10040 				mutex_exit(&rp->r_statelock);
10041 				error = nfs4_bio(bp, NULL, cr, FALSE);
10042 			}
10043 
10044 			/*
10045 			 * Unmap the buffer before freeing it.
10046 			 */
10047 			bp_mapout(bp);
10048 			pageio_done(bp);
10049 
10050 			savepp = pp;
10051 			do {
10052 				pp->p_fsdata = C_NOCOMMIT;
10053 			} while ((pp = pp->p_next) != savepp);
10054 
10055 			if (error == NFS_EOF) {
10056 				/*
10057 				 * If doing a write system call just return
10058 				 * zeroed pages, else user tried to get pages
10059 				 * beyond EOF, return error.  We don't check
10060 				 * that the rw flag is S_WRITE here because
10061 				 * some implementations may attempt a read
10062 				 * access to the buffer before copying data.
10063 				 */
10064 				if (seg == segkmap)
10065 					error = 0;
10066 				else
10067 					error = EFAULT;
10068 			}
10069 
10070 			if (!readahead_issued && !error) {
10071 				mutex_enter(&rp->r_statelock);
10072 				rp->r_nextr = io_off + io_len;
10073 				mutex_exit(&rp->r_statelock);
10074 			}
10075 		}
10076 	}
10077 
10078 out:
10079 	if (pl == NULL)
10080 		return (error);
10081 
10082 	if (error) {
10083 		if (pp != NULL)
10084 			pvn_read_done(pp, B_ERROR);
10085 		return (error);
10086 	}
10087 
10088 	if (pagefound) {
10089 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
10090 
10091 		/*
10092 		 * Page exists in the cache, acquire the appropriate lock.
10093 		 * If this fails, start all over again.
10094 		 */
10095 		if ((pp = page_lookup(vp, off, se)) == NULL) {
10096 #ifdef DEBUG
10097 			nfs4_lostpage++;
10098 #endif
10099 			goto reread;
10100 		}
10101 		pl[0] = pp;
10102 		pl[1] = NULL;
10103 		return (0);
10104 	}
10105 
10106 	if (pp != NULL)
10107 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
10108 
10109 	return (error);
10110 }
10111 
10112 static void
10113 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
10114     cred_t *cr)
10115 {
10116 	int error;
10117 	page_t *pp;
10118 	u_offset_t io_off;
10119 	size_t io_len;
10120 	struct buf *bp;
10121 	uint_t bsize, blksize;
10122 	rnode4_t *rp = VTOR4(vp);
10123 	page_t *savepp;
10124 
10125 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10126 
10127 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10128 
10129 	mutex_enter(&rp->r_statelock);
10130 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
10131 		/*
10132 		 * If less than a block left in file read less
10133 		 * than a block.
10134 		 */
10135 		blksize = rp->r_size - blkoff;
10136 	} else
10137 		blksize = bsize;
10138 	mutex_exit(&rp->r_statelock);
10139 
10140 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
10141 	    &io_off, &io_len, blkoff, blksize, 1);
10142 	/*
10143 	 * The isra flag passed to the kluster function is 1, we may have
10144 	 * gotten a return value of NULL for a variety of reasons (# of free
10145 	 * pages < minfree, someone entered the page on the vnode etc). In all
10146 	 * cases, we want to punt on the readahead.
10147 	 */
10148 	if (pp == NULL)
10149 		return;
10150 
10151 	/*
10152 	 * Now round the request size up to page boundaries.
10153 	 * This ensures that the entire page will be
10154 	 * initialized to zeroes if EOF is encountered.
10155 	 */
10156 	io_len = ptob(btopr(io_len));
10157 
10158 	bp = pageio_setup(pp, io_len, vp, B_READ);
10159 	ASSERT(bp != NULL);
10160 
10161 	/*
10162 	 * pageio_setup should have set b_addr to 0.  This is correct since
10163 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10164 	 * to calculate an offset, and then set b_addr to the kernel virtual
10165 	 * address it allocated for us.
10166 	 */
10167 	ASSERT(bp->b_un.b_addr == 0);
10168 
10169 	bp->b_edev = 0;
10170 	bp->b_dev = 0;
10171 	bp->b_lblkno = lbtodb(io_off);
10172 	bp->b_file = vp;
10173 	bp->b_offset = (offset_t)blkoff;
10174 	bp_mapin(bp);
10175 
10176 	/*
10177 	 * If doing a write beyond what we believe is EOF, don't bother trying
10178 	 * to read the pages from the server, we'll just zero the pages here.
10179 	 * We don't check that the rw flag is S_WRITE here because some
10180 	 * implementations may attempt a read access to the buffer before
10181 	 * copying data.
10182 	 */
10183 	mutex_enter(&rp->r_statelock);
10184 	if (io_off >= rp->r_size && seg == segkmap) {
10185 		mutex_exit(&rp->r_statelock);
10186 		bzero(bp->b_un.b_addr, io_len);
10187 		error = 0;
10188 	} else {
10189 		mutex_exit(&rp->r_statelock);
10190 		error = nfs4_bio(bp, NULL, cr, TRUE);
10191 		if (error == NFS_EOF)
10192 			error = 0;
10193 	}
10194 
10195 	/*
10196 	 * Unmap the buffer before freeing it.
10197 	 */
10198 	bp_mapout(bp);
10199 	pageio_done(bp);
10200 
10201 	savepp = pp;
10202 	do {
10203 		pp->p_fsdata = C_NOCOMMIT;
10204 	} while ((pp = pp->p_next) != savepp);
10205 
10206 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10207 
10208 	/*
10209 	 * In case of error set readahead offset
10210 	 * to the lowest offset.
10211 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10212 	 */
10213 	if (error && rp->r_nextr > io_off) {
10214 		mutex_enter(&rp->r_statelock);
10215 		if (rp->r_nextr > io_off)
10216 			rp->r_nextr = io_off;
10217 		mutex_exit(&rp->r_statelock);
10218 	}
10219 }
10220 
10221 /*
10222  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10223  * If len == 0, do from off to EOF.
10224  *
10225  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10226  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10227  * (from pageout).
10228  */
10229 /* ARGSUSED */
10230 static int
10231 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
10232     caller_context_t *ct)
10233 {
10234 	int error;
10235 	rnode4_t *rp;
10236 
10237 	ASSERT(cr != NULL);
10238 
10239 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10240 		return (EIO);
10241 
10242 	rp = VTOR4(vp);
10243 	if (IS_SHADOW(vp, rp))
10244 		vp = RTOV4(rp);
10245 
10246 	/*
10247 	 * XXX - Why should this check be made here?
10248 	 */
10249 	if (vp->v_flag & VNOMAP)
10250 		return (ENOSYS);
10251 
10252 	if (len == 0 && !(flags & B_INVAL) &&
10253 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10254 		return (0);
10255 
10256 	mutex_enter(&rp->r_statelock);
10257 	rp->r_count++;
10258 	mutex_exit(&rp->r_statelock);
10259 	error = nfs4_putpages(vp, off, len, flags, cr);
10260 	mutex_enter(&rp->r_statelock);
10261 	rp->r_count--;
10262 	cv_broadcast(&rp->r_cv);
10263 	mutex_exit(&rp->r_statelock);
10264 
10265 	return (error);
10266 }
10267 
10268 /*
10269  * Write out a single page, possibly klustering adjacent dirty pages.
10270  */
10271 int
10272 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10273     int flags, cred_t *cr)
10274 {
10275 	u_offset_t io_off;
10276 	u_offset_t lbn_off;
10277 	u_offset_t lbn;
10278 	size_t io_len;
10279 	uint_t bsize;
10280 	int error;
10281 	rnode4_t *rp;
10282 
10283 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10284 	ASSERT(pp != NULL);
10285 	ASSERT(cr != NULL);
10286 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10287 
10288 	rp = VTOR4(vp);
10289 	ASSERT(rp->r_count > 0);
10290 	ASSERT(!IS_SHADOW(vp, rp));
10291 
10292 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10293 	lbn = pp->p_offset / bsize;
10294 	lbn_off = lbn * bsize;
10295 
10296 	/*
10297 	 * Find a kluster that fits in one block, or in
10298 	 * one page if pages are bigger than blocks.  If
10299 	 * there is less file space allocated than a whole
10300 	 * page, we'll shorten the i/o request below.
10301 	 */
10302 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10303 	    roundup(bsize, PAGESIZE), flags);
10304 
10305 	/*
10306 	 * pvn_write_kluster shouldn't have returned a page with offset
10307 	 * behind the original page we were given.  Verify that.
10308 	 */
10309 	ASSERT((pp->p_offset / bsize) >= lbn);
10310 
10311 	/*
10312 	 * Now pp will have the list of kept dirty pages marked for
10313 	 * write back.  It will also handle invalidation and freeing
10314 	 * of pages that are not dirty.  Check for page length rounding
10315 	 * problems.
10316 	 */
10317 	if (io_off + io_len > lbn_off + bsize) {
10318 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10319 		io_len = lbn_off + bsize - io_off;
10320 	}
10321 	/*
10322 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10323 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10324 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10325 	 * progress and the r_size has not been made consistent with the
10326 	 * new size of the file. When the uiomove() completes the r_size is
10327 	 * updated and the R4MODINPROGRESS flag is cleared.
10328 	 *
10329 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10330 	 * consistent value of r_size. Without this handshaking, it is
10331 	 * possible that nfs4_bio() picks  up the old value of r_size
10332 	 * before the uiomove() in writerp4() completes. This will result
10333 	 * in the write through nfs4_bio() being dropped.
10334 	 *
10335 	 * More precisely, there is a window between the time the uiomove()
10336 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10337 	 * operation intervenes in this window, the page will be picked up,
10338 	 * because it is dirty (it will be unlocked, unless it was
10339 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10340 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10341 	 * checked. This will still be the old size. Therefore the page will
10342 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10343 	 * the page will be found to be clean and the write will be dropped.
10344 	 */
10345 	if (rp->r_flags & R4MODINPROGRESS) {
10346 		mutex_enter(&rp->r_statelock);
10347 		if ((rp->r_flags & R4MODINPROGRESS) &&
10348 		    rp->r_modaddr + MAXBSIZE > io_off &&
10349 		    rp->r_modaddr < io_off + io_len) {
10350 			page_t *plist;
10351 			/*
10352 			 * A write is in progress for this region of the file.
10353 			 * If we did not detect R4MODINPROGRESS here then this
10354 			 * path through nfs_putapage() would eventually go to
10355 			 * nfs4_bio() and may not write out all of the data
10356 			 * in the pages. We end up losing data. So we decide
10357 			 * to set the modified bit on each page in the page
10358 			 * list and mark the rnode with R4DIRTY. This write
10359 			 * will be restarted at some later time.
10360 			 */
10361 			plist = pp;
10362 			while (plist != NULL) {
10363 				pp = plist;
10364 				page_sub(&plist, pp);
10365 				hat_setmod(pp);
10366 				page_io_unlock(pp);
10367 				page_unlock(pp);
10368 			}
10369 			rp->r_flags |= R4DIRTY;
10370 			mutex_exit(&rp->r_statelock);
10371 			if (offp)
10372 				*offp = io_off;
10373 			if (lenp)
10374 				*lenp = io_len;
10375 			return (0);
10376 		}
10377 		mutex_exit(&rp->r_statelock);
10378 	}
10379 
10380 	if (flags & B_ASYNC) {
10381 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10382 		    nfs4_sync_putapage);
10383 	} else
10384 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10385 
10386 	if (offp)
10387 		*offp = io_off;
10388 	if (lenp)
10389 		*lenp = io_len;
10390 	return (error);
10391 }
10392 
10393 static int
10394 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10395     int flags, cred_t *cr)
10396 {
10397 	int error;
10398 	rnode4_t *rp;
10399 
10400 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10401 
10402 	flags |= B_WRITE;
10403 
10404 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10405 
10406 	rp = VTOR4(vp);
10407 
10408 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10409 	    error == EACCES) &&
10410 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10411 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10412 			mutex_enter(&rp->r_statelock);
10413 			rp->r_flags |= R4OUTOFSPACE;
10414 			mutex_exit(&rp->r_statelock);
10415 		}
10416 		flags |= B_ERROR;
10417 		pvn_write_done(pp, flags);
10418 		/*
10419 		 * If this was not an async thread, then try again to
10420 		 * write out the pages, but this time, also destroy
10421 		 * them whether or not the write is successful.  This
10422 		 * will prevent memory from filling up with these
10423 		 * pages and destroying them is the only alternative
10424 		 * if they can't be written out.
10425 		 *
10426 		 * Don't do this if this is an async thread because
10427 		 * when the pages are unlocked in pvn_write_done,
10428 		 * some other thread could have come along, locked
10429 		 * them, and queued for an async thread.  It would be
10430 		 * possible for all of the async threads to be tied
10431 		 * up waiting to lock the pages again and they would
10432 		 * all already be locked and waiting for an async
10433 		 * thread to handle them.  Deadlock.
10434 		 */
10435 		if (!(flags & B_ASYNC)) {
10436 			error = nfs4_putpage(vp, io_off, io_len,
10437 			    B_INVAL | B_FORCE, cr, NULL);
10438 		}
10439 	} else {
10440 		if (error)
10441 			flags |= B_ERROR;
10442 		else if (rp->r_flags & R4OUTOFSPACE) {
10443 			mutex_enter(&rp->r_statelock);
10444 			rp->r_flags &= ~R4OUTOFSPACE;
10445 			mutex_exit(&rp->r_statelock);
10446 		}
10447 		pvn_write_done(pp, flags);
10448 		if (freemem < desfree)
10449 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10450 			    NFS4_WRITE_NOWAIT);
10451 	}
10452 
10453 	return (error);
10454 }
10455 
10456 #ifdef DEBUG
10457 int nfs4_force_open_before_mmap = 0;
10458 #endif
10459 
10460 /* ARGSUSED */
10461 static int
10462 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10463     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10464     caller_context_t *ct)
10465 {
10466 	struct segvn_crargs vn_a;
10467 	int error = 0;
10468 	rnode4_t *rp = VTOR4(vp);
10469 	mntinfo4_t *mi = VTOMI4(vp);
10470 
10471 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10472 		return (EIO);
10473 
10474 	if (vp->v_flag & VNOMAP)
10475 		return (ENOSYS);
10476 
10477 	if (off < 0 || (off + len) < 0)
10478 		return (ENXIO);
10479 
10480 	if (vp->v_type != VREG)
10481 		return (ENODEV);
10482 
10483 	/*
10484 	 * If the file is delegated to the client don't do anything.
10485 	 * If the file is not delegated, then validate the data cache.
10486 	 */
10487 	mutex_enter(&rp->r_statev4_lock);
10488 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10489 		mutex_exit(&rp->r_statev4_lock);
10490 		error = nfs4_validate_caches(vp, cr);
10491 		if (error)
10492 			return (error);
10493 	} else {
10494 		mutex_exit(&rp->r_statev4_lock);
10495 	}
10496 
10497 	/*
10498 	 * Check to see if the vnode is currently marked as not cachable.
10499 	 * This means portions of the file are locked (through VOP_FRLOCK).
10500 	 * In this case the map request must be refused.  We use
10501 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10502 	 *
10503 	 * Atomically increment r_inmap after acquiring r_rwlock. The
10504 	 * idea here is to acquire r_rwlock to block read/write and
10505 	 * not to protect r_inmap. r_inmap will inform nfs4_read/write()
10506 	 * that we are in nfs4_map(). Now, r_rwlock is acquired in order
10507 	 * and we can prevent the deadlock that would have occurred
10508 	 * when nfs4_addmap() would have acquired it out of order.
10509 	 *
10510 	 * Since we are not protecting r_inmap by any lock, we do not
10511 	 * hold any lock when we decrement it. We atomically decrement
10512 	 * r_inmap after we release r_lkserlock.
10513 	 */
10514 
10515 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR4(vp)))
10516 		return (EINTR);
10517 	atomic_inc_uint(&rp->r_inmap);
10518 	nfs_rw_exit(&rp->r_rwlock);
10519 
10520 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp))) {
10521 		atomic_dec_uint(&rp->r_inmap);
10522 		return (EINTR);
10523 	}
10524 
10525 
10526 	if (vp->v_flag & VNOCACHE) {
10527 		error = EAGAIN;
10528 		goto done;
10529 	}
10530 
10531 	/*
10532 	 * Don't allow concurrent locks and mapping if mandatory locking is
10533 	 * enabled.
10534 	 */
10535 	if (flk_has_remote_locks(vp)) {
10536 		struct vattr va;
10537 		va.va_mask = AT_MODE;
10538 		error = nfs4getattr(vp, &va, cr);
10539 		if (error != 0)
10540 			goto done;
10541 		if (MANDLOCK(vp, va.va_mode)) {
10542 			error = EAGAIN;
10543 			goto done;
10544 		}
10545 	}
10546 
10547 	/*
10548 	 * It is possible that the rnode has a lost lock request that we
10549 	 * are still trying to recover, and that the request conflicts with
10550 	 * this map request.
10551 	 *
10552 	 * An alternative approach would be for nfs4_safemap() to consider
10553 	 * queued lock requests when deciding whether to set or clear
10554 	 * VNOCACHE.  This would require the frlock code path to call
10555 	 * nfs4_safemap() after enqueing a lost request.
10556 	 */
10557 	if (nfs4_map_lost_lock_conflict(vp)) {
10558 		error = EAGAIN;
10559 		goto done;
10560 	}
10561 
10562 	as_rangelock(as);
10563 	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
10564 	if (error != 0) {
10565 		as_rangeunlock(as);
10566 		goto done;
10567 	}
10568 
10569 	if (vp->v_type == VREG) {
10570 		/*
10571 		 * We need to retrieve the open stream
10572 		 */
10573 		nfs4_open_stream_t	*osp = NULL;
10574 		nfs4_open_owner_t	*oop = NULL;
10575 
10576 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10577 		if (oop != NULL) {
10578 			/* returns with 'os_sync_lock' held */
10579 			osp = find_open_stream(oop, rp);
10580 			open_owner_rele(oop);
10581 		}
10582 		if (osp == NULL) {
10583 #ifdef DEBUG
10584 			if (nfs4_force_open_before_mmap) {
10585 				error = EIO;
10586 				goto done;
10587 			}
10588 #endif
10589 			/* returns with 'os_sync_lock' held */
10590 			error = open_and_get_osp(vp, cr, &osp);
10591 			if (osp == NULL) {
10592 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10593 				    "nfs4_map: we tried to OPEN the file "
10594 				    "but again no osp, so fail with EIO"));
10595 				goto done;
10596 			}
10597 		}
10598 
10599 		if (osp->os_failed_reopen) {
10600 			mutex_exit(&osp->os_sync_lock);
10601 			open_stream_rele(osp, rp);
10602 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10603 			    "nfs4_map: os_failed_reopen set on "
10604 			    "osp %p, cr %p, rp %s", (void *)osp,
10605 			    (void *)cr, rnode4info(rp)));
10606 			error = EIO;
10607 			goto done;
10608 		}
10609 		mutex_exit(&osp->os_sync_lock);
10610 		open_stream_rele(osp, rp);
10611 	}
10612 
10613 	vn_a.vp = vp;
10614 	vn_a.offset = off;
10615 	vn_a.type = (flags & MAP_TYPE);
10616 	vn_a.prot = (uchar_t)prot;
10617 	vn_a.maxprot = (uchar_t)maxprot;
10618 	vn_a.flags = (flags & ~MAP_TYPE);
10619 	vn_a.cred = cr;
10620 	vn_a.amp = NULL;
10621 	vn_a.szc = 0;
10622 	vn_a.lgrp_mem_policy_flags = 0;
10623 
10624 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10625 	as_rangeunlock(as);
10626 
10627 done:
10628 	nfs_rw_exit(&rp->r_lkserlock);
10629 	atomic_dec_uint(&rp->r_inmap);
10630 	return (error);
10631 }
10632 
10633 /*
10634  * We're most likely dealing with a kernel module that likes to READ
10635  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10636  * officially OPEN the file to create the necessary client state
10637  * for bookkeeping of os_mmap_read/write counts.
10638  *
10639  * Since VOP_MAP only passes in a pointer to the vnode rather than
10640  * a double pointer, we can't handle the case where nfs4open_otw()
10641  * returns a different vnode than the one passed into VOP_MAP (since
10642  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10643  * we return NULL and let nfs4_map() fail.  Note: the only case where
10644  * this should happen is if the file got removed and replaced with the
10645  * same name on the server (in addition to the fact that we're trying
10646  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10647  */
10648 static int
10649 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10650 {
10651 	rnode4_t		*rp, *drp;
10652 	vnode_t			*dvp, *open_vp;
10653 	char			file_name[MAXNAMELEN];
10654 	int			just_created;
10655 	nfs4_open_stream_t	*osp;
10656 	nfs4_open_owner_t	*oop;
10657 	int			error;
10658 
10659 	*ospp = NULL;
10660 	open_vp = map_vp;
10661 
10662 	rp = VTOR4(open_vp);
10663 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10664 		return (error);
10665 	drp = VTOR4(dvp);
10666 
10667 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10668 		VN_RELE(dvp);
10669 		return (EINTR);
10670 	}
10671 
10672 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10673 		nfs_rw_exit(&drp->r_rwlock);
10674 		VN_RELE(dvp);
10675 		return (error);
10676 	}
10677 
10678 	mutex_enter(&rp->r_statev4_lock);
10679 	if (rp->created_v4) {
10680 		rp->created_v4 = 0;
10681 		mutex_exit(&rp->r_statev4_lock);
10682 
10683 		dnlc_update(dvp, file_name, open_vp);
10684 		/* This is needed so we don't bump the open ref count */
10685 		just_created = 1;
10686 	} else {
10687 		mutex_exit(&rp->r_statev4_lock);
10688 		just_created = 0;
10689 	}
10690 
10691 	VN_HOLD(map_vp);
10692 
10693 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10694 	    just_created);
10695 	if (error) {
10696 		nfs_rw_exit(&drp->r_rwlock);
10697 		VN_RELE(dvp);
10698 		VN_RELE(map_vp);
10699 		return (error);
10700 	}
10701 
10702 	nfs_rw_exit(&drp->r_rwlock);
10703 	VN_RELE(dvp);
10704 
10705 	/*
10706 	 * If nfs4open_otw() returned a different vnode then "undo"
10707 	 * the open and return failure to the caller.
10708 	 */
10709 	if (!VN_CMP(open_vp, map_vp)) {
10710 		nfs4_error_t e;
10711 
10712 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10713 		    "open returned a different vnode"));
10714 		/*
10715 		 * If there's an error, ignore it,
10716 		 * and let VOP_INACTIVE handle it.
10717 		 */
10718 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10719 		    CLOSE_NORM, 0, 0, 0);
10720 		VN_RELE(map_vp);
10721 		return (EIO);
10722 	}
10723 
10724 	VN_RELE(map_vp);
10725 
10726 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10727 	if (!oop) {
10728 		nfs4_error_t e;
10729 
10730 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10731 		    "no open owner"));
10732 		/*
10733 		 * If there's an error, ignore it,
10734 		 * and let VOP_INACTIVE handle it.
10735 		 */
10736 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10737 		    CLOSE_NORM, 0, 0, 0);
10738 		return (EIO);
10739 	}
10740 	osp = find_open_stream(oop, rp);
10741 	open_owner_rele(oop);
10742 	*ospp = osp;
10743 	return (0);
10744 }
10745 
10746 /*
10747  * Please be aware that when this function is called, the address space write
10748  * a_lock is held.  Do not put over the wire calls in this function.
10749  */
10750 /* ARGSUSED */
10751 static int
10752 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10753     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10754     caller_context_t *ct)
10755 {
10756 	rnode4_t		*rp;
10757 	int			error = 0;
10758 	mntinfo4_t		*mi;
10759 
10760 	mi = VTOMI4(vp);
10761 	rp = VTOR4(vp);
10762 
10763 	if (nfs_zone() != mi->mi_zone)
10764 		return (EIO);
10765 	if (vp->v_flag & VNOMAP)
10766 		return (ENOSYS);
10767 
10768 	/*
10769 	 * Don't need to update the open stream first, since this
10770 	 * mmap can't add any additional share access that isn't
10771 	 * already contained in the open stream (for the case where we
10772 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10773 	 * take into account os_mmap_read[write] counts).
10774 	 */
10775 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10776 
10777 	if (vp->v_type == VREG) {
10778 		/*
10779 		 * We need to retrieve the open stream and update the counts.
10780 		 * If there is no open stream here, something is wrong.
10781 		 */
10782 		nfs4_open_stream_t	*osp = NULL;
10783 		nfs4_open_owner_t	*oop = NULL;
10784 
10785 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10786 		if (oop != NULL) {
10787 			/* returns with 'os_sync_lock' held */
10788 			osp = find_open_stream(oop, rp);
10789 			open_owner_rele(oop);
10790 		}
10791 		if (osp == NULL) {
10792 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10793 			    "nfs4_addmap: we should have an osp"
10794 			    "but we don't, so fail with EIO"));
10795 			error = EIO;
10796 			goto out;
10797 		}
10798 
10799 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10800 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10801 
10802 		/*
10803 		 * Update the map count in the open stream.
10804 		 * This is necessary in the case where we
10805 		 * open/mmap/close/, then the server reboots, and we
10806 		 * attempt to reopen.  If the mmap doesn't add share
10807 		 * access then we send an invalid reopen with
10808 		 * access = NONE.
10809 		 *
10810 		 * We need to specifically check each PROT_* so a mmap
10811 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10812 		 * read and write access.  A simple comparison of prot
10813 		 * to ~PROT_WRITE to determine read access is insufficient
10814 		 * since prot can be |= with PROT_USER, etc.
10815 		 */
10816 
10817 		/*
10818 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10819 		 */
10820 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10821 			osp->os_mmap_write += btopr(len);
10822 		if (maxprot & PROT_READ)
10823 			osp->os_mmap_read += btopr(len);
10824 		if (maxprot & PROT_EXEC)
10825 			osp->os_mmap_read += btopr(len);
10826 		/*
10827 		 * Ensure that os_mmap_read gets incremented, even if
10828 		 * maxprot were to look like PROT_NONE.
10829 		 */
10830 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10831 		    !(maxprot & PROT_EXEC))
10832 			osp->os_mmap_read += btopr(len);
10833 		osp->os_mapcnt += btopr(len);
10834 		mutex_exit(&osp->os_sync_lock);
10835 		open_stream_rele(osp, rp);
10836 	}
10837 
10838 out:
10839 	/*
10840 	 * If we got an error, then undo our
10841 	 * incrementing of 'r_mapcnt'.
10842 	 */
10843 
10844 	if (error) {
10845 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10846 		ASSERT(rp->r_mapcnt >= 0);
10847 	}
10848 	return (error);
10849 }
10850 
10851 /* ARGSUSED */
10852 static int
10853 nfs4_cmp(vnode_t *vp1, vnode_t *vp2, caller_context_t *ct)
10854 {
10855 
10856 	return (VTOR4(vp1) == VTOR4(vp2));
10857 }
10858 
10859 /*
10860  * Data structure for nfs4_lkserlock_callback() function.
10861  */
10862 struct nfs4_lkserlock_callback_data {
10863 	vnode_t *vp;
10864 	int rc;
10865 };
10866 
10867 /*
10868  * Callback function for reclock().
10869  */
10870 static callb_cpr_t *
10871 nfs4_lkserlock_callback(flk_cb_when_t when, void *infop)
10872 {
10873 	struct nfs4_lkserlock_callback_data *dp =
10874 	    (struct nfs4_lkserlock_callback_data *)infop;
10875 	rnode4_t *rp = VTOR4(dp->vp);
10876 
10877 	if (when == FLK_BEFORE_SLEEP)
10878 		nfs_rw_exit(&rp->r_lkserlock);
10879 	else
10880 		dp->rc = nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER,
10881 		    INTR4(dp->vp));
10882 
10883 	return (NULL);
10884 }
10885 
10886 /* ARGSUSED */
10887 static int
10888 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10889     offset_t offset, struct flk_callback *flk_cbp, cred_t *cr,
10890     caller_context_t *ct)
10891 {
10892 	int rc = 0;
10893 	rnode4_t *rp;
10894 	int intr = INTR4(vp);
10895 	nfs4_error_t e;
10896 	int frcmd;
10897 	struct lm_sysid	*ls = NULL;
10898 
10899 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10900 		return (EIO);
10901 
10902 	/* check for valid cmd parameter and set frcmd appropriately */
10903 	switch (cmd) {
10904 	case F_GETLK:
10905 		frcmd = 0;
10906 		break;
10907 	case F_SETLK:
10908 		frcmd = SETFLCK;
10909 		break;
10910 	case F_SETLKW:
10911 		frcmd = SETFLCK | SLPFLCK;
10912 		break;
10913 	default:
10914 		return (EINVAL);
10915 	}
10916 
10917 	/*
10918 	 * If lock is relative to EOF, we need the newest length of the file.
10919 	 * Therefore invalidate the ATTR_CACHE.
10920 	 */
10921 	if (bfp->l_whence == 2)		/* SEEK_END */
10922 		PURGE_ATTRCACHE4(vp);
10923 
10924 	/*
10925 	 * If the filesystem is mounted using local locking, pass the
10926 	 * request off to the local locking code.
10927 	 */
10928 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10929 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10930 			/*
10931 			 * For complete safety, we should be holding
10932 			 * r_lkserlock.  However, we can't call
10933 			 * nfs4_safelock and then fs_frlock while
10934 			 * holding r_lkserlock, so just invoke
10935 			 * nfs4_safelock and expect that this will
10936 			 * catch enough of the cases.
10937 			 */
10938 			if (!nfs4_safelock(vp, bfp, cr))
10939 				return (EAGAIN);
10940 		}
10941 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
10942 	}
10943 
10944 	/*
10945 	 * Convert the offset.  We need to do this to make sure our view of the
10946 	 * locking range is always the same through the rest of this function.
10947 	 * This is especially needed for bfp->l_whence == SEEK_END, because the
10948 	 * length of the file could change anytime and thus the locking range
10949 	 * would be a moving target for us.
10950 	 *
10951 	 * For the bfp->l_whence == SEEK_CUR case this is just a convenient
10952 	 * conversion to make the life easier for nfs4frlock().
10953 	 */
10954 	rc = convoff(vp, bfp, 0, offset);
10955 	if (rc != 0)
10956 		return (rc);
10957 
10958 	if (bfp->l_type == F_UNLCK) {
10959 		u_offset_t start, end;
10960 
10961 		/*
10962 		 * Shortcut for trivial case.
10963 		 */
10964 		if (cmd == F_GETLK)
10965 			return (rc);
10966 
10967 		/*
10968 		 * For every lock or unlock request we need to do two steps:
10969 		 * (un)register the local lock, and (un)register the lock at
10970 		 * the NFSv4 server.  It is essential to make sure the lock
10971 		 * status registered at the server and registered locally is
10972 		 * same and never goes out of sync.  This means that if one
10973 		 * step fails, the other one needs to be either skipped, or
10974 		 * reverted.
10975 		 *
10976 		 * For lock requests the situation is easy since a lock
10977 		 * registration can be reverted without any risk of data
10978 		 * corruption.
10979 		 *
10980 		 * The unlock requests cannot be reverted because once a lock
10981 		 * is unregistered the race window is open and some other
10982 		 * process could grab a conflicting lock.  This means that once
10983 		 * the first step (the first lock unregistration) succeeded,
10984 		 * the second step cannot fail.  The second step for the unlock
10985 		 * request is the local lock unregistration by the reclock()
10986 		 * call.
10987 		 *
10988 		 * The only way how the reclock() call for an unlock request
10989 		 * could fail is the invalid unlock range so we check it here,
10990 		 * before the lock is unregistered at NFSv4 server.  This
10991 		 * duplicates the check done in the reclock() function.
10992 		 */
10993 		rc = flk_convert_lock_data(vp, bfp, &start, &end, offset);
10994 		if (rc != 0)
10995 			return (rc);
10996 		rc = flk_check_lock_data(start, end, MAXEND);
10997 		if (rc != 0)
10998 			return (rc);
10999 
11000 		intr = 0;
11001 	}
11002 
11003 	/*
11004 	 * For F_SETLK and F_SETLKW we need to set sysid.
11005 	 */
11006 	if (cmd == F_SETLK || cmd == F_SETLKW) {
11007 		rc = nfs4frlock_get_sysid(&ls, vp, bfp);
11008 		if (rc != 0)
11009 			return (rc);
11010 
11011 		/*
11012 		 * Client locks are registerred locally by oring the sysid with
11013 		 * LM_SYSID_CLIENT.  The server registers locks locally using
11014 		 * just the sysid.  We need to distinguish between the two to
11015 		 * avoid collision in a case one machine is used as both client
11016 		 * and server.
11017 		 */
11018 		bfp->l_sysid |= LM_SYSID_CLIENT;
11019 	}
11020 
11021 	bfp->l_pid = curproc->p_pid;
11022 
11023 	rp = VTOR4(vp);
11024 
11025 	/*
11026 	 * Check whether the given lock request can proceed, given the
11027 	 * current file mappings.
11028 	 */
11029 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr)) {
11030 		if (ls != NULL)
11031 			lm_rel_sysid(ls);
11032 		return (EINTR);
11033 	}
11034 	if (cmd == F_SETLK || cmd == F_SETLKW) {
11035 		if (!nfs4_safelock(vp, bfp, cr)) {
11036 			rc = EAGAIN;
11037 			goto done;
11038 		}
11039 	}
11040 
11041 	/*
11042 	 * For query we will try to find a conflicting local lock first by
11043 	 * calling reclock().
11044 	 *
11045 	 * In a case this is a lock request we need to register it locally
11046 	 * first before we consult the NFSv4 server.
11047 	 */
11048 	if (cmd == F_GETLK || bfp->l_type != F_UNLCK) {
11049 		/*
11050 		 * Save l_type.  This is needed in a case the query (F_GETLK)
11051 		 * founds no local lock and we need to consult the server to
11052 		 * find possible conflicting lock.
11053 		 */
11054 		short saved_l_type = bfp->l_type;
11055 
11056 		/*
11057 		 * If we might sleep in reclock() we need to register a
11058 		 * callback to release the r_lkserlock during the sleep.
11059 		 */
11060 		if ((frcmd & SLPFLCK) == 0) {
11061 			rc = reclock(vp, bfp, frcmd, flag, 0, flk_cbp);
11062 		} else {
11063 			flk_callback_t callback;
11064 			struct nfs4_lkserlock_callback_data callback_data =
11065 			    {vp, 0};
11066 
11067 			flk_add_callback(&callback, nfs4_lkserlock_callback,
11068 			    &callback_data, flk_cbp);
11069 			rc = reclock(vp, bfp, frcmd, flag, 0, &callback);
11070 			flk_del_callback(&callback);
11071 
11072 			if (callback_data.rc != 0) {
11073 				/*
11074 				 * The nfs_rw_enter_sig() call in
11075 				 * nfs4_lkserlock_callback() failed.
11076 				 */
11077 
11078 				if (rc == 0) {
11079 					/*
11080 					 * The reclock() call above succeeded
11081 					 * so we need to revert it.
11082 					 */
11083 					bfp->l_type = F_UNLCK;
11084 					rc = reclock(vp, bfp, frcmd, flag, 0,
11085 					    flk_cbp);
11086 					/* The unlock cannot fail */
11087 					ASSERT(rc == 0);
11088 
11089 					/*
11090 					 * We are here because we failed to
11091 					 * acquire r_lkserlock in
11092 					 * nfs4_lkserlock_callback() due to a
11093 					 * signal.  Return the appropriate
11094 					 * error.
11095 					 */
11096 					rc = EINTR;
11097 				}
11098 
11099 				ASSERT(ls != NULL);
11100 				lm_rel_sysid(ls);
11101 
11102 				return (rc);
11103 			}
11104 
11105 			/*
11106 			 * We possibly released r_lkserlock in reclock() so
11107 			 * make sure it is still safe to lock the file.
11108 			 */
11109 			if (!nfs4_safelock(vp, bfp, cr)) {
11110 				rc = EAGAIN;
11111 				goto revert;
11112 			}
11113 
11114 		}
11115 
11116 		/*
11117 		 * If the reclock() call failed we are done and we will return
11118 		 * an error to the caller.  Similarly, if we found a
11119 		 * conflicting lock registered locally we are done too.  We do
11120 		 * not need to consult the server.
11121 		 */
11122 		if ((rc != 0) || (cmd == F_GETLK && bfp->l_type != F_UNLCK))
11123 			goto done;
11124 
11125 		/*
11126 		 * If this is a query (F_GETLK) and we didn't found any
11127 		 * conflicting local lock (otherwise we would just jump out
11128 		 * above) the original l_type got replaced by F_UNLCK.  Restore
11129 		 * its value so we will ask the server with original l_type.
11130 		 */
11131 		if (cmd == F_GETLK)
11132 			bfp->l_type = saved_l_type;
11133 	}
11134 
11135 	/*
11136 	 * Flush the cache after waiting for async I/O to finish.  For new
11137 	 * locks, this is so that the process gets the latest bits from the
11138 	 * server.  For unlocks, this is so that other clients see the
11139 	 * latest bits once the file has been unlocked.  If currently dirty
11140 	 * pages can't be flushed, then don't allow a lock to be set.  But
11141 	 * allow unlocks to succeed, to avoid having orphan locks on the
11142 	 * server.
11143 	 */
11144 	if (cmd != F_GETLK) {
11145 		mutex_enter(&rp->r_statelock);
11146 		while (rp->r_count > 0) {
11147 			if (intr) {
11148 				klwp_t *lwp = ttolwp(curthread);
11149 
11150 				if (lwp != NULL)
11151 					lwp->lwp_nostop++;
11152 				if (cv_wait_sig(&rp->r_cv,
11153 				    &rp->r_statelock) == 0) {
11154 					if (lwp != NULL)
11155 						lwp->lwp_nostop--;
11156 					rc = EINTR;
11157 					break;
11158 				}
11159 				if (lwp != NULL)
11160 					lwp->lwp_nostop--;
11161 				} else
11162 					cv_wait(&rp->r_cv, &rp->r_statelock);
11163 		}
11164 		mutex_exit(&rp->r_statelock);
11165 		if (rc != 0) {
11166 			ASSERT(bfp->l_type != F_UNLCK);
11167 
11168 			goto revert;
11169 		}
11170 
11171 		rc = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr, ct);
11172 		if (rc != 0) {
11173 			if (rc == ENOSPC || rc == EDQUOT) {
11174 				mutex_enter(&rp->r_statelock);
11175 				if (!rp->r_error)
11176 					rp->r_error = rc;
11177 				mutex_exit(&rp->r_statelock);
11178 			}
11179 
11180 			/*
11181 			 * If this was a lock request, make sure it is
11182 			 * reverted.
11183 			 */
11184 			if (bfp->l_type != F_UNLCK) {
11185 				rc = ENOLCK;
11186 				goto revert;
11187 			}
11188 		}
11189 	}
11190 
11191 	/*
11192 	 * Call the lock manager to do the real work of contacting
11193 	 * the server and obtaining the lock.
11194 	 */
11195 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, cr, &e, NULL, NULL);
11196 	rc = e.error;
11197 
11198 	if (rc == 0)
11199 		nfs4_lockcompletion(vp, cmd);
11200 
11201 revert:
11202 	/*
11203 	 * If this is either successful unlock request or a lock request that
11204 	 * failed we should unregister/revert the local lock now.
11205 	 */
11206 	if ((rc == 0 && cmd != F_GETLK && bfp->l_type == F_UNLCK) ||
11207 	    (rc != 0 && cmd != F_GETLK && bfp->l_type != F_UNLCK)) {
11208 		int r;
11209 
11210 		bfp->l_type = F_UNLCK;
11211 		r = reclock(vp, bfp, frcmd, flag, 0, flk_cbp);
11212 		/* The unlock cannot fail */
11213 		ASSERT(r == 0);
11214 	}
11215 
11216 done:
11217 	nfs_rw_exit(&rp->r_lkserlock);
11218 	if (ls != NULL)
11219 		lm_rel_sysid(ls);
11220 
11221 	return (rc);
11222 }
11223 
11224 /*
11225  * Free storage space associated with the specified vnode.  The portion
11226  * to be freed is specified by bfp->l_start and bfp->l_len (already
11227  * normalized to a "whence" of 0).
11228  *
11229  * This is an experimental facility whose continued existence is not
11230  * guaranteed.  Currently, we only support the special case
11231  * of l_len == 0, meaning free to end of file.
11232  */
11233 /* ARGSUSED */
11234 static int
11235 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
11236     offset_t offset, cred_t *cr, caller_context_t *ct)
11237 {
11238 	int error;
11239 
11240 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11241 		return (EIO);
11242 	ASSERT(vp->v_type == VREG);
11243 	if (cmd != F_FREESP)
11244 		return (EINVAL);
11245 
11246 	error = convoff(vp, bfp, 0, offset);
11247 	if (!error) {
11248 		ASSERT(bfp->l_start >= 0);
11249 		if (bfp->l_len == 0) {
11250 			struct vattr va;
11251 
11252 			va.va_mask = AT_SIZE;
11253 			va.va_size = bfp->l_start;
11254 			error = nfs4setattr(vp, &va, 0, cr, NULL);
11255 
11256 			if (error == 0 && bfp->l_start == 0)
11257 				vnevent_truncate(vp, ct);
11258 		} else
11259 			error = EINVAL;
11260 	}
11261 
11262 	return (error);
11263 }
11264 
11265 /* ARGSUSED */
11266 int
11267 nfs4_realvp(vnode_t *vp, vnode_t **vpp, caller_context_t *ct)
11268 {
11269 	rnode4_t *rp;
11270 	rp = VTOR4(vp);
11271 
11272 	if (vp->v_type == VREG && IS_SHADOW(vp, rp)) {
11273 		vp = RTOV4(rp);
11274 	}
11275 	*vpp = vp;
11276 	return (0);
11277 }
11278 
11279 /*
11280  * Setup and add an address space callback to do the work of the delmap call.
11281  * The callback will (and must be) deleted in the actual callback function.
11282  *
11283  * This is done in order to take care of the problem that we have with holding
11284  * the address space's a_lock for a long period of time (e.g. if the NFS server
11285  * is down).  Callbacks will be executed in the address space code while the
11286  * a_lock is not held.  Holding the address space's a_lock causes things such
11287  * as ps and fork to hang because they are trying to acquire this lock as well.
11288  */
11289 /* ARGSUSED */
11290 static int
11291 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
11292     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
11293     caller_context_t *ct)
11294 {
11295 	int			caller_found;
11296 	int			error;
11297 	rnode4_t		*rp;
11298 	nfs4_delmap_args_t	*dmapp;
11299 	nfs4_delmapcall_t	*delmap_call;
11300 
11301 	if (vp->v_flag & VNOMAP)
11302 		return (ENOSYS);
11303 
11304 	/*
11305 	 * A process may not change zones if it has NFS pages mmap'ed
11306 	 * in, so we can't legitimately get here from the wrong zone.
11307 	 */
11308 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11309 
11310 	rp = VTOR4(vp);
11311 
11312 	/*
11313 	 * The way that the address space of this process deletes its mapping
11314 	 * of this file is via the following call chains:
11315 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11316 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11317 	 *
11318 	 * With the use of address space callbacks we are allowed to drop the
11319 	 * address space lock, a_lock, while executing the NFS operations that
11320 	 * need to go over the wire.  Returning EAGAIN to the caller of this
11321 	 * function is what drives the execution of the callback that we add
11322 	 * below.  The callback will be executed by the address space code
11323 	 * after dropping the a_lock.  When the callback is finished, since
11324 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
11325 	 * is called again on the same segment to finish the rest of the work
11326 	 * that needs to happen during unmapping.
11327 	 *
11328 	 * This action of calling back into the segment driver causes
11329 	 * nfs4_delmap() to get called again, but since the callback was
11330 	 * already executed at this point, it already did the work and there
11331 	 * is nothing left for us to do.
11332 	 *
11333 	 * To Summarize:
11334 	 * - The first time nfs4_delmap is called by the current thread is when
11335 	 * we add the caller associated with this delmap to the delmap caller
11336 	 * list, add the callback, and return EAGAIN.
11337 	 * - The second time in this call chain when nfs4_delmap is called we
11338 	 * will find this caller in the delmap caller list and realize there
11339 	 * is no more work to do thus removing this caller from the list and
11340 	 * returning the error that was set in the callback execution.
11341 	 */
11342 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
11343 	if (caller_found) {
11344 		/*
11345 		 * 'error' is from the actual delmap operations.  To avoid
11346 		 * hangs, we need to handle the return of EAGAIN differently
11347 		 * since this is what drives the callback execution.
11348 		 * In this case, we don't want to return EAGAIN and do the
11349 		 * callback execution because there are none to execute.
11350 		 */
11351 		if (error == EAGAIN)
11352 			return (0);
11353 		else
11354 			return (error);
11355 	}
11356 
11357 	/* current caller was not in the list */
11358 	delmap_call = nfs4_init_delmapcall();
11359 
11360 	mutex_enter(&rp->r_statelock);
11361 	list_insert_tail(&rp->r_indelmap, delmap_call);
11362 	mutex_exit(&rp->r_statelock);
11363 
11364 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
11365 
11366 	dmapp->vp = vp;
11367 	dmapp->off = off;
11368 	dmapp->addr = addr;
11369 	dmapp->len = len;
11370 	dmapp->prot = prot;
11371 	dmapp->maxprot = maxprot;
11372 	dmapp->flags = flags;
11373 	dmapp->cr = cr;
11374 	dmapp->caller = delmap_call;
11375 
11376 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
11377 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
11378 
11379 	return (error ? error : EAGAIN);
11380 }
11381 
11382 static nfs4_delmapcall_t *
11383 nfs4_init_delmapcall()
11384 {
11385 	nfs4_delmapcall_t	*delmap_call;
11386 
11387 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
11388 	delmap_call->call_id = curthread;
11389 	delmap_call->error = 0;
11390 
11391 	return (delmap_call);
11392 }
11393 
11394 static void
11395 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11396 {
11397 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11398 }
11399 
11400 /*
11401  * Searches for the current delmap caller (based on curthread) in the list of
11402  * callers.  If it is found, we remove it and free the delmap caller.
11403  * Returns:
11404  *      0 if the caller wasn't found
11405  *      1 if the caller was found, removed and freed.  *errp will be set
11406  *	to what the result of the delmap was.
11407  */
11408 static int
11409 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11410 {
11411 	nfs4_delmapcall_t	*delmap_call;
11412 
11413 	/*
11414 	 * If the list doesn't exist yet, we create it and return
11415 	 * that the caller wasn't found.  No list = no callers.
11416 	 */
11417 	mutex_enter(&rp->r_statelock);
11418 	if (!(rp->r_flags & R4DELMAPLIST)) {
11419 		/* The list does not exist */
11420 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11421 		    offsetof(nfs4_delmapcall_t, call_node));
11422 		rp->r_flags |= R4DELMAPLIST;
11423 		mutex_exit(&rp->r_statelock);
11424 		return (0);
11425 	} else {
11426 		/* The list exists so search it */
11427 		for (delmap_call = list_head(&rp->r_indelmap);
11428 		    delmap_call != NULL;
11429 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11430 			if (delmap_call->call_id == curthread) {
11431 				/* current caller is in the list */
11432 				*errp = delmap_call->error;
11433 				list_remove(&rp->r_indelmap, delmap_call);
11434 				mutex_exit(&rp->r_statelock);
11435 				nfs4_free_delmapcall(delmap_call);
11436 				return (1);
11437 			}
11438 		}
11439 	}
11440 	mutex_exit(&rp->r_statelock);
11441 	return (0);
11442 }
11443 
11444 /*
11445  * Remove some pages from an mmap'd vnode.  Just update the
11446  * count of pages.  If doing close-to-open, then flush and
11447  * commit all of the pages associated with this file.
11448  * Otherwise, start an asynchronous page flush to write out
11449  * any dirty pages.  This will also associate a credential
11450  * with the rnode which can be used to write the pages.
11451  */
11452 /* ARGSUSED */
11453 static void
11454 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11455 {
11456 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11457 	rnode4_t		*rp;
11458 	mntinfo4_t		*mi;
11459 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11460 
11461 	rp = VTOR4(dmapp->vp);
11462 	mi = VTOMI4(dmapp->vp);
11463 
11464 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11465 	ASSERT(rp->r_mapcnt >= 0);
11466 
11467 	/*
11468 	 * Initiate a page flush and potential commit if there are
11469 	 * pages, the file system was not mounted readonly, the segment
11470 	 * was mapped shared, and the pages themselves were writeable.
11471 	 */
11472 	if (nfs4_has_pages(dmapp->vp) &&
11473 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11474 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11475 		mutex_enter(&rp->r_statelock);
11476 		rp->r_flags |= R4DIRTY;
11477 		mutex_exit(&rp->r_statelock);
11478 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11479 		    dmapp->len, dmapp->cr);
11480 		if (!e.error) {
11481 			mutex_enter(&rp->r_statelock);
11482 			e.error = rp->r_error;
11483 			rp->r_error = 0;
11484 			mutex_exit(&rp->r_statelock);
11485 		}
11486 	} else
11487 		e.error = 0;
11488 
11489 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11490 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11491 		    B_INVAL, dmapp->cr, NULL);
11492 
11493 	if (e.error) {
11494 		e.stat = puterrno4(e.error);
11495 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11496 		    OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11497 		dmapp->caller->error = e.error;
11498 	}
11499 
11500 	/* Check to see if we need to close the file */
11501 
11502 	if (dmapp->vp->v_type == VREG) {
11503 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11504 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11505 
11506 		if (e.error != 0 || e.stat != NFS4_OK) {
11507 			/*
11508 			 * Since it is possible that e.error == 0 and
11509 			 * e.stat != NFS4_OK (and vice versa),
11510 			 * we do the proper checking in order to get both
11511 			 * e.error and e.stat reporting the correct info.
11512 			 */
11513 			if (e.stat == NFS4_OK)
11514 				e.stat = puterrno4(e.error);
11515 			if (e.error == 0)
11516 				e.error = geterrno4(e.stat);
11517 
11518 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11519 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11520 			dmapp->caller->error = e.error;
11521 		}
11522 	}
11523 
11524 	(void) as_delete_callback(as, arg);
11525 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11526 }
11527 
11528 
11529 static uint_t
11530 fattr4_maxfilesize_to_bits(uint64_t ll)
11531 {
11532 	uint_t l = 1;
11533 
11534 	if (ll == 0) {
11535 		return (0);
11536 	}
11537 
11538 	if (ll & 0xffffffff00000000) {
11539 		l += 32; ll >>= 32;
11540 	}
11541 	if (ll & 0xffff0000) {
11542 		l += 16; ll >>= 16;
11543 	}
11544 	if (ll & 0xff00) {
11545 		l += 8; ll >>= 8;
11546 	}
11547 	if (ll & 0xf0) {
11548 		l += 4; ll >>= 4;
11549 	}
11550 	if (ll & 0xc) {
11551 		l += 2; ll >>= 2;
11552 	}
11553 	if (ll & 0x2) {
11554 		l += 1;
11555 	}
11556 	return (l);
11557 }
11558 
11559 static int
11560 nfs4_have_xattrs(vnode_t *vp, ulong_t *valp, cred_t *cr)
11561 {
11562 	vnode_t *avp = NULL;
11563 	int error;
11564 
11565 	if ((error = nfs4lookup_xattr(vp, "", &avp,
11566 	    LOOKUP_XATTR, cr)) == 0)
11567 		error = do_xattr_exists_check(avp, valp, cr);
11568 	if (avp)
11569 		VN_RELE(avp);
11570 
11571 	return (error);
11572 }
11573 
11574 /* ARGSUSED */
11575 int
11576 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
11577     caller_context_t *ct)
11578 {
11579 	int error;
11580 	hrtime_t t;
11581 	rnode4_t *rp;
11582 	nfs4_ga_res_t gar;
11583 	nfs4_ga_ext_res_t ger;
11584 
11585 	gar.n4g_ext_res = &ger;
11586 
11587 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11588 		return (EIO);
11589 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11590 		*valp = MAXPATHLEN;
11591 		return (0);
11592 	}
11593 	if (cmd == _PC_ACL_ENABLED) {
11594 		*valp = _ACL_ACE_ENABLED;
11595 		return (0);
11596 	}
11597 
11598 	rp = VTOR4(vp);
11599 	if (cmd == _PC_XATTR_EXISTS) {
11600 		/*
11601 		 * The existence of the xattr directory is not sufficient
11602 		 * for determining whether generic user attributes exists.
11603 		 * The attribute directory could only be a transient directory
11604 		 * used for Solaris sysattr support.  Do a small readdir
11605 		 * to verify if the only entries are sysattrs or not.
11606 		 *
11607 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11608 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11609 		 * and we don't have any way to update the "base" object's
11610 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11611 		 * could help out.
11612 		 */
11613 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11614 		    rp->r_xattr_dir == NULL) {
11615 			return (nfs4_have_xattrs(vp, valp, cr));
11616 		}
11617 	} else {  /* OLD CODE */
11618 		if (ATTRCACHE4_VALID(vp)) {
11619 			mutex_enter(&rp->r_statelock);
11620 			if (rp->r_pathconf.pc4_cache_valid) {
11621 				error = 0;
11622 				switch (cmd) {
11623 				case _PC_FILESIZEBITS:
11624 					*valp =
11625 					    rp->r_pathconf.pc4_filesizebits;
11626 					break;
11627 				case _PC_LINK_MAX:
11628 					*valp =
11629 					    rp->r_pathconf.pc4_link_max;
11630 					break;
11631 				case _PC_NAME_MAX:
11632 					*valp =
11633 					    rp->r_pathconf.pc4_name_max;
11634 					break;
11635 				case _PC_CHOWN_RESTRICTED:
11636 					*valp =
11637 					    rp->r_pathconf.pc4_chown_restricted;
11638 					break;
11639 				case _PC_NO_TRUNC:
11640 					*valp =
11641 					    rp->r_pathconf.pc4_no_trunc;
11642 					break;
11643 				default:
11644 					error = EINVAL;
11645 					break;
11646 				}
11647 				mutex_exit(&rp->r_statelock);
11648 #ifdef DEBUG
11649 				nfs4_pathconf_cache_hits++;
11650 #endif
11651 				return (error);
11652 			}
11653 			mutex_exit(&rp->r_statelock);
11654 		}
11655 	}
11656 #ifdef DEBUG
11657 	nfs4_pathconf_cache_misses++;
11658 #endif
11659 
11660 	t = gethrtime();
11661 
11662 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11663 
11664 	if (error) {
11665 		mutex_enter(&rp->r_statelock);
11666 		rp->r_pathconf.pc4_cache_valid = FALSE;
11667 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11668 		mutex_exit(&rp->r_statelock);
11669 		return (error);
11670 	}
11671 
11672 	/* interpret the max filesize */
11673 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11674 	    fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11675 
11676 	/* Store the attributes we just received */
11677 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11678 
11679 	switch (cmd) {
11680 	case _PC_FILESIZEBITS:
11681 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11682 		break;
11683 	case _PC_LINK_MAX:
11684 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11685 		break;
11686 	case _PC_NAME_MAX:
11687 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11688 		break;
11689 	case _PC_CHOWN_RESTRICTED:
11690 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11691 		break;
11692 	case _PC_NO_TRUNC:
11693 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11694 		break;
11695 	case _PC_XATTR_EXISTS:
11696 		if (gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists) {
11697 			if (error = nfs4_have_xattrs(vp, valp, cr))
11698 				return (error);
11699 		}
11700 		break;
11701 	default:
11702 		return (EINVAL);
11703 	}
11704 
11705 	return (0);
11706 }
11707 
11708 /*
11709  * Called by async thread to do synchronous pageio. Do the i/o, wait
11710  * for it to complete, and cleanup the page list when done.
11711  */
11712 static int
11713 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11714     int flags, cred_t *cr)
11715 {
11716 	int error;
11717 
11718 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11719 
11720 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11721 	if (flags & B_READ)
11722 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11723 	else
11724 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11725 	return (error);
11726 }
11727 
11728 /* ARGSUSED */
11729 static int
11730 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11731     int flags, cred_t *cr, caller_context_t *ct)
11732 {
11733 	int error;
11734 	rnode4_t *rp;
11735 
11736 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11737 		return (EIO);
11738 
11739 	if (pp == NULL)
11740 		return (EINVAL);
11741 
11742 	rp = VTOR4(vp);
11743 	mutex_enter(&rp->r_statelock);
11744 	rp->r_count++;
11745 	mutex_exit(&rp->r_statelock);
11746 
11747 	if (flags & B_ASYNC) {
11748 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11749 		    nfs4_sync_pageio);
11750 	} else
11751 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11752 	mutex_enter(&rp->r_statelock);
11753 	rp->r_count--;
11754 	cv_broadcast(&rp->r_cv);
11755 	mutex_exit(&rp->r_statelock);
11756 	return (error);
11757 }
11758 
11759 /* ARGSUSED */
11760 static void
11761 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr,
11762     caller_context_t *ct)
11763 {
11764 	int error;
11765 	rnode4_t *rp;
11766 	page_t *plist;
11767 	page_t *pptr;
11768 	offset3 offset;
11769 	count3 len;
11770 	k_sigset_t smask;
11771 
11772 	/*
11773 	 * We should get called with fl equal to either B_FREE or
11774 	 * B_INVAL.  Any other value is illegal.
11775 	 *
11776 	 * The page that we are either supposed to free or destroy
11777 	 * should be exclusive locked and its io lock should not
11778 	 * be held.
11779 	 */
11780 	ASSERT(fl == B_FREE || fl == B_INVAL);
11781 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11782 
11783 	rp = VTOR4(vp);
11784 
11785 	/*
11786 	 * If the page doesn't need to be committed or we shouldn't
11787 	 * even bother attempting to commit it, then just make sure
11788 	 * that the p_fsdata byte is clear and then either free or
11789 	 * destroy the page as appropriate.
11790 	 */
11791 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11792 		pp->p_fsdata = C_NOCOMMIT;
11793 		if (fl == B_FREE)
11794 			page_free(pp, dn);
11795 		else
11796 			page_destroy(pp, dn);
11797 		return;
11798 	}
11799 
11800 	/*
11801 	 * If there is a page invalidation operation going on, then
11802 	 * if this is one of the pages being destroyed, then just
11803 	 * clear the p_fsdata byte and then either free or destroy
11804 	 * the page as appropriate.
11805 	 */
11806 	mutex_enter(&rp->r_statelock);
11807 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11808 		mutex_exit(&rp->r_statelock);
11809 		pp->p_fsdata = C_NOCOMMIT;
11810 		if (fl == B_FREE)
11811 			page_free(pp, dn);
11812 		else
11813 			page_destroy(pp, dn);
11814 		return;
11815 	}
11816 
11817 	/*
11818 	 * If we are freeing this page and someone else is already
11819 	 * waiting to do a commit, then just unlock the page and
11820 	 * return.  That other thread will take care of commiting
11821 	 * this page.  The page can be freed sometime after the
11822 	 * commit has finished.  Otherwise, if the page is marked
11823 	 * as delay commit, then we may be getting called from
11824 	 * pvn_write_done, one page at a time.   This could result
11825 	 * in one commit per page, so we end up doing lots of small
11826 	 * commits instead of fewer larger commits.  This is bad,
11827 	 * we want do as few commits as possible.
11828 	 */
11829 	if (fl == B_FREE) {
11830 		if (rp->r_flags & R4COMMITWAIT) {
11831 			page_unlock(pp);
11832 			mutex_exit(&rp->r_statelock);
11833 			return;
11834 		}
11835 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11836 			pp->p_fsdata = C_COMMIT;
11837 			page_unlock(pp);
11838 			mutex_exit(&rp->r_statelock);
11839 			return;
11840 		}
11841 	}
11842 
11843 	/*
11844 	 * Check to see if there is a signal which would prevent an
11845 	 * attempt to commit the pages from being successful.  If so,
11846 	 * then don't bother with all of the work to gather pages and
11847 	 * generate the unsuccessful RPC.  Just return from here and
11848 	 * let the page be committed at some later time.
11849 	 */
11850 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11851 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11852 		sigunintr(&smask);
11853 		page_unlock(pp);
11854 		mutex_exit(&rp->r_statelock);
11855 		return;
11856 	}
11857 	sigunintr(&smask);
11858 
11859 	/*
11860 	 * We are starting to need to commit pages, so let's try
11861 	 * to commit as many as possible at once to reduce the
11862 	 * overhead.
11863 	 *
11864 	 * Set the `commit inprogress' state bit.  We must
11865 	 * first wait until any current one finishes.  Then
11866 	 * we initialize the c_pages list with this page.
11867 	 */
11868 	while (rp->r_flags & R4COMMIT) {
11869 		rp->r_flags |= R4COMMITWAIT;
11870 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11871 		rp->r_flags &= ~R4COMMITWAIT;
11872 	}
11873 	rp->r_flags |= R4COMMIT;
11874 	mutex_exit(&rp->r_statelock);
11875 	ASSERT(rp->r_commit.c_pages == NULL);
11876 	rp->r_commit.c_pages = pp;
11877 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11878 	rp->r_commit.c_commlen = PAGESIZE;
11879 
11880 	/*
11881 	 * Gather together all other pages which can be committed.
11882 	 * They will all be chained off r_commit.c_pages.
11883 	 */
11884 	nfs4_get_commit(vp);
11885 
11886 	/*
11887 	 * Clear the `commit inprogress' status and disconnect
11888 	 * the list of pages to be committed from the rnode.
11889 	 * At this same time, we also save the starting offset
11890 	 * and length of data to be committed on the server.
11891 	 */
11892 	plist = rp->r_commit.c_pages;
11893 	rp->r_commit.c_pages = NULL;
11894 	offset = rp->r_commit.c_commbase;
11895 	len = rp->r_commit.c_commlen;
11896 	mutex_enter(&rp->r_statelock);
11897 	rp->r_flags &= ~R4COMMIT;
11898 	cv_broadcast(&rp->r_commit.c_cv);
11899 	mutex_exit(&rp->r_statelock);
11900 
11901 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11902 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11903 		nfs4_async_commit(vp, plist, offset, len,
11904 		    cr, do_nfs4_async_commit);
11905 		return;
11906 	}
11907 
11908 	/*
11909 	 * Actually generate the COMMIT op over the wire operation.
11910 	 */
11911 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11912 
11913 	/*
11914 	 * If we got an error during the commit, just unlock all
11915 	 * of the pages.  The pages will get retransmitted to the
11916 	 * server during a putpage operation.
11917 	 */
11918 	if (error) {
11919 		while (plist != NULL) {
11920 			pptr = plist;
11921 			page_sub(&plist, pptr);
11922 			page_unlock(pptr);
11923 		}
11924 		return;
11925 	}
11926 
11927 	/*
11928 	 * We've tried as hard as we can to commit the data to stable
11929 	 * storage on the server.  We just unlock the rest of the pages
11930 	 * and clear the commit required state.  They will be put
11931 	 * onto the tail of the cachelist if they are nolonger
11932 	 * mapped.
11933 	 */
11934 	while (plist != pp) {
11935 		pptr = plist;
11936 		page_sub(&plist, pptr);
11937 		pptr->p_fsdata = C_NOCOMMIT;
11938 		page_unlock(pptr);
11939 	}
11940 
11941 	/*
11942 	 * It is possible that nfs4_commit didn't return error but
11943 	 * some other thread has modified the page we are going
11944 	 * to free/destroy.
11945 	 *    In this case we need to rewrite the page. Do an explicit check
11946 	 * before attempting to free/destroy the page. If modified, needs to
11947 	 * be rewritten so unlock the page and return.
11948 	 */
11949 	if (hat_ismod(pp)) {
11950 		pp->p_fsdata = C_NOCOMMIT;
11951 		page_unlock(pp);
11952 		return;
11953 	}
11954 
11955 	/*
11956 	 * Now, as appropriate, either free or destroy the page
11957 	 * that we were called with.
11958 	 */
11959 	pp->p_fsdata = C_NOCOMMIT;
11960 	if (fl == B_FREE)
11961 		page_free(pp, dn);
11962 	else
11963 		page_destroy(pp, dn);
11964 }
11965 
11966 /*
11967  * Commit requires that the current fh be the file written to.
11968  * The compound op structure is:
11969  *      PUTFH(file), COMMIT
11970  */
11971 static int
11972 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11973 {
11974 	COMPOUND4args_clnt args;
11975 	COMPOUND4res_clnt res;
11976 	COMMIT4res *cm_res;
11977 	nfs_argop4 argop[2];
11978 	nfs_resop4 *resop;
11979 	int doqueue;
11980 	mntinfo4_t *mi;
11981 	rnode4_t *rp;
11982 	cred_t *cred_otw = NULL;
11983 	bool_t needrecov = FALSE;
11984 	nfs4_recov_state_t recov_state;
11985 	nfs4_open_stream_t *osp = NULL;
11986 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11987 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11988 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11989 
11990 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11991 
11992 	rp = VTOR4(vp);
11993 
11994 	mi = VTOMI4(vp);
11995 	recov_state.rs_flags = 0;
11996 	recov_state.rs_num_retry_despite_err = 0;
11997 get_commit_cred:
11998 	/*
11999 	 * Releases the osp, if a valid open stream is provided.
12000 	 * Puts a hold on the cred_otw and the new osp (if found).
12001 	 */
12002 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
12003 	    &first_time, &last_time);
12004 	args.ctag = TAG_COMMIT;
12005 recov_retry:
12006 	/*
12007 	 * Commit ops: putfh file; commit
12008 	 */
12009 	args.array_len = 2;
12010 	args.array = argop;
12011 
12012 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
12013 	    &recov_state, NULL);
12014 	if (e.error) {
12015 		crfree(cred_otw);
12016 		if (osp != NULL)
12017 			open_stream_rele(osp, rp);
12018 		return (e.error);
12019 	}
12020 
12021 	/* putfh directory */
12022 	argop[0].argop = OP_CPUTFH;
12023 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
12024 
12025 	/* commit */
12026 	argop[1].argop = OP_COMMIT;
12027 	argop[1].nfs_argop4_u.opcommit.offset = offset;
12028 	argop[1].nfs_argop4_u.opcommit.count = count;
12029 
12030 	doqueue = 1;
12031 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
12032 
12033 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
12034 	if (!needrecov && e.error) {
12035 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
12036 		    needrecov);
12037 		crfree(cred_otw);
12038 		if (e.error == EACCES && last_time == FALSE)
12039 			goto get_commit_cred;
12040 		if (osp != NULL)
12041 			open_stream_rele(osp, rp);
12042 		return (e.error);
12043 	}
12044 
12045 	if (needrecov) {
12046 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
12047 		    NULL, OP_COMMIT, NULL, NULL, NULL) == FALSE) {
12048 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
12049 			    &recov_state, needrecov);
12050 			if (!e.error)
12051 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12052 				    (caddr_t)&res);
12053 			goto recov_retry;
12054 		}
12055 		if (e.error) {
12056 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
12057 			    &recov_state, needrecov);
12058 			crfree(cred_otw);
12059 			if (osp != NULL)
12060 				open_stream_rele(osp, rp);
12061 			return (e.error);
12062 		}
12063 		/* fall through for res.status case */
12064 	}
12065 
12066 	if (res.status) {
12067 		e.error = geterrno4(res.status);
12068 		if (e.error == EACCES && last_time == FALSE) {
12069 			crfree(cred_otw);
12070 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
12071 			    &recov_state, needrecov);
12072 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12073 			goto get_commit_cred;
12074 		}
12075 		/*
12076 		 * Can't do a nfs4_purge_stale_fh here because this
12077 		 * can cause a deadlock.  nfs4_commit can
12078 		 * be called from nfs4_dispose which can be called
12079 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
12080 		 * can call back to pvn_vplist_dirty.
12081 		 */
12082 		if (e.error == ESTALE) {
12083 			mutex_enter(&rp->r_statelock);
12084 			rp->r_flags |= R4STALE;
12085 			if (!rp->r_error)
12086 				rp->r_error = e.error;
12087 			mutex_exit(&rp->r_statelock);
12088 			PURGE_ATTRCACHE4(vp);
12089 		} else {
12090 			mutex_enter(&rp->r_statelock);
12091 			if (!rp->r_error)
12092 				rp->r_error = e.error;
12093 			mutex_exit(&rp->r_statelock);
12094 		}
12095 	} else {
12096 		ASSERT(rp->r_flags & R4HAVEVERF);
12097 		resop = &res.array[1];	/* commit res */
12098 		cm_res = &resop->nfs_resop4_u.opcommit;
12099 		mutex_enter(&rp->r_statelock);
12100 		if (cm_res->writeverf == rp->r_writeverf) {
12101 			mutex_exit(&rp->r_statelock);
12102 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12103 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
12104 			    &recov_state, needrecov);
12105 			crfree(cred_otw);
12106 			if (osp != NULL)
12107 				open_stream_rele(osp, rp);
12108 			return (0);
12109 		}
12110 		nfs4_set_mod(vp);
12111 		rp->r_writeverf = cm_res->writeverf;
12112 		mutex_exit(&rp->r_statelock);
12113 		e.error = NFS_VERF_MISMATCH;
12114 	}
12115 
12116 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12117 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
12118 	crfree(cred_otw);
12119 	if (osp != NULL)
12120 		open_stream_rele(osp, rp);
12121 
12122 	return (e.error);
12123 }
12124 
12125 static void
12126 nfs4_set_mod(vnode_t *vp)
12127 {
12128 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12129 
12130 	/* make sure we're looking at the master vnode, not a shadow */
12131 	pvn_vplist_setdirty(RTOV4(VTOR4(vp)), nfs_setmod_check);
12132 }
12133 
12134 /*
12135  * This function is used to gather a page list of the pages which
12136  * can be committed on the server.
12137  *
12138  * The calling thread must have set R4COMMIT.  This bit is used to
12139  * serialize access to the commit structure in the rnode.  As long
12140  * as the thread has set R4COMMIT, then it can manipulate the commit
12141  * structure without requiring any other locks.
12142  *
12143  * When this function is called from nfs4_dispose() the page passed
12144  * into nfs4_dispose() will be SE_EXCL locked, and so this function
12145  * will skip it. This is not a problem since we initially add the
12146  * page to the r_commit page list.
12147  *
12148  */
12149 static void
12150 nfs4_get_commit(vnode_t *vp)
12151 {
12152 	rnode4_t *rp;
12153 	page_t *pp;
12154 	kmutex_t *vphm;
12155 
12156 	rp = VTOR4(vp);
12157 
12158 	ASSERT(rp->r_flags & R4COMMIT);
12159 
12160 	/* make sure we're looking at the master vnode, not a shadow */
12161 
12162 	if (IS_SHADOW(vp, rp))
12163 		vp = RTOV4(rp);
12164 
12165 	vphm = page_vnode_mutex(vp);
12166 	mutex_enter(vphm);
12167 
12168 	/*
12169 	 * If there are no pages associated with this vnode, then
12170 	 * just return.
12171 	 */
12172 	if ((pp = vp->v_pages) == NULL) {
12173 		mutex_exit(vphm);
12174 		return;
12175 	}
12176 
12177 	/*
12178 	 * Step through all of the pages associated with this vnode
12179 	 * looking for pages which need to be committed.
12180 	 */
12181 	do {
12182 		/* Skip marker pages. */
12183 		if (pp->p_hash == PVN_VPLIST_HASH_TAG)
12184 			continue;
12185 
12186 		/*
12187 		 * First short-cut everything (without the page_lock)
12188 		 * and see if this page does not need to be committed
12189 		 * or is modified if so then we'll just skip it.
12190 		 */
12191 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
12192 			continue;
12193 
12194 		/*
12195 		 * Attempt to lock the page.  If we can't, then
12196 		 * someone else is messing with it or we have been
12197 		 * called from nfs4_dispose and this is the page that
12198 		 * nfs4_dispose was called with.. anyway just skip it.
12199 		 */
12200 		if (!page_trylock(pp, SE_EXCL))
12201 			continue;
12202 
12203 		/*
12204 		 * Lets check again now that we have the page lock.
12205 		 */
12206 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
12207 			page_unlock(pp);
12208 			continue;
12209 		}
12210 
12211 		/* this had better not be a free page */
12212 		ASSERT(PP_ISFREE(pp) == 0);
12213 
12214 		/*
12215 		 * The page needs to be committed and we locked it.
12216 		 * Update the base and length parameters and add it
12217 		 * to r_pages.
12218 		 */
12219 		if (rp->r_commit.c_pages == NULL) {
12220 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
12221 			rp->r_commit.c_commlen = PAGESIZE;
12222 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
12223 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
12224 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
12225 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
12226 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
12227 		    <= pp->p_offset) {
12228 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
12229 			    rp->r_commit.c_commbase + PAGESIZE;
12230 		}
12231 		page_add(&rp->r_commit.c_pages, pp);
12232 	} while ((pp = pp->p_vpnext) != vp->v_pages);
12233 
12234 	mutex_exit(vphm);
12235 }
12236 
12237 /*
12238  * This routine is used to gather together a page list of the pages
12239  * which are to be committed on the server.  This routine must not
12240  * be called if the calling thread holds any locked pages.
12241  *
12242  * The calling thread must have set R4COMMIT.  This bit is used to
12243  * serialize access to the commit structure in the rnode.  As long
12244  * as the thread has set R4COMMIT, then it can manipulate the commit
12245  * structure without requiring any other locks.
12246  */
12247 static void
12248 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
12249 {
12250 
12251 	rnode4_t *rp;
12252 	page_t *pp;
12253 	u_offset_t end;
12254 	u_offset_t off;
12255 	ASSERT(len != 0);
12256 	rp = VTOR4(vp);
12257 	ASSERT(rp->r_flags & R4COMMIT);
12258 
12259 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12260 
12261 	/* make sure we're looking at the master vnode, not a shadow */
12262 
12263 	if (IS_SHADOW(vp, rp))
12264 		vp = RTOV4(rp);
12265 
12266 	/*
12267 	 * If there are no pages associated with this vnode, then
12268 	 * just return.
12269 	 */
12270 	if ((pp = vp->v_pages) == NULL)
12271 		return;
12272 	/*
12273 	 * Calculate the ending offset.
12274 	 */
12275 	end = soff + len;
12276 	for (off = soff; off < end; off += PAGESIZE) {
12277 		/*
12278 		 * Lookup each page by vp, offset.
12279 		 */
12280 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
12281 			continue;
12282 		/*
12283 		 * If this page does not need to be committed or is
12284 		 * modified, then just skip it.
12285 		 */
12286 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
12287 			page_unlock(pp);
12288 			continue;
12289 		}
12290 
12291 		ASSERT(PP_ISFREE(pp) == 0);
12292 		/*
12293 		 * The page needs to be committed and we locked it.
12294 		 * Update the base and length parameters and add it
12295 		 * to r_pages.
12296 		 */
12297 		if (rp->r_commit.c_pages == NULL) {
12298 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
12299 			rp->r_commit.c_commlen = PAGESIZE;
12300 		} else {
12301 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
12302 			    rp->r_commit.c_commbase + PAGESIZE;
12303 		}
12304 		page_add(&rp->r_commit.c_pages, pp);
12305 	}
12306 }
12307 
12308 /*
12309  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
12310  * Flushes and commits data to the server.
12311  */
12312 static int
12313 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
12314 {
12315 	int error;
12316 	verifier4 write_verf;
12317 	rnode4_t *rp = VTOR4(vp);
12318 
12319 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12320 
12321 	/*
12322 	 * Flush the data portion of the file and then commit any
12323 	 * portions which need to be committed.  This may need to
12324 	 * be done twice if the server has changed state since
12325 	 * data was last written.  The data will need to be
12326 	 * rewritten to the server and then a new commit done.
12327 	 *
12328 	 * In fact, this may need to be done several times if the
12329 	 * server is having problems and crashing while we are
12330 	 * attempting to do this.
12331 	 */
12332 
12333 top:
12334 	/*
12335 	 * Do a flush based on the poff and plen arguments.  This
12336 	 * will synchronously write out any modified pages in the
12337 	 * range specified by (poff, plen). This starts all of the
12338 	 * i/o operations which will be waited for in the next
12339 	 * call to nfs4_putpage
12340 	 */
12341 
12342 	mutex_enter(&rp->r_statelock);
12343 	write_verf = rp->r_writeverf;
12344 	mutex_exit(&rp->r_statelock);
12345 
12346 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr, NULL);
12347 	if (error == EAGAIN)
12348 		error = 0;
12349 
12350 	/*
12351 	 * Do a flush based on the poff and plen arguments.  This
12352 	 * will synchronously write out any modified pages in the
12353 	 * range specified by (poff, plen) and wait until all of
12354 	 * the asynchronous i/o's in that range are done as well.
12355 	 */
12356 	if (!error)
12357 		error = nfs4_putpage(vp, poff, plen, 0, cr, NULL);
12358 
12359 	if (error)
12360 		return (error);
12361 
12362 	mutex_enter(&rp->r_statelock);
12363 	if (rp->r_writeverf != write_verf) {
12364 		mutex_exit(&rp->r_statelock);
12365 		goto top;
12366 	}
12367 	mutex_exit(&rp->r_statelock);
12368 
12369 	/*
12370 	 * Now commit any pages which might need to be committed.
12371 	 * If the error, NFS_VERF_MISMATCH, is returned, then
12372 	 * start over with the flush operation.
12373 	 */
12374 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
12375 
12376 	if (error == NFS_VERF_MISMATCH)
12377 		goto top;
12378 
12379 	return (error);
12380 }
12381 
12382 /*
12383  * nfs4_commit_vp()  will wait for other pending commits and
12384  * will either commit the whole file or a range, plen dictates
12385  * if we commit whole file. a value of zero indicates the whole
12386  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
12387  */
12388 static int
12389 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12390     cred_t *cr, int wait_on_writes)
12391 {
12392 	rnode4_t *rp;
12393 	page_t *plist;
12394 	offset3 offset;
12395 	count3 len;
12396 
12397 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12398 
12399 	rp = VTOR4(vp);
12400 
12401 	/*
12402 	 *  before we gather commitable pages make
12403 	 *  sure there are no outstanding async writes
12404 	 */
12405 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12406 		mutex_enter(&rp->r_statelock);
12407 		while (rp->r_count > 0) {
12408 			cv_wait(&rp->r_cv, &rp->r_statelock);
12409 		}
12410 		mutex_exit(&rp->r_statelock);
12411 	}
12412 
12413 	/*
12414 	 * Set the `commit inprogress' state bit.  We must
12415 	 * first wait until any current one finishes.
12416 	 */
12417 	mutex_enter(&rp->r_statelock);
12418 	while (rp->r_flags & R4COMMIT) {
12419 		rp->r_flags |= R4COMMITWAIT;
12420 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12421 		rp->r_flags &= ~R4COMMITWAIT;
12422 	}
12423 	rp->r_flags |= R4COMMIT;
12424 	mutex_exit(&rp->r_statelock);
12425 
12426 	/*
12427 	 * Gather all of the pages which need to be
12428 	 * committed.
12429 	 */
12430 	if (plen == 0)
12431 		nfs4_get_commit(vp);
12432 	else
12433 		nfs4_get_commit_range(vp, poff, plen);
12434 
12435 	/*
12436 	 * Clear the `commit inprogress' bit and disconnect the
12437 	 * page list which was gathered by nfs4_get_commit.
12438 	 */
12439 	plist = rp->r_commit.c_pages;
12440 	rp->r_commit.c_pages = NULL;
12441 	offset = rp->r_commit.c_commbase;
12442 	len = rp->r_commit.c_commlen;
12443 	mutex_enter(&rp->r_statelock);
12444 	rp->r_flags &= ~R4COMMIT;
12445 	cv_broadcast(&rp->r_commit.c_cv);
12446 	mutex_exit(&rp->r_statelock);
12447 
12448 	/*
12449 	 * If any pages need to be committed, commit them and
12450 	 * then unlock them so that they can be freed some
12451 	 * time later.
12452 	 */
12453 	if (plist == NULL)
12454 		return (0);
12455 
12456 	/*
12457 	 * No error occurred during the flush portion
12458 	 * of this operation, so now attempt to commit
12459 	 * the data to stable storage on the server.
12460 	 *
12461 	 * This will unlock all of the pages on the list.
12462 	 */
12463 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12464 }
12465 
12466 static int
12467 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12468     cred_t *cr)
12469 {
12470 	int error;
12471 	page_t *pp;
12472 
12473 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12474 
12475 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12476 
12477 	/*
12478 	 * If we got an error, then just unlock all of the pages
12479 	 * on the list.
12480 	 */
12481 	if (error) {
12482 		while (plist != NULL) {
12483 			pp = plist;
12484 			page_sub(&plist, pp);
12485 			page_unlock(pp);
12486 		}
12487 		return (error);
12488 	}
12489 	/*
12490 	 * We've tried as hard as we can to commit the data to stable
12491 	 * storage on the server.  We just unlock the pages and clear
12492 	 * the commit required state.  They will get freed later.
12493 	 */
12494 	while (plist != NULL) {
12495 		pp = plist;
12496 		page_sub(&plist, pp);
12497 		pp->p_fsdata = C_NOCOMMIT;
12498 		page_unlock(pp);
12499 	}
12500 
12501 	return (error);
12502 }
12503 
12504 static void
12505 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12506     cred_t *cr)
12507 {
12508 
12509 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12510 }
12511 
12512 /*ARGSUSED*/
12513 static int
12514 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12515     caller_context_t *ct)
12516 {
12517 	int		error = 0;
12518 	mntinfo4_t	*mi;
12519 	vattr_t		va;
12520 	vsecattr_t	nfsace4_vsap;
12521 
12522 	mi = VTOMI4(vp);
12523 	if (nfs_zone() != mi->mi_zone)
12524 		return (EIO);
12525 	if (mi->mi_flags & MI4_ACL) {
12526 		/* if we have a delegation, return it */
12527 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12528 			(void) nfs4delegreturn(VTOR4(vp),
12529 			    NFS4_DR_REOPEN|NFS4_DR_PUSH);
12530 
12531 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12532 		    NFS4_ACL_SET);
12533 		if (error) /* EINVAL */
12534 			return (error);
12535 
12536 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12537 			/*
12538 			 * These are aclent_t type entries.
12539 			 */
12540 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12541 			    vp->v_type == VDIR, FALSE);
12542 			if (error)
12543 				return (error);
12544 		} else {
12545 			/*
12546 			 * These are ace_t type entries.
12547 			 */
12548 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12549 			    FALSE);
12550 			if (error)
12551 				return (error);
12552 		}
12553 		bzero(&va, sizeof (va));
12554 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12555 		vs_ace4_destroy(&nfsace4_vsap);
12556 		return (error);
12557 	}
12558 	return (ENOSYS);
12559 }
12560 
12561 /* ARGSUSED */
12562 int
12563 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12564     caller_context_t *ct)
12565 {
12566 	int		error;
12567 	mntinfo4_t	*mi;
12568 	nfs4_ga_res_t	gar;
12569 	rnode4_t	*rp = VTOR4(vp);
12570 
12571 	mi = VTOMI4(vp);
12572 	if (nfs_zone() != mi->mi_zone)
12573 		return (EIO);
12574 
12575 	bzero(&gar, sizeof (gar));
12576 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12577 
12578 	/*
12579 	 * vsecattr->vsa_mask holds the original acl request mask.
12580 	 * This is needed when determining what to return.
12581 	 * (See: nfs4_create_getsecattr_return())
12582 	 */
12583 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12584 	if (error) /* EINVAL */
12585 		return (error);
12586 
12587 	/*
12588 	 * If this is a referral stub, don't try to go OTW for an ACL
12589 	 */
12590 	if (RP_ISSTUB_REFERRAL(VTOR4(vp)))
12591 		return (fs_fab_acl(vp, vsecattr, flag, cr, ct));
12592 
12593 	if (mi->mi_flags & MI4_ACL) {
12594 		/*
12595 		 * Check if the data is cached and the cache is valid.  If it
12596 		 * is we don't go over the wire.
12597 		 */
12598 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12599 			mutex_enter(&rp->r_statelock);
12600 			if (rp->r_secattr != NULL) {
12601 				error = nfs4_create_getsecattr_return(
12602 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12603 				    rp->r_attr.va_gid,
12604 				    vp->v_type == VDIR);
12605 				if (!error) { /* error == 0 - Success! */
12606 					mutex_exit(&rp->r_statelock);
12607 					return (error);
12608 				}
12609 			}
12610 			mutex_exit(&rp->r_statelock);
12611 		}
12612 
12613 		/*
12614 		 * The getattr otw call will always get both the acl, in
12615 		 * the form of a list of nfsace4's, and the number of acl
12616 		 * entries; independent of the value of gar.n4g_va.va_mask.
12617 		 */
12618 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12619 		if (error) {
12620 			vs_ace4_destroy(&gar.n4g_vsa);
12621 			if (error == ENOTSUP || error == EOPNOTSUPP)
12622 				error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12623 			return (error);
12624 		}
12625 
12626 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12627 			/*
12628 			 * No error was returned, but according to the response
12629 			 * bitmap, neither was an acl.
12630 			 */
12631 			vs_ace4_destroy(&gar.n4g_vsa);
12632 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12633 			return (error);
12634 		}
12635 
12636 		/*
12637 		 * Update the cache with the ACL.
12638 		 */
12639 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12640 
12641 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12642 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12643 		    vp->v_type == VDIR);
12644 		vs_ace4_destroy(&gar.n4g_vsa);
12645 		if ((error) && (vsecattr->vsa_mask &
12646 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12647 		    (error != EACCES)) {
12648 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12649 		}
12650 		return (error);
12651 	}
12652 	error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12653 	return (error);
12654 }
12655 
12656 /*
12657  * The function returns:
12658  *	- 0 (zero) if the passed in "acl_mask" is a valid request.
12659  *	- EINVAL if the passed in "acl_mask" is an invalid request.
12660  *
12661  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12662  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12663  *
12664  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12665  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12666  * - We have a count field set without the corresponding acl field set. (e.g. -
12667  * VSA_ACECNT is set, but VSA_ACE is not)
12668  */
12669 static int
12670 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12671 {
12672 	/* Shortcut the masks that are always valid. */
12673 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12674 		return (0);
12675 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12676 		return (0);
12677 
12678 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12679 		/*
12680 		 * We can't have any VSA_ACL type stuff in the mask now.
12681 		 */
12682 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12683 		    VSA_DFACLCNT))
12684 			return (EINVAL);
12685 
12686 		if (op == NFS4_ACL_SET) {
12687 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12688 				return (EINVAL);
12689 		}
12690 	}
12691 
12692 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12693 		/*
12694 		 * We can't have any VSA_ACE type stuff in the mask now.
12695 		 */
12696 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12697 			return (EINVAL);
12698 
12699 		if (op == NFS4_ACL_SET) {
12700 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12701 				return (EINVAL);
12702 
12703 			if ((acl_mask & VSA_DFACLCNT) &&
12704 			    !(acl_mask & VSA_DFACL))
12705 				return (EINVAL);
12706 		}
12707 	}
12708 	return (0);
12709 }
12710 
12711 /*
12712  * The theory behind creating the correct getsecattr return is simply this:
12713  * "Don't return anything that the caller is not expecting to have to free."
12714  */
12715 static int
12716 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12717     uid_t uid, gid_t gid, int isdir)
12718 {
12719 	int error = 0;
12720 	/* Save the mask since the translators modify it. */
12721 	uint_t	orig_mask = vsap->vsa_mask;
12722 
12723 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12724 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid, FALSE);
12725 
12726 		if (error)
12727 			return (error);
12728 
12729 		/*
12730 		 * If the caller only asked for the ace count (VSA_ACECNT)
12731 		 * don't give them the full acl (VSA_ACE), free it.
12732 		 */
12733 		if (!orig_mask & VSA_ACE) {
12734 			if (vsap->vsa_aclentp != NULL) {
12735 				kmem_free(vsap->vsa_aclentp,
12736 				    vsap->vsa_aclcnt * sizeof (ace_t));
12737 				vsap->vsa_aclentp = NULL;
12738 			}
12739 		}
12740 		vsap->vsa_mask = orig_mask;
12741 
12742 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12743 	    VSA_DFACLCNT)) {
12744 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12745 		    isdir, FALSE);
12746 
12747 		if (error)
12748 			return (error);
12749 
12750 		/*
12751 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12752 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12753 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12754 		 */
12755 		if (!orig_mask & VSA_ACL) {
12756 			if (vsap->vsa_aclentp != NULL) {
12757 				kmem_free(vsap->vsa_aclentp,
12758 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12759 				vsap->vsa_aclentp = NULL;
12760 			}
12761 		}
12762 
12763 		if (!orig_mask & VSA_DFACL) {
12764 			if (vsap->vsa_dfaclentp != NULL) {
12765 				kmem_free(vsap->vsa_dfaclentp,
12766 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12767 				vsap->vsa_dfaclentp = NULL;
12768 			}
12769 		}
12770 		vsap->vsa_mask = orig_mask;
12771 	}
12772 	return (0);
12773 }
12774 
12775 /* ARGSUSED */
12776 int
12777 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr,
12778     caller_context_t *ct)
12779 {
12780 	int error;
12781 
12782 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12783 		return (EIO);
12784 	/*
12785 	 * check for valid cmd parameter
12786 	 */
12787 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12788 		return (EINVAL);
12789 
12790 	/*
12791 	 * Check access permissions
12792 	 */
12793 	if ((cmd & F_SHARE) &&
12794 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12795 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12796 		return (EBADF);
12797 
12798 	/*
12799 	 * If the filesystem is mounted using local locking, pass the
12800 	 * request off to the local share code.
12801 	 */
12802 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12803 		return (fs_shrlock(vp, cmd, shr, flag, cr, ct));
12804 
12805 	switch (cmd) {
12806 	case F_SHARE:
12807 	case F_UNSHARE:
12808 		/*
12809 		 * This will be properly implemented later,
12810 		 * see RFE: 4823948 .
12811 		 */
12812 		error = EAGAIN;
12813 		break;
12814 
12815 	case F_HASREMOTELOCKS:
12816 		/*
12817 		 * NFS client can't store remote locks itself
12818 		 */
12819 		shr->s_access = 0;
12820 		error = 0;
12821 		break;
12822 
12823 	default:
12824 		error = EINVAL;
12825 		break;
12826 	}
12827 
12828 	return (error);
12829 }
12830 
12831 /*
12832  * Common code called by directory ops to update the attrcache
12833  */
12834 static int
12835 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12836     hrtime_t t, vnode_t *vp, cred_t *cr)
12837 {
12838 	int error = 0;
12839 
12840 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12841 
12842 	if (status != NFS4_OK) {
12843 		/* getattr not done or failed */
12844 		PURGE_ATTRCACHE4(vp);
12845 		return (error);
12846 	}
12847 
12848 	if (garp) {
12849 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12850 	} else {
12851 		PURGE_ATTRCACHE4(vp);
12852 	}
12853 	return (error);
12854 }
12855 
12856 /*
12857  * Update directory caches for directory modification ops (link, rename, etc.)
12858  * When dinfo is NULL, manage dircaches in the old way.
12859  */
12860 static void
12861 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12862     dirattr_info_t *dinfo)
12863 {
12864 	rnode4_t	*drp = VTOR4(dvp);
12865 
12866 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12867 
12868 	/* Purge rddir cache for dir since it changed */
12869 	if (drp->r_dir != NULL)
12870 		nfs4_purge_rddir_cache(dvp);
12871 
12872 	/*
12873 	 * If caller provided dinfo, then use it to manage dir caches.
12874 	 */
12875 	if (dinfo != NULL) {
12876 		if (vp != NULL) {
12877 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12878 			if (!VTOR4(vp)->created_v4) {
12879 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12880 				dnlc_update(dvp, nm, vp);
12881 			} else {
12882 				/*
12883 				 * XXX don't update if the created_v4 flag is
12884 				 * set
12885 				 */
12886 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12887 				NFS4_DEBUG(nfs4_client_state_debug,
12888 				    (CE_NOTE, "nfs4_update_dircaches: "
12889 				    "don't update dnlc: created_v4 flag"));
12890 			}
12891 		}
12892 
12893 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12894 		    dinfo->di_cred, FALSE, cinfo);
12895 
12896 		return;
12897 	}
12898 
12899 	/*
12900 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12901 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12902 	 * attrs, the dir's attrs must be purged.
12903 	 *
12904 	 * XXX this check and dnlc update/purge should really be atomic,
12905 	 * XXX but can't use rnode statelock because it'll deadlock in
12906 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12907 	 * XXX does occur.
12908 	 *
12909 	 * XXX We also may want to check that atomic is true in the
12910 	 * XXX change_info struct. If it is not, the change_info may
12911 	 * XXX reflect changes by more than one clients which means that
12912 	 * XXX our cache may not be valid.
12913 	 */
12914 	PURGE_ATTRCACHE4(dvp);
12915 	if (drp->r_change == cinfo->before) {
12916 		/* no changes took place in the directory prior to our link */
12917 		if (vp != NULL) {
12918 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12919 			if (!VTOR4(vp)->created_v4) {
12920 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12921 				dnlc_update(dvp, nm, vp);
12922 			} else {
12923 				/*
12924 				 * XXX dont' update if the created_v4 flag
12925 				 * is set
12926 				 */
12927 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12928 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12929 				    "nfs4_update_dircaches: don't"
12930 				    " update dnlc: created_v4 flag"));
12931 			}
12932 		}
12933 	} else {
12934 		/* Another client modified directory - purge its dnlc cache */
12935 		dnlc_purge_vp(dvp);
12936 	}
12937 }
12938 
12939 /*
12940  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12941  * file.
12942  *
12943  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12944  * file (ie: client recovery) and otherwise set to FALSE.
12945  *
12946  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12947  * initiated) calling functions.
12948  *
12949  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12950  * of resending a 'lost' open request.
12951  *
12952  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12953  * server that hands out BAD_SEQID on open confirm.
12954  *
12955  * Errors are returned via the nfs4_error_t parameter.
12956  */
12957 void
12958 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12959     bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12960     bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12961 {
12962 	COMPOUND4args_clnt args;
12963 	COMPOUND4res_clnt res;
12964 	nfs_argop4 argop[2];
12965 	nfs_resop4 *resop;
12966 	int doqueue = 1;
12967 	mntinfo4_t *mi;
12968 	OPEN_CONFIRM4args *open_confirm_args;
12969 	int needrecov;
12970 
12971 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12972 #if DEBUG
12973 	mutex_enter(&oop->oo_lock);
12974 	ASSERT(oop->oo_seqid_inuse);
12975 	mutex_exit(&oop->oo_lock);
12976 #endif
12977 
12978 recov_retry_confirm:
12979 	nfs4_error_zinit(ep);
12980 	*retry_open = FALSE;
12981 
12982 	if (resend)
12983 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12984 	else
12985 		args.ctag = TAG_OPEN_CONFIRM;
12986 
12987 	args.array_len = 2;
12988 	args.array = argop;
12989 
12990 	/* putfh target fh */
12991 	argop[0].argop = OP_CPUTFH;
12992 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12993 
12994 	argop[1].argop = OP_OPEN_CONFIRM;
12995 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12996 
12997 	(*seqid) += 1;
12998 	open_confirm_args->seqid = *seqid;
12999 	open_confirm_args->open_stateid = *stateid;
13000 
13001 	mi = VTOMI4(vp);
13002 
13003 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
13004 
13005 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
13006 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
13007 	}
13008 
13009 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
13010 	if (!needrecov && ep->error)
13011 		return;
13012 
13013 	if (needrecov) {
13014 		bool_t abort = FALSE;
13015 
13016 		if (reopening_file == FALSE) {
13017 			nfs4_bseqid_entry_t *bsep = NULL;
13018 
13019 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
13020 				bsep = nfs4_create_bseqid_entry(oop, NULL,
13021 				    vp, 0, args.ctag,
13022 				    open_confirm_args->seqid);
13023 
13024 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
13025 			    NULL, NULL, OP_OPEN_CONFIRM, bsep, NULL, NULL);
13026 			if (bsep) {
13027 				kmem_free(bsep, sizeof (*bsep));
13028 				if (num_bseqid_retryp &&
13029 				    --(*num_bseqid_retryp) == 0)
13030 					abort = TRUE;
13031 			}
13032 		}
13033 		if ((ep->error == ETIMEDOUT ||
13034 		    res.status == NFS4ERR_RESOURCE) &&
13035 		    abort == FALSE && resend == FALSE) {
13036 			if (!ep->error)
13037 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13038 				    (caddr_t)&res);
13039 
13040 			delay(SEC_TO_TICK(confirm_retry_sec));
13041 			goto recov_retry_confirm;
13042 		}
13043 		/* State may have changed so retry the entire OPEN op */
13044 		if (abort == FALSE)
13045 			*retry_open = TRUE;
13046 		else
13047 			*retry_open = FALSE;
13048 		if (!ep->error)
13049 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
13050 		return;
13051 	}
13052 
13053 	if (res.status) {
13054 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
13055 		return;
13056 	}
13057 
13058 	resop = &res.array[1];  /* open confirm res */
13059 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
13060 	    stateid, sizeof (*stateid));
13061 
13062 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
13063 }
13064 
13065 /*
13066  * Return the credentials associated with a client state object.  The
13067  * caller is responsible for freeing the credentials.
13068  */
13069 
13070 static cred_t *
13071 state_to_cred(nfs4_open_stream_t *osp)
13072 {
13073 	cred_t *cr;
13074 
13075 	/*
13076 	 * It's ok to not lock the open stream and open owner to get
13077 	 * the oo_cred since this is only written once (upon creation)
13078 	 * and will not change.
13079 	 */
13080 	cr = osp->os_open_owner->oo_cred;
13081 	crhold(cr);
13082 
13083 	return (cr);
13084 }
13085 
13086 /*
13087  * nfs4_find_sysid
13088  *
13089  * Find the sysid for the knetconfig associated with the given mi.
13090  */
13091 static struct lm_sysid *
13092 nfs4_find_sysid(mntinfo4_t *mi)
13093 {
13094 	ASSERT(nfs_zone() == mi->mi_zone);
13095 
13096 	/*
13097 	 * Switch from RDMA knconf to original mount knconf
13098 	 */
13099 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
13100 	    mi->mi_curr_serv->sv_hostname, NULL));
13101 }
13102 
13103 #ifdef DEBUG
13104 /*
13105  * Return a string version of the call type for easy reading.
13106  */
13107 static char *
13108 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
13109 {
13110 	switch (ctype) {
13111 	case NFS4_LCK_CTYPE_NORM:
13112 		return ("NORMAL");
13113 	case NFS4_LCK_CTYPE_RECLAIM:
13114 		return ("RECLAIM");
13115 	case NFS4_LCK_CTYPE_RESEND:
13116 		return ("RESEND");
13117 	case NFS4_LCK_CTYPE_REINSTATE:
13118 		return ("REINSTATE");
13119 	default:
13120 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
13121 		    "type %d", ctype);
13122 		return ("");
13123 	}
13124 }
13125 #endif
13126 
13127 /*
13128  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
13129  * Unlock requests don't have an over-the-wire locktype, so we just return
13130  * something non-threatening.
13131  */
13132 
13133 static nfs_lock_type4
13134 flk_to_locktype(int cmd, int l_type)
13135 {
13136 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
13137 
13138 	switch (l_type) {
13139 	case F_UNLCK:
13140 		return (READ_LT);
13141 	case F_RDLCK:
13142 		if (cmd == F_SETLK)
13143 			return (READ_LT);
13144 		else
13145 			return (READW_LT);
13146 	case F_WRLCK:
13147 		if (cmd == F_SETLK)
13148 			return (WRITE_LT);
13149 		else
13150 			return (WRITEW_LT);
13151 	}
13152 	panic("flk_to_locktype");
13153 	/*NOTREACHED*/
13154 }
13155 
13156 /*
13157  * Set the flock64's lm_sysid for nfs4frlock.
13158  */
13159 static int
13160 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
13161 {
13162 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13163 
13164 	/* Find the lm_sysid */
13165 	*lspp = nfs4_find_sysid(VTOMI4(vp));
13166 
13167 	if (*lspp == NULL) {
13168 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13169 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
13170 		return (ENOLCK);
13171 	}
13172 
13173 	flk->l_sysid = lm_sysidt(*lspp);
13174 
13175 	return (0);
13176 }
13177 
13178 /*
13179  * Do the remaining preliminary setup for nfs4frlock.
13180  */
13181 static void
13182 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
13183     vnode_t *vp, cred_t *search_cr, cred_t **cred_otw)
13184 {
13185 	/*
13186 	 * set tick_delay to the base delay time.
13187 	 * (nfs4_base_wait_time is in msecs)
13188 	 */
13189 
13190 	*tick_delayp = drv_usectohz(nfs4_base_wait_time * 1000);
13191 
13192 	recov_statep->rs_flags = 0;
13193 	recov_statep->rs_num_retry_despite_err = 0;
13194 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
13195 }
13196 
13197 /*
13198  * Initialize and allocate the data structures necessary for
13199  * the nfs4frlock call.
13200  * Allocates argsp's op array, frees up the saved_rqstpp if there is one.
13201  */
13202 static void
13203 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
13204     nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
13205     bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
13206     bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
13207 {
13208 	int		argoplist_size;
13209 	int		num_ops = 2;
13210 
13211 	*retry = FALSE;
13212 	*did_start_fop = FALSE;
13213 	*skip_get_err = FALSE;
13214 	lost_rqstp->lr_op = 0;
13215 	argoplist_size  = num_ops * sizeof (nfs_argop4);
13216 	/* fill array with zero */
13217 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
13218 
13219 	*argspp = argsp;
13220 	*respp = NULL;
13221 
13222 	argsp->array_len = num_ops;
13223 	argsp->array = *argopp;
13224 
13225 	/* initialize in case of error; will get real value down below */
13226 	argsp->ctag = TAG_NONE;
13227 
13228 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
13229 		*op_hintp = OH_LOCKU;
13230 	else
13231 		*op_hintp = OH_OTHER;
13232 }
13233 
13234 /*
13235  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
13236  * the proper nfs4_server_t for this instance of nfs4frlock.
13237  * Returns 0 (success) or an errno value.
13238  */
13239 static int
13240 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
13241     nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
13242     bool_t *did_start_fop, bool_t *startrecovp)
13243 {
13244 	int error = 0;
13245 	rnode4_t *rp;
13246 
13247 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13248 
13249 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13250 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
13251 		    recov_statep, startrecovp);
13252 		if (error)
13253 			return (error);
13254 		*did_start_fop = TRUE;
13255 	} else {
13256 		*did_start_fop = FALSE;
13257 		*startrecovp = FALSE;
13258 	}
13259 
13260 	if (!error) {
13261 		rp = VTOR4(vp);
13262 
13263 		/* If the file failed recovery, just quit. */
13264 		mutex_enter(&rp->r_statelock);
13265 		if (rp->r_flags & R4RECOVERR) {
13266 			error = EIO;
13267 		}
13268 		mutex_exit(&rp->r_statelock);
13269 	}
13270 
13271 	return (error);
13272 }
13273 
13274 /*
13275  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
13276  * resend nfs4frlock call is initiated by the recovery framework.
13277  * Acquires the lop and oop seqid synchronization.
13278  */
13279 static void
13280 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
13281     COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
13282     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13283     LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
13284 {
13285 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
13286 	int error;
13287 
13288 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
13289 	    (CE_NOTE,
13290 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
13291 	ASSERT(resend_rqstp != NULL);
13292 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
13293 	    resend_rqstp->lr_op == OP_LOCKU);
13294 
13295 	*oopp = resend_rqstp->lr_oop;
13296 	if (resend_rqstp->lr_oop) {
13297 		open_owner_hold(resend_rqstp->lr_oop);
13298 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
13299 		ASSERT(error == 0);	/* recov thread always succeeds */
13300 	}
13301 
13302 	/* Must resend this lost lock/locku request. */
13303 	ASSERT(resend_rqstp->lr_lop != NULL);
13304 	*lopp = resend_rqstp->lr_lop;
13305 	lock_owner_hold(resend_rqstp->lr_lop);
13306 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
13307 	ASSERT(error == 0);	/* recov thread always succeeds */
13308 
13309 	*ospp = resend_rqstp->lr_osp;
13310 	if (*ospp)
13311 		open_stream_hold(resend_rqstp->lr_osp);
13312 
13313 	if (resend_rqstp->lr_op == OP_LOCK) {
13314 		LOCK4args *lock_args;
13315 
13316 		argop->argop = OP_LOCK;
13317 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
13318 		lock_args->locktype = resend_rqstp->lr_locktype;
13319 		lock_args->reclaim =
13320 		    (resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
13321 		lock_args->offset = resend_rqstp->lr_flk->l_start;
13322 		lock_args->length = resend_rqstp->lr_flk->l_len;
13323 		if (lock_args->length == 0)
13324 			lock_args->length = ~lock_args->length;
13325 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
13326 		    mi2clientid(mi), &lock_args->locker);
13327 
13328 		switch (resend_rqstp->lr_ctype) {
13329 		case NFS4_LCK_CTYPE_RESEND:
13330 			argsp->ctag = TAG_LOCK_RESEND;
13331 			break;
13332 		case NFS4_LCK_CTYPE_REINSTATE:
13333 			argsp->ctag = TAG_LOCK_REINSTATE;
13334 			break;
13335 		case NFS4_LCK_CTYPE_RECLAIM:
13336 			argsp->ctag = TAG_LOCK_RECLAIM;
13337 			break;
13338 		default:
13339 			argsp->ctag = TAG_LOCK_UNKNOWN;
13340 			break;
13341 		}
13342 	} else {
13343 		LOCKU4args *locku_args;
13344 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
13345 
13346 		argop->argop = OP_LOCKU;
13347 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
13348 		locku_args->locktype = READ_LT;
13349 		locku_args->seqid = lop->lock_seqid + 1;
13350 		mutex_enter(&lop->lo_lock);
13351 		locku_args->lock_stateid = lop->lock_stateid;
13352 		mutex_exit(&lop->lo_lock);
13353 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13354 		locku_args->length = resend_rqstp->lr_flk->l_len;
13355 		if (locku_args->length == 0)
13356 			locku_args->length = ~locku_args->length;
13357 
13358 		switch (resend_rqstp->lr_ctype) {
13359 		case NFS4_LCK_CTYPE_RESEND:
13360 			argsp->ctag = TAG_LOCKU_RESEND;
13361 			break;
13362 		case NFS4_LCK_CTYPE_REINSTATE:
13363 			argsp->ctag = TAG_LOCKU_REINSTATE;
13364 			break;
13365 		default:
13366 			argsp->ctag = TAG_LOCK_UNKNOWN;
13367 			break;
13368 		}
13369 	}
13370 }
13371 
13372 /*
13373  * Setup the LOCKT4 arguments.
13374  */
13375 static void
13376 nfs4frlock_setup_lockt_args(nfs_argop4 *argop, LOCKT4args **lockt_argsp,
13377     COMPOUND4args_clnt *argsp, flock64_t *flk, rnode4_t *rp)
13378 {
13379 	LOCKT4args *lockt_args;
13380 
13381 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13382 	argop->argop = OP_LOCKT;
13383 	argsp->ctag = TAG_LOCKT;
13384 	lockt_args = &argop->nfs_argop4_u.oplockt;
13385 
13386 	/*
13387 	 * The locktype will be READ_LT unless it's
13388 	 * a write lock. We do this because the Solaris
13389 	 * system call allows the combination of
13390 	 * F_UNLCK and F_GETLK* and so in that case the
13391 	 * unlock is mapped to a read.
13392 	 */
13393 	if (flk->l_type == F_WRLCK)
13394 		lockt_args->locktype = WRITE_LT;
13395 	else
13396 		lockt_args->locktype = READ_LT;
13397 
13398 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13399 	/* set the lock owner4 args */
13400 	nfs4_setlockowner_args(&lockt_args->owner, rp, flk->l_pid);
13401 	lockt_args->offset = flk->l_start;
13402 	lockt_args->length = flk->l_len;
13403 	if (flk->l_len == 0)
13404 		lockt_args->length = ~lockt_args->length;
13405 
13406 	*lockt_argsp = lockt_args;
13407 }
13408 
13409 /*
13410  * If the client is holding a delegation, and the open stream to be used
13411  * with this lock request is a delegation open stream, then re-open the stream.
13412  * Sets the nfs4_error_t to all zeros unless the open stream has already
13413  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13414  * means the caller should retry (like a recovery retry).
13415  */
13416 static void
13417 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13418 {
13419 	open_delegation_type4	dt;
13420 	bool_t			reopen_needed, force;
13421 	nfs4_open_stream_t	*osp;
13422 	open_claim_type4	oclaim;
13423 	rnode4_t		*rp = VTOR4(vp);
13424 	mntinfo4_t		*mi = VTOMI4(vp);
13425 
13426 	ASSERT(nfs_zone() == mi->mi_zone);
13427 
13428 	nfs4_error_zinit(ep);
13429 
13430 	mutex_enter(&rp->r_statev4_lock);
13431 	dt = rp->r_deleg_type;
13432 	mutex_exit(&rp->r_statev4_lock);
13433 
13434 	if (dt != OPEN_DELEGATE_NONE) {
13435 		nfs4_open_owner_t	*oop;
13436 
13437 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13438 		if (!oop) {
13439 			ep->stat = NFS4ERR_IO;
13440 			return;
13441 		}
13442 		/* returns with 'os_sync_lock' held */
13443 		osp = find_open_stream(oop, rp);
13444 		if (!osp) {
13445 			open_owner_rele(oop);
13446 			ep->stat = NFS4ERR_IO;
13447 			return;
13448 		}
13449 
13450 		if (osp->os_failed_reopen) {
13451 			NFS4_DEBUG((nfs4_open_stream_debug ||
13452 			    nfs4_client_lock_debug), (CE_NOTE,
13453 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13454 			    "for osp %p, cr %p, rp %s", (void *)osp,
13455 			    (void *)cr, rnode4info(rp)));
13456 			mutex_exit(&osp->os_sync_lock);
13457 			open_stream_rele(osp, rp);
13458 			open_owner_rele(oop);
13459 			ep->stat = NFS4ERR_IO;
13460 			return;
13461 		}
13462 
13463 		/*
13464 		 * Determine whether a reopen is needed.  If this
13465 		 * is a delegation open stream, then send the open
13466 		 * to the server to give visibility to the open owner.
13467 		 * Even if it isn't a delegation open stream, we need
13468 		 * to check if the previous open CLAIM_DELEGATE_CUR
13469 		 * was sufficient.
13470 		 */
13471 
13472 		reopen_needed = osp->os_delegation ||
13473 		    ((lt == F_RDLCK &&
13474 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13475 		    (lt == F_WRLCK &&
13476 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13477 
13478 		mutex_exit(&osp->os_sync_lock);
13479 		open_owner_rele(oop);
13480 
13481 		if (reopen_needed) {
13482 			/*
13483 			 * Always use CLAIM_PREVIOUS after server reboot.
13484 			 * The server will reject CLAIM_DELEGATE_CUR if
13485 			 * it is used during the grace period.
13486 			 */
13487 			mutex_enter(&mi->mi_lock);
13488 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13489 				oclaim = CLAIM_PREVIOUS;
13490 				force = TRUE;
13491 			} else {
13492 				oclaim = CLAIM_DELEGATE_CUR;
13493 				force = FALSE;
13494 			}
13495 			mutex_exit(&mi->mi_lock);
13496 
13497 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13498 			if (ep->error == EAGAIN) {
13499 				nfs4_error_zinit(ep);
13500 				ep->stat = NFS4ERR_DELAY;
13501 			}
13502 		}
13503 		open_stream_rele(osp, rp);
13504 		osp = NULL;
13505 	}
13506 }
13507 
13508 /*
13509  * Setup the LOCKU4 arguments.
13510  * Returns errors via the nfs4_error_t.
13511  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13512  *			over-the-wire.  The caller must release the
13513  *			reference on *lopp.
13514  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13515  * (other)		unrecoverable error.
13516  */
13517 static void
13518 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13519     LOCKU4args **locku_argsp, flock64_t *flk,
13520     nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13521     vnode_t *vp, cred_t *cr, bool_t *skip_get_err, bool_t *go_otwp)
13522 {
13523 	nfs4_lock_owner_t	*lop = NULL;
13524 	LOCKU4args		*locku_args;
13525 	pid_t			pid = flk->l_pid;
13526 	bool_t			is_spec = FALSE;
13527 	rnode4_t		*rp = VTOR4(vp);
13528 
13529 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13530 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13531 
13532 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13533 	if (ep->error || ep->stat)
13534 		return;
13535 
13536 	argop->argop = OP_LOCKU;
13537 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13538 		argsp->ctag = TAG_LOCKU_REINSTATE;
13539 	else
13540 		argsp->ctag = TAG_LOCKU;
13541 	locku_args = &argop->nfs_argop4_u.oplocku;
13542 	*locku_argsp = locku_args;
13543 
13544 	/*
13545 	 * XXX what should locku_args->locktype be?
13546 	 * setting to ALWAYS be READ_LT so at least
13547 	 * it is a valid locktype.
13548 	 */
13549 
13550 	locku_args->locktype = READ_LT;
13551 
13552 	/*
13553 	 * Get the lock owner stateid.  If no lock owner
13554 	 * exists, return success.
13555 	 */
13556 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13557 	*lopp = lop;
13558 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13559 		is_spec = TRUE;
13560 	if (!lop || is_spec) {
13561 		/*
13562 		 * No lock owner so no locks to unlock.
13563 		 * Return success.
13564 		 *
13565 		 * If the lockowner is using a special stateid,
13566 		 * then the original lock request (that created
13567 		 * this lockowner) was never successful, so we
13568 		 * have no lock to undo OTW.
13569 		 */
13570 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13571 		    "nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13572 		    "(%ld) so return success", (long)pid));
13573 
13574 		/*
13575 		 * Release our hold and NULL out so final_cleanup
13576 		 * doesn't try to end a lock seqid sync we
13577 		 * never started.
13578 		 */
13579 		if (is_spec) {
13580 			lock_owner_rele(lop);
13581 			*lopp = NULL;
13582 		}
13583 		*skip_get_err = TRUE;
13584 		*go_otwp = FALSE;
13585 		return;
13586 	}
13587 
13588 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13589 	if (ep->error == EAGAIN) {
13590 		lock_owner_rele(lop);
13591 		*lopp = NULL;
13592 		return;
13593 	}
13594 
13595 	mutex_enter(&lop->lo_lock);
13596 	locku_args->lock_stateid = lop->lock_stateid;
13597 	mutex_exit(&lop->lo_lock);
13598 	locku_args->seqid = lop->lock_seqid + 1;
13599 
13600 	/* leave the ref count on lop, rele after RPC call */
13601 
13602 	locku_args->offset = flk->l_start;
13603 	locku_args->length = flk->l_len;
13604 	if (flk->l_len == 0)
13605 		locku_args->length = ~locku_args->length;
13606 
13607 	*go_otwp = TRUE;
13608 }
13609 
13610 /*
13611  * Setup the LOCK4 arguments.
13612  *
13613  * Returns errors via the nfs4_error_t.
13614  * NFS4_OK		no problems
13615  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13616  * (other)		unrecoverable error
13617  */
13618 static void
13619 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13620     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13621     nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13622     flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13623 {
13624 	LOCK4args		*lock_args;
13625 	nfs4_open_owner_t	*oop = NULL;
13626 	nfs4_open_stream_t	*osp = NULL;
13627 	nfs4_lock_owner_t	*lop = NULL;
13628 	pid_t			pid = flk->l_pid;
13629 	rnode4_t		*rp = VTOR4(vp);
13630 
13631 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13632 
13633 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13634 	if (ep->error || ep->stat != NFS4_OK)
13635 		return;
13636 
13637 	argop->argop = OP_LOCK;
13638 	if (ctype == NFS4_LCK_CTYPE_NORM)
13639 		argsp->ctag = TAG_LOCK;
13640 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13641 		argsp->ctag = TAG_RELOCK;
13642 	else
13643 		argsp->ctag = TAG_LOCK_REINSTATE;
13644 	lock_args = &argop->nfs_argop4_u.oplock;
13645 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13646 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13647 	/*
13648 	 * Get the lock owner.  If no lock owner exists,
13649 	 * create a 'temporary' one and grab the open seqid
13650 	 * synchronization (which puts a hold on the open
13651 	 * owner and open stream).
13652 	 * This also grabs the lock seqid synchronization.
13653 	 */
13654 	ep->stat =
13655 	    nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13656 
13657 	if (ep->stat != NFS4_OK)
13658 		goto out;
13659 
13660 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13661 	    &lock_args->locker);
13662 
13663 	lock_args->offset = flk->l_start;
13664 	lock_args->length = flk->l_len;
13665 	if (flk->l_len == 0)
13666 		lock_args->length = ~lock_args->length;
13667 	*lock_argsp = lock_args;
13668 out:
13669 	*oopp = oop;
13670 	*ospp = osp;
13671 	*lopp = lop;
13672 }
13673 
13674 /*
13675  * After we get the reply from the server, record the proper information
13676  * for possible resend lock requests.
13677  *
13678  * Allocates memory for the saved_rqstp if we have a lost lock to save.
13679  */
13680 static void
13681 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13682     nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13683     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13684     nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13685 {
13686 	bool_t unlock = (flk->l_type == F_UNLCK);
13687 
13688 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13689 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13690 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13691 
13692 	if (error != 0 && !unlock) {
13693 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13694 		    nfs4_client_lock_debug), (CE_NOTE,
13695 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13696 		    " for lop %p", (void *)lop));
13697 		ASSERT(lop != NULL);
13698 		mutex_enter(&lop->lo_lock);
13699 		lop->lo_pending_rqsts = 1;
13700 		mutex_exit(&lop->lo_lock);
13701 	}
13702 
13703 	lost_rqstp->lr_putfirst = FALSE;
13704 	lost_rqstp->lr_op = 0;
13705 
13706 	/*
13707 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13708 	 * recovery purposes so that the lock request that was sent
13709 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13710 	 * unmount.  This is done to have the client's local locking state
13711 	 * match the v4 server's state; that is, the request was
13712 	 * potentially received and accepted by the server but the client
13713 	 * thinks it was not.
13714 	 */
13715 	if (error == ETIMEDOUT || error == EINTR ||
13716 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13717 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13718 		    nfs4_client_lock_debug), (CE_NOTE,
13719 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13720 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13721 		    (void *)lop, (void *)oop, (void *)osp));
13722 		if (unlock)
13723 			lost_rqstp->lr_op = OP_LOCKU;
13724 		else {
13725 			lost_rqstp->lr_op = OP_LOCK;
13726 			lost_rqstp->lr_locktype = locktype;
13727 		}
13728 		/*
13729 		 * Objects are held and rele'd via the recovery code.
13730 		 * See nfs4_save_lost_rqst.
13731 		 */
13732 		lost_rqstp->lr_vp = vp;
13733 		lost_rqstp->lr_dvp = NULL;
13734 		lost_rqstp->lr_oop = oop;
13735 		lost_rqstp->lr_osp = osp;
13736 		lost_rqstp->lr_lop = lop;
13737 		lost_rqstp->lr_cr = cr;
13738 		switch (ctype) {
13739 		case NFS4_LCK_CTYPE_NORM:
13740 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13741 			break;
13742 		case NFS4_LCK_CTYPE_REINSTATE:
13743 			lost_rqstp->lr_putfirst = TRUE;
13744 			lost_rqstp->lr_ctype = ctype;
13745 			break;
13746 		default:
13747 			break;
13748 		}
13749 		lost_rqstp->lr_flk = flk;
13750 	}
13751 }
13752 
13753 /*
13754  * Update lop's seqid.  Also update the seqid stored in a resend request,
13755  * if any.  (Some recovery errors increment the seqid, and we may have to
13756  * send the resend request again.)
13757  */
13758 
13759 static void
13760 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13761     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13762 {
13763 	if (lock_args) {
13764 		if (lock_args->locker.new_lock_owner == TRUE)
13765 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13766 		else {
13767 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13768 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13769 		}
13770 	} else if (locku_args) {
13771 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13772 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13773 	}
13774 }
13775 
13776 /*
13777  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13778  * COMPOUND4 args/res for calls that need to retry.
13779  * Switches the *cred_otwp to base_cr.
13780  */
13781 static void
13782 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13783     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13784     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13785     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13786     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13787 {
13788 	nfs4_open_owner_t	*oop = *oopp;
13789 	nfs4_open_stream_t	*osp = *ospp;
13790 	nfs4_lock_owner_t	*lop = *lopp;
13791 	nfs_argop4		*argop = (*argspp)->array;
13792 
13793 	if (*did_start_fop) {
13794 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13795 		    needrecov);
13796 		*did_start_fop = FALSE;
13797 	}
13798 	ASSERT((*argspp)->array_len == 2);
13799 	if (argop[1].argop == OP_LOCK)
13800 		nfs4args_lock_free(&argop[1]);
13801 	else if (argop[1].argop == OP_LOCKT)
13802 		nfs4args_lockt_free(&argop[1]);
13803 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13804 	if (!error)
13805 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13806 	*argspp = NULL;
13807 	*respp = NULL;
13808 
13809 	if (lop) {
13810 		nfs4_end_lock_seqid_sync(lop);
13811 		lock_owner_rele(lop);
13812 		*lopp = NULL;
13813 	}
13814 
13815 	/* need to free up the reference on osp for lock args */
13816 	if (osp != NULL) {
13817 		open_stream_rele(osp, VTOR4(vp));
13818 		*ospp = NULL;
13819 	}
13820 
13821 	/* need to free up the reference on oop for lock args */
13822 	if (oop != NULL) {
13823 		nfs4_end_open_seqid_sync(oop);
13824 		open_owner_rele(oop);
13825 		*oopp = NULL;
13826 	}
13827 
13828 	crfree(*cred_otwp);
13829 	*cred_otwp = base_cr;
13830 	crhold(*cred_otwp);
13831 }
13832 
13833 /*
13834  * Function to process the client's recovery for nfs4frlock.
13835  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13836  *
13837  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13838  * COMPOUND4 args/res for calls that need to retry.
13839  *
13840  * Note: the rp's r_lkserlock is *not* dropped during this path.
13841  */
13842 static bool_t
13843 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13844     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13845     LOCK4args *lock_args, LOCKU4args *locku_args,
13846     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13847     nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13848     nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13849     bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13850 {
13851 	nfs4_open_owner_t	*oop = *oopp;
13852 	nfs4_open_stream_t	*osp = *ospp;
13853 	nfs4_lock_owner_t	*lop = *lopp;
13854 
13855 	bool_t abort, retry;
13856 
13857 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13858 	ASSERT((*argspp) != NULL);
13859 	ASSERT((*respp) != NULL);
13860 	if (lock_args || locku_args)
13861 		ASSERT(lop != NULL);
13862 
13863 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13864 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13865 
13866 	retry = TRUE;
13867 	abort = FALSE;
13868 	if (needrecov) {
13869 		nfs4_bseqid_entry_t *bsep = NULL;
13870 		nfs_opnum4 op;
13871 
13872 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13873 
13874 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13875 			seqid4 seqid;
13876 
13877 			if (lock_args) {
13878 				if (lock_args->locker.new_lock_owner == TRUE)
13879 					seqid = lock_args->locker.locker4_u.
13880 					    open_owner.open_seqid;
13881 				else
13882 					seqid = lock_args->locker.locker4_u.
13883 					    lock_owner.lock_seqid;
13884 			} else if (locku_args) {
13885 				seqid = locku_args->seqid;
13886 			} else {
13887 				seqid = 0;
13888 			}
13889 
13890 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13891 			    flk->l_pid, (*argspp)->ctag, seqid);
13892 		}
13893 
13894 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13895 		    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13896 		    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13897 		    NULL, op, bsep, NULL, NULL);
13898 
13899 		if (bsep)
13900 			kmem_free(bsep, sizeof (*bsep));
13901 	}
13902 
13903 	/*
13904 	 * Return that we do not want to retry the request for 3 cases:
13905 	 * 1. If we received EINTR or are bailing out because of a forced
13906 	 *    unmount, we came into this code path just for the sake of
13907 	 *    initiating recovery, we now need to return the error.
13908 	 * 2. If we have aborted recovery.
13909 	 * 3. We received NFS4ERR_BAD_SEQID.
13910 	 */
13911 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13912 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13913 		retry = FALSE;
13914 
13915 	if (*did_start_fop == TRUE) {
13916 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13917 		    needrecov);
13918 		*did_start_fop = FALSE;
13919 	}
13920 
13921 	if (retry == TRUE) {
13922 		nfs_argop4	*argop;
13923 
13924 		argop = (*argspp)->array;
13925 		ASSERT((*argspp)->array_len == 2);
13926 
13927 		if (argop[1].argop == OP_LOCK)
13928 			nfs4args_lock_free(&argop[1]);
13929 		else if (argop[1].argop == OP_LOCKT)
13930 			nfs4args_lockt_free(&argop[1]);
13931 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13932 		if (!ep->error)
13933 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13934 		*respp = NULL;
13935 		*argspp = NULL;
13936 	}
13937 
13938 	if (lop != NULL) {
13939 		nfs4_end_lock_seqid_sync(lop);
13940 		lock_owner_rele(lop);
13941 	}
13942 
13943 	*lopp = NULL;
13944 
13945 	/* need to free up the reference on osp for lock args */
13946 	if (osp != NULL) {
13947 		open_stream_rele(osp, rp);
13948 		*ospp = NULL;
13949 	}
13950 
13951 	/* need to free up the reference on oop for lock args */
13952 	if (oop != NULL) {
13953 		nfs4_end_open_seqid_sync(oop);
13954 		open_owner_rele(oop);
13955 		*oopp = NULL;
13956 	}
13957 
13958 	return (retry);
13959 }
13960 
13961 /*
13962  * Handle the DENIED reply from the server for nfs4frlock.
13963  * Returns TRUE if we should retry the request; FALSE otherwise.
13964  *
13965  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13966  * COMPOUND4 args/res for calls that need to retry.  Can also
13967  * drop and regrab the r_lkserlock.
13968  */
13969 static bool_t
13970 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13971     LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13972     nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13973     vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13974     nfs4_recov_state_t *recov_statep, int needrecov,
13975     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13976     clock_t *tick_delayp, int *errorp,
13977     nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13978     bool_t *skip_get_err)
13979 {
13980 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13981 
13982 	if (lock_args) {
13983 		nfs4_open_owner_t	*oop = *oopp;
13984 		nfs4_open_stream_t	*osp = *ospp;
13985 		nfs4_lock_owner_t	*lop = *lopp;
13986 		int			intr;
13987 
13988 		/*
13989 		 * Blocking lock needs to sleep and retry from the request.
13990 		 *
13991 		 * Do not block and wait for 'resend' or 'reinstate'
13992 		 * lock requests, just return the error.
13993 		 *
13994 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13995 		 */
13996 		if (cmd == F_SETLKW) {
13997 			rnode4_t *rp = VTOR4(vp);
13998 			nfs_argop4 *argop = (*argspp)->array;
13999 
14000 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14001 
14002 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14003 			    recov_statep, needrecov);
14004 			*did_start_fop = FALSE;
14005 			ASSERT((*argspp)->array_len == 2);
14006 			if (argop[1].argop == OP_LOCK)
14007 				nfs4args_lock_free(&argop[1]);
14008 			else if (argop[1].argop == OP_LOCKT)
14009 				nfs4args_lockt_free(&argop[1]);
14010 			kmem_free(argop, 2 * sizeof (nfs_argop4));
14011 			if (*respp)
14012 				(void) xdr_free(xdr_COMPOUND4res_clnt,
14013 				    (caddr_t)*respp);
14014 			*argspp = NULL;
14015 			*respp = NULL;
14016 			nfs4_end_lock_seqid_sync(lop);
14017 			lock_owner_rele(lop);
14018 			*lopp = NULL;
14019 			if (osp != NULL) {
14020 				open_stream_rele(osp, rp);
14021 				*ospp = NULL;
14022 			}
14023 			if (oop != NULL) {
14024 				nfs4_end_open_seqid_sync(oop);
14025 				open_owner_rele(oop);
14026 				*oopp = NULL;
14027 			}
14028 
14029 			nfs_rw_exit(&rp->r_lkserlock);
14030 
14031 			intr = nfs4_block_and_wait(tick_delayp);
14032 
14033 			(void) nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER,
14034 			    FALSE);
14035 
14036 			if (intr) {
14037 				*errorp = EINTR;
14038 				return (FALSE);
14039 			}
14040 
14041 			/*
14042 			 * Make sure we are still safe to lock with
14043 			 * regards to mmapping.
14044 			 */
14045 			if (!nfs4_safelock(vp, flk, cr)) {
14046 				*errorp = EAGAIN;
14047 				return (FALSE);
14048 			}
14049 
14050 			return (TRUE);
14051 		}
14052 		if (ctype == NFS4_LCK_CTYPE_NORM)
14053 			*errorp = EAGAIN;
14054 		*skip_get_err = TRUE;
14055 		flk->l_whence = 0;
14056 		return (FALSE);
14057 	} else if (lockt_args) {
14058 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14059 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
14060 
14061 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
14062 		    flk, lockt_args);
14063 
14064 		/* according to NLM code */
14065 		*errorp = 0;
14066 		*skip_get_err = TRUE;
14067 		return (FALSE);
14068 	}
14069 	return (FALSE);
14070 }
14071 
14072 /*
14073  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
14074  */
14075 static void
14076 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
14077 {
14078 	switch (resp->status) {
14079 	case NFS4ERR_ACCESS:
14080 	case NFS4ERR_ADMIN_REVOKED:
14081 	case NFS4ERR_BADHANDLE:
14082 	case NFS4ERR_BAD_RANGE:
14083 	case NFS4ERR_BAD_SEQID:
14084 	case NFS4ERR_BAD_STATEID:
14085 	case NFS4ERR_BADXDR:
14086 	case NFS4ERR_DEADLOCK:
14087 	case NFS4ERR_DELAY:
14088 	case NFS4ERR_EXPIRED:
14089 	case NFS4ERR_FHEXPIRED:
14090 	case NFS4ERR_GRACE:
14091 	case NFS4ERR_INVAL:
14092 	case NFS4ERR_ISDIR:
14093 	case NFS4ERR_LEASE_MOVED:
14094 	case NFS4ERR_LOCK_NOTSUPP:
14095 	case NFS4ERR_LOCK_RANGE:
14096 	case NFS4ERR_MOVED:
14097 	case NFS4ERR_NOFILEHANDLE:
14098 	case NFS4ERR_NO_GRACE:
14099 	case NFS4ERR_OLD_STATEID:
14100 	case NFS4ERR_OPENMODE:
14101 	case NFS4ERR_RECLAIM_BAD:
14102 	case NFS4ERR_RECLAIM_CONFLICT:
14103 	case NFS4ERR_RESOURCE:
14104 	case NFS4ERR_SERVERFAULT:
14105 	case NFS4ERR_STALE:
14106 	case NFS4ERR_STALE_CLIENTID:
14107 	case NFS4ERR_STALE_STATEID:
14108 		return;
14109 	default:
14110 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14111 		    "nfs4frlock_results_default: got unrecognizable "
14112 		    "res.status %d", resp->status));
14113 		*errorp = NFS4ERR_INVAL;
14114 	}
14115 }
14116 
14117 /*
14118  * The lock request was successful, so update the client's state.
14119  */
14120 static void
14121 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
14122     LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
14123     vnode_t *vp, flock64_t *flk, cred_t *cr,
14124     nfs4_lost_rqst_t *resend_rqstp)
14125 {
14126 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14127 
14128 	if (lock_args) {
14129 		LOCK4res *lock_res;
14130 
14131 		lock_res = &resop->nfs_resop4_u.oplock;
14132 		/* update the stateid with server's response */
14133 
14134 		if (lock_args->locker.new_lock_owner == TRUE) {
14135 			mutex_enter(&lop->lo_lock);
14136 			lop->lo_just_created = NFS4_PERM_CREATED;
14137 			mutex_exit(&lop->lo_lock);
14138 		}
14139 
14140 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
14141 
14142 		/*
14143 		 * If the lock was the result of a resending a lost
14144 		 * request, we've synched up the stateid and seqid
14145 		 * with the server, but now the server might be out of sync
14146 		 * with what the application thinks it has for locks.
14147 		 * Clean that up here.  It's unclear whether we should do
14148 		 * this even if the filesystem has been forcibly unmounted.
14149 		 * For most servers, it's probably wasted effort, but
14150 		 * RFC3530 lets servers require that unlocks exactly match
14151 		 * the locks that are held.
14152 		 */
14153 		if (resend_rqstp != NULL &&
14154 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
14155 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
14156 		} else {
14157 			flk->l_whence = 0;
14158 		}
14159 	} else if (locku_args) {
14160 		LOCKU4res *locku_res;
14161 
14162 		locku_res = &resop->nfs_resop4_u.oplocku;
14163 
14164 		/* Update the stateid with the server's response */
14165 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
14166 	} else if (lockt_args) {
14167 		/* Switch the lock type to express success, see fcntl */
14168 		flk->l_type = F_UNLCK;
14169 		flk->l_whence = 0;
14170 	}
14171 }
14172 
14173 /*
14174  * Do final cleanup before exiting nfs4frlock.
14175  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
14176  * COMPOUND4 args/res for calls that haven't already.
14177  */
14178 static void
14179 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
14180     COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
14181     nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
14182     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop,
14183     int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
14184     bool_t did_start_fop, bool_t skip_get_err,
14185     cred_t *cred_otw, cred_t *cred)
14186 {
14187 	mntinfo4_t	*mi = VTOMI4(vp);
14188 	rnode4_t	*rp = VTOR4(vp);
14189 	int		error = *errorp;
14190 	nfs_argop4	*argop;
14191 	int	do_flush_pages = 0;
14192 
14193 	ASSERT(nfs_zone() == mi->mi_zone);
14194 	/*
14195 	 * The client recovery code wants the raw status information,
14196 	 * so don't map the NFS status code to an errno value for
14197 	 * non-normal call types.
14198 	 */
14199 	if (ctype == NFS4_LCK_CTYPE_NORM) {
14200 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
14201 			*errorp = geterrno4(resp->status);
14202 		if (did_start_fop == TRUE)
14203 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
14204 			    needrecov);
14205 
14206 		/*
14207 		 * We've established a new lock on the server, so invalidate
14208 		 * the pages associated with the vnode to get the most up to
14209 		 * date pages from the server after acquiring the lock. We
14210 		 * want to be sure that the read operation gets the newest data.
14211 		 *
14212 		 * We flush the pages below after calling nfs4_end_fop above.
14213 		 *
14214 		 * The flush of the page cache must be done after
14215 		 * nfs4_end_open_seqid_sync() to avoid a 4-way hang.
14216 		 */
14217 		if (!error && resp && resp->status == NFS4_OK)
14218 			do_flush_pages = 1;
14219 	}
14220 	if (argsp) {
14221 		ASSERT(argsp->array_len == 2);
14222 		argop = argsp->array;
14223 		if (argop[1].argop == OP_LOCK)
14224 			nfs4args_lock_free(&argop[1]);
14225 		else if (argop[1].argop == OP_LOCKT)
14226 			nfs4args_lockt_free(&argop[1]);
14227 		kmem_free(argop, 2 * sizeof (nfs_argop4));
14228 		if (resp)
14229 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
14230 	}
14231 
14232 	/* free the reference on the lock owner */
14233 	if (lop != NULL) {
14234 		nfs4_end_lock_seqid_sync(lop);
14235 		lock_owner_rele(lop);
14236 	}
14237 
14238 	/* need to free up the reference on osp for lock args */
14239 	if (osp != NULL)
14240 		open_stream_rele(osp, rp);
14241 
14242 	/* need to free up the reference on oop for lock args */
14243 	if (oop != NULL) {
14244 		nfs4_end_open_seqid_sync(oop);
14245 		open_owner_rele(oop);
14246 	}
14247 
14248 	if (do_flush_pages)
14249 		nfs4_flush_pages(vp, cred);
14250 
14251 	/*
14252 	 * Record debug information in the event we get EINVAL.
14253 	 */
14254 	mutex_enter(&mi->mi_lock);
14255 	if (*errorp == EINVAL && (lock_args || locku_args) &&
14256 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
14257 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
14258 			zcmn_err(getzoneid(), CE_NOTE,
14259 			    "%s operation failed with "
14260 			    "EINVAL probably since the server, %s,"
14261 			    " doesn't support POSIX style locking",
14262 			    lock_args ? "LOCK" : "LOCKU",
14263 			    mi->mi_curr_serv->sv_hostname);
14264 			mi->mi_flags |= MI4_LOCK_DEBUG;
14265 		}
14266 	}
14267 	mutex_exit(&mi->mi_lock);
14268 
14269 	if (cred_otw)
14270 		crfree(cred_otw);
14271 }
14272 
14273 /*
14274  * This calls the server.
14275  *
14276  * Blocking lock requests will continually retry to acquire the lock
14277  * forever.
14278  *
14279  * The ctype is defined as follows:
14280  * NFS4_LCK_CTYPE_NORM: normal lock request.
14281  *
14282  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
14283  * recovery.
14284  *
14285  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
14286  * that we will use the information passed in via resend_rqstp to setup the
14287  * lock/locku request.  This resend is the exact same request as the 'lost
14288  * lock', and is initiated by the recovery framework. A successful resend
14289  * request can initiate one or more reinstate requests.
14290  *
14291  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14292  * does not trigger additional reinstate requests.  This lock call type is
14293  * set for setting the v4 server's locking state back to match what the
14294  * client's local locking state is in the event of a received 'lost lock'.
14295  *
14296  * Errors are returned via the nfs4_error_t parameter.
14297  */
14298 void
14299 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14300     cred_t *cr, nfs4_error_t *ep, nfs4_lost_rqst_t *resend_rqstp,
14301     int *did_reclaimp)
14302 {
14303 	COMPOUND4args_clnt	args, *argsp = NULL;
14304 	COMPOUND4res_clnt	res, *resp = NULL;
14305 	nfs_argop4	*argop;
14306 	nfs_resop4	*resop;
14307 	rnode4_t	*rp;
14308 	int		doqueue = 1;
14309 	clock_t		tick_delay;  /* delay in clock ticks */
14310 	LOCK4args	*lock_args = NULL;
14311 	LOCKU4args	*locku_args = NULL;
14312 	LOCKT4args	*lockt_args = NULL;
14313 	nfs4_open_owner_t *oop = NULL;
14314 	nfs4_open_stream_t *osp = NULL;
14315 	nfs4_lock_owner_t *lop = NULL;
14316 	bool_t		needrecov = FALSE;
14317 	nfs4_recov_state_t recov_state;
14318 	nfs4_op_hint_t	op_hint;
14319 	nfs4_lost_rqst_t lost_rqst;
14320 	bool_t		retry = FALSE;
14321 	bool_t		did_start_fop = FALSE;
14322 	bool_t		skip_get_err = FALSE;
14323 	cred_t		*cred_otw = NULL;
14324 	bool_t		recovonly;	/* just queue request */
14325 	int		frc_no_reclaim = 0;
14326 #ifdef DEBUG
14327 	char *name;
14328 #endif
14329 
14330 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14331 
14332 #ifdef DEBUG
14333 	name = fn_name(VTOSV(vp)->sv_name);
14334 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14335 	    "%s: cmd %d, type %d, start %"PRIx64", "
14336 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14337 	    "resend request %s", name, cmd, flk->l_type, flk->l_start,
14338 	    flk->l_len, flk->l_pid, flk->l_sysid,
14339 	    nfs4frlock_get_call_type(ctype),
14340 	    resend_rqstp ? "TRUE" : "FALSE"));
14341 	kmem_free(name, MAXNAMELEN);
14342 #endif
14343 
14344 	nfs4_error_zinit(ep);
14345 
14346 	nfs4frlock_pre_setup(&tick_delay, &recov_state, vp, cr, &cred_otw);
14347 
14348 	rp = VTOR4(vp);
14349 
14350 recov_retry:
14351 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14352 	    &retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14353 
14354 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14355 	    &did_start_fop, &recovonly);
14356 
14357 	if (ep->error)
14358 		goto out;
14359 
14360 	if (recovonly) {
14361 		/*
14362 		 * Leave the request for the recovery system to deal with.
14363 		 */
14364 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14365 		ASSERT(cmd != F_GETLK);
14366 		ASSERT(flk->l_type == F_UNLCK);
14367 
14368 		nfs4_error_init(ep, EINTR);
14369 		needrecov = TRUE;
14370 		lop = find_lock_owner(rp, flk->l_pid, LOWN_ANY);
14371 		if (lop != NULL) {
14372 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14373 			    NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14374 			(void) nfs4_start_recovery(ep,
14375 			    VTOMI4(vp), vp, NULL, NULL,
14376 			    (lost_rqst.lr_op == OP_LOCK ||
14377 			    lost_rqst.lr_op == OP_LOCKU) ?
14378 			    &lost_rqst : NULL, OP_LOCKU, NULL, NULL, NULL);
14379 			lock_owner_rele(lop);
14380 			lop = NULL;
14381 		}
14382 		goto out;
14383 	}
14384 
14385 	/* putfh directory fh */
14386 	argop[0].argop = OP_CPUTFH;
14387 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14388 
14389 	/*
14390 	 * Set up the over-the-wire arguments and get references to the
14391 	 * open owner, etc.
14392 	 */
14393 
14394 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14395 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14396 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14397 		    &argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14398 	} else {
14399 		bool_t go_otw = TRUE;
14400 
14401 		ASSERT(resend_rqstp == NULL);
14402 
14403 		switch (cmd) {
14404 		case F_GETLK:
14405 		case F_O_GETLK:
14406 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14407 			nfs4frlock_setup_lockt_args(&argop[1], &lockt_args,
14408 			    argsp, flk, rp);
14409 			break;
14410 		case F_SETLKW:
14411 		case F_SETLK:
14412 			if (flk->l_type == F_UNLCK)
14413 				nfs4frlock_setup_locku_args(ctype,
14414 				    &argop[1], &locku_args, flk,
14415 				    &lop, ep, argsp, vp, cr,
14416 				    &skip_get_err, &go_otw);
14417 			else
14418 				nfs4frlock_setup_lock_args(ctype,
14419 				    &lock_args, &oop, &osp, &lop, &argop[1],
14420 				    argsp, flk, cmd, vp, cr, ep);
14421 
14422 			if (ep->error)
14423 				goto out;
14424 
14425 			switch (ep->stat) {
14426 			case NFS4_OK:
14427 				break;
14428 			case NFS4ERR_DELAY:
14429 				/* recov thread never gets this error */
14430 				ASSERT(resend_rqstp == NULL);
14431 				ASSERT(did_start_fop);
14432 
14433 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14434 				    &recov_state, TRUE);
14435 				did_start_fop = FALSE;
14436 				if (argop[1].argop == OP_LOCK)
14437 					nfs4args_lock_free(&argop[1]);
14438 				else if (argop[1].argop == OP_LOCKT)
14439 					nfs4args_lockt_free(&argop[1]);
14440 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14441 				argsp = NULL;
14442 				goto recov_retry;
14443 			default:
14444 				ep->error = EIO;
14445 				goto out;
14446 			}
14447 			break;
14448 		default:
14449 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14450 			    "nfs4_frlock: invalid cmd %d", cmd));
14451 			ep->error = EINVAL;
14452 			goto out;
14453 		}
14454 
14455 		if (!go_otw)
14456 			goto out;
14457 	}
14458 
14459 	/*
14460 	 * Send the server the lock request.  Continually loop with a delay
14461 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14462 	 */
14463 	resp = &res;
14464 
14465 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14466 	    (CE_NOTE,
14467 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14468 	    rnode4info(rp)));
14469 
14470 	if (lock_args && frc_no_reclaim) {
14471 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14472 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14473 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14474 		lock_args->reclaim = FALSE;
14475 		if (did_reclaimp)
14476 			*did_reclaimp = 0;
14477 	}
14478 
14479 	/*
14480 	 * Do the OTW call.
14481 	 */
14482 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14483 
14484 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14485 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14486 
14487 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14488 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14489 	    "nfs4frlock: needrecov %d", needrecov));
14490 
14491 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14492 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14493 		    args.ctag);
14494 
14495 	/*
14496 	 * Check if one of these mutually exclusive error cases has
14497 	 * happened:
14498 	 *   need to swap credentials due to access error
14499 	 *   recovery is needed
14500 	 *   different error (only known case is missing Kerberos ticket)
14501 	 */
14502 
14503 	if ((ep->error == EACCES ||
14504 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14505 	    cred_otw != cr) {
14506 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14507 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14508 		    cr, &cred_otw);
14509 		goto recov_retry;
14510 	}
14511 
14512 	if (needrecov) {
14513 		/*
14514 		 * LOCKT requests don't need to recover from lost
14515 		 * requests since they don't create/modify state.
14516 		 */
14517 		if ((ep->error == EINTR ||
14518 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14519 		    lockt_args)
14520 			goto out;
14521 		/*
14522 		 * Do not attempt recovery for requests initiated by
14523 		 * the recovery framework.  Let the framework redrive them.
14524 		 */
14525 		if (ctype != NFS4_LCK_CTYPE_NORM)
14526 			goto out;
14527 		else {
14528 			ASSERT(resend_rqstp == NULL);
14529 		}
14530 
14531 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14532 		    flk_to_locktype(cmd, flk->l_type),
14533 		    oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14534 
14535 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14536 		    &resp, lock_args, locku_args, &oop, &osp, &lop,
14537 		    rp, vp, &recov_state, op_hint, &did_start_fop,
14538 		    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14539 
14540 		if (retry) {
14541 			ASSERT(oop == NULL);
14542 			ASSERT(osp == NULL);
14543 			ASSERT(lop == NULL);
14544 			goto recov_retry;
14545 		}
14546 		goto out;
14547 	}
14548 
14549 	/*
14550 	 * Bail out if have reached this point with ep->error set. Can
14551 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14552 	 * This happens if Kerberos ticket has expired or has been
14553 	 * destroyed.
14554 	 */
14555 	if (ep->error != 0)
14556 		goto out;
14557 
14558 	/*
14559 	 * Process the reply.
14560 	 */
14561 	switch (resp->status) {
14562 	case NFS4_OK:
14563 		resop = &resp->array[1];
14564 		/*
14565 		 * Have a successful lock operation, now update state.
14566 		 */
14567 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14568 		    resop, lop, vp, flk, cr, resend_rqstp);
14569 		break;
14570 
14571 	case NFS4ERR_DENIED:
14572 		resop = &resp->array[1];
14573 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14574 		    &oop, &osp, &lop, cmd, vp, flk, op_hint,
14575 		    &recov_state, needrecov, &argsp, &resp,
14576 		    &tick_delay, &ep->error, resop, cr,
14577 		    &did_start_fop, &skip_get_err);
14578 
14579 		if (retry) {
14580 			ASSERT(oop == NULL);
14581 			ASSERT(osp == NULL);
14582 			ASSERT(lop == NULL);
14583 			goto recov_retry;
14584 		}
14585 		break;
14586 	/*
14587 	 * If the server won't let us reclaim, fall-back to trying to lock
14588 	 * the file from scratch. Code elsewhere will check the changeinfo
14589 	 * to ensure the file hasn't been changed.
14590 	 */
14591 	case NFS4ERR_NO_GRACE:
14592 		if (lock_args && lock_args->reclaim == TRUE) {
14593 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14594 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14595 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14596 			frc_no_reclaim = 1;
14597 			/* clean up before retrying */
14598 			needrecov = 0;
14599 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14600 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14601 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14602 			goto recov_retry;
14603 		}
14604 		/* FALLTHROUGH */
14605 
14606 	default:
14607 		nfs4frlock_results_default(resp, &ep->error);
14608 		break;
14609 	}
14610 out:
14611 	/*
14612 	 * Process and cleanup from error.  Make interrupted unlock
14613 	 * requests look successful, since they will be handled by the
14614 	 * client recovery code.
14615 	 */
14616 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14617 	    needrecov, oop, osp, lop, &ep->error,
14618 	    lock_args, locku_args, did_start_fop,
14619 	    skip_get_err, cred_otw, cr);
14620 
14621 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14622 	    (cmd == F_SETLK || cmd == F_SETLKW))
14623 		ep->error = 0;
14624 }
14625 
14626 /*
14627  * nfs4_safelock:
14628  *
14629  * Return non-zero if the given lock request can be handled without
14630  * violating the constraints on concurrent mapping and locking.
14631  */
14632 
14633 static int
14634 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14635 {
14636 	rnode4_t *rp = VTOR4(vp);
14637 	struct vattr va;
14638 	int error;
14639 
14640 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14641 	ASSERT(rp->r_mapcnt >= 0);
14642 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14643 	    "(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14644 	    "write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14645 	    bfp->l_start, bfp->l_len, rp->r_mapcnt));
14646 
14647 	if (rp->r_mapcnt == 0)
14648 		return (1);		/* always safe if not mapped */
14649 
14650 	/*
14651 	 * If the file is already mapped and there are locks, then they
14652 	 * should be all safe locks.  So adding or removing a lock is safe
14653 	 * as long as the new request is safe (i.e., whole-file, meaning
14654 	 * length and starting offset are both zero).
14655 	 */
14656 
14657 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14658 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14659 		    "cannot lock a memory mapped file unless locking the "
14660 		    "entire file: start %"PRIx64", len %"PRIx64,
14661 		    bfp->l_start, bfp->l_len));
14662 		return (0);
14663 	}
14664 
14665 	/* mandatory locking and mapping don't mix */
14666 	va.va_mask = AT_MODE;
14667 	error = VOP_GETATTR(vp, &va, 0, cr, NULL);
14668 	if (error != 0) {
14669 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14670 		    "getattr error %d", error));
14671 		return (0);		/* treat errors conservatively */
14672 	}
14673 	if (MANDLOCK(vp, va.va_mode)) {
14674 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14675 		    "cannot mandatory lock and mmap a file"));
14676 		return (0);
14677 	}
14678 
14679 	return (1);
14680 }
14681 
14682 /*
14683  * nfs4_lockrelease:
14684  *
14685  * Release any locks on the given vnode that are held by the current
14686  * process.  Also removes the lock owner (if one exists) from the rnode's
14687  * list.
14688  */
14689 static int
14690 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14691 {
14692 	flock64_t ld;
14693 	int ret, error;
14694 	rnode4_t *rp;
14695 	nfs4_lock_owner_t *lop;
14696 	nfs4_recov_state_t recov_state;
14697 	mntinfo4_t *mi;
14698 	bool_t possible_orphan = FALSE;
14699 	bool_t recovonly;
14700 
14701 	ASSERT((uintptr_t)vp > KERNELBASE);
14702 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14703 
14704 	rp = VTOR4(vp);
14705 	mi = VTOMI4(vp);
14706 
14707 	/*
14708 	 * If we have not locked anything then we can
14709 	 * just return since we have no work to do.
14710 	 */
14711 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14712 		return (0);
14713 	}
14714 
14715 	/*
14716 	 * We need to comprehend that another thread may
14717 	 * kick off recovery and the lock_owner we have stashed
14718 	 * in lop might be invalid so we should NOT cache it
14719 	 * locally!
14720 	 */
14721 	recov_state.rs_flags = 0;
14722 	recov_state.rs_num_retry_despite_err = 0;
14723 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14724 	    &recovonly);
14725 	if (error) {
14726 		mutex_enter(&rp->r_statelock);
14727 		rp->r_flags |= R4LODANGLERS;
14728 		mutex_exit(&rp->r_statelock);
14729 		return (error);
14730 	}
14731 
14732 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14733 
14734 	/*
14735 	 * Check if the lock owner might have a lock (request was sent but
14736 	 * no response was received).  Also check if there are any remote
14737 	 * locks on the file.  (In theory we shouldn't have to make this
14738 	 * second check if there's no lock owner, but for now we'll be
14739 	 * conservative and do it anyway.)  If either condition is true,
14740 	 * send an unlock for the entire file to the server.
14741 	 *
14742 	 * Note that no explicit synchronization is needed here.  At worst,
14743 	 * flk_has_remote_locks() will return a false positive, in which case
14744 	 * the unlock call wastes time but doesn't harm correctness.
14745 	 */
14746 
14747 	if (lop) {
14748 		mutex_enter(&lop->lo_lock);
14749 		possible_orphan = lop->lo_pending_rqsts;
14750 		mutex_exit(&lop->lo_lock);
14751 		lock_owner_rele(lop);
14752 	}
14753 
14754 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14755 
14756 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14757 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14758 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14759 	    (void *)lop));
14760 
14761 	if (possible_orphan || flk_has_remote_locks(vp)) {
14762 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14763 		ld.l_whence = 0;	/* unlock from start of file */
14764 		ld.l_start = 0;
14765 		ld.l_len = 0;		/* do entire file */
14766 
14767 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL,
14768 		    cr, NULL);
14769 
14770 		if (ret != 0) {
14771 			/*
14772 			 * If VOP_FRLOCK fails, make sure we unregister
14773 			 * local locks before we continue.
14774 			 */
14775 			struct lm_sysid *lmsid = nfs4_find_sysid(VTOMI4(vp));
14776 
14777 			if (lmsid != NULL) {
14778 				cleanlocks(vp, curproc->p_pid,
14779 				    lm_sysidt(lmsid) | LM_SYSID_CLIENT);
14780 				lm_rel_sysid(lmsid);
14781 			}
14782 
14783 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14784 			    "nfs4_lockrelease: lock release error on vp"
14785 			    " %p: error %d.\n", (void *)vp, ret));
14786 		}
14787 	}
14788 
14789 	recov_state.rs_flags = 0;
14790 	recov_state.rs_num_retry_despite_err = 0;
14791 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14792 	    &recovonly);
14793 	if (error) {
14794 		mutex_enter(&rp->r_statelock);
14795 		rp->r_flags |= R4LODANGLERS;
14796 		mutex_exit(&rp->r_statelock);
14797 		return (error);
14798 	}
14799 
14800 	/*
14801 	 * So, here we're going to need to retrieve the lock-owner
14802 	 * again (in case recovery has done a switch-a-roo) and
14803 	 * remove it because we can.
14804 	 */
14805 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14806 
14807 	if (lop) {
14808 		nfs4_rnode_remove_lock_owner(rp, lop);
14809 		lock_owner_rele(lop);
14810 	}
14811 
14812 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14813 	return (0);
14814 }
14815 
14816 /*
14817  * Wait for 'tick_delay' clock ticks.
14818  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14819  *
14820  * The client should retry to acquire the lock faster than the lease period.
14821  * We use roughly half of the lease time to use a similar calculation as it is
14822  * used in nfs4_renew_lease_thread().
14823  *
14824  * XXX For future improvements, should implement a waiting queue scheme.
14825  */
14826 static int
14827 nfs4_block_and_wait(clock_t *tick_delay)
14828 {
14829 	/* wait tick_delay clock ticks or siginteruptus */
14830 	if (delay_sig(*tick_delay)) {
14831 		return (EINTR);
14832 	}
14833 
14834 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14835 	    "reissue the lock request: blocked for %ld clock ticks: %ld "
14836 	    "milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14837 
14838 	*tick_delay = MIN(drv_usectohz(nfs4_max_base_wait_time * 1000),
14839 			  *tick_delay * 1.5);
14840 	return (0);
14841 }
14842 
14843 void
14844 nfs4_vnops_init(void)
14845 {
14846 }
14847 
14848 void
14849 nfs4_vnops_fini(void)
14850 {
14851 }
14852 
14853 /*
14854  * Return a reference to the directory (parent) vnode for a given vnode,
14855  * using the saved pathname information and the directory file handle.  The
14856  * caller is responsible for disposing of the reference.
14857  * Returns zero or an errno value.
14858  *
14859  * Caller should set need_start_op to FALSE if it is the recovery
14860  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14861  */
14862 int
14863 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14864 {
14865 	svnode_t *svnp;
14866 	vnode_t *dvp = NULL;
14867 	servinfo4_t *svp;
14868 	nfs4_fname_t *mfname;
14869 	int error;
14870 
14871 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14872 
14873 	if (vp->v_flag & VROOT) {
14874 		nfs4_sharedfh_t *sfh;
14875 		nfs_fh4 fh;
14876 		mntinfo4_t *mi;
14877 
14878 		ASSERT(vp->v_type == VREG);
14879 
14880 		mi = VTOMI4(vp);
14881 		svp = mi->mi_curr_serv;
14882 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14883 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14884 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14885 		sfh = sfh4_get(&fh, VTOMI4(vp));
14886 		nfs_rw_exit(&svp->sv_lock);
14887 		mfname = mi->mi_fname;
14888 		fn_hold(mfname);
14889 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14890 		sfh4_rele(&sfh);
14891 
14892 		if (dvp->v_type == VNON)
14893 			dvp->v_type = VDIR;
14894 		*dvpp = dvp;
14895 		return (0);
14896 	}
14897 
14898 	svnp = VTOSV(vp);
14899 
14900 	if (svnp == NULL) {
14901 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14902 		    "shadow node is NULL"));
14903 		return (EINVAL);
14904 	}
14905 
14906 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14907 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14908 		    "shadow node name or dfh val == NULL"));
14909 		return (EINVAL);
14910 	}
14911 
14912 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14913 	    (int)need_start_op);
14914 	if (error != 0) {
14915 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14916 		    "nfs4_make_dotdot returned %d", error));
14917 		return (error);
14918 	}
14919 	if (!dvp) {
14920 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14921 		    "nfs4_make_dotdot returned a NULL dvp"));
14922 		return (EIO);
14923 	}
14924 	if (dvp->v_type == VNON)
14925 		dvp->v_type = VDIR;
14926 	ASSERT(dvp->v_type == VDIR);
14927 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14928 		mutex_enter(&dvp->v_lock);
14929 		dvp->v_flag |= V_XATTRDIR;
14930 		mutex_exit(&dvp->v_lock);
14931 	}
14932 	*dvpp = dvp;
14933 	return (0);
14934 }
14935 
14936 /*
14937  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14938  * length that fnamep can accept, including the trailing null.
14939  * Returns 0 if okay, returns an errno value if there was a problem.
14940  */
14941 
14942 int
14943 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14944 {
14945 	char *fn;
14946 	int err = 0;
14947 	servinfo4_t *svp;
14948 	svnode_t *shvp;
14949 
14950 	/*
14951 	 * If the file being opened has VROOT set, then this is
14952 	 * a "file" mount.  sv_name will not be interesting, so
14953 	 * go back to the servinfo4 to get the original mount
14954 	 * path and strip off all but the final edge.  Otherwise
14955 	 * just return the name from the shadow vnode.
14956 	 */
14957 
14958 	if (vp->v_flag & VROOT) {
14959 
14960 		svp = VTOMI4(vp)->mi_curr_serv;
14961 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14962 
14963 		fn = strrchr(svp->sv_path, '/');
14964 		if (fn == NULL)
14965 			err = EINVAL;
14966 		else
14967 			fn++;
14968 	} else {
14969 		shvp = VTOSV(vp);
14970 		fn = fn_name(shvp->sv_name);
14971 	}
14972 
14973 	if (err == 0)
14974 		if (strlen(fn) < maxlen)
14975 			(void) strcpy(fnamep, fn);
14976 		else
14977 			err = ENAMETOOLONG;
14978 
14979 	if (vp->v_flag & VROOT)
14980 		nfs_rw_exit(&svp->sv_lock);
14981 	else
14982 		kmem_free(fn, MAXNAMELEN);
14983 
14984 	return (err);
14985 }
14986 
14987 /*
14988  * Bookkeeping for a close that doesn't need to go over the wire.
14989  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14990  * it is left at 1.
14991  */
14992 void
14993 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14994 {
14995 	rnode4_t		*rp;
14996 	mntinfo4_t		*mi;
14997 
14998 	mi = VTOMI4(vp);
14999 	rp = VTOR4(vp);
15000 
15001 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
15002 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
15003 	ASSERT(nfs_zone() == mi->mi_zone);
15004 	ASSERT(mutex_owned(&osp->os_sync_lock));
15005 	ASSERT(*have_lockp);
15006 
15007 	if (!osp->os_valid ||
15008 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15009 		return;
15010 	}
15011 
15012 	/*
15013 	 * This removes the reference obtained at OPEN; ie,
15014 	 * when the open stream structure was created.
15015 	 *
15016 	 * We don't have to worry about calling 'open_stream_rele'
15017 	 * since we our currently holding a reference to this
15018 	 * open stream which means the count can not go to 0 with
15019 	 * this decrement.
15020 	 */
15021 	ASSERT(osp->os_ref_count >= 2);
15022 	osp->os_ref_count--;
15023 	osp->os_valid = 0;
15024 	mutex_exit(&osp->os_sync_lock);
15025 	*have_lockp = 0;
15026 
15027 	nfs4_dec_state_ref_count(mi);
15028 }
15029 
15030 /*
15031  * Close all remaining open streams on the rnode.  These open streams
15032  * could be here because:
15033  * - The close attempted at either close or delmap failed
15034  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
15035  * - Someone did mknod on a regular file but never opened it
15036  */
15037 int
15038 nfs4close_all(vnode_t *vp, cred_t *cr)
15039 {
15040 	nfs4_open_stream_t *osp;
15041 	int error;
15042 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
15043 	rnode4_t *rp;
15044 
15045 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15046 
15047 	error = 0;
15048 	rp = VTOR4(vp);
15049 
15050 	/*
15051 	 * At this point, all we know is that the last time
15052 	 * someone called vn_rele, the count was 1.  Since then,
15053 	 * the vnode could have been re-activated.  We want to
15054 	 * loop through the open streams and close each one, but
15055 	 * we have to be careful since once we release the rnode
15056 	 * hash bucket lock, someone else is free to come in and
15057 	 * re-activate the rnode and add new open streams.  The
15058 	 * strategy is take the rnode hash bucket lock, verify that
15059 	 * the count is still 1, grab the open stream off the
15060 	 * head of the list and mark it invalid, then release the
15061 	 * rnode hash bucket lock and proceed with that open stream.
15062 	 * This is ok because nfs4close_one() will acquire the proper
15063 	 * open/create to close/destroy synchronization for open
15064 	 * streams, and will ensure that if someone has reopened
15065 	 * the open stream after we've dropped the hash bucket lock
15066 	 * then we'll just simply return without destroying the
15067 	 * open stream.
15068 	 * Repeat until the list is empty.
15069 	 */
15070 
15071 	for (;;) {
15072 
15073 		/* make sure vnode hasn't been reactivated */
15074 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
15075 		mutex_enter(&vp->v_lock);
15076 		if (vp->v_count > 1) {
15077 			mutex_exit(&vp->v_lock);
15078 			rw_exit(&rp->r_hashq->r_lock);
15079 			break;
15080 		}
15081 		/*
15082 		 * Grabbing r_os_lock before releasing v_lock prevents
15083 		 * a window where the rnode/open stream could get
15084 		 * reactivated (and os_force_close set to 0) before we
15085 		 * had a chance to set os_force_close to 1.
15086 		 */
15087 		mutex_enter(&rp->r_os_lock);
15088 		mutex_exit(&vp->v_lock);
15089 
15090 		osp = list_head(&rp->r_open_streams);
15091 		if (!osp) {
15092 			/* nothing left to CLOSE OTW, so return */
15093 			mutex_exit(&rp->r_os_lock);
15094 			rw_exit(&rp->r_hashq->r_lock);
15095 			break;
15096 		}
15097 
15098 		mutex_enter(&rp->r_statev4_lock);
15099 		/* the file can't still be mem mapped */
15100 		ASSERT(rp->r_mapcnt == 0);
15101 		if (rp->created_v4)
15102 			rp->created_v4 = 0;
15103 		mutex_exit(&rp->r_statev4_lock);
15104 
15105 		/*
15106 		 * Grab a ref on this open stream; nfs4close_one
15107 		 * will mark it as invalid
15108 		 */
15109 		mutex_enter(&osp->os_sync_lock);
15110 		osp->os_ref_count++;
15111 		osp->os_force_close = 1;
15112 		mutex_exit(&osp->os_sync_lock);
15113 		mutex_exit(&rp->r_os_lock);
15114 		rw_exit(&rp->r_hashq->r_lock);
15115 
15116 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
15117 
15118 		/* Update error if it isn't already non-zero */
15119 		if (error == 0) {
15120 			if (e.error)
15121 				error = e.error;
15122 			else if (e.stat)
15123 				error = geterrno4(e.stat);
15124 		}
15125 
15126 #ifdef	DEBUG
15127 		nfs4close_all_cnt++;
15128 #endif
15129 		/* Release the ref on osp acquired above. */
15130 		open_stream_rele(osp, rp);
15131 
15132 		/* Proceed to the next open stream, if any */
15133 	}
15134 	return (error);
15135 }
15136 
15137 /*
15138  * nfs4close_one - close one open stream for a file if needed.
15139  *
15140  * "close_type" indicates which close path this is:
15141  * CLOSE_NORM: close initiated via VOP_CLOSE.
15142  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
15143  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
15144  *	the close and release of client state for this open stream
15145  *	(unless someone else has the open stream open).
15146  * CLOSE_RESEND: indicates the request is a replay of an earlier request
15147  *	(e.g., due to abort because of a signal).
15148  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
15149  *
15150  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
15151  * recovery.  Instead, the caller is expected to deal with retries.
15152  *
15153  * The caller can either pass in the osp ('provided_osp') or not.
15154  *
15155  * 'access_bits' represents the access we are closing/downgrading.
15156  *
15157  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
15158  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
15159  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
15160  *
15161  * Errors are returned via the nfs4_error_t.
15162  */
15163 void
15164 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
15165     int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
15166     nfs4_close_type_t close_type, size_t len, uint_t maxprot,
15167     uint_t mmap_flags)
15168 {
15169 	nfs4_open_owner_t *oop;
15170 	nfs4_open_stream_t *osp = NULL;
15171 	int retry = 0;
15172 	int num_retries = NFS4_NUM_RECOV_RETRIES;
15173 	rnode4_t *rp;
15174 	mntinfo4_t *mi;
15175 	nfs4_recov_state_t recov_state;
15176 	cred_t *cred_otw = NULL;
15177 	bool_t recovonly = FALSE;
15178 	int isrecov;
15179 	int force_close;
15180 	int close_failed = 0;
15181 	int did_dec_count = 0;
15182 	int did_start_op = 0;
15183 	int did_force_recovlock = 0;
15184 	int did_start_seqid_sync = 0;
15185 	int have_sync_lock = 0;
15186 
15187 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15188 
15189 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
15190 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
15191 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
15192 	    len, maxprot, mmap_flags, access_bits));
15193 
15194 	nfs4_error_zinit(ep);
15195 	rp = VTOR4(vp);
15196 	mi = VTOMI4(vp);
15197 	isrecov = (close_type == CLOSE_RESEND ||
15198 	    close_type == CLOSE_AFTER_RESEND);
15199 
15200 	/*
15201 	 * First get the open owner.
15202 	 */
15203 	if (!provided_osp) {
15204 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
15205 	} else {
15206 		oop = provided_osp->os_open_owner;
15207 		ASSERT(oop != NULL);
15208 		open_owner_hold(oop);
15209 	}
15210 
15211 	if (!oop) {
15212 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15213 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15214 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15215 		    (void *)provided_osp, close_type));
15216 		ep->error = EIO;
15217 		goto out;
15218 	}
15219 
15220 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15221 recov_retry:
15222 	osp = NULL;
15223 	close_failed = 0;
15224 	force_close = (close_type == CLOSE_FORCE);
15225 	retry = 0;
15226 	did_start_op = 0;
15227 	did_force_recovlock = 0;
15228 	did_start_seqid_sync = 0;
15229 	have_sync_lock = 0;
15230 	recovonly = FALSE;
15231 	recov_state.rs_flags = 0;
15232 	recov_state.rs_num_retry_despite_err = 0;
15233 
15234 	/*
15235 	 * Second synchronize with recovery.
15236 	 */
15237 	if (!isrecov) {
15238 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15239 		    &recov_state, &recovonly);
15240 		if (!ep->error) {
15241 			did_start_op = 1;
15242 		} else {
15243 			close_failed = 1;
15244 			/*
15245 			 * If we couldn't get start_fop, but have to
15246 			 * cleanup state, then at least acquire the
15247 			 * mi_recovlock so we can synchronize with
15248 			 * recovery.
15249 			 */
15250 			if (close_type == CLOSE_FORCE) {
15251 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15252 				    RW_READER, FALSE);
15253 				did_force_recovlock = 1;
15254 			} else
15255 				goto out;
15256 		}
15257 	}
15258 
15259 	/*
15260 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15261 	 * set 'recovonly' to TRUE since most likely this is due to
15262 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15263 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15264 	 * to retry, causing us to loop until recovery finishes.  Plus we
15265 	 * don't need protection over the open seqid since we're not going
15266 	 * OTW, hence don't need to use the seqid.
15267 	 */
15268 	if (recovonly == FALSE) {
15269 		/* need to grab the open owner sync before 'os_sync_lock' */
15270 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15271 		if (ep->error == EAGAIN) {
15272 			ASSERT(!isrecov);
15273 			if (did_start_op)
15274 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15275 				    &recov_state, TRUE);
15276 			if (did_force_recovlock)
15277 				nfs_rw_exit(&mi->mi_recovlock);
15278 			goto recov_retry;
15279 		}
15280 		did_start_seqid_sync = 1;
15281 	}
15282 
15283 	/*
15284 	 * Third get an open stream and acquire 'os_sync_lock' to
15285 	 * sychronize the opening/creating of an open stream with the
15286 	 * closing/destroying of an open stream.
15287 	 */
15288 	if (!provided_osp) {
15289 		/* returns with 'os_sync_lock' held */
15290 		osp = find_open_stream(oop, rp);
15291 		if (!osp) {
15292 			ep->error = EIO;
15293 			goto out;
15294 		}
15295 	} else {
15296 		osp = provided_osp;
15297 		open_stream_hold(osp);
15298 		mutex_enter(&osp->os_sync_lock);
15299 	}
15300 	have_sync_lock = 1;
15301 
15302 	ASSERT(oop == osp->os_open_owner);
15303 
15304 	/*
15305 	 * Fourth, do any special pre-OTW CLOSE processing
15306 	 * based on the specific close type.
15307 	 */
15308 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15309 	    !did_dec_count) {
15310 		ASSERT(osp->os_open_ref_count > 0);
15311 		osp->os_open_ref_count--;
15312 		did_dec_count = 1;
15313 		if (osp->os_open_ref_count == 0)
15314 			osp->os_final_close = 1;
15315 	}
15316 
15317 	if (close_type == CLOSE_FORCE) {
15318 		/* see if somebody reopened the open stream. */
15319 		if (!osp->os_force_close) {
15320 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15321 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15322 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15323 			ep->error = 0;
15324 			ep->stat = NFS4_OK;
15325 			goto out;
15326 		}
15327 
15328 		if (!osp->os_final_close && !did_dec_count) {
15329 			osp->os_open_ref_count--;
15330 			did_dec_count = 1;
15331 		}
15332 
15333 		/*
15334 		 * We can't depend on os_open_ref_count being 0 due to the
15335 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15336 		 */
15337 #ifdef	NOTYET
15338 		ASSERT(osp->os_open_ref_count == 0);
15339 #endif
15340 		if (osp->os_open_ref_count != 0) {
15341 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15342 			    "nfs4close_one: should panic here on an "
15343 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15344 			    "since this is probably the exec problem."));
15345 
15346 			osp->os_open_ref_count = 0;
15347 		}
15348 
15349 		/*
15350 		 * There is the possibility that nfs4close_one()
15351 		 * for close_type == CLOSE_DELMAP couldn't find the
15352 		 * open stream, thus couldn't decrement its os_mapcnt;
15353 		 * therefore we can't use this ASSERT yet.
15354 		 */
15355 #ifdef	NOTYET
15356 		ASSERT(osp->os_mapcnt == 0);
15357 #endif
15358 		osp->os_mapcnt = 0;
15359 	}
15360 
15361 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15362 		ASSERT(osp->os_mapcnt >= btopr(len));
15363 
15364 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15365 			osp->os_mmap_write -= btopr(len);
15366 		if (maxprot & PROT_READ)
15367 			osp->os_mmap_read -= btopr(len);
15368 		if (maxprot & PROT_EXEC)
15369 			osp->os_mmap_read -= btopr(len);
15370 		/* mirror the PROT_NONE check in nfs4_addmap() */
15371 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15372 		    !(maxprot & PROT_EXEC))
15373 			osp->os_mmap_read -= btopr(len);
15374 		osp->os_mapcnt -= btopr(len);
15375 		did_dec_count = 1;
15376 	}
15377 
15378 	if (recovonly) {
15379 		nfs4_lost_rqst_t lost_rqst;
15380 
15381 		/* request should not already be in recovery queue */
15382 		ASSERT(lrp == NULL);
15383 		nfs4_error_init(ep, EINTR);
15384 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15385 		    osp, cred_otw, vp);
15386 		mutex_exit(&osp->os_sync_lock);
15387 		have_sync_lock = 0;
15388 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15389 		    lost_rqst.lr_op == OP_CLOSE ?
15390 		    &lost_rqst : NULL, OP_CLOSE, NULL, NULL, NULL);
15391 		close_failed = 1;
15392 		force_close = 0;
15393 		goto close_cleanup;
15394 	}
15395 
15396 	/*
15397 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15398 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15399 	 * space, which means we stopped operating on the open stream
15400 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15401 	 * stateid could be stale, potentially triggering a false
15402 	 * setclientid), and just clean up the client's internal state.
15403 	 */
15404 	if (osp->os_orig_oo_name != oop->oo_name) {
15405 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15406 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15407 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15408 		    "oo_name %" PRIx64")",
15409 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15410 		    oop->oo_name));
15411 		close_failed = 1;
15412 	}
15413 
15414 	/* If the file failed recovery, just quit. */
15415 	mutex_enter(&rp->r_statelock);
15416 	if (rp->r_flags & R4RECOVERR) {
15417 		close_failed = 1;
15418 	}
15419 	mutex_exit(&rp->r_statelock);
15420 
15421 	/*
15422 	 * If the force close path failed to obtain start_fop
15423 	 * then skip the OTW close and just remove the state.
15424 	 */
15425 	if (close_failed)
15426 		goto close_cleanup;
15427 
15428 	/*
15429 	 * Fifth, check to see if there are still mapped pages or other
15430 	 * opens using this open stream.  If there are then we can't
15431 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15432 	 */
15433 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15434 		nfs4_lost_rqst_t	new_lost_rqst;
15435 		bool_t			needrecov = FALSE;
15436 		cred_t			*odg_cred_otw = NULL;
15437 		seqid4			open_dg_seqid = 0;
15438 
15439 		if (osp->os_delegation) {
15440 			/*
15441 			 * If this open stream was never OPENed OTW then we
15442 			 * surely can't DOWNGRADE it (especially since the
15443 			 * osp->open_stateid is really a delegation stateid
15444 			 * when os_delegation is 1).
15445 			 */
15446 			if (access_bits & FREAD)
15447 				osp->os_share_acc_read--;
15448 			if (access_bits & FWRITE)
15449 				osp->os_share_acc_write--;
15450 			osp->os_share_deny_none--;
15451 			nfs4_error_zinit(ep);
15452 			goto out;
15453 		}
15454 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15455 		    lrp, ep, &odg_cred_otw, &open_dg_seqid);
15456 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15457 		if (needrecov && !isrecov) {
15458 			bool_t abort;
15459 			nfs4_bseqid_entry_t *bsep = NULL;
15460 
15461 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15462 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15463 				    vp, 0,
15464 				    lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15465 				    open_dg_seqid);
15466 
15467 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15468 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15469 			mutex_exit(&osp->os_sync_lock);
15470 			have_sync_lock = 0;
15471 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15472 			    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15473 			    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15474 			    bsep, NULL, NULL);
15475 			if (odg_cred_otw)
15476 				crfree(odg_cred_otw);
15477 			if (bsep)
15478 				kmem_free(bsep, sizeof (*bsep));
15479 
15480 			if (abort == TRUE)
15481 				goto out;
15482 
15483 			if (did_start_seqid_sync) {
15484 				nfs4_end_open_seqid_sync(oop);
15485 				did_start_seqid_sync = 0;
15486 			}
15487 			open_stream_rele(osp, rp);
15488 
15489 			if (did_start_op)
15490 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15491 				    &recov_state, FALSE);
15492 			if (did_force_recovlock)
15493 				nfs_rw_exit(&mi->mi_recovlock);
15494 
15495 			goto recov_retry;
15496 		} else {
15497 			if (odg_cred_otw)
15498 				crfree(odg_cred_otw);
15499 		}
15500 		goto out;
15501 	}
15502 
15503 	/*
15504 	 * If this open stream was created as the results of an open
15505 	 * while holding a delegation, then just release it; no need
15506 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15507 	 */
15508 	if (osp->os_delegation) {
15509 		nfs4close_notw(vp, osp, &have_sync_lock);
15510 		nfs4_error_zinit(ep);
15511 		goto out;
15512 	}
15513 
15514 	/*
15515 	 * If this stream is not valid, we're done.
15516 	 */
15517 	if (!osp->os_valid) {
15518 		nfs4_error_zinit(ep);
15519 		goto out;
15520 	}
15521 
15522 	/*
15523 	 * Last open or mmap ref has vanished, need to do an OTW close.
15524 	 * First check to see if a close is still necessary.
15525 	 */
15526 	if (osp->os_failed_reopen) {
15527 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15528 		    "don't close OTW osp %p since reopen failed.",
15529 		    (void *)osp));
15530 		/*
15531 		 * Reopen of the open stream failed, hence the
15532 		 * stateid of the open stream is invalid/stale, and
15533 		 * sending this OTW would incorrectly cause another
15534 		 * round of recovery.  In this case, we need to set
15535 		 * the 'os_valid' bit to 0 so another thread doesn't
15536 		 * come in and re-open this open stream before
15537 		 * this "closing" thread cleans up state (decrementing
15538 		 * the nfs4_server_t's state_ref_count and decrementing
15539 		 * the os_ref_count).
15540 		 */
15541 		osp->os_valid = 0;
15542 		/*
15543 		 * This removes the reference obtained at OPEN; ie,
15544 		 * when the open stream structure was created.
15545 		 *
15546 		 * We don't have to worry about calling 'open_stream_rele'
15547 		 * since we our currently holding a reference to this
15548 		 * open stream which means the count can not go to 0 with
15549 		 * this decrement.
15550 		 */
15551 		ASSERT(osp->os_ref_count >= 2);
15552 		osp->os_ref_count--;
15553 		nfs4_error_zinit(ep);
15554 		close_failed = 0;
15555 		goto close_cleanup;
15556 	}
15557 
15558 	ASSERT(osp->os_ref_count > 1);
15559 
15560 	/*
15561 	 * Sixth, try the CLOSE OTW.
15562 	 */
15563 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15564 	    close_type, ep, &have_sync_lock);
15565 
15566 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15567 		/*
15568 		 * Let the recovery thread be responsible for
15569 		 * removing the state for CLOSE.
15570 		 */
15571 		close_failed = 1;
15572 		force_close = 0;
15573 		retry = 0;
15574 	}
15575 
15576 	/* See if we need to retry with a different cred */
15577 	if ((ep->error == EACCES ||
15578 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15579 	    cred_otw != cr) {
15580 		crfree(cred_otw);
15581 		cred_otw = cr;
15582 		crhold(cred_otw);
15583 		retry = 1;
15584 	}
15585 
15586 	if (ep->error || ep->stat)
15587 		close_failed = 1;
15588 
15589 	if (retry && !isrecov && num_retries-- > 0) {
15590 		if (have_sync_lock) {
15591 			mutex_exit(&osp->os_sync_lock);
15592 			have_sync_lock = 0;
15593 		}
15594 		if (did_start_seqid_sync) {
15595 			nfs4_end_open_seqid_sync(oop);
15596 			did_start_seqid_sync = 0;
15597 		}
15598 		open_stream_rele(osp, rp);
15599 
15600 		if (did_start_op)
15601 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15602 			    &recov_state, FALSE);
15603 		if (did_force_recovlock)
15604 			nfs_rw_exit(&mi->mi_recovlock);
15605 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15606 		    "nfs4close_one: need to retry the close "
15607 		    "operation"));
15608 		goto recov_retry;
15609 	}
15610 close_cleanup:
15611 	/*
15612 	 * Seventh and lastly, process our results.
15613 	 */
15614 	if (close_failed && force_close) {
15615 		/*
15616 		 * It's ok to drop and regrab the 'os_sync_lock' since
15617 		 * nfs4close_notw() will recheck to make sure the
15618 		 * "close"/removal of state should happen.
15619 		 */
15620 		if (!have_sync_lock) {
15621 			mutex_enter(&osp->os_sync_lock);
15622 			have_sync_lock = 1;
15623 		}
15624 		/*
15625 		 * This is last call, remove the ref on the open
15626 		 * stream created by open and clean everything up.
15627 		 */
15628 		osp->os_pending_close = 0;
15629 		nfs4close_notw(vp, osp, &have_sync_lock);
15630 		nfs4_error_zinit(ep);
15631 	}
15632 
15633 	if (!close_failed) {
15634 		if (have_sync_lock) {
15635 			osp->os_pending_close = 0;
15636 			mutex_exit(&osp->os_sync_lock);
15637 			have_sync_lock = 0;
15638 		} else {
15639 			mutex_enter(&osp->os_sync_lock);
15640 			osp->os_pending_close = 0;
15641 			mutex_exit(&osp->os_sync_lock);
15642 		}
15643 		if (did_start_op && recov_state.rs_sp != NULL) {
15644 			mutex_enter(&recov_state.rs_sp->s_lock);
15645 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15646 			mutex_exit(&recov_state.rs_sp->s_lock);
15647 		} else {
15648 			nfs4_dec_state_ref_count(mi);
15649 		}
15650 		nfs4_error_zinit(ep);
15651 	}
15652 
15653 out:
15654 	if (have_sync_lock)
15655 		mutex_exit(&osp->os_sync_lock);
15656 	if (did_start_op)
15657 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15658 		    recovonly ? TRUE : FALSE);
15659 	if (did_force_recovlock)
15660 		nfs_rw_exit(&mi->mi_recovlock);
15661 	if (cred_otw)
15662 		crfree(cred_otw);
15663 	if (osp)
15664 		open_stream_rele(osp, rp);
15665 	if (oop) {
15666 		if (did_start_seqid_sync)
15667 			nfs4_end_open_seqid_sync(oop);
15668 		open_owner_rele(oop);
15669 	}
15670 }
15671 
15672 /*
15673  * Convert information returned by the server in the LOCK4denied
15674  * structure to the form required by fcntl.
15675  */
15676 static void
15677 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15678 {
15679 	nfs4_lo_name_t *lo;
15680 
15681 #ifdef	DEBUG
15682 	if (denied_to_flk_debug) {
15683 		lockt_denied_debug = lockt_denied;
15684 		debug_enter("lockt_denied");
15685 	}
15686 #endif
15687 
15688 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15689 	flk->l_whence = 0;	/* aka SEEK_SET */
15690 	flk->l_start = lockt_denied->offset;
15691 	flk->l_len = lockt_denied->length;
15692 
15693 	/*
15694 	 * If the blocking clientid matches our client id, then we can
15695 	 * interpret the lockowner (since we built it).  If not, then
15696 	 * fabricate a sysid and pid.  Note that the l_sysid field
15697 	 * in *flk already has the local sysid.
15698 	 */
15699 
15700 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15701 
15702 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15703 			lo = (nfs4_lo_name_t *)
15704 			    lockt_denied->owner.owner_val;
15705 
15706 			flk->l_pid = lo->ln_pid;
15707 		} else {
15708 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15709 			    "denied_to_flk: bad lock owner length\n"));
15710 
15711 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15712 		}
15713 	} else {
15714 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15715 		"denied_to_flk: foreign clientid\n"));
15716 
15717 		/*
15718 		 * Construct a new sysid which should be different from
15719 		 * sysids of other systems.
15720 		 */
15721 
15722 		flk->l_sysid++;
15723 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15724 	}
15725 }
15726 
15727 static pid_t
15728 lo_to_pid(lock_owner4 *lop)
15729 {
15730 	pid_t pid = 0;
15731 	uchar_t *cp;
15732 	int i;
15733 
15734 	cp = (uchar_t *)&lop->clientid;
15735 
15736 	for (i = 0; i < sizeof (lop->clientid); i++)
15737 		pid += (pid_t)*cp++;
15738 
15739 	cp = (uchar_t *)lop->owner_val;
15740 
15741 	for (i = 0; i < lop->owner_len; i++)
15742 		pid += (pid_t)*cp++;
15743 
15744 	return (pid);
15745 }
15746 
15747 /*
15748  * Given a lock pointer, returns the length of that lock.
15749  * "end" is the last locked offset the "l_len" covers from
15750  * the start of the lock.
15751  */
15752 static off64_t
15753 lock_to_end(flock64_t *lock)
15754 {
15755 	off64_t lock_end;
15756 
15757 	if (lock->l_len == 0)
15758 		lock_end = (off64_t)MAXEND;
15759 	else
15760 		lock_end = lock->l_start + lock->l_len - 1;
15761 
15762 	return (lock_end);
15763 }
15764 
15765 /*
15766  * Given the end of a lock, it will return you the length "l_len" for that lock.
15767  */
15768 static off64_t
15769 end_to_len(off64_t start, off64_t end)
15770 {
15771 	off64_t lock_len;
15772 
15773 	ASSERT(end >= start);
15774 	if (end == MAXEND)
15775 		lock_len = 0;
15776 	else
15777 		lock_len = end - start + 1;
15778 
15779 	return (lock_len);
15780 }
15781 
15782 /*
15783  * On given end for a lock it determines if it is the last locked offset
15784  * or not, if so keeps it as is, else adds one to return the length for
15785  * valid start.
15786  */
15787 static off64_t
15788 start_check(off64_t x)
15789 {
15790 	if (x == MAXEND)
15791 		return (x);
15792 	else
15793 		return (x + 1);
15794 }
15795 
15796 /*
15797  * See if these two locks overlap, and if so return 1;
15798  * otherwise, return 0.
15799  */
15800 static int
15801 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15802 {
15803 	off64_t llfp_end, curfp_end;
15804 
15805 	llfp_end = lock_to_end(llfp);
15806 	curfp_end = lock_to_end(curfp);
15807 
15808 	if (((llfp_end >= curfp->l_start) &&
15809 	    (llfp->l_start <= curfp->l_start)) ||
15810 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15811 		return (1);
15812 	return (0);
15813 }
15814 
15815 /*
15816  * Determine what the intersecting lock region is, and add that to the
15817  * 'nl_llpp' locklist in increasing order (by l_start).
15818  */
15819 static void
15820 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15821     locklist_t **nl_llpp, vnode_t *vp)
15822 {
15823 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15824 	off64_t lost_flp_end, local_flp_end, len, start;
15825 
15826 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15827 
15828 	if (!locks_intersect(lost_flp, local_flp))
15829 		return;
15830 
15831 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15832 	    "locks intersect"));
15833 
15834 	lost_flp_end = lock_to_end(lost_flp);
15835 	local_flp_end = lock_to_end(local_flp);
15836 
15837 	/* Find the starting point of the intersecting region */
15838 	if (local_flp->l_start > lost_flp->l_start)
15839 		start = local_flp->l_start;
15840 	else
15841 		start = lost_flp->l_start;
15842 
15843 	/* Find the lenght of the intersecting region */
15844 	if (lost_flp_end < local_flp_end)
15845 		len = end_to_len(start, lost_flp_end);
15846 	else
15847 		len = end_to_len(start, local_flp_end);
15848 
15849 	/*
15850 	 * Prepare the flock structure for the intersection found and insert
15851 	 * it into the new list in increasing l_start order. This list contains
15852 	 * intersections of locks registered by the client with the local host
15853 	 * and the lost lock.
15854 	 * The lock type of this lock is the same as that of the local_flp.
15855 	 */
15856 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15857 	intersect_llp->ll_flock.l_start = start;
15858 	intersect_llp->ll_flock.l_len = len;
15859 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15860 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15861 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15862 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15863 	intersect_llp->ll_vp = vp;
15864 
15865 	tmp_fllp = *nl_llpp;
15866 	cur_fllp = NULL;
15867 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15868 	    intersect_llp->ll_flock.l_start) {
15869 			cur_fllp = tmp_fllp;
15870 			tmp_fllp = tmp_fllp->ll_next;
15871 	}
15872 	if (cur_fllp == NULL) {
15873 		/* first on the list */
15874 		intersect_llp->ll_next = *nl_llpp;
15875 		*nl_llpp = intersect_llp;
15876 	} else {
15877 		intersect_llp->ll_next = cur_fllp->ll_next;
15878 		cur_fllp->ll_next = intersect_llp;
15879 	}
15880 
15881 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15882 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15883 	    intersect_llp->ll_flock.l_start,
15884 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15885 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15886 }
15887 
15888 /*
15889  * Our local locking current state is potentially different than
15890  * what the NFSv4 server thinks we have due to a lost lock that was
15891  * resent and then received.  We need to reset our "NFSv4" locking
15892  * state to match the current local locking state for this pid since
15893  * that is what the user/application sees as what the world is.
15894  *
15895  * We cannot afford to drop the open/lock seqid sync since then we can
15896  * get confused about what the current local locking state "is" versus
15897  * "was".
15898  *
15899  * If we are unable to fix up the locks, we send SIGLOST to the affected
15900  * process.  This is not done if the filesystem has been forcibly
15901  * unmounted, in case the process has already exited and a new process
15902  * exists with the same pid.
15903  */
15904 static void
15905 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15906     nfs4_lock_owner_t *lop)
15907 {
15908 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15909 	mntinfo4_t *mi = VTOMI4(vp);
15910 	const int cmd = F_SETLK;
15911 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15912 	flock64_t ul_fl;
15913 
15914 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15915 	    "nfs4_reinstitute_local_lock_state"));
15916 
15917 	/*
15918 	 * Find active locks for this vp from the local locking code.
15919 	 * Scan through this list and find out the locks that intersect with
15920 	 * the lost lock. Once we find the lock that intersects, add the
15921 	 * intersection area as a new lock to a new list "ri_llp". The lock
15922 	 * type of the intersection region lock added to ri_llp is the same
15923 	 * as that found in the active lock list, "list". The intersecting
15924 	 * region locks are added to ri_llp in increasing l_start order.
15925 	 */
15926 	ASSERT(nfs_zone() == mi->mi_zone);
15927 
15928 	locks = flk_active_locks_for_vp(vp);
15929 	ri_llp = NULL;
15930 
15931 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15932 		ASSERT(llp->ll_vp == vp);
15933 		/*
15934 		 * Pick locks that belong to this pid/lockowner
15935 		 */
15936 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15937 			continue;
15938 
15939 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15940 	}
15941 
15942 	/*
15943 	 * Now we have the list of intersections with the lost lock. These are
15944 	 * the locks that were/are active before the server replied to the
15945 	 * last/lost lock. Issue these locks to the server here. Playing these
15946 	 * locks to the server will re-establish aur current local locking state
15947 	 * with the v4 server.
15948 	 * If we get an error, send SIGLOST to the application for that lock.
15949 	 */
15950 
15951 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15952 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15953 		    "nfs4_reinstitute_local_lock_state: need to issue "
15954 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15955 		    llp->ll_flock.l_start,
15956 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15957 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15958 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15959 		/*
15960 		 * No need to relock what we already have
15961 		 */
15962 		if (llp->ll_flock.l_type == lost_flp->l_type)
15963 			continue;
15964 
15965 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15966 	}
15967 
15968 	/*
15969 	 * Now keeping the start of the lost lock as our reference parse the
15970 	 * newly created ri_llp locklist to find the ranges that we have locked
15971 	 * with the v4 server but not in the current local locking. We need
15972 	 * to unlock these ranges.
15973 	 * These ranges can also be reffered to as those ranges, where the lost
15974 	 * lock does not overlap with the locks in the ri_llp but are locked
15975 	 * since the server replied to the lost lock.
15976 	 */
15977 	cur_start = lost_flp->l_start;
15978 	lost_flp_end = lock_to_end(lost_flp);
15979 
15980 	ul_fl.l_type = F_UNLCK;
15981 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15982 	ul_fl.l_sysid = lost_flp->l_sysid;
15983 	ul_fl.l_pid = lost_flp->l_pid;
15984 
15985 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15986 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15987 
15988 		if (llp->ll_flock.l_start <= cur_start) {
15989 			cur_start = start_check(llp_ll_flock_end);
15990 			continue;
15991 		}
15992 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15993 		    "nfs4_reinstitute_local_lock_state: "
15994 		    "UNLOCK [%"PRIx64" - %"PRIx64"]",
15995 		    cur_start, llp->ll_flock.l_start));
15996 
15997 		ul_fl.l_start = cur_start;
15998 		ul_fl.l_len = end_to_len(cur_start,
15999 		    (llp->ll_flock.l_start - 1));
16000 
16001 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
16002 		cur_start = start_check(llp_ll_flock_end);
16003 	}
16004 
16005 	/*
16006 	 * In the case where the lost lock ends after all intersecting locks,
16007 	 * unlock the last part of the lost lock range.
16008 	 */
16009 	if (cur_start != start_check(lost_flp_end)) {
16010 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
16011 		    "nfs4_reinstitute_local_lock_state: UNLOCK end of the "
16012 		    "lost lock region [%"PRIx64" - %"PRIx64"]",
16013 		    cur_start, lost_flp->l_start + lost_flp->l_len));
16014 
16015 		ul_fl.l_start = cur_start;
16016 		/*
16017 		 * Is it an to-EOF lock? if so unlock till the end
16018 		 */
16019 		if (lost_flp->l_len == 0)
16020 			ul_fl.l_len = 0;
16021 		else
16022 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
16023 
16024 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
16025 	}
16026 
16027 	if (locks != NULL)
16028 		flk_free_locklist(locks);
16029 
16030 	/* Free up our newly created locklist */
16031 	for (llp = ri_llp; llp != NULL; ) {
16032 		tmp_llp = llp->ll_next;
16033 		kmem_free(llp, sizeof (locklist_t));
16034 		llp = tmp_llp;
16035 	}
16036 
16037 	/*
16038 	 * Now return back to the original calling nfs4frlock()
16039 	 * and let us naturally drop our seqid syncs.
16040 	 */
16041 }
16042 
16043 /*
16044  * Create a lost state record for the given lock reinstantiation request
16045  * and push it onto the lost state queue.
16046  */
16047 static void
16048 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
16049     nfs4_lock_owner_t *lop)
16050 {
16051 	nfs4_lost_rqst_t req;
16052 	nfs_lock_type4 locktype;
16053 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
16054 
16055 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
16056 
16057 	locktype = flk_to_locktype(cmd, flk->l_type);
16058 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
16059 	    NULL, NULL, lop, flk, &req, cr, vp);
16060 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
16061 	    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
16062 	    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
16063 	    NULL, NULL, NULL);
16064 }
16065