xref: /titanic_44/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision 77b65ce69d04f1ba0eceb747081964672b718796)
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 			/*
1564 			 * Couldn't correct the attributes of
1565 			 * the newly created file and the
1566 			 * attributes are wrong.  Remove the
1567 			 * file and return an error to the
1568 			 * application.
1569 			 */
1570 			/* XXX will this take care of client state ? */
1571 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1572 			    "nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1573 			    " remove file", e.error));
1574 			VN_RELE(vp);
1575 			(void) nfs4_remove(dvp, file_name, cr, NULL, 0);
1576 			/*
1577 			 * Since we've reled the vnode and removed
1578 			 * the file we now need to return the error.
1579 			 * At this point we don't want to update the
1580 			 * dircaches, call nfs4_waitfor_purge_complete
1581 			 * or set vpp to vp so we need to skip these
1582 			 * as well.
1583 			 */
1584 			goto skip_update_dircaches;
1585 		}
1586 	}
1587 
1588 	/*
1589 	 * If we created or found the correct vnode, due to create_flag or
1590 	 * fh_differs being set, then update directory cache attribute, readdir
1591 	 * and dnlc caches.
1592 	 */
1593 	if (create_flag || fh_differs) {
1594 		dirattr_info_t dinfo, *dinfop;
1595 
1596 		/*
1597 		 * Make sure getattr succeeded before using results.
1598 		 * note: op 7 is getattr(dir) for both flavors of
1599 		 * open(create).
1600 		 */
1601 		if (create_flag && res.status == NFS4_OK) {
1602 			dinfo.di_time_call = t;
1603 			dinfo.di_cred = cr;
1604 			dinfo.di_garp =
1605 			    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
1606 			dinfop = &dinfo;
1607 		} else {
1608 			dinfop = NULL;
1609 		}
1610 
1611 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1612 		    dinfop);
1613 	}
1614 
1615 	/*
1616 	 * If the page cache for this file was flushed from actions
1617 	 * above, it was done asynchronously and if that is true,
1618 	 * there is a need to wait here for it to complete.  This must
1619 	 * be done outside of start_fop/end_fop.
1620 	 */
1621 	(void) nfs4_waitfor_purge_complete(vp);
1622 
1623 	/*
1624 	 * It is implicit that we are in the open case (create_flag == 0) since
1625 	 * fh_differs can only be set to a non-zero value in the open case.
1626 	 */
1627 	if (fh_differs != 0 && vpi != NULL)
1628 		VN_RELE(vpi);
1629 
1630 	/*
1631 	 * Be sure to set *vpp to the correct value before returning.
1632 	 */
1633 	*vpp = vp;
1634 
1635 skip_update_dircaches:
1636 
1637 	nfs4args_copen_free(open_args);
1638 	if (setgid_flag) {
1639 		nfs4args_verify_free(&argop[8]);
1640 		nfs4args_setattr_free(&argop[9]);
1641 	}
1642 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1643 
1644 	if (ncr)
1645 		crfree(ncr);
1646 	kmem_free(argop, argoplist_size);
1647 	return (e.error);
1648 }
1649 
1650 /*
1651  * Reopen an open instance.  cf. nfs4open_otw().
1652  *
1653  * Errors are returned by the nfs4_error_t parameter.
1654  * - ep->error contains an errno value or zero.
1655  * - if it is zero, ep->stat is set to an NFS status code, if any.
1656  *   If the file could not be reopened, but the caller should continue, the
1657  *   file is marked dead and no error values are returned.  If the caller
1658  *   should stop recovering open files and start over, either the ep->error
1659  *   value or ep->stat will indicate an error (either something that requires
1660  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1661  *   filehandles) may be handled silently by this routine.
1662  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1663  *   will be started, so the caller should not do it.
1664  *
1665  * Gotos:
1666  * - kill_file : reopen failed in such a fashion to constitute marking the
1667  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1668  *   is for cases where recovery is not possible.
1669  * - failed_reopen : same as above, except that the file has already been
1670  *   marked dead, so no need to do it again.
1671  * - bailout : reopen failed but we are able to recover and retry the reopen -
1672  *   either within this function immediately or via the calling function.
1673  */
1674 
1675 void
1676 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1677     open_claim_type4 claim, bool_t frc_use_claim_previous,
1678     bool_t is_recov)
1679 {
1680 	COMPOUND4args_clnt args;
1681 	COMPOUND4res_clnt res;
1682 	nfs_argop4 argop[4];
1683 	nfs_resop4 *resop;
1684 	OPEN4res *op_res = NULL;
1685 	OPEN4cargs *open_args;
1686 	GETFH4res *gf_res;
1687 	rnode4_t *rp = VTOR4(vp);
1688 	int doqueue = 1;
1689 	cred_t *cr = NULL, *cred_otw = NULL;
1690 	nfs4_open_owner_t *oop = NULL;
1691 	seqid4 seqid;
1692 	nfs4_ga_res_t *garp;
1693 	char fn[MAXNAMELEN];
1694 	nfs4_recov_state_t recov = {NULL, 0};
1695 	nfs4_lost_rqst_t lost_rqst;
1696 	mntinfo4_t *mi = VTOMI4(vp);
1697 	bool_t abort;
1698 	char *failed_msg = "";
1699 	int fh_different;
1700 	hrtime_t t;
1701 	nfs4_bseqid_entry_t *bsep = NULL;
1702 
1703 	ASSERT(nfs4_consistent_type(vp));
1704 	ASSERT(nfs_zone() == mi->mi_zone);
1705 
1706 	nfs4_error_zinit(ep);
1707 
1708 	/* this is the cred used to find the open owner */
1709 	cr = state_to_cred(osp);
1710 	if (cr == NULL) {
1711 		failed_msg = "Couldn't reopen: no cred";
1712 		goto kill_file;
1713 	}
1714 	/* use this cred for OTW operations */
1715 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1716 
1717 top:
1718 	nfs4_error_zinit(ep);
1719 
1720 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1721 		/* File system has been unmounted, quit */
1722 		ep->error = EIO;
1723 		failed_msg = "Couldn't reopen: file system has been unmounted";
1724 		goto kill_file;
1725 	}
1726 
1727 	oop = osp->os_open_owner;
1728 
1729 	ASSERT(oop != NULL);
1730 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1731 		failed_msg = "can't reopen: no open owner";
1732 		goto kill_file;
1733 	}
1734 	open_owner_hold(oop);
1735 
1736 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1737 	if (ep->error) {
1738 		open_owner_rele(oop);
1739 		oop = NULL;
1740 		goto bailout;
1741 	}
1742 
1743 	/*
1744 	 * If the rnode has a delegation and the delegation has been
1745 	 * recovered and the server didn't request a recall and the caller
1746 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1747 	 * recovery) and the rnode hasn't been marked dead, then install
1748 	 * the delegation stateid in the open stream.  Otherwise, proceed
1749 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1750 	 */
1751 	mutex_enter(&rp->r_statev4_lock);
1752 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1753 	    !rp->r_deleg_return_pending &&
1754 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1755 	    !rp->r_deleg_needs_recall &&
1756 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1757 	    !(rp->r_flags & R4RECOVERR)) {
1758 		mutex_enter(&osp->os_sync_lock);
1759 		osp->os_delegation = 1;
1760 		osp->open_stateid = rp->r_deleg_stateid;
1761 		mutex_exit(&osp->os_sync_lock);
1762 		mutex_exit(&rp->r_statev4_lock);
1763 		goto bailout;
1764 	}
1765 	mutex_exit(&rp->r_statev4_lock);
1766 
1767 	/*
1768 	 * If the file failed recovery, just quit.  This failure need not
1769 	 * affect other reopens, so don't return an error.
1770 	 */
1771 	mutex_enter(&rp->r_statelock);
1772 	if (rp->r_flags & R4RECOVERR) {
1773 		mutex_exit(&rp->r_statelock);
1774 		ep->error = 0;
1775 		goto failed_reopen;
1776 	}
1777 	mutex_exit(&rp->r_statelock);
1778 
1779 	/*
1780 	 * argop is empty here
1781 	 *
1782 	 * PUTFH, OPEN, GETATTR
1783 	 */
1784 	args.ctag = TAG_REOPEN;
1785 	args.array_len = 4;
1786 	args.array = argop;
1787 
1788 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1789 	    "nfs4_reopen: file is type %d, id %s",
1790 	    vp->v_type, rnode4info(VTOR4(vp))));
1791 
1792 	argop[0].argop = OP_CPUTFH;
1793 
1794 	if (claim != CLAIM_PREVIOUS) {
1795 		/*
1796 		 * if this is a file mount then
1797 		 * use the mntinfo parentfh
1798 		 */
1799 		argop[0].nfs_argop4_u.opcputfh.sfh =
1800 		    (vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1801 		    VTOSV(vp)->sv_dfh;
1802 	} else {
1803 		/* putfh fh to reopen */
1804 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1805 	}
1806 
1807 	argop[1].argop = OP_COPEN;
1808 	open_args = &argop[1].nfs_argop4_u.opcopen;
1809 	open_args->claim = claim;
1810 
1811 	if (claim == CLAIM_NULL) {
1812 
1813 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1814 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1815 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1816 			    (void *)vp);
1817 			failed_msg = "Couldn't reopen: vtoname failed for "
1818 			    "CLAIM_NULL";
1819 			/* nothing allocated yet */
1820 			goto kill_file;
1821 		}
1822 
1823 		open_args->open_claim4_u.cfile = fn;
1824 	} else if (claim == CLAIM_PREVIOUS) {
1825 
1826 		/*
1827 		 * We have two cases to deal with here:
1828 		 * 1) We're being called to reopen files in order to satisfy
1829 		 *    a lock operation request which requires us to explicitly
1830 		 *    reopen files which were opened under a delegation.  If
1831 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1832 		 *    that case, frc_use_claim_previous is TRUE and we must
1833 		 *    use the rnode's current delegation type (r_deleg_type).
1834 		 * 2) We're reopening files during some form of recovery.
1835 		 *    In this case, frc_use_claim_previous is FALSE and we
1836 		 *    use the delegation type appropriate for recovery
1837 		 *    (r_deleg_needs_recovery).
1838 		 */
1839 		mutex_enter(&rp->r_statev4_lock);
1840 		open_args->open_claim4_u.delegate_type =
1841 		    frc_use_claim_previous ?
1842 		    rp->r_deleg_type :
1843 		    rp->r_deleg_needs_recovery;
1844 		mutex_exit(&rp->r_statev4_lock);
1845 
1846 	} else if (claim == CLAIM_DELEGATE_CUR) {
1847 
1848 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1849 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1850 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1851 			    "with %m", (void *)vp);
1852 			failed_msg = "Couldn't reopen: vtoname failed for "
1853 			    "CLAIM_DELEGATE_CUR";
1854 			/* nothing allocated yet */
1855 			goto kill_file;
1856 		}
1857 
1858 		mutex_enter(&rp->r_statev4_lock);
1859 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1860 		    rp->r_deleg_stateid;
1861 		mutex_exit(&rp->r_statev4_lock);
1862 
1863 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1864 	}
1865 	open_args->opentype = OPEN4_NOCREATE;
1866 	open_args->owner.clientid = mi2clientid(mi);
1867 	open_args->owner.owner_len = sizeof (oop->oo_name);
1868 	open_args->owner.owner_val =
1869 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1870 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1871 	    open_args->owner.owner_len);
1872 	open_args->share_access = 0;
1873 	open_args->share_deny = 0;
1874 
1875 	mutex_enter(&osp->os_sync_lock);
1876 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1877 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1878 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1879 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1880 	    osp->os_share_acc_write, osp->os_open_ref_count,
1881 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1882 
1883 	if (osp->os_share_acc_read || osp->os_mmap_read)
1884 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1885 	if (osp->os_share_acc_write || osp->os_mmap_write)
1886 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1887 	if (osp->os_share_deny_read)
1888 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1889 	if (osp->os_share_deny_write)
1890 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1891 	mutex_exit(&osp->os_sync_lock);
1892 
1893 	seqid = nfs4_get_open_seqid(oop) + 1;
1894 	open_args->seqid = seqid;
1895 
1896 	/* Construct the getfh part of the compound */
1897 	argop[2].argop = OP_GETFH;
1898 
1899 	/* Construct the getattr part of the compound */
1900 	argop[3].argop = OP_GETATTR;
1901 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1902 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1903 
1904 	t = gethrtime();
1905 
1906 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1907 
1908 	if (ep->error) {
1909 		if (!is_recov && !frc_use_claim_previous &&
1910 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1911 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1912 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1913 			    cred_otw, vp, NULL, open_args);
1914 			abort = nfs4_start_recovery(ep,
1915 			    VTOMI4(vp), vp, NULL, NULL,
1916 			    lost_rqst.lr_op == OP_OPEN ?
1917 			    &lost_rqst : NULL, OP_OPEN, NULL, NULL, NULL);
1918 			nfs4args_copen_free(open_args);
1919 			goto bailout;
1920 		}
1921 
1922 		nfs4args_copen_free(open_args);
1923 
1924 		if (ep->error == EACCES && cred_otw != cr) {
1925 			crfree(cred_otw);
1926 			cred_otw = cr;
1927 			crhold(cred_otw);
1928 			nfs4_end_open_seqid_sync(oop);
1929 			open_owner_rele(oop);
1930 			oop = NULL;
1931 			goto top;
1932 		}
1933 		if (ep->error == ETIMEDOUT)
1934 			goto bailout;
1935 		failed_msg = "Couldn't reopen: rpc error";
1936 		goto kill_file;
1937 	}
1938 
1939 	if (nfs4_need_to_bump_seqid(&res))
1940 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1941 
1942 	switch (res.status) {
1943 	case NFS4_OK:
1944 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1945 			mutex_enter(&rp->r_statelock);
1946 			rp->r_delay_interval = 0;
1947 			mutex_exit(&rp->r_statelock);
1948 		}
1949 		break;
1950 	case NFS4ERR_BAD_SEQID:
1951 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1952 		    args.ctag, open_args->seqid);
1953 
1954 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1955 		    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1956 		    NULL, OP_OPEN, bsep, NULL, NULL);
1957 
1958 		nfs4args_copen_free(open_args);
1959 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1960 		nfs4_end_open_seqid_sync(oop);
1961 		open_owner_rele(oop);
1962 		oop = NULL;
1963 		kmem_free(bsep, sizeof (*bsep));
1964 
1965 		goto kill_file;
1966 	case NFS4ERR_NO_GRACE:
1967 		nfs4args_copen_free(open_args);
1968 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1969 		nfs4_end_open_seqid_sync(oop);
1970 		open_owner_rele(oop);
1971 		oop = NULL;
1972 		if (claim == CLAIM_PREVIOUS) {
1973 			/*
1974 			 * Retry as a plain open. We don't need to worry about
1975 			 * checking the changeinfo: it is acceptable for a
1976 			 * client to re-open a file and continue processing
1977 			 * (in the absence of locks).
1978 			 */
1979 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1980 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1981 			    "will retry as CLAIM_NULL"));
1982 			claim = CLAIM_NULL;
1983 			nfs4_mi_kstat_inc_no_grace(mi);
1984 			goto top;
1985 		}
1986 		failed_msg =
1987 		    "Couldn't reopen: tried reclaim outside grace period. ";
1988 		goto kill_file;
1989 	case NFS4ERR_GRACE:
1990 		nfs4_set_grace_wait(mi);
1991 		nfs4args_copen_free(open_args);
1992 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1993 		nfs4_end_open_seqid_sync(oop);
1994 		open_owner_rele(oop);
1995 		oop = NULL;
1996 		ep->error = nfs4_wait_for_grace(mi, &recov);
1997 		if (ep->error != 0)
1998 			goto bailout;
1999 		goto top;
2000 	case NFS4ERR_DELAY:
2001 		nfs4_set_delay_wait(vp);
2002 		nfs4args_copen_free(open_args);
2003 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2004 		nfs4_end_open_seqid_sync(oop);
2005 		open_owner_rele(oop);
2006 		oop = NULL;
2007 		ep->error = nfs4_wait_for_delay(vp, &recov);
2008 		nfs4_mi_kstat_inc_delay(mi);
2009 		if (ep->error != 0)
2010 			goto bailout;
2011 		goto top;
2012 	case NFS4ERR_FHEXPIRED:
2013 		/* recover filehandle and retry */
2014 		abort = nfs4_start_recovery(ep,
2015 		    mi, vp, NULL, NULL, NULL, OP_OPEN, NULL, NULL, NULL);
2016 		nfs4args_copen_free(open_args);
2017 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2018 		nfs4_end_open_seqid_sync(oop);
2019 		open_owner_rele(oop);
2020 		oop = NULL;
2021 		if (abort == FALSE)
2022 			goto top;
2023 		failed_msg = "Couldn't reopen: recovery aborted";
2024 		goto kill_file;
2025 	case NFS4ERR_RESOURCE:
2026 	case NFS4ERR_STALE_CLIENTID:
2027 	case NFS4ERR_WRONGSEC:
2028 	case NFS4ERR_EXPIRED:
2029 		/*
2030 		 * Do not mark the file dead and let the calling
2031 		 * function initiate recovery.
2032 		 */
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 		goto bailout;
2039 	case NFS4ERR_ACCESS:
2040 		if (cred_otw != cr) {
2041 			crfree(cred_otw);
2042 			cred_otw = cr;
2043 			crhold(cred_otw);
2044 			nfs4args_copen_free(open_args);
2045 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2046 			nfs4_end_open_seqid_sync(oop);
2047 			open_owner_rele(oop);
2048 			oop = NULL;
2049 			goto top;
2050 		}
2051 		/* fall through */
2052 	default:
2053 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2054 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2055 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2056 		    rnode4info(VTOR4(vp))));
2057 		failed_msg = "Couldn't reopen: NFSv4 error";
2058 		nfs4args_copen_free(open_args);
2059 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2060 		goto kill_file;
2061 	}
2062 
2063 	resop = &res.array[1];  /* open res */
2064 	op_res = &resop->nfs_resop4_u.opopen;
2065 
2066 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2067 
2068 	/*
2069 	 * Check if the path we reopened really is the same
2070 	 * file. We could end up in a situation where the file
2071 	 * was removed and a new file created with the same name.
2072 	 */
2073 	resop = &res.array[2];
2074 	gf_res = &resop->nfs_resop4_u.opgetfh;
2075 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2076 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2077 	if (fh_different) {
2078 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2079 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2080 			/* Oops, we don't have the same file */
2081 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2082 				failed_msg = "Couldn't reopen: Persistent "
2083 				    "file handle changed";
2084 			else
2085 				failed_msg = "Couldn't reopen: Volatile "
2086 				    "(no expire on open) file handle changed";
2087 
2088 			nfs4args_copen_free(open_args);
2089 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2090 			nfs_rw_exit(&mi->mi_fh_lock);
2091 			goto kill_file;
2092 
2093 		} else {
2094 			/*
2095 			 * We have volatile file handles that don't compare.
2096 			 * If the fids are the same then we assume that the
2097 			 * file handle expired but the rnode still refers to
2098 			 * the same file object.
2099 			 *
2100 			 * First check that we have fids or not.
2101 			 * If we don't we have a dumb server so we will
2102 			 * just assume every thing is ok for now.
2103 			 */
2104 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2105 			    rp->r_attr.va_mask & AT_NODEID &&
2106 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2107 				/*
2108 				 * We have fids, but they don't
2109 				 * compare. So kill the file.
2110 				 */
2111 				failed_msg =
2112 				    "Couldn't reopen: file handle changed"
2113 				    " due to mismatched fids";
2114 				nfs4args_copen_free(open_args);
2115 				(void) xdr_free(xdr_COMPOUND4res_clnt,
2116 				    (caddr_t)&res);
2117 				nfs_rw_exit(&mi->mi_fh_lock);
2118 				goto kill_file;
2119 			} else {
2120 				/*
2121 				 * We have volatile file handles that refers
2122 				 * to the same file (at least they have the
2123 				 * same fid) or we don't have fids so we
2124 				 * can't tell. :(. We'll be a kind and accepting
2125 				 * client so we'll update the rnode's file
2126 				 * handle with the otw handle.
2127 				 *
2128 				 * We need to drop mi->mi_fh_lock since
2129 				 * sh4_update acquires it. Since there is
2130 				 * only one recovery thread there is no
2131 				 * race.
2132 				 */
2133 				nfs_rw_exit(&mi->mi_fh_lock);
2134 				sfh4_update(rp->r_fh, &gf_res->object);
2135 			}
2136 		}
2137 	} else {
2138 		nfs_rw_exit(&mi->mi_fh_lock);
2139 	}
2140 
2141 	ASSERT(nfs4_consistent_type(vp));
2142 
2143 	/*
2144 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2145 	 * over.  Presumably if there is a persistent error it will show up
2146 	 * when we resend the OPEN.
2147 	 */
2148 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2149 		bool_t retry_open = FALSE;
2150 
2151 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2152 		    cred_otw, is_recov, &retry_open,
2153 		    oop, FALSE, ep, NULL);
2154 		if (ep->error || ep->stat) {
2155 			nfs4args_copen_free(open_args);
2156 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2157 			nfs4_end_open_seqid_sync(oop);
2158 			open_owner_rele(oop);
2159 			oop = NULL;
2160 			goto top;
2161 		}
2162 	}
2163 
2164 	mutex_enter(&osp->os_sync_lock);
2165 	osp->open_stateid = op_res->stateid;
2166 	osp->os_delegation = 0;
2167 	/*
2168 	 * Need to reset this bitfield for the possible case where we were
2169 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2170 	 * we could retry the CLOSE, OPENed the file again.
2171 	 */
2172 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2173 	osp->os_final_close = 0;
2174 	osp->os_force_close = 0;
2175 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2176 		osp->os_dc_openacc = open_args->share_access;
2177 	mutex_exit(&osp->os_sync_lock);
2178 
2179 	nfs4_end_open_seqid_sync(oop);
2180 
2181 	/* accept delegation, if any */
2182 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2183 
2184 	nfs4args_copen_free(open_args);
2185 
2186 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2187 
2188 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2189 
2190 	ASSERT(nfs4_consistent_type(vp));
2191 
2192 	open_owner_rele(oop);
2193 	crfree(cr);
2194 	crfree(cred_otw);
2195 	return;
2196 
2197 kill_file:
2198 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2199 failed_reopen:
2200 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2201 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2202 	    (void *)osp, (void *)cr, rnode4info(rp)));
2203 	mutex_enter(&osp->os_sync_lock);
2204 	osp->os_failed_reopen = 1;
2205 	mutex_exit(&osp->os_sync_lock);
2206 bailout:
2207 	if (oop != NULL) {
2208 		nfs4_end_open_seqid_sync(oop);
2209 		open_owner_rele(oop);
2210 	}
2211 	if (cr != NULL)
2212 		crfree(cr);
2213 	if (cred_otw != NULL)
2214 		crfree(cred_otw);
2215 }
2216 
2217 /* for . and .. OPENs */
2218 /* ARGSUSED */
2219 static int
2220 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2221 {
2222 	rnode4_t *rp;
2223 	nfs4_ga_res_t gar;
2224 
2225 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2226 
2227 	/*
2228 	 * If close-to-open consistency checking is turned off or
2229 	 * if there is no cached data, we can avoid
2230 	 * the over the wire getattr.  Otherwise, force a
2231 	 * call to the server to get fresh attributes and to
2232 	 * check caches. This is required for close-to-open
2233 	 * consistency.
2234 	 */
2235 	rp = VTOR4(*vpp);
2236 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2237 	    (rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2238 		return (0);
2239 
2240 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2241 }
2242 
2243 /*
2244  * CLOSE a file
2245  */
2246 /* ARGSUSED */
2247 static int
2248 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
2249     caller_context_t *ct)
2250 {
2251 	rnode4_t	*rp;
2252 	int		 error = 0;
2253 	int		 r_error = 0;
2254 	int		 n4error = 0;
2255 	nfs4_error_t	 e = { 0, NFS4_OK, RPC_SUCCESS };
2256 
2257 	/*
2258 	 * Remove client state for this (lockowner, file) pair.
2259 	 * Issue otw v4 call to have the server do the same.
2260 	 */
2261 
2262 	rp = VTOR4(vp);
2263 
2264 	/*
2265 	 * zone_enter(2) prevents processes from changing zones with NFS files
2266 	 * open; if we happen to get here from the wrong zone we can't do
2267 	 * anything over the wire.
2268 	 */
2269 	if (VTOMI4(vp)->mi_zone != nfs_zone()) {
2270 		/*
2271 		 * We could attempt to clean up locks, except we're sure
2272 		 * that the current process didn't acquire any locks on
2273 		 * the file: any attempt to lock a file belong to another zone
2274 		 * will fail, and one can't lock an NFS file and then change
2275 		 * zones, as that fails too.
2276 		 *
2277 		 * Returning an error here is the sane thing to do.  A
2278 		 * subsequent call to VN_RELE() which translates to a
2279 		 * nfs4_inactive() will clean up state: if the zone of the
2280 		 * vnode's origin is still alive and kicking, the inactive
2281 		 * thread will handle the request (from the correct zone), and
2282 		 * everything (minus the OTW close call) should be OK.  If the
2283 		 * zone is going away nfs4_async_inactive() will throw away
2284 		 * delegations, open streams and cached pages inline.
2285 		 */
2286 		return (EIO);
2287 	}
2288 
2289 	/*
2290 	 * If we are using local locking for this filesystem, then
2291 	 * release all of the SYSV style record locks.  Otherwise,
2292 	 * we are doing network locking and we need to release all
2293 	 * of the network locks.  All of the locks held by this
2294 	 * process on this file are released no matter what the
2295 	 * incoming reference count is.
2296 	 */
2297 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK) {
2298 		cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
2299 		cleanshares(vp, ttoproc(curthread)->p_pid);
2300 	} else
2301 		e.error = nfs4_lockrelease(vp, flag, offset, cr);
2302 
2303 	if (e.error) {
2304 		struct lm_sysid *lmsid;
2305 		lmsid = nfs4_find_sysid(VTOMI4(vp));
2306 		if (lmsid == NULL) {
2307 			DTRACE_PROBE2(unknown__sysid, int, e.error,
2308 			    vnode_t *, vp);
2309 		} else {
2310 			cleanlocks(vp, ttoproc(curthread)->p_pid,
2311 			    (lm_sysidt(lmsid) | LM_SYSID_CLIENT));
2312 
2313 			lm_rel_sysid(lmsid);
2314 		}
2315 		return (e.error);
2316 	}
2317 
2318 	if (count > 1)
2319 		return (0);
2320 
2321 	/*
2322 	 * If the file has been `unlinked', then purge the
2323 	 * DNLC so that this vnode will get reycled quicker
2324 	 * and the .nfs* file on the server will get removed.
2325 	 */
2326 	if (rp->r_unldvp != NULL)
2327 		dnlc_purge_vp(vp);
2328 
2329 	/*
2330 	 * If the file was open for write and there are pages,
2331 	 * do a synchronous flush and commit of all of the
2332 	 * dirty and uncommitted pages.
2333 	 */
2334 	ASSERT(!e.error);
2335 	if ((flag & FWRITE) && nfs4_has_pages(vp))
2336 		error = nfs4_putpage_commit(vp, 0, 0, cr);
2337 
2338 	mutex_enter(&rp->r_statelock);
2339 	r_error = rp->r_error;
2340 	rp->r_error = 0;
2341 	mutex_exit(&rp->r_statelock);
2342 
2343 	/*
2344 	 * If this file type is one for which no explicit 'open' was
2345 	 * done, then bail now (ie. no need for protocol 'close'). If
2346 	 * there was an error w/the vm subsystem, return _that_ error,
2347 	 * otherwise, return any errors that may've been reported via
2348 	 * the rnode.
2349 	 */
2350 	if (vp->v_type != VREG)
2351 		return (error ? error : r_error);
2352 
2353 	/*
2354 	 * The sync putpage commit may have failed above, but since
2355 	 * we're working w/a regular file, we need to do the protocol
2356 	 * 'close' (nfs4close_one will figure out if an otw close is
2357 	 * needed or not). Report any errors _after_ doing the protocol
2358 	 * 'close'.
2359 	 */
2360 	nfs4close_one(vp, NULL, cr, flag, NULL, &e, CLOSE_NORM, 0, 0, 0);
2361 	n4error = e.error ? e.error : geterrno4(e.stat);
2362 
2363 	/*
2364 	 * Error reporting prio (Hi -> Lo)
2365 	 *
2366 	 *   i) nfs4_putpage_commit (error)
2367 	 *  ii) rnode's (r_error)
2368 	 * iii) nfs4close_one (n4error)
2369 	 */
2370 	return (error ? error : (r_error ? r_error : n4error));
2371 }
2372 
2373 /*
2374  * Initialize *lost_rqstp.
2375  */
2376 
2377 static void
2378 nfs4close_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
2379     nfs4_open_owner_t *oop, nfs4_open_stream_t *osp, cred_t *cr,
2380     vnode_t *vp)
2381 {
2382 	if (error != ETIMEDOUT && error != EINTR &&
2383 	    !NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
2384 		lost_rqstp->lr_op = 0;
2385 		return;
2386 	}
2387 
2388 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
2389 	    "nfs4close_save_lost_rqst: error %d", error));
2390 
2391 	lost_rqstp->lr_op = OP_CLOSE;
2392 	/*
2393 	 * The vp is held and rele'd via the recovery code.
2394 	 * See nfs4_save_lost_rqst.
2395 	 */
2396 	lost_rqstp->lr_vp = vp;
2397 	lost_rqstp->lr_dvp = NULL;
2398 	lost_rqstp->lr_oop = oop;
2399 	lost_rqstp->lr_osp = osp;
2400 	ASSERT(osp != NULL);
2401 	ASSERT(mutex_owned(&osp->os_sync_lock));
2402 	osp->os_pending_close = 1;
2403 	lost_rqstp->lr_lop = NULL;
2404 	lost_rqstp->lr_cr = cr;
2405 	lost_rqstp->lr_flk = NULL;
2406 	lost_rqstp->lr_putfirst = FALSE;
2407 }
2408 
2409 /*
2410  * Assumes you already have the open seqid sync grabbed as well as the
2411  * 'os_sync_lock'.  Note: this will release the open seqid sync and
2412  * 'os_sync_lock' if client recovery starts.  Calling functions have to
2413  * be prepared to handle this.
2414  *
2415  * 'recov' is returned as 1 if the CLOSE operation detected client recovery
2416  * was needed and was started, and that the calling function should retry
2417  * this function; otherwise it is returned as 0.
2418  *
2419  * Errors are returned via the nfs4_error_t parameter.
2420  */
2421 static void
2422 nfs4close_otw(rnode4_t *rp, cred_t *cred_otw, nfs4_open_owner_t *oop,
2423     nfs4_open_stream_t *osp, int *recov, int *did_start_seqid_syncp,
2424     nfs4_close_type_t close_type, nfs4_error_t *ep, int *have_sync_lockp)
2425 {
2426 	COMPOUND4args_clnt args;
2427 	COMPOUND4res_clnt res;
2428 	CLOSE4args *close_args;
2429 	nfs_resop4 *resop;
2430 	nfs_argop4 argop[3];
2431 	int doqueue = 1;
2432 	mntinfo4_t *mi;
2433 	seqid4 seqid;
2434 	vnode_t *vp;
2435 	bool_t needrecov = FALSE;
2436 	nfs4_lost_rqst_t lost_rqst;
2437 	hrtime_t t;
2438 
2439 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
2440 
2441 	ASSERT(MUTEX_HELD(&osp->os_sync_lock));
2442 
2443 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw"));
2444 
2445 	/* Only set this to 1 if recovery is started */
2446 	*recov = 0;
2447 
2448 	/* do the OTW call to close the file */
2449 
2450 	if (close_type == CLOSE_RESEND)
2451 		args.ctag = TAG_CLOSE_LOST;
2452 	else if (close_type == CLOSE_AFTER_RESEND)
2453 		args.ctag = TAG_CLOSE_UNDO;
2454 	else
2455 		args.ctag = TAG_CLOSE;
2456 
2457 	args.array_len = 3;
2458 	args.array = argop;
2459 
2460 	vp = RTOV4(rp);
2461 
2462 	mi = VTOMI4(vp);
2463 
2464 	/* putfh target fh */
2465 	argop[0].argop = OP_CPUTFH;
2466 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
2467 
2468 	argop[1].argop = OP_GETATTR;
2469 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
2470 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
2471 
2472 	argop[2].argop = OP_CLOSE;
2473 	close_args = &argop[2].nfs_argop4_u.opclose;
2474 
2475 	seqid = nfs4_get_open_seqid(oop) + 1;
2476 
2477 	close_args->seqid = seqid;
2478 	close_args->open_stateid = osp->open_stateid;
2479 
2480 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
2481 	    "nfs4close_otw: %s call, rp %s", needrecov ? "recov" : "first",
2482 	    rnode4info(rp)));
2483 
2484 	t = gethrtime();
2485 
2486 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
2487 
2488 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
2489 		nfs4_set_open_seqid(seqid, oop, args.ctag);
2490 	}
2491 
2492 	needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
2493 	if (ep->error && !needrecov) {
2494 		/*
2495 		 * if there was an error and no recovery is to be done
2496 		 * then then set up the file to flush its cache if
2497 		 * needed for the next caller.
2498 		 */
2499 		mutex_enter(&rp->r_statelock);
2500 		PURGE_ATTRCACHE4_LOCKED(rp);
2501 		rp->r_flags &= ~R4WRITEMODIFIED;
2502 		mutex_exit(&rp->r_statelock);
2503 		return;
2504 	}
2505 
2506 	if (needrecov) {
2507 		bool_t abort;
2508 		nfs4_bseqid_entry_t *bsep = NULL;
2509 
2510 		if (close_type != CLOSE_RESEND)
2511 			nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
2512 			    osp, cred_otw, vp);
2513 
2514 		if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
2515 			bsep = nfs4_create_bseqid_entry(oop, NULL, vp,
2516 			    0, args.ctag, close_args->seqid);
2517 
2518 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
2519 		    "nfs4close_otw: initiating recovery. error %d "
2520 		    "res.status %d", ep->error, res.status));
2521 
2522 		/*
2523 		 * Drop the 'os_sync_lock' here so we don't hit
2524 		 * a potential recursive mutex_enter via an
2525 		 * 'open_stream_hold()'.
2526 		 */
2527 		mutex_exit(&osp->os_sync_lock);
2528 		*have_sync_lockp = 0;
2529 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
2530 		    (close_type != CLOSE_RESEND &&
2531 		    lost_rqst.lr_op == OP_CLOSE) ? &lost_rqst : NULL,
2532 		    OP_CLOSE, bsep, NULL, NULL);
2533 
2534 		/* drop open seq sync, and let the calling function regrab it */
2535 		nfs4_end_open_seqid_sync(oop);
2536 		*did_start_seqid_syncp = 0;
2537 
2538 		if (bsep)
2539 			kmem_free(bsep, sizeof (*bsep));
2540 		/*
2541 		 * For signals, the caller wants to quit, so don't say to
2542 		 * retry.  For forced unmount, if it's a user thread, it
2543 		 * wants to quit.  If it's a recovery thread, the retry
2544 		 * will happen higher-up on the call stack.  Either way,
2545 		 * don't say to retry.
2546 		 */
2547 		if (abort == FALSE && ep->error != EINTR &&
2548 		    !NFS4_FRC_UNMT_ERR(ep->error, mi->mi_vfsp) &&
2549 		    close_type != CLOSE_RESEND &&
2550 		    close_type != CLOSE_AFTER_RESEND)
2551 			*recov = 1;
2552 		else
2553 			*recov = 0;
2554 
2555 		if (!ep->error)
2556 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2557 		return;
2558 	}
2559 
2560 	if (res.status) {
2561 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2562 		return;
2563 	}
2564 
2565 	mutex_enter(&rp->r_statev4_lock);
2566 	rp->created_v4 = 0;
2567 	mutex_exit(&rp->r_statev4_lock);
2568 
2569 	resop = &res.array[2];
2570 	osp->open_stateid = resop->nfs_resop4_u.opclose.open_stateid;
2571 	osp->os_valid = 0;
2572 
2573 	/*
2574 	 * This removes the reference obtained at OPEN; ie, when the
2575 	 * open stream structure was created.
2576 	 *
2577 	 * We don't have to worry about calling 'open_stream_rele'
2578 	 * since we our currently holding a reference to the open
2579 	 * stream which means the count cannot go to 0 with this
2580 	 * decrement.
2581 	 */
2582 	ASSERT(osp->os_ref_count >= 2);
2583 	osp->os_ref_count--;
2584 
2585 	if (ep->error == 0) {
2586 		/*
2587 		 * Avoid a deadlock with the r_serial thread waiting for
2588 		 * os_sync_lock in nfs4_get_otw_cred_by_osp() which might be
2589 		 * held by us. We will wait in nfs4_attr_cache() for the
2590 		 * completion of the r_serial thread.
2591 		 */
2592 		mutex_exit(&osp->os_sync_lock);
2593 		*have_sync_lockp = 0;
2594 
2595 		nfs4_attr_cache(vp,
2596 		    &res.array[1].nfs_resop4_u.opgetattr.ga_res,
2597 		    t, cred_otw, TRUE, NULL);
2598 	}
2599 
2600 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw:"
2601 	    " returning %d", ep->error));
2602 
2603 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2604 }
2605 
2606 /* ARGSUSED */
2607 static int
2608 nfs4_read(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2609     caller_context_t *ct)
2610 {
2611 	rnode4_t *rp;
2612 	u_offset_t off;
2613 	offset_t diff;
2614 	uint_t on;
2615 	uint_t n;
2616 	caddr_t base;
2617 	uint_t flags;
2618 	int error;
2619 	mntinfo4_t *mi;
2620 
2621 	rp = VTOR4(vp);
2622 
2623 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2624 
2625 	if (IS_SHADOW(vp, rp))
2626 		vp = RTOV4(rp);
2627 
2628 	if (vp->v_type != VREG)
2629 		return (EISDIR);
2630 
2631 	mi = VTOMI4(vp);
2632 
2633 	if (nfs_zone() != mi->mi_zone)
2634 		return (EIO);
2635 
2636 	if (uiop->uio_resid == 0)
2637 		return (0);
2638 
2639 	if (uiop->uio_loffset < 0 || uiop->uio_loffset + uiop->uio_resid < 0)
2640 		return (EINVAL);
2641 
2642 	mutex_enter(&rp->r_statelock);
2643 	if (rp->r_flags & R4RECOVERRP)
2644 		error = (rp->r_error ? rp->r_error : EIO);
2645 	else
2646 		error = 0;
2647 	mutex_exit(&rp->r_statelock);
2648 	if (error)
2649 		return (error);
2650 
2651 	/*
2652 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2653 	 * using client-side direct I/O and the file is not mmap'd and
2654 	 * there are no cached pages.
2655 	 */
2656 	if ((vp->v_flag & VNOCACHE) ||
2657 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2658 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2659 		size_t resid = 0;
2660 
2661 		return (nfs4read(vp, NULL, uiop->uio_loffset,
2662 		    uiop->uio_resid, &resid, cr, FALSE, uiop));
2663 	}
2664 
2665 	error = 0;
2666 
2667 	do {
2668 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2669 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2670 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2671 
2672 		if (error = nfs4_validate_caches(vp, cr))
2673 			break;
2674 
2675 		mutex_enter(&rp->r_statelock);
2676 		while (rp->r_flags & R4INCACHEPURGE) {
2677 			if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2678 				mutex_exit(&rp->r_statelock);
2679 				return (EINTR);
2680 			}
2681 		}
2682 		diff = rp->r_size - uiop->uio_loffset;
2683 		mutex_exit(&rp->r_statelock);
2684 		if (diff <= 0)
2685 			break;
2686 		if (diff < n)
2687 			n = (uint_t)diff;
2688 
2689 		if (vpm_enable) {
2690 			/*
2691 			 * Copy data.
2692 			 */
2693 			error = vpm_data_copy(vp, off + on, n, uiop,
2694 			    1, NULL, 0, S_READ);
2695 		} else {
2696 			base = segmap_getmapflt(segkmap, vp, off + on, n, 1,
2697 			    S_READ);
2698 
2699 			error = uiomove(base + on, n, UIO_READ, uiop);
2700 		}
2701 
2702 		if (!error) {
2703 			/*
2704 			 * If read a whole block or read to eof,
2705 			 * won't need this buffer again soon.
2706 			 */
2707 			mutex_enter(&rp->r_statelock);
2708 			if (n + on == MAXBSIZE ||
2709 			    uiop->uio_loffset == rp->r_size)
2710 				flags = SM_DONTNEED;
2711 			else
2712 				flags = 0;
2713 			mutex_exit(&rp->r_statelock);
2714 			if (vpm_enable) {
2715 				error = vpm_sync_pages(vp, off, n, flags);
2716 			} else {
2717 				error = segmap_release(segkmap, base, flags);
2718 			}
2719 		} else {
2720 			if (vpm_enable) {
2721 				(void) vpm_sync_pages(vp, off, n, 0);
2722 			} else {
2723 				(void) segmap_release(segkmap, base, 0);
2724 			}
2725 		}
2726 	} while (!error && uiop->uio_resid > 0);
2727 
2728 	return (error);
2729 }
2730 
2731 /* ARGSUSED */
2732 static int
2733 nfs4_write(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2734     caller_context_t *ct)
2735 {
2736 	rlim64_t limit = uiop->uio_llimit;
2737 	rnode4_t *rp;
2738 	u_offset_t off;
2739 	caddr_t base;
2740 	uint_t flags;
2741 	int remainder;
2742 	size_t n;
2743 	int on;
2744 	int error;
2745 	int resid;
2746 	u_offset_t offset;
2747 	mntinfo4_t *mi;
2748 	uint_t bsize;
2749 
2750 	rp = VTOR4(vp);
2751 
2752 	if (IS_SHADOW(vp, rp))
2753 		vp = RTOV4(rp);
2754 
2755 	if (vp->v_type != VREG)
2756 		return (EISDIR);
2757 
2758 	mi = VTOMI4(vp);
2759 
2760 	if (nfs_zone() != mi->mi_zone)
2761 		return (EIO);
2762 
2763 	if (uiop->uio_resid == 0)
2764 		return (0);
2765 
2766 	mutex_enter(&rp->r_statelock);
2767 	if (rp->r_flags & R4RECOVERRP)
2768 		error = (rp->r_error ? rp->r_error : EIO);
2769 	else
2770 		error = 0;
2771 	mutex_exit(&rp->r_statelock);
2772 	if (error)
2773 		return (error);
2774 
2775 	if (ioflag & FAPPEND) {
2776 		struct vattr va;
2777 
2778 		/*
2779 		 * Must serialize if appending.
2780 		 */
2781 		if (nfs_rw_lock_held(&rp->r_rwlock, RW_READER)) {
2782 			nfs_rw_exit(&rp->r_rwlock);
2783 			if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER,
2784 			    INTR4(vp)))
2785 				return (EINTR);
2786 		}
2787 
2788 		va.va_mask = AT_SIZE;
2789 		error = nfs4getattr(vp, &va, cr);
2790 		if (error)
2791 			return (error);
2792 		uiop->uio_loffset = va.va_size;
2793 	}
2794 
2795 	offset = uiop->uio_loffset + uiop->uio_resid;
2796 
2797 	if (uiop->uio_loffset < (offset_t)0 || offset < 0)
2798 		return (EINVAL);
2799 
2800 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
2801 		limit = MAXOFFSET_T;
2802 
2803 	/*
2804 	 * Check to make sure that the process will not exceed
2805 	 * its limit on file size.  It is okay to write up to
2806 	 * the limit, but not beyond.  Thus, the write which
2807 	 * reaches the limit will be short and the next write
2808 	 * will return an error.
2809 	 */
2810 	remainder = 0;
2811 	if (offset > uiop->uio_llimit) {
2812 		remainder = offset - uiop->uio_llimit;
2813 		uiop->uio_resid = uiop->uio_llimit - uiop->uio_loffset;
2814 		if (uiop->uio_resid <= 0) {
2815 			proc_t *p = ttoproc(curthread);
2816 
2817 			uiop->uio_resid += remainder;
2818 			mutex_enter(&p->p_lock);
2819 			(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE],
2820 			    p->p_rctls, p, RCA_UNSAFE_SIGINFO);
2821 			mutex_exit(&p->p_lock);
2822 			return (EFBIG);
2823 		}
2824 	}
2825 
2826 	/* update the change attribute, if we have a write delegation */
2827 
2828 	mutex_enter(&rp->r_statev4_lock);
2829 	if (rp->r_deleg_type == OPEN_DELEGATE_WRITE)
2830 		rp->r_deleg_change++;
2831 
2832 	mutex_exit(&rp->r_statev4_lock);
2833 
2834 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, INTR4(vp)))
2835 		return (EINTR);
2836 
2837 	/*
2838 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2839 	 * using client-side direct I/O and the file is not mmap'd and
2840 	 * there are no cached pages.
2841 	 */
2842 	if ((vp->v_flag & VNOCACHE) ||
2843 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2844 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2845 		size_t bufsize;
2846 		int count;
2847 		u_offset_t org_offset;
2848 		stable_how4 stab_comm;
2849 nfs4_fwrite:
2850 		if (rp->r_flags & R4STALE) {
2851 			resid = uiop->uio_resid;
2852 			offset = uiop->uio_loffset;
2853 			error = rp->r_error;
2854 			/*
2855 			 * A close may have cleared r_error, if so,
2856 			 * propagate ESTALE error return properly
2857 			 */
2858 			if (error == 0)
2859 				error = ESTALE;
2860 			goto bottom;
2861 		}
2862 
2863 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2864 		base = kmem_alloc(bufsize, KM_SLEEP);
2865 		do {
2866 			if (ioflag & FDSYNC)
2867 				stab_comm = DATA_SYNC4;
2868 			else
2869 				stab_comm = FILE_SYNC4;
2870 			resid = uiop->uio_resid;
2871 			offset = uiop->uio_loffset;
2872 			count = MIN(uiop->uio_resid, bufsize);
2873 			org_offset = uiop->uio_loffset;
2874 			error = uiomove(base, count, UIO_WRITE, uiop);
2875 			if (!error) {
2876 				error = nfs4write(vp, base, org_offset,
2877 				    count, cr, &stab_comm);
2878 				if (!error) {
2879 					mutex_enter(&rp->r_statelock);
2880 					if (rp->r_size < uiop->uio_loffset)
2881 						rp->r_size = uiop->uio_loffset;
2882 					mutex_exit(&rp->r_statelock);
2883 				}
2884 			}
2885 		} while (!error && uiop->uio_resid > 0);
2886 		kmem_free(base, bufsize);
2887 		goto bottom;
2888 	}
2889 
2890 	bsize = vp->v_vfsp->vfs_bsize;
2891 
2892 	do {
2893 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2894 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2895 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2896 
2897 		resid = uiop->uio_resid;
2898 		offset = uiop->uio_loffset;
2899 
2900 		if (rp->r_flags & R4STALE) {
2901 			error = rp->r_error;
2902 			/*
2903 			 * A close may have cleared r_error, if so,
2904 			 * propagate ESTALE error return properly
2905 			 */
2906 			if (error == 0)
2907 				error = ESTALE;
2908 			break;
2909 		}
2910 
2911 		/*
2912 		 * Don't create dirty pages faster than they
2913 		 * can be cleaned so that the system doesn't
2914 		 * get imbalanced.  If the async queue is
2915 		 * maxed out, then wait for it to drain before
2916 		 * creating more dirty pages.  Also, wait for
2917 		 * any threads doing pagewalks in the vop_getattr
2918 		 * entry points so that they don't block for
2919 		 * long periods.
2920 		 */
2921 		mutex_enter(&rp->r_statelock);
2922 		while ((mi->mi_max_threads != 0 &&
2923 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2924 		    rp->r_gcount > 0) {
2925 			if (INTR4(vp)) {
2926 				klwp_t *lwp = ttolwp(curthread);
2927 
2928 				if (lwp != NULL)
2929 					lwp->lwp_nostop++;
2930 				if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2931 					mutex_exit(&rp->r_statelock);
2932 					if (lwp != NULL)
2933 						lwp->lwp_nostop--;
2934 					error = EINTR;
2935 					goto bottom;
2936 				}
2937 				if (lwp != NULL)
2938 					lwp->lwp_nostop--;
2939 			} else
2940 				cv_wait(&rp->r_cv, &rp->r_statelock);
2941 		}
2942 		mutex_exit(&rp->r_statelock);
2943 
2944 		/*
2945 		 * Touch the page and fault it in if it is not in core
2946 		 * before segmap_getmapflt or vpm_data_copy can lock it.
2947 		 * This is to avoid the deadlock if the buffer is mapped
2948 		 * to the same file through mmap which we want to write.
2949 		 */
2950 		uio_prefaultpages((long)n, uiop);
2951 
2952 		if (vpm_enable) {
2953 			/*
2954 			 * It will use kpm mappings, so no need to
2955 			 * pass an address.
2956 			 */
2957 			error = writerp4(rp, NULL, n, uiop, 0);
2958 		} else  {
2959 			if (segmap_kpm) {
2960 				int pon = uiop->uio_loffset & PAGEOFFSET;
2961 				size_t pn = MIN(PAGESIZE - pon,
2962 				    uiop->uio_resid);
2963 				int pagecreate;
2964 
2965 				mutex_enter(&rp->r_statelock);
2966 				pagecreate = (pon == 0) && (pn == PAGESIZE ||
2967 				    uiop->uio_loffset + pn >= rp->r_size);
2968 				mutex_exit(&rp->r_statelock);
2969 
2970 				base = segmap_getmapflt(segkmap, vp, off + on,
2971 				    pn, !pagecreate, S_WRITE);
2972 
2973 				error = writerp4(rp, base + pon, n, uiop,
2974 				    pagecreate);
2975 
2976 			} else {
2977 				base = segmap_getmapflt(segkmap, vp, off + on,
2978 				    n, 0, S_READ);
2979 				error = writerp4(rp, base + on, n, uiop, 0);
2980 			}
2981 		}
2982 
2983 		if (!error) {
2984 			if (mi->mi_flags & MI4_NOAC)
2985 				flags = SM_WRITE;
2986 			else if ((uiop->uio_loffset % bsize) == 0 ||
2987 			    IS_SWAPVP(vp)) {
2988 				/*
2989 				 * Have written a whole block.
2990 				 * Start an asynchronous write
2991 				 * and mark the buffer to
2992 				 * indicate that it won't be
2993 				 * needed again soon.
2994 				 */
2995 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
2996 			} else
2997 				flags = 0;
2998 			if ((ioflag & (FSYNC|FDSYNC)) ||
2999 			    (rp->r_flags & R4OUTOFSPACE)) {
3000 				flags &= ~SM_ASYNC;
3001 				flags |= SM_WRITE;
3002 			}
3003 			if (vpm_enable) {
3004 				error = vpm_sync_pages(vp, off, n, flags);
3005 			} else {
3006 				error = segmap_release(segkmap, base, flags);
3007 			}
3008 		} else {
3009 			if (vpm_enable) {
3010 				(void) vpm_sync_pages(vp, off, n, 0);
3011 			} else {
3012 				(void) segmap_release(segkmap, base, 0);
3013 			}
3014 			/*
3015 			 * In the event that we got an access error while
3016 			 * faulting in a page for a write-only file just
3017 			 * force a write.
3018 			 */
3019 			if (error == EACCES)
3020 				goto nfs4_fwrite;
3021 		}
3022 	} while (!error && uiop->uio_resid > 0);
3023 
3024 bottom:
3025 	if (error) {
3026 		uiop->uio_resid = resid + remainder;
3027 		uiop->uio_loffset = offset;
3028 	} else {
3029 		uiop->uio_resid += remainder;
3030 
3031 		mutex_enter(&rp->r_statev4_lock);
3032 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
3033 			gethrestime(&rp->r_attr.va_mtime);
3034 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3035 		}
3036 		mutex_exit(&rp->r_statev4_lock);
3037 	}
3038 
3039 	nfs_rw_exit(&rp->r_lkserlock);
3040 
3041 	return (error);
3042 }
3043 
3044 /*
3045  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
3046  */
3047 static int
3048 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
3049     int flags, cred_t *cr)
3050 {
3051 	struct buf *bp;
3052 	int error;
3053 	page_t *savepp;
3054 	uchar_t fsdata;
3055 	stable_how4 stab_comm;
3056 
3057 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3058 	bp = pageio_setup(pp, len, vp, flags);
3059 	ASSERT(bp != NULL);
3060 
3061 	/*
3062 	 * pageio_setup should have set b_addr to 0.  This
3063 	 * is correct since we want to do I/O on a page
3064 	 * boundary.  bp_mapin will use this addr to calculate
3065 	 * an offset, and then set b_addr to the kernel virtual
3066 	 * address it allocated for us.
3067 	 */
3068 	ASSERT(bp->b_un.b_addr == 0);
3069 
3070 	bp->b_edev = 0;
3071 	bp->b_dev = 0;
3072 	bp->b_lblkno = lbtodb(off);
3073 	bp->b_file = vp;
3074 	bp->b_offset = (offset_t)off;
3075 	bp_mapin(bp);
3076 
3077 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
3078 	    freemem > desfree)
3079 		stab_comm = UNSTABLE4;
3080 	else
3081 		stab_comm = FILE_SYNC4;
3082 
3083 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
3084 
3085 	bp_mapout(bp);
3086 	pageio_done(bp);
3087 
3088 	if (stab_comm == UNSTABLE4)
3089 		fsdata = C_DELAYCOMMIT;
3090 	else
3091 		fsdata = C_NOCOMMIT;
3092 
3093 	savepp = pp;
3094 	do {
3095 		pp->p_fsdata = fsdata;
3096 	} while ((pp = pp->p_next) != savepp);
3097 
3098 	return (error);
3099 }
3100 
3101 /*
3102  */
3103 static int
3104 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
3105 {
3106 	nfs4_open_owner_t	*oop;
3107 	nfs4_open_stream_t	*osp;
3108 	rnode4_t		*rp = VTOR4(vp);
3109 	mntinfo4_t		*mi = VTOMI4(vp);
3110 	int			reopen_needed;
3111 
3112 	ASSERT(nfs_zone() == mi->mi_zone);
3113 
3114 
3115 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
3116 	if (!oop)
3117 		return (EIO);
3118 
3119 	/* returns with 'os_sync_lock' held */
3120 	osp = find_open_stream(oop, rp);
3121 	if (!osp) {
3122 		open_owner_rele(oop);
3123 		return (EIO);
3124 	}
3125 
3126 	if (osp->os_failed_reopen) {
3127 		mutex_exit(&osp->os_sync_lock);
3128 		open_stream_rele(osp, rp);
3129 		open_owner_rele(oop);
3130 		return (EIO);
3131 	}
3132 
3133 	/*
3134 	 * Determine whether a reopen is needed.  If this
3135 	 * is a delegation open stream, then the os_delegation bit
3136 	 * should be set.
3137 	 */
3138 
3139 	reopen_needed = osp->os_delegation;
3140 
3141 	mutex_exit(&osp->os_sync_lock);
3142 	open_owner_rele(oop);
3143 
3144 	if (reopen_needed) {
3145 		nfs4_error_zinit(ep);
3146 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
3147 		mutex_enter(&osp->os_sync_lock);
3148 		if (ep->error || ep->stat || osp->os_failed_reopen) {
3149 			mutex_exit(&osp->os_sync_lock);
3150 			open_stream_rele(osp, rp);
3151 			return (EIO);
3152 		}
3153 		mutex_exit(&osp->os_sync_lock);
3154 	}
3155 	open_stream_rele(osp, rp);
3156 
3157 	return (0);
3158 }
3159 
3160 /*
3161  * Write to file.  Writes to remote server in largest size
3162  * chunks that the server can handle.  Write is synchronous.
3163  */
3164 static int
3165 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3166     stable_how4 *stab_comm)
3167 {
3168 	mntinfo4_t *mi;
3169 	COMPOUND4args_clnt args;
3170 	COMPOUND4res_clnt res;
3171 	WRITE4args *wargs;
3172 	WRITE4res *wres;
3173 	nfs_argop4 argop[2];
3174 	nfs_resop4 *resop;
3175 	int tsize;
3176 	stable_how4 stable;
3177 	rnode4_t *rp;
3178 	int doqueue = 1;
3179 	bool_t needrecov;
3180 	nfs4_recov_state_t recov_state;
3181 	nfs4_stateid_types_t sid_types;
3182 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3183 	int recov;
3184 
3185 	rp = VTOR4(vp);
3186 	mi = VTOMI4(vp);
3187 
3188 	ASSERT(nfs_zone() == mi->mi_zone);
3189 
3190 	stable = *stab_comm;
3191 	*stab_comm = FILE_SYNC4;
3192 
3193 	needrecov = FALSE;
3194 	recov_state.rs_flags = 0;
3195 	recov_state.rs_num_retry_despite_err = 0;
3196 	nfs4_init_stateid_types(&sid_types);
3197 
3198 	/* Is curthread the recovery thread? */
3199 	mutex_enter(&mi->mi_lock);
3200 	recov = (mi->mi_recovthread == curthread);
3201 	mutex_exit(&mi->mi_lock);
3202 
3203 recov_retry:
3204 	args.ctag = TAG_WRITE;
3205 	args.array_len = 2;
3206 	args.array = argop;
3207 
3208 	if (!recov) {
3209 		e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3210 		    &recov_state, NULL);
3211 		if (e.error)
3212 			return (e.error);
3213 	}
3214 
3215 	/* 0. putfh target fh */
3216 	argop[0].argop = OP_CPUTFH;
3217 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3218 
3219 	/* 1. write */
3220 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3221 
3222 	do {
3223 
3224 		wargs->offset = (offset4)offset;
3225 		wargs->data_val = base;
3226 
3227 		if (mi->mi_io_kstats) {
3228 			mutex_enter(&mi->mi_lock);
3229 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3230 			mutex_exit(&mi->mi_lock);
3231 		}
3232 
3233 		if ((vp->v_flag & VNOCACHE) ||
3234 		    (rp->r_flags & R4DIRECTIO) ||
3235 		    (mi->mi_flags & MI4_DIRECTIO))
3236 			tsize = MIN(mi->mi_stsize, count);
3237 		else
3238 			tsize = MIN(mi->mi_curwrite, count);
3239 		wargs->data_len = (uint_t)tsize;
3240 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3241 
3242 		if (mi->mi_io_kstats) {
3243 			mutex_enter(&mi->mi_lock);
3244 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3245 			mutex_exit(&mi->mi_lock);
3246 		}
3247 
3248 		if (!recov) {
3249 			needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3250 			if (e.error && !needrecov) {
3251 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3252 				    &recov_state, needrecov);
3253 				return (e.error);
3254 			}
3255 		} else {
3256 			if (e.error)
3257 				return (e.error);
3258 		}
3259 
3260 		/*
3261 		 * Do handling of OLD_STATEID outside
3262 		 * of the normal recovery framework.
3263 		 *
3264 		 * If write receives a BAD stateid error while using a
3265 		 * delegation stateid, retry using the open stateid (if it
3266 		 * exists).  If it doesn't have an open stateid, reopen the
3267 		 * file first, then retry.
3268 		 */
3269 		if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3270 		    sid_types.cur_sid_type != SPEC_SID) {
3271 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3272 			if (!recov)
3273 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3274 				    &recov_state, needrecov);
3275 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3276 			goto recov_retry;
3277 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3278 		    sid_types.cur_sid_type == DEL_SID) {
3279 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3280 			mutex_enter(&rp->r_statev4_lock);
3281 			rp->r_deleg_return_pending = TRUE;
3282 			mutex_exit(&rp->r_statev4_lock);
3283 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3284 				if (!recov)
3285 					nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3286 					    &recov_state, needrecov);
3287 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3288 				    (caddr_t)&res);
3289 				return (EIO);
3290 			}
3291 			if (!recov)
3292 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3293 				    &recov_state, needrecov);
3294 			/* hold needed for nfs4delegreturn_thread */
3295 			VN_HOLD(vp);
3296 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3297 			    NFS4_DR_DISCARD), FALSE);
3298 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3299 			goto recov_retry;
3300 		}
3301 
3302 		if (needrecov) {
3303 			bool_t abort;
3304 
3305 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3306 			    "nfs4write: client got error %d, res.status %d"
3307 			    ", so start recovery", e.error, res.status));
3308 
3309 			abort = nfs4_start_recovery(&e,
3310 			    VTOMI4(vp), vp, NULL, &wargs->stateid,
3311 			    NULL, OP_WRITE, NULL, NULL, NULL);
3312 			if (!e.error) {
3313 				e.error = geterrno4(res.status);
3314 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3315 				    (caddr_t)&res);
3316 			}
3317 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3318 			    &recov_state, needrecov);
3319 			if (abort == FALSE)
3320 				goto recov_retry;
3321 			return (e.error);
3322 		}
3323 
3324 		if (res.status) {
3325 			e.error = geterrno4(res.status);
3326 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3327 			if (!recov)
3328 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3329 				    &recov_state, needrecov);
3330 			return (e.error);
3331 		}
3332 
3333 		resop = &res.array[1];	/* write res */
3334 		wres = &resop->nfs_resop4_u.opwrite;
3335 
3336 		if ((int)wres->count > tsize) {
3337 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3338 
3339 			zcmn_err(getzoneid(), CE_WARN,
3340 			    "nfs4write: server wrote %u, requested was %u",
3341 			    (int)wres->count, tsize);
3342 			if (!recov)
3343 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3344 				    &recov_state, needrecov);
3345 			return (EIO);
3346 		}
3347 		if (wres->committed == UNSTABLE4) {
3348 			*stab_comm = UNSTABLE4;
3349 			if (wargs->stable == DATA_SYNC4 ||
3350 			    wargs->stable == FILE_SYNC4) {
3351 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3352 				    (caddr_t)&res);
3353 				zcmn_err(getzoneid(), CE_WARN,
3354 				    "nfs4write: server %s did not commit "
3355 				    "to stable storage",
3356 				    rp->r_server->sv_hostname);
3357 				if (!recov)
3358 					nfs4_end_fop(VTOMI4(vp), vp, NULL,
3359 					    OH_WRITE, &recov_state, needrecov);
3360 				return (EIO);
3361 			}
3362 		}
3363 
3364 		tsize = (int)wres->count;
3365 		count -= tsize;
3366 		base += tsize;
3367 		offset += tsize;
3368 		if (mi->mi_io_kstats) {
3369 			mutex_enter(&mi->mi_lock);
3370 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3371 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3372 			    tsize;
3373 			mutex_exit(&mi->mi_lock);
3374 		}
3375 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3376 		mutex_enter(&rp->r_statelock);
3377 		if (rp->r_flags & R4HAVEVERF) {
3378 			if (rp->r_writeverf != wres->writeverf) {
3379 				nfs4_set_mod(vp);
3380 				rp->r_writeverf = wres->writeverf;
3381 			}
3382 		} else {
3383 			rp->r_writeverf = wres->writeverf;
3384 			rp->r_flags |= R4HAVEVERF;
3385 		}
3386 		PURGE_ATTRCACHE4_LOCKED(rp);
3387 		rp->r_flags |= R4WRITEMODIFIED;
3388 		gethrestime(&rp->r_attr.va_mtime);
3389 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3390 		mutex_exit(&rp->r_statelock);
3391 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3392 	} while (count);
3393 
3394 	if (!recov)
3395 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state,
3396 		    needrecov);
3397 
3398 	return (e.error);
3399 }
3400 
3401 /*
3402  * Read from a file.  Reads data in largest chunks our interface can handle.
3403  */
3404 static int
3405 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3406     size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3407 {
3408 	mntinfo4_t *mi;
3409 	COMPOUND4args_clnt args;
3410 	COMPOUND4res_clnt res;
3411 	READ4args *rargs;
3412 	nfs_argop4 argop[2];
3413 	int tsize;
3414 	int doqueue;
3415 	rnode4_t *rp;
3416 	int data_len;
3417 	bool_t is_eof;
3418 	bool_t needrecov = FALSE;
3419 	nfs4_recov_state_t recov_state;
3420 	nfs4_stateid_types_t sid_types;
3421 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3422 
3423 	rp = VTOR4(vp);
3424 	mi = VTOMI4(vp);
3425 	doqueue = 1;
3426 
3427 	ASSERT(nfs_zone() == mi->mi_zone);
3428 
3429 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3430 
3431 	args.array_len = 2;
3432 	args.array = argop;
3433 
3434 	nfs4_init_stateid_types(&sid_types);
3435 
3436 	recov_state.rs_flags = 0;
3437 	recov_state.rs_num_retry_despite_err = 0;
3438 
3439 recov_retry:
3440 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3441 	    &recov_state, NULL);
3442 	if (e.error)
3443 		return (e.error);
3444 
3445 	/* putfh target fh */
3446 	argop[0].argop = OP_CPUTFH;
3447 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3448 
3449 	/* read */
3450 	argop[1].argop = OP_READ;
3451 	rargs = &argop[1].nfs_argop4_u.opread;
3452 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3453 	    OP_READ, &sid_types, async);
3454 
3455 	do {
3456 		if (mi->mi_io_kstats) {
3457 			mutex_enter(&mi->mi_lock);
3458 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3459 			mutex_exit(&mi->mi_lock);
3460 		}
3461 
3462 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3463 		    "nfs4read: %s call, rp %s",
3464 		    needrecov ? "recov" : "first",
3465 		    rnode4info(rp)));
3466 
3467 		if ((vp->v_flag & VNOCACHE) ||
3468 		    (rp->r_flags & R4DIRECTIO) ||
3469 		    (mi->mi_flags & MI4_DIRECTIO))
3470 			tsize = MIN(mi->mi_tsize, count);
3471 		else
3472 			tsize = MIN(mi->mi_curread, count);
3473 
3474 		rargs->offset = (offset4)offset;
3475 		rargs->count = (count4)tsize;
3476 		rargs->res_data_val_alt = NULL;
3477 		rargs->res_mblk = NULL;
3478 		rargs->res_uiop = NULL;
3479 		rargs->res_maxsize = 0;
3480 		rargs->wlist = NULL;
3481 
3482 		if (uiop)
3483 			rargs->res_uiop = uiop;
3484 		else
3485 			rargs->res_data_val_alt = base;
3486 		rargs->res_maxsize = tsize;
3487 
3488 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3489 #ifdef	DEBUG
3490 		if (nfs4read_error_inject) {
3491 			res.status = nfs4read_error_inject;
3492 			nfs4read_error_inject = 0;
3493 		}
3494 #endif
3495 
3496 		if (mi->mi_io_kstats) {
3497 			mutex_enter(&mi->mi_lock);
3498 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3499 			mutex_exit(&mi->mi_lock);
3500 		}
3501 
3502 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3503 		if (e.error != 0 && !needrecov) {
3504 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3505 			    &recov_state, needrecov);
3506 			return (e.error);
3507 		}
3508 
3509 		/*
3510 		 * Do proper retry for OLD and BAD stateid errors outside
3511 		 * of the normal recovery framework.  There are two differences
3512 		 * between async and sync reads.  The first is that we allow
3513 		 * retry on BAD_STATEID for async reads, but not sync reads.
3514 		 * The second is that we mark the file dead for a failed
3515 		 * attempt with a special stateid for sync reads, but just
3516 		 * return EIO for async reads.
3517 		 *
3518 		 * If a sync read receives a BAD stateid error while using a
3519 		 * delegation stateid, retry using the open stateid (if it
3520 		 * exists).  If it doesn't have an open stateid, reopen the
3521 		 * file first, then retry.
3522 		 */
3523 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3524 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3525 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3526 			    &recov_state, needrecov);
3527 			if (sid_types.cur_sid_type == SPEC_SID) {
3528 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3529 				    (caddr_t)&res);
3530 				return (EIO);
3531 			}
3532 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3533 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3534 			goto recov_retry;
3535 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3536 		    !async && sid_types.cur_sid_type != SPEC_SID) {
3537 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3538 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3539 			    &recov_state, needrecov);
3540 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3541 			goto recov_retry;
3542 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3543 		    sid_types.cur_sid_type == DEL_SID) {
3544 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3545 			mutex_enter(&rp->r_statev4_lock);
3546 			rp->r_deleg_return_pending = TRUE;
3547 			mutex_exit(&rp->r_statev4_lock);
3548 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3549 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3550 				    &recov_state, needrecov);
3551 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3552 				    (caddr_t)&res);
3553 				return (EIO);
3554 			}
3555 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3556 			    &recov_state, needrecov);
3557 			/* hold needed for nfs4delegreturn_thread */
3558 			VN_HOLD(vp);
3559 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3560 			    NFS4_DR_DISCARD), FALSE);
3561 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3562 			goto recov_retry;
3563 		}
3564 		if (needrecov) {
3565 			bool_t abort;
3566 
3567 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3568 			    "nfs4read: initiating recovery\n"));
3569 			abort = nfs4_start_recovery(&e,
3570 			    mi, vp, NULL, &rargs->stateid,
3571 			    NULL, OP_READ, NULL, NULL, NULL);
3572 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3573 			    &recov_state, needrecov);
3574 			/*
3575 			 * Do not retry if we got OLD_STATEID using a special
3576 			 * stateid.  This avoids looping with a broken server.
3577 			 */
3578 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3579 			    sid_types.cur_sid_type == SPEC_SID)
3580 				abort = TRUE;
3581 
3582 			if (abort == FALSE) {
3583 				/*
3584 				 * Need to retry all possible stateids in
3585 				 * case the recovery error wasn't stateid
3586 				 * related or the stateids have become
3587 				 * stale (server reboot).
3588 				 */
3589 				nfs4_init_stateid_types(&sid_types);
3590 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3591 				    (caddr_t)&res);
3592 				goto recov_retry;
3593 			}
3594 
3595 			if (!e.error) {
3596 				e.error = geterrno4(res.status);
3597 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3598 				    (caddr_t)&res);
3599 			}
3600 			return (e.error);
3601 		}
3602 
3603 		if (res.status) {
3604 			e.error = geterrno4(res.status);
3605 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3606 			    &recov_state, needrecov);
3607 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3608 			return (e.error);
3609 		}
3610 
3611 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3612 		count -= data_len;
3613 		if (base)
3614 			base += data_len;
3615 		offset += data_len;
3616 		if (mi->mi_io_kstats) {
3617 			mutex_enter(&mi->mi_lock);
3618 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3619 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3620 			mutex_exit(&mi->mi_lock);
3621 		}
3622 		lwp_stat_update(LWP_STAT_INBLK, 1);
3623 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3624 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3625 
3626 	} while (count && !is_eof);
3627 
3628 	*residp = count;
3629 
3630 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3631 
3632 	return (e.error);
3633 }
3634 
3635 /* ARGSUSED */
3636 static int
3637 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp,
3638     caller_context_t *ct)
3639 {
3640 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3641 		return (EIO);
3642 	switch (cmd) {
3643 		case _FIODIRECTIO:
3644 			return (nfs4_directio(vp, (int)arg, cr));
3645 		default:
3646 			return (ENOTTY);
3647 	}
3648 }
3649 
3650 /* ARGSUSED */
3651 int
3652 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3653     caller_context_t *ct)
3654 {
3655 	int error;
3656 	rnode4_t *rp = VTOR4(vp);
3657 
3658 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3659 		return (EIO);
3660 	/*
3661 	 * If it has been specified that the return value will
3662 	 * just be used as a hint, and we are only being asked
3663 	 * for size, fsid or rdevid, then return the client's
3664 	 * notion of these values without checking to make sure
3665 	 * that the attribute cache is up to date.
3666 	 * The whole point is to avoid an over the wire GETATTR
3667 	 * call.
3668 	 */
3669 	if (flags & ATTR_HINT) {
3670 		if (!(vap->va_mask & ~(AT_SIZE | AT_FSID | AT_RDEV))) {
3671 			mutex_enter(&rp->r_statelock);
3672 			if (vap->va_mask & AT_SIZE)
3673 				vap->va_size = rp->r_size;
3674 			if (vap->va_mask & AT_FSID)
3675 				vap->va_fsid = rp->r_attr.va_fsid;
3676 			if (vap->va_mask & AT_RDEV)
3677 				vap->va_rdev = rp->r_attr.va_rdev;
3678 			mutex_exit(&rp->r_statelock);
3679 			return (0);
3680 		}
3681 	}
3682 
3683 	/*
3684 	 * Only need to flush pages if asking for the mtime
3685 	 * and if there any dirty pages or any outstanding
3686 	 * asynchronous (write) requests for this file.
3687 	 */
3688 	if (vap->va_mask & AT_MTIME) {
3689 		rp = VTOR4(vp);
3690 		if (nfs4_has_pages(vp)) {
3691 			mutex_enter(&rp->r_statev4_lock);
3692 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3693 				mutex_exit(&rp->r_statev4_lock);
3694 				if (rp->r_flags & R4DIRTY ||
3695 				    rp->r_awcount > 0) {
3696 					mutex_enter(&rp->r_statelock);
3697 					rp->r_gcount++;
3698 					mutex_exit(&rp->r_statelock);
3699 					error =
3700 					    nfs4_putpage(vp, (u_offset_t)0,
3701 					    0, 0, cr, NULL);
3702 					mutex_enter(&rp->r_statelock);
3703 					if (error && (error == ENOSPC ||
3704 					    error == EDQUOT)) {
3705 						if (!rp->r_error)
3706 							rp->r_error = error;
3707 					}
3708 					if (--rp->r_gcount == 0)
3709 						cv_broadcast(&rp->r_cv);
3710 					mutex_exit(&rp->r_statelock);
3711 				}
3712 			} else {
3713 				mutex_exit(&rp->r_statev4_lock);
3714 			}
3715 		}
3716 	}
3717 	return (nfs4getattr(vp, vap, cr));
3718 }
3719 
3720 int
3721 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3722 {
3723 	/*
3724 	 * If these are the only two bits cleared
3725 	 * on the server then return 0 (OK) else
3726 	 * return 1 (BAD).
3727 	 */
3728 	on_client &= ~(S_ISUID|S_ISGID);
3729 	if (on_client == from_server)
3730 		return (0);
3731 	else
3732 		return (1);
3733 }
3734 
3735 /*ARGSUSED4*/
3736 static int
3737 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3738     caller_context_t *ct)
3739 {
3740 	int error;
3741 
3742 	if (vap->va_mask & AT_NOSET)
3743 		return (EINVAL);
3744 
3745 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3746 		return (EIO);
3747 
3748 	/*
3749 	 * Don't call secpolicy_vnode_setattr, the client cannot
3750 	 * use its cached attributes to make security decisions
3751 	 * as the server may be faking mode bits or mapping uid/gid.
3752 	 * Always just let the server to the checking.
3753 	 * If we provide the ability to remove basic priviledges
3754 	 * to setattr (e.g. basic without chmod) then we will
3755 	 * need to add a check here before calling the server.
3756 	 */
3757 	error = nfs4setattr(vp, vap, flags, cr, NULL);
3758 
3759 	if (error == 0 && (vap->va_mask & AT_SIZE) && vap->va_size == 0)
3760 		vnevent_truncate(vp, ct);
3761 
3762 	return (error);
3763 }
3764 
3765 /*
3766  * To replace the "guarded" version 3 setattr, we use two types of compound
3767  * setattr requests:
3768  * 1. The "normal" setattr, used when the size of the file isn't being
3769  *    changed - { Putfh <fh>; Setattr; Getattr }/
3770  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3771  *    with only ctime as the argument. If the server ctime differs from
3772  *    what is cached on the client, the verify will fail, but we would
3773  *    already have the ctime from the preceding getattr, so just set it
3774  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3775  *	Setattr; Getattr }.
3776  *
3777  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3778  * this setattr and NULL if they are not.
3779  */
3780 static int
3781 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3782     vsecattr_t *vsap)
3783 {
3784 	COMPOUND4args_clnt args;
3785 	COMPOUND4res_clnt res, *resp = NULL;
3786 	nfs4_ga_res_t *garp = NULL;
3787 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3788 	nfs_argop4 argop[5];
3789 	int verify_argop = -1;
3790 	int setattr_argop = 1;
3791 	nfs_resop4 *resop;
3792 	vattr_t va;
3793 	rnode4_t *rp;
3794 	int doqueue = 1;
3795 	uint_t mask = vap->va_mask;
3796 	mode_t omode;
3797 	vsecattr_t *vsp;
3798 	timestruc_t ctime;
3799 	bool_t needrecov = FALSE;
3800 	nfs4_recov_state_t recov_state;
3801 	nfs4_stateid_types_t sid_types;
3802 	stateid4 stateid;
3803 	hrtime_t t;
3804 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3805 	servinfo4_t *svp;
3806 	bitmap4 supp_attrs;
3807 
3808 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3809 	rp = VTOR4(vp);
3810 	nfs4_init_stateid_types(&sid_types);
3811 
3812 	/*
3813 	 * Only need to flush pages if there are any pages and
3814 	 * if the file is marked as dirty in some fashion.  The
3815 	 * file must be flushed so that we can accurately
3816 	 * determine the size of the file and the cached data
3817 	 * after the SETATTR returns.  A file is considered to
3818 	 * be dirty if it is either marked with R4DIRTY, has
3819 	 * outstanding i/o's active, or is mmap'd.  In this
3820 	 * last case, we can't tell whether there are dirty
3821 	 * pages, so we flush just to be sure.
3822 	 */
3823 	if (nfs4_has_pages(vp) &&
3824 	    ((rp->r_flags & R4DIRTY) ||
3825 	    rp->r_count > 0 ||
3826 	    rp->r_mapcnt > 0)) {
3827 		ASSERT(vp->v_type != VCHR);
3828 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr, NULL);
3829 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3830 			mutex_enter(&rp->r_statelock);
3831 			if (!rp->r_error)
3832 				rp->r_error = e.error;
3833 			mutex_exit(&rp->r_statelock);
3834 		}
3835 	}
3836 
3837 	if (mask & AT_SIZE) {
3838 		/*
3839 		 * Verification setattr compound for non-deleg AT_SIZE:
3840 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3841 		 * Set ctime local here (outside the do_again label)
3842 		 * so that subsequent retries (after failed VERIFY)
3843 		 * will use ctime from GETATTR results (from failed
3844 		 * verify compound) as VERIFY arg.
3845 		 * If file has delegation, then VERIFY(time_metadata)
3846 		 * is of little added value, so don't bother.
3847 		 */
3848 		mutex_enter(&rp->r_statev4_lock);
3849 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3850 		    rp->r_deleg_return_pending) {
3851 			numops = 5;
3852 			ctime = rp->r_attr.va_ctime;
3853 		}
3854 		mutex_exit(&rp->r_statev4_lock);
3855 	}
3856 
3857 	recov_state.rs_flags = 0;
3858 	recov_state.rs_num_retry_despite_err = 0;
3859 
3860 	args.ctag = TAG_SETATTR;
3861 do_again:
3862 recov_retry:
3863 	setattr_argop = numops - 2;
3864 
3865 	args.array = argop;
3866 	args.array_len = numops;
3867 
3868 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3869 	if (e.error)
3870 		return (e.error);
3871 
3872 
3873 	/* putfh target fh */
3874 	argop[0].argop = OP_CPUTFH;
3875 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3876 
3877 	if (numops == 5) {
3878 		/*
3879 		 * We only care about the ctime, but need to get mtime
3880 		 * and size for proper cache update.
3881 		 */
3882 		/* getattr */
3883 		argop[1].argop = OP_GETATTR;
3884 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3885 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3886 
3887 		/* verify - set later in loop */
3888 		verify_argop = 2;
3889 	}
3890 
3891 	/* setattr */
3892 	svp = rp->r_server;
3893 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3894 	supp_attrs = svp->sv_supp_attrs;
3895 	nfs_rw_exit(&svp->sv_lock);
3896 
3897 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3898 	    supp_attrs, &e.error, &sid_types);
3899 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3900 	if (e.error) {
3901 		/* req time field(s) overflow - return immediately */
3902 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3903 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3904 		    opsetattr.obj_attributes);
3905 		return (e.error);
3906 	}
3907 	omode = rp->r_attr.va_mode;
3908 
3909 	/* getattr */
3910 	argop[numops-1].argop = OP_GETATTR;
3911 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3912 	/*
3913 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3914 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3915 	 * used in updating the ACL cache.
3916 	 */
3917 	if (vsap != NULL)
3918 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3919 		    FATTR4_ACL_MASK;
3920 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3921 
3922 	/*
3923 	 * setattr iterates if the object size is set and the cached ctime
3924 	 * does not match the file ctime. In that case, verify the ctime first.
3925 	 */
3926 
3927 	do {
3928 		if (verify_argop != -1) {
3929 			/*
3930 			 * Verify that the ctime match before doing setattr.
3931 			 */
3932 			va.va_mask = AT_CTIME;
3933 			va.va_ctime = ctime;
3934 			svp = rp->r_server;
3935 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3936 			supp_attrs = svp->sv_supp_attrs;
3937 			nfs_rw_exit(&svp->sv_lock);
3938 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3939 			    OP_VERIFY, supp_attrs);
3940 			if (e.error) {
3941 				/* req time field(s) overflow - return */
3942 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3943 				    needrecov);
3944 				break;
3945 			}
3946 		}
3947 
3948 		doqueue = 1;
3949 
3950 		t = gethrtime();
3951 
3952 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3953 
3954 		/*
3955 		 * Purge the access cache and ACL cache if changing either the
3956 		 * owner of the file, the group owner, or the mode.  These may
3957 		 * change the access permissions of the file, so purge old
3958 		 * information and start over again.
3959 		 */
3960 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3961 			(void) nfs4_access_purge_rp(rp);
3962 			if (rp->r_secattr != NULL) {
3963 				mutex_enter(&rp->r_statelock);
3964 				vsp = rp->r_secattr;
3965 				rp->r_secattr = NULL;
3966 				mutex_exit(&rp->r_statelock);
3967 				if (vsp != NULL)
3968 					nfs4_acl_free_cache(vsp);
3969 			}
3970 		}
3971 
3972 		/*
3973 		 * If res.array_len == numops, then everything succeeded,
3974 		 * except for possibly the final getattr.  If only the
3975 		 * last getattr failed, give up, and don't try recovery.
3976 		 */
3977 		if (res.array_len == numops) {
3978 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3979 			    needrecov);
3980 			if (! e.error)
3981 				resp = &res;
3982 			break;
3983 		}
3984 
3985 		/*
3986 		 * if either rpc call failed or completely succeeded - done
3987 		 */
3988 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
3989 		if (e.error) {
3990 			PURGE_ATTRCACHE4(vp);
3991 			if (!needrecov) {
3992 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3993 				    needrecov);
3994 				break;
3995 			}
3996 		}
3997 
3998 		/*
3999 		 * Do proper retry for OLD_STATEID outside of the normal
4000 		 * recovery framework.
4001 		 */
4002 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
4003 		    sid_types.cur_sid_type != SPEC_SID &&
4004 		    sid_types.cur_sid_type != NO_SID) {
4005 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4006 			    needrecov);
4007 			nfs4_save_stateid(&stateid, &sid_types);
4008 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4009 			    opsetattr.obj_attributes);
4010 			if (verify_argop != -1) {
4011 				nfs4args_verify_free(&argop[verify_argop]);
4012 				verify_argop = -1;
4013 			}
4014 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4015 			goto recov_retry;
4016 		}
4017 
4018 		if (needrecov) {
4019 			bool_t abort;
4020 
4021 			abort = nfs4_start_recovery(&e,
4022 			    VTOMI4(vp), vp, NULL, NULL, NULL,
4023 			    OP_SETATTR, NULL, NULL, NULL);
4024 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4025 			    needrecov);
4026 			/*
4027 			 * Do not retry if we failed with OLD_STATEID using
4028 			 * a special stateid.  This is done to avoid looping
4029 			 * with a broken server.
4030 			 */
4031 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
4032 			    (sid_types.cur_sid_type == SPEC_SID ||
4033 			    sid_types.cur_sid_type == NO_SID))
4034 				abort = TRUE;
4035 			if (!e.error) {
4036 				if (res.status == NFS4ERR_BADOWNER)
4037 					nfs4_log_badowner(VTOMI4(vp),
4038 					    OP_SETATTR);
4039 
4040 				e.error = geterrno4(res.status);
4041 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4042 				    (caddr_t)&res);
4043 			}
4044 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4045 			    opsetattr.obj_attributes);
4046 			if (verify_argop != -1) {
4047 				nfs4args_verify_free(&argop[verify_argop]);
4048 				verify_argop = -1;
4049 			}
4050 			if (abort == FALSE) {
4051 				/*
4052 				 * Need to retry all possible stateids in
4053 				 * case the recovery error wasn't stateid
4054 				 * related or the stateids have become
4055 				 * stale (server reboot).
4056 				 */
4057 				nfs4_init_stateid_types(&sid_types);
4058 				goto recov_retry;
4059 			}
4060 			return (e.error);
4061 		}
4062 
4063 		/*
4064 		 * Need to call nfs4_end_op before nfs4getattr to
4065 		 * avoid potential nfs4_start_op deadlock. See RFE
4066 		 * 4777612.  Calls to nfs4_invalidate_pages() and
4067 		 * nfs4_purge_stale_fh() might also generate over the
4068 		 * wire calls which my cause nfs4_start_op() deadlock.
4069 		 */
4070 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4071 
4072 		/*
4073 		 * Check to update lease.
4074 		 */
4075 		resp = &res;
4076 		if (res.status == NFS4_OK) {
4077 			break;
4078 		}
4079 
4080 		/*
4081 		 * Check if verify failed to see if try again
4082 		 */
4083 		if ((verify_argop == -1) || (res.array_len != 3)) {
4084 			/*
4085 			 * can't continue...
4086 			 */
4087 			if (res.status == NFS4ERR_BADOWNER)
4088 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
4089 
4090 			e.error = geterrno4(res.status);
4091 		} else {
4092 			/*
4093 			 * When the verify request fails, the client ctime is
4094 			 * not in sync with the server. This is the same as
4095 			 * the version 3 "not synchronized" error, and we
4096 			 * handle it in a similar manner (XXX do we need to???).
4097 			 * Use the ctime returned in the first getattr for
4098 			 * the input to the next verify.
4099 			 * If we couldn't get the attributes, then we give up
4100 			 * because we can't complete the operation as required.
4101 			 */
4102 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
4103 		}
4104 		if (e.error) {
4105 			PURGE_ATTRCACHE4(vp);
4106 			nfs4_purge_stale_fh(e.error, vp, cr);
4107 		} else {
4108 			/*
4109 			 * retry with a new verify value
4110 			 */
4111 			ctime = garp->n4g_va.va_ctime;
4112 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4113 			resp = NULL;
4114 		}
4115 		if (!e.error) {
4116 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4117 			    opsetattr.obj_attributes);
4118 			if (verify_argop != -1) {
4119 				nfs4args_verify_free(&argop[verify_argop]);
4120 				verify_argop = -1;
4121 			}
4122 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4123 			goto do_again;
4124 		}
4125 	} while (!e.error);
4126 
4127 	if (e.error) {
4128 		/*
4129 		 * If we are here, rfs4call has an irrecoverable error - return
4130 		 */
4131 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4132 		    opsetattr.obj_attributes);
4133 		if (verify_argop != -1) {
4134 			nfs4args_verify_free(&argop[verify_argop]);
4135 			verify_argop = -1;
4136 		}
4137 		if (resp)
4138 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4139 		return (e.error);
4140 	}
4141 
4142 
4143 
4144 	/*
4145 	 * If changing the size of the file, invalidate
4146 	 * any local cached data which is no longer part
4147 	 * of the file.  We also possibly invalidate the
4148 	 * last page in the file.  We could use
4149 	 * pvn_vpzero(), but this would mark the page as
4150 	 * modified and require it to be written back to
4151 	 * the server for no particularly good reason.
4152 	 * This way, if we access it, then we bring it
4153 	 * back in.  A read should be cheaper than a
4154 	 * write.
4155 	 */
4156 	if (mask & AT_SIZE) {
4157 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
4158 	}
4159 
4160 	/* either no error or one of the postop getattr failed */
4161 
4162 	/*
4163 	 * XXX Perform a simplified version of wcc checking. Instead of
4164 	 * have another getattr to get pre-op, just purge cache if
4165 	 * any of the ops prior to and including the getattr failed.
4166 	 * If the getattr succeeded then update the attrcache accordingly.
4167 	 */
4168 
4169 	garp = NULL;
4170 	if (res.status == NFS4_OK) {
4171 		/*
4172 		 * Last getattr
4173 		 */
4174 		resop = &res.array[numops - 1];
4175 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4176 	}
4177 	/*
4178 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
4179 	 * rather than filling it.  See the function itself for details.
4180 	 */
4181 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4182 	if (garp != NULL) {
4183 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
4184 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
4185 			vs_ace4_destroy(&garp->n4g_vsa);
4186 		} else {
4187 			if (vsap != NULL) {
4188 				/*
4189 				 * The ACL was supposed to be set and to be
4190 				 * returned in the last getattr of this
4191 				 * compound, but for some reason the getattr
4192 				 * result doesn't contain the ACL.  In this
4193 				 * case, purge the ACL cache.
4194 				 */
4195 				if (rp->r_secattr != NULL) {
4196 					mutex_enter(&rp->r_statelock);
4197 					vsp = rp->r_secattr;
4198 					rp->r_secattr = NULL;
4199 					mutex_exit(&rp->r_statelock);
4200 					if (vsp != NULL)
4201 						nfs4_acl_free_cache(vsp);
4202 				}
4203 			}
4204 		}
4205 	}
4206 
4207 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4208 		/*
4209 		 * Set the size, rather than relying on getting it updated
4210 		 * via a GETATTR.  With delegations the client tries to
4211 		 * suppress GETATTR calls.
4212 		 */
4213 		mutex_enter(&rp->r_statelock);
4214 		rp->r_size = vap->va_size;
4215 		mutex_exit(&rp->r_statelock);
4216 	}
4217 
4218 	/*
4219 	 * Can free up request args and res
4220 	 */
4221 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4222 	    opsetattr.obj_attributes);
4223 	if (verify_argop != -1) {
4224 		nfs4args_verify_free(&argop[verify_argop]);
4225 		verify_argop = -1;
4226 	}
4227 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4228 
4229 	/*
4230 	 * Some servers will change the mode to clear the setuid
4231 	 * and setgid bits when changing the uid or gid.  The
4232 	 * client needs to compensate appropriately.
4233 	 */
4234 	if (mask & (AT_UID | AT_GID)) {
4235 		int terror, do_setattr;
4236 
4237 		do_setattr = 0;
4238 		va.va_mask = AT_MODE;
4239 		terror = nfs4getattr(vp, &va, cr);
4240 		if (!terror &&
4241 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4242 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4243 			va.va_mask = AT_MODE;
4244 			if (mask & AT_MODE) {
4245 				/*
4246 				 * We asked the mode to be changed and what
4247 				 * we just got from the server in getattr is
4248 				 * not what we wanted it to be, so set it now.
4249 				 */
4250 				va.va_mode = vap->va_mode;
4251 				do_setattr = 1;
4252 			} else {
4253 				/*
4254 				 * We did not ask the mode to be changed,
4255 				 * Check to see that the server just cleared
4256 				 * I_SUID and I_GUID from it. If not then
4257 				 * set mode to omode with UID/GID cleared.
4258 				 */
4259 				if (nfs4_compare_modes(va.va_mode, omode)) {
4260 					omode &= ~(S_ISUID|S_ISGID);
4261 					va.va_mode = omode;
4262 					do_setattr = 1;
4263 				}
4264 			}
4265 
4266 			if (do_setattr)
4267 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4268 		}
4269 	}
4270 
4271 	return (e.error);
4272 }
4273 
4274 /* ARGSUSED */
4275 static int
4276 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr, caller_context_t *ct)
4277 {
4278 	COMPOUND4args_clnt args;
4279 	COMPOUND4res_clnt res;
4280 	int doqueue;
4281 	uint32_t acc, resacc, argacc;
4282 	rnode4_t *rp;
4283 	cred_t *cred, *ncr, *ncrfree = NULL;
4284 	nfs4_access_type_t cacc;
4285 	int num_ops;
4286 	nfs_argop4 argop[3];
4287 	nfs_resop4 *resop;
4288 	bool_t needrecov = FALSE, do_getattr;
4289 	nfs4_recov_state_t recov_state;
4290 	int rpc_error;
4291 	hrtime_t t;
4292 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4293 	mntinfo4_t *mi = VTOMI4(vp);
4294 
4295 	if (nfs_zone() != mi->mi_zone)
4296 		return (EIO);
4297 
4298 	acc = 0;
4299 	if (mode & VREAD)
4300 		acc |= ACCESS4_READ;
4301 	if (mode & VWRITE) {
4302 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4303 			return (EROFS);
4304 		if (vp->v_type == VDIR)
4305 			acc |= ACCESS4_DELETE;
4306 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4307 	}
4308 	if (mode & VEXEC) {
4309 		if (vp->v_type == VDIR)
4310 			acc |= ACCESS4_LOOKUP;
4311 		else
4312 			acc |= ACCESS4_EXECUTE;
4313 	}
4314 
4315 	if (VTOR4(vp)->r_acache != NULL) {
4316 		e.error = nfs4_validate_caches(vp, cr);
4317 		if (e.error)
4318 			return (e.error);
4319 	}
4320 
4321 	rp = VTOR4(vp);
4322 	if (vp->v_type == VDIR)
4323 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4324 		    ACCESS4_EXTEND | ACCESS4_LOOKUP;
4325 	else
4326 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4327 		    ACCESS4_EXECUTE;
4328 	recov_state.rs_flags = 0;
4329 	recov_state.rs_num_retry_despite_err = 0;
4330 
4331 	cred = cr;
4332 	/*
4333 	 * ncr and ncrfree both initially
4334 	 * point to the memory area returned
4335 	 * by crnetadjust();
4336 	 * ncrfree not NULL when exiting means
4337 	 * that we need to release it
4338 	 */
4339 	ncr = crnetadjust(cred);
4340 	ncrfree = ncr;
4341 
4342 tryagain:
4343 	cacc = nfs4_access_check(rp, acc, cred);
4344 	if (cacc == NFS4_ACCESS_ALLOWED) {
4345 		if (ncrfree != NULL)
4346 			crfree(ncrfree);
4347 		return (0);
4348 	}
4349 	if (cacc == NFS4_ACCESS_DENIED) {
4350 		/*
4351 		 * If the cred can be adjusted, try again
4352 		 * with the new cred.
4353 		 */
4354 		if (ncr != NULL) {
4355 			cred = ncr;
4356 			ncr = NULL;
4357 			goto tryagain;
4358 		}
4359 		if (ncrfree != NULL)
4360 			crfree(ncrfree);
4361 		return (EACCES);
4362 	}
4363 
4364 recov_retry:
4365 	/*
4366 	 * Don't take with r_statev4_lock here. r_deleg_type could
4367 	 * change as soon as lock is released.  Since it is an int,
4368 	 * there is no atomicity issue.
4369 	 */
4370 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4371 	num_ops = do_getattr ? 3 : 2;
4372 
4373 	args.ctag = TAG_ACCESS;
4374 
4375 	args.array_len = num_ops;
4376 	args.array = argop;
4377 
4378 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4379 	    &recov_state, NULL)) {
4380 		if (ncrfree != NULL)
4381 			crfree(ncrfree);
4382 		return (e.error);
4383 	}
4384 
4385 	/* putfh target fh */
4386 	argop[0].argop = OP_CPUTFH;
4387 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4388 
4389 	/* access */
4390 	argop[1].argop = OP_ACCESS;
4391 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4392 
4393 	/* getattr */
4394 	if (do_getattr) {
4395 		argop[2].argop = OP_GETATTR;
4396 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4397 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4398 	}
4399 
4400 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4401 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4402 	    rnode4info(VTOR4(vp))));
4403 
4404 	doqueue = 1;
4405 	t = gethrtime();
4406 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4407 	rpc_error = e.error;
4408 
4409 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4410 	if (needrecov) {
4411 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4412 		    "nfs4_access: initiating recovery\n"));
4413 
4414 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4415 		    NULL, OP_ACCESS, NULL, NULL, NULL) == FALSE) {
4416 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4417 			    &recov_state, needrecov);
4418 			if (!e.error)
4419 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4420 				    (caddr_t)&res);
4421 			goto recov_retry;
4422 		}
4423 	}
4424 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4425 
4426 	if (e.error)
4427 		goto out;
4428 
4429 	if (res.status) {
4430 		e.error = geterrno4(res.status);
4431 		/*
4432 		 * This might generate over the wire calls throught
4433 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4434 		 * here to avoid a deadlock.
4435 		 */
4436 		nfs4_purge_stale_fh(e.error, vp, cr);
4437 		goto out;
4438 	}
4439 	resop = &res.array[1];	/* access res */
4440 
4441 	resacc = resop->nfs_resop4_u.opaccess.access;
4442 
4443 	if (do_getattr) {
4444 		resop++;	/* getattr res */
4445 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4446 		    t, cr, FALSE, NULL);
4447 	}
4448 
4449 	if (!e.error) {
4450 		nfs4_access_cache(rp, argacc, resacc, cred);
4451 		/*
4452 		 * we just cached results with cred; if cred is the
4453 		 * adjusted credentials from crnetadjust, we do not want
4454 		 * to release them before exiting: hence setting ncrfree
4455 		 * to NULL
4456 		 */
4457 		if (cred != cr)
4458 			ncrfree = NULL;
4459 		/* XXX check the supported bits too? */
4460 		if ((acc & resacc) != acc) {
4461 			/*
4462 			 * The following code implements the semantic
4463 			 * that a setuid root program has *at least* the
4464 			 * permissions of the user that is running the
4465 			 * program.  See rfs3call() for more portions
4466 			 * of the implementation of this functionality.
4467 			 */
4468 			/* XXX-LP */
4469 			if (ncr != NULL) {
4470 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4471 				    (caddr_t)&res);
4472 				cred = ncr;
4473 				ncr = NULL;
4474 				goto tryagain;
4475 			}
4476 			e.error = EACCES;
4477 		}
4478 	}
4479 
4480 out:
4481 	if (!rpc_error)
4482 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4483 
4484 	if (ncrfree != NULL)
4485 		crfree(ncrfree);
4486 
4487 	return (e.error);
4488 }
4489 
4490 /* ARGSUSED */
4491 static int
4492 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr, caller_context_t *ct)
4493 {
4494 	COMPOUND4args_clnt args;
4495 	COMPOUND4res_clnt res;
4496 	int doqueue;
4497 	rnode4_t *rp;
4498 	nfs_argop4 argop[3];
4499 	nfs_resop4 *resop;
4500 	READLINK4res *lr_res;
4501 	nfs4_ga_res_t *garp;
4502 	uint_t len;
4503 	char *linkdata;
4504 	bool_t needrecov = FALSE;
4505 	nfs4_recov_state_t recov_state;
4506 	hrtime_t t;
4507 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4508 
4509 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4510 		return (EIO);
4511 	/*
4512 	 * Can't readlink anything other than a symbolic link.
4513 	 */
4514 	if (vp->v_type != VLNK)
4515 		return (EINVAL);
4516 
4517 	rp = VTOR4(vp);
4518 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4519 		e.error = nfs4_validate_caches(vp, cr);
4520 		if (e.error)
4521 			return (e.error);
4522 		mutex_enter(&rp->r_statelock);
4523 		if (rp->r_symlink.contents != NULL) {
4524 			e.error = uiomove(rp->r_symlink.contents,
4525 			    rp->r_symlink.len, UIO_READ, uiop);
4526 			mutex_exit(&rp->r_statelock);
4527 			return (e.error);
4528 		}
4529 		mutex_exit(&rp->r_statelock);
4530 	}
4531 	recov_state.rs_flags = 0;
4532 	recov_state.rs_num_retry_despite_err = 0;
4533 
4534 recov_retry:
4535 	args.array_len = 3;
4536 	args.array = argop;
4537 	args.ctag = TAG_READLINK;
4538 
4539 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4540 	if (e.error) {
4541 		return (e.error);
4542 	}
4543 
4544 	/* 0. putfh symlink fh */
4545 	argop[0].argop = OP_CPUTFH;
4546 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4547 
4548 	/* 1. readlink */
4549 	argop[1].argop = OP_READLINK;
4550 
4551 	/* 2. getattr */
4552 	argop[2].argop = OP_GETATTR;
4553 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4554 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4555 
4556 	doqueue = 1;
4557 
4558 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4559 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4560 	    rnode4info(VTOR4(vp))));
4561 
4562 	t = gethrtime();
4563 
4564 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4565 
4566 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4567 	if (needrecov) {
4568 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4569 		    "nfs4_readlink: initiating recovery\n"));
4570 
4571 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4572 		    NULL, OP_READLINK, NULL, NULL, NULL) == FALSE) {
4573 			if (!e.error)
4574 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4575 				    (caddr_t)&res);
4576 
4577 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4578 			    needrecov);
4579 			goto recov_retry;
4580 		}
4581 	}
4582 
4583 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4584 
4585 	if (e.error)
4586 		return (e.error);
4587 
4588 	/*
4589 	 * There is an path in the code below which calls
4590 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4591 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4592 	 * here to avoid nfs4_start_op() deadlock.
4593 	 */
4594 
4595 	if (res.status && (res.array_len < args.array_len)) {
4596 		/*
4597 		 * either Putfh or Link failed
4598 		 */
4599 		e.error = geterrno4(res.status);
4600 		nfs4_purge_stale_fh(e.error, vp, cr);
4601 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4602 		return (e.error);
4603 	}
4604 
4605 	resop = &res.array[1];	/* readlink res */
4606 	lr_res = &resop->nfs_resop4_u.opreadlink;
4607 
4608 	/*
4609 	 * treat symlink names as data
4610 	 */
4611 	linkdata = utf8_to_str((utf8string *)&lr_res->link, &len, NULL);
4612 	if (linkdata != NULL) {
4613 		int uio_len = len - 1;
4614 		/* len includes null byte, which we won't uiomove */
4615 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4616 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4617 			mutex_enter(&rp->r_statelock);
4618 			if (rp->r_symlink.contents == NULL) {
4619 				rp->r_symlink.contents = linkdata;
4620 				rp->r_symlink.len = uio_len;
4621 				rp->r_symlink.size = len;
4622 				mutex_exit(&rp->r_statelock);
4623 			} else {
4624 				mutex_exit(&rp->r_statelock);
4625 				kmem_free(linkdata, len);
4626 			}
4627 		} else {
4628 			kmem_free(linkdata, len);
4629 		}
4630 	}
4631 	if (res.status == NFS4_OK) {
4632 		resop++;	/* getattr res */
4633 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4634 	}
4635 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4636 
4637 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4638 
4639 	/*
4640 	 * The over the wire error for attempting to readlink something
4641 	 * other than a symbolic link is ENXIO.  However, we need to
4642 	 * return EINVAL instead of ENXIO, so we map it here.
4643 	 */
4644 	return (e.error == ENXIO ? EINVAL : e.error);
4645 }
4646 
4647 /*
4648  * Flush local dirty pages to stable storage on the server.
4649  *
4650  * If FNODSYNC is specified, then there is nothing to do because
4651  * metadata changes are not cached on the client before being
4652  * sent to the server.
4653  */
4654 /* ARGSUSED */
4655 static int
4656 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
4657 {
4658 	int error;
4659 
4660 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4661 		return (0);
4662 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4663 		return (EIO);
4664 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4665 	if (!error)
4666 		error = VTOR4(vp)->r_error;
4667 	return (error);
4668 }
4669 
4670 /*
4671  * Weirdness: if the file was removed or the target of a rename
4672  * operation while it was open, it got renamed instead.  Here we
4673  * remove the renamed file.
4674  */
4675 /* ARGSUSED */
4676 void
4677 nfs4_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4678 {
4679 	rnode4_t *rp;
4680 
4681 	ASSERT(vp != DNLC_NO_VNODE);
4682 
4683 	rp = VTOR4(vp);
4684 
4685 	if (IS_SHADOW(vp, rp)) {
4686 		sv_inactive(vp);
4687 		return;
4688 	}
4689 
4690 	/*
4691 	 * If this is coming from the wrong zone, we let someone in the right
4692 	 * zone take care of it asynchronously.  We can get here due to
4693 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4694 	 * potentially turn into an expensive no-op if, for instance, v_count
4695 	 * gets incremented in the meantime, but it's still correct.
4696 	 */
4697 	if (nfs_zone() != VTOMI4(vp)->mi_zone) {
4698 		nfs4_async_inactive(vp, cr);
4699 		return;
4700 	}
4701 
4702 	/*
4703 	 * Some of the cleanup steps might require over-the-wire
4704 	 * operations.  Since VOP_INACTIVE can get called as a result of
4705 	 * other over-the-wire operations (e.g., an attribute cache update
4706 	 * can lead to a DNLC purge), doing those steps now would lead to a
4707 	 * nested call to the recovery framework, which can deadlock.  So
4708 	 * do any over-the-wire cleanups asynchronously, in a separate
4709 	 * thread.
4710 	 */
4711 
4712 	mutex_enter(&rp->r_os_lock);
4713 	mutex_enter(&rp->r_statelock);
4714 	mutex_enter(&rp->r_statev4_lock);
4715 
4716 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4717 		mutex_exit(&rp->r_statev4_lock);
4718 		mutex_exit(&rp->r_statelock);
4719 		mutex_exit(&rp->r_os_lock);
4720 		nfs4_async_inactive(vp, cr);
4721 		return;
4722 	}
4723 
4724 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4725 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4726 		mutex_exit(&rp->r_statev4_lock);
4727 		mutex_exit(&rp->r_statelock);
4728 		mutex_exit(&rp->r_os_lock);
4729 		nfs4_async_inactive(vp, cr);
4730 		return;
4731 	}
4732 
4733 	if (rp->r_unldvp != NULL) {
4734 		mutex_exit(&rp->r_statev4_lock);
4735 		mutex_exit(&rp->r_statelock);
4736 		mutex_exit(&rp->r_os_lock);
4737 		nfs4_async_inactive(vp, cr);
4738 		return;
4739 	}
4740 	mutex_exit(&rp->r_statev4_lock);
4741 	mutex_exit(&rp->r_statelock);
4742 	mutex_exit(&rp->r_os_lock);
4743 
4744 	rp4_addfree(rp, cr);
4745 }
4746 
4747 /*
4748  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4749  * various bits of state.  The caller must not refer to vp after this call.
4750  */
4751 
4752 void
4753 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4754 {
4755 	rnode4_t *rp = VTOR4(vp);
4756 	nfs4_recov_state_t recov_state;
4757 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4758 	vnode_t *unldvp;
4759 	char *unlname;
4760 	cred_t *unlcred;
4761 	COMPOUND4args_clnt args;
4762 	COMPOUND4res_clnt res, *resp;
4763 	nfs_argop4 argop[2];
4764 	int doqueue;
4765 #ifdef DEBUG
4766 	char *name;
4767 #endif
4768 
4769 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
4770 	ASSERT(!IS_SHADOW(vp, rp));
4771 
4772 #ifdef DEBUG
4773 	name = fn_name(VTOSV(vp)->sv_name);
4774 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4775 	    "release vnode %s", name));
4776 	kmem_free(name, MAXNAMELEN);
4777 #endif
4778 
4779 	if (vp->v_type == VREG) {
4780 		bool_t recov_failed = FALSE;
4781 
4782 		e.error = nfs4close_all(vp, cr);
4783 		if (e.error) {
4784 			/* Check to see if recovery failed */
4785 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4786 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4787 				recov_failed = TRUE;
4788 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4789 			if (!recov_failed) {
4790 				mutex_enter(&rp->r_statelock);
4791 				if (rp->r_flags & R4RECOVERR)
4792 					recov_failed = TRUE;
4793 				mutex_exit(&rp->r_statelock);
4794 			}
4795 			if (recov_failed) {
4796 				NFS4_DEBUG(nfs4_client_recov_debug,
4797 				    (CE_NOTE, "nfs4_inactive_otw: "
4798 				    "close failed (recovery failure)"));
4799 			}
4800 		}
4801 	}
4802 
4803 redo:
4804 	if (rp->r_unldvp == NULL) {
4805 		rp4_addfree(rp, cr);
4806 		return;
4807 	}
4808 
4809 	/*
4810 	 * Save the vnode pointer for the directory where the
4811 	 * unlinked-open file got renamed, then set it to NULL
4812 	 * to prevent another thread from getting here before
4813 	 * we're done with the remove.  While we have the
4814 	 * statelock, make local copies of the pertinent rnode
4815 	 * fields.  If we weren't to do this in an atomic way, the
4816 	 * the unl* fields could become inconsistent with respect
4817 	 * to each other due to a race condition between this
4818 	 * code and nfs_remove().  See bug report 1034328.
4819 	 */
4820 	mutex_enter(&rp->r_statelock);
4821 	if (rp->r_unldvp == NULL) {
4822 		mutex_exit(&rp->r_statelock);
4823 		rp4_addfree(rp, cr);
4824 		return;
4825 	}
4826 
4827 	unldvp = rp->r_unldvp;
4828 	rp->r_unldvp = NULL;
4829 	unlname = rp->r_unlname;
4830 	rp->r_unlname = NULL;
4831 	unlcred = rp->r_unlcred;
4832 	rp->r_unlcred = NULL;
4833 	mutex_exit(&rp->r_statelock);
4834 
4835 	/*
4836 	 * If there are any dirty pages left, then flush
4837 	 * them.  This is unfortunate because they just
4838 	 * may get thrown away during the remove operation,
4839 	 * but we have to do this for correctness.
4840 	 */
4841 	if (nfs4_has_pages(vp) &&
4842 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4843 		ASSERT(vp->v_type != VCHR);
4844 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, NULL);
4845 		if (e.error) {
4846 			mutex_enter(&rp->r_statelock);
4847 			if (!rp->r_error)
4848 				rp->r_error = e.error;
4849 			mutex_exit(&rp->r_statelock);
4850 		}
4851 	}
4852 
4853 	recov_state.rs_flags = 0;
4854 	recov_state.rs_num_retry_despite_err = 0;
4855 recov_retry_remove:
4856 	/*
4857 	 * Do the remove operation on the renamed file
4858 	 */
4859 	args.ctag = TAG_INACTIVE;
4860 
4861 	/*
4862 	 * Remove ops: putfh dir; remove
4863 	 */
4864 	args.array_len = 2;
4865 	args.array = argop;
4866 
4867 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4868 	if (e.error) {
4869 		kmem_free(unlname, MAXNAMELEN);
4870 		crfree(unlcred);
4871 		VN_RELE(unldvp);
4872 		/*
4873 		 * Try again; this time around r_unldvp will be NULL, so we'll
4874 		 * just call rp4_addfree() and return.
4875 		 */
4876 		goto redo;
4877 	}
4878 
4879 	/* putfh directory */
4880 	argop[0].argop = OP_CPUTFH;
4881 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4882 
4883 	/* remove */
4884 	argop[1].argop = OP_CREMOVE;
4885 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4886 
4887 	doqueue = 1;
4888 	resp = &res;
4889 
4890 #if 0 /* notyet */
4891 	/*
4892 	 * Can't do this yet.  We may be being called from
4893 	 * dnlc_purge_XXX while that routine is holding a
4894 	 * mutex lock to the nc_rele list.  The calls to
4895 	 * nfs3_cache_wcc_data may result in calls to
4896 	 * dnlc_purge_XXX.  This will result in a deadlock.
4897 	 */
4898 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4899 	if (e.error) {
4900 		PURGE_ATTRCACHE4(unldvp);
4901 		resp = NULL;
4902 	} else if (res.status) {
4903 		e.error = geterrno4(res.status);
4904 		PURGE_ATTRCACHE4(unldvp);
4905 		/*
4906 		 * This code is inactive right now
4907 		 * but if made active there should
4908 		 * be a nfs4_end_op() call before
4909 		 * nfs4_purge_stale_fh to avoid start_op()
4910 		 * deadlock. See BugId: 4948726
4911 		 */
4912 		nfs4_purge_stale_fh(error, unldvp, cr);
4913 	} else {
4914 		nfs_resop4 *resop;
4915 		REMOVE4res *rm_res;
4916 
4917 		resop = &res.array[1];
4918 		rm_res = &resop->nfs_resop4_u.opremove;
4919 		/*
4920 		 * Update directory cache attribute,
4921 		 * readdir and dnlc caches.
4922 		 */
4923 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4924 	}
4925 #else
4926 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4927 
4928 	PURGE_ATTRCACHE4(unldvp);
4929 #endif
4930 
4931 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4932 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4933 		    NULL, NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
4934 			if (!e.error)
4935 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4936 				    (caddr_t)&res);
4937 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4938 			    &recov_state, TRUE);
4939 			goto recov_retry_remove;
4940 		}
4941 	}
4942 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4943 
4944 	/*
4945 	 * Release stuff held for the remove
4946 	 */
4947 	VN_RELE(unldvp);
4948 	if (!e.error && resp)
4949 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4950 
4951 	kmem_free(unlname, MAXNAMELEN);
4952 	crfree(unlcred);
4953 	goto redo;
4954 }
4955 
4956 /*
4957  * Remote file system operations having to do with directory manipulation.
4958  */
4959 /* ARGSUSED3 */
4960 int
4961 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4962     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
4963     int *direntflags, pathname_t *realpnp)
4964 {
4965 	int error;
4966 	vnode_t *vp, *avp = NULL;
4967 	rnode4_t *drp;
4968 
4969 	*vpp = NULL;
4970 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4971 		return (EPERM);
4972 	/*
4973 	 * if LOOKUP_XATTR, must replace dvp (object) with
4974 	 * object's attrdir before continuing with lookup
4975 	 */
4976 	if (flags & LOOKUP_XATTR) {
4977 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4978 		if (error)
4979 			return (error);
4980 
4981 		dvp = avp;
4982 
4983 		/*
4984 		 * If lookup is for "", just return dvp now.  The attrdir
4985 		 * has already been activated (from nfs4lookup_xattr), and
4986 		 * the caller will RELE the original dvp -- not
4987 		 * the attrdir.  So, set vpp and return.
4988 		 * Currently, when the LOOKUP_XATTR flag is
4989 		 * passed to VOP_LOOKUP, the name is always empty, and
4990 		 * shortcircuiting here avoids 3 unneeded lock/unlock
4991 		 * pairs.
4992 		 *
4993 		 * If a non-empty name was provided, then it is the
4994 		 * attribute name, and it will be looked up below.
4995 		 */
4996 		if (*nm == '\0') {
4997 			*vpp = dvp;
4998 			return (0);
4999 		}
5000 
5001 		/*
5002 		 * The vfs layer never sends a name when asking for the
5003 		 * attrdir, so we should never get here (unless of course
5004 		 * name is passed at some time in future -- at which time
5005 		 * we'll blow up here).
5006 		 */
5007 		ASSERT(0);
5008 	}
5009 
5010 	drp = VTOR4(dvp);
5011 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
5012 		return (EINTR);
5013 
5014 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
5015 	nfs_rw_exit(&drp->r_rwlock);
5016 
5017 	/*
5018 	 * If vnode is a device, create special vnode.
5019 	 */
5020 	if (!error && ISVDEV((*vpp)->v_type)) {
5021 		vp = *vpp;
5022 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
5023 		VN_RELE(vp);
5024 	}
5025 
5026 	return (error);
5027 }
5028 
5029 /* ARGSUSED */
5030 static int
5031 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
5032 {
5033 	int error;
5034 	rnode4_t *drp;
5035 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
5036 	mntinfo4_t *mi;
5037 
5038 	mi = VTOMI4(dvp);
5039 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR) &&
5040 	    !vfs_has_feature(mi->mi_vfsp, VFSFT_SYSATTR_VIEWS))
5041 		return (EINVAL);
5042 
5043 	drp = VTOR4(dvp);
5044 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
5045 		return (EINTR);
5046 
5047 	mutex_enter(&drp->r_statelock);
5048 	/*
5049 	 * If the server doesn't support xattrs just return EINVAL
5050 	 */
5051 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
5052 		mutex_exit(&drp->r_statelock);
5053 		nfs_rw_exit(&drp->r_rwlock);
5054 		return (EINVAL);
5055 	}
5056 
5057 	/*
5058 	 * If there is a cached xattr directory entry,
5059 	 * use it as long as the attributes are valid. If the
5060 	 * attributes are not valid, take the simple approach and
5061 	 * free the cached value and re-fetch a new value.
5062 	 *
5063 	 * We don't negative entry cache for now, if we did we
5064 	 * would need to check if the file has changed on every
5065 	 * lookup. But xattrs don't exist very often and failing
5066 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
5067 	 * so do an openattr over the wire for now.
5068 	 */
5069 	if (drp->r_xattr_dir != NULL) {
5070 		if (ATTRCACHE4_VALID(dvp)) {
5071 			VN_HOLD(drp->r_xattr_dir);
5072 			*vpp = drp->r_xattr_dir;
5073 			mutex_exit(&drp->r_statelock);
5074 			nfs_rw_exit(&drp->r_rwlock);
5075 			return (0);
5076 		}
5077 		VN_RELE(drp->r_xattr_dir);
5078 		drp->r_xattr_dir = NULL;
5079 	}
5080 	mutex_exit(&drp->r_statelock);
5081 
5082 	error = nfs4openattr(dvp, vpp, cflag, cr);
5083 
5084 	nfs_rw_exit(&drp->r_rwlock);
5085 
5086 	return (error);
5087 }
5088 
5089 static int
5090 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
5091 {
5092 	int error;
5093 	rnode4_t *drp;
5094 
5095 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5096 
5097 	/*
5098 	 * If lookup is for "", just return dvp.  Don't need
5099 	 * to send it over the wire, look it up in the dnlc,
5100 	 * or perform any access checks.
5101 	 */
5102 	if (*nm == '\0') {
5103 		VN_HOLD(dvp);
5104 		*vpp = dvp;
5105 		return (0);
5106 	}
5107 
5108 	/*
5109 	 * Can't do lookups in non-directories.
5110 	 */
5111 	if (dvp->v_type != VDIR)
5112 		return (ENOTDIR);
5113 
5114 	/*
5115 	 * If lookup is for ".", just return dvp.  Don't need
5116 	 * to send it over the wire or look it up in the dnlc,
5117 	 * just need to check access.
5118 	 */
5119 	if (nm[0] == '.' && nm[1] == '\0') {
5120 		error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5121 		if (error)
5122 			return (error);
5123 		VN_HOLD(dvp);
5124 		*vpp = dvp;
5125 		return (0);
5126 	}
5127 
5128 	drp = VTOR4(dvp);
5129 	if (!(drp->r_flags & R4LOOKUP)) {
5130 		mutex_enter(&drp->r_statelock);
5131 		drp->r_flags |= R4LOOKUP;
5132 		mutex_exit(&drp->r_statelock);
5133 	}
5134 
5135 	*vpp = NULL;
5136 	/*
5137 	 * Lookup this name in the DNLC.  If there is no entry
5138 	 * lookup over the wire.
5139 	 */
5140 	if (!skipdnlc)
5141 		*vpp = dnlc_lookup(dvp, nm);
5142 	if (*vpp == NULL) {
5143 		/*
5144 		 * We need to go over the wire to lookup the name.
5145 		 */
5146 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
5147 	}
5148 
5149 	/*
5150 	 * We hit on the dnlc
5151 	 */
5152 	if (*vpp != DNLC_NO_VNODE ||
5153 	    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
5154 		/*
5155 		 * But our attrs may not be valid.
5156 		 */
5157 		if (ATTRCACHE4_VALID(dvp)) {
5158 			error = nfs4_waitfor_purge_complete(dvp);
5159 			if (error) {
5160 				VN_RELE(*vpp);
5161 				*vpp = NULL;
5162 				return (error);
5163 			}
5164 
5165 			/*
5166 			 * If after the purge completes, check to make sure
5167 			 * our attrs are still valid.
5168 			 */
5169 			if (ATTRCACHE4_VALID(dvp)) {
5170 				/*
5171 				 * If we waited for a purge we may have
5172 				 * lost our vnode so look it up again.
5173 				 */
5174 				VN_RELE(*vpp);
5175 				*vpp = dnlc_lookup(dvp, nm);
5176 				if (*vpp == NULL)
5177 					return (nfs4lookupnew_otw(dvp,
5178 					    nm, vpp, cr));
5179 
5180 				/*
5181 				 * The access cache should almost always hit
5182 				 */
5183 				error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5184 
5185 				if (error) {
5186 					VN_RELE(*vpp);
5187 					*vpp = NULL;
5188 					return (error);
5189 				}
5190 				if (*vpp == DNLC_NO_VNODE) {
5191 					VN_RELE(*vpp);
5192 					*vpp = NULL;
5193 					return (ENOENT);
5194 				}
5195 				return (0);
5196 			}
5197 		}
5198 	}
5199 
5200 	ASSERT(*vpp != NULL);
5201 
5202 	/*
5203 	 * We may have gotten here we have one of the following cases:
5204 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5205 	 *		need to validate them.
5206 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5207 	 *		must validate.
5208 	 *
5209 	 * Go to the server and check if the directory has changed, if
5210 	 * it hasn't we are done and can use the dnlc entry.
5211 	 */
5212 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5213 }
5214 
5215 /*
5216  * Go to the server and check if the directory has changed, if
5217  * it hasn't we are done and can use the dnlc entry.  If it
5218  * has changed we get a new copy of its attributes and check
5219  * the access for VEXEC, then relookup the filename and
5220  * get its filehandle and attributes.
5221  *
5222  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5223  *	if the NVERIFY failed we must
5224  *		purge the caches
5225  *		cache new attributes (will set r_time_attr_inval)
5226  *		cache new access
5227  *		recheck VEXEC access
5228  *		add name to dnlc, possibly negative
5229  *		if LOOKUP succeeded
5230  *			cache new attributes
5231  *	else
5232  *		set a new r_time_attr_inval for dvp
5233  *		check to make sure we have access
5234  *
5235  * The vpp returned is the vnode passed in if the directory is valid,
5236  * a new vnode if successful lookup, or NULL on error.
5237  */
5238 static int
5239 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5240 {
5241 	COMPOUND4args_clnt args;
5242 	COMPOUND4res_clnt res;
5243 	fattr4 *ver_fattr;
5244 	fattr4_change dchange;
5245 	int32_t *ptr;
5246 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5247 	nfs_argop4 *argop;
5248 	int doqueue;
5249 	mntinfo4_t *mi;
5250 	nfs4_recov_state_t recov_state;
5251 	hrtime_t t;
5252 	int isdotdot;
5253 	vnode_t *nvp;
5254 	nfs_fh4 *fhp;
5255 	nfs4_sharedfh_t *sfhp;
5256 	nfs4_access_type_t cacc;
5257 	rnode4_t *nrp;
5258 	rnode4_t *drp = VTOR4(dvp);
5259 	nfs4_ga_res_t *garp = NULL;
5260 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5261 
5262 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5263 	ASSERT(nm != NULL);
5264 	ASSERT(nm[0] != '\0');
5265 	ASSERT(dvp->v_type == VDIR);
5266 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5267 	ASSERT(*vpp != NULL);
5268 
5269 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5270 		isdotdot = 1;
5271 		args.ctag = TAG_LOOKUP_VPARENT;
5272 	} else {
5273 		/*
5274 		 * If dvp were a stub, it should have triggered and caused
5275 		 * a mount for us to get this far.
5276 		 */
5277 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5278 
5279 		isdotdot = 0;
5280 		args.ctag = TAG_LOOKUP_VALID;
5281 	}
5282 
5283 	mi = VTOMI4(dvp);
5284 	recov_state.rs_flags = 0;
5285 	recov_state.rs_num_retry_despite_err = 0;
5286 
5287 	nvp = NULL;
5288 
5289 	/* Save the original mount point security information */
5290 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5291 
5292 recov_retry:
5293 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5294 	    &recov_state, NULL);
5295 	if (e.error) {
5296 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5297 		VN_RELE(*vpp);
5298 		*vpp = NULL;
5299 		return (e.error);
5300 	}
5301 
5302 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5303 
5304 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5305 	args.array_len = 7;
5306 	args.array = argop;
5307 
5308 	/* 0. putfh file */
5309 	argop[0].argop = OP_CPUTFH;
5310 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5311 
5312 	/* 1. nverify the change info */
5313 	argop[1].argop = OP_NVERIFY;
5314 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5315 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5316 	ver_fattr->attrlist4 = (char *)&dchange;
5317 	ptr = (int32_t *)&dchange;
5318 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5319 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5320 
5321 	/* 2. getattr directory */
5322 	argop[2].argop = OP_GETATTR;
5323 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5324 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5325 
5326 	/* 3. access directory */
5327 	argop[3].argop = OP_ACCESS;
5328 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5329 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5330 
5331 	/* 4. lookup name */
5332 	if (isdotdot) {
5333 		argop[4].argop = OP_LOOKUPP;
5334 	} else {
5335 		argop[4].argop = OP_CLOOKUP;
5336 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5337 	}
5338 
5339 	/* 5. resulting file handle */
5340 	argop[5].argop = OP_GETFH;
5341 
5342 	/* 6. resulting file attributes */
5343 	argop[6].argop = OP_GETATTR;
5344 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5345 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5346 
5347 	doqueue = 1;
5348 	t = gethrtime();
5349 
5350 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5351 
5352 	if (!isdotdot && res.status == NFS4ERR_MOVED) {
5353 		e.error = nfs4_setup_referral(dvp, nm, vpp, cr);
5354 		if (e.error != 0 && *vpp != NULL)
5355 			VN_RELE(*vpp);
5356 		nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5357 		    &recov_state, FALSE);
5358 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5359 		kmem_free(argop, argoplist_size);
5360 		return (e.error);
5361 	}
5362 
5363 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5364 		/*
5365 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5366 		 * from this thread, do not go thru the recovery thread since
5367 		 * we need the nm information.
5368 		 *
5369 		 * Not doing dotdot case because there is no specification
5370 		 * for (PUTFH, SECINFO "..") yet.
5371 		 */
5372 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5373 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5374 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5375 				    &recov_state, FALSE);
5376 			else
5377 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5378 				    &recov_state, TRUE);
5379 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5380 			kmem_free(argop, argoplist_size);
5381 			if (!e.error)
5382 				goto recov_retry;
5383 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5384 			VN_RELE(*vpp);
5385 			*vpp = NULL;
5386 			return (e.error);
5387 		}
5388 
5389 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5390 		    OP_LOOKUP, NULL, NULL, NULL) == FALSE) {
5391 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5392 			    &recov_state, TRUE);
5393 
5394 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5395 			kmem_free(argop, argoplist_size);
5396 			goto recov_retry;
5397 		}
5398 	}
5399 
5400 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5401 
5402 	if (e.error || res.array_len == 0) {
5403 		/*
5404 		 * If e.error isn't set, then reply has no ops (or we couldn't
5405 		 * be here).  The only legal way to reply without an op array
5406 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5407 		 * be in the reply for all other status values.
5408 		 *
5409 		 * For valid replies without an ops array, return ENOTSUP
5410 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5411 		 * return EIO -- don't trust status.
5412 		 */
5413 		if (e.error == 0)
5414 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5415 			    ENOTSUP : EIO;
5416 		VN_RELE(*vpp);
5417 		*vpp = NULL;
5418 		kmem_free(argop, argoplist_size);
5419 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5420 		return (e.error);
5421 	}
5422 
5423 	if (res.status != NFS4ERR_SAME) {
5424 		e.error = geterrno4(res.status);
5425 
5426 		/*
5427 		 * The NVERIFY "failed" so the directory has changed
5428 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5429 		 * cleanly.
5430 		 */
5431 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5432 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5433 			nfs4_purge_stale_fh(e.error, dvp, cr);
5434 			VN_RELE(*vpp);
5435 			*vpp = NULL;
5436 			goto exit;
5437 		}
5438 
5439 		/*
5440 		 * We know the NVERIFY "failed" so we must:
5441 		 *	purge the caches (access and indirectly dnlc if needed)
5442 		 */
5443 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5444 
5445 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5446 			nfs4_purge_stale_fh(e.error, dvp, cr);
5447 			VN_RELE(*vpp);
5448 			*vpp = NULL;
5449 			goto exit;
5450 		}
5451 
5452 		/*
5453 		 * Install new cached attributes for the directory
5454 		 */
5455 		nfs4_attr_cache(dvp,
5456 		    &res.array[2].nfs_resop4_u.opgetattr.ga_res,
5457 		    t, cr, FALSE, NULL);
5458 
5459 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5460 			nfs4_purge_stale_fh(e.error, dvp, cr);
5461 			VN_RELE(*vpp);
5462 			*vpp = NULL;
5463 			e.error = geterrno4(res.status);
5464 			goto exit;
5465 		}
5466 
5467 		/*
5468 		 * Now we know the directory is valid,
5469 		 * cache new directory access
5470 		 */
5471 		nfs4_access_cache(drp,
5472 		    args.array[3].nfs_argop4_u.opaccess.access,
5473 		    res.array[3].nfs_resop4_u.opaccess.access, cr);
5474 
5475 		/*
5476 		 * recheck VEXEC access
5477 		 */
5478 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5479 		if (cacc != NFS4_ACCESS_ALLOWED) {
5480 			/*
5481 			 * Directory permissions might have been revoked
5482 			 */
5483 			if (cacc == NFS4_ACCESS_DENIED) {
5484 				e.error = EACCES;
5485 				VN_RELE(*vpp);
5486 				*vpp = NULL;
5487 				goto exit;
5488 			}
5489 
5490 			/*
5491 			 * Somehow we must not have asked for enough
5492 			 * so try a singleton ACCESS, should never happen.
5493 			 */
5494 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5495 			if (e.error) {
5496 				VN_RELE(*vpp);
5497 				*vpp = NULL;
5498 				goto exit;
5499 			}
5500 		}
5501 
5502 		e.error = geterrno4(res.status);
5503 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5504 			/*
5505 			 * The lookup failed, probably no entry
5506 			 */
5507 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5508 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5509 			} else {
5510 				/*
5511 				 * Might be some other error, so remove
5512 				 * the dnlc entry to make sure we start all
5513 				 * over again, next time.
5514 				 */
5515 				dnlc_remove(dvp, nm);
5516 			}
5517 			VN_RELE(*vpp);
5518 			*vpp = NULL;
5519 			goto exit;
5520 		}
5521 
5522 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5523 			/*
5524 			 * The file exists but we can't get its fh for
5525 			 * some unknown reason.  Remove it from the dnlc
5526 			 * and error out to be safe.
5527 			 */
5528 			dnlc_remove(dvp, nm);
5529 			VN_RELE(*vpp);
5530 			*vpp = NULL;
5531 			goto exit;
5532 		}
5533 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5534 		if (fhp->nfs_fh4_len == 0) {
5535 			/*
5536 			 * The file exists but a bogus fh
5537 			 * some unknown reason.  Remove it from the dnlc
5538 			 * and error out to be safe.
5539 			 */
5540 			e.error = ENOENT;
5541 			dnlc_remove(dvp, nm);
5542 			VN_RELE(*vpp);
5543 			*vpp = NULL;
5544 			goto exit;
5545 		}
5546 		sfhp = sfh4_get(fhp, mi);
5547 
5548 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5549 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5550 
5551 		/*
5552 		 * Make the new rnode
5553 		 */
5554 		if (isdotdot) {
5555 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5556 			if (e.error) {
5557 				sfh4_rele(&sfhp);
5558 				VN_RELE(*vpp);
5559 				*vpp = NULL;
5560 				goto exit;
5561 			}
5562 			/*
5563 			 * XXX if nfs4_make_dotdot uses an existing rnode
5564 			 * XXX it doesn't update the attributes.
5565 			 * XXX for now just save them again to save an OTW
5566 			 */
5567 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5568 		} else {
5569 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5570 			    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
5571 			/*
5572 			 * If v_type == VNON, then garp was NULL because
5573 			 * the last op in the compound failed and makenfs4node
5574 			 * could not find the vnode for sfhp. It created
5575 			 * a new vnode, so we have nothing to purge here.
5576 			 */
5577 			if (nvp->v_type == VNON) {
5578 				vattr_t vattr;
5579 
5580 				vattr.va_mask = AT_TYPE;
5581 				/*
5582 				 * N.B. We've already called nfs4_end_fop above.
5583 				 */
5584 				e.error = nfs4getattr(nvp, &vattr, cr);
5585 				if (e.error) {
5586 					sfh4_rele(&sfhp);
5587 					VN_RELE(*vpp);
5588 					*vpp = NULL;
5589 					VN_RELE(nvp);
5590 					goto exit;
5591 				}
5592 				nvp->v_type = vattr.va_type;
5593 			}
5594 		}
5595 		sfh4_rele(&sfhp);
5596 
5597 		nrp = VTOR4(nvp);
5598 		mutex_enter(&nrp->r_statev4_lock);
5599 		if (!nrp->created_v4) {
5600 			mutex_exit(&nrp->r_statev4_lock);
5601 			dnlc_update(dvp, nm, nvp);
5602 		} else
5603 			mutex_exit(&nrp->r_statev4_lock);
5604 
5605 		VN_RELE(*vpp);
5606 		*vpp = nvp;
5607 	} else {
5608 		hrtime_t now;
5609 		hrtime_t delta = 0;
5610 
5611 		e.error = 0;
5612 
5613 		/*
5614 		 * Because the NVERIFY "succeeded" we know that the
5615 		 * directory attributes are still valid
5616 		 * so update r_time_attr_inval
5617 		 */
5618 		now = gethrtime();
5619 		mutex_enter(&drp->r_statelock);
5620 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5621 			delta = now - drp->r_time_attr_saved;
5622 			if (delta < mi->mi_acdirmin)
5623 				delta = mi->mi_acdirmin;
5624 			else if (delta > mi->mi_acdirmax)
5625 				delta = mi->mi_acdirmax;
5626 		}
5627 		drp->r_time_attr_inval = now + delta;
5628 		mutex_exit(&drp->r_statelock);
5629 		dnlc_update(dvp, nm, *vpp);
5630 
5631 		/*
5632 		 * Even though we have a valid directory attr cache
5633 		 * and dnlc entry, we may not have access.
5634 		 * This should almost always hit the cache.
5635 		 */
5636 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5637 		if (e.error) {
5638 			VN_RELE(*vpp);
5639 			*vpp = NULL;
5640 		}
5641 
5642 		if (*vpp == DNLC_NO_VNODE) {
5643 			VN_RELE(*vpp);
5644 			*vpp = NULL;
5645 			e.error = ENOENT;
5646 		}
5647 	}
5648 
5649 exit:
5650 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5651 	kmem_free(argop, argoplist_size);
5652 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5653 	return (e.error);
5654 }
5655 
5656 /*
5657  * We need to go over the wire to lookup the name, but
5658  * while we are there verify the directory has not
5659  * changed but if it has, get new attributes and check access
5660  *
5661  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5662  *					NVERIFY GETATTR ACCESS
5663  *
5664  * With the results:
5665  *	if the NVERIFY failed we must purge the caches, add new attributes,
5666  *		and cache new access.
5667  *	set a new r_time_attr_inval
5668  *	add name to dnlc, possibly negative
5669  *	if LOOKUP succeeded
5670  *		cache new attributes
5671  */
5672 static int
5673 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5674 {
5675 	COMPOUND4args_clnt args;
5676 	COMPOUND4res_clnt res;
5677 	fattr4 *ver_fattr;
5678 	fattr4_change dchange;
5679 	int32_t *ptr;
5680 	nfs4_ga_res_t *garp = NULL;
5681 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5682 	nfs_argop4 *argop;
5683 	int doqueue;
5684 	mntinfo4_t *mi;
5685 	nfs4_recov_state_t recov_state;
5686 	hrtime_t t;
5687 	int isdotdot;
5688 	vnode_t *nvp;
5689 	nfs_fh4 *fhp;
5690 	nfs4_sharedfh_t *sfhp;
5691 	nfs4_access_type_t cacc;
5692 	rnode4_t *nrp;
5693 	rnode4_t *drp = VTOR4(dvp);
5694 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5695 
5696 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5697 	ASSERT(nm != NULL);
5698 	ASSERT(nm[0] != '\0');
5699 	ASSERT(dvp->v_type == VDIR);
5700 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5701 	ASSERT(*vpp == NULL);
5702 
5703 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5704 		isdotdot = 1;
5705 		args.ctag = TAG_LOOKUP_PARENT;
5706 	} else {
5707 		/*
5708 		 * If dvp were a stub, it should have triggered and caused
5709 		 * a mount for us to get this far.
5710 		 */
5711 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5712 
5713 		isdotdot = 0;
5714 		args.ctag = TAG_LOOKUP;
5715 	}
5716 
5717 	mi = VTOMI4(dvp);
5718 	recov_state.rs_flags = 0;
5719 	recov_state.rs_num_retry_despite_err = 0;
5720 
5721 	nvp = NULL;
5722 
5723 	/* Save the original mount point security information */
5724 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5725 
5726 recov_retry:
5727 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5728 	    &recov_state, NULL);
5729 	if (e.error) {
5730 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5731 		return (e.error);
5732 	}
5733 
5734 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5735 
5736 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5737 	args.array_len = 9;
5738 	args.array = argop;
5739 
5740 	/* 0. putfh file */
5741 	argop[0].argop = OP_CPUTFH;
5742 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5743 
5744 	/* 1. savefh for the nverify */
5745 	argop[1].argop = OP_SAVEFH;
5746 
5747 	/* 2. lookup name */
5748 	if (isdotdot) {
5749 		argop[2].argop = OP_LOOKUPP;
5750 	} else {
5751 		argop[2].argop = OP_CLOOKUP;
5752 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5753 	}
5754 
5755 	/* 3. resulting file handle */
5756 	argop[3].argop = OP_GETFH;
5757 
5758 	/* 4. resulting file attributes */
5759 	argop[4].argop = OP_GETATTR;
5760 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5761 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5762 
5763 	/* 5. restorefh back the directory for the nverify */
5764 	argop[5].argop = OP_RESTOREFH;
5765 
5766 	/* 6. nverify the change info */
5767 	argop[6].argop = OP_NVERIFY;
5768 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5769 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5770 	ver_fattr->attrlist4 = (char *)&dchange;
5771 	ptr = (int32_t *)&dchange;
5772 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5773 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5774 
5775 	/* 7. getattr directory */
5776 	argop[7].argop = OP_GETATTR;
5777 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5778 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5779 
5780 	/* 8. access directory */
5781 	argop[8].argop = OP_ACCESS;
5782 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5783 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5784 
5785 	doqueue = 1;
5786 	t = gethrtime();
5787 
5788 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5789 
5790 	if (!isdotdot && res.status == NFS4ERR_MOVED) {
5791 		e.error = nfs4_setup_referral(dvp, nm, vpp, cr);
5792 		if (e.error != 0 && *vpp != NULL)
5793 			VN_RELE(*vpp);
5794 		nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5795 		    &recov_state, FALSE);
5796 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5797 		kmem_free(argop, argoplist_size);
5798 		return (e.error);
5799 	}
5800 
5801 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5802 		/*
5803 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5804 		 * from this thread, do not go thru the recovery thread since
5805 		 * we need the nm information.
5806 		 *
5807 		 * Not doing dotdot case because there is no specification
5808 		 * for (PUTFH, SECINFO "..") yet.
5809 		 */
5810 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5811 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5812 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5813 				    &recov_state, FALSE);
5814 			else
5815 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5816 				    &recov_state, TRUE);
5817 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5818 			kmem_free(argop, argoplist_size);
5819 			if (!e.error)
5820 				goto recov_retry;
5821 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5822 			return (e.error);
5823 		}
5824 
5825 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5826 		    OP_LOOKUP, NULL, NULL, NULL) == FALSE) {
5827 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5828 			    &recov_state, TRUE);
5829 
5830 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5831 			kmem_free(argop, argoplist_size);
5832 			goto recov_retry;
5833 		}
5834 	}
5835 
5836 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5837 
5838 	if (e.error || res.array_len == 0) {
5839 		/*
5840 		 * If e.error isn't set, then reply has no ops (or we couldn't
5841 		 * be here).  The only legal way to reply without an op array
5842 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5843 		 * be in the reply for all other status values.
5844 		 *
5845 		 * For valid replies without an ops array, return ENOTSUP
5846 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5847 		 * return EIO -- don't trust status.
5848 		 */
5849 		if (e.error == 0)
5850 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5851 			    ENOTSUP : EIO;
5852 
5853 		kmem_free(argop, argoplist_size);
5854 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5855 		return (e.error);
5856 	}
5857 
5858 	e.error = geterrno4(res.status);
5859 
5860 	/*
5861 	 * The PUTFH and SAVEFH may have failed.
5862 	 */
5863 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5864 	    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5865 		nfs4_purge_stale_fh(e.error, dvp, cr);
5866 		goto exit;
5867 	}
5868 
5869 	/*
5870 	 * Check if the file exists, if it does delay entering
5871 	 * into the dnlc until after we update the directory
5872 	 * attributes so we don't cause it to get purged immediately.
5873 	 */
5874 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5875 		/*
5876 		 * The lookup failed, probably no entry
5877 		 */
5878 		if (e.error == ENOENT && nfs4_lookup_neg_cache)
5879 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5880 		goto exit;
5881 	}
5882 
5883 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5884 		/*
5885 		 * The file exists but we can't get its fh for
5886 		 * some unknown reason. Error out to be safe.
5887 		 */
5888 		goto exit;
5889 	}
5890 
5891 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5892 	if (fhp->nfs_fh4_len == 0) {
5893 		/*
5894 		 * The file exists but a bogus fh
5895 		 * some unknown reason.  Error out to be safe.
5896 		 */
5897 		e.error = EIO;
5898 		goto exit;
5899 	}
5900 	sfhp = sfh4_get(fhp, mi);
5901 
5902 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5903 		sfh4_rele(&sfhp);
5904 		goto exit;
5905 	}
5906 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5907 
5908 	/*
5909 	 * The RESTOREFH may have failed
5910 	 */
5911 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5912 		sfh4_rele(&sfhp);
5913 		e.error = EIO;
5914 		goto exit;
5915 	}
5916 
5917 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5918 		/*
5919 		 * First make sure the NVERIFY failed as we expected,
5920 		 * if it didn't then be conservative and error out
5921 		 * as we can't trust the directory.
5922 		 */
5923 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5924 			sfh4_rele(&sfhp);
5925 			e.error = EIO;
5926 			goto exit;
5927 		}
5928 
5929 		/*
5930 		 * We know the NVERIFY "failed" so the directory has changed,
5931 		 * so we must:
5932 		 *	purge the caches (access and indirectly dnlc if needed)
5933 		 */
5934 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5935 
5936 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5937 			sfh4_rele(&sfhp);
5938 			goto exit;
5939 		}
5940 		nfs4_attr_cache(dvp,
5941 		    &res.array[7].nfs_resop4_u.opgetattr.ga_res,
5942 		    t, cr, FALSE, NULL);
5943 
5944 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5945 			nfs4_purge_stale_fh(e.error, dvp, cr);
5946 			sfh4_rele(&sfhp);
5947 			e.error = geterrno4(res.status);
5948 			goto exit;
5949 		}
5950 
5951 		/*
5952 		 * Now we know the directory is valid,
5953 		 * cache new directory access
5954 		 */
5955 		nfs4_access_cache(drp,
5956 		    args.array[8].nfs_argop4_u.opaccess.access,
5957 		    res.array[8].nfs_resop4_u.opaccess.access, cr);
5958 
5959 		/*
5960 		 * recheck VEXEC access
5961 		 */
5962 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5963 		if (cacc != NFS4_ACCESS_ALLOWED) {
5964 			/*
5965 			 * Directory permissions might have been revoked
5966 			 */
5967 			if (cacc == NFS4_ACCESS_DENIED) {
5968 				sfh4_rele(&sfhp);
5969 				e.error = EACCES;
5970 				goto exit;
5971 			}
5972 
5973 			/*
5974 			 * Somehow we must not have asked for enough
5975 			 * so try a singleton ACCESS should never happen
5976 			 */
5977 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5978 			if (e.error) {
5979 				sfh4_rele(&sfhp);
5980 				goto exit;
5981 			}
5982 		}
5983 
5984 		e.error = geterrno4(res.status);
5985 	} else {
5986 		hrtime_t now;
5987 		hrtime_t delta = 0;
5988 
5989 		e.error = 0;
5990 
5991 		/*
5992 		 * Because the NVERIFY "succeeded" we know that the
5993 		 * directory attributes are still valid
5994 		 * so update r_time_attr_inval
5995 		 */
5996 		now = gethrtime();
5997 		mutex_enter(&drp->r_statelock);
5998 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5999 			delta = now - drp->r_time_attr_saved;
6000 			if (delta < mi->mi_acdirmin)
6001 				delta = mi->mi_acdirmin;
6002 			else if (delta > mi->mi_acdirmax)
6003 				delta = mi->mi_acdirmax;
6004 		}
6005 		drp->r_time_attr_inval = now + delta;
6006 		mutex_exit(&drp->r_statelock);
6007 
6008 		/*
6009 		 * Even though we have a valid directory attr cache,
6010 		 * we may not have access.
6011 		 * This should almost always hit the cache.
6012 		 */
6013 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
6014 		if (e.error) {
6015 			sfh4_rele(&sfhp);
6016 			goto exit;
6017 		}
6018 	}
6019 
6020 	/*
6021 	 * Now we have successfully completed the lookup, if the
6022 	 * directory has changed we now have the valid attributes.
6023 	 * We also know we have directory access.
6024 	 * Create the new rnode and insert it in the dnlc.
6025 	 */
6026 	if (isdotdot) {
6027 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
6028 		if (e.error) {
6029 			sfh4_rele(&sfhp);
6030 			goto exit;
6031 		}
6032 		/*
6033 		 * XXX if nfs4_make_dotdot uses an existing rnode
6034 		 * XXX it doesn't update the attributes.
6035 		 * XXX for now just save them again to save an OTW
6036 		 */
6037 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
6038 	} else {
6039 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
6040 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
6041 	}
6042 	sfh4_rele(&sfhp);
6043 
6044 	nrp = VTOR4(nvp);
6045 	mutex_enter(&nrp->r_statev4_lock);
6046 	if (!nrp->created_v4) {
6047 		mutex_exit(&nrp->r_statev4_lock);
6048 		dnlc_update(dvp, nm, nvp);
6049 	} else
6050 		mutex_exit(&nrp->r_statev4_lock);
6051 
6052 	*vpp = nvp;
6053 
6054 exit:
6055 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6056 	kmem_free(argop, argoplist_size);
6057 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
6058 	return (e.error);
6059 }
6060 
6061 #ifdef DEBUG
6062 void
6063 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
6064 {
6065 	uint_t i, len;
6066 	zoneid_t zoneid = getzoneid();
6067 	char *s;
6068 
6069 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
6070 	for (i = 0; i < argcnt; i++) {
6071 		nfs_argop4 *op = &argbase[i];
6072 		switch (op->argop) {
6073 		case OP_CPUTFH:
6074 		case OP_PUTFH:
6075 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
6076 			break;
6077 		case OP_PUTROOTFH:
6078 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
6079 			break;
6080 		case OP_CLOOKUP:
6081 			s = op->nfs_argop4_u.opclookup.cname;
6082 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6083 			break;
6084 		case OP_LOOKUP:
6085 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
6086 			    &len, NULL);
6087 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6088 			kmem_free(s, len);
6089 			break;
6090 		case OP_LOOKUPP:
6091 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
6092 			break;
6093 		case OP_GETFH:
6094 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
6095 			break;
6096 		case OP_GETATTR:
6097 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
6098 			break;
6099 		case OP_OPENATTR:
6100 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
6101 			break;
6102 		default:
6103 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
6104 			    op->argop);
6105 			break;
6106 		}
6107 	}
6108 }
6109 #endif
6110 
6111 /*
6112  * nfs4lookup_setup - constructs a multi-lookup compound request.
6113  *
6114  * Given the path "nm1/nm2/.../nmn", the following compound requests
6115  * may be created:
6116  *
6117  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
6118  * is faster, for now.
6119  *
6120  * l4_getattrs indicates the type of compound requested.
6121  *
6122  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
6123  *
6124  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
6125  *
6126  *   total number of ops is n + 1.
6127  *
6128  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
6129  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
6130  *      before the last component, and only get attributes
6131  *      for the last component.  Note that the second-to-last
6132  *	pathname component is XATTR_RPATH, which does NOT go
6133  *	over-the-wire as a lookup.
6134  *
6135  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
6136  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
6137  *
6138  *   and total number of ops is n + 5.
6139  *
6140  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
6141  *      attribute directory: create lookups plus an OPENATTR
6142  *	replacing the last lookup.  Note that the last pathname
6143  *	component is XATTR_RPATH, which does NOT go over-the-wire
6144  *	as a lookup.
6145  *
6146  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
6147  *		Openattr; Getfh; Getattr }
6148  *
6149  *   and total number of ops is n + 5.
6150  *
6151  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6152  *	nodes too.
6153  *
6154  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6155  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6156  *
6157  *   and total number of ops is 3*n + 1.
6158  *
6159  * All cases: returns the index in the arg array of the final LOOKUP op, or
6160  * -1 if no LOOKUPs were used.
6161  */
6162 int
6163 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6164 {
6165 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6166 	nfs_argop4 *argbase, *argop;
6167 	int arglen, argcnt;
6168 	int n = 1;	/* number of components */
6169 	int nga = 1;	/* number of Getattr's in request */
6170 	char c = '\0', *s, *p;
6171 	int lookup_idx = -1;
6172 	int argoplist_size;
6173 
6174 	/* set lookuparg response result to 0 */
6175 	lookupargp->resp->status = NFS4_OK;
6176 
6177 	/* skip leading "/" or "." e.g. ".//./" if there is */
6178 	for (; ; nm++) {
6179 		if (*nm != '/' && *nm != '.')
6180 			break;
6181 
6182 		/* ".." is counted as 1 component */
6183 		if (*nm == '.' && *(nm + 1) != '/')
6184 			break;
6185 	}
6186 
6187 	/*
6188 	 * Find n = number of components - nm must be null terminated
6189 	 * Skip "." components.
6190 	 */
6191 	if (*nm != '\0')
6192 		for (n = 1, s = nm; *s != '\0'; s++) {
6193 			if ((*s == '/') && (*(s + 1) != '/') &&
6194 			    (*(s + 1) != '\0') &&
6195 			    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6196 			    *(s + 2) == '\0')))
6197 				n++;
6198 		}
6199 	else
6200 		n = 0;
6201 
6202 	/*
6203 	 * nga is number of components that need Getfh+Getattr
6204 	 */
6205 	switch (l4_getattrs) {
6206 	case LKP4_NO_ATTRIBUTES:
6207 		nga = 0;
6208 		break;
6209 	case LKP4_ALL_ATTRIBUTES:
6210 		nga = n;
6211 		/*
6212 		 * Always have at least 1 getfh, getattr pair
6213 		 */
6214 		if (nga == 0)
6215 			nga++;
6216 		break;
6217 	case LKP4_LAST_ATTRDIR:
6218 	case LKP4_LAST_NAMED_ATTR:
6219 		nga = n+1;
6220 		break;
6221 	}
6222 
6223 	/*
6224 	 * If change to use the filehandle attr instead of getfh
6225 	 * the following line can be deleted.
6226 	 */
6227 	nga *= 2;
6228 
6229 	/*
6230 	 * calculate number of ops in request as
6231 	 * header + trailer + lookups + getattrs
6232 	 */
6233 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6234 
6235 	argoplist_size = arglen * sizeof (nfs_argop4);
6236 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6237 	lookupargp->argsp->array = argop;
6238 
6239 	argcnt = lookupargp->header_len;
6240 	argop += argcnt;
6241 
6242 	/*
6243 	 * loop and create a lookup op and possibly getattr/getfh for
6244 	 * each component. Skip "." components.
6245 	 */
6246 	for (s = nm; *s != '\0'; s = p) {
6247 		/*
6248 		 * Set up a pathname struct for each component if needed
6249 		 */
6250 		while (*s == '/')
6251 			s++;
6252 		if (*s == '\0')
6253 			break;
6254 
6255 		for (p = s; (*p != '/') && (*p != '\0'); p++)
6256 			;
6257 		c = *p;
6258 		*p = '\0';
6259 
6260 		if (s[0] == '.' && s[1] == '\0') {
6261 			*p = c;
6262 			continue;
6263 		}
6264 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6265 		    strcmp(s, XATTR_RPATH) == 0) {
6266 			/* getfh XXX may not be needed in future */
6267 			argop->argop = OP_GETFH;
6268 			argop++;
6269 			argcnt++;
6270 
6271 			/* getattr */
6272 			argop->argop = OP_GETATTR;
6273 			argop->nfs_argop4_u.opgetattr.attr_request =
6274 			    lookupargp->ga_bits;
6275 			argop->nfs_argop4_u.opgetattr.mi =
6276 			    lookupargp->mi;
6277 			argop++;
6278 			argcnt++;
6279 
6280 			/* openattr */
6281 			argop->argop = OP_OPENATTR;
6282 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6283 		    strcmp(s, XATTR_RPATH) == 0) {
6284 			/* openattr */
6285 			argop->argop = OP_OPENATTR;
6286 			argop++;
6287 			argcnt++;
6288 
6289 			/* getfh XXX may not be needed in future */
6290 			argop->argop = OP_GETFH;
6291 			argop++;
6292 			argcnt++;
6293 
6294 			/* getattr */
6295 			argop->argop = OP_GETATTR;
6296 			argop->nfs_argop4_u.opgetattr.attr_request =
6297 			    lookupargp->ga_bits;
6298 			argop->nfs_argop4_u.opgetattr.mi =
6299 			    lookupargp->mi;
6300 			argop++;
6301 			argcnt++;
6302 			*p = c;
6303 			continue;
6304 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6305 			/* lookupp */
6306 			argop->argop = OP_LOOKUPP;
6307 		} else {
6308 			/* lookup */
6309 			argop->argop = OP_LOOKUP;
6310 			(void) str_to_utf8(s,
6311 			    &argop->nfs_argop4_u.oplookup.objname);
6312 		}
6313 		lookup_idx = argcnt;
6314 		argop++;
6315 		argcnt++;
6316 
6317 		*p = c;
6318 
6319 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6320 			/* getfh XXX may not be needed in future */
6321 			argop->argop = OP_GETFH;
6322 			argop++;
6323 			argcnt++;
6324 
6325 			/* getattr */
6326 			argop->argop = OP_GETATTR;
6327 			argop->nfs_argop4_u.opgetattr.attr_request =
6328 			    lookupargp->ga_bits;
6329 			argop->nfs_argop4_u.opgetattr.mi =
6330 			    lookupargp->mi;
6331 			argop++;
6332 			argcnt++;
6333 		}
6334 	}
6335 
6336 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6337 	    ((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6338 		if (needgetfh) {
6339 			/* stick in a post-lookup getfh */
6340 			argop->argop = OP_GETFH;
6341 			argcnt++;
6342 			argop++;
6343 		}
6344 		/* post-lookup getattr */
6345 		argop->argop = OP_GETATTR;
6346 		argop->nfs_argop4_u.opgetattr.attr_request =
6347 		    lookupargp->ga_bits;
6348 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6349 		argcnt++;
6350 	}
6351 	argcnt += lookupargp->trailer_len;	/* actual op count */
6352 	lookupargp->argsp->array_len = argcnt;
6353 	lookupargp->arglen = arglen;
6354 
6355 #ifdef DEBUG
6356 	if (nfs4_client_lookup_debug)
6357 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6358 #endif
6359 
6360 	return (lookup_idx);
6361 }
6362 
6363 static int
6364 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6365 {
6366 	COMPOUND4args_clnt	args;
6367 	COMPOUND4res_clnt	res;
6368 	GETFH4res	*gf_res = NULL;
6369 	nfs_argop4	argop[4];
6370 	nfs_resop4	*resop = NULL;
6371 	nfs4_sharedfh_t *sfhp;
6372 	hrtime_t t;
6373 	nfs4_error_t	e;
6374 
6375 	rnode4_t	*drp;
6376 	int		doqueue = 1;
6377 	vnode_t		*vp;
6378 	int		needrecov = 0;
6379 	nfs4_recov_state_t recov_state;
6380 
6381 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6382 
6383 	*avp = NULL;
6384 	recov_state.rs_flags = 0;
6385 	recov_state.rs_num_retry_despite_err = 0;
6386 
6387 recov_retry:
6388 	/* COMPOUND: putfh, openattr, getfh, getattr */
6389 	args.array_len = 4;
6390 	args.array = argop;
6391 	args.ctag = TAG_OPENATTR;
6392 
6393 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6394 	if (e.error)
6395 		return (e.error);
6396 
6397 	drp = VTOR4(dvp);
6398 
6399 	/* putfh */
6400 	argop[0].argop = OP_CPUTFH;
6401 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6402 
6403 	/* openattr */
6404 	argop[1].argop = OP_OPENATTR;
6405 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6406 
6407 	/* getfh */
6408 	argop[2].argop = OP_GETFH;
6409 
6410 	/* getattr */
6411 	argop[3].argop = OP_GETATTR;
6412 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6413 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6414 
6415 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6416 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6417 	    rnode4info(drp)));
6418 
6419 	t = gethrtime();
6420 
6421 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6422 
6423 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6424 	if (needrecov) {
6425 		bool_t abort;
6426 
6427 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6428 		    "nfs4openattr: initiating recovery\n"));
6429 
6430 		abort = nfs4_start_recovery(&e,
6431 		    VTOMI4(dvp), dvp, NULL, NULL, NULL,
6432 		    OP_OPENATTR, NULL, NULL, NULL);
6433 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6434 		if (!e.error) {
6435 			e.error = geterrno4(res.status);
6436 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6437 		}
6438 		if (abort == FALSE)
6439 			goto recov_retry;
6440 		return (e.error);
6441 	}
6442 
6443 	if (e.error) {
6444 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6445 		return (e.error);
6446 	}
6447 
6448 	if (res.status) {
6449 		/*
6450 		 * If OTW errro is NOTSUPP, then it should be
6451 		 * translated to EINVAL.  All Solaris file system
6452 		 * implementations return EINVAL to the syscall layer
6453 		 * when the attrdir cannot be created due to an
6454 		 * implementation restriction or noxattr mount option.
6455 		 */
6456 		if (res.status == NFS4ERR_NOTSUPP) {
6457 			mutex_enter(&drp->r_statelock);
6458 			if (drp->r_xattr_dir)
6459 				VN_RELE(drp->r_xattr_dir);
6460 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6461 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6462 			mutex_exit(&drp->r_statelock);
6463 
6464 			e.error = EINVAL;
6465 		} else {
6466 			e.error = geterrno4(res.status);
6467 		}
6468 
6469 		if (e.error) {
6470 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6471 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6472 			    needrecov);
6473 			return (e.error);
6474 		}
6475 	}
6476 
6477 	resop = &res.array[0];  /* putfh res */
6478 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6479 
6480 	resop = &res.array[1];  /* openattr res */
6481 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6482 
6483 	resop = &res.array[2];  /* getfh res */
6484 	gf_res = &resop->nfs_resop4_u.opgetfh;
6485 	if (gf_res->object.nfs_fh4_len == 0) {
6486 		*avp = NULL;
6487 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6488 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6489 		return (ENOENT);
6490 	}
6491 
6492 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6493 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6494 	    dvp->v_vfsp, t, cr, dvp,
6495 	    fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH, sfhp));
6496 	sfh4_rele(&sfhp);
6497 
6498 	if (e.error)
6499 		PURGE_ATTRCACHE4(vp);
6500 
6501 	mutex_enter(&vp->v_lock);
6502 	vp->v_flag |= V_XATTRDIR;
6503 	mutex_exit(&vp->v_lock);
6504 
6505 	*avp = vp;
6506 
6507 	mutex_enter(&drp->r_statelock);
6508 	if (drp->r_xattr_dir)
6509 		VN_RELE(drp->r_xattr_dir);
6510 	VN_HOLD(vp);
6511 	drp->r_xattr_dir = vp;
6512 
6513 	/*
6514 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6515 	 * NULL.  xattrs could be created at any time, and we have no
6516 	 * way to update pc4_xattr_exists in the base object if/when
6517 	 * it happens.
6518 	 */
6519 	drp->r_pathconf.pc4_xattr_valid = 0;
6520 
6521 	mutex_exit(&drp->r_statelock);
6522 
6523 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6524 
6525 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6526 
6527 	return (0);
6528 }
6529 
6530 /* ARGSUSED */
6531 static int
6532 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6533     int mode, vnode_t **vpp, cred_t *cr, int flags, caller_context_t *ct,
6534     vsecattr_t *vsecp)
6535 {
6536 	int error;
6537 	vnode_t *vp = NULL;
6538 	rnode4_t *rp;
6539 	struct vattr vattr;
6540 	rnode4_t *drp;
6541 	vnode_t *tempvp;
6542 	enum createmode4 createmode;
6543 	bool_t must_trunc = FALSE;
6544 	int	truncating = 0;
6545 
6546 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6547 		return (EPERM);
6548 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6549 		return (EINVAL);
6550 	}
6551 
6552 	/* . and .. have special meaning in the protocol, reject them. */
6553 
6554 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6555 		return (EISDIR);
6556 
6557 	drp = VTOR4(dvp);
6558 
6559 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6560 		return (EINTR);
6561 
6562 top:
6563 	/*
6564 	 * We make a copy of the attributes because the caller does not
6565 	 * expect us to change what va points to.
6566 	 */
6567 	vattr = *va;
6568 
6569 	/*
6570 	 * If the pathname is "", then dvp is the root vnode of
6571 	 * a remote file mounted over a local directory.
6572 	 * All that needs to be done is access
6573 	 * checking and truncation.  Note that we avoid doing
6574 	 * open w/ create because the parent directory might
6575 	 * be in pseudo-fs and the open would fail.
6576 	 */
6577 	if (*nm == '\0') {
6578 		error = 0;
6579 		VN_HOLD(dvp);
6580 		vp = dvp;
6581 		must_trunc = TRUE;
6582 	} else {
6583 		/*
6584 		 * We need to go over the wire, just to be sure whether the
6585 		 * file exists or not.  Using the DNLC can be dangerous in
6586 		 * this case when making a decision regarding existence.
6587 		 */
6588 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6589 	}
6590 
6591 	if (exclusive)
6592 		createmode = EXCLUSIVE4;
6593 	else
6594 		createmode = GUARDED4;
6595 
6596 	/*
6597 	 * error would be set if the file does not exist on the
6598 	 * server, so lets go create it.
6599 	 */
6600 	if (error) {
6601 		goto create_otw;
6602 	}
6603 
6604 	/*
6605 	 * File does exist on the server
6606 	 */
6607 	if (exclusive == EXCL)
6608 		error = EEXIST;
6609 	else if (vp->v_type == VDIR && (mode & VWRITE))
6610 		error = EISDIR;
6611 	else {
6612 		/*
6613 		 * If vnode is a device, create special vnode.
6614 		 */
6615 		if (ISVDEV(vp->v_type)) {
6616 			tempvp = vp;
6617 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6618 			VN_RELE(tempvp);
6619 		}
6620 		if (!(error = VOP_ACCESS(vp, mode, 0, cr, ct))) {
6621 			if ((vattr.va_mask & AT_SIZE) &&
6622 			    vp->v_type == VREG) {
6623 				rp = VTOR4(vp);
6624 				/*
6625 				 * Check here for large file handled
6626 				 * by LF-unaware process (as
6627 				 * ufs_create() does)
6628 				 */
6629 				if (!(flags & FOFFMAX)) {
6630 					mutex_enter(&rp->r_statelock);
6631 					if (rp->r_size > MAXOFF32_T)
6632 						error = EOVERFLOW;
6633 					mutex_exit(&rp->r_statelock);
6634 				}
6635 
6636 				/* if error is set then we need to return */
6637 				if (error) {
6638 					nfs_rw_exit(&drp->r_rwlock);
6639 					VN_RELE(vp);
6640 					return (error);
6641 				}
6642 
6643 				if (must_trunc) {
6644 					vattr.va_mask = AT_SIZE;
6645 					error = nfs4setattr(vp, &vattr, 0, cr,
6646 					    NULL);
6647 				} else {
6648 				/*
6649 				 * we know we have a regular file that already
6650 				 * exists and we may end up truncating the file
6651 				 * as a result of the open_otw, so flush out
6652 				 * any dirty pages for this file first.
6653 				 */
6654 					if (nfs4_has_pages(vp) &&
6655 					    ((rp->r_flags & R4DIRTY) ||
6656 					    rp->r_count > 0 ||
6657 					    rp->r_mapcnt > 0)) {
6658 						error = nfs4_putpage(vp,
6659 						    (offset_t)0, 0, 0, cr, ct);
6660 						if (error && (error == ENOSPC ||
6661 						    error == EDQUOT)) {
6662 							mutex_enter(
6663 							    &rp->r_statelock);
6664 							if (!rp->r_error)
6665 								rp->r_error =
6666 								    error;
6667 							mutex_exit(
6668 							    &rp->r_statelock);
6669 						}
6670 					}
6671 					vattr.va_mask = (AT_SIZE |
6672 					    AT_TYPE | AT_MODE);
6673 					vattr.va_type = VREG;
6674 					createmode = UNCHECKED4;
6675 					truncating = 1;
6676 					goto create_otw;
6677 				}
6678 			}
6679 		}
6680 	}
6681 	nfs_rw_exit(&drp->r_rwlock);
6682 	if (error) {
6683 		VN_RELE(vp);
6684 	} else {
6685 		vnode_t *tvp;
6686 		rnode4_t *trp;
6687 		tvp = vp;
6688 		if (vp->v_type == VREG) {
6689 			trp = VTOR4(vp);
6690 			if (IS_SHADOW(vp, trp))
6691 				tvp = RTOV4(trp);
6692 		}
6693 
6694 		if (must_trunc) {
6695 			/*
6696 			 * existing file got truncated, notify.
6697 			 */
6698 			vnevent_create(tvp, ct);
6699 		}
6700 
6701 		*vpp = vp;
6702 	}
6703 	return (error);
6704 
6705 create_otw:
6706 	dnlc_remove(dvp, nm);
6707 
6708 	ASSERT(vattr.va_mask & AT_TYPE);
6709 
6710 	/*
6711 	 * If not a regular file let nfs4mknod() handle it.
6712 	 */
6713 	if (vattr.va_type != VREG) {
6714 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6715 		nfs_rw_exit(&drp->r_rwlock);
6716 		return (error);
6717 	}
6718 
6719 	/*
6720 	 * It _is_ a regular file.
6721 	 */
6722 	ASSERT(vattr.va_mask & AT_MODE);
6723 	if (MANDMODE(vattr.va_mode)) {
6724 		nfs_rw_exit(&drp->r_rwlock);
6725 		return (EACCES);
6726 	}
6727 
6728 	/*
6729 	 * If this happens to be a mknod of a regular file, then flags will
6730 	 * have neither FREAD or FWRITE.  However, we must set at least one
6731 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6732 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6733 	 * set (based on openmode specified by app).
6734 	 */
6735 	if ((flags & (FREAD|FWRITE)) == 0)
6736 		flags |= (FREAD|FWRITE);
6737 
6738 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6739 
6740 	if (vp != NULL) {
6741 		/* if create was successful, throw away the file's pages */
6742 		if (!error && (vattr.va_mask & AT_SIZE))
6743 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6744 			    cr);
6745 		/* release the lookup hold */
6746 		VN_RELE(vp);
6747 		vp = NULL;
6748 	}
6749 
6750 	/*
6751 	 * validate that we opened a regular file. This handles a misbehaving
6752 	 * server that returns an incorrect FH.
6753 	 */
6754 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6755 		error = EISDIR;
6756 		VN_RELE(*vpp);
6757 	}
6758 
6759 	/*
6760 	 * If this is not an exclusive create, then the CREATE
6761 	 * request will be made with the GUARDED mode set.  This
6762 	 * means that the server will return EEXIST if the file
6763 	 * exists.  The file could exist because of a retransmitted
6764 	 * request.  In this case, we recover by starting over and
6765 	 * checking to see whether the file exists.  This second
6766 	 * time through it should and a CREATE request will not be
6767 	 * sent.
6768 	 *
6769 	 * This handles the problem of a dangling CREATE request
6770 	 * which contains attributes which indicate that the file
6771 	 * should be truncated.  This retransmitted request could
6772 	 * possibly truncate valid data in the file if not caught
6773 	 * by the duplicate request mechanism on the server or if
6774 	 * not caught by other means.  The scenario is:
6775 	 *
6776 	 * Client transmits CREATE request with size = 0
6777 	 * Client times out, retransmits request.
6778 	 * Response to the first request arrives from the server
6779 	 *  and the client proceeds on.
6780 	 * Client writes data to the file.
6781 	 * The server now processes retransmitted CREATE request
6782 	 *  and truncates file.
6783 	 *
6784 	 * The use of the GUARDED CREATE request prevents this from
6785 	 * happening because the retransmitted CREATE would fail
6786 	 * with EEXIST and would not truncate the file.
6787 	 */
6788 	if (error == EEXIST && exclusive == NONEXCL) {
6789 #ifdef DEBUG
6790 		nfs4_create_misses++;
6791 #endif
6792 		goto top;
6793 	}
6794 	nfs_rw_exit(&drp->r_rwlock);
6795 	if (truncating && !error && *vpp) {
6796 		vnode_t *tvp;
6797 		rnode4_t *trp;
6798 		/*
6799 		 * existing file got truncated, notify.
6800 		 */
6801 		tvp = *vpp;
6802 		trp = VTOR4(tvp);
6803 		if (IS_SHADOW(tvp, trp))
6804 			tvp = RTOV4(trp);
6805 		vnevent_create(tvp, ct);
6806 	}
6807 	return (error);
6808 }
6809 
6810 /*
6811  * Create compound (for mkdir, mknod, symlink):
6812  * { Putfh <dfh>; Create; Getfh; Getattr }
6813  * It's okay if setattr failed to set gid - this is not considered
6814  * an error, but purge attrs in that case.
6815  */
6816 static int
6817 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6818     vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6819 {
6820 	int need_end_op = FALSE;
6821 	COMPOUND4args_clnt args;
6822 	COMPOUND4res_clnt res, *resp = NULL;
6823 	nfs_argop4 *argop;
6824 	nfs_resop4 *resop;
6825 	int doqueue;
6826 	mntinfo4_t *mi;
6827 	rnode4_t *drp = VTOR4(dvp);
6828 	change_info4 *cinfo;
6829 	GETFH4res *gf_res;
6830 	struct vattr vattr;
6831 	vnode_t *vp;
6832 	fattr4 *crattr;
6833 	bool_t needrecov = FALSE;
6834 	nfs4_recov_state_t recov_state;
6835 	nfs4_sharedfh_t *sfhp = NULL;
6836 	hrtime_t t;
6837 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6838 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6839 	dirattr_info_t dinfo, *dinfop;
6840 	servinfo4_t *svp;
6841 	bitmap4 supp_attrs;
6842 
6843 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6844 	    type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6845 
6846 	mi = VTOMI4(dvp);
6847 
6848 	/*
6849 	 * Make sure we properly deal with setting the right gid
6850 	 * on a new directory to reflect the parent's setgid bit
6851 	 */
6852 	setgid_flag = 0;
6853 	if (type == NF4DIR) {
6854 		struct vattr dva;
6855 
6856 		va->va_mode &= ~VSGID;
6857 		dva.va_mask = AT_MODE | AT_GID;
6858 		if (VOP_GETATTR(dvp, &dva, 0, cr, NULL) == 0) {
6859 
6860 			/*
6861 			 * If the parent's directory has the setgid bit set
6862 			 * _and_ the client was able to get a valid mapping
6863 			 * for the parent dir's owner_group, we want to
6864 			 * append NVERIFY(owner_group == dva.va_gid) and
6865 			 * SETTATTR to the CREATE compound.
6866 			 */
6867 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6868 				setgid_flag = 1;
6869 				va->va_mode |= VSGID;
6870 				if (dva.va_gid != GID_NOBODY) {
6871 					va->va_mask |= AT_GID;
6872 					va->va_gid = dva.va_gid;
6873 				}
6874 			}
6875 		}
6876 	}
6877 
6878 	/*
6879 	 * Create ops:
6880 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6881 	 *	5:restorefh(dir) 6:getattr(dir)
6882 	 *
6883 	 * if (setgid)
6884 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6885 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6886 	 *	8:nverify 9:setattr
6887 	 */
6888 	if (setgid_flag) {
6889 		numops = 10;
6890 		idx_create = 1;
6891 		idx_fattr = 3;
6892 	} else {
6893 		numops = 7;
6894 		idx_create = 2;
6895 		idx_fattr = 4;
6896 	}
6897 
6898 	ASSERT(nfs_zone() == mi->mi_zone);
6899 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6900 		return (EINTR);
6901 	}
6902 	recov_state.rs_flags = 0;
6903 	recov_state.rs_num_retry_despite_err = 0;
6904 
6905 	argoplist_size = numops * sizeof (nfs_argop4);
6906 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6907 
6908 recov_retry:
6909 	if (type == NF4LNK)
6910 		args.ctag = TAG_SYMLINK;
6911 	else if (type == NF4DIR)
6912 		args.ctag = TAG_MKDIR;
6913 	else
6914 		args.ctag = TAG_MKNOD;
6915 
6916 	args.array_len = numops;
6917 	args.array = argop;
6918 
6919 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6920 		nfs_rw_exit(&drp->r_rwlock);
6921 		kmem_free(argop, argoplist_size);
6922 		return (e.error);
6923 	}
6924 	need_end_op = TRUE;
6925 
6926 
6927 	/* 0: putfh directory */
6928 	argop[0].argop = OP_CPUTFH;
6929 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6930 
6931 	/* 1/2: Create object */
6932 	argop[idx_create].argop = OP_CCREATE;
6933 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6934 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6935 	if (type == NF4LNK) {
6936 		/*
6937 		 * symlink, treat name as data
6938 		 */
6939 		ASSERT(data != NULL);
6940 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6941 		    (char *)data;
6942 	}
6943 	if (type == NF4BLK || type == NF4CHR) {
6944 		ASSERT(data != NULL);
6945 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6946 		    *((specdata4 *)data);
6947 	}
6948 
6949 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6950 
6951 	svp = drp->r_server;
6952 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6953 	supp_attrs = svp->sv_supp_attrs;
6954 	nfs_rw_exit(&svp->sv_lock);
6955 
6956 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6957 		nfs_rw_exit(&drp->r_rwlock);
6958 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6959 		e.error = EINVAL;
6960 		kmem_free(argop, argoplist_size);
6961 		return (e.error);
6962 	}
6963 
6964 	/* 2/3: getfh fh of created object */
6965 	ASSERT(idx_create + 1 == idx_fattr - 1);
6966 	argop[idx_create + 1].argop = OP_GETFH;
6967 
6968 	/* 3/4: getattr of new object */
6969 	argop[idx_fattr].argop = OP_GETATTR;
6970 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6971 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6972 
6973 	if (setgid_flag) {
6974 		vattr_t	_v;
6975 
6976 		argop[4].argop = OP_SAVEFH;
6977 
6978 		argop[5].argop = OP_CPUTFH;
6979 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6980 
6981 		argop[6].argop = OP_GETATTR;
6982 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6983 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6984 
6985 		argop[7].argop = OP_RESTOREFH;
6986 
6987 		/*
6988 		 * nverify
6989 		 *
6990 		 * XXX - Revisit the last argument to nfs4_end_op()
6991 		 *	 once 5020486 is fixed.
6992 		 */
6993 		_v.va_mask = AT_GID;
6994 		_v.va_gid = va->va_gid;
6995 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6996 		    supp_attrs)) {
6997 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6998 			nfs_rw_exit(&drp->r_rwlock);
6999 			nfs4_fattr4_free(crattr);
7000 			kmem_free(argop, argoplist_size);
7001 			return (e.error);
7002 		}
7003 
7004 		/*
7005 		 * setattr
7006 		 *
7007 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
7008 		 * so no need for stateid or flags. Also we specify NULL
7009 		 * rp since we're only interested in setting owner_group
7010 		 * attributes.
7011 		 */
7012 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
7013 		    &e.error, 0);
7014 
7015 		if (e.error) {
7016 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
7017 			nfs_rw_exit(&drp->r_rwlock);
7018 			nfs4_fattr4_free(crattr);
7019 			nfs4args_verify_free(&argop[8]);
7020 			kmem_free(argop, argoplist_size);
7021 			return (e.error);
7022 		}
7023 	} else {
7024 		argop[1].argop = OP_SAVEFH;
7025 
7026 		argop[5].argop = OP_RESTOREFH;
7027 
7028 		argop[6].argop = OP_GETATTR;
7029 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7030 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
7031 	}
7032 
7033 	dnlc_remove(dvp, nm);
7034 
7035 	doqueue = 1;
7036 	t = gethrtime();
7037 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7038 
7039 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7040 	if (e.error) {
7041 		PURGE_ATTRCACHE4(dvp);
7042 		if (!needrecov)
7043 			goto out;
7044 	}
7045 
7046 	if (needrecov) {
7047 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
7048 		    OP_CREATE, NULL, NULL, NULL) == FALSE) {
7049 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7050 			    needrecov);
7051 			need_end_op = FALSE;
7052 			nfs4_fattr4_free(crattr);
7053 			if (setgid_flag) {
7054 				nfs4args_verify_free(&argop[8]);
7055 				nfs4args_setattr_free(&argop[9]);
7056 			}
7057 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
7058 			goto recov_retry;
7059 		}
7060 	}
7061 
7062 	resp = &res;
7063 
7064 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
7065 
7066 		if (res.status == NFS4ERR_BADOWNER)
7067 			nfs4_log_badowner(mi, OP_CREATE);
7068 
7069 		e.error = geterrno4(res.status);
7070 
7071 		/*
7072 		 * This check is left over from when create was implemented
7073 		 * using a setattr op (instead of createattrs).  If the
7074 		 * putfh/create/getfh failed, the error was returned.  If
7075 		 * setattr/getattr failed, we keep going.
7076 		 *
7077 		 * It might be better to get rid of the GETFH also, and just
7078 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
7079 		 * Then if any of the operations failed, we could return the
7080 		 * error now, and remove much of the error code below.
7081 		 */
7082 		if (res.array_len <= idx_fattr) {
7083 			/*
7084 			 * Either Putfh, Create or Getfh failed.
7085 			 */
7086 			PURGE_ATTRCACHE4(dvp);
7087 			/*
7088 			 * nfs4_purge_stale_fh() may generate otw calls through
7089 			 * nfs4_invalidate_pages. Hence the need to call
7090 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
7091 			 */
7092 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7093 			    needrecov);
7094 			need_end_op = FALSE;
7095 			nfs4_purge_stale_fh(e.error, dvp, cr);
7096 			goto out;
7097 		}
7098 	}
7099 
7100 	resop = &res.array[idx_create];	/* create res */
7101 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
7102 
7103 	resop = &res.array[idx_create + 1]; /* getfh res */
7104 	gf_res = &resop->nfs_resop4_u.opgetfh;
7105 
7106 	sfhp = sfh4_get(&gf_res->object, mi);
7107 	if (e.error) {
7108 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
7109 		    fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7110 		if (vp->v_type == VNON) {
7111 			vattr.va_mask = AT_TYPE;
7112 			/*
7113 			 * Need to call nfs4_end_op before nfs4getattr to avoid
7114 			 * potential nfs4_start_op deadlock. See RFE 4777612.
7115 			 */
7116 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7117 			    needrecov);
7118 			need_end_op = FALSE;
7119 			e.error = nfs4getattr(vp, &vattr, cr);
7120 			if (e.error) {
7121 				VN_RELE(vp);
7122 				*vpp = NULL;
7123 				goto out;
7124 			}
7125 			vp->v_type = vattr.va_type;
7126 		}
7127 		e.error = 0;
7128 	} else {
7129 		*vpp = vp = makenfs4node(sfhp,
7130 		    &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
7131 		    dvp->v_vfsp, t, cr,
7132 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7133 	}
7134 
7135 	/*
7136 	 * If compound succeeded, then update dir attrs
7137 	 */
7138 	if (res.status == NFS4_OK) {
7139 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
7140 		dinfo.di_cred = cr;
7141 		dinfo.di_time_call = t;
7142 		dinfop = &dinfo;
7143 	} else
7144 		dinfop = NULL;
7145 
7146 	/* Update directory cache attribute, readdir and dnlc caches */
7147 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
7148 
7149 out:
7150 	if (sfhp != NULL)
7151 		sfh4_rele(&sfhp);
7152 	nfs_rw_exit(&drp->r_rwlock);
7153 	nfs4_fattr4_free(crattr);
7154 	if (setgid_flag) {
7155 		nfs4args_verify_free(&argop[8]);
7156 		nfs4args_setattr_free(&argop[9]);
7157 	}
7158 	if (resp)
7159 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7160 	if (need_end_op)
7161 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7162 
7163 	kmem_free(argop, argoplist_size);
7164 	return (e.error);
7165 }
7166 
7167 /* ARGSUSED */
7168 static int
7169 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7170     int mode, vnode_t **vpp, cred_t *cr)
7171 {
7172 	int error;
7173 	vnode_t *vp;
7174 	nfs_ftype4 type;
7175 	specdata4 spec, *specp = NULL;
7176 
7177 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7178 
7179 	switch (va->va_type) {
7180 	case VCHR:
7181 	case VBLK:
7182 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7183 		spec.specdata1 = getmajor(va->va_rdev);
7184 		spec.specdata2 = getminor(va->va_rdev);
7185 		specp = &spec;
7186 		break;
7187 
7188 	case VFIFO:
7189 		type = NF4FIFO;
7190 		break;
7191 	case VSOCK:
7192 		type = NF4SOCK;
7193 		break;
7194 
7195 	default:
7196 		return (EINVAL);
7197 	}
7198 
7199 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7200 	if (error) {
7201 		return (error);
7202 	}
7203 
7204 	/*
7205 	 * This might not be needed any more; special case to deal
7206 	 * with problematic v2/v3 servers.  Since create was unable
7207 	 * to set group correctly, not sure what hope setattr has.
7208 	 */
7209 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7210 		va->va_mask = AT_GID;
7211 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7212 	}
7213 
7214 	/*
7215 	 * If vnode is a device create special vnode
7216 	 */
7217 	if (ISVDEV(vp->v_type)) {
7218 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7219 		VN_RELE(vp);
7220 	} else {
7221 		*vpp = vp;
7222 	}
7223 	return (error);
7224 }
7225 
7226 /*
7227  * Remove requires that the current fh be the target directory.
7228  * After the operation, the current fh is unchanged.
7229  * The compound op structure is:
7230  *      PUTFH(targetdir), REMOVE
7231  *
7232  * Weirdness: if the vnode to be removed is open
7233  * we rename it instead of removing it and nfs_inactive
7234  * will remove the new name.
7235  */
7236 /* ARGSUSED */
7237 static int
7238 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr, caller_context_t *ct, int flags)
7239 {
7240 	COMPOUND4args_clnt args;
7241 	COMPOUND4res_clnt res, *resp = NULL;
7242 	REMOVE4res *rm_res;
7243 	nfs_argop4 argop[3];
7244 	nfs_resop4 *resop;
7245 	vnode_t *vp;
7246 	char *tmpname;
7247 	int doqueue;
7248 	mntinfo4_t *mi;
7249 	rnode4_t *rp;
7250 	rnode4_t *drp;
7251 	int needrecov = 0;
7252 	nfs4_recov_state_t recov_state;
7253 	int isopen;
7254 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7255 	dirattr_info_t dinfo;
7256 
7257 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7258 		return (EPERM);
7259 	drp = VTOR4(dvp);
7260 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7261 		return (EINTR);
7262 
7263 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7264 	if (e.error) {
7265 		nfs_rw_exit(&drp->r_rwlock);
7266 		return (e.error);
7267 	}
7268 
7269 	if (vp->v_type == VDIR) {
7270 		VN_RELE(vp);
7271 		nfs_rw_exit(&drp->r_rwlock);
7272 		return (EISDIR);
7273 	}
7274 
7275 	/*
7276 	 * First just remove the entry from the name cache, as it
7277 	 * is most likely the only entry for this vp.
7278 	 */
7279 	dnlc_remove(dvp, nm);
7280 
7281 	rp = VTOR4(vp);
7282 
7283 	/*
7284 	 * For regular file types, check to see if the file is open by looking
7285 	 * at the open streams.
7286 	 * For all other types, check the reference count on the vnode.  Since
7287 	 * they are not opened OTW they never have an open stream.
7288 	 *
7289 	 * If the file is open, rename it to .nfsXXXX.
7290 	 */
7291 	if (vp->v_type != VREG) {
7292 		/*
7293 		 * If the file has a v_count > 1 then there may be more than one
7294 		 * entry in the name cache due multiple links or an open file,
7295 		 * but we don't have the real reference count so flush all
7296 		 * possible entries.
7297 		 */
7298 		if (vp->v_count > 1)
7299 			dnlc_purge_vp(vp);
7300 
7301 		/*
7302 		 * Now we have the real reference count.
7303 		 */
7304 		isopen = vp->v_count > 1;
7305 	} else {
7306 		mutex_enter(&rp->r_os_lock);
7307 		isopen = list_head(&rp->r_open_streams) != NULL;
7308 		mutex_exit(&rp->r_os_lock);
7309 	}
7310 
7311 	mutex_enter(&rp->r_statelock);
7312 	if (isopen &&
7313 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7314 		mutex_exit(&rp->r_statelock);
7315 		tmpname = newname();
7316 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr, ct);
7317 		if (e.error)
7318 			kmem_free(tmpname, MAXNAMELEN);
7319 		else {
7320 			mutex_enter(&rp->r_statelock);
7321 			if (rp->r_unldvp == NULL) {
7322 				VN_HOLD(dvp);
7323 				rp->r_unldvp = dvp;
7324 				if (rp->r_unlcred != NULL)
7325 					crfree(rp->r_unlcred);
7326 				crhold(cr);
7327 				rp->r_unlcred = cr;
7328 				rp->r_unlname = tmpname;
7329 			} else {
7330 				kmem_free(rp->r_unlname, MAXNAMELEN);
7331 				rp->r_unlname = tmpname;
7332 			}
7333 			mutex_exit(&rp->r_statelock);
7334 		}
7335 		VN_RELE(vp);
7336 		nfs_rw_exit(&drp->r_rwlock);
7337 		return (e.error);
7338 	}
7339 	/*
7340 	 * Actually remove the file/dir
7341 	 */
7342 	mutex_exit(&rp->r_statelock);
7343 
7344 	/*
7345 	 * We need to flush any dirty pages which happen to
7346 	 * be hanging around before removing the file.
7347 	 * This shouldn't happen very often since in NFSv4
7348 	 * we should be close to open consistent.
7349 	 */
7350 	if (nfs4_has_pages(vp) &&
7351 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7352 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, ct);
7353 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7354 			mutex_enter(&rp->r_statelock);
7355 			if (!rp->r_error)
7356 				rp->r_error = e.error;
7357 			mutex_exit(&rp->r_statelock);
7358 		}
7359 	}
7360 
7361 	mi = VTOMI4(dvp);
7362 
7363 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7364 	recov_state.rs_flags = 0;
7365 	recov_state.rs_num_retry_despite_err = 0;
7366 
7367 recov_retry:
7368 	/*
7369 	 * Remove ops: putfh dir; remove
7370 	 */
7371 	args.ctag = TAG_REMOVE;
7372 	args.array_len = 3;
7373 	args.array = argop;
7374 
7375 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7376 	if (e.error) {
7377 		nfs_rw_exit(&drp->r_rwlock);
7378 		VN_RELE(vp);
7379 		return (e.error);
7380 	}
7381 
7382 	/* putfh directory */
7383 	argop[0].argop = OP_CPUTFH;
7384 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7385 
7386 	/* remove */
7387 	argop[1].argop = OP_CREMOVE;
7388 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7389 
7390 	/* getattr dir */
7391 	argop[2].argop = OP_GETATTR;
7392 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7393 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7394 
7395 	doqueue = 1;
7396 	dinfo.di_time_call = gethrtime();
7397 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7398 
7399 	PURGE_ATTRCACHE4(vp);
7400 
7401 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7402 	if (e.error)
7403 		PURGE_ATTRCACHE4(dvp);
7404 
7405 	if (needrecov) {
7406 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7407 		    NULL, NULL, NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
7408 			if (!e.error)
7409 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7410 				    (caddr_t)&res);
7411 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7412 			    needrecov);
7413 			goto recov_retry;
7414 		}
7415 	}
7416 
7417 	/*
7418 	 * Matching nfs4_end_op() for start_op() above.
7419 	 * There is a path in the code below which calls
7420 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7421 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7422 	 * here to avoid nfs4_start_op() deadlock.
7423 	 */
7424 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7425 
7426 	if (!e.error) {
7427 		resp = &res;
7428 
7429 		if (res.status) {
7430 			e.error = geterrno4(res.status);
7431 			PURGE_ATTRCACHE4(dvp);
7432 			nfs4_purge_stale_fh(e.error, dvp, cr);
7433 		} else {
7434 			resop = &res.array[1];	/* remove res */
7435 			rm_res = &resop->nfs_resop4_u.opremove;
7436 
7437 			dinfo.di_garp =
7438 			    &res.array[2].nfs_resop4_u.opgetattr.ga_res;
7439 			dinfo.di_cred = cr;
7440 
7441 			/* Update directory attr, readdir and dnlc caches */
7442 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7443 			    &dinfo);
7444 		}
7445 	}
7446 	nfs_rw_exit(&drp->r_rwlock);
7447 	if (resp)
7448 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7449 
7450 	if (e.error == 0) {
7451 		vnode_t *tvp;
7452 		rnode4_t *trp;
7453 		trp = VTOR4(vp);
7454 		tvp = vp;
7455 		if (IS_SHADOW(vp, trp))
7456 			tvp = RTOV4(trp);
7457 		vnevent_remove(tvp, dvp, nm, ct);
7458 	}
7459 	VN_RELE(vp);
7460 	return (e.error);
7461 }
7462 
7463 /*
7464  * Link requires that the current fh be the target directory and the
7465  * saved fh be the source fh. After the operation, the current fh is unchanged.
7466  * Thus the compound op structure is:
7467  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7468  *	GETATTR(file)
7469  */
7470 /* ARGSUSED */
7471 static int
7472 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr,
7473     caller_context_t *ct, int flags)
7474 {
7475 	COMPOUND4args_clnt args;
7476 	COMPOUND4res_clnt res, *resp = NULL;
7477 	LINK4res *ln_res;
7478 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7479 	nfs_argop4 *argop;
7480 	nfs_resop4 *resop;
7481 	vnode_t *realvp, *nvp;
7482 	int doqueue;
7483 	mntinfo4_t *mi;
7484 	rnode4_t *tdrp;
7485 	bool_t needrecov = FALSE;
7486 	nfs4_recov_state_t recov_state;
7487 	hrtime_t t;
7488 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7489 	dirattr_info_t dinfo;
7490 
7491 	ASSERT(*tnm != '\0');
7492 	ASSERT(tdvp->v_type == VDIR);
7493 	ASSERT(nfs4_consistent_type(tdvp));
7494 	ASSERT(nfs4_consistent_type(svp));
7495 
7496 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7497 		return (EPERM);
7498 	if (VOP_REALVP(svp, &realvp, ct) == 0) {
7499 		svp = realvp;
7500 		ASSERT(nfs4_consistent_type(svp));
7501 	}
7502 
7503 	tdrp = VTOR4(tdvp);
7504 	mi = VTOMI4(svp);
7505 
7506 	if (!(mi->mi_flags & MI4_LINK)) {
7507 		return (EOPNOTSUPP);
7508 	}
7509 	recov_state.rs_flags = 0;
7510 	recov_state.rs_num_retry_despite_err = 0;
7511 
7512 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7513 		return (EINTR);
7514 
7515 recov_retry:
7516 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7517 
7518 	args.ctag = TAG_LINK;
7519 
7520 	/*
7521 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7522 	 * restorefh; getattr(fl)
7523 	 */
7524 	args.array_len = 7;
7525 	args.array = argop;
7526 
7527 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7528 	if (e.error) {
7529 		kmem_free(argop, argoplist_size);
7530 		nfs_rw_exit(&tdrp->r_rwlock);
7531 		return (e.error);
7532 	}
7533 
7534 	/* 0. putfh file */
7535 	argop[0].argop = OP_CPUTFH;
7536 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7537 
7538 	/* 1. save current fh to free up the space for the dir */
7539 	argop[1].argop = OP_SAVEFH;
7540 
7541 	/* 2. putfh targetdir */
7542 	argop[2].argop = OP_CPUTFH;
7543 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7544 
7545 	/* 3. link: current_fh is targetdir, saved_fh is source */
7546 	argop[3].argop = OP_CLINK;
7547 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7548 
7549 	/* 4. Get attributes of dir */
7550 	argop[4].argop = OP_GETATTR;
7551 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7552 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7553 
7554 	/* 5. If link was successful, restore current vp to file */
7555 	argop[5].argop = OP_RESTOREFH;
7556 
7557 	/* 6. Get attributes of linked object */
7558 	argop[6].argop = OP_GETATTR;
7559 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7560 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7561 
7562 	dnlc_remove(tdvp, tnm);
7563 
7564 	doqueue = 1;
7565 	t = gethrtime();
7566 
7567 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7568 
7569 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7570 	if (e.error != 0 && !needrecov) {
7571 		PURGE_ATTRCACHE4(tdvp);
7572 		PURGE_ATTRCACHE4(svp);
7573 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7574 		goto out;
7575 	}
7576 
7577 	if (needrecov) {
7578 		bool_t abort;
7579 
7580 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7581 		    NULL, NULL, OP_LINK, NULL, NULL, NULL);
7582 		if (abort == FALSE) {
7583 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7584 			    needrecov);
7585 			kmem_free(argop, argoplist_size);
7586 			if (!e.error)
7587 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7588 				    (caddr_t)&res);
7589 			goto recov_retry;
7590 		} else {
7591 			if (e.error != 0) {
7592 				PURGE_ATTRCACHE4(tdvp);
7593 				PURGE_ATTRCACHE4(svp);
7594 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7595 				    &recov_state, needrecov);
7596 				goto out;
7597 			}
7598 			/* fall through for res.status case */
7599 		}
7600 	}
7601 
7602 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7603 
7604 	resp = &res;
7605 	if (res.status) {
7606 		/* If link succeeded, then don't return error */
7607 		e.error = geterrno4(res.status);
7608 		if (res.array_len <= 4) {
7609 			/*
7610 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7611 			 */
7612 			PURGE_ATTRCACHE4(svp);
7613 			PURGE_ATTRCACHE4(tdvp);
7614 			if (e.error == EOPNOTSUPP) {
7615 				mutex_enter(&mi->mi_lock);
7616 				mi->mi_flags &= ~MI4_LINK;
7617 				mutex_exit(&mi->mi_lock);
7618 			}
7619 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7620 			/* XXX-LP */
7621 			if (e.error == EISDIR && crgetuid(cr) != 0)
7622 				e.error = EPERM;
7623 			goto out;
7624 		}
7625 	}
7626 
7627 	/* either no error or one of the postop getattr failed */
7628 
7629 	/*
7630 	 * XXX - if LINK succeeded, but no attrs were returned for link
7631 	 * file, purge its cache.
7632 	 *
7633 	 * XXX Perform a simplified version of wcc checking. Instead of
7634 	 * have another getattr to get pre-op, just purge cache if
7635 	 * any of the ops prior to and including the getattr failed.
7636 	 * If the getattr succeeded then update the attrcache accordingly.
7637 	 */
7638 
7639 	/*
7640 	 * update cache with link file postattrs.
7641 	 * Note: at this point resop points to link res.
7642 	 */
7643 	resop = &res.array[3];	/* link res */
7644 	ln_res = &resop->nfs_resop4_u.oplink;
7645 	if (res.status == NFS4_OK)
7646 		e.error = nfs4_update_attrcache(res.status,
7647 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res,
7648 		    t, svp, cr);
7649 
7650 	/*
7651 	 * Call makenfs4node to create the new shadow vp for tnm.
7652 	 * We pass NULL attrs because we just cached attrs for
7653 	 * the src object.  All we're trying to accomplish is to
7654 	 * to create the new shadow vnode.
7655 	 */
7656 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7657 	    tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm, VTOR4(svp)->r_fh));
7658 
7659 	/* Update target cache attribute, readdir and dnlc caches */
7660 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7661 	dinfo.di_time_call = t;
7662 	dinfo.di_cred = cr;
7663 
7664 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7665 	ASSERT(nfs4_consistent_type(tdvp));
7666 	ASSERT(nfs4_consistent_type(svp));
7667 	ASSERT(nfs4_consistent_type(nvp));
7668 	VN_RELE(nvp);
7669 
7670 	if (!e.error) {
7671 		vnode_t *tvp;
7672 		rnode4_t *trp;
7673 		/*
7674 		 * Notify the source file of this link operation.
7675 		 */
7676 		trp = VTOR4(svp);
7677 		tvp = svp;
7678 		if (IS_SHADOW(svp, trp))
7679 			tvp = RTOV4(trp);
7680 		vnevent_link(tvp, ct);
7681 	}
7682 out:
7683 	kmem_free(argop, argoplist_size);
7684 	if (resp)
7685 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7686 
7687 	nfs_rw_exit(&tdrp->r_rwlock);
7688 
7689 	return (e.error);
7690 }
7691 
7692 /* ARGSUSED */
7693 static int
7694 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7695     caller_context_t *ct, int flags)
7696 {
7697 	vnode_t *realvp;
7698 
7699 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7700 		return (EPERM);
7701 	if (VOP_REALVP(ndvp, &realvp, ct) == 0)
7702 		ndvp = realvp;
7703 
7704 	return (nfs4rename(odvp, onm, ndvp, nnm, cr, ct));
7705 }
7706 
7707 /*
7708  * nfs4rename does the real work of renaming in NFS Version 4.
7709  *
7710  * A file handle is considered volatile for renaming purposes if either
7711  * of the volatile bits are turned on. However, the compound may differ
7712  * based on the likelihood of the filehandle to change during rename.
7713  */
7714 static int
7715 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7716     caller_context_t *ct)
7717 {
7718 	int error;
7719 	mntinfo4_t *mi;
7720 	vnode_t *nvp = NULL;
7721 	vnode_t *ovp = NULL;
7722 	char *tmpname = NULL;
7723 	rnode4_t *rp;
7724 	rnode4_t *odrp;
7725 	rnode4_t *ndrp;
7726 	int did_link = 0;
7727 	int do_link = 1;
7728 	nfsstat4 stat = NFS4_OK;
7729 
7730 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7731 	ASSERT(nfs4_consistent_type(odvp));
7732 	ASSERT(nfs4_consistent_type(ndvp));
7733 
7734 	if (onm[0] == '.' && (onm[1] == '\0' ||
7735 	    (onm[1] == '.' && onm[2] == '\0')))
7736 		return (EINVAL);
7737 
7738 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7739 	    (nnm[1] == '.' && nnm[2] == '\0')))
7740 		return (EINVAL);
7741 
7742 	odrp = VTOR4(odvp);
7743 	ndrp = VTOR4(ndvp);
7744 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7745 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7746 			return (EINTR);
7747 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7748 			nfs_rw_exit(&odrp->r_rwlock);
7749 			return (EINTR);
7750 		}
7751 	} else {
7752 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7753 			return (EINTR);
7754 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7755 			nfs_rw_exit(&ndrp->r_rwlock);
7756 			return (EINTR);
7757 		}
7758 	}
7759 
7760 	/*
7761 	 * Lookup the target file.  If it exists, it needs to be
7762 	 * checked to see whether it is a mount point and whether
7763 	 * it is active (open).
7764 	 */
7765 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7766 	if (!error) {
7767 		int	isactive;
7768 
7769 		ASSERT(nfs4_consistent_type(nvp));
7770 		/*
7771 		 * If this file has been mounted on, then just
7772 		 * return busy because renaming to it would remove
7773 		 * the mounted file system from the name space.
7774 		 */
7775 		if (vn_ismntpt(nvp)) {
7776 			VN_RELE(nvp);
7777 			nfs_rw_exit(&odrp->r_rwlock);
7778 			nfs_rw_exit(&ndrp->r_rwlock);
7779 			return (EBUSY);
7780 		}
7781 
7782 		/*
7783 		 * First just remove the entry from the name cache, as it
7784 		 * is most likely the only entry for this vp.
7785 		 */
7786 		dnlc_remove(ndvp, nnm);
7787 
7788 		rp = VTOR4(nvp);
7789 
7790 		if (nvp->v_type != VREG) {
7791 			/*
7792 			 * Purge the name cache of all references to this vnode
7793 			 * so that we can check the reference count to infer
7794 			 * whether it is active or not.
7795 			 */
7796 			if (nvp->v_count > 1)
7797 				dnlc_purge_vp(nvp);
7798 
7799 			isactive = nvp->v_count > 1;
7800 		} else {
7801 			mutex_enter(&rp->r_os_lock);
7802 			isactive = list_head(&rp->r_open_streams) != NULL;
7803 			mutex_exit(&rp->r_os_lock);
7804 		}
7805 
7806 		/*
7807 		 * If the vnode is active and is not a directory,
7808 		 * arrange to rename it to a
7809 		 * temporary file so that it will continue to be
7810 		 * accessible.  This implements the "unlink-open-file"
7811 		 * semantics for the target of a rename operation.
7812 		 * Before doing this though, make sure that the
7813 		 * source and target files are not already the same.
7814 		 */
7815 		if (isactive && nvp->v_type != VDIR) {
7816 			/*
7817 			 * Lookup the source name.
7818 			 */
7819 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7820 
7821 			/*
7822 			 * The source name *should* already exist.
7823 			 */
7824 			if (error) {
7825 				VN_RELE(nvp);
7826 				nfs_rw_exit(&odrp->r_rwlock);
7827 				nfs_rw_exit(&ndrp->r_rwlock);
7828 				return (error);
7829 			}
7830 
7831 			ASSERT(nfs4_consistent_type(ovp));
7832 
7833 			/*
7834 			 * Compare the two vnodes.  If they are the same,
7835 			 * just release all held vnodes and return success.
7836 			 */
7837 			if (VN_CMP(ovp, nvp)) {
7838 				VN_RELE(ovp);
7839 				VN_RELE(nvp);
7840 				nfs_rw_exit(&odrp->r_rwlock);
7841 				nfs_rw_exit(&ndrp->r_rwlock);
7842 				return (0);
7843 			}
7844 
7845 			/*
7846 			 * Can't mix and match directories and non-
7847 			 * directories in rename operations.  We already
7848 			 * know that the target is not a directory.  If
7849 			 * the source is a directory, return an error.
7850 			 */
7851 			if (ovp->v_type == VDIR) {
7852 				VN_RELE(ovp);
7853 				VN_RELE(nvp);
7854 				nfs_rw_exit(&odrp->r_rwlock);
7855 				nfs_rw_exit(&ndrp->r_rwlock);
7856 				return (ENOTDIR);
7857 			}
7858 link_call:
7859 			/*
7860 			 * The target file exists, is not the same as
7861 			 * the source file, and is active.  We first
7862 			 * try to Link it to a temporary filename to
7863 			 * avoid having the server removing the file
7864 			 * completely (which could cause data loss to
7865 			 * the user's POV in the event the Rename fails
7866 			 * -- see bug 1165874).
7867 			 */
7868 			/*
7869 			 * The do_link and did_link booleans are
7870 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7871 			 * returned for the Rename.  Some servers can
7872 			 * not Rename over an Open file, so they return
7873 			 * this error.  The client needs to Remove the
7874 			 * newly created Link and do two Renames, just
7875 			 * as if the server didn't support LINK.
7876 			 */
7877 			tmpname = newname();
7878 			error = 0;
7879 
7880 			if (do_link) {
7881 				error = nfs4_link(ndvp, nvp, tmpname, cr,
7882 				    NULL, 0);
7883 			}
7884 			if (error == EOPNOTSUPP || !do_link) {
7885 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7886 				    cr, NULL, 0);
7887 				did_link = 0;
7888 			} else {
7889 				did_link = 1;
7890 			}
7891 			if (error) {
7892 				kmem_free(tmpname, MAXNAMELEN);
7893 				VN_RELE(ovp);
7894 				VN_RELE(nvp);
7895 				nfs_rw_exit(&odrp->r_rwlock);
7896 				nfs_rw_exit(&ndrp->r_rwlock);
7897 				return (error);
7898 			}
7899 
7900 			mutex_enter(&rp->r_statelock);
7901 			if (rp->r_unldvp == NULL) {
7902 				VN_HOLD(ndvp);
7903 				rp->r_unldvp = ndvp;
7904 				if (rp->r_unlcred != NULL)
7905 					crfree(rp->r_unlcred);
7906 				crhold(cr);
7907 				rp->r_unlcred = cr;
7908 				rp->r_unlname = tmpname;
7909 			} else {
7910 				if (rp->r_unlname)
7911 					kmem_free(rp->r_unlname, MAXNAMELEN);
7912 				rp->r_unlname = tmpname;
7913 			}
7914 			mutex_exit(&rp->r_statelock);
7915 		}
7916 
7917 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7918 
7919 		ASSERT(nfs4_consistent_type(nvp));
7920 	}
7921 
7922 	if (ovp == NULL) {
7923 		/*
7924 		 * When renaming directories to be a subdirectory of a
7925 		 * different parent, the dnlc entry for ".." will no
7926 		 * longer be valid, so it must be removed.
7927 		 *
7928 		 * We do a lookup here to determine whether we are renaming
7929 		 * a directory and we need to check if we are renaming
7930 		 * an unlinked file.  This might have already been done
7931 		 * in previous code, so we check ovp == NULL to avoid
7932 		 * doing it twice.
7933 		 */
7934 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7935 		/*
7936 		 * The source name *should* already exist.
7937 		 */
7938 		if (error) {
7939 			nfs_rw_exit(&odrp->r_rwlock);
7940 			nfs_rw_exit(&ndrp->r_rwlock);
7941 			if (nvp) {
7942 				VN_RELE(nvp);
7943 			}
7944 			return (error);
7945 		}
7946 		ASSERT(ovp != NULL);
7947 		ASSERT(nfs4_consistent_type(ovp));
7948 	}
7949 
7950 	/*
7951 	 * Is the object being renamed a dir, and if so, is
7952 	 * it being renamed to a child of itself?  The underlying
7953 	 * fs should ultimately return EINVAL for this case;
7954 	 * however, buggy beta non-Solaris NFSv4 servers at
7955 	 * interop testing events have allowed this behavior,
7956 	 * and it caused our client to panic due to a recursive
7957 	 * mutex_enter in fn_move.
7958 	 *
7959 	 * The tedious locking in fn_move could be changed to
7960 	 * deal with this case, and the client could avoid the
7961 	 * panic; however, the client would just confuse itself
7962 	 * later and misbehave.  A better way to handle the broken
7963 	 * server is to detect this condition and return EINVAL
7964 	 * without ever sending the the bogus rename to the server.
7965 	 * We know the rename is invalid -- just fail it now.
7966 	 */
7967 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7968 		VN_RELE(ovp);
7969 		nfs_rw_exit(&odrp->r_rwlock);
7970 		nfs_rw_exit(&ndrp->r_rwlock);
7971 		if (nvp) {
7972 			VN_RELE(nvp);
7973 		}
7974 		return (EINVAL);
7975 	}
7976 
7977 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7978 
7979 	/*
7980 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7981 	 * possible for the filehandle to change due to the rename.
7982 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7983 	 * the fh will not change because of the rename, but we still need
7984 	 * to update its rnode entry with the new name for
7985 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7986 	 * has no effect on these for now, but for future improvements,
7987 	 * we might want to use it too to simplify handling of files
7988 	 * that are open with that flag on. (XXX)
7989 	 */
7990 	mi = VTOMI4(odvp);
7991 	if (NFS4_VOLATILE_FH(mi))
7992 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7993 		    &stat);
7994 	else
7995 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7996 		    &stat);
7997 
7998 	ASSERT(nfs4_consistent_type(odvp));
7999 	ASSERT(nfs4_consistent_type(ndvp));
8000 	ASSERT(nfs4_consistent_type(ovp));
8001 
8002 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
8003 		do_link = 0;
8004 		/*
8005 		 * Before the 'link_call' code, we did a nfs4_lookup
8006 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
8007 		 * call we call VN_RELE to match that hold.  We need
8008 		 * to place an additional VN_HOLD here since we will
8009 		 * be hitting that VN_RELE again.
8010 		 */
8011 		VN_HOLD(nvp);
8012 
8013 		(void) nfs4_remove(ndvp, tmpname, cr, NULL, 0);
8014 
8015 		/* Undo the unlinked file naming stuff we just did */
8016 		mutex_enter(&rp->r_statelock);
8017 		if (rp->r_unldvp) {
8018 			VN_RELE(ndvp);
8019 			rp->r_unldvp = NULL;
8020 			if (rp->r_unlcred != NULL)
8021 				crfree(rp->r_unlcred);
8022 			rp->r_unlcred = NULL;
8023 			/* rp->r_unlanme points to tmpname */
8024 			if (rp->r_unlname)
8025 				kmem_free(rp->r_unlname, MAXNAMELEN);
8026 			rp->r_unlname = NULL;
8027 		}
8028 		mutex_exit(&rp->r_statelock);
8029 
8030 		if (nvp) {
8031 			VN_RELE(nvp);
8032 		}
8033 		goto link_call;
8034 	}
8035 
8036 	if (error) {
8037 		VN_RELE(ovp);
8038 		nfs_rw_exit(&odrp->r_rwlock);
8039 		nfs_rw_exit(&ndrp->r_rwlock);
8040 		if (nvp) {
8041 			VN_RELE(nvp);
8042 		}
8043 		return (error);
8044 	}
8045 
8046 	/*
8047 	 * when renaming directories to be a subdirectory of a
8048 	 * different parent, the dnlc entry for ".." will no
8049 	 * longer be valid, so it must be removed
8050 	 */
8051 	rp = VTOR4(ovp);
8052 	if (ndvp != odvp) {
8053 		if (ovp->v_type == VDIR) {
8054 			dnlc_remove(ovp, "..");
8055 			if (rp->r_dir != NULL)
8056 				nfs4_purge_rddir_cache(ovp);
8057 		}
8058 	}
8059 
8060 	/*
8061 	 * If we are renaming the unlinked file, update the
8062 	 * r_unldvp and r_unlname as needed.
8063 	 */
8064 	mutex_enter(&rp->r_statelock);
8065 	if (rp->r_unldvp != NULL) {
8066 		if (strcmp(rp->r_unlname, onm) == 0) {
8067 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
8068 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
8069 			if (ndvp != rp->r_unldvp) {
8070 				VN_RELE(rp->r_unldvp);
8071 				rp->r_unldvp = ndvp;
8072 				VN_HOLD(ndvp);
8073 			}
8074 		}
8075 	}
8076 	mutex_exit(&rp->r_statelock);
8077 
8078 	/*
8079 	 * Notify the rename vnevents to source vnode, and to the target
8080 	 * vnode if it already existed.
8081 	 */
8082 	if (error == 0) {
8083 		vnode_t *tvp;
8084 		rnode4_t *trp;
8085 		/*
8086 		 * Notify the vnode. Each links is represented by
8087 		 * a different vnode, in nfsv4.
8088 		 */
8089 		if (nvp) {
8090 			trp = VTOR4(nvp);
8091 			tvp = nvp;
8092 			if (IS_SHADOW(nvp, trp))
8093 				tvp = RTOV4(trp);
8094 			vnevent_rename_dest(tvp, ndvp, nnm, ct);
8095 		}
8096 
8097 		/*
8098 		 * if the source and destination directory are not the
8099 		 * same notify the destination directory.
8100 		 */
8101 		if (VTOR4(odvp) != VTOR4(ndvp)) {
8102 			trp = VTOR4(ndvp);
8103 			tvp = ndvp;
8104 			if (IS_SHADOW(ndvp, trp))
8105 				tvp = RTOV4(trp);
8106 			vnevent_rename_dest_dir(tvp, ct);
8107 		}
8108 
8109 		trp = VTOR4(ovp);
8110 		tvp = ovp;
8111 		if (IS_SHADOW(ovp, trp))
8112 			tvp = RTOV4(trp);
8113 		vnevent_rename_src(tvp, odvp, onm, ct);
8114 	}
8115 
8116 	if (nvp) {
8117 		VN_RELE(nvp);
8118 	}
8119 	VN_RELE(ovp);
8120 
8121 	nfs_rw_exit(&odrp->r_rwlock);
8122 	nfs_rw_exit(&ndrp->r_rwlock);
8123 
8124 	return (error);
8125 }
8126 
8127 /*
8128  * When the parent directory has changed, sv_dfh must be updated
8129  */
8130 static void
8131 update_parentdir_sfh(vnode_t *vp, vnode_t *ndvp)
8132 {
8133 	svnode_t *sv = VTOSV(vp);
8134 	nfs4_sharedfh_t *old_dfh = sv->sv_dfh;
8135 	nfs4_sharedfh_t *new_dfh = VTOR4(ndvp)->r_fh;
8136 
8137 	sfh4_hold(new_dfh);
8138 	sv->sv_dfh = new_dfh;
8139 	sfh4_rele(&old_dfh);
8140 }
8141 
8142 /*
8143  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
8144  * when it is known that the filehandle is persistent through rename.
8145  *
8146  * Rename requires that the current fh be the target directory and the
8147  * saved fh be the source directory. After the operation, the current fh
8148  * is unchanged.
8149  * The compound op structure for persistent fh rename is:
8150  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
8151  * Rather than bother with the directory postop args, we'll simply
8152  * update that a change occurred in the cache, so no post-op getattrs.
8153  */
8154 static int
8155 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
8156     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8157 {
8158 	COMPOUND4args_clnt args;
8159 	COMPOUND4res_clnt res, *resp = NULL;
8160 	nfs_argop4 *argop;
8161 	nfs_resop4 *resop;
8162 	int doqueue, argoplist_size;
8163 	mntinfo4_t *mi;
8164 	rnode4_t *odrp = VTOR4(odvp);
8165 	rnode4_t *ndrp = VTOR4(ndvp);
8166 	RENAME4res *rn_res;
8167 	bool_t needrecov;
8168 	nfs4_recov_state_t recov_state;
8169 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8170 	dirattr_info_t dinfo, *dinfop;
8171 
8172 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8173 
8174 	recov_state.rs_flags = 0;
8175 	recov_state.rs_num_retry_despite_err = 0;
8176 
8177 	/*
8178 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
8179 	 *
8180 	 * If source/target are different dirs, then append putfh(src); getattr
8181 	 */
8182 	args.array_len = (odvp == ndvp) ? 5 : 7;
8183 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8184 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8185 
8186 recov_retry:
8187 	*statp = NFS4_OK;
8188 
8189 	/* No need to Lookup the file, persistent fh */
8190 	args.ctag = TAG_RENAME;
8191 
8192 	mi = VTOMI4(odvp);
8193 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8194 	if (e.error) {
8195 		kmem_free(argop, argoplist_size);
8196 		return (e.error);
8197 	}
8198 
8199 	/* 0: putfh source directory */
8200 	argop[0].argop = OP_CPUTFH;
8201 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8202 
8203 	/* 1: Save source fh to free up current for target */
8204 	argop[1].argop = OP_SAVEFH;
8205 
8206 	/* 2: putfh targetdir */
8207 	argop[2].argop = OP_CPUTFH;
8208 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8209 
8210 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8211 	argop[3].argop = OP_CRENAME;
8212 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8213 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8214 
8215 	/* 4: getattr (targetdir) */
8216 	argop[4].argop = OP_GETATTR;
8217 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8218 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8219 
8220 	if (ndvp != odvp) {
8221 
8222 		/* 5: putfh (sourcedir) */
8223 		argop[5].argop = OP_CPUTFH;
8224 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8225 
8226 		/* 6: getattr (sourcedir) */
8227 		argop[6].argop = OP_GETATTR;
8228 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8229 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8230 	}
8231 
8232 	dnlc_remove(odvp, onm);
8233 	dnlc_remove(ndvp, nnm);
8234 
8235 	doqueue = 1;
8236 	dinfo.di_time_call = gethrtime();
8237 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8238 
8239 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8240 	if (e.error) {
8241 		PURGE_ATTRCACHE4(odvp);
8242 		PURGE_ATTRCACHE4(ndvp);
8243 	} else {
8244 		*statp = res.status;
8245 	}
8246 
8247 	if (needrecov) {
8248 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8249 		    OP_RENAME, NULL, NULL, NULL) == FALSE) {
8250 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8251 			if (!e.error)
8252 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8253 				    (caddr_t)&res);
8254 			goto recov_retry;
8255 		}
8256 	}
8257 
8258 	if (!e.error) {
8259 		resp = &res;
8260 		/*
8261 		 * as long as OP_RENAME
8262 		 */
8263 		if (res.status != NFS4_OK && res.array_len <= 4) {
8264 			e.error = geterrno4(res.status);
8265 			PURGE_ATTRCACHE4(odvp);
8266 			PURGE_ATTRCACHE4(ndvp);
8267 			/*
8268 			 * System V defines rename to return EEXIST, not
8269 			 * ENOTEMPTY if the target directory is not empty.
8270 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8271 			 * which geterrno4 maps to ENOTEMPTY.
8272 			 */
8273 			if (e.error == ENOTEMPTY)
8274 				e.error = EEXIST;
8275 		} else {
8276 
8277 			resop = &res.array[3];	/* rename res */
8278 			rn_res = &resop->nfs_resop4_u.oprename;
8279 
8280 			if (res.status == NFS4_OK) {
8281 				/*
8282 				 * Update target attribute, readdir and dnlc
8283 				 * caches.
8284 				 */
8285 				dinfo.di_garp =
8286 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8287 				dinfo.di_cred = cr;
8288 				dinfop = &dinfo;
8289 			} else
8290 				dinfop = NULL;
8291 
8292 			nfs4_update_dircaches(&rn_res->target_cinfo,
8293 			    ndvp, NULL, NULL, dinfop);
8294 
8295 			/*
8296 			 * Update source attribute, readdir and dnlc caches
8297 			 *
8298 			 */
8299 			if (ndvp != odvp) {
8300 				update_parentdir_sfh(renvp, ndvp);
8301 
8302 				if (dinfop)
8303 					dinfo.di_garp =
8304 					    &(res.array[6].nfs_resop4_u.
8305 					    opgetattr.ga_res);
8306 
8307 				nfs4_update_dircaches(&rn_res->source_cinfo,
8308 				    odvp, NULL, NULL, dinfop);
8309 			}
8310 
8311 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8312 			    nnm);
8313 		}
8314 	}
8315 
8316 	if (resp)
8317 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8318 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8319 	kmem_free(argop, argoplist_size);
8320 
8321 	return (e.error);
8322 }
8323 
8324 /*
8325  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8326  * it is possible for the filehandle to change due to the rename.
8327  *
8328  * The compound req in this case includes a post-rename lookup and getattr
8329  * to ensure that we have the correct fh and attributes for the object.
8330  *
8331  * Rename requires that the current fh be the target directory and the
8332  * saved fh be the source directory. After the operation, the current fh
8333  * is unchanged.
8334  *
8335  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8336  * update the filehandle for the renamed object.  We also get the old
8337  * filehandle for historical reasons; this should be taken out sometime.
8338  * This results in a rather cumbersome compound...
8339  *
8340  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8341  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8342  *
8343  */
8344 static int
8345 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8346     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8347 {
8348 	COMPOUND4args_clnt args;
8349 	COMPOUND4res_clnt res, *resp = NULL;
8350 	int argoplist_size;
8351 	nfs_argop4 *argop;
8352 	nfs_resop4 *resop;
8353 	int doqueue;
8354 	mntinfo4_t *mi;
8355 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8356 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8357 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8358 	RENAME4res *rn_res;
8359 	GETFH4res *ngf_res;
8360 	bool_t needrecov;
8361 	nfs4_recov_state_t recov_state;
8362 	hrtime_t t;
8363 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8364 	dirattr_info_t dinfo, *dinfop = &dinfo;
8365 
8366 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8367 
8368 	recov_state.rs_flags = 0;
8369 	recov_state.rs_num_retry_despite_err = 0;
8370 
8371 recov_retry:
8372 	*statp = NFS4_OK;
8373 
8374 	/*
8375 	 * There is a window between the RPC and updating the path and
8376 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8377 	 * code, so that it doesn't try to use the old path during that
8378 	 * window.
8379 	 */
8380 	mutex_enter(&orp->r_statelock);
8381 	while (orp->r_flags & R4RECEXPFH) {
8382 		klwp_t *lwp = ttolwp(curthread);
8383 
8384 		if (lwp != NULL)
8385 			lwp->lwp_nostop++;
8386 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8387 			mutex_exit(&orp->r_statelock);
8388 			if (lwp != NULL)
8389 				lwp->lwp_nostop--;
8390 			return (EINTR);
8391 		}
8392 		if (lwp != NULL)
8393 			lwp->lwp_nostop--;
8394 	}
8395 	orp->r_flags |= R4RECEXPFH;
8396 	mutex_exit(&orp->r_statelock);
8397 
8398 	mi = VTOMI4(odvp);
8399 
8400 	args.ctag = TAG_RENAME_VFH;
8401 	args.array_len = (odvp == ndvp) ? 10 : 12;
8402 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8403 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8404 
8405 	/*
8406 	 * Rename ops:
8407 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8408 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8409 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8410 	 *
8411 	 *    if (odvp != ndvp)
8412 	 *	add putfh(sourcedir), getattr(sourcedir) }
8413 	 */
8414 	args.array = argop;
8415 
8416 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8417 	    &recov_state, NULL);
8418 	if (e.error) {
8419 		kmem_free(argop, argoplist_size);
8420 		mutex_enter(&orp->r_statelock);
8421 		orp->r_flags &= ~R4RECEXPFH;
8422 		cv_broadcast(&orp->r_cv);
8423 		mutex_exit(&orp->r_statelock);
8424 		return (e.error);
8425 	}
8426 
8427 	/* 0: putfh source directory */
8428 	argop[0].argop = OP_CPUTFH;
8429 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8430 
8431 	/* 1: Save source fh to free up current for target */
8432 	argop[1].argop = OP_SAVEFH;
8433 
8434 	/* 2: Lookup pre-rename fh of renamed object */
8435 	argop[2].argop = OP_CLOOKUP;
8436 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8437 
8438 	/* 3: getfh fh of renamed object (before rename) */
8439 	argop[3].argop = OP_GETFH;
8440 
8441 	/* 4: putfh targetdir */
8442 	argop[4].argop = OP_CPUTFH;
8443 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8444 
8445 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8446 	argop[5].argop = OP_CRENAME;
8447 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8448 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8449 
8450 	/* 6: getattr of target dir (post op attrs) */
8451 	argop[6].argop = OP_GETATTR;
8452 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8453 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8454 
8455 	/* 7: Lookup post-rename fh of renamed object */
8456 	argop[7].argop = OP_CLOOKUP;
8457 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8458 
8459 	/* 8: getfh fh of renamed object (after rename) */
8460 	argop[8].argop = OP_GETFH;
8461 
8462 	/* 9: getattr of renamed object */
8463 	argop[9].argop = OP_GETATTR;
8464 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8465 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8466 
8467 	/*
8468 	 * If source/target dirs are different, then get new post-op
8469 	 * attrs for source dir also.
8470 	 */
8471 	if (ndvp != odvp) {
8472 		/* 10: putfh (sourcedir) */
8473 		argop[10].argop = OP_CPUTFH;
8474 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8475 
8476 		/* 11: getattr (sourcedir) */
8477 		argop[11].argop = OP_GETATTR;
8478 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8479 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8480 	}
8481 
8482 	dnlc_remove(odvp, onm);
8483 	dnlc_remove(ndvp, nnm);
8484 
8485 	doqueue = 1;
8486 	t = gethrtime();
8487 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8488 
8489 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8490 	if (e.error) {
8491 		PURGE_ATTRCACHE4(odvp);
8492 		PURGE_ATTRCACHE4(ndvp);
8493 		if (!needrecov) {
8494 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8495 			    &recov_state, needrecov);
8496 			goto out;
8497 		}
8498 	} else {
8499 		*statp = res.status;
8500 	}
8501 
8502 	if (needrecov) {
8503 		bool_t abort;
8504 
8505 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8506 		    OP_RENAME, NULL, NULL, NULL);
8507 		if (abort == FALSE) {
8508 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8509 			    &recov_state, needrecov);
8510 			kmem_free(argop, argoplist_size);
8511 			if (!e.error)
8512 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8513 				    (caddr_t)&res);
8514 			mutex_enter(&orp->r_statelock);
8515 			orp->r_flags &= ~R4RECEXPFH;
8516 			cv_broadcast(&orp->r_cv);
8517 			mutex_exit(&orp->r_statelock);
8518 			goto recov_retry;
8519 		} else {
8520 			if (e.error != 0) {
8521 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8522 				    &recov_state, needrecov);
8523 				goto out;
8524 			}
8525 			/* fall through for res.status case */
8526 		}
8527 	}
8528 
8529 	resp = &res;
8530 	/*
8531 	 * If OP_RENAME (or any prev op) failed, then return an error.
8532 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8533 	 */
8534 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8535 		/*
8536 		 * Error in an op other than last Getattr
8537 		 */
8538 		e.error = geterrno4(res.status);
8539 		PURGE_ATTRCACHE4(odvp);
8540 		PURGE_ATTRCACHE4(ndvp);
8541 		/*
8542 		 * System V defines rename to return EEXIST, not
8543 		 * ENOTEMPTY if the target directory is not empty.
8544 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8545 		 * which geterrno4 maps to ENOTEMPTY.
8546 		 */
8547 		if (e.error == ENOTEMPTY)
8548 			e.error = EEXIST;
8549 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8550 		    needrecov);
8551 		goto out;
8552 	}
8553 
8554 	/* rename results */
8555 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8556 
8557 	if (res.status == NFS4_OK) {
8558 		/* Update target attribute, readdir and dnlc caches */
8559 		dinfo.di_garp =
8560 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
8561 		dinfo.di_cred = cr;
8562 		dinfo.di_time_call = t;
8563 	} else
8564 		dinfop = NULL;
8565 
8566 	/* Update source cache attribute, readdir and dnlc caches */
8567 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8568 
8569 	/* Update source cache attribute, readdir and dnlc caches */
8570 	if (ndvp != odvp) {
8571 		update_parentdir_sfh(ovp, ndvp);
8572 
8573 		/*
8574 		 * If dinfop is non-NULL, then compound succeded, so
8575 		 * set di_garp to attrs for source dir.  dinfop is only
8576 		 * set to NULL when compound fails.
8577 		 */
8578 		if (dinfop)
8579 			dinfo.di_garp =
8580 			    &res.array[11].nfs_resop4_u.opgetattr.ga_res;
8581 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8582 		    dinfop);
8583 	}
8584 
8585 	/*
8586 	 * Update the rnode with the new component name and args,
8587 	 * and if the file handle changed, also update it with the new fh.
8588 	 * This is only necessary if the target object has an rnode
8589 	 * entry and there is no need to create one for it.
8590 	 */
8591 	resop = &res.array[8];	/* getfh new res */
8592 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8593 
8594 	/*
8595 	 * Update the path and filehandle for the renamed object.
8596 	 */
8597 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8598 
8599 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8600 
8601 	if (res.status == NFS4_OK) {
8602 		resop++;	/* getattr res */
8603 		e.error = nfs4_update_attrcache(res.status,
8604 		    &resop->nfs_resop4_u.opgetattr.ga_res,
8605 		    t, ovp, cr);
8606 	}
8607 
8608 out:
8609 	kmem_free(argop, argoplist_size);
8610 	if (resp)
8611 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8612 	mutex_enter(&orp->r_statelock);
8613 	orp->r_flags &= ~R4RECEXPFH;
8614 	cv_broadcast(&orp->r_cv);
8615 	mutex_exit(&orp->r_statelock);
8616 
8617 	return (e.error);
8618 }
8619 
8620 /* ARGSUSED */
8621 static int
8622 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr,
8623     caller_context_t *ct, int flags, vsecattr_t *vsecp)
8624 {
8625 	int error;
8626 	vnode_t *vp;
8627 
8628 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8629 		return (EPERM);
8630 	/*
8631 	 * As ".." has special meaning and rather than send a mkdir
8632 	 * over the wire to just let the server freak out, we just
8633 	 * short circuit it here and return EEXIST
8634 	 */
8635 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8636 		return (EEXIST);
8637 
8638 	/*
8639 	 * Decision to get the right gid and setgid bit of the
8640 	 * new directory is now made in call_nfs4_create_req.
8641 	 */
8642 	va->va_mask |= AT_MODE;
8643 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8644 	if (error)
8645 		return (error);
8646 
8647 	*vpp = vp;
8648 	return (0);
8649 }
8650 
8651 
8652 /*
8653  * rmdir is using the same remove v4 op as does remove.
8654  * Remove requires that the current fh be the target directory.
8655  * After the operation, the current fh is unchanged.
8656  * The compound op structure is:
8657  *      PUTFH(targetdir), REMOVE
8658  */
8659 /*ARGSUSED4*/
8660 static int
8661 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr,
8662     caller_context_t *ct, int flags)
8663 {
8664 	int need_end_op = FALSE;
8665 	COMPOUND4args_clnt args;
8666 	COMPOUND4res_clnt res, *resp = NULL;
8667 	REMOVE4res *rm_res;
8668 	nfs_argop4 argop[3];
8669 	nfs_resop4 *resop;
8670 	vnode_t *vp;
8671 	int doqueue;
8672 	mntinfo4_t *mi;
8673 	rnode4_t *drp;
8674 	bool_t needrecov = FALSE;
8675 	nfs4_recov_state_t recov_state;
8676 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8677 	dirattr_info_t dinfo, *dinfop;
8678 
8679 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8680 		return (EPERM);
8681 	/*
8682 	 * As ".." has special meaning and rather than send a rmdir
8683 	 * over the wire to just let the server freak out, we just
8684 	 * short circuit it here and return EEXIST
8685 	 */
8686 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8687 		return (EEXIST);
8688 
8689 	drp = VTOR4(dvp);
8690 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8691 		return (EINTR);
8692 
8693 	/*
8694 	 * Attempt to prevent a rmdir(".") from succeeding.
8695 	 */
8696 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8697 	if (e.error) {
8698 		nfs_rw_exit(&drp->r_rwlock);
8699 		return (e.error);
8700 	}
8701 	if (vp == cdir) {
8702 		VN_RELE(vp);
8703 		nfs_rw_exit(&drp->r_rwlock);
8704 		return (EINVAL);
8705 	}
8706 
8707 	/*
8708 	 * Since nfsv4 remove op works on both files and directories,
8709 	 * check that the removed object is indeed a directory.
8710 	 */
8711 	if (vp->v_type != VDIR) {
8712 		VN_RELE(vp);
8713 		nfs_rw_exit(&drp->r_rwlock);
8714 		return (ENOTDIR);
8715 	}
8716 
8717 	/*
8718 	 * First just remove the entry from the name cache, as it
8719 	 * is most likely an entry for this vp.
8720 	 */
8721 	dnlc_remove(dvp, nm);
8722 
8723 	/*
8724 	 * If there vnode reference count is greater than one, then
8725 	 * there may be additional references in the DNLC which will
8726 	 * need to be purged.  First, trying removing the entry for
8727 	 * the parent directory and see if that removes the additional
8728 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8729 	 * to completely remove any references to the directory which
8730 	 * might still exist in the DNLC.
8731 	 */
8732 	if (vp->v_count > 1) {
8733 		dnlc_remove(vp, "..");
8734 		if (vp->v_count > 1)
8735 			dnlc_purge_vp(vp);
8736 	}
8737 
8738 	mi = VTOMI4(dvp);
8739 	recov_state.rs_flags = 0;
8740 	recov_state.rs_num_retry_despite_err = 0;
8741 
8742 recov_retry:
8743 	args.ctag = TAG_RMDIR;
8744 
8745 	/*
8746 	 * Rmdir ops: putfh dir; remove
8747 	 */
8748 	args.array_len = 3;
8749 	args.array = argop;
8750 
8751 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8752 	if (e.error) {
8753 		nfs_rw_exit(&drp->r_rwlock);
8754 		return (e.error);
8755 	}
8756 	need_end_op = TRUE;
8757 
8758 	/* putfh directory */
8759 	argop[0].argop = OP_CPUTFH;
8760 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8761 
8762 	/* remove */
8763 	argop[1].argop = OP_CREMOVE;
8764 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8765 
8766 	/* getattr (postop attrs for dir that contained removed dir) */
8767 	argop[2].argop = OP_GETATTR;
8768 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8769 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8770 
8771 	dinfo.di_time_call = gethrtime();
8772 	doqueue = 1;
8773 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8774 
8775 	PURGE_ATTRCACHE4(vp);
8776 
8777 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8778 	if (e.error) {
8779 		PURGE_ATTRCACHE4(dvp);
8780 	}
8781 
8782 	if (needrecov) {
8783 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8784 		    NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
8785 			if (!e.error)
8786 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8787 				    (caddr_t)&res);
8788 
8789 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8790 			    needrecov);
8791 			need_end_op = FALSE;
8792 			goto recov_retry;
8793 		}
8794 	}
8795 
8796 	if (!e.error) {
8797 		resp = &res;
8798 
8799 		/*
8800 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8801 		 * failed.
8802 		 */
8803 		if (res.status != NFS4_OK && res.array_len <= 2) {
8804 			e.error = geterrno4(res.status);
8805 			PURGE_ATTRCACHE4(dvp);
8806 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8807 			    &recov_state, needrecov);
8808 			need_end_op = FALSE;
8809 			nfs4_purge_stale_fh(e.error, dvp, cr);
8810 			/*
8811 			 * System V defines rmdir to return EEXIST, not
8812 			 * ENOTEMPTY if the directory is not empty.  Over
8813 			 * the wire, the error is NFSERR_ENOTEMPTY which
8814 			 * geterrno4 maps to ENOTEMPTY.
8815 			 */
8816 			if (e.error == ENOTEMPTY)
8817 				e.error = EEXIST;
8818 		} else {
8819 			resop = &res.array[1];	/* remove res */
8820 			rm_res = &resop->nfs_resop4_u.opremove;
8821 
8822 			if (res.status == NFS4_OK) {
8823 				resop = &res.array[2];	/* dir attrs */
8824 				dinfo.di_garp =
8825 				    &resop->nfs_resop4_u.opgetattr.ga_res;
8826 				dinfo.di_cred = cr;
8827 				dinfop = &dinfo;
8828 			} else
8829 				dinfop = NULL;
8830 
8831 			/* Update dir attribute, readdir and dnlc caches */
8832 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8833 			    dinfop);
8834 
8835 			/* destroy rddir cache for dir that was removed */
8836 			if (VTOR4(vp)->r_dir != NULL)
8837 				nfs4_purge_rddir_cache(vp);
8838 		}
8839 	}
8840 
8841 	if (need_end_op)
8842 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8843 
8844 	nfs_rw_exit(&drp->r_rwlock);
8845 
8846 	if (resp)
8847 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8848 
8849 	if (e.error == 0) {
8850 		vnode_t *tvp;
8851 		rnode4_t *trp;
8852 		trp = VTOR4(vp);
8853 		tvp = vp;
8854 		if (IS_SHADOW(vp, trp))
8855 			tvp = RTOV4(trp);
8856 		vnevent_rmdir(tvp, dvp, nm, ct);
8857 	}
8858 
8859 	VN_RELE(vp);
8860 
8861 	return (e.error);
8862 }
8863 
8864 /* ARGSUSED */
8865 static int
8866 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr,
8867     caller_context_t *ct, int flags)
8868 {
8869 	int error;
8870 	vnode_t *vp;
8871 	rnode4_t *rp;
8872 	char *contents;
8873 	mntinfo4_t *mi = VTOMI4(dvp);
8874 
8875 	if (nfs_zone() != mi->mi_zone)
8876 		return (EPERM);
8877 	if (!(mi->mi_flags & MI4_SYMLINK))
8878 		return (EOPNOTSUPP);
8879 
8880 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8881 	if (error)
8882 		return (error);
8883 
8884 	ASSERT(nfs4_consistent_type(vp));
8885 	rp = VTOR4(vp);
8886 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8887 
8888 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8889 
8890 		if (contents != NULL) {
8891 			mutex_enter(&rp->r_statelock);
8892 			if (rp->r_symlink.contents == NULL) {
8893 				rp->r_symlink.len = strlen(tnm);
8894 				bcopy(tnm, contents, rp->r_symlink.len);
8895 				rp->r_symlink.contents = contents;
8896 				rp->r_symlink.size = MAXPATHLEN;
8897 				mutex_exit(&rp->r_statelock);
8898 			} else {
8899 				mutex_exit(&rp->r_statelock);
8900 				kmem_free((void *)contents, MAXPATHLEN);
8901 			}
8902 		}
8903 	}
8904 	VN_RELE(vp);
8905 
8906 	return (error);
8907 }
8908 
8909 
8910 /*
8911  * Read directory entries.
8912  * There are some weird things to look out for here.  The uio_loffset
8913  * field is either 0 or it is the offset returned from a previous
8914  * readdir.  It is an opaque value used by the server to find the
8915  * correct directory block to read. The count field is the number
8916  * of blocks to read on the server.  This is advisory only, the server
8917  * may return only one block's worth of entries.  Entries may be compressed
8918  * on the server.
8919  */
8920 /* ARGSUSED */
8921 static int
8922 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp,
8923     caller_context_t *ct, int flags)
8924 {
8925 	int error;
8926 	uint_t count;
8927 	rnode4_t *rp;
8928 	rddir4_cache *rdc;
8929 	rddir4_cache *rrdc;
8930 
8931 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8932 		return (EIO);
8933 	rp = VTOR4(vp);
8934 
8935 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8936 
8937 	/*
8938 	 * Make sure that the directory cache is valid.
8939 	 */
8940 	if (rp->r_dir != NULL) {
8941 		if (nfs_disable_rddir_cache != 0) {
8942 			/*
8943 			 * Setting nfs_disable_rddir_cache in /etc/system
8944 			 * allows interoperability with servers that do not
8945 			 * properly update the attributes of directories.
8946 			 * Any cached information gets purged before an
8947 			 * access is made to it.
8948 			 */
8949 			nfs4_purge_rddir_cache(vp);
8950 		}
8951 
8952 		error = nfs4_validate_caches(vp, cr);
8953 		if (error)
8954 			return (error);
8955 	}
8956 
8957 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8958 
8959 	/*
8960 	 * Short circuit last readdir which always returns 0 bytes.
8961 	 * This can be done after the directory has been read through
8962 	 * completely at least once.  This will set r_direof which
8963 	 * can be used to find the value of the last cookie.
8964 	 */
8965 	mutex_enter(&rp->r_statelock);
8966 	if (rp->r_direof != NULL &&
8967 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8968 		mutex_exit(&rp->r_statelock);
8969 #ifdef DEBUG
8970 		nfs4_readdir_cache_shorts++;
8971 #endif
8972 		if (eofp)
8973 			*eofp = 1;
8974 		return (0);
8975 	}
8976 
8977 	/*
8978 	 * Look for a cache entry.  Cache entries are identified
8979 	 * by the NFS cookie value and the byte count requested.
8980 	 */
8981 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8982 
8983 	/*
8984 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8985 	 */
8986 	if (rdc == NULL) {
8987 		mutex_exit(&rp->r_statelock);
8988 		return (EINTR);
8989 	}
8990 
8991 	/*
8992 	 * Check to see if we need to fill this entry in.
8993 	 */
8994 	if (rdc->flags & RDDIRREQ) {
8995 		rdc->flags &= ~RDDIRREQ;
8996 		rdc->flags |= RDDIR;
8997 		mutex_exit(&rp->r_statelock);
8998 
8999 		/*
9000 		 * Do the readdir.
9001 		 */
9002 		nfs4readdir(vp, rdc, cr);
9003 
9004 		/*
9005 		 * Reacquire the lock, so that we can continue
9006 		 */
9007 		mutex_enter(&rp->r_statelock);
9008 		/*
9009 		 * The entry is now complete
9010 		 */
9011 		rdc->flags &= ~RDDIR;
9012 	}
9013 
9014 	ASSERT(!(rdc->flags & RDDIR));
9015 
9016 	/*
9017 	 * If an error occurred while attempting
9018 	 * to fill the cache entry, mark the entry invalid and
9019 	 * just return the error.
9020 	 */
9021 	if (rdc->error) {
9022 		error = rdc->error;
9023 		rdc->flags |= RDDIRREQ;
9024 		rddir4_cache_rele(rp, rdc);
9025 		mutex_exit(&rp->r_statelock);
9026 		return (error);
9027 	}
9028 
9029 	/*
9030 	 * The cache entry is complete and good,
9031 	 * copyout the dirent structs to the calling
9032 	 * thread.
9033 	 */
9034 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
9035 
9036 	/*
9037 	 * If no error occurred during the copyout,
9038 	 * update the offset in the uio struct to
9039 	 * contain the value of the next NFS 4 cookie
9040 	 * and set the eof value appropriately.
9041 	 */
9042 	if (!error) {
9043 		uiop->uio_loffset = rdc->nfs4_ncookie;
9044 		if (eofp)
9045 			*eofp = rdc->eof;
9046 	}
9047 
9048 	/*
9049 	 * Decide whether to do readahead.  Don't if we
9050 	 * have already read to the end of directory.
9051 	 */
9052 	if (rdc->eof) {
9053 		/*
9054 		 * Make the entry the direof only if it is cached
9055 		 */
9056 		if (rdc->flags & RDDIRCACHED)
9057 			rp->r_direof = rdc;
9058 		rddir4_cache_rele(rp, rdc);
9059 		mutex_exit(&rp->r_statelock);
9060 		return (error);
9061 	}
9062 
9063 	/* Determine if a readdir readahead should be done */
9064 	if (!(rp->r_flags & R4LOOKUP)) {
9065 		rddir4_cache_rele(rp, rdc);
9066 		mutex_exit(&rp->r_statelock);
9067 		return (error);
9068 	}
9069 
9070 	/*
9071 	 * Now look for a readahead entry.
9072 	 *
9073 	 * Check to see whether we found an entry for the readahead.
9074 	 * If so, we don't need to do anything further, so free the new
9075 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
9076 	 * it to the cache, and then initiate an asynchronous readdir
9077 	 * operation to fill it.
9078 	 */
9079 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
9080 
9081 	/*
9082 	 * A readdir cache entry could not be obtained for the readahead.  In
9083 	 * this case we skip the readahead and return.
9084 	 */
9085 	if (rrdc == NULL) {
9086 		rddir4_cache_rele(rp, rdc);
9087 		mutex_exit(&rp->r_statelock);
9088 		return (error);
9089 	}
9090 
9091 	/*
9092 	 * Check to see if we need to fill this entry in.
9093 	 */
9094 	if (rrdc->flags & RDDIRREQ) {
9095 		rrdc->flags &= ~RDDIRREQ;
9096 		rrdc->flags |= RDDIR;
9097 		rddir4_cache_rele(rp, rdc);
9098 		mutex_exit(&rp->r_statelock);
9099 #ifdef DEBUG
9100 		nfs4_readdir_readahead++;
9101 #endif
9102 		/*
9103 		 * Do the readdir.
9104 		 */
9105 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
9106 		return (error);
9107 	}
9108 
9109 	rddir4_cache_rele(rp, rrdc);
9110 	rddir4_cache_rele(rp, rdc);
9111 	mutex_exit(&rp->r_statelock);
9112 	return (error);
9113 }
9114 
9115 static int
9116 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9117 {
9118 	int error;
9119 	rnode4_t *rp;
9120 
9121 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9122 
9123 	rp = VTOR4(vp);
9124 
9125 	/*
9126 	 * Obtain the readdir results for the caller.
9127 	 */
9128 	nfs4readdir(vp, rdc, cr);
9129 
9130 	mutex_enter(&rp->r_statelock);
9131 	/*
9132 	 * The entry is now complete
9133 	 */
9134 	rdc->flags &= ~RDDIR;
9135 
9136 	error = rdc->error;
9137 	if (error)
9138 		rdc->flags |= RDDIRREQ;
9139 	rddir4_cache_rele(rp, rdc);
9140 	mutex_exit(&rp->r_statelock);
9141 
9142 	return (error);
9143 }
9144 
9145 /*
9146  * Read directory entries.
9147  * There are some weird things to look out for here.  The uio_loffset
9148  * field is either 0 or it is the offset returned from a previous
9149  * readdir.  It is an opaque value used by the server to find the
9150  * correct directory block to read. The count field is the number
9151  * of blocks to read on the server.  This is advisory only, the server
9152  * may return only one block's worth of entries.  Entries may be compressed
9153  * on the server.
9154  *
9155  * Generates the following compound request:
9156  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9157  *    must include a Lookupp as well. In this case, send:
9158  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9159  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9160  *
9161  * Get complete attributes and filehandles for entries if this is the
9162  * first read of the directory. Otherwise, just get fileid's.
9163  */
9164 static void
9165 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9166 {
9167 	COMPOUND4args_clnt args;
9168 	COMPOUND4res_clnt res;
9169 	READDIR4args *rargs;
9170 	READDIR4res_clnt *rd_res;
9171 	bitmap4 rd_bitsval;
9172 	nfs_argop4 argop[5];
9173 	nfs_resop4 *resop;
9174 	rnode4_t *rp = VTOR4(vp);
9175 	mntinfo4_t *mi = VTOMI4(vp);
9176 	int doqueue;
9177 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9178 	vnode_t *dvp;
9179 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9180 	int num_ops, res_opcnt;
9181 	bool_t needrecov = FALSE;
9182 	nfs4_recov_state_t recov_state;
9183 	hrtime_t t;
9184 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9185 
9186 	ASSERT(nfs_zone() == mi->mi_zone);
9187 	ASSERT(rdc->flags & RDDIR);
9188 	ASSERT(rdc->entries == NULL);
9189 
9190 	/*
9191 	 * If rp were a stub, it should have triggered and caused
9192 	 * a mount for us to get this far.
9193 	 */
9194 	ASSERT(!RP_ISSTUB(rp));
9195 
9196 	num_ops = 2;
9197 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9198 		/*
9199 		 * Since nfsv4 readdir may not return entries for "." and "..",
9200 		 * the client must recreate them:
9201 		 * To find the correct nodeid, do the following:
9202 		 * For current node, get nodeid from dnlc.
9203 		 * - if current node is rootvp, set pnodeid to nodeid.
9204 		 * - else if parent is in the dnlc, get its nodeid from there.
9205 		 * - else add LOOKUPP+GETATTR to compound.
9206 		 */
9207 		nodeid = rp->r_attr.va_nodeid;
9208 		if (vp->v_flag & VROOT) {
9209 			pnodeid = nodeid;	/* root of mount point */
9210 		} else {
9211 			dvp = dnlc_lookup(vp, "..");
9212 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9213 				/* parent in dnlc cache - no need for otw */
9214 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9215 			} else {
9216 				/*
9217 				 * parent not in dnlc cache,
9218 				 * do lookupp to get its id
9219 				 */
9220 				num_ops = 5;
9221 				pnodeid = 0; /* set later by getattr parent */
9222 			}
9223 			if (dvp)
9224 				VN_RELE(dvp);
9225 		}
9226 	}
9227 	recov_state.rs_flags = 0;
9228 	recov_state.rs_num_retry_despite_err = 0;
9229 
9230 	/* Save the original mount point security flavor */
9231 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9232 
9233 recov_retry:
9234 	args.ctag = TAG_READDIR;
9235 
9236 	args.array = argop;
9237 	args.array_len = num_ops;
9238 
9239 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9240 	    &recov_state, NULL)) {
9241 		/*
9242 		 * If readdir a node that is a stub for a crossed mount point,
9243 		 * keep the original secinfo flavor for the current file
9244 		 * system, not the crossed one.
9245 		 */
9246 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9247 		rdc->error = e.error;
9248 		return;
9249 	}
9250 
9251 	/*
9252 	 * Determine which attrs to request for dirents.  This code
9253 	 * must be protected by nfs4_start/end_fop because of r_server
9254 	 * (which will change during failover recovery).
9255 	 *
9256 	 */
9257 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9258 		/*
9259 		 * Get all vattr attrs plus filehandle and rdattr_error
9260 		 */
9261 		rd_bitsval = NFS4_VATTR_MASK |
9262 		    FATTR4_RDATTR_ERROR_MASK |
9263 		    FATTR4_FILEHANDLE_MASK;
9264 
9265 		if (rp->r_flags & R4READDIRWATTR) {
9266 			mutex_enter(&rp->r_statelock);
9267 			rp->r_flags &= ~R4READDIRWATTR;
9268 			mutex_exit(&rp->r_statelock);
9269 		}
9270 	} else {
9271 		servinfo4_t *svp = rp->r_server;
9272 
9273 		/*
9274 		 * Already read directory. Use readdir with
9275 		 * no attrs (except for mounted_on_fileid) for updates.
9276 		 */
9277 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9278 
9279 		/*
9280 		 * request mounted on fileid if supported, else request
9281 		 * fileid.  maybe we should verify that fileid is supported
9282 		 * and request something else if not.
9283 		 */
9284 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9285 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9286 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9287 		nfs_rw_exit(&svp->sv_lock);
9288 	}
9289 
9290 	/* putfh directory fh */
9291 	argop[0].argop = OP_CPUTFH;
9292 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9293 
9294 	argop[1].argop = OP_READDIR;
9295 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9296 	/*
9297 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9298 	 * cookie 0 should be used over-the-wire to start reading at
9299 	 * the beginning of the directory excluding "." and "..".
9300 	 */
9301 	if (rdc->nfs4_cookie == 0 ||
9302 	    rdc->nfs4_cookie == 1 ||
9303 	    rdc->nfs4_cookie == 2) {
9304 		rargs->cookie = (nfs_cookie4)0;
9305 		rargs->cookieverf = 0;
9306 	} else {
9307 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9308 		mutex_enter(&rp->r_statelock);
9309 		rargs->cookieverf = rp->r_cookieverf4;
9310 		mutex_exit(&rp->r_statelock);
9311 	}
9312 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9313 	rargs->maxcount = mi->mi_tsize;
9314 	rargs->attr_request = rd_bitsval;
9315 	rargs->rdc = rdc;
9316 	rargs->dvp = vp;
9317 	rargs->mi = mi;
9318 	rargs->cr = cr;
9319 
9320 
9321 	/*
9322 	 * If count < than the minimum required, we return no entries
9323 	 * and fail with EINVAL
9324 	 */
9325 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9326 		rdc->error = EINVAL;
9327 		goto out;
9328 	}
9329 
9330 	if (args.array_len == 5) {
9331 		/*
9332 		 * Add lookupp and getattr for parent nodeid.
9333 		 */
9334 		argop[2].argop = OP_LOOKUPP;
9335 
9336 		argop[3].argop = OP_GETFH;
9337 
9338 		/* getattr parent */
9339 		argop[4].argop = OP_GETATTR;
9340 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9341 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9342 	}
9343 
9344 	doqueue = 1;
9345 
9346 	if (mi->mi_io_kstats) {
9347 		mutex_enter(&mi->mi_lock);
9348 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9349 		mutex_exit(&mi->mi_lock);
9350 	}
9351 
9352 	/* capture the time of this call */
9353 	rargs->t = t = gethrtime();
9354 
9355 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9356 
9357 	if (mi->mi_io_kstats) {
9358 		mutex_enter(&mi->mi_lock);
9359 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9360 		mutex_exit(&mi->mi_lock);
9361 	}
9362 
9363 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9364 
9365 	/*
9366 	 * If RPC error occurred and it isn't an error that
9367 	 * triggers recovery, then go ahead and fail now.
9368 	 */
9369 	if (e.error != 0 && !needrecov) {
9370 		rdc->error = e.error;
9371 		goto out;
9372 	}
9373 
9374 	if (needrecov) {
9375 		bool_t abort;
9376 
9377 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9378 		    "nfs4readdir: initiating recovery.\n"));
9379 
9380 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9381 		    NULL, OP_READDIR, NULL, NULL, NULL);
9382 		if (abort == FALSE) {
9383 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9384 			    &recov_state, needrecov);
9385 			if (!e.error)
9386 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9387 				    (caddr_t)&res);
9388 			if (rdc->entries != NULL) {
9389 				kmem_free(rdc->entries, rdc->entlen);
9390 				rdc->entries = NULL;
9391 			}
9392 			goto recov_retry;
9393 		}
9394 
9395 		if (e.error != 0) {
9396 			rdc->error = e.error;
9397 			goto out;
9398 		}
9399 
9400 		/* fall through for res.status case */
9401 	}
9402 
9403 	res_opcnt = res.array_len;
9404 
9405 	/*
9406 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9407 	 * failure here.  Subsequent ops are for filling out dot-dot
9408 	 * dirent, and if they fail, we still want to give the caller
9409 	 * the dirents returned by (the successful) READDIR op, so we need
9410 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9411 	 *
9412 	 * One example where PUTFH+READDIR ops would succeed but
9413 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9414 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9415 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9416 	 * x perm.  We need to come up with a non-vendor-specific way
9417 	 * for a POSIX server to return d_ino from dotdot's dirent if
9418 	 * client only requests mounted_on_fileid, and just say the
9419 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9420 	 * client requested any mandatory attrs, server would be required
9421 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9422 	 * for dotdot.
9423 	 */
9424 
9425 	if (res.status) {
9426 		if (res_opcnt <= 2) {
9427 			e.error = geterrno4(res.status);
9428 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9429 			    &recov_state, needrecov);
9430 			nfs4_purge_stale_fh(e.error, vp, cr);
9431 			rdc->error = e.error;
9432 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9433 			if (rdc->entries != NULL) {
9434 				kmem_free(rdc->entries, rdc->entlen);
9435 				rdc->entries = NULL;
9436 			}
9437 			/*
9438 			 * If readdir a node that is a stub for a
9439 			 * crossed mount point, keep the original
9440 			 * secinfo flavor for the current file system,
9441 			 * not the crossed one.
9442 			 */
9443 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9444 			return;
9445 		}
9446 	}
9447 
9448 	resop = &res.array[1];	/* readdir res */
9449 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9450 
9451 	mutex_enter(&rp->r_statelock);
9452 	rp->r_cookieverf4 = rd_res->cookieverf;
9453 	mutex_exit(&rp->r_statelock);
9454 
9455 	/*
9456 	 * For "." and ".." entries
9457 	 * e.g.
9458 	 *	seek(cookie=0) -> "." entry with d_off = 1
9459 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9460 	 */
9461 	if (cookie == (nfs_cookie4) 0) {
9462 		if (rd_res->dotp)
9463 			rd_res->dotp->d_ino = nodeid;
9464 		if (rd_res->dotdotp)
9465 			rd_res->dotdotp->d_ino = pnodeid;
9466 	}
9467 	if (cookie == (nfs_cookie4) 1) {
9468 		if (rd_res->dotdotp)
9469 			rd_res->dotdotp->d_ino = pnodeid;
9470 	}
9471 
9472 
9473 	/* LOOKUPP+GETATTR attemped */
9474 	if (args.array_len == 5 && rd_res->dotdotp) {
9475 		if (res.status == NFS4_OK && res_opcnt == 5) {
9476 			nfs_fh4 *fhp;
9477 			nfs4_sharedfh_t *sfhp;
9478 			vnode_t *pvp;
9479 			nfs4_ga_res_t *garp;
9480 
9481 			resop++;	/* lookupp */
9482 			resop++;	/* getfh   */
9483 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9484 
9485 			resop++;	/* getattr of parent */
9486 
9487 			/*
9488 			 * First, take care of finishing the
9489 			 * readdir results.
9490 			 */
9491 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9492 			/*
9493 			 * The d_ino of .. must be the inode number
9494 			 * of the mounted filesystem.
9495 			 */
9496 			if (garp->n4g_va.va_mask & AT_NODEID)
9497 				rd_res->dotdotp->d_ino =
9498 				    garp->n4g_va.va_nodeid;
9499 
9500 
9501 			/*
9502 			 * Next, create the ".." dnlc entry
9503 			 */
9504 			sfhp = sfh4_get(fhp, mi);
9505 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9506 				dnlc_update(vp, "..", pvp);
9507 				VN_RELE(pvp);
9508 			}
9509 			sfh4_rele(&sfhp);
9510 		}
9511 	}
9512 
9513 	if (mi->mi_io_kstats) {
9514 		mutex_enter(&mi->mi_lock);
9515 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9516 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9517 		mutex_exit(&mi->mi_lock);
9518 	}
9519 
9520 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9521 
9522 out:
9523 	/*
9524 	 * If readdir a node that is a stub for a crossed mount point,
9525 	 * keep the original secinfo flavor for the current file system,
9526 	 * not the crossed one.
9527 	 */
9528 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9529 
9530 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9531 }
9532 
9533 
9534 static int
9535 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9536 {
9537 	rnode4_t *rp = VTOR4(bp->b_vp);
9538 	int count;
9539 	int error;
9540 	cred_t *cred_otw = NULL;
9541 	offset_t offset;
9542 	nfs4_open_stream_t *osp = NULL;
9543 	bool_t first_time = TRUE;	/* first time getting otw cred */
9544 	bool_t last_time = FALSE;	/* last time getting otw cred */
9545 
9546 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9547 
9548 	DTRACE_IO1(start, struct buf *, bp);
9549 	offset = ldbtob(bp->b_lblkno);
9550 
9551 	if (bp->b_flags & B_READ) {
9552 	read_again:
9553 		/*
9554 		 * Releases the osp, if it is provided.
9555 		 * Puts a hold on the cred_otw and the new osp (if found).
9556 		 */
9557 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9558 		    &first_time, &last_time);
9559 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9560 		    offset, bp->b_bcount, &bp->b_resid, cred_otw,
9561 		    readahead, NULL);
9562 		crfree(cred_otw);
9563 		if (!error) {
9564 			if (bp->b_resid) {
9565 				/*
9566 				 * Didn't get it all because we hit EOF,
9567 				 * zero all the memory beyond the EOF.
9568 				 */
9569 				/* bzero(rdaddr + */
9570 				bzero(bp->b_un.b_addr +
9571 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9572 			}
9573 			mutex_enter(&rp->r_statelock);
9574 			if (bp->b_resid == bp->b_bcount &&
9575 			    offset >= rp->r_size) {
9576 				/*
9577 				 * We didn't read anything at all as we are
9578 				 * past EOF.  Return an error indicator back
9579 				 * but don't destroy the pages (yet).
9580 				 */
9581 				error = NFS_EOF;
9582 			}
9583 			mutex_exit(&rp->r_statelock);
9584 		} else if (error == EACCES && last_time == FALSE) {
9585 				goto read_again;
9586 		}
9587 	} else {
9588 		if (!(rp->r_flags & R4STALE)) {
9589 write_again:
9590 			/*
9591 			 * Releases the osp, if it is provided.
9592 			 * Puts a hold on the cred_otw and the new
9593 			 * osp (if found).
9594 			 */
9595 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9596 			    &first_time, &last_time);
9597 			mutex_enter(&rp->r_statelock);
9598 			count = MIN(bp->b_bcount, rp->r_size - offset);
9599 			mutex_exit(&rp->r_statelock);
9600 			if (count < 0)
9601 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9602 #ifdef DEBUG
9603 			if (count == 0) {
9604 				zoneid_t zoneid = getzoneid();
9605 
9606 				zcmn_err(zoneid, CE_WARN,
9607 				    "nfs4_bio: zero length write at %lld",
9608 				    offset);
9609 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9610 				    "b_bcount=%ld, file size=%lld",
9611 				    rp->r_flags, (long)bp->b_bcount,
9612 				    rp->r_size);
9613 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9614 				if (nfs4_bio_do_stop)
9615 					debug_enter("nfs4_bio");
9616 			}
9617 #endif
9618 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9619 			    count, cred_otw, stab_comm);
9620 			if (error == EACCES && last_time == FALSE) {
9621 				crfree(cred_otw);
9622 				goto write_again;
9623 			}
9624 			bp->b_error = error;
9625 			if (error && error != EINTR &&
9626 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9627 				/*
9628 				 * Don't print EDQUOT errors on the console.
9629 				 * Don't print asynchronous EACCES errors.
9630 				 * Don't print EFBIG errors.
9631 				 * Print all other write errors.
9632 				 */
9633 				if (error != EDQUOT && error != EFBIG &&
9634 				    (error != EACCES ||
9635 				    !(bp->b_flags & B_ASYNC)))
9636 					nfs4_write_error(bp->b_vp,
9637 					    error, cred_otw);
9638 				/*
9639 				 * Update r_error and r_flags as appropriate.
9640 				 * If the error was ESTALE, then mark the
9641 				 * rnode as not being writeable and save
9642 				 * the error status.  Otherwise, save any
9643 				 * errors which occur from asynchronous
9644 				 * page invalidations.  Any errors occurring
9645 				 * from other operations should be saved
9646 				 * by the caller.
9647 				 */
9648 				mutex_enter(&rp->r_statelock);
9649 				if (error == ESTALE) {
9650 					rp->r_flags |= R4STALE;
9651 					if (!rp->r_error)
9652 						rp->r_error = error;
9653 				} else if (!rp->r_error &&
9654 				    (bp->b_flags &
9655 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9656 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9657 					rp->r_error = error;
9658 				}
9659 				mutex_exit(&rp->r_statelock);
9660 			}
9661 			crfree(cred_otw);
9662 		} else {
9663 			error = rp->r_error;
9664 			/*
9665 			 * A close may have cleared r_error, if so,
9666 			 * propagate ESTALE error return properly
9667 			 */
9668 			if (error == 0)
9669 				error = ESTALE;
9670 		}
9671 	}
9672 
9673 	if (error != 0 && error != NFS_EOF)
9674 		bp->b_flags |= B_ERROR;
9675 
9676 	if (osp)
9677 		open_stream_rele(osp, rp);
9678 
9679 	DTRACE_IO1(done, struct buf *, bp);
9680 
9681 	return (error);
9682 }
9683 
9684 /* ARGSUSED */
9685 int
9686 nfs4_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
9687 {
9688 	return (EREMOTE);
9689 }
9690 
9691 /* ARGSUSED2 */
9692 int
9693 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9694 {
9695 	rnode4_t *rp = VTOR4(vp);
9696 
9697 	if (!write_lock) {
9698 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9699 		return (V_WRITELOCK_FALSE);
9700 	}
9701 
9702 	if ((rp->r_flags & R4DIRECTIO) ||
9703 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9704 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9705 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9706 			return (V_WRITELOCK_FALSE);
9707 		nfs_rw_exit(&rp->r_rwlock);
9708 	}
9709 
9710 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9711 	return (V_WRITELOCK_TRUE);
9712 }
9713 
9714 /* ARGSUSED */
9715 void
9716 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9717 {
9718 	rnode4_t *rp = VTOR4(vp);
9719 
9720 	nfs_rw_exit(&rp->r_rwlock);
9721 }
9722 
9723 /* ARGSUSED */
9724 static int
9725 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp, caller_context_t *ct)
9726 {
9727 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9728 		return (EIO);
9729 
9730 	/*
9731 	 * Because we stuff the readdir cookie into the offset field
9732 	 * someone may attempt to do an lseek with the cookie which
9733 	 * we want to succeed.
9734 	 */
9735 	if (vp->v_type == VDIR)
9736 		return (0);
9737 	if (*noffp < 0)
9738 		return (EINVAL);
9739 	return (0);
9740 }
9741 
9742 
9743 /*
9744  * Return all the pages from [off..off+len) in file
9745  */
9746 /* ARGSUSED */
9747 static int
9748 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9749     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9750     enum seg_rw rw, cred_t *cr, caller_context_t *ct)
9751 {
9752 	rnode4_t *rp;
9753 	int error;
9754 	mntinfo4_t *mi;
9755 
9756 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9757 		return (EIO);
9758 	rp = VTOR4(vp);
9759 	if (IS_SHADOW(vp, rp))
9760 		vp = RTOV4(rp);
9761 
9762 	if (vp->v_flag & VNOMAP)
9763 		return (ENOSYS);
9764 
9765 	if (protp != NULL)
9766 		*protp = PROT_ALL;
9767 
9768 	/*
9769 	 * Now validate that the caches are up to date.
9770 	 */
9771 	if (error = nfs4_validate_caches(vp, cr))
9772 		return (error);
9773 
9774 	mi = VTOMI4(vp);
9775 retry:
9776 	mutex_enter(&rp->r_statelock);
9777 
9778 	/*
9779 	 * Don't create dirty pages faster than they
9780 	 * can be cleaned so that the system doesn't
9781 	 * get imbalanced.  If the async queue is
9782 	 * maxed out, then wait for it to drain before
9783 	 * creating more dirty pages.  Also, wait for
9784 	 * any threads doing pagewalks in the vop_getattr
9785 	 * entry points so that they don't block for
9786 	 * long periods.
9787 	 */
9788 	if (rw == S_CREATE) {
9789 		while ((mi->mi_max_threads != 0 &&
9790 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
9791 		    rp->r_gcount > 0)
9792 			cv_wait(&rp->r_cv, &rp->r_statelock);
9793 	}
9794 
9795 	/*
9796 	 * If we are getting called as a side effect of an nfs_write()
9797 	 * operation the local file size might not be extended yet.
9798 	 * In this case we want to be able to return pages of zeroes.
9799 	 */
9800 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9801 		NFS4_DEBUG(nfs4_pageio_debug,
9802 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9803 		    "len=%llu, size=%llu, attrsize =%llu", off,
9804 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9805 		mutex_exit(&rp->r_statelock);
9806 		return (EFAULT);		/* beyond EOF */
9807 	}
9808 
9809 	mutex_exit(&rp->r_statelock);
9810 
9811 	error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9812 	    pl, plsz, seg, addr, rw, cr);
9813 	NFS4_DEBUG(nfs4_pageio_debug && error,
9814 	    (CE_NOTE, "getpages error %d; off=%lld, len=%lld",
9815 	    error, off, (u_longlong_t)len));
9816 
9817 	switch (error) {
9818 	case NFS_EOF:
9819 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9820 		goto retry;
9821 	case ESTALE:
9822 		nfs4_purge_stale_fh(error, vp, cr);
9823 	}
9824 
9825 	return (error);
9826 }
9827 
9828 /*
9829  * Called from pvn_getpages to get a particular page.
9830  */
9831 /* ARGSUSED */
9832 static int
9833 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9834     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9835     enum seg_rw rw, cred_t *cr)
9836 {
9837 	rnode4_t *rp;
9838 	uint_t bsize;
9839 	struct buf *bp;
9840 	page_t *pp;
9841 	u_offset_t lbn;
9842 	u_offset_t io_off;
9843 	u_offset_t blkoff;
9844 	u_offset_t rablkoff;
9845 	size_t io_len;
9846 	uint_t blksize;
9847 	int error;
9848 	int readahead;
9849 	int readahead_issued = 0;
9850 	int ra_window; /* readahead window */
9851 	page_t *pagefound;
9852 	page_t *savepp;
9853 
9854 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9855 		return (EIO);
9856 
9857 	rp = VTOR4(vp);
9858 	ASSERT(!IS_SHADOW(vp, rp));
9859 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9860 
9861 reread:
9862 	bp = NULL;
9863 	pp = NULL;
9864 	pagefound = NULL;
9865 
9866 	if (pl != NULL)
9867 		pl[0] = NULL;
9868 
9869 	error = 0;
9870 	lbn = off / bsize;
9871 	blkoff = lbn * bsize;
9872 
9873 	/*
9874 	 * Queueing up the readahead before doing the synchronous read
9875 	 * results in a significant increase in read throughput because
9876 	 * of the increased parallelism between the async threads and
9877 	 * the process context.
9878 	 */
9879 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9880 	    rw != S_CREATE &&
9881 	    !(vp->v_flag & VNOCACHE)) {
9882 		mutex_enter(&rp->r_statelock);
9883 
9884 		/*
9885 		 * Calculate the number of readaheads to do.
9886 		 * a) No readaheads at offset = 0.
9887 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9888 		 *    window is closed.
9889 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9890 		 *    upon how far the readahead window is open or close.
9891 		 * d) No readaheads if rp->r_nextr is not within the scope
9892 		 *    of the readahead window (random i/o).
9893 		 */
9894 
9895 		if (off == 0)
9896 			readahead = 0;
9897 		else if (blkoff == rp->r_nextr)
9898 			readahead = nfs4_nra;
9899 		else if (rp->r_nextr > blkoff &&
9900 		    ((ra_window = (rp->r_nextr - blkoff) / bsize)
9901 		    <= (nfs4_nra - 1)))
9902 			readahead = nfs4_nra - ra_window;
9903 		else
9904 			readahead = 0;
9905 
9906 		rablkoff = rp->r_nextr;
9907 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9908 			mutex_exit(&rp->r_statelock);
9909 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9910 			    addr + (rablkoff + bsize - off),
9911 			    seg, cr, nfs4_readahead) < 0) {
9912 				mutex_enter(&rp->r_statelock);
9913 				break;
9914 			}
9915 			readahead--;
9916 			rablkoff += bsize;
9917 			/*
9918 			 * Indicate that we did a readahead so
9919 			 * readahead offset is not updated
9920 			 * by the synchronous read below.
9921 			 */
9922 			readahead_issued = 1;
9923 			mutex_enter(&rp->r_statelock);
9924 			/*
9925 			 * set readahead offset to
9926 			 * offset of last async readahead
9927 			 * request.
9928 			 */
9929 			rp->r_nextr = rablkoff;
9930 		}
9931 		mutex_exit(&rp->r_statelock);
9932 	}
9933 
9934 again:
9935 	if ((pagefound = page_exists(vp, off)) == NULL) {
9936 		if (pl == NULL) {
9937 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9938 			    nfs4_readahead);
9939 		} else if (rw == S_CREATE) {
9940 			/*
9941 			 * Block for this page is not allocated, or the offset
9942 			 * is beyond the current allocation size, or we're
9943 			 * allocating a swap slot and the page was not found,
9944 			 * so allocate it and return a zero page.
9945 			 */
9946 			if ((pp = page_create_va(vp, off,
9947 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9948 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9949 			io_len = PAGESIZE;
9950 			mutex_enter(&rp->r_statelock);
9951 			rp->r_nextr = off + PAGESIZE;
9952 			mutex_exit(&rp->r_statelock);
9953 		} else {
9954 			/*
9955 			 * Need to go to server to get a block
9956 			 */
9957 			mutex_enter(&rp->r_statelock);
9958 			if (blkoff < rp->r_size &&
9959 			    blkoff + bsize > rp->r_size) {
9960 				/*
9961 				 * If less than a block left in
9962 				 * file read less than a block.
9963 				 */
9964 				if (rp->r_size <= off) {
9965 					/*
9966 					 * Trying to access beyond EOF,
9967 					 * set up to get at least one page.
9968 					 */
9969 					blksize = off + PAGESIZE - blkoff;
9970 				} else
9971 					blksize = rp->r_size - blkoff;
9972 			} else if ((off == 0) ||
9973 			    (off != rp->r_nextr && !readahead_issued)) {
9974 				blksize = PAGESIZE;
9975 				blkoff = off; /* block = page here */
9976 			} else
9977 				blksize = bsize;
9978 			mutex_exit(&rp->r_statelock);
9979 
9980 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9981 			    &io_len, blkoff, blksize, 0);
9982 
9983 			/*
9984 			 * Some other thread has entered the page,
9985 			 * so just use it.
9986 			 */
9987 			if (pp == NULL)
9988 				goto again;
9989 
9990 			/*
9991 			 * Now round the request size up to page boundaries.
9992 			 * This ensures that the entire page will be
9993 			 * initialized to zeroes if EOF is encountered.
9994 			 */
9995 			io_len = ptob(btopr(io_len));
9996 
9997 			bp = pageio_setup(pp, io_len, vp, B_READ);
9998 			ASSERT(bp != NULL);
9999 
10000 			/*
10001 			 * pageio_setup should have set b_addr to 0.  This
10002 			 * is correct since we want to do I/O on a page
10003 			 * boundary.  bp_mapin will use this addr to calculate
10004 			 * an offset, and then set b_addr to the kernel virtual
10005 			 * address it allocated for us.
10006 			 */
10007 			ASSERT(bp->b_un.b_addr == 0);
10008 
10009 			bp->b_edev = 0;
10010 			bp->b_dev = 0;
10011 			bp->b_lblkno = lbtodb(io_off);
10012 			bp->b_file = vp;
10013 			bp->b_offset = (offset_t)off;
10014 			bp_mapin(bp);
10015 
10016 			/*
10017 			 * If doing a write beyond what we believe is EOF,
10018 			 * don't bother trying to read the pages from the
10019 			 * server, we'll just zero the pages here.  We
10020 			 * don't check that the rw flag is S_WRITE here
10021 			 * because some implementations may attempt a
10022 			 * read access to the buffer before copying data.
10023 			 */
10024 			mutex_enter(&rp->r_statelock);
10025 			if (io_off >= rp->r_size && seg == segkmap) {
10026 				mutex_exit(&rp->r_statelock);
10027 				bzero(bp->b_un.b_addr, io_len);
10028 			} else {
10029 				mutex_exit(&rp->r_statelock);
10030 				error = nfs4_bio(bp, NULL, cr, FALSE);
10031 			}
10032 
10033 			/*
10034 			 * Unmap the buffer before freeing it.
10035 			 */
10036 			bp_mapout(bp);
10037 			pageio_done(bp);
10038 
10039 			savepp = pp;
10040 			do {
10041 				pp->p_fsdata = C_NOCOMMIT;
10042 			} while ((pp = pp->p_next) != savepp);
10043 
10044 			if (error == NFS_EOF) {
10045 				/*
10046 				 * If doing a write system call just return
10047 				 * zeroed pages, else user tried to get pages
10048 				 * beyond EOF, return error.  We don't check
10049 				 * that the rw flag is S_WRITE here because
10050 				 * some implementations may attempt a read
10051 				 * access to the buffer before copying data.
10052 				 */
10053 				if (seg == segkmap)
10054 					error = 0;
10055 				else
10056 					error = EFAULT;
10057 			}
10058 
10059 			if (!readahead_issued && !error) {
10060 				mutex_enter(&rp->r_statelock);
10061 				rp->r_nextr = io_off + io_len;
10062 				mutex_exit(&rp->r_statelock);
10063 			}
10064 		}
10065 	}
10066 
10067 out:
10068 	if (pl == NULL)
10069 		return (error);
10070 
10071 	if (error) {
10072 		if (pp != NULL)
10073 			pvn_read_done(pp, B_ERROR);
10074 		return (error);
10075 	}
10076 
10077 	if (pagefound) {
10078 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
10079 
10080 		/*
10081 		 * Page exists in the cache, acquire the appropriate lock.
10082 		 * If this fails, start all over again.
10083 		 */
10084 		if ((pp = page_lookup(vp, off, se)) == NULL) {
10085 #ifdef DEBUG
10086 			nfs4_lostpage++;
10087 #endif
10088 			goto reread;
10089 		}
10090 		pl[0] = pp;
10091 		pl[1] = NULL;
10092 		return (0);
10093 	}
10094 
10095 	if (pp != NULL)
10096 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
10097 
10098 	return (error);
10099 }
10100 
10101 static void
10102 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
10103     cred_t *cr)
10104 {
10105 	int error;
10106 	page_t *pp;
10107 	u_offset_t io_off;
10108 	size_t io_len;
10109 	struct buf *bp;
10110 	uint_t bsize, blksize;
10111 	rnode4_t *rp = VTOR4(vp);
10112 	page_t *savepp;
10113 
10114 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10115 
10116 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10117 
10118 	mutex_enter(&rp->r_statelock);
10119 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
10120 		/*
10121 		 * If less than a block left in file read less
10122 		 * than a block.
10123 		 */
10124 		blksize = rp->r_size - blkoff;
10125 	} else
10126 		blksize = bsize;
10127 	mutex_exit(&rp->r_statelock);
10128 
10129 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
10130 	    &io_off, &io_len, blkoff, blksize, 1);
10131 	/*
10132 	 * The isra flag passed to the kluster function is 1, we may have
10133 	 * gotten a return value of NULL for a variety of reasons (# of free
10134 	 * pages < minfree, someone entered the page on the vnode etc). In all
10135 	 * cases, we want to punt on the readahead.
10136 	 */
10137 	if (pp == NULL)
10138 		return;
10139 
10140 	/*
10141 	 * Now round the request size up to page boundaries.
10142 	 * This ensures that the entire page will be
10143 	 * initialized to zeroes if EOF is encountered.
10144 	 */
10145 	io_len = ptob(btopr(io_len));
10146 
10147 	bp = pageio_setup(pp, io_len, vp, B_READ);
10148 	ASSERT(bp != NULL);
10149 
10150 	/*
10151 	 * pageio_setup should have set b_addr to 0.  This is correct since
10152 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10153 	 * to calculate an offset, and then set b_addr to the kernel virtual
10154 	 * address it allocated for us.
10155 	 */
10156 	ASSERT(bp->b_un.b_addr == 0);
10157 
10158 	bp->b_edev = 0;
10159 	bp->b_dev = 0;
10160 	bp->b_lblkno = lbtodb(io_off);
10161 	bp->b_file = vp;
10162 	bp->b_offset = (offset_t)blkoff;
10163 	bp_mapin(bp);
10164 
10165 	/*
10166 	 * If doing a write beyond what we believe is EOF, don't bother trying
10167 	 * to read the pages from the server, we'll just zero the pages here.
10168 	 * We don't check that the rw flag is S_WRITE here because some
10169 	 * implementations may attempt a read access to the buffer before
10170 	 * copying data.
10171 	 */
10172 	mutex_enter(&rp->r_statelock);
10173 	if (io_off >= rp->r_size && seg == segkmap) {
10174 		mutex_exit(&rp->r_statelock);
10175 		bzero(bp->b_un.b_addr, io_len);
10176 		error = 0;
10177 	} else {
10178 		mutex_exit(&rp->r_statelock);
10179 		error = nfs4_bio(bp, NULL, cr, TRUE);
10180 		if (error == NFS_EOF)
10181 			error = 0;
10182 	}
10183 
10184 	/*
10185 	 * Unmap the buffer before freeing it.
10186 	 */
10187 	bp_mapout(bp);
10188 	pageio_done(bp);
10189 
10190 	savepp = pp;
10191 	do {
10192 		pp->p_fsdata = C_NOCOMMIT;
10193 	} while ((pp = pp->p_next) != savepp);
10194 
10195 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10196 
10197 	/*
10198 	 * In case of error set readahead offset
10199 	 * to the lowest offset.
10200 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10201 	 */
10202 	if (error && rp->r_nextr > io_off) {
10203 		mutex_enter(&rp->r_statelock);
10204 		if (rp->r_nextr > io_off)
10205 			rp->r_nextr = io_off;
10206 		mutex_exit(&rp->r_statelock);
10207 	}
10208 }
10209 
10210 /*
10211  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10212  * If len == 0, do from off to EOF.
10213  *
10214  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10215  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10216  * (from pageout).
10217  */
10218 /* ARGSUSED */
10219 static int
10220 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
10221     caller_context_t *ct)
10222 {
10223 	int error;
10224 	rnode4_t *rp;
10225 
10226 	ASSERT(cr != NULL);
10227 
10228 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10229 		return (EIO);
10230 
10231 	rp = VTOR4(vp);
10232 	if (IS_SHADOW(vp, rp))
10233 		vp = RTOV4(rp);
10234 
10235 	/*
10236 	 * XXX - Why should this check be made here?
10237 	 */
10238 	if (vp->v_flag & VNOMAP)
10239 		return (ENOSYS);
10240 
10241 	if (len == 0 && !(flags & B_INVAL) &&
10242 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10243 		return (0);
10244 
10245 	mutex_enter(&rp->r_statelock);
10246 	rp->r_count++;
10247 	mutex_exit(&rp->r_statelock);
10248 	error = nfs4_putpages(vp, off, len, flags, cr);
10249 	mutex_enter(&rp->r_statelock);
10250 	rp->r_count--;
10251 	cv_broadcast(&rp->r_cv);
10252 	mutex_exit(&rp->r_statelock);
10253 
10254 	return (error);
10255 }
10256 
10257 /*
10258  * Write out a single page, possibly klustering adjacent dirty pages.
10259  */
10260 int
10261 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10262     int flags, cred_t *cr)
10263 {
10264 	u_offset_t io_off;
10265 	u_offset_t lbn_off;
10266 	u_offset_t lbn;
10267 	size_t io_len;
10268 	uint_t bsize;
10269 	int error;
10270 	rnode4_t *rp;
10271 
10272 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10273 	ASSERT(pp != NULL);
10274 	ASSERT(cr != NULL);
10275 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10276 
10277 	rp = VTOR4(vp);
10278 	ASSERT(rp->r_count > 0);
10279 	ASSERT(!IS_SHADOW(vp, rp));
10280 
10281 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10282 	lbn = pp->p_offset / bsize;
10283 	lbn_off = lbn * bsize;
10284 
10285 	/*
10286 	 * Find a kluster that fits in one block, or in
10287 	 * one page if pages are bigger than blocks.  If
10288 	 * there is less file space allocated than a whole
10289 	 * page, we'll shorten the i/o request below.
10290 	 */
10291 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10292 	    roundup(bsize, PAGESIZE), flags);
10293 
10294 	/*
10295 	 * pvn_write_kluster shouldn't have returned a page with offset
10296 	 * behind the original page we were given.  Verify that.
10297 	 */
10298 	ASSERT((pp->p_offset / bsize) >= lbn);
10299 
10300 	/*
10301 	 * Now pp will have the list of kept dirty pages marked for
10302 	 * write back.  It will also handle invalidation and freeing
10303 	 * of pages that are not dirty.  Check for page length rounding
10304 	 * problems.
10305 	 */
10306 	if (io_off + io_len > lbn_off + bsize) {
10307 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10308 		io_len = lbn_off + bsize - io_off;
10309 	}
10310 	/*
10311 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10312 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10313 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10314 	 * progress and the r_size has not been made consistent with the
10315 	 * new size of the file. When the uiomove() completes the r_size is
10316 	 * updated and the R4MODINPROGRESS flag is cleared.
10317 	 *
10318 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10319 	 * consistent value of r_size. Without this handshaking, it is
10320 	 * possible that nfs4_bio() picks  up the old value of r_size
10321 	 * before the uiomove() in writerp4() completes. This will result
10322 	 * in the write through nfs4_bio() being dropped.
10323 	 *
10324 	 * More precisely, there is a window between the time the uiomove()
10325 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10326 	 * operation intervenes in this window, the page will be picked up,
10327 	 * because it is dirty (it will be unlocked, unless it was
10328 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10329 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10330 	 * checked. This will still be the old size. Therefore the page will
10331 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10332 	 * the page will be found to be clean and the write will be dropped.
10333 	 */
10334 	if (rp->r_flags & R4MODINPROGRESS) {
10335 		mutex_enter(&rp->r_statelock);
10336 		if ((rp->r_flags & R4MODINPROGRESS) &&
10337 		    rp->r_modaddr + MAXBSIZE > io_off &&
10338 		    rp->r_modaddr < io_off + io_len) {
10339 			page_t *plist;
10340 			/*
10341 			 * A write is in progress for this region of the file.
10342 			 * If we did not detect R4MODINPROGRESS here then this
10343 			 * path through nfs_putapage() would eventually go to
10344 			 * nfs4_bio() and may not write out all of the data
10345 			 * in the pages. We end up losing data. So we decide
10346 			 * to set the modified bit on each page in the page
10347 			 * list and mark the rnode with R4DIRTY. This write
10348 			 * will be restarted at some later time.
10349 			 */
10350 			plist = pp;
10351 			while (plist != NULL) {
10352 				pp = plist;
10353 				page_sub(&plist, pp);
10354 				hat_setmod(pp);
10355 				page_io_unlock(pp);
10356 				page_unlock(pp);
10357 			}
10358 			rp->r_flags |= R4DIRTY;
10359 			mutex_exit(&rp->r_statelock);
10360 			if (offp)
10361 				*offp = io_off;
10362 			if (lenp)
10363 				*lenp = io_len;
10364 			return (0);
10365 		}
10366 		mutex_exit(&rp->r_statelock);
10367 	}
10368 
10369 	if (flags & B_ASYNC) {
10370 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10371 		    nfs4_sync_putapage);
10372 	} else
10373 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10374 
10375 	if (offp)
10376 		*offp = io_off;
10377 	if (lenp)
10378 		*lenp = io_len;
10379 	return (error);
10380 }
10381 
10382 static int
10383 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10384     int flags, cred_t *cr)
10385 {
10386 	int error;
10387 	rnode4_t *rp;
10388 
10389 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10390 
10391 	flags |= B_WRITE;
10392 
10393 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10394 
10395 	rp = VTOR4(vp);
10396 
10397 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10398 	    error == EACCES) &&
10399 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10400 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10401 			mutex_enter(&rp->r_statelock);
10402 			rp->r_flags |= R4OUTOFSPACE;
10403 			mutex_exit(&rp->r_statelock);
10404 		}
10405 		flags |= B_ERROR;
10406 		pvn_write_done(pp, flags);
10407 		/*
10408 		 * If this was not an async thread, then try again to
10409 		 * write out the pages, but this time, also destroy
10410 		 * them whether or not the write is successful.  This
10411 		 * will prevent memory from filling up with these
10412 		 * pages and destroying them is the only alternative
10413 		 * if they can't be written out.
10414 		 *
10415 		 * Don't do this if this is an async thread because
10416 		 * when the pages are unlocked in pvn_write_done,
10417 		 * some other thread could have come along, locked
10418 		 * them, and queued for an async thread.  It would be
10419 		 * possible for all of the async threads to be tied
10420 		 * up waiting to lock the pages again and they would
10421 		 * all already be locked and waiting for an async
10422 		 * thread to handle them.  Deadlock.
10423 		 */
10424 		if (!(flags & B_ASYNC)) {
10425 			error = nfs4_putpage(vp, io_off, io_len,
10426 			    B_INVAL | B_FORCE, cr, NULL);
10427 		}
10428 	} else {
10429 		if (error)
10430 			flags |= B_ERROR;
10431 		else if (rp->r_flags & R4OUTOFSPACE) {
10432 			mutex_enter(&rp->r_statelock);
10433 			rp->r_flags &= ~R4OUTOFSPACE;
10434 			mutex_exit(&rp->r_statelock);
10435 		}
10436 		pvn_write_done(pp, flags);
10437 		if (freemem < desfree)
10438 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10439 			    NFS4_WRITE_NOWAIT);
10440 	}
10441 
10442 	return (error);
10443 }
10444 
10445 #ifdef DEBUG
10446 int nfs4_force_open_before_mmap = 0;
10447 #endif
10448 
10449 /* ARGSUSED */
10450 static int
10451 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10452     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10453     caller_context_t *ct)
10454 {
10455 	struct segvn_crargs vn_a;
10456 	int error = 0;
10457 	rnode4_t *rp = VTOR4(vp);
10458 	mntinfo4_t *mi = VTOMI4(vp);
10459 
10460 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10461 		return (EIO);
10462 
10463 	if (vp->v_flag & VNOMAP)
10464 		return (ENOSYS);
10465 
10466 	if (off < 0 || (off + len) < 0)
10467 		return (ENXIO);
10468 
10469 	if (vp->v_type != VREG)
10470 		return (ENODEV);
10471 
10472 	/*
10473 	 * If the file is delegated to the client don't do anything.
10474 	 * If the file is not delegated, then validate the data cache.
10475 	 */
10476 	mutex_enter(&rp->r_statev4_lock);
10477 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10478 		mutex_exit(&rp->r_statev4_lock);
10479 		error = nfs4_validate_caches(vp, cr);
10480 		if (error)
10481 			return (error);
10482 	} else {
10483 		mutex_exit(&rp->r_statev4_lock);
10484 	}
10485 
10486 	/*
10487 	 * Check to see if the vnode is currently marked as not cachable.
10488 	 * This means portions of the file are locked (through VOP_FRLOCK).
10489 	 * In this case the map request must be refused.  We use
10490 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10491 	 *
10492 	 * Atomically increment r_inmap after acquiring r_rwlock. The
10493 	 * idea here is to acquire r_rwlock to block read/write and
10494 	 * not to protect r_inmap. r_inmap will inform nfs4_read/write()
10495 	 * that we are in nfs4_map(). Now, r_rwlock is acquired in order
10496 	 * and we can prevent the deadlock that would have occurred
10497 	 * when nfs4_addmap() would have acquired it out of order.
10498 	 *
10499 	 * Since we are not protecting r_inmap by any lock, we do not
10500 	 * hold any lock when we decrement it. We atomically decrement
10501 	 * r_inmap after we release r_lkserlock.
10502 	 */
10503 
10504 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR4(vp)))
10505 		return (EINTR);
10506 	atomic_inc_uint(&rp->r_inmap);
10507 	nfs_rw_exit(&rp->r_rwlock);
10508 
10509 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp))) {
10510 		atomic_dec_uint(&rp->r_inmap);
10511 		return (EINTR);
10512 	}
10513 
10514 
10515 	if (vp->v_flag & VNOCACHE) {
10516 		error = EAGAIN;
10517 		goto done;
10518 	}
10519 
10520 	/*
10521 	 * Don't allow concurrent locks and mapping if mandatory locking is
10522 	 * enabled.
10523 	 */
10524 	if (flk_has_remote_locks(vp)) {
10525 		struct vattr va;
10526 		va.va_mask = AT_MODE;
10527 		error = nfs4getattr(vp, &va, cr);
10528 		if (error != 0)
10529 			goto done;
10530 		if (MANDLOCK(vp, va.va_mode)) {
10531 			error = EAGAIN;
10532 			goto done;
10533 		}
10534 	}
10535 
10536 	/*
10537 	 * It is possible that the rnode has a lost lock request that we
10538 	 * are still trying to recover, and that the request conflicts with
10539 	 * this map request.
10540 	 *
10541 	 * An alternative approach would be for nfs4_safemap() to consider
10542 	 * queued lock requests when deciding whether to set or clear
10543 	 * VNOCACHE.  This would require the frlock code path to call
10544 	 * nfs4_safemap() after enqueing a lost request.
10545 	 */
10546 	if (nfs4_map_lost_lock_conflict(vp)) {
10547 		error = EAGAIN;
10548 		goto done;
10549 	}
10550 
10551 	as_rangelock(as);
10552 	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
10553 	if (error != 0) {
10554 		as_rangeunlock(as);
10555 		goto done;
10556 	}
10557 
10558 	if (vp->v_type == VREG) {
10559 		/*
10560 		 * We need to retrieve the open stream
10561 		 */
10562 		nfs4_open_stream_t	*osp = NULL;
10563 		nfs4_open_owner_t	*oop = NULL;
10564 
10565 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10566 		if (oop != NULL) {
10567 			/* returns with 'os_sync_lock' held */
10568 			osp = find_open_stream(oop, rp);
10569 			open_owner_rele(oop);
10570 		}
10571 		if (osp == NULL) {
10572 #ifdef DEBUG
10573 			if (nfs4_force_open_before_mmap) {
10574 				error = EIO;
10575 				goto done;
10576 			}
10577 #endif
10578 			/* returns with 'os_sync_lock' held */
10579 			error = open_and_get_osp(vp, cr, &osp);
10580 			if (osp == NULL) {
10581 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10582 				    "nfs4_map: we tried to OPEN the file "
10583 				    "but again no osp, so fail with EIO"));
10584 				goto done;
10585 			}
10586 		}
10587 
10588 		if (osp->os_failed_reopen) {
10589 			mutex_exit(&osp->os_sync_lock);
10590 			open_stream_rele(osp, rp);
10591 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10592 			    "nfs4_map: os_failed_reopen set on "
10593 			    "osp %p, cr %p, rp %s", (void *)osp,
10594 			    (void *)cr, rnode4info(rp)));
10595 			error = EIO;
10596 			goto done;
10597 		}
10598 		mutex_exit(&osp->os_sync_lock);
10599 		open_stream_rele(osp, rp);
10600 	}
10601 
10602 	vn_a.vp = vp;
10603 	vn_a.offset = off;
10604 	vn_a.type = (flags & MAP_TYPE);
10605 	vn_a.prot = (uchar_t)prot;
10606 	vn_a.maxprot = (uchar_t)maxprot;
10607 	vn_a.flags = (flags & ~MAP_TYPE);
10608 	vn_a.cred = cr;
10609 	vn_a.amp = NULL;
10610 	vn_a.szc = 0;
10611 	vn_a.lgrp_mem_policy_flags = 0;
10612 
10613 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10614 	as_rangeunlock(as);
10615 
10616 done:
10617 	nfs_rw_exit(&rp->r_lkserlock);
10618 	atomic_dec_uint(&rp->r_inmap);
10619 	return (error);
10620 }
10621 
10622 /*
10623  * We're most likely dealing with a kernel module that likes to READ
10624  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10625  * officially OPEN the file to create the necessary client state
10626  * for bookkeeping of os_mmap_read/write counts.
10627  *
10628  * Since VOP_MAP only passes in a pointer to the vnode rather than
10629  * a double pointer, we can't handle the case where nfs4open_otw()
10630  * returns a different vnode than the one passed into VOP_MAP (since
10631  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10632  * we return NULL and let nfs4_map() fail.  Note: the only case where
10633  * this should happen is if the file got removed and replaced with the
10634  * same name on the server (in addition to the fact that we're trying
10635  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10636  */
10637 static int
10638 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10639 {
10640 	rnode4_t		*rp, *drp;
10641 	vnode_t			*dvp, *open_vp;
10642 	char			file_name[MAXNAMELEN];
10643 	int			just_created;
10644 	nfs4_open_stream_t	*osp;
10645 	nfs4_open_owner_t	*oop;
10646 	int			error;
10647 
10648 	*ospp = NULL;
10649 	open_vp = map_vp;
10650 
10651 	rp = VTOR4(open_vp);
10652 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10653 		return (error);
10654 	drp = VTOR4(dvp);
10655 
10656 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10657 		VN_RELE(dvp);
10658 		return (EINTR);
10659 	}
10660 
10661 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10662 		nfs_rw_exit(&drp->r_rwlock);
10663 		VN_RELE(dvp);
10664 		return (error);
10665 	}
10666 
10667 	mutex_enter(&rp->r_statev4_lock);
10668 	if (rp->created_v4) {
10669 		rp->created_v4 = 0;
10670 		mutex_exit(&rp->r_statev4_lock);
10671 
10672 		dnlc_update(dvp, file_name, open_vp);
10673 		/* This is needed so we don't bump the open ref count */
10674 		just_created = 1;
10675 	} else {
10676 		mutex_exit(&rp->r_statev4_lock);
10677 		just_created = 0;
10678 	}
10679 
10680 	VN_HOLD(map_vp);
10681 
10682 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10683 	    just_created);
10684 	if (error) {
10685 		nfs_rw_exit(&drp->r_rwlock);
10686 		VN_RELE(dvp);
10687 		VN_RELE(map_vp);
10688 		return (error);
10689 	}
10690 
10691 	nfs_rw_exit(&drp->r_rwlock);
10692 	VN_RELE(dvp);
10693 
10694 	/*
10695 	 * If nfs4open_otw() returned a different vnode then "undo"
10696 	 * the open and return failure to the caller.
10697 	 */
10698 	if (!VN_CMP(open_vp, map_vp)) {
10699 		nfs4_error_t e;
10700 
10701 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10702 		    "open returned a different vnode"));
10703 		/*
10704 		 * If there's an error, ignore it,
10705 		 * and let VOP_INACTIVE handle it.
10706 		 */
10707 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10708 		    CLOSE_NORM, 0, 0, 0);
10709 		VN_RELE(map_vp);
10710 		return (EIO);
10711 	}
10712 
10713 	VN_RELE(map_vp);
10714 
10715 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10716 	if (!oop) {
10717 		nfs4_error_t e;
10718 
10719 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10720 		    "no open owner"));
10721 		/*
10722 		 * If there's an error, ignore it,
10723 		 * and let VOP_INACTIVE handle it.
10724 		 */
10725 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10726 		    CLOSE_NORM, 0, 0, 0);
10727 		return (EIO);
10728 	}
10729 	osp = find_open_stream(oop, rp);
10730 	open_owner_rele(oop);
10731 	*ospp = osp;
10732 	return (0);
10733 }
10734 
10735 /*
10736  * Please be aware that when this function is called, the address space write
10737  * a_lock is held.  Do not put over the wire calls in this function.
10738  */
10739 /* ARGSUSED */
10740 static int
10741 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10742     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10743     caller_context_t *ct)
10744 {
10745 	rnode4_t		*rp;
10746 	int			error = 0;
10747 	mntinfo4_t		*mi;
10748 
10749 	mi = VTOMI4(vp);
10750 	rp = VTOR4(vp);
10751 
10752 	if (nfs_zone() != mi->mi_zone)
10753 		return (EIO);
10754 	if (vp->v_flag & VNOMAP)
10755 		return (ENOSYS);
10756 
10757 	/*
10758 	 * Don't need to update the open stream first, since this
10759 	 * mmap can't add any additional share access that isn't
10760 	 * already contained in the open stream (for the case where we
10761 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10762 	 * take into account os_mmap_read[write] counts).
10763 	 */
10764 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10765 
10766 	if (vp->v_type == VREG) {
10767 		/*
10768 		 * We need to retrieve the open stream and update the counts.
10769 		 * If there is no open stream here, something is wrong.
10770 		 */
10771 		nfs4_open_stream_t	*osp = NULL;
10772 		nfs4_open_owner_t	*oop = NULL;
10773 
10774 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10775 		if (oop != NULL) {
10776 			/* returns with 'os_sync_lock' held */
10777 			osp = find_open_stream(oop, rp);
10778 			open_owner_rele(oop);
10779 		}
10780 		if (osp == NULL) {
10781 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10782 			    "nfs4_addmap: we should have an osp"
10783 			    "but we don't, so fail with EIO"));
10784 			error = EIO;
10785 			goto out;
10786 		}
10787 
10788 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10789 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10790 
10791 		/*
10792 		 * Update the map count in the open stream.
10793 		 * This is necessary in the case where we
10794 		 * open/mmap/close/, then the server reboots, and we
10795 		 * attempt to reopen.  If the mmap doesn't add share
10796 		 * access then we send an invalid reopen with
10797 		 * access = NONE.
10798 		 *
10799 		 * We need to specifically check each PROT_* so a mmap
10800 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10801 		 * read and write access.  A simple comparison of prot
10802 		 * to ~PROT_WRITE to determine read access is insufficient
10803 		 * since prot can be |= with PROT_USER, etc.
10804 		 */
10805 
10806 		/*
10807 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10808 		 */
10809 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10810 			osp->os_mmap_write += btopr(len);
10811 		if (maxprot & PROT_READ)
10812 			osp->os_mmap_read += btopr(len);
10813 		if (maxprot & PROT_EXEC)
10814 			osp->os_mmap_read += btopr(len);
10815 		/*
10816 		 * Ensure that os_mmap_read gets incremented, even if
10817 		 * maxprot were to look like PROT_NONE.
10818 		 */
10819 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10820 		    !(maxprot & PROT_EXEC))
10821 			osp->os_mmap_read += btopr(len);
10822 		osp->os_mapcnt += btopr(len);
10823 		mutex_exit(&osp->os_sync_lock);
10824 		open_stream_rele(osp, rp);
10825 	}
10826 
10827 out:
10828 	/*
10829 	 * If we got an error, then undo our
10830 	 * incrementing of 'r_mapcnt'.
10831 	 */
10832 
10833 	if (error) {
10834 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10835 		ASSERT(rp->r_mapcnt >= 0);
10836 	}
10837 	return (error);
10838 }
10839 
10840 /* ARGSUSED */
10841 static int
10842 nfs4_cmp(vnode_t *vp1, vnode_t *vp2, caller_context_t *ct)
10843 {
10844 
10845 	return (VTOR4(vp1) == VTOR4(vp2));
10846 }
10847 
10848 /*
10849  * Data structure for nfs4_lkserlock_callback() function.
10850  */
10851 struct nfs4_lkserlock_callback_data {
10852 	vnode_t *vp;
10853 	int rc;
10854 };
10855 
10856 /*
10857  * Callback function for reclock().
10858  */
10859 static callb_cpr_t *
10860 nfs4_lkserlock_callback(flk_cb_when_t when, void *infop)
10861 {
10862 	struct nfs4_lkserlock_callback_data *dp =
10863 	    (struct nfs4_lkserlock_callback_data *)infop;
10864 	rnode4_t *rp = VTOR4(dp->vp);
10865 
10866 	if (when == FLK_BEFORE_SLEEP)
10867 		nfs_rw_exit(&rp->r_lkserlock);
10868 	else
10869 		dp->rc = nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER,
10870 		    INTR4(dp->vp));
10871 
10872 	return (NULL);
10873 }
10874 
10875 /* ARGSUSED */
10876 static int
10877 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10878     offset_t offset, struct flk_callback *flk_cbp, cred_t *cr,
10879     caller_context_t *ct)
10880 {
10881 	int rc = 0;
10882 	rnode4_t *rp;
10883 	int intr = INTR4(vp);
10884 	nfs4_error_t e;
10885 	int frcmd;
10886 	struct lm_sysid	*ls = NULL;
10887 
10888 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10889 		return (EIO);
10890 
10891 	/* check for valid cmd parameter and set frcmd appropriately */
10892 	switch (cmd) {
10893 	case F_GETLK:
10894 		frcmd = 0;
10895 		break;
10896 	case F_SETLK:
10897 		frcmd = SETFLCK;
10898 		break;
10899 	case F_SETLKW:
10900 		frcmd = SETFLCK | SLPFLCK;
10901 		break;
10902 	default:
10903 		return (EINVAL);
10904 	}
10905 
10906 	/*
10907 	 * If lock is relative to EOF, we need the newest length of the file.
10908 	 * Therefore invalidate the ATTR_CACHE.
10909 	 */
10910 	if (bfp->l_whence == 2)		/* SEEK_END */
10911 		PURGE_ATTRCACHE4(vp);
10912 
10913 	/*
10914 	 * If the filesystem is mounted using local locking, pass the
10915 	 * request off to the local locking code.
10916 	 */
10917 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10918 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10919 			/*
10920 			 * For complete safety, we should be holding
10921 			 * r_lkserlock.  However, we can't call
10922 			 * nfs4_safelock and then fs_frlock while
10923 			 * holding r_lkserlock, so just invoke
10924 			 * nfs4_safelock and expect that this will
10925 			 * catch enough of the cases.
10926 			 */
10927 			if (!nfs4_safelock(vp, bfp, cr))
10928 				return (EAGAIN);
10929 		}
10930 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
10931 	}
10932 
10933 	/*
10934 	 * Convert the offset.  We need to do this to make sure our view of the
10935 	 * locking range is always the same through the rest of this function.
10936 	 * This is especially needed for bfp->l_whence == SEEK_END, because the
10937 	 * length of the file could change anytime and thus the locking range
10938 	 * would be a moving target for us.
10939 	 *
10940 	 * For the bfp->l_whence == SEEK_CUR case this is just a convenient
10941 	 * conversion to make the life easier for nfs4frlock().
10942 	 */
10943 	rc = convoff(vp, bfp, 0, offset);
10944 	if (rc != 0)
10945 		return (rc);
10946 
10947 	if (bfp->l_type == F_UNLCK) {
10948 		u_offset_t start, end;
10949 
10950 		/*
10951 		 * Shortcut for trivial case.
10952 		 */
10953 		if (cmd == F_GETLK)
10954 			return (rc);
10955 
10956 		/*
10957 		 * For every lock or unlock request we need to do two steps:
10958 		 * (un)register the local lock, and (un)register the lock at
10959 		 * the NFSv4 server.  It is essential to make sure the lock
10960 		 * status registered at the server and registered locally is
10961 		 * same and never goes out of sync.  This means that if one
10962 		 * step fails, the other one needs to be either skipped, or
10963 		 * reverted.
10964 		 *
10965 		 * For lock requests the situation is easy since a lock
10966 		 * registration can be reverted without any risk of data
10967 		 * corruption.
10968 		 *
10969 		 * The unlock requests cannot be reverted because once a lock
10970 		 * is unregistered the race window is open and some other
10971 		 * process could grab a conflicting lock.  This means that once
10972 		 * the first step (the first lock unregistration) succeeded,
10973 		 * the second step cannot fail.  The second step for the unlock
10974 		 * request is the local lock unregistration by the reclock()
10975 		 * call.
10976 		 *
10977 		 * The only way how the reclock() call for an unlock request
10978 		 * could fail is the invalid unlock range so we check it here,
10979 		 * before the lock is unregistered at NFSv4 server.  This
10980 		 * duplicates the check done in the reclock() function.
10981 		 */
10982 		rc = flk_convert_lock_data(vp, bfp, &start, &end, offset);
10983 		if (rc != 0)
10984 			return (rc);
10985 		rc = flk_check_lock_data(start, end, MAXEND);
10986 		if (rc != 0)
10987 			return (rc);
10988 
10989 		intr = 0;
10990 	}
10991 
10992 	/*
10993 	 * For F_SETLK and F_SETLKW we need to set sysid.
10994 	 */
10995 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10996 		rc = nfs4frlock_get_sysid(&ls, vp, bfp);
10997 		if (rc != 0)
10998 			return (rc);
10999 
11000 		/*
11001 		 * Client locks are registerred locally by oring the sysid with
11002 		 * LM_SYSID_CLIENT.  The server registers locks locally using
11003 		 * just the sysid.  We need to distinguish between the two to
11004 		 * avoid collision in a case one machine is used as both client
11005 		 * and server.
11006 		 */
11007 		bfp->l_sysid |= LM_SYSID_CLIENT;
11008 	}
11009 
11010 	bfp->l_pid = curproc->p_pid;
11011 
11012 	rp = VTOR4(vp);
11013 
11014 	/*
11015 	 * Check whether the given lock request can proceed, given the
11016 	 * current file mappings.
11017 	 */
11018 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr)) {
11019 		if (ls != NULL)
11020 			lm_rel_sysid(ls);
11021 		return (EINTR);
11022 	}
11023 	if (cmd == F_SETLK || cmd == F_SETLKW) {
11024 		if (!nfs4_safelock(vp, bfp, cr)) {
11025 			rc = EAGAIN;
11026 			goto done;
11027 		}
11028 	}
11029 
11030 	/*
11031 	 * For query we will try to find a conflicting local lock first by
11032 	 * calling reclock().
11033 	 *
11034 	 * In a case this is a lock request we need to register it locally
11035 	 * first before we consult the NFSv4 server.
11036 	 */
11037 	if (cmd == F_GETLK || bfp->l_type != F_UNLCK) {
11038 		/*
11039 		 * If we might sleep in reclock() we need to register a
11040 		 * callback to release the r_lkserlock during the sleep.
11041 		 */
11042 		if ((frcmd & SLPFLCK) == 0) {
11043 			rc = reclock(vp, bfp, frcmd, flag, 0, flk_cbp);
11044 		} else {
11045 			flk_callback_t callback;
11046 			struct nfs4_lkserlock_callback_data callback_data =
11047 			    {vp, 0};
11048 
11049 			flk_add_callback(&callback, nfs4_lkserlock_callback,
11050 			    &callback_data, flk_cbp);
11051 			rc = reclock(vp, bfp, frcmd, flag, 0, &callback);
11052 			flk_del_callback(&callback);
11053 
11054 			if (callback_data.rc != 0) {
11055 				/*
11056 				 * The nfs_rw_enter_sig() call in
11057 				 * nfs4_lkserlock_callback() failed.
11058 				 */
11059 
11060 				if (rc == 0) {
11061 					/*
11062 					 * The reclock() call above succeeded
11063 					 * so we need to revert it.
11064 					 */
11065 					bfp->l_type = F_UNLCK;
11066 					rc = reclock(vp, bfp, frcmd, flag, 0,
11067 					    flk_cbp);
11068 					/* The unlock cannot fail */
11069 					ASSERT(rc == 0);
11070 
11071 					/*
11072 					 * We are here because we failed to
11073 					 * acquire r_lkserlock in
11074 					 * nfs4_lkserlock_callback() due to a
11075 					 * signal.  Return the appropriate
11076 					 * error.
11077 					 */
11078 					rc = EINTR;
11079 				}
11080 
11081 				ASSERT(ls != NULL);
11082 				lm_rel_sysid(ls);
11083 
11084 				return (rc);
11085 			}
11086 
11087 			/*
11088 			 * We possibly released r_lkserlock in reclock() so
11089 			 * make sure it is still safe to lock the file.
11090 			 */
11091 			if (!nfs4_safelock(vp, bfp, cr)) {
11092 				rc = EAGAIN;
11093 				goto revert;
11094 			}
11095 
11096 		}
11097 
11098 		/*
11099 		 * If the reclock() call failed we are done and we will return
11100 		 * an error to the caller.  Similarly, if we found a
11101 		 * conflicting lock registered locally we are done too.  We do
11102 		 * not need to consult the server.
11103 		 */
11104 		if ((rc != 0) || (cmd == F_GETLK && bfp->l_type != F_UNLCK))
11105 			goto done;
11106 	}
11107 
11108 	/*
11109 	 * Flush the cache after waiting for async I/O to finish.  For new
11110 	 * locks, this is so that the process gets the latest bits from the
11111 	 * server.  For unlocks, this is so that other clients see the
11112 	 * latest bits once the file has been unlocked.  If currently dirty
11113 	 * pages can't be flushed, then don't allow a lock to be set.  But
11114 	 * allow unlocks to succeed, to avoid having orphan locks on the
11115 	 * server.
11116 	 */
11117 	if (cmd != F_GETLK) {
11118 		mutex_enter(&rp->r_statelock);
11119 		while (rp->r_count > 0) {
11120 			if (intr) {
11121 				klwp_t *lwp = ttolwp(curthread);
11122 
11123 				if (lwp != NULL)
11124 					lwp->lwp_nostop++;
11125 				if (cv_wait_sig(&rp->r_cv,
11126 				    &rp->r_statelock) == 0) {
11127 					if (lwp != NULL)
11128 						lwp->lwp_nostop--;
11129 					rc = EINTR;
11130 					break;
11131 				}
11132 				if (lwp != NULL)
11133 					lwp->lwp_nostop--;
11134 				} else
11135 					cv_wait(&rp->r_cv, &rp->r_statelock);
11136 		}
11137 		mutex_exit(&rp->r_statelock);
11138 		if (rc != 0) {
11139 			ASSERT(bfp->l_type != F_UNLCK);
11140 
11141 			goto revert;
11142 		}
11143 
11144 		rc = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr, ct);
11145 		if (rc != 0) {
11146 			if (rc == ENOSPC || rc == EDQUOT) {
11147 				mutex_enter(&rp->r_statelock);
11148 				if (!rp->r_error)
11149 					rp->r_error = rc;
11150 				mutex_exit(&rp->r_statelock);
11151 			}
11152 
11153 			/*
11154 			 * If this was a lock request, make sure it is
11155 			 * reverted.
11156 			 */
11157 			if (bfp->l_type != F_UNLCK) {
11158 				rc = ENOLCK;
11159 				goto revert;
11160 			}
11161 		}
11162 	}
11163 
11164 	/*
11165 	 * Call the lock manager to do the real work of contacting
11166 	 * the server and obtaining the lock.
11167 	 */
11168 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, cr, &e, NULL, NULL);
11169 	rc = e.error;
11170 
11171 	if (rc == 0)
11172 		nfs4_lockcompletion(vp, cmd);
11173 
11174 revert:
11175 	/*
11176 	 * If this is either successful unlock request or a lock request that
11177 	 * failed we should unregister/revert the local lock now.
11178 	 */
11179 	if ((rc == 0 && cmd != F_GETLK && bfp->l_type == F_UNLCK) ||
11180 	    (rc != 0 && cmd != F_GETLK && bfp->l_type != F_UNLCK)) {
11181 		int r;
11182 
11183 		bfp->l_type = F_UNLCK;
11184 		r = reclock(vp, bfp, frcmd, flag, 0, flk_cbp);
11185 		/* The unlock cannot fail */
11186 		ASSERT(r == 0);
11187 	}
11188 
11189 done:
11190 	nfs_rw_exit(&rp->r_lkserlock);
11191 	if (ls != NULL)
11192 		lm_rel_sysid(ls);
11193 
11194 	return (rc);
11195 }
11196 
11197 /*
11198  * Free storage space associated with the specified vnode.  The portion
11199  * to be freed is specified by bfp->l_start and bfp->l_len (already
11200  * normalized to a "whence" of 0).
11201  *
11202  * This is an experimental facility whose continued existence is not
11203  * guaranteed.  Currently, we only support the special case
11204  * of l_len == 0, meaning free to end of file.
11205  */
11206 /* ARGSUSED */
11207 static int
11208 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
11209     offset_t offset, cred_t *cr, caller_context_t *ct)
11210 {
11211 	int error;
11212 
11213 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11214 		return (EIO);
11215 	ASSERT(vp->v_type == VREG);
11216 	if (cmd != F_FREESP)
11217 		return (EINVAL);
11218 
11219 	error = convoff(vp, bfp, 0, offset);
11220 	if (!error) {
11221 		ASSERT(bfp->l_start >= 0);
11222 		if (bfp->l_len == 0) {
11223 			struct vattr va;
11224 
11225 			va.va_mask = AT_SIZE;
11226 			va.va_size = bfp->l_start;
11227 			error = nfs4setattr(vp, &va, 0, cr, NULL);
11228 
11229 			if (error == 0 && bfp->l_start == 0)
11230 				vnevent_truncate(vp, ct);
11231 		} else
11232 			error = EINVAL;
11233 	}
11234 
11235 	return (error);
11236 }
11237 
11238 /* ARGSUSED */
11239 int
11240 nfs4_realvp(vnode_t *vp, vnode_t **vpp, caller_context_t *ct)
11241 {
11242 	rnode4_t *rp;
11243 	rp = VTOR4(vp);
11244 
11245 	if (vp->v_type == VREG && IS_SHADOW(vp, rp)) {
11246 		vp = RTOV4(rp);
11247 	}
11248 	*vpp = vp;
11249 	return (0);
11250 }
11251 
11252 /*
11253  * Setup and add an address space callback to do the work of the delmap call.
11254  * The callback will (and must be) deleted in the actual callback function.
11255  *
11256  * This is done in order to take care of the problem that we have with holding
11257  * the address space's a_lock for a long period of time (e.g. if the NFS server
11258  * is down).  Callbacks will be executed in the address space code while the
11259  * a_lock is not held.  Holding the address space's a_lock causes things such
11260  * as ps and fork to hang because they are trying to acquire this lock as well.
11261  */
11262 /* ARGSUSED */
11263 static int
11264 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
11265     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
11266     caller_context_t *ct)
11267 {
11268 	int			caller_found;
11269 	int			error;
11270 	rnode4_t		*rp;
11271 	nfs4_delmap_args_t	*dmapp;
11272 	nfs4_delmapcall_t	*delmap_call;
11273 
11274 	if (vp->v_flag & VNOMAP)
11275 		return (ENOSYS);
11276 
11277 	/*
11278 	 * A process may not change zones if it has NFS pages mmap'ed
11279 	 * in, so we can't legitimately get here from the wrong zone.
11280 	 */
11281 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11282 
11283 	rp = VTOR4(vp);
11284 
11285 	/*
11286 	 * The way that the address space of this process deletes its mapping
11287 	 * of this file is via the following call chains:
11288 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11289 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11290 	 *
11291 	 * With the use of address space callbacks we are allowed to drop the
11292 	 * address space lock, a_lock, while executing the NFS operations that
11293 	 * need to go over the wire.  Returning EAGAIN to the caller of this
11294 	 * function is what drives the execution of the callback that we add
11295 	 * below.  The callback will be executed by the address space code
11296 	 * after dropping the a_lock.  When the callback is finished, since
11297 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
11298 	 * is called again on the same segment to finish the rest of the work
11299 	 * that needs to happen during unmapping.
11300 	 *
11301 	 * This action of calling back into the segment driver causes
11302 	 * nfs4_delmap() to get called again, but since the callback was
11303 	 * already executed at this point, it already did the work and there
11304 	 * is nothing left for us to do.
11305 	 *
11306 	 * To Summarize:
11307 	 * - The first time nfs4_delmap is called by the current thread is when
11308 	 * we add the caller associated with this delmap to the delmap caller
11309 	 * list, add the callback, and return EAGAIN.
11310 	 * - The second time in this call chain when nfs4_delmap is called we
11311 	 * will find this caller in the delmap caller list and realize there
11312 	 * is no more work to do thus removing this caller from the list and
11313 	 * returning the error that was set in the callback execution.
11314 	 */
11315 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
11316 	if (caller_found) {
11317 		/*
11318 		 * 'error' is from the actual delmap operations.  To avoid
11319 		 * hangs, we need to handle the return of EAGAIN differently
11320 		 * since this is what drives the callback execution.
11321 		 * In this case, we don't want to return EAGAIN and do the
11322 		 * callback execution because there are none to execute.
11323 		 */
11324 		if (error == EAGAIN)
11325 			return (0);
11326 		else
11327 			return (error);
11328 	}
11329 
11330 	/* current caller was not in the list */
11331 	delmap_call = nfs4_init_delmapcall();
11332 
11333 	mutex_enter(&rp->r_statelock);
11334 	list_insert_tail(&rp->r_indelmap, delmap_call);
11335 	mutex_exit(&rp->r_statelock);
11336 
11337 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
11338 
11339 	dmapp->vp = vp;
11340 	dmapp->off = off;
11341 	dmapp->addr = addr;
11342 	dmapp->len = len;
11343 	dmapp->prot = prot;
11344 	dmapp->maxprot = maxprot;
11345 	dmapp->flags = flags;
11346 	dmapp->cr = cr;
11347 	dmapp->caller = delmap_call;
11348 
11349 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
11350 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
11351 
11352 	return (error ? error : EAGAIN);
11353 }
11354 
11355 static nfs4_delmapcall_t *
11356 nfs4_init_delmapcall()
11357 {
11358 	nfs4_delmapcall_t	*delmap_call;
11359 
11360 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
11361 	delmap_call->call_id = curthread;
11362 	delmap_call->error = 0;
11363 
11364 	return (delmap_call);
11365 }
11366 
11367 static void
11368 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11369 {
11370 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11371 }
11372 
11373 /*
11374  * Searches for the current delmap caller (based on curthread) in the list of
11375  * callers.  If it is found, we remove it and free the delmap caller.
11376  * Returns:
11377  *      0 if the caller wasn't found
11378  *      1 if the caller was found, removed and freed.  *errp will be set
11379  *	to what the result of the delmap was.
11380  */
11381 static int
11382 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11383 {
11384 	nfs4_delmapcall_t	*delmap_call;
11385 
11386 	/*
11387 	 * If the list doesn't exist yet, we create it and return
11388 	 * that the caller wasn't found.  No list = no callers.
11389 	 */
11390 	mutex_enter(&rp->r_statelock);
11391 	if (!(rp->r_flags & R4DELMAPLIST)) {
11392 		/* The list does not exist */
11393 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11394 		    offsetof(nfs4_delmapcall_t, call_node));
11395 		rp->r_flags |= R4DELMAPLIST;
11396 		mutex_exit(&rp->r_statelock);
11397 		return (0);
11398 	} else {
11399 		/* The list exists so search it */
11400 		for (delmap_call = list_head(&rp->r_indelmap);
11401 		    delmap_call != NULL;
11402 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11403 			if (delmap_call->call_id == curthread) {
11404 				/* current caller is in the list */
11405 				*errp = delmap_call->error;
11406 				list_remove(&rp->r_indelmap, delmap_call);
11407 				mutex_exit(&rp->r_statelock);
11408 				nfs4_free_delmapcall(delmap_call);
11409 				return (1);
11410 			}
11411 		}
11412 	}
11413 	mutex_exit(&rp->r_statelock);
11414 	return (0);
11415 }
11416 
11417 /*
11418  * Remove some pages from an mmap'd vnode.  Just update the
11419  * count of pages.  If doing close-to-open, then flush and
11420  * commit all of the pages associated with this file.
11421  * Otherwise, start an asynchronous page flush to write out
11422  * any dirty pages.  This will also associate a credential
11423  * with the rnode which can be used to write the pages.
11424  */
11425 /* ARGSUSED */
11426 static void
11427 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11428 {
11429 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11430 	rnode4_t		*rp;
11431 	mntinfo4_t		*mi;
11432 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11433 
11434 	rp = VTOR4(dmapp->vp);
11435 	mi = VTOMI4(dmapp->vp);
11436 
11437 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11438 	ASSERT(rp->r_mapcnt >= 0);
11439 
11440 	/*
11441 	 * Initiate a page flush and potential commit if there are
11442 	 * pages, the file system was not mounted readonly, the segment
11443 	 * was mapped shared, and the pages themselves were writeable.
11444 	 */
11445 	if (nfs4_has_pages(dmapp->vp) &&
11446 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11447 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11448 		mutex_enter(&rp->r_statelock);
11449 		rp->r_flags |= R4DIRTY;
11450 		mutex_exit(&rp->r_statelock);
11451 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11452 		    dmapp->len, dmapp->cr);
11453 		if (!e.error) {
11454 			mutex_enter(&rp->r_statelock);
11455 			e.error = rp->r_error;
11456 			rp->r_error = 0;
11457 			mutex_exit(&rp->r_statelock);
11458 		}
11459 	} else
11460 		e.error = 0;
11461 
11462 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11463 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11464 		    B_INVAL, dmapp->cr, NULL);
11465 
11466 	if (e.error) {
11467 		e.stat = puterrno4(e.error);
11468 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11469 		    OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11470 		dmapp->caller->error = e.error;
11471 	}
11472 
11473 	/* Check to see if we need to close the file */
11474 
11475 	if (dmapp->vp->v_type == VREG) {
11476 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11477 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11478 
11479 		if (e.error != 0 || e.stat != NFS4_OK) {
11480 			/*
11481 			 * Since it is possible that e.error == 0 and
11482 			 * e.stat != NFS4_OK (and vice versa),
11483 			 * we do the proper checking in order to get both
11484 			 * e.error and e.stat reporting the correct info.
11485 			 */
11486 			if (e.stat == NFS4_OK)
11487 				e.stat = puterrno4(e.error);
11488 			if (e.error == 0)
11489 				e.error = geterrno4(e.stat);
11490 
11491 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11492 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11493 			dmapp->caller->error = e.error;
11494 		}
11495 	}
11496 
11497 	(void) as_delete_callback(as, arg);
11498 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11499 }
11500 
11501 
11502 static uint_t
11503 fattr4_maxfilesize_to_bits(uint64_t ll)
11504 {
11505 	uint_t l = 1;
11506 
11507 	if (ll == 0) {
11508 		return (0);
11509 	}
11510 
11511 	if (ll & 0xffffffff00000000) {
11512 		l += 32; ll >>= 32;
11513 	}
11514 	if (ll & 0xffff0000) {
11515 		l += 16; ll >>= 16;
11516 	}
11517 	if (ll & 0xff00) {
11518 		l += 8; ll >>= 8;
11519 	}
11520 	if (ll & 0xf0) {
11521 		l += 4; ll >>= 4;
11522 	}
11523 	if (ll & 0xc) {
11524 		l += 2; ll >>= 2;
11525 	}
11526 	if (ll & 0x2) {
11527 		l += 1;
11528 	}
11529 	return (l);
11530 }
11531 
11532 static int
11533 nfs4_have_xattrs(vnode_t *vp, ulong_t *valp, cred_t *cr)
11534 {
11535 	vnode_t *avp = NULL;
11536 	int error;
11537 
11538 	if ((error = nfs4lookup_xattr(vp, "", &avp,
11539 	    LOOKUP_XATTR, cr)) == 0)
11540 		error = do_xattr_exists_check(avp, valp, cr);
11541 	if (avp)
11542 		VN_RELE(avp);
11543 
11544 	return (error);
11545 }
11546 
11547 /* ARGSUSED */
11548 int
11549 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
11550     caller_context_t *ct)
11551 {
11552 	int error;
11553 	hrtime_t t;
11554 	rnode4_t *rp;
11555 	nfs4_ga_res_t gar;
11556 	nfs4_ga_ext_res_t ger;
11557 
11558 	gar.n4g_ext_res = &ger;
11559 
11560 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11561 		return (EIO);
11562 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11563 		*valp = MAXPATHLEN;
11564 		return (0);
11565 	}
11566 	if (cmd == _PC_ACL_ENABLED) {
11567 		*valp = _ACL_ACE_ENABLED;
11568 		return (0);
11569 	}
11570 
11571 	rp = VTOR4(vp);
11572 	if (cmd == _PC_XATTR_EXISTS) {
11573 		/*
11574 		 * The existence of the xattr directory is not sufficient
11575 		 * for determining whether generic user attributes exists.
11576 		 * The attribute directory could only be a transient directory
11577 		 * used for Solaris sysattr support.  Do a small readdir
11578 		 * to verify if the only entries are sysattrs or not.
11579 		 *
11580 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11581 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11582 		 * and we don't have any way to update the "base" object's
11583 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11584 		 * could help out.
11585 		 */
11586 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11587 		    rp->r_xattr_dir == NULL) {
11588 			return (nfs4_have_xattrs(vp, valp, cr));
11589 		}
11590 	} else {  /* OLD CODE */
11591 		if (ATTRCACHE4_VALID(vp)) {
11592 			mutex_enter(&rp->r_statelock);
11593 			if (rp->r_pathconf.pc4_cache_valid) {
11594 				error = 0;
11595 				switch (cmd) {
11596 				case _PC_FILESIZEBITS:
11597 					*valp =
11598 					    rp->r_pathconf.pc4_filesizebits;
11599 					break;
11600 				case _PC_LINK_MAX:
11601 					*valp =
11602 					    rp->r_pathconf.pc4_link_max;
11603 					break;
11604 				case _PC_NAME_MAX:
11605 					*valp =
11606 					    rp->r_pathconf.pc4_name_max;
11607 					break;
11608 				case _PC_CHOWN_RESTRICTED:
11609 					*valp =
11610 					    rp->r_pathconf.pc4_chown_restricted;
11611 					break;
11612 				case _PC_NO_TRUNC:
11613 					*valp =
11614 					    rp->r_pathconf.pc4_no_trunc;
11615 					break;
11616 				default:
11617 					error = EINVAL;
11618 					break;
11619 				}
11620 				mutex_exit(&rp->r_statelock);
11621 #ifdef DEBUG
11622 				nfs4_pathconf_cache_hits++;
11623 #endif
11624 				return (error);
11625 			}
11626 			mutex_exit(&rp->r_statelock);
11627 		}
11628 	}
11629 #ifdef DEBUG
11630 	nfs4_pathconf_cache_misses++;
11631 #endif
11632 
11633 	t = gethrtime();
11634 
11635 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11636 
11637 	if (error) {
11638 		mutex_enter(&rp->r_statelock);
11639 		rp->r_pathconf.pc4_cache_valid = FALSE;
11640 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11641 		mutex_exit(&rp->r_statelock);
11642 		return (error);
11643 	}
11644 
11645 	/* interpret the max filesize */
11646 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11647 	    fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11648 
11649 	/* Store the attributes we just received */
11650 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11651 
11652 	switch (cmd) {
11653 	case _PC_FILESIZEBITS:
11654 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11655 		break;
11656 	case _PC_LINK_MAX:
11657 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11658 		break;
11659 	case _PC_NAME_MAX:
11660 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11661 		break;
11662 	case _PC_CHOWN_RESTRICTED:
11663 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11664 		break;
11665 	case _PC_NO_TRUNC:
11666 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11667 		break;
11668 	case _PC_XATTR_EXISTS:
11669 		if (gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists) {
11670 			if (error = nfs4_have_xattrs(vp, valp, cr))
11671 				return (error);
11672 		}
11673 		break;
11674 	default:
11675 		return (EINVAL);
11676 	}
11677 
11678 	return (0);
11679 }
11680 
11681 /*
11682  * Called by async thread to do synchronous pageio. Do the i/o, wait
11683  * for it to complete, and cleanup the page list when done.
11684  */
11685 static int
11686 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11687     int flags, cred_t *cr)
11688 {
11689 	int error;
11690 
11691 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11692 
11693 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11694 	if (flags & B_READ)
11695 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11696 	else
11697 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11698 	return (error);
11699 }
11700 
11701 /* ARGSUSED */
11702 static int
11703 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11704     int flags, cred_t *cr, caller_context_t *ct)
11705 {
11706 	int error;
11707 	rnode4_t *rp;
11708 
11709 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11710 		return (EIO);
11711 
11712 	if (pp == NULL)
11713 		return (EINVAL);
11714 
11715 	rp = VTOR4(vp);
11716 	mutex_enter(&rp->r_statelock);
11717 	rp->r_count++;
11718 	mutex_exit(&rp->r_statelock);
11719 
11720 	if (flags & B_ASYNC) {
11721 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11722 		    nfs4_sync_pageio);
11723 	} else
11724 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11725 	mutex_enter(&rp->r_statelock);
11726 	rp->r_count--;
11727 	cv_broadcast(&rp->r_cv);
11728 	mutex_exit(&rp->r_statelock);
11729 	return (error);
11730 }
11731 
11732 /* ARGSUSED */
11733 static void
11734 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr,
11735     caller_context_t *ct)
11736 {
11737 	int error;
11738 	rnode4_t *rp;
11739 	page_t *plist;
11740 	page_t *pptr;
11741 	offset3 offset;
11742 	count3 len;
11743 	k_sigset_t smask;
11744 
11745 	/*
11746 	 * We should get called with fl equal to either B_FREE or
11747 	 * B_INVAL.  Any other value is illegal.
11748 	 *
11749 	 * The page that we are either supposed to free or destroy
11750 	 * should be exclusive locked and its io lock should not
11751 	 * be held.
11752 	 */
11753 	ASSERT(fl == B_FREE || fl == B_INVAL);
11754 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11755 
11756 	rp = VTOR4(vp);
11757 
11758 	/*
11759 	 * If the page doesn't need to be committed or we shouldn't
11760 	 * even bother attempting to commit it, then just make sure
11761 	 * that the p_fsdata byte is clear and then either free or
11762 	 * destroy the page as appropriate.
11763 	 */
11764 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11765 		pp->p_fsdata = C_NOCOMMIT;
11766 		if (fl == B_FREE)
11767 			page_free(pp, dn);
11768 		else
11769 			page_destroy(pp, dn);
11770 		return;
11771 	}
11772 
11773 	/*
11774 	 * If there is a page invalidation operation going on, then
11775 	 * if this is one of the pages being destroyed, then just
11776 	 * clear the p_fsdata byte and then either free or destroy
11777 	 * the page as appropriate.
11778 	 */
11779 	mutex_enter(&rp->r_statelock);
11780 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11781 		mutex_exit(&rp->r_statelock);
11782 		pp->p_fsdata = C_NOCOMMIT;
11783 		if (fl == B_FREE)
11784 			page_free(pp, dn);
11785 		else
11786 			page_destroy(pp, dn);
11787 		return;
11788 	}
11789 
11790 	/*
11791 	 * If we are freeing this page and someone else is already
11792 	 * waiting to do a commit, then just unlock the page and
11793 	 * return.  That other thread will take care of commiting
11794 	 * this page.  The page can be freed sometime after the
11795 	 * commit has finished.  Otherwise, if the page is marked
11796 	 * as delay commit, then we may be getting called from
11797 	 * pvn_write_done, one page at a time.   This could result
11798 	 * in one commit per page, so we end up doing lots of small
11799 	 * commits instead of fewer larger commits.  This is bad,
11800 	 * we want do as few commits as possible.
11801 	 */
11802 	if (fl == B_FREE) {
11803 		if (rp->r_flags & R4COMMITWAIT) {
11804 			page_unlock(pp);
11805 			mutex_exit(&rp->r_statelock);
11806 			return;
11807 		}
11808 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11809 			pp->p_fsdata = C_COMMIT;
11810 			page_unlock(pp);
11811 			mutex_exit(&rp->r_statelock);
11812 			return;
11813 		}
11814 	}
11815 
11816 	/*
11817 	 * Check to see if there is a signal which would prevent an
11818 	 * attempt to commit the pages from being successful.  If so,
11819 	 * then don't bother with all of the work to gather pages and
11820 	 * generate the unsuccessful RPC.  Just return from here and
11821 	 * let the page be committed at some later time.
11822 	 */
11823 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11824 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11825 		sigunintr(&smask);
11826 		page_unlock(pp);
11827 		mutex_exit(&rp->r_statelock);
11828 		return;
11829 	}
11830 	sigunintr(&smask);
11831 
11832 	/*
11833 	 * We are starting to need to commit pages, so let's try
11834 	 * to commit as many as possible at once to reduce the
11835 	 * overhead.
11836 	 *
11837 	 * Set the `commit inprogress' state bit.  We must
11838 	 * first wait until any current one finishes.  Then
11839 	 * we initialize the c_pages list with this page.
11840 	 */
11841 	while (rp->r_flags & R4COMMIT) {
11842 		rp->r_flags |= R4COMMITWAIT;
11843 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11844 		rp->r_flags &= ~R4COMMITWAIT;
11845 	}
11846 	rp->r_flags |= R4COMMIT;
11847 	mutex_exit(&rp->r_statelock);
11848 	ASSERT(rp->r_commit.c_pages == NULL);
11849 	rp->r_commit.c_pages = pp;
11850 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11851 	rp->r_commit.c_commlen = PAGESIZE;
11852 
11853 	/*
11854 	 * Gather together all other pages which can be committed.
11855 	 * They will all be chained off r_commit.c_pages.
11856 	 */
11857 	nfs4_get_commit(vp);
11858 
11859 	/*
11860 	 * Clear the `commit inprogress' status and disconnect
11861 	 * the list of pages to be committed from the rnode.
11862 	 * At this same time, we also save the starting offset
11863 	 * and length of data to be committed on the server.
11864 	 */
11865 	plist = rp->r_commit.c_pages;
11866 	rp->r_commit.c_pages = NULL;
11867 	offset = rp->r_commit.c_commbase;
11868 	len = rp->r_commit.c_commlen;
11869 	mutex_enter(&rp->r_statelock);
11870 	rp->r_flags &= ~R4COMMIT;
11871 	cv_broadcast(&rp->r_commit.c_cv);
11872 	mutex_exit(&rp->r_statelock);
11873 
11874 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11875 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11876 		nfs4_async_commit(vp, plist, offset, len,
11877 		    cr, do_nfs4_async_commit);
11878 		return;
11879 	}
11880 
11881 	/*
11882 	 * Actually generate the COMMIT op over the wire operation.
11883 	 */
11884 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11885 
11886 	/*
11887 	 * If we got an error during the commit, just unlock all
11888 	 * of the pages.  The pages will get retransmitted to the
11889 	 * server during a putpage operation.
11890 	 */
11891 	if (error) {
11892 		while (plist != NULL) {
11893 			pptr = plist;
11894 			page_sub(&plist, pptr);
11895 			page_unlock(pptr);
11896 		}
11897 		return;
11898 	}
11899 
11900 	/*
11901 	 * We've tried as hard as we can to commit the data to stable
11902 	 * storage on the server.  We just unlock the rest of the pages
11903 	 * and clear the commit required state.  They will be put
11904 	 * onto the tail of the cachelist if they are nolonger
11905 	 * mapped.
11906 	 */
11907 	while (plist != pp) {
11908 		pptr = plist;
11909 		page_sub(&plist, pptr);
11910 		pptr->p_fsdata = C_NOCOMMIT;
11911 		page_unlock(pptr);
11912 	}
11913 
11914 	/*
11915 	 * It is possible that nfs4_commit didn't return error but
11916 	 * some other thread has modified the page we are going
11917 	 * to free/destroy.
11918 	 *    In this case we need to rewrite the page. Do an explicit check
11919 	 * before attempting to free/destroy the page. If modified, needs to
11920 	 * be rewritten so unlock the page and return.
11921 	 */
11922 	if (hat_ismod(pp)) {
11923 		pp->p_fsdata = C_NOCOMMIT;
11924 		page_unlock(pp);
11925 		return;
11926 	}
11927 
11928 	/*
11929 	 * Now, as appropriate, either free or destroy the page
11930 	 * that we were called with.
11931 	 */
11932 	pp->p_fsdata = C_NOCOMMIT;
11933 	if (fl == B_FREE)
11934 		page_free(pp, dn);
11935 	else
11936 		page_destroy(pp, dn);
11937 }
11938 
11939 /*
11940  * Commit requires that the current fh be the file written to.
11941  * The compound op structure is:
11942  *      PUTFH(file), COMMIT
11943  */
11944 static int
11945 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11946 {
11947 	COMPOUND4args_clnt args;
11948 	COMPOUND4res_clnt res;
11949 	COMMIT4res *cm_res;
11950 	nfs_argop4 argop[2];
11951 	nfs_resop4 *resop;
11952 	int doqueue;
11953 	mntinfo4_t *mi;
11954 	rnode4_t *rp;
11955 	cred_t *cred_otw = NULL;
11956 	bool_t needrecov = FALSE;
11957 	nfs4_recov_state_t recov_state;
11958 	nfs4_open_stream_t *osp = NULL;
11959 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11960 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11961 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11962 
11963 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11964 
11965 	rp = VTOR4(vp);
11966 
11967 	mi = VTOMI4(vp);
11968 	recov_state.rs_flags = 0;
11969 	recov_state.rs_num_retry_despite_err = 0;
11970 get_commit_cred:
11971 	/*
11972 	 * Releases the osp, if a valid open stream is provided.
11973 	 * Puts a hold on the cred_otw and the new osp (if found).
11974 	 */
11975 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11976 	    &first_time, &last_time);
11977 	args.ctag = TAG_COMMIT;
11978 recov_retry:
11979 	/*
11980 	 * Commit ops: putfh file; commit
11981 	 */
11982 	args.array_len = 2;
11983 	args.array = argop;
11984 
11985 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11986 	    &recov_state, NULL);
11987 	if (e.error) {
11988 		crfree(cred_otw);
11989 		if (osp != NULL)
11990 			open_stream_rele(osp, rp);
11991 		return (e.error);
11992 	}
11993 
11994 	/* putfh directory */
11995 	argop[0].argop = OP_CPUTFH;
11996 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11997 
11998 	/* commit */
11999 	argop[1].argop = OP_COMMIT;
12000 	argop[1].nfs_argop4_u.opcommit.offset = offset;
12001 	argop[1].nfs_argop4_u.opcommit.count = count;
12002 
12003 	doqueue = 1;
12004 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
12005 
12006 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
12007 	if (!needrecov && e.error) {
12008 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
12009 		    needrecov);
12010 		crfree(cred_otw);
12011 		if (e.error == EACCES && last_time == FALSE)
12012 			goto get_commit_cred;
12013 		if (osp != NULL)
12014 			open_stream_rele(osp, rp);
12015 		return (e.error);
12016 	}
12017 
12018 	if (needrecov) {
12019 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
12020 		    NULL, OP_COMMIT, NULL, NULL, NULL) == FALSE) {
12021 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
12022 			    &recov_state, needrecov);
12023 			if (!e.error)
12024 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12025 				    (caddr_t)&res);
12026 			goto recov_retry;
12027 		}
12028 		if (e.error) {
12029 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
12030 			    &recov_state, needrecov);
12031 			crfree(cred_otw);
12032 			if (osp != NULL)
12033 				open_stream_rele(osp, rp);
12034 			return (e.error);
12035 		}
12036 		/* fall through for res.status case */
12037 	}
12038 
12039 	if (res.status) {
12040 		e.error = geterrno4(res.status);
12041 		if (e.error == EACCES && last_time == FALSE) {
12042 			crfree(cred_otw);
12043 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
12044 			    &recov_state, needrecov);
12045 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12046 			goto get_commit_cred;
12047 		}
12048 		/*
12049 		 * Can't do a nfs4_purge_stale_fh here because this
12050 		 * can cause a deadlock.  nfs4_commit can
12051 		 * be called from nfs4_dispose which can be called
12052 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
12053 		 * can call back to pvn_vplist_dirty.
12054 		 */
12055 		if (e.error == ESTALE) {
12056 			mutex_enter(&rp->r_statelock);
12057 			rp->r_flags |= R4STALE;
12058 			if (!rp->r_error)
12059 				rp->r_error = e.error;
12060 			mutex_exit(&rp->r_statelock);
12061 			PURGE_ATTRCACHE4(vp);
12062 		} else {
12063 			mutex_enter(&rp->r_statelock);
12064 			if (!rp->r_error)
12065 				rp->r_error = e.error;
12066 			mutex_exit(&rp->r_statelock);
12067 		}
12068 	} else {
12069 		ASSERT(rp->r_flags & R4HAVEVERF);
12070 		resop = &res.array[1];	/* commit res */
12071 		cm_res = &resop->nfs_resop4_u.opcommit;
12072 		mutex_enter(&rp->r_statelock);
12073 		if (cm_res->writeverf == rp->r_writeverf) {
12074 			mutex_exit(&rp->r_statelock);
12075 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12076 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
12077 			    &recov_state, needrecov);
12078 			crfree(cred_otw);
12079 			if (osp != NULL)
12080 				open_stream_rele(osp, rp);
12081 			return (0);
12082 		}
12083 		nfs4_set_mod(vp);
12084 		rp->r_writeverf = cm_res->writeverf;
12085 		mutex_exit(&rp->r_statelock);
12086 		e.error = NFS_VERF_MISMATCH;
12087 	}
12088 
12089 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12090 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
12091 	crfree(cred_otw);
12092 	if (osp != NULL)
12093 		open_stream_rele(osp, rp);
12094 
12095 	return (e.error);
12096 }
12097 
12098 static void
12099 nfs4_set_mod(vnode_t *vp)
12100 {
12101 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12102 
12103 	/* make sure we're looking at the master vnode, not a shadow */
12104 	pvn_vplist_setdirty(RTOV4(VTOR4(vp)), nfs_setmod_check);
12105 }
12106 
12107 /*
12108  * This function is used to gather a page list of the pages which
12109  * can be committed on the server.
12110  *
12111  * The calling thread must have set R4COMMIT.  This bit is used to
12112  * serialize access to the commit structure in the rnode.  As long
12113  * as the thread has set R4COMMIT, then it can manipulate the commit
12114  * structure without requiring any other locks.
12115  *
12116  * When this function is called from nfs4_dispose() the page passed
12117  * into nfs4_dispose() will be SE_EXCL locked, and so this function
12118  * will skip it. This is not a problem since we initially add the
12119  * page to the r_commit page list.
12120  *
12121  */
12122 static void
12123 nfs4_get_commit(vnode_t *vp)
12124 {
12125 	rnode4_t *rp;
12126 	page_t *pp;
12127 	kmutex_t *vphm;
12128 
12129 	rp = VTOR4(vp);
12130 
12131 	ASSERT(rp->r_flags & R4COMMIT);
12132 
12133 	/* make sure we're looking at the master vnode, not a shadow */
12134 
12135 	if (IS_SHADOW(vp, rp))
12136 		vp = RTOV4(rp);
12137 
12138 	vphm = page_vnode_mutex(vp);
12139 	mutex_enter(vphm);
12140 
12141 	/*
12142 	 * If there are no pages associated with this vnode, then
12143 	 * just return.
12144 	 */
12145 	if ((pp = vp->v_pages) == NULL) {
12146 		mutex_exit(vphm);
12147 		return;
12148 	}
12149 
12150 	/*
12151 	 * Step through all of the pages associated with this vnode
12152 	 * looking for pages which need to be committed.
12153 	 */
12154 	do {
12155 		/* Skip marker pages. */
12156 		if (pp->p_hash == PVN_VPLIST_HASH_TAG)
12157 			continue;
12158 
12159 		/*
12160 		 * First short-cut everything (without the page_lock)
12161 		 * and see if this page does not need to be committed
12162 		 * or is modified if so then we'll just skip it.
12163 		 */
12164 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
12165 			continue;
12166 
12167 		/*
12168 		 * Attempt to lock the page.  If we can't, then
12169 		 * someone else is messing with it or we have been
12170 		 * called from nfs4_dispose and this is the page that
12171 		 * nfs4_dispose was called with.. anyway just skip it.
12172 		 */
12173 		if (!page_trylock(pp, SE_EXCL))
12174 			continue;
12175 
12176 		/*
12177 		 * Lets check again now that we have the page lock.
12178 		 */
12179 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
12180 			page_unlock(pp);
12181 			continue;
12182 		}
12183 
12184 		/* this had better not be a free page */
12185 		ASSERT(PP_ISFREE(pp) == 0);
12186 
12187 		/*
12188 		 * The page needs to be committed and we locked it.
12189 		 * Update the base and length parameters and add it
12190 		 * to r_pages.
12191 		 */
12192 		if (rp->r_commit.c_pages == NULL) {
12193 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
12194 			rp->r_commit.c_commlen = PAGESIZE;
12195 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
12196 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
12197 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
12198 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
12199 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
12200 		    <= pp->p_offset) {
12201 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
12202 			    rp->r_commit.c_commbase + PAGESIZE;
12203 		}
12204 		page_add(&rp->r_commit.c_pages, pp);
12205 	} while ((pp = pp->p_vpnext) != vp->v_pages);
12206 
12207 	mutex_exit(vphm);
12208 }
12209 
12210 /*
12211  * This routine is used to gather together a page list of the pages
12212  * which are to be committed on the server.  This routine must not
12213  * be called if the calling thread holds any locked pages.
12214  *
12215  * The calling thread must have set R4COMMIT.  This bit is used to
12216  * serialize access to the commit structure in the rnode.  As long
12217  * as the thread has set R4COMMIT, then it can manipulate the commit
12218  * structure without requiring any other locks.
12219  */
12220 static void
12221 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
12222 {
12223 
12224 	rnode4_t *rp;
12225 	page_t *pp;
12226 	u_offset_t end;
12227 	u_offset_t off;
12228 	ASSERT(len != 0);
12229 	rp = VTOR4(vp);
12230 	ASSERT(rp->r_flags & R4COMMIT);
12231 
12232 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12233 
12234 	/* make sure we're looking at the master vnode, not a shadow */
12235 
12236 	if (IS_SHADOW(vp, rp))
12237 		vp = RTOV4(rp);
12238 
12239 	/*
12240 	 * If there are no pages associated with this vnode, then
12241 	 * just return.
12242 	 */
12243 	if ((pp = vp->v_pages) == NULL)
12244 		return;
12245 	/*
12246 	 * Calculate the ending offset.
12247 	 */
12248 	end = soff + len;
12249 	for (off = soff; off < end; off += PAGESIZE) {
12250 		/*
12251 		 * Lookup each page by vp, offset.
12252 		 */
12253 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
12254 			continue;
12255 		/*
12256 		 * If this page does not need to be committed or is
12257 		 * modified, then just skip it.
12258 		 */
12259 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
12260 			page_unlock(pp);
12261 			continue;
12262 		}
12263 
12264 		ASSERT(PP_ISFREE(pp) == 0);
12265 		/*
12266 		 * The page needs to be committed and we locked it.
12267 		 * Update the base and length parameters and add it
12268 		 * to r_pages.
12269 		 */
12270 		if (rp->r_commit.c_pages == NULL) {
12271 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
12272 			rp->r_commit.c_commlen = PAGESIZE;
12273 		} else {
12274 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
12275 			    rp->r_commit.c_commbase + PAGESIZE;
12276 		}
12277 		page_add(&rp->r_commit.c_pages, pp);
12278 	}
12279 }
12280 
12281 /*
12282  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
12283  * Flushes and commits data to the server.
12284  */
12285 static int
12286 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
12287 {
12288 	int error;
12289 	verifier4 write_verf;
12290 	rnode4_t *rp = VTOR4(vp);
12291 
12292 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12293 
12294 	/*
12295 	 * Flush the data portion of the file and then commit any
12296 	 * portions which need to be committed.  This may need to
12297 	 * be done twice if the server has changed state since
12298 	 * data was last written.  The data will need to be
12299 	 * rewritten to the server and then a new commit done.
12300 	 *
12301 	 * In fact, this may need to be done several times if the
12302 	 * server is having problems and crashing while we are
12303 	 * attempting to do this.
12304 	 */
12305 
12306 top:
12307 	/*
12308 	 * Do a flush based on the poff and plen arguments.  This
12309 	 * will synchronously write out any modified pages in the
12310 	 * range specified by (poff, plen). This starts all of the
12311 	 * i/o operations which will be waited for in the next
12312 	 * call to nfs4_putpage
12313 	 */
12314 
12315 	mutex_enter(&rp->r_statelock);
12316 	write_verf = rp->r_writeverf;
12317 	mutex_exit(&rp->r_statelock);
12318 
12319 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr, NULL);
12320 	if (error == EAGAIN)
12321 		error = 0;
12322 
12323 	/*
12324 	 * Do a flush based on the poff and plen arguments.  This
12325 	 * will synchronously write out any modified pages in the
12326 	 * range specified by (poff, plen) and wait until all of
12327 	 * the asynchronous i/o's in that range are done as well.
12328 	 */
12329 	if (!error)
12330 		error = nfs4_putpage(vp, poff, plen, 0, cr, NULL);
12331 
12332 	if (error)
12333 		return (error);
12334 
12335 	mutex_enter(&rp->r_statelock);
12336 	if (rp->r_writeverf != write_verf) {
12337 		mutex_exit(&rp->r_statelock);
12338 		goto top;
12339 	}
12340 	mutex_exit(&rp->r_statelock);
12341 
12342 	/*
12343 	 * Now commit any pages which might need to be committed.
12344 	 * If the error, NFS_VERF_MISMATCH, is returned, then
12345 	 * start over with the flush operation.
12346 	 */
12347 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
12348 
12349 	if (error == NFS_VERF_MISMATCH)
12350 		goto top;
12351 
12352 	return (error);
12353 }
12354 
12355 /*
12356  * nfs4_commit_vp()  will wait for other pending commits and
12357  * will either commit the whole file or a range, plen dictates
12358  * if we commit whole file. a value of zero indicates the whole
12359  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
12360  */
12361 static int
12362 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12363     cred_t *cr, int wait_on_writes)
12364 {
12365 	rnode4_t *rp;
12366 	page_t *plist;
12367 	offset3 offset;
12368 	count3 len;
12369 
12370 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12371 
12372 	rp = VTOR4(vp);
12373 
12374 	/*
12375 	 *  before we gather commitable pages make
12376 	 *  sure there are no outstanding async writes
12377 	 */
12378 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12379 		mutex_enter(&rp->r_statelock);
12380 		while (rp->r_count > 0) {
12381 			cv_wait(&rp->r_cv, &rp->r_statelock);
12382 		}
12383 		mutex_exit(&rp->r_statelock);
12384 	}
12385 
12386 	/*
12387 	 * Set the `commit inprogress' state bit.  We must
12388 	 * first wait until any current one finishes.
12389 	 */
12390 	mutex_enter(&rp->r_statelock);
12391 	while (rp->r_flags & R4COMMIT) {
12392 		rp->r_flags |= R4COMMITWAIT;
12393 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12394 		rp->r_flags &= ~R4COMMITWAIT;
12395 	}
12396 	rp->r_flags |= R4COMMIT;
12397 	mutex_exit(&rp->r_statelock);
12398 
12399 	/*
12400 	 * Gather all of the pages which need to be
12401 	 * committed.
12402 	 */
12403 	if (plen == 0)
12404 		nfs4_get_commit(vp);
12405 	else
12406 		nfs4_get_commit_range(vp, poff, plen);
12407 
12408 	/*
12409 	 * Clear the `commit inprogress' bit and disconnect the
12410 	 * page list which was gathered by nfs4_get_commit.
12411 	 */
12412 	plist = rp->r_commit.c_pages;
12413 	rp->r_commit.c_pages = NULL;
12414 	offset = rp->r_commit.c_commbase;
12415 	len = rp->r_commit.c_commlen;
12416 	mutex_enter(&rp->r_statelock);
12417 	rp->r_flags &= ~R4COMMIT;
12418 	cv_broadcast(&rp->r_commit.c_cv);
12419 	mutex_exit(&rp->r_statelock);
12420 
12421 	/*
12422 	 * If any pages need to be committed, commit them and
12423 	 * then unlock them so that they can be freed some
12424 	 * time later.
12425 	 */
12426 	if (plist == NULL)
12427 		return (0);
12428 
12429 	/*
12430 	 * No error occurred during the flush portion
12431 	 * of this operation, so now attempt to commit
12432 	 * the data to stable storage on the server.
12433 	 *
12434 	 * This will unlock all of the pages on the list.
12435 	 */
12436 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12437 }
12438 
12439 static int
12440 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12441     cred_t *cr)
12442 {
12443 	int error;
12444 	page_t *pp;
12445 
12446 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12447 
12448 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12449 
12450 	/*
12451 	 * If we got an error, then just unlock all of the pages
12452 	 * on the list.
12453 	 */
12454 	if (error) {
12455 		while (plist != NULL) {
12456 			pp = plist;
12457 			page_sub(&plist, pp);
12458 			page_unlock(pp);
12459 		}
12460 		return (error);
12461 	}
12462 	/*
12463 	 * We've tried as hard as we can to commit the data to stable
12464 	 * storage on the server.  We just unlock the pages and clear
12465 	 * the commit required state.  They will get freed later.
12466 	 */
12467 	while (plist != NULL) {
12468 		pp = plist;
12469 		page_sub(&plist, pp);
12470 		pp->p_fsdata = C_NOCOMMIT;
12471 		page_unlock(pp);
12472 	}
12473 
12474 	return (error);
12475 }
12476 
12477 static void
12478 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12479     cred_t *cr)
12480 {
12481 
12482 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12483 }
12484 
12485 /*ARGSUSED*/
12486 static int
12487 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12488     caller_context_t *ct)
12489 {
12490 	int		error = 0;
12491 	mntinfo4_t	*mi;
12492 	vattr_t		va;
12493 	vsecattr_t	nfsace4_vsap;
12494 
12495 	mi = VTOMI4(vp);
12496 	if (nfs_zone() != mi->mi_zone)
12497 		return (EIO);
12498 	if (mi->mi_flags & MI4_ACL) {
12499 		/* if we have a delegation, return it */
12500 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12501 			(void) nfs4delegreturn(VTOR4(vp),
12502 			    NFS4_DR_REOPEN|NFS4_DR_PUSH);
12503 
12504 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12505 		    NFS4_ACL_SET);
12506 		if (error) /* EINVAL */
12507 			return (error);
12508 
12509 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12510 			/*
12511 			 * These are aclent_t type entries.
12512 			 */
12513 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12514 			    vp->v_type == VDIR, FALSE);
12515 			if (error)
12516 				return (error);
12517 		} else {
12518 			/*
12519 			 * These are ace_t type entries.
12520 			 */
12521 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12522 			    FALSE);
12523 			if (error)
12524 				return (error);
12525 		}
12526 		bzero(&va, sizeof (va));
12527 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12528 		vs_ace4_destroy(&nfsace4_vsap);
12529 		return (error);
12530 	}
12531 	return (ENOSYS);
12532 }
12533 
12534 /* ARGSUSED */
12535 int
12536 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12537     caller_context_t *ct)
12538 {
12539 	int		error;
12540 	mntinfo4_t	*mi;
12541 	nfs4_ga_res_t	gar;
12542 	rnode4_t	*rp = VTOR4(vp);
12543 
12544 	mi = VTOMI4(vp);
12545 	if (nfs_zone() != mi->mi_zone)
12546 		return (EIO);
12547 
12548 	bzero(&gar, sizeof (gar));
12549 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12550 
12551 	/*
12552 	 * vsecattr->vsa_mask holds the original acl request mask.
12553 	 * This is needed when determining what to return.
12554 	 * (See: nfs4_create_getsecattr_return())
12555 	 */
12556 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12557 	if (error) /* EINVAL */
12558 		return (error);
12559 
12560 	/*
12561 	 * If this is a referral stub, don't try to go OTW for an ACL
12562 	 */
12563 	if (RP_ISSTUB_REFERRAL(VTOR4(vp)))
12564 		return (fs_fab_acl(vp, vsecattr, flag, cr, ct));
12565 
12566 	if (mi->mi_flags & MI4_ACL) {
12567 		/*
12568 		 * Check if the data is cached and the cache is valid.  If it
12569 		 * is we don't go over the wire.
12570 		 */
12571 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12572 			mutex_enter(&rp->r_statelock);
12573 			if (rp->r_secattr != NULL) {
12574 				error = nfs4_create_getsecattr_return(
12575 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12576 				    rp->r_attr.va_gid,
12577 				    vp->v_type == VDIR);
12578 				if (!error) { /* error == 0 - Success! */
12579 					mutex_exit(&rp->r_statelock);
12580 					return (error);
12581 				}
12582 			}
12583 			mutex_exit(&rp->r_statelock);
12584 		}
12585 
12586 		/*
12587 		 * The getattr otw call will always get both the acl, in
12588 		 * the form of a list of nfsace4's, and the number of acl
12589 		 * entries; independent of the value of gar.n4g_va.va_mask.
12590 		 */
12591 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12592 		if (error) {
12593 			vs_ace4_destroy(&gar.n4g_vsa);
12594 			if (error == ENOTSUP || error == EOPNOTSUPP)
12595 				error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12596 			return (error);
12597 		}
12598 
12599 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12600 			/*
12601 			 * No error was returned, but according to the response
12602 			 * bitmap, neither was an acl.
12603 			 */
12604 			vs_ace4_destroy(&gar.n4g_vsa);
12605 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12606 			return (error);
12607 		}
12608 
12609 		/*
12610 		 * Update the cache with the ACL.
12611 		 */
12612 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12613 
12614 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12615 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12616 		    vp->v_type == VDIR);
12617 		vs_ace4_destroy(&gar.n4g_vsa);
12618 		if ((error) && (vsecattr->vsa_mask &
12619 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12620 		    (error != EACCES)) {
12621 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12622 		}
12623 		return (error);
12624 	}
12625 	error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12626 	return (error);
12627 }
12628 
12629 /*
12630  * The function returns:
12631  *	- 0 (zero) if the passed in "acl_mask" is a valid request.
12632  *	- EINVAL if the passed in "acl_mask" is an invalid request.
12633  *
12634  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12635  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12636  *
12637  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12638  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12639  * - We have a count field set without the corresponding acl field set. (e.g. -
12640  * VSA_ACECNT is set, but VSA_ACE is not)
12641  */
12642 static int
12643 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12644 {
12645 	/* Shortcut the masks that are always valid. */
12646 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12647 		return (0);
12648 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12649 		return (0);
12650 
12651 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12652 		/*
12653 		 * We can't have any VSA_ACL type stuff in the mask now.
12654 		 */
12655 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12656 		    VSA_DFACLCNT))
12657 			return (EINVAL);
12658 
12659 		if (op == NFS4_ACL_SET) {
12660 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12661 				return (EINVAL);
12662 		}
12663 	}
12664 
12665 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12666 		/*
12667 		 * We can't have any VSA_ACE type stuff in the mask now.
12668 		 */
12669 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12670 			return (EINVAL);
12671 
12672 		if (op == NFS4_ACL_SET) {
12673 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12674 				return (EINVAL);
12675 
12676 			if ((acl_mask & VSA_DFACLCNT) &&
12677 			    !(acl_mask & VSA_DFACL))
12678 				return (EINVAL);
12679 		}
12680 	}
12681 	return (0);
12682 }
12683 
12684 /*
12685  * The theory behind creating the correct getsecattr return is simply this:
12686  * "Don't return anything that the caller is not expecting to have to free."
12687  */
12688 static int
12689 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12690     uid_t uid, gid_t gid, int isdir)
12691 {
12692 	int error = 0;
12693 	/* Save the mask since the translators modify it. */
12694 	uint_t	orig_mask = vsap->vsa_mask;
12695 
12696 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12697 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid, FALSE);
12698 
12699 		if (error)
12700 			return (error);
12701 
12702 		/*
12703 		 * If the caller only asked for the ace count (VSA_ACECNT)
12704 		 * don't give them the full acl (VSA_ACE), free it.
12705 		 */
12706 		if (!orig_mask & VSA_ACE) {
12707 			if (vsap->vsa_aclentp != NULL) {
12708 				kmem_free(vsap->vsa_aclentp,
12709 				    vsap->vsa_aclcnt * sizeof (ace_t));
12710 				vsap->vsa_aclentp = NULL;
12711 			}
12712 		}
12713 		vsap->vsa_mask = orig_mask;
12714 
12715 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12716 	    VSA_DFACLCNT)) {
12717 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12718 		    isdir, FALSE);
12719 
12720 		if (error)
12721 			return (error);
12722 
12723 		/*
12724 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12725 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12726 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12727 		 */
12728 		if (!orig_mask & VSA_ACL) {
12729 			if (vsap->vsa_aclentp != NULL) {
12730 				kmem_free(vsap->vsa_aclentp,
12731 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12732 				vsap->vsa_aclentp = NULL;
12733 			}
12734 		}
12735 
12736 		if (!orig_mask & VSA_DFACL) {
12737 			if (vsap->vsa_dfaclentp != NULL) {
12738 				kmem_free(vsap->vsa_dfaclentp,
12739 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12740 				vsap->vsa_dfaclentp = NULL;
12741 			}
12742 		}
12743 		vsap->vsa_mask = orig_mask;
12744 	}
12745 	return (0);
12746 }
12747 
12748 /* ARGSUSED */
12749 int
12750 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr,
12751     caller_context_t *ct)
12752 {
12753 	int error;
12754 
12755 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12756 		return (EIO);
12757 	/*
12758 	 * check for valid cmd parameter
12759 	 */
12760 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12761 		return (EINVAL);
12762 
12763 	/*
12764 	 * Check access permissions
12765 	 */
12766 	if ((cmd & F_SHARE) &&
12767 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12768 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12769 		return (EBADF);
12770 
12771 	/*
12772 	 * If the filesystem is mounted using local locking, pass the
12773 	 * request off to the local share code.
12774 	 */
12775 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12776 		return (fs_shrlock(vp, cmd, shr, flag, cr, ct));
12777 
12778 	switch (cmd) {
12779 	case F_SHARE:
12780 	case F_UNSHARE:
12781 		/*
12782 		 * This will be properly implemented later,
12783 		 * see RFE: 4823948 .
12784 		 */
12785 		error = EAGAIN;
12786 		break;
12787 
12788 	case F_HASREMOTELOCKS:
12789 		/*
12790 		 * NFS client can't store remote locks itself
12791 		 */
12792 		shr->s_access = 0;
12793 		error = 0;
12794 		break;
12795 
12796 	default:
12797 		error = EINVAL;
12798 		break;
12799 	}
12800 
12801 	return (error);
12802 }
12803 
12804 /*
12805  * Common code called by directory ops to update the attrcache
12806  */
12807 static int
12808 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12809     hrtime_t t, vnode_t *vp, cred_t *cr)
12810 {
12811 	int error = 0;
12812 
12813 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12814 
12815 	if (status != NFS4_OK) {
12816 		/* getattr not done or failed */
12817 		PURGE_ATTRCACHE4(vp);
12818 		return (error);
12819 	}
12820 
12821 	if (garp) {
12822 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12823 	} else {
12824 		PURGE_ATTRCACHE4(vp);
12825 	}
12826 	return (error);
12827 }
12828 
12829 /*
12830  * Update directory caches for directory modification ops (link, rename, etc.)
12831  * When dinfo is NULL, manage dircaches in the old way.
12832  */
12833 static void
12834 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12835     dirattr_info_t *dinfo)
12836 {
12837 	rnode4_t	*drp = VTOR4(dvp);
12838 
12839 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12840 
12841 	/* Purge rddir cache for dir since it changed */
12842 	if (drp->r_dir != NULL)
12843 		nfs4_purge_rddir_cache(dvp);
12844 
12845 	/*
12846 	 * If caller provided dinfo, then use it to manage dir caches.
12847 	 */
12848 	if (dinfo != NULL) {
12849 		if (vp != NULL) {
12850 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12851 			if (!VTOR4(vp)->created_v4) {
12852 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12853 				dnlc_update(dvp, nm, vp);
12854 			} else {
12855 				/*
12856 				 * XXX don't update if the created_v4 flag is
12857 				 * set
12858 				 */
12859 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12860 				NFS4_DEBUG(nfs4_client_state_debug,
12861 				    (CE_NOTE, "nfs4_update_dircaches: "
12862 				    "don't update dnlc: created_v4 flag"));
12863 			}
12864 		}
12865 
12866 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12867 		    dinfo->di_cred, FALSE, cinfo);
12868 
12869 		return;
12870 	}
12871 
12872 	/*
12873 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12874 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12875 	 * attrs, the dir's attrs must be purged.
12876 	 *
12877 	 * XXX this check and dnlc update/purge should really be atomic,
12878 	 * XXX but can't use rnode statelock because it'll deadlock in
12879 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12880 	 * XXX does occur.
12881 	 *
12882 	 * XXX We also may want to check that atomic is true in the
12883 	 * XXX change_info struct. If it is not, the change_info may
12884 	 * XXX reflect changes by more than one clients which means that
12885 	 * XXX our cache may not be valid.
12886 	 */
12887 	PURGE_ATTRCACHE4(dvp);
12888 	if (drp->r_change == cinfo->before) {
12889 		/* no changes took place in the directory prior to our link */
12890 		if (vp != NULL) {
12891 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12892 			if (!VTOR4(vp)->created_v4) {
12893 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12894 				dnlc_update(dvp, nm, vp);
12895 			} else {
12896 				/*
12897 				 * XXX dont' update if the created_v4 flag
12898 				 * is set
12899 				 */
12900 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12901 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12902 				    "nfs4_update_dircaches: don't"
12903 				    " update dnlc: created_v4 flag"));
12904 			}
12905 		}
12906 	} else {
12907 		/* Another client modified directory - purge its dnlc cache */
12908 		dnlc_purge_vp(dvp);
12909 	}
12910 }
12911 
12912 /*
12913  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12914  * file.
12915  *
12916  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12917  * file (ie: client recovery) and otherwise set to FALSE.
12918  *
12919  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12920  * initiated) calling functions.
12921  *
12922  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12923  * of resending a 'lost' open request.
12924  *
12925  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12926  * server that hands out BAD_SEQID on open confirm.
12927  *
12928  * Errors are returned via the nfs4_error_t parameter.
12929  */
12930 void
12931 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12932     bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12933     bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12934 {
12935 	COMPOUND4args_clnt args;
12936 	COMPOUND4res_clnt res;
12937 	nfs_argop4 argop[2];
12938 	nfs_resop4 *resop;
12939 	int doqueue = 1;
12940 	mntinfo4_t *mi;
12941 	OPEN_CONFIRM4args *open_confirm_args;
12942 	int needrecov;
12943 
12944 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12945 #if DEBUG
12946 	mutex_enter(&oop->oo_lock);
12947 	ASSERT(oop->oo_seqid_inuse);
12948 	mutex_exit(&oop->oo_lock);
12949 #endif
12950 
12951 recov_retry_confirm:
12952 	nfs4_error_zinit(ep);
12953 	*retry_open = FALSE;
12954 
12955 	if (resend)
12956 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12957 	else
12958 		args.ctag = TAG_OPEN_CONFIRM;
12959 
12960 	args.array_len = 2;
12961 	args.array = argop;
12962 
12963 	/* putfh target fh */
12964 	argop[0].argop = OP_CPUTFH;
12965 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12966 
12967 	argop[1].argop = OP_OPEN_CONFIRM;
12968 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12969 
12970 	(*seqid) += 1;
12971 	open_confirm_args->seqid = *seqid;
12972 	open_confirm_args->open_stateid = *stateid;
12973 
12974 	mi = VTOMI4(vp);
12975 
12976 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12977 
12978 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12979 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12980 	}
12981 
12982 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12983 	if (!needrecov && ep->error)
12984 		return;
12985 
12986 	if (needrecov) {
12987 		bool_t abort = FALSE;
12988 
12989 		if (reopening_file == FALSE) {
12990 			nfs4_bseqid_entry_t *bsep = NULL;
12991 
12992 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12993 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12994 				    vp, 0, args.ctag,
12995 				    open_confirm_args->seqid);
12996 
12997 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
12998 			    NULL, NULL, OP_OPEN_CONFIRM, bsep, NULL, NULL);
12999 			if (bsep) {
13000 				kmem_free(bsep, sizeof (*bsep));
13001 				if (num_bseqid_retryp &&
13002 				    --(*num_bseqid_retryp) == 0)
13003 					abort = TRUE;
13004 			}
13005 		}
13006 		if ((ep->error == ETIMEDOUT ||
13007 		    res.status == NFS4ERR_RESOURCE) &&
13008 		    abort == FALSE && resend == FALSE) {
13009 			if (!ep->error)
13010 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13011 				    (caddr_t)&res);
13012 
13013 			delay(SEC_TO_TICK(confirm_retry_sec));
13014 			goto recov_retry_confirm;
13015 		}
13016 		/* State may have changed so retry the entire OPEN op */
13017 		if (abort == FALSE)
13018 			*retry_open = TRUE;
13019 		else
13020 			*retry_open = FALSE;
13021 		if (!ep->error)
13022 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
13023 		return;
13024 	}
13025 
13026 	if (res.status) {
13027 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
13028 		return;
13029 	}
13030 
13031 	resop = &res.array[1];  /* open confirm res */
13032 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
13033 	    stateid, sizeof (*stateid));
13034 
13035 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
13036 }
13037 
13038 /*
13039  * Return the credentials associated with a client state object.  The
13040  * caller is responsible for freeing the credentials.
13041  */
13042 
13043 static cred_t *
13044 state_to_cred(nfs4_open_stream_t *osp)
13045 {
13046 	cred_t *cr;
13047 
13048 	/*
13049 	 * It's ok to not lock the open stream and open owner to get
13050 	 * the oo_cred since this is only written once (upon creation)
13051 	 * and will not change.
13052 	 */
13053 	cr = osp->os_open_owner->oo_cred;
13054 	crhold(cr);
13055 
13056 	return (cr);
13057 }
13058 
13059 /*
13060  * nfs4_find_sysid
13061  *
13062  * Find the sysid for the knetconfig associated with the given mi.
13063  */
13064 static struct lm_sysid *
13065 nfs4_find_sysid(mntinfo4_t *mi)
13066 {
13067 	ASSERT(nfs_zone() == mi->mi_zone);
13068 
13069 	/*
13070 	 * Switch from RDMA knconf to original mount knconf
13071 	 */
13072 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
13073 	    mi->mi_curr_serv->sv_hostname, NULL));
13074 }
13075 
13076 #ifdef DEBUG
13077 /*
13078  * Return a string version of the call type for easy reading.
13079  */
13080 static char *
13081 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
13082 {
13083 	switch (ctype) {
13084 	case NFS4_LCK_CTYPE_NORM:
13085 		return ("NORMAL");
13086 	case NFS4_LCK_CTYPE_RECLAIM:
13087 		return ("RECLAIM");
13088 	case NFS4_LCK_CTYPE_RESEND:
13089 		return ("RESEND");
13090 	case NFS4_LCK_CTYPE_REINSTATE:
13091 		return ("REINSTATE");
13092 	default:
13093 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
13094 		    "type %d", ctype);
13095 		return ("");
13096 	}
13097 }
13098 #endif
13099 
13100 /*
13101  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
13102  * Unlock requests don't have an over-the-wire locktype, so we just return
13103  * something non-threatening.
13104  */
13105 
13106 static nfs_lock_type4
13107 flk_to_locktype(int cmd, int l_type)
13108 {
13109 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
13110 
13111 	switch (l_type) {
13112 	case F_UNLCK:
13113 		return (READ_LT);
13114 	case F_RDLCK:
13115 		if (cmd == F_SETLK)
13116 			return (READ_LT);
13117 		else
13118 			return (READW_LT);
13119 	case F_WRLCK:
13120 		if (cmd == F_SETLK)
13121 			return (WRITE_LT);
13122 		else
13123 			return (WRITEW_LT);
13124 	}
13125 	panic("flk_to_locktype");
13126 	/*NOTREACHED*/
13127 }
13128 
13129 /*
13130  * Set the flock64's lm_sysid for nfs4frlock.
13131  */
13132 static int
13133 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
13134 {
13135 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13136 
13137 	/* Find the lm_sysid */
13138 	*lspp = nfs4_find_sysid(VTOMI4(vp));
13139 
13140 	if (*lspp == NULL) {
13141 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13142 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
13143 		return (ENOLCK);
13144 	}
13145 
13146 	flk->l_sysid = lm_sysidt(*lspp);
13147 
13148 	return (0);
13149 }
13150 
13151 /*
13152  * Do the remaining preliminary setup for nfs4frlock.
13153  */
13154 static void
13155 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
13156     vnode_t *vp, cred_t *search_cr, cred_t **cred_otw)
13157 {
13158 	/*
13159 	 * set tick_delay to the base delay time.
13160 	 * (nfs4_base_wait_time is in msecs)
13161 	 */
13162 
13163 	*tick_delayp = drv_usectohz(nfs4_base_wait_time * 1000);
13164 
13165 	recov_statep->rs_flags = 0;
13166 	recov_statep->rs_num_retry_despite_err = 0;
13167 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
13168 }
13169 
13170 /*
13171  * Initialize and allocate the data structures necessary for
13172  * the nfs4frlock call.
13173  * Allocates argsp's op array, frees up the saved_rqstpp if there is one.
13174  */
13175 static void
13176 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
13177     nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
13178     bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
13179     bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
13180 {
13181 	int		argoplist_size;
13182 	int		num_ops = 2;
13183 
13184 	*retry = FALSE;
13185 	*did_start_fop = FALSE;
13186 	*skip_get_err = FALSE;
13187 	lost_rqstp->lr_op = 0;
13188 	argoplist_size  = num_ops * sizeof (nfs_argop4);
13189 	/* fill array with zero */
13190 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
13191 
13192 	*argspp = argsp;
13193 	*respp = NULL;
13194 
13195 	argsp->array_len = num_ops;
13196 	argsp->array = *argopp;
13197 
13198 	/* initialize in case of error; will get real value down below */
13199 	argsp->ctag = TAG_NONE;
13200 
13201 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
13202 		*op_hintp = OH_LOCKU;
13203 	else
13204 		*op_hintp = OH_OTHER;
13205 }
13206 
13207 /*
13208  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
13209  * the proper nfs4_server_t for this instance of nfs4frlock.
13210  * Returns 0 (success) or an errno value.
13211  */
13212 static int
13213 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
13214     nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
13215     bool_t *did_start_fop, bool_t *startrecovp)
13216 {
13217 	int error = 0;
13218 	rnode4_t *rp;
13219 
13220 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13221 
13222 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13223 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
13224 		    recov_statep, startrecovp);
13225 		if (error)
13226 			return (error);
13227 		*did_start_fop = TRUE;
13228 	} else {
13229 		*did_start_fop = FALSE;
13230 		*startrecovp = FALSE;
13231 	}
13232 
13233 	if (!error) {
13234 		rp = VTOR4(vp);
13235 
13236 		/* If the file failed recovery, just quit. */
13237 		mutex_enter(&rp->r_statelock);
13238 		if (rp->r_flags & R4RECOVERR) {
13239 			error = EIO;
13240 		}
13241 		mutex_exit(&rp->r_statelock);
13242 	}
13243 
13244 	return (error);
13245 }
13246 
13247 /*
13248  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
13249  * resend nfs4frlock call is initiated by the recovery framework.
13250  * Acquires the lop and oop seqid synchronization.
13251  */
13252 static void
13253 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
13254     COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
13255     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13256     LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
13257 {
13258 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
13259 	int error;
13260 
13261 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
13262 	    (CE_NOTE,
13263 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
13264 	ASSERT(resend_rqstp != NULL);
13265 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
13266 	    resend_rqstp->lr_op == OP_LOCKU);
13267 
13268 	*oopp = resend_rqstp->lr_oop;
13269 	if (resend_rqstp->lr_oop) {
13270 		open_owner_hold(resend_rqstp->lr_oop);
13271 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
13272 		ASSERT(error == 0);	/* recov thread always succeeds */
13273 	}
13274 
13275 	/* Must resend this lost lock/locku request. */
13276 	ASSERT(resend_rqstp->lr_lop != NULL);
13277 	*lopp = resend_rqstp->lr_lop;
13278 	lock_owner_hold(resend_rqstp->lr_lop);
13279 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
13280 	ASSERT(error == 0);	/* recov thread always succeeds */
13281 
13282 	*ospp = resend_rqstp->lr_osp;
13283 	if (*ospp)
13284 		open_stream_hold(resend_rqstp->lr_osp);
13285 
13286 	if (resend_rqstp->lr_op == OP_LOCK) {
13287 		LOCK4args *lock_args;
13288 
13289 		argop->argop = OP_LOCK;
13290 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
13291 		lock_args->locktype = resend_rqstp->lr_locktype;
13292 		lock_args->reclaim =
13293 		    (resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
13294 		lock_args->offset = resend_rqstp->lr_flk->l_start;
13295 		lock_args->length = resend_rqstp->lr_flk->l_len;
13296 		if (lock_args->length == 0)
13297 			lock_args->length = ~lock_args->length;
13298 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
13299 		    mi2clientid(mi), &lock_args->locker);
13300 
13301 		switch (resend_rqstp->lr_ctype) {
13302 		case NFS4_LCK_CTYPE_RESEND:
13303 			argsp->ctag = TAG_LOCK_RESEND;
13304 			break;
13305 		case NFS4_LCK_CTYPE_REINSTATE:
13306 			argsp->ctag = TAG_LOCK_REINSTATE;
13307 			break;
13308 		case NFS4_LCK_CTYPE_RECLAIM:
13309 			argsp->ctag = TAG_LOCK_RECLAIM;
13310 			break;
13311 		default:
13312 			argsp->ctag = TAG_LOCK_UNKNOWN;
13313 			break;
13314 		}
13315 	} else {
13316 		LOCKU4args *locku_args;
13317 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
13318 
13319 		argop->argop = OP_LOCKU;
13320 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
13321 		locku_args->locktype = READ_LT;
13322 		locku_args->seqid = lop->lock_seqid + 1;
13323 		mutex_enter(&lop->lo_lock);
13324 		locku_args->lock_stateid = lop->lock_stateid;
13325 		mutex_exit(&lop->lo_lock);
13326 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13327 		locku_args->length = resend_rqstp->lr_flk->l_len;
13328 		if (locku_args->length == 0)
13329 			locku_args->length = ~locku_args->length;
13330 
13331 		switch (resend_rqstp->lr_ctype) {
13332 		case NFS4_LCK_CTYPE_RESEND:
13333 			argsp->ctag = TAG_LOCKU_RESEND;
13334 			break;
13335 		case NFS4_LCK_CTYPE_REINSTATE:
13336 			argsp->ctag = TAG_LOCKU_REINSTATE;
13337 			break;
13338 		default:
13339 			argsp->ctag = TAG_LOCK_UNKNOWN;
13340 			break;
13341 		}
13342 	}
13343 }
13344 
13345 /*
13346  * Setup the LOCKT4 arguments.
13347  */
13348 static void
13349 nfs4frlock_setup_lockt_args(nfs_argop4 *argop, LOCKT4args **lockt_argsp,
13350     COMPOUND4args_clnt *argsp, flock64_t *flk, rnode4_t *rp)
13351 {
13352 	LOCKT4args *lockt_args;
13353 
13354 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13355 	argop->argop = OP_LOCKT;
13356 	argsp->ctag = TAG_LOCKT;
13357 	lockt_args = &argop->nfs_argop4_u.oplockt;
13358 
13359 	/*
13360 	 * The locktype will be READ_LT unless it's
13361 	 * a write lock. We do this because the Solaris
13362 	 * system call allows the combination of
13363 	 * F_UNLCK and F_GETLK* and so in that case the
13364 	 * unlock is mapped to a read.
13365 	 */
13366 	if (flk->l_type == F_WRLCK)
13367 		lockt_args->locktype = WRITE_LT;
13368 	else
13369 		lockt_args->locktype = READ_LT;
13370 
13371 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13372 	/* set the lock owner4 args */
13373 	nfs4_setlockowner_args(&lockt_args->owner, rp, flk->l_pid);
13374 	lockt_args->offset = flk->l_start;
13375 	lockt_args->length = flk->l_len;
13376 	if (flk->l_len == 0)
13377 		lockt_args->length = ~lockt_args->length;
13378 
13379 	*lockt_argsp = lockt_args;
13380 }
13381 
13382 /*
13383  * If the client is holding a delegation, and the open stream to be used
13384  * with this lock request is a delegation open stream, then re-open the stream.
13385  * Sets the nfs4_error_t to all zeros unless the open stream has already
13386  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13387  * means the caller should retry (like a recovery retry).
13388  */
13389 static void
13390 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13391 {
13392 	open_delegation_type4	dt;
13393 	bool_t			reopen_needed, force;
13394 	nfs4_open_stream_t	*osp;
13395 	open_claim_type4	oclaim;
13396 	rnode4_t		*rp = VTOR4(vp);
13397 	mntinfo4_t		*mi = VTOMI4(vp);
13398 
13399 	ASSERT(nfs_zone() == mi->mi_zone);
13400 
13401 	nfs4_error_zinit(ep);
13402 
13403 	mutex_enter(&rp->r_statev4_lock);
13404 	dt = rp->r_deleg_type;
13405 	mutex_exit(&rp->r_statev4_lock);
13406 
13407 	if (dt != OPEN_DELEGATE_NONE) {
13408 		nfs4_open_owner_t	*oop;
13409 
13410 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13411 		if (!oop) {
13412 			ep->stat = NFS4ERR_IO;
13413 			return;
13414 		}
13415 		/* returns with 'os_sync_lock' held */
13416 		osp = find_open_stream(oop, rp);
13417 		if (!osp) {
13418 			open_owner_rele(oop);
13419 			ep->stat = NFS4ERR_IO;
13420 			return;
13421 		}
13422 
13423 		if (osp->os_failed_reopen) {
13424 			NFS4_DEBUG((nfs4_open_stream_debug ||
13425 			    nfs4_client_lock_debug), (CE_NOTE,
13426 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13427 			    "for osp %p, cr %p, rp %s", (void *)osp,
13428 			    (void *)cr, rnode4info(rp)));
13429 			mutex_exit(&osp->os_sync_lock);
13430 			open_stream_rele(osp, rp);
13431 			open_owner_rele(oop);
13432 			ep->stat = NFS4ERR_IO;
13433 			return;
13434 		}
13435 
13436 		/*
13437 		 * Determine whether a reopen is needed.  If this
13438 		 * is a delegation open stream, then send the open
13439 		 * to the server to give visibility to the open owner.
13440 		 * Even if it isn't a delegation open stream, we need
13441 		 * to check if the previous open CLAIM_DELEGATE_CUR
13442 		 * was sufficient.
13443 		 */
13444 
13445 		reopen_needed = osp->os_delegation ||
13446 		    ((lt == F_RDLCK &&
13447 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13448 		    (lt == F_WRLCK &&
13449 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13450 
13451 		mutex_exit(&osp->os_sync_lock);
13452 		open_owner_rele(oop);
13453 
13454 		if (reopen_needed) {
13455 			/*
13456 			 * Always use CLAIM_PREVIOUS after server reboot.
13457 			 * The server will reject CLAIM_DELEGATE_CUR if
13458 			 * it is used during the grace period.
13459 			 */
13460 			mutex_enter(&mi->mi_lock);
13461 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13462 				oclaim = CLAIM_PREVIOUS;
13463 				force = TRUE;
13464 			} else {
13465 				oclaim = CLAIM_DELEGATE_CUR;
13466 				force = FALSE;
13467 			}
13468 			mutex_exit(&mi->mi_lock);
13469 
13470 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13471 			if (ep->error == EAGAIN) {
13472 				nfs4_error_zinit(ep);
13473 				ep->stat = NFS4ERR_DELAY;
13474 			}
13475 		}
13476 		open_stream_rele(osp, rp);
13477 		osp = NULL;
13478 	}
13479 }
13480 
13481 /*
13482  * Setup the LOCKU4 arguments.
13483  * Returns errors via the nfs4_error_t.
13484  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13485  *			over-the-wire.  The caller must release the
13486  *			reference on *lopp.
13487  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13488  * (other)		unrecoverable error.
13489  */
13490 static void
13491 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13492     LOCKU4args **locku_argsp, flock64_t *flk,
13493     nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13494     vnode_t *vp, cred_t *cr, bool_t *skip_get_err, bool_t *go_otwp)
13495 {
13496 	nfs4_lock_owner_t	*lop = NULL;
13497 	LOCKU4args		*locku_args;
13498 	pid_t			pid = flk->l_pid;
13499 	bool_t			is_spec = FALSE;
13500 	rnode4_t		*rp = VTOR4(vp);
13501 
13502 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13503 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13504 
13505 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13506 	if (ep->error || ep->stat)
13507 		return;
13508 
13509 	argop->argop = OP_LOCKU;
13510 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13511 		argsp->ctag = TAG_LOCKU_REINSTATE;
13512 	else
13513 		argsp->ctag = TAG_LOCKU;
13514 	locku_args = &argop->nfs_argop4_u.oplocku;
13515 	*locku_argsp = locku_args;
13516 
13517 	/*
13518 	 * XXX what should locku_args->locktype be?
13519 	 * setting to ALWAYS be READ_LT so at least
13520 	 * it is a valid locktype.
13521 	 */
13522 
13523 	locku_args->locktype = READ_LT;
13524 
13525 	/*
13526 	 * Get the lock owner stateid.  If no lock owner
13527 	 * exists, return success.
13528 	 */
13529 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13530 	*lopp = lop;
13531 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13532 		is_spec = TRUE;
13533 	if (!lop || is_spec) {
13534 		/*
13535 		 * No lock owner so no locks to unlock.
13536 		 * Return success.
13537 		 *
13538 		 * If the lockowner is using a special stateid,
13539 		 * then the original lock request (that created
13540 		 * this lockowner) was never successful, so we
13541 		 * have no lock to undo OTW.
13542 		 */
13543 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13544 		    "nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13545 		    "(%ld) so return success", (long)pid));
13546 
13547 		/*
13548 		 * Release our hold and NULL out so final_cleanup
13549 		 * doesn't try to end a lock seqid sync we
13550 		 * never started.
13551 		 */
13552 		if (is_spec) {
13553 			lock_owner_rele(lop);
13554 			*lopp = NULL;
13555 		}
13556 		*skip_get_err = TRUE;
13557 		*go_otwp = FALSE;
13558 		return;
13559 	}
13560 
13561 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13562 	if (ep->error == EAGAIN) {
13563 		lock_owner_rele(lop);
13564 		*lopp = NULL;
13565 		return;
13566 	}
13567 
13568 	mutex_enter(&lop->lo_lock);
13569 	locku_args->lock_stateid = lop->lock_stateid;
13570 	mutex_exit(&lop->lo_lock);
13571 	locku_args->seqid = lop->lock_seqid + 1;
13572 
13573 	/* leave the ref count on lop, rele after RPC call */
13574 
13575 	locku_args->offset = flk->l_start;
13576 	locku_args->length = flk->l_len;
13577 	if (flk->l_len == 0)
13578 		locku_args->length = ~locku_args->length;
13579 
13580 	*go_otwp = TRUE;
13581 }
13582 
13583 /*
13584  * Setup the LOCK4 arguments.
13585  *
13586  * Returns errors via the nfs4_error_t.
13587  * NFS4_OK		no problems
13588  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13589  * (other)		unrecoverable error
13590  */
13591 static void
13592 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13593     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13594     nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13595     flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13596 {
13597 	LOCK4args		*lock_args;
13598 	nfs4_open_owner_t	*oop = NULL;
13599 	nfs4_open_stream_t	*osp = NULL;
13600 	nfs4_lock_owner_t	*lop = NULL;
13601 	pid_t			pid = flk->l_pid;
13602 	rnode4_t		*rp = VTOR4(vp);
13603 
13604 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13605 
13606 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13607 	if (ep->error || ep->stat != NFS4_OK)
13608 		return;
13609 
13610 	argop->argop = OP_LOCK;
13611 	if (ctype == NFS4_LCK_CTYPE_NORM)
13612 		argsp->ctag = TAG_LOCK;
13613 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13614 		argsp->ctag = TAG_RELOCK;
13615 	else
13616 		argsp->ctag = TAG_LOCK_REINSTATE;
13617 	lock_args = &argop->nfs_argop4_u.oplock;
13618 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13619 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13620 	/*
13621 	 * Get the lock owner.  If no lock owner exists,
13622 	 * create a 'temporary' one and grab the open seqid
13623 	 * synchronization (which puts a hold on the open
13624 	 * owner and open stream).
13625 	 * This also grabs the lock seqid synchronization.
13626 	 */
13627 	ep->stat =
13628 	    nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13629 
13630 	if (ep->stat != NFS4_OK)
13631 		goto out;
13632 
13633 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13634 	    &lock_args->locker);
13635 
13636 	lock_args->offset = flk->l_start;
13637 	lock_args->length = flk->l_len;
13638 	if (flk->l_len == 0)
13639 		lock_args->length = ~lock_args->length;
13640 	*lock_argsp = lock_args;
13641 out:
13642 	*oopp = oop;
13643 	*ospp = osp;
13644 	*lopp = lop;
13645 }
13646 
13647 /*
13648  * After we get the reply from the server, record the proper information
13649  * for possible resend lock requests.
13650  *
13651  * Allocates memory for the saved_rqstp if we have a lost lock to save.
13652  */
13653 static void
13654 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13655     nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13656     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13657     nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13658 {
13659 	bool_t unlock = (flk->l_type == F_UNLCK);
13660 
13661 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13662 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13663 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13664 
13665 	if (error != 0 && !unlock) {
13666 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13667 		    nfs4_client_lock_debug), (CE_NOTE,
13668 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13669 		    " for lop %p", (void *)lop));
13670 		ASSERT(lop != NULL);
13671 		mutex_enter(&lop->lo_lock);
13672 		lop->lo_pending_rqsts = 1;
13673 		mutex_exit(&lop->lo_lock);
13674 	}
13675 
13676 	lost_rqstp->lr_putfirst = FALSE;
13677 	lost_rqstp->lr_op = 0;
13678 
13679 	/*
13680 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13681 	 * recovery purposes so that the lock request that was sent
13682 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13683 	 * unmount.  This is done to have the client's local locking state
13684 	 * match the v4 server's state; that is, the request was
13685 	 * potentially received and accepted by the server but the client
13686 	 * thinks it was not.
13687 	 */
13688 	if (error == ETIMEDOUT || error == EINTR ||
13689 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13690 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13691 		    nfs4_client_lock_debug), (CE_NOTE,
13692 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13693 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13694 		    (void *)lop, (void *)oop, (void *)osp));
13695 		if (unlock)
13696 			lost_rqstp->lr_op = OP_LOCKU;
13697 		else {
13698 			lost_rqstp->lr_op = OP_LOCK;
13699 			lost_rqstp->lr_locktype = locktype;
13700 		}
13701 		/*
13702 		 * Objects are held and rele'd via the recovery code.
13703 		 * See nfs4_save_lost_rqst.
13704 		 */
13705 		lost_rqstp->lr_vp = vp;
13706 		lost_rqstp->lr_dvp = NULL;
13707 		lost_rqstp->lr_oop = oop;
13708 		lost_rqstp->lr_osp = osp;
13709 		lost_rqstp->lr_lop = lop;
13710 		lost_rqstp->lr_cr = cr;
13711 		switch (ctype) {
13712 		case NFS4_LCK_CTYPE_NORM:
13713 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13714 			break;
13715 		case NFS4_LCK_CTYPE_REINSTATE:
13716 			lost_rqstp->lr_putfirst = TRUE;
13717 			lost_rqstp->lr_ctype = ctype;
13718 			break;
13719 		default:
13720 			break;
13721 		}
13722 		lost_rqstp->lr_flk = flk;
13723 	}
13724 }
13725 
13726 /*
13727  * Update lop's seqid.  Also update the seqid stored in a resend request,
13728  * if any.  (Some recovery errors increment the seqid, and we may have to
13729  * send the resend request again.)
13730  */
13731 
13732 static void
13733 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13734     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13735 {
13736 	if (lock_args) {
13737 		if (lock_args->locker.new_lock_owner == TRUE)
13738 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13739 		else {
13740 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13741 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13742 		}
13743 	} else if (locku_args) {
13744 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13745 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13746 	}
13747 }
13748 
13749 /*
13750  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13751  * COMPOUND4 args/res for calls that need to retry.
13752  * Switches the *cred_otwp to base_cr.
13753  */
13754 static void
13755 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13756     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13757     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13758     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13759     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13760 {
13761 	nfs4_open_owner_t	*oop = *oopp;
13762 	nfs4_open_stream_t	*osp = *ospp;
13763 	nfs4_lock_owner_t	*lop = *lopp;
13764 	nfs_argop4		*argop = (*argspp)->array;
13765 
13766 	if (*did_start_fop) {
13767 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13768 		    needrecov);
13769 		*did_start_fop = FALSE;
13770 	}
13771 	ASSERT((*argspp)->array_len == 2);
13772 	if (argop[1].argop == OP_LOCK)
13773 		nfs4args_lock_free(&argop[1]);
13774 	else if (argop[1].argop == OP_LOCKT)
13775 		nfs4args_lockt_free(&argop[1]);
13776 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13777 	if (!error)
13778 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13779 	*argspp = NULL;
13780 	*respp = NULL;
13781 
13782 	if (lop) {
13783 		nfs4_end_lock_seqid_sync(lop);
13784 		lock_owner_rele(lop);
13785 		*lopp = NULL;
13786 	}
13787 
13788 	/* need to free up the reference on osp for lock args */
13789 	if (osp != NULL) {
13790 		open_stream_rele(osp, VTOR4(vp));
13791 		*ospp = NULL;
13792 	}
13793 
13794 	/* need to free up the reference on oop for lock args */
13795 	if (oop != NULL) {
13796 		nfs4_end_open_seqid_sync(oop);
13797 		open_owner_rele(oop);
13798 		*oopp = NULL;
13799 	}
13800 
13801 	crfree(*cred_otwp);
13802 	*cred_otwp = base_cr;
13803 	crhold(*cred_otwp);
13804 }
13805 
13806 /*
13807  * Function to process the client's recovery for nfs4frlock.
13808  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13809  *
13810  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13811  * COMPOUND4 args/res for calls that need to retry.
13812  *
13813  * Note: the rp's r_lkserlock is *not* dropped during this path.
13814  */
13815 static bool_t
13816 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13817     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13818     LOCK4args *lock_args, LOCKU4args *locku_args,
13819     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13820     nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13821     nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13822     bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13823 {
13824 	nfs4_open_owner_t	*oop = *oopp;
13825 	nfs4_open_stream_t	*osp = *ospp;
13826 	nfs4_lock_owner_t	*lop = *lopp;
13827 
13828 	bool_t abort, retry;
13829 
13830 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13831 	ASSERT((*argspp) != NULL);
13832 	ASSERT((*respp) != NULL);
13833 	if (lock_args || locku_args)
13834 		ASSERT(lop != NULL);
13835 
13836 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13837 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13838 
13839 	retry = TRUE;
13840 	abort = FALSE;
13841 	if (needrecov) {
13842 		nfs4_bseqid_entry_t *bsep = NULL;
13843 		nfs_opnum4 op;
13844 
13845 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13846 
13847 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13848 			seqid4 seqid;
13849 
13850 			if (lock_args) {
13851 				if (lock_args->locker.new_lock_owner == TRUE)
13852 					seqid = lock_args->locker.locker4_u.
13853 					    open_owner.open_seqid;
13854 				else
13855 					seqid = lock_args->locker.locker4_u.
13856 					    lock_owner.lock_seqid;
13857 			} else if (locku_args) {
13858 				seqid = locku_args->seqid;
13859 			} else {
13860 				seqid = 0;
13861 			}
13862 
13863 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13864 			    flk->l_pid, (*argspp)->ctag, seqid);
13865 		}
13866 
13867 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13868 		    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13869 		    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13870 		    NULL, op, bsep, NULL, NULL);
13871 
13872 		if (bsep)
13873 			kmem_free(bsep, sizeof (*bsep));
13874 	}
13875 
13876 	/*
13877 	 * Return that we do not want to retry the request for 3 cases:
13878 	 * 1. If we received EINTR or are bailing out because of a forced
13879 	 *    unmount, we came into this code path just for the sake of
13880 	 *    initiating recovery, we now need to return the error.
13881 	 * 2. If we have aborted recovery.
13882 	 * 3. We received NFS4ERR_BAD_SEQID.
13883 	 */
13884 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13885 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13886 		retry = FALSE;
13887 
13888 	if (*did_start_fop == TRUE) {
13889 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13890 		    needrecov);
13891 		*did_start_fop = FALSE;
13892 	}
13893 
13894 	if (retry == TRUE) {
13895 		nfs_argop4	*argop;
13896 
13897 		argop = (*argspp)->array;
13898 		ASSERT((*argspp)->array_len == 2);
13899 
13900 		if (argop[1].argop == OP_LOCK)
13901 			nfs4args_lock_free(&argop[1]);
13902 		else if (argop[1].argop == OP_LOCKT)
13903 			nfs4args_lockt_free(&argop[1]);
13904 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13905 		if (!ep->error)
13906 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13907 		*respp = NULL;
13908 		*argspp = NULL;
13909 	}
13910 
13911 	if (lop != NULL) {
13912 		nfs4_end_lock_seqid_sync(lop);
13913 		lock_owner_rele(lop);
13914 	}
13915 
13916 	*lopp = NULL;
13917 
13918 	/* need to free up the reference on osp for lock args */
13919 	if (osp != NULL) {
13920 		open_stream_rele(osp, rp);
13921 		*ospp = NULL;
13922 	}
13923 
13924 	/* need to free up the reference on oop for lock args */
13925 	if (oop != NULL) {
13926 		nfs4_end_open_seqid_sync(oop);
13927 		open_owner_rele(oop);
13928 		*oopp = NULL;
13929 	}
13930 
13931 	return (retry);
13932 }
13933 
13934 /*
13935  * Handle the DENIED reply from the server for nfs4frlock.
13936  * Returns TRUE if we should retry the request; FALSE otherwise.
13937  *
13938  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13939  * COMPOUND4 args/res for calls that need to retry.  Can also
13940  * drop and regrab the r_lkserlock.
13941  */
13942 static bool_t
13943 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13944     LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13945     nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13946     vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13947     nfs4_recov_state_t *recov_statep, int needrecov,
13948     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13949     clock_t *tick_delayp, int *errorp,
13950     nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13951     bool_t *skip_get_err)
13952 {
13953 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13954 
13955 	if (lock_args) {
13956 		nfs4_open_owner_t	*oop = *oopp;
13957 		nfs4_open_stream_t	*osp = *ospp;
13958 		nfs4_lock_owner_t	*lop = *lopp;
13959 		int			intr;
13960 
13961 		/*
13962 		 * Blocking lock needs to sleep and retry from the request.
13963 		 *
13964 		 * Do not block and wait for 'resend' or 'reinstate'
13965 		 * lock requests, just return the error.
13966 		 *
13967 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13968 		 */
13969 		if (cmd == F_SETLKW) {
13970 			rnode4_t *rp = VTOR4(vp);
13971 			nfs_argop4 *argop = (*argspp)->array;
13972 
13973 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13974 
13975 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13976 			    recov_statep, needrecov);
13977 			*did_start_fop = FALSE;
13978 			ASSERT((*argspp)->array_len == 2);
13979 			if (argop[1].argop == OP_LOCK)
13980 				nfs4args_lock_free(&argop[1]);
13981 			else if (argop[1].argop == OP_LOCKT)
13982 				nfs4args_lockt_free(&argop[1]);
13983 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13984 			if (*respp)
13985 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13986 				    (caddr_t)*respp);
13987 			*argspp = NULL;
13988 			*respp = NULL;
13989 			nfs4_end_lock_seqid_sync(lop);
13990 			lock_owner_rele(lop);
13991 			*lopp = NULL;
13992 			if (osp != NULL) {
13993 				open_stream_rele(osp, rp);
13994 				*ospp = NULL;
13995 			}
13996 			if (oop != NULL) {
13997 				nfs4_end_open_seqid_sync(oop);
13998 				open_owner_rele(oop);
13999 				*oopp = NULL;
14000 			}
14001 
14002 			nfs_rw_exit(&rp->r_lkserlock);
14003 
14004 			intr = nfs4_block_and_wait(tick_delayp);
14005 
14006 			(void) nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER,
14007 			    FALSE);
14008 
14009 			if (intr) {
14010 				*errorp = EINTR;
14011 				return (FALSE);
14012 			}
14013 
14014 			/*
14015 			 * Make sure we are still safe to lock with
14016 			 * regards to mmapping.
14017 			 */
14018 			if (!nfs4_safelock(vp, flk, cr)) {
14019 				*errorp = EAGAIN;
14020 				return (FALSE);
14021 			}
14022 
14023 			return (TRUE);
14024 		}
14025 		if (ctype == NFS4_LCK_CTYPE_NORM)
14026 			*errorp = EAGAIN;
14027 		*skip_get_err = TRUE;
14028 		flk->l_whence = 0;
14029 		return (FALSE);
14030 	} else if (lockt_args) {
14031 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14032 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
14033 
14034 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
14035 		    flk, lockt_args);
14036 
14037 		/* according to NLM code */
14038 		*errorp = 0;
14039 		*skip_get_err = TRUE;
14040 		return (FALSE);
14041 	}
14042 	return (FALSE);
14043 }
14044 
14045 /*
14046  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
14047  */
14048 static void
14049 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
14050 {
14051 	switch (resp->status) {
14052 	case NFS4ERR_ACCESS:
14053 	case NFS4ERR_ADMIN_REVOKED:
14054 	case NFS4ERR_BADHANDLE:
14055 	case NFS4ERR_BAD_RANGE:
14056 	case NFS4ERR_BAD_SEQID:
14057 	case NFS4ERR_BAD_STATEID:
14058 	case NFS4ERR_BADXDR:
14059 	case NFS4ERR_DEADLOCK:
14060 	case NFS4ERR_DELAY:
14061 	case NFS4ERR_EXPIRED:
14062 	case NFS4ERR_FHEXPIRED:
14063 	case NFS4ERR_GRACE:
14064 	case NFS4ERR_INVAL:
14065 	case NFS4ERR_ISDIR:
14066 	case NFS4ERR_LEASE_MOVED:
14067 	case NFS4ERR_LOCK_NOTSUPP:
14068 	case NFS4ERR_LOCK_RANGE:
14069 	case NFS4ERR_MOVED:
14070 	case NFS4ERR_NOFILEHANDLE:
14071 	case NFS4ERR_NO_GRACE:
14072 	case NFS4ERR_OLD_STATEID:
14073 	case NFS4ERR_OPENMODE:
14074 	case NFS4ERR_RECLAIM_BAD:
14075 	case NFS4ERR_RECLAIM_CONFLICT:
14076 	case NFS4ERR_RESOURCE:
14077 	case NFS4ERR_SERVERFAULT:
14078 	case NFS4ERR_STALE:
14079 	case NFS4ERR_STALE_CLIENTID:
14080 	case NFS4ERR_STALE_STATEID:
14081 		return;
14082 	default:
14083 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14084 		    "nfs4frlock_results_default: got unrecognizable "
14085 		    "res.status %d", resp->status));
14086 		*errorp = NFS4ERR_INVAL;
14087 	}
14088 }
14089 
14090 /*
14091  * The lock request was successful, so update the client's state.
14092  */
14093 static void
14094 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
14095     LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
14096     vnode_t *vp, flock64_t *flk, cred_t *cr,
14097     nfs4_lost_rqst_t *resend_rqstp)
14098 {
14099 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14100 
14101 	if (lock_args) {
14102 		LOCK4res *lock_res;
14103 
14104 		lock_res = &resop->nfs_resop4_u.oplock;
14105 		/* update the stateid with server's response */
14106 
14107 		if (lock_args->locker.new_lock_owner == TRUE) {
14108 			mutex_enter(&lop->lo_lock);
14109 			lop->lo_just_created = NFS4_PERM_CREATED;
14110 			mutex_exit(&lop->lo_lock);
14111 		}
14112 
14113 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
14114 
14115 		/*
14116 		 * If the lock was the result of a resending a lost
14117 		 * request, we've synched up the stateid and seqid
14118 		 * with the server, but now the server might be out of sync
14119 		 * with what the application thinks it has for locks.
14120 		 * Clean that up here.  It's unclear whether we should do
14121 		 * this even if the filesystem has been forcibly unmounted.
14122 		 * For most servers, it's probably wasted effort, but
14123 		 * RFC3530 lets servers require that unlocks exactly match
14124 		 * the locks that are held.
14125 		 */
14126 		if (resend_rqstp != NULL &&
14127 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
14128 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
14129 		} else {
14130 			flk->l_whence = 0;
14131 		}
14132 	} else if (locku_args) {
14133 		LOCKU4res *locku_res;
14134 
14135 		locku_res = &resop->nfs_resop4_u.oplocku;
14136 
14137 		/* Update the stateid with the server's response */
14138 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
14139 	} else if (lockt_args) {
14140 		/* Switch the lock type to express success, see fcntl */
14141 		flk->l_type = F_UNLCK;
14142 		flk->l_whence = 0;
14143 	}
14144 }
14145 
14146 /*
14147  * Do final cleanup before exiting nfs4frlock.
14148  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
14149  * COMPOUND4 args/res for calls that haven't already.
14150  */
14151 static void
14152 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
14153     COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
14154     nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
14155     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop,
14156     int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
14157     bool_t did_start_fop, bool_t skip_get_err,
14158     cred_t *cred_otw, cred_t *cred)
14159 {
14160 	mntinfo4_t	*mi = VTOMI4(vp);
14161 	rnode4_t	*rp = VTOR4(vp);
14162 	int		error = *errorp;
14163 	nfs_argop4	*argop;
14164 	int	do_flush_pages = 0;
14165 
14166 	ASSERT(nfs_zone() == mi->mi_zone);
14167 	/*
14168 	 * The client recovery code wants the raw status information,
14169 	 * so don't map the NFS status code to an errno value for
14170 	 * non-normal call types.
14171 	 */
14172 	if (ctype == NFS4_LCK_CTYPE_NORM) {
14173 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
14174 			*errorp = geterrno4(resp->status);
14175 		if (did_start_fop == TRUE)
14176 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
14177 			    needrecov);
14178 
14179 		/*
14180 		 * We've established a new lock on the server, so invalidate
14181 		 * the pages associated with the vnode to get the most up to
14182 		 * date pages from the server after acquiring the lock. We
14183 		 * want to be sure that the read operation gets the newest data.
14184 		 *
14185 		 * We flush the pages below after calling nfs4_end_fop above.
14186 		 *
14187 		 * The flush of the page cache must be done after
14188 		 * nfs4_end_open_seqid_sync() to avoid a 4-way hang.
14189 		 */
14190 		if (!error && resp && resp->status == NFS4_OK)
14191 			do_flush_pages = 1;
14192 	}
14193 	if (argsp) {
14194 		ASSERT(argsp->array_len == 2);
14195 		argop = argsp->array;
14196 		if (argop[1].argop == OP_LOCK)
14197 			nfs4args_lock_free(&argop[1]);
14198 		else if (argop[1].argop == OP_LOCKT)
14199 			nfs4args_lockt_free(&argop[1]);
14200 		kmem_free(argop, 2 * sizeof (nfs_argop4));
14201 		if (resp)
14202 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
14203 	}
14204 
14205 	/* free the reference on the lock owner */
14206 	if (lop != NULL) {
14207 		nfs4_end_lock_seqid_sync(lop);
14208 		lock_owner_rele(lop);
14209 	}
14210 
14211 	/* need to free up the reference on osp for lock args */
14212 	if (osp != NULL)
14213 		open_stream_rele(osp, rp);
14214 
14215 	/* need to free up the reference on oop for lock args */
14216 	if (oop != NULL) {
14217 		nfs4_end_open_seqid_sync(oop);
14218 		open_owner_rele(oop);
14219 	}
14220 
14221 	if (do_flush_pages)
14222 		nfs4_flush_pages(vp, cred);
14223 
14224 	/*
14225 	 * Record debug information in the event we get EINVAL.
14226 	 */
14227 	mutex_enter(&mi->mi_lock);
14228 	if (*errorp == EINVAL && (lock_args || locku_args) &&
14229 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
14230 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
14231 			zcmn_err(getzoneid(), CE_NOTE,
14232 			    "%s operation failed with "
14233 			    "EINVAL probably since the server, %s,"
14234 			    " doesn't support POSIX style locking",
14235 			    lock_args ? "LOCK" : "LOCKU",
14236 			    mi->mi_curr_serv->sv_hostname);
14237 			mi->mi_flags |= MI4_LOCK_DEBUG;
14238 		}
14239 	}
14240 	mutex_exit(&mi->mi_lock);
14241 
14242 	if (cred_otw)
14243 		crfree(cred_otw);
14244 }
14245 
14246 /*
14247  * This calls the server.
14248  *
14249  * Blocking lock requests will continually retry to acquire the lock
14250  * forever.
14251  *
14252  * The ctype is defined as follows:
14253  * NFS4_LCK_CTYPE_NORM: normal lock request.
14254  *
14255  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
14256  * recovery.
14257  *
14258  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
14259  * that we will use the information passed in via resend_rqstp to setup the
14260  * lock/locku request.  This resend is the exact same request as the 'lost
14261  * lock', and is initiated by the recovery framework. A successful resend
14262  * request can initiate one or more reinstate requests.
14263  *
14264  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14265  * does not trigger additional reinstate requests.  This lock call type is
14266  * set for setting the v4 server's locking state back to match what the
14267  * client's local locking state is in the event of a received 'lost lock'.
14268  *
14269  * Errors are returned via the nfs4_error_t parameter.
14270  */
14271 void
14272 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14273     cred_t *cr, nfs4_error_t *ep, nfs4_lost_rqst_t *resend_rqstp,
14274     int *did_reclaimp)
14275 {
14276 	COMPOUND4args_clnt	args, *argsp = NULL;
14277 	COMPOUND4res_clnt	res, *resp = NULL;
14278 	nfs_argop4	*argop;
14279 	nfs_resop4	*resop;
14280 	rnode4_t	*rp;
14281 	int		doqueue = 1;
14282 	clock_t		tick_delay;  /* delay in clock ticks */
14283 	LOCK4args	*lock_args = NULL;
14284 	LOCKU4args	*locku_args = NULL;
14285 	LOCKT4args	*lockt_args = NULL;
14286 	nfs4_open_owner_t *oop = NULL;
14287 	nfs4_open_stream_t *osp = NULL;
14288 	nfs4_lock_owner_t *lop = NULL;
14289 	bool_t		needrecov = FALSE;
14290 	nfs4_recov_state_t recov_state;
14291 	nfs4_op_hint_t	op_hint;
14292 	nfs4_lost_rqst_t lost_rqst;
14293 	bool_t		retry = FALSE;
14294 	bool_t		did_start_fop = FALSE;
14295 	bool_t		skip_get_err = FALSE;
14296 	cred_t		*cred_otw = NULL;
14297 	bool_t		recovonly;	/* just queue request */
14298 	int		frc_no_reclaim = 0;
14299 #ifdef DEBUG
14300 	char *name;
14301 #endif
14302 
14303 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14304 
14305 #ifdef DEBUG
14306 	name = fn_name(VTOSV(vp)->sv_name);
14307 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14308 	    "%s: cmd %d, type %d, start %"PRIx64", "
14309 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14310 	    "resend request %s", name, cmd, flk->l_type, flk->l_start,
14311 	    flk->l_len, flk->l_pid, flk->l_sysid,
14312 	    nfs4frlock_get_call_type(ctype),
14313 	    resend_rqstp ? "TRUE" : "FALSE"));
14314 	kmem_free(name, MAXNAMELEN);
14315 #endif
14316 
14317 	nfs4_error_zinit(ep);
14318 
14319 	nfs4frlock_pre_setup(&tick_delay, &recov_state, vp, cr, &cred_otw);
14320 
14321 	rp = VTOR4(vp);
14322 
14323 recov_retry:
14324 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14325 	    &retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14326 
14327 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14328 	    &did_start_fop, &recovonly);
14329 
14330 	if (ep->error)
14331 		goto out;
14332 
14333 	if (recovonly) {
14334 		/*
14335 		 * Leave the request for the recovery system to deal with.
14336 		 */
14337 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14338 		ASSERT(cmd != F_GETLK);
14339 		ASSERT(flk->l_type == F_UNLCK);
14340 
14341 		nfs4_error_init(ep, EINTR);
14342 		needrecov = TRUE;
14343 		lop = find_lock_owner(rp, flk->l_pid, LOWN_ANY);
14344 		if (lop != NULL) {
14345 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14346 			    NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14347 			(void) nfs4_start_recovery(ep,
14348 			    VTOMI4(vp), vp, NULL, NULL,
14349 			    (lost_rqst.lr_op == OP_LOCK ||
14350 			    lost_rqst.lr_op == OP_LOCKU) ?
14351 			    &lost_rqst : NULL, OP_LOCKU, NULL, NULL, NULL);
14352 			lock_owner_rele(lop);
14353 			lop = NULL;
14354 		}
14355 		goto out;
14356 	}
14357 
14358 	/* putfh directory fh */
14359 	argop[0].argop = OP_CPUTFH;
14360 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14361 
14362 	/*
14363 	 * Set up the over-the-wire arguments and get references to the
14364 	 * open owner, etc.
14365 	 */
14366 
14367 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14368 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14369 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14370 		    &argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14371 	} else {
14372 		bool_t go_otw = TRUE;
14373 
14374 		ASSERT(resend_rqstp == NULL);
14375 
14376 		switch (cmd) {
14377 		case F_GETLK:
14378 		case F_O_GETLK:
14379 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14380 			nfs4frlock_setup_lockt_args(&argop[1], &lockt_args,
14381 			    argsp, flk, rp);
14382 			break;
14383 		case F_SETLKW:
14384 		case F_SETLK:
14385 			if (flk->l_type == F_UNLCK)
14386 				nfs4frlock_setup_locku_args(ctype,
14387 				    &argop[1], &locku_args, flk,
14388 				    &lop, ep, argsp, vp, cr,
14389 				    &skip_get_err, &go_otw);
14390 			else
14391 				nfs4frlock_setup_lock_args(ctype,
14392 				    &lock_args, &oop, &osp, &lop, &argop[1],
14393 				    argsp, flk, cmd, vp, cr, ep);
14394 
14395 			if (ep->error)
14396 				goto out;
14397 
14398 			switch (ep->stat) {
14399 			case NFS4_OK:
14400 				break;
14401 			case NFS4ERR_DELAY:
14402 				/* recov thread never gets this error */
14403 				ASSERT(resend_rqstp == NULL);
14404 				ASSERT(did_start_fop);
14405 
14406 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14407 				    &recov_state, TRUE);
14408 				did_start_fop = FALSE;
14409 				if (argop[1].argop == OP_LOCK)
14410 					nfs4args_lock_free(&argop[1]);
14411 				else if (argop[1].argop == OP_LOCKT)
14412 					nfs4args_lockt_free(&argop[1]);
14413 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14414 				argsp = NULL;
14415 				goto recov_retry;
14416 			default:
14417 				ep->error = EIO;
14418 				goto out;
14419 			}
14420 			break;
14421 		default:
14422 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14423 			    "nfs4_frlock: invalid cmd %d", cmd));
14424 			ep->error = EINVAL;
14425 			goto out;
14426 		}
14427 
14428 		if (!go_otw)
14429 			goto out;
14430 	}
14431 
14432 	/*
14433 	 * Send the server the lock request.  Continually loop with a delay
14434 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14435 	 */
14436 	resp = &res;
14437 
14438 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14439 	    (CE_NOTE,
14440 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14441 	    rnode4info(rp)));
14442 
14443 	if (lock_args && frc_no_reclaim) {
14444 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14445 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14446 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14447 		lock_args->reclaim = FALSE;
14448 		if (did_reclaimp)
14449 			*did_reclaimp = 0;
14450 	}
14451 
14452 	/*
14453 	 * Do the OTW call.
14454 	 */
14455 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14456 
14457 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14458 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14459 
14460 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14461 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14462 	    "nfs4frlock: needrecov %d", needrecov));
14463 
14464 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14465 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14466 		    args.ctag);
14467 
14468 	/*
14469 	 * Check if one of these mutually exclusive error cases has
14470 	 * happened:
14471 	 *   need to swap credentials due to access error
14472 	 *   recovery is needed
14473 	 *   different error (only known case is missing Kerberos ticket)
14474 	 */
14475 
14476 	if ((ep->error == EACCES ||
14477 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14478 	    cred_otw != cr) {
14479 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14480 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14481 		    cr, &cred_otw);
14482 		goto recov_retry;
14483 	}
14484 
14485 	if (needrecov) {
14486 		/*
14487 		 * LOCKT requests don't need to recover from lost
14488 		 * requests since they don't create/modify state.
14489 		 */
14490 		if ((ep->error == EINTR ||
14491 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14492 		    lockt_args)
14493 			goto out;
14494 		/*
14495 		 * Do not attempt recovery for requests initiated by
14496 		 * the recovery framework.  Let the framework redrive them.
14497 		 */
14498 		if (ctype != NFS4_LCK_CTYPE_NORM)
14499 			goto out;
14500 		else {
14501 			ASSERT(resend_rqstp == NULL);
14502 		}
14503 
14504 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14505 		    flk_to_locktype(cmd, flk->l_type),
14506 		    oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14507 
14508 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14509 		    &resp, lock_args, locku_args, &oop, &osp, &lop,
14510 		    rp, vp, &recov_state, op_hint, &did_start_fop,
14511 		    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14512 
14513 		if (retry) {
14514 			ASSERT(oop == NULL);
14515 			ASSERT(osp == NULL);
14516 			ASSERT(lop == NULL);
14517 			goto recov_retry;
14518 		}
14519 		goto out;
14520 	}
14521 
14522 	/*
14523 	 * Bail out if have reached this point with ep->error set. Can
14524 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14525 	 * This happens if Kerberos ticket has expired or has been
14526 	 * destroyed.
14527 	 */
14528 	if (ep->error != 0)
14529 		goto out;
14530 
14531 	/*
14532 	 * Process the reply.
14533 	 */
14534 	switch (resp->status) {
14535 	case NFS4_OK:
14536 		resop = &resp->array[1];
14537 		/*
14538 		 * Have a successful lock operation, now update state.
14539 		 */
14540 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14541 		    resop, lop, vp, flk, cr, resend_rqstp);
14542 		break;
14543 
14544 	case NFS4ERR_DENIED:
14545 		resop = &resp->array[1];
14546 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14547 		    &oop, &osp, &lop, cmd, vp, flk, op_hint,
14548 		    &recov_state, needrecov, &argsp, &resp,
14549 		    &tick_delay, &ep->error, resop, cr,
14550 		    &did_start_fop, &skip_get_err);
14551 
14552 		if (retry) {
14553 			ASSERT(oop == NULL);
14554 			ASSERT(osp == NULL);
14555 			ASSERT(lop == NULL);
14556 			goto recov_retry;
14557 		}
14558 		break;
14559 	/*
14560 	 * If the server won't let us reclaim, fall-back to trying to lock
14561 	 * the file from scratch. Code elsewhere will check the changeinfo
14562 	 * to ensure the file hasn't been changed.
14563 	 */
14564 	case NFS4ERR_NO_GRACE:
14565 		if (lock_args && lock_args->reclaim == TRUE) {
14566 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14567 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14568 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14569 			frc_no_reclaim = 1;
14570 			/* clean up before retrying */
14571 			needrecov = 0;
14572 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14573 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14574 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14575 			goto recov_retry;
14576 		}
14577 		/* FALLTHROUGH */
14578 
14579 	default:
14580 		nfs4frlock_results_default(resp, &ep->error);
14581 		break;
14582 	}
14583 out:
14584 	/*
14585 	 * Process and cleanup from error.  Make interrupted unlock
14586 	 * requests look successful, since they will be handled by the
14587 	 * client recovery code.
14588 	 */
14589 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14590 	    needrecov, oop, osp, lop, &ep->error,
14591 	    lock_args, locku_args, did_start_fop,
14592 	    skip_get_err, cred_otw, cr);
14593 
14594 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14595 	    (cmd == F_SETLK || cmd == F_SETLKW))
14596 		ep->error = 0;
14597 }
14598 
14599 /*
14600  * nfs4_safelock:
14601  *
14602  * Return non-zero if the given lock request can be handled without
14603  * violating the constraints on concurrent mapping and locking.
14604  */
14605 
14606 static int
14607 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14608 {
14609 	rnode4_t *rp = VTOR4(vp);
14610 	struct vattr va;
14611 	int error;
14612 
14613 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14614 	ASSERT(rp->r_mapcnt >= 0);
14615 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14616 	    "(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14617 	    "write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14618 	    bfp->l_start, bfp->l_len, rp->r_mapcnt));
14619 
14620 	if (rp->r_mapcnt == 0)
14621 		return (1);		/* always safe if not mapped */
14622 
14623 	/*
14624 	 * If the file is already mapped and there are locks, then they
14625 	 * should be all safe locks.  So adding or removing a lock is safe
14626 	 * as long as the new request is safe (i.e., whole-file, meaning
14627 	 * length and starting offset are both zero).
14628 	 */
14629 
14630 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14631 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14632 		    "cannot lock a memory mapped file unless locking the "
14633 		    "entire file: start %"PRIx64", len %"PRIx64,
14634 		    bfp->l_start, bfp->l_len));
14635 		return (0);
14636 	}
14637 
14638 	/* mandatory locking and mapping don't mix */
14639 	va.va_mask = AT_MODE;
14640 	error = VOP_GETATTR(vp, &va, 0, cr, NULL);
14641 	if (error != 0) {
14642 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14643 		    "getattr error %d", error));
14644 		return (0);		/* treat errors conservatively */
14645 	}
14646 	if (MANDLOCK(vp, va.va_mode)) {
14647 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14648 		    "cannot mandatory lock and mmap a file"));
14649 		return (0);
14650 	}
14651 
14652 	return (1);
14653 }
14654 
14655 /*
14656  * nfs4_lockrelease:
14657  *
14658  * Release any locks on the given vnode that are held by the current
14659  * process.  Also removes the lock owner (if one exists) from the rnode's
14660  * list.
14661  */
14662 static int
14663 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14664 {
14665 	flock64_t ld;
14666 	int ret, error;
14667 	rnode4_t *rp;
14668 	nfs4_lock_owner_t *lop;
14669 	nfs4_recov_state_t recov_state;
14670 	mntinfo4_t *mi;
14671 	bool_t possible_orphan = FALSE;
14672 	bool_t recovonly;
14673 
14674 	ASSERT((uintptr_t)vp > KERNELBASE);
14675 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14676 
14677 	rp = VTOR4(vp);
14678 	mi = VTOMI4(vp);
14679 
14680 	/*
14681 	 * If we have not locked anything then we can
14682 	 * just return since we have no work to do.
14683 	 */
14684 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14685 		return (0);
14686 	}
14687 
14688 	/*
14689 	 * We need to comprehend that another thread may
14690 	 * kick off recovery and the lock_owner we have stashed
14691 	 * in lop might be invalid so we should NOT cache it
14692 	 * locally!
14693 	 */
14694 	recov_state.rs_flags = 0;
14695 	recov_state.rs_num_retry_despite_err = 0;
14696 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14697 	    &recovonly);
14698 	if (error) {
14699 		mutex_enter(&rp->r_statelock);
14700 		rp->r_flags |= R4LODANGLERS;
14701 		mutex_exit(&rp->r_statelock);
14702 		return (error);
14703 	}
14704 
14705 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14706 
14707 	/*
14708 	 * Check if the lock owner might have a lock (request was sent but
14709 	 * no response was received).  Also check if there are any remote
14710 	 * locks on the file.  (In theory we shouldn't have to make this
14711 	 * second check if there's no lock owner, but for now we'll be
14712 	 * conservative and do it anyway.)  If either condition is true,
14713 	 * send an unlock for the entire file to the server.
14714 	 *
14715 	 * Note that no explicit synchronization is needed here.  At worst,
14716 	 * flk_has_remote_locks() will return a false positive, in which case
14717 	 * the unlock call wastes time but doesn't harm correctness.
14718 	 */
14719 
14720 	if (lop) {
14721 		mutex_enter(&lop->lo_lock);
14722 		possible_orphan = lop->lo_pending_rqsts;
14723 		mutex_exit(&lop->lo_lock);
14724 		lock_owner_rele(lop);
14725 	}
14726 
14727 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14728 
14729 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14730 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14731 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14732 	    (void *)lop));
14733 
14734 	if (possible_orphan || flk_has_remote_locks(vp)) {
14735 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14736 		ld.l_whence = 0;	/* unlock from start of file */
14737 		ld.l_start = 0;
14738 		ld.l_len = 0;		/* do entire file */
14739 
14740 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL,
14741 		    cr, NULL);
14742 
14743 		if (ret != 0) {
14744 			/*
14745 			 * If VOP_FRLOCK fails, make sure we unregister
14746 			 * local locks before we continue.
14747 			 */
14748 			struct lm_sysid *lmsid = nfs4_find_sysid(VTOMI4(vp));
14749 
14750 			if (lmsid != NULL) {
14751 				cleanlocks(vp, curproc->p_pid,
14752 				    lm_sysidt(lmsid) | LM_SYSID_CLIENT);
14753 				lm_rel_sysid(lmsid);
14754 			}
14755 
14756 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14757 			    "nfs4_lockrelease: lock release error on vp"
14758 			    " %p: error %d.\n", (void *)vp, ret));
14759 		}
14760 	}
14761 
14762 	recov_state.rs_flags = 0;
14763 	recov_state.rs_num_retry_despite_err = 0;
14764 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14765 	    &recovonly);
14766 	if (error) {
14767 		mutex_enter(&rp->r_statelock);
14768 		rp->r_flags |= R4LODANGLERS;
14769 		mutex_exit(&rp->r_statelock);
14770 		return (error);
14771 	}
14772 
14773 	/*
14774 	 * So, here we're going to need to retrieve the lock-owner
14775 	 * again (in case recovery has done a switch-a-roo) and
14776 	 * remove it because we can.
14777 	 */
14778 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14779 
14780 	if (lop) {
14781 		nfs4_rnode_remove_lock_owner(rp, lop);
14782 		lock_owner_rele(lop);
14783 	}
14784 
14785 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14786 	return (0);
14787 }
14788 
14789 /*
14790  * Wait for 'tick_delay' clock ticks.
14791  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14792  *
14793  * The client should retry to acquire the lock faster than the lease period.
14794  * We use roughly half of the lease time to use a similar calculation as it is
14795  * used in nfs4_renew_lease_thread().
14796  *
14797  * XXX For future improvements, should implement a waiting queue scheme.
14798  */
14799 static int
14800 nfs4_block_and_wait(clock_t *tick_delay)
14801 {
14802 	/* wait tick_delay clock ticks or siginteruptus */
14803 	if (delay_sig(*tick_delay)) {
14804 		return (EINTR);
14805 	}
14806 
14807 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14808 	    "reissue the lock request: blocked for %ld clock ticks: %ld "
14809 	    "milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14810 
14811 	*tick_delay = MIN(drv_usectohz(nfs4_max_base_wait_time * 1000),
14812 			  *tick_delay * 1.5);
14813 	return (0);
14814 }
14815 
14816 void
14817 nfs4_vnops_init(void)
14818 {
14819 }
14820 
14821 void
14822 nfs4_vnops_fini(void)
14823 {
14824 }
14825 
14826 /*
14827  * Return a reference to the directory (parent) vnode for a given vnode,
14828  * using the saved pathname information and the directory file handle.  The
14829  * caller is responsible for disposing of the reference.
14830  * Returns zero or an errno value.
14831  *
14832  * Caller should set need_start_op to FALSE if it is the recovery
14833  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14834  */
14835 int
14836 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14837 {
14838 	svnode_t *svnp;
14839 	vnode_t *dvp = NULL;
14840 	servinfo4_t *svp;
14841 	nfs4_fname_t *mfname;
14842 	int error;
14843 
14844 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14845 
14846 	if (vp->v_flag & VROOT) {
14847 		nfs4_sharedfh_t *sfh;
14848 		nfs_fh4 fh;
14849 		mntinfo4_t *mi;
14850 
14851 		ASSERT(vp->v_type == VREG);
14852 
14853 		mi = VTOMI4(vp);
14854 		svp = mi->mi_curr_serv;
14855 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14856 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14857 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14858 		sfh = sfh4_get(&fh, VTOMI4(vp));
14859 		nfs_rw_exit(&svp->sv_lock);
14860 		mfname = mi->mi_fname;
14861 		fn_hold(mfname);
14862 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14863 		sfh4_rele(&sfh);
14864 
14865 		if (dvp->v_type == VNON)
14866 			dvp->v_type = VDIR;
14867 		*dvpp = dvp;
14868 		return (0);
14869 	}
14870 
14871 	svnp = VTOSV(vp);
14872 
14873 	if (svnp == NULL) {
14874 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14875 		    "shadow node is NULL"));
14876 		return (EINVAL);
14877 	}
14878 
14879 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14880 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14881 		    "shadow node name or dfh val == NULL"));
14882 		return (EINVAL);
14883 	}
14884 
14885 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14886 	    (int)need_start_op);
14887 	if (error != 0) {
14888 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14889 		    "nfs4_make_dotdot returned %d", error));
14890 		return (error);
14891 	}
14892 	if (!dvp) {
14893 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14894 		    "nfs4_make_dotdot returned a NULL dvp"));
14895 		return (EIO);
14896 	}
14897 	if (dvp->v_type == VNON)
14898 		dvp->v_type = VDIR;
14899 	ASSERT(dvp->v_type == VDIR);
14900 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14901 		mutex_enter(&dvp->v_lock);
14902 		dvp->v_flag |= V_XATTRDIR;
14903 		mutex_exit(&dvp->v_lock);
14904 	}
14905 	*dvpp = dvp;
14906 	return (0);
14907 }
14908 
14909 /*
14910  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14911  * length that fnamep can accept, including the trailing null.
14912  * Returns 0 if okay, returns an errno value if there was a problem.
14913  */
14914 
14915 int
14916 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14917 {
14918 	char *fn;
14919 	int err = 0;
14920 	servinfo4_t *svp;
14921 	svnode_t *shvp;
14922 
14923 	/*
14924 	 * If the file being opened has VROOT set, then this is
14925 	 * a "file" mount.  sv_name will not be interesting, so
14926 	 * go back to the servinfo4 to get the original mount
14927 	 * path and strip off all but the final edge.  Otherwise
14928 	 * just return the name from the shadow vnode.
14929 	 */
14930 
14931 	if (vp->v_flag & VROOT) {
14932 
14933 		svp = VTOMI4(vp)->mi_curr_serv;
14934 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14935 
14936 		fn = strrchr(svp->sv_path, '/');
14937 		if (fn == NULL)
14938 			err = EINVAL;
14939 		else
14940 			fn++;
14941 	} else {
14942 		shvp = VTOSV(vp);
14943 		fn = fn_name(shvp->sv_name);
14944 	}
14945 
14946 	if (err == 0)
14947 		if (strlen(fn) < maxlen)
14948 			(void) strcpy(fnamep, fn);
14949 		else
14950 			err = ENAMETOOLONG;
14951 
14952 	if (vp->v_flag & VROOT)
14953 		nfs_rw_exit(&svp->sv_lock);
14954 	else
14955 		kmem_free(fn, MAXNAMELEN);
14956 
14957 	return (err);
14958 }
14959 
14960 /*
14961  * Bookkeeping for a close that doesn't need to go over the wire.
14962  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14963  * it is left at 1.
14964  */
14965 void
14966 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14967 {
14968 	rnode4_t		*rp;
14969 	mntinfo4_t		*mi;
14970 
14971 	mi = VTOMI4(vp);
14972 	rp = VTOR4(vp);
14973 
14974 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14975 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14976 	ASSERT(nfs_zone() == mi->mi_zone);
14977 	ASSERT(mutex_owned(&osp->os_sync_lock));
14978 	ASSERT(*have_lockp);
14979 
14980 	if (!osp->os_valid ||
14981 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14982 		return;
14983 	}
14984 
14985 	/*
14986 	 * This removes the reference obtained at OPEN; ie,
14987 	 * when the open stream structure was created.
14988 	 *
14989 	 * We don't have to worry about calling 'open_stream_rele'
14990 	 * since we our currently holding a reference to this
14991 	 * open stream which means the count can not go to 0 with
14992 	 * this decrement.
14993 	 */
14994 	ASSERT(osp->os_ref_count >= 2);
14995 	osp->os_ref_count--;
14996 	osp->os_valid = 0;
14997 	mutex_exit(&osp->os_sync_lock);
14998 	*have_lockp = 0;
14999 
15000 	nfs4_dec_state_ref_count(mi);
15001 }
15002 
15003 /*
15004  * Close all remaining open streams on the rnode.  These open streams
15005  * could be here because:
15006  * - The close attempted at either close or delmap failed
15007  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
15008  * - Someone did mknod on a regular file but never opened it
15009  */
15010 int
15011 nfs4close_all(vnode_t *vp, cred_t *cr)
15012 {
15013 	nfs4_open_stream_t *osp;
15014 	int error;
15015 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
15016 	rnode4_t *rp;
15017 
15018 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15019 
15020 	error = 0;
15021 	rp = VTOR4(vp);
15022 
15023 	/*
15024 	 * At this point, all we know is that the last time
15025 	 * someone called vn_rele, the count was 1.  Since then,
15026 	 * the vnode could have been re-activated.  We want to
15027 	 * loop through the open streams and close each one, but
15028 	 * we have to be careful since once we release the rnode
15029 	 * hash bucket lock, someone else is free to come in and
15030 	 * re-activate the rnode and add new open streams.  The
15031 	 * strategy is take the rnode hash bucket lock, verify that
15032 	 * the count is still 1, grab the open stream off the
15033 	 * head of the list and mark it invalid, then release the
15034 	 * rnode hash bucket lock and proceed with that open stream.
15035 	 * This is ok because nfs4close_one() will acquire the proper
15036 	 * open/create to close/destroy synchronization for open
15037 	 * streams, and will ensure that if someone has reopened
15038 	 * the open stream after we've dropped the hash bucket lock
15039 	 * then we'll just simply return without destroying the
15040 	 * open stream.
15041 	 * Repeat until the list is empty.
15042 	 */
15043 
15044 	for (;;) {
15045 
15046 		/* make sure vnode hasn't been reactivated */
15047 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
15048 		mutex_enter(&vp->v_lock);
15049 		if (vp->v_count > 1) {
15050 			mutex_exit(&vp->v_lock);
15051 			rw_exit(&rp->r_hashq->r_lock);
15052 			break;
15053 		}
15054 		/*
15055 		 * Grabbing r_os_lock before releasing v_lock prevents
15056 		 * a window where the rnode/open stream could get
15057 		 * reactivated (and os_force_close set to 0) before we
15058 		 * had a chance to set os_force_close to 1.
15059 		 */
15060 		mutex_enter(&rp->r_os_lock);
15061 		mutex_exit(&vp->v_lock);
15062 
15063 		osp = list_head(&rp->r_open_streams);
15064 		if (!osp) {
15065 			/* nothing left to CLOSE OTW, so return */
15066 			mutex_exit(&rp->r_os_lock);
15067 			rw_exit(&rp->r_hashq->r_lock);
15068 			break;
15069 		}
15070 
15071 		mutex_enter(&rp->r_statev4_lock);
15072 		/* the file can't still be mem mapped */
15073 		ASSERT(rp->r_mapcnt == 0);
15074 		if (rp->created_v4)
15075 			rp->created_v4 = 0;
15076 		mutex_exit(&rp->r_statev4_lock);
15077 
15078 		/*
15079 		 * Grab a ref on this open stream; nfs4close_one
15080 		 * will mark it as invalid
15081 		 */
15082 		mutex_enter(&osp->os_sync_lock);
15083 		osp->os_ref_count++;
15084 		osp->os_force_close = 1;
15085 		mutex_exit(&osp->os_sync_lock);
15086 		mutex_exit(&rp->r_os_lock);
15087 		rw_exit(&rp->r_hashq->r_lock);
15088 
15089 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
15090 
15091 		/* Update error if it isn't already non-zero */
15092 		if (error == 0) {
15093 			if (e.error)
15094 				error = e.error;
15095 			else if (e.stat)
15096 				error = geterrno4(e.stat);
15097 		}
15098 
15099 #ifdef	DEBUG
15100 		nfs4close_all_cnt++;
15101 #endif
15102 		/* Release the ref on osp acquired above. */
15103 		open_stream_rele(osp, rp);
15104 
15105 		/* Proceed to the next open stream, if any */
15106 	}
15107 	return (error);
15108 }
15109 
15110 /*
15111  * nfs4close_one - close one open stream for a file if needed.
15112  *
15113  * "close_type" indicates which close path this is:
15114  * CLOSE_NORM: close initiated via VOP_CLOSE.
15115  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
15116  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
15117  *	the close and release of client state for this open stream
15118  *	(unless someone else has the open stream open).
15119  * CLOSE_RESEND: indicates the request is a replay of an earlier request
15120  *	(e.g., due to abort because of a signal).
15121  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
15122  *
15123  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
15124  * recovery.  Instead, the caller is expected to deal with retries.
15125  *
15126  * The caller can either pass in the osp ('provided_osp') or not.
15127  *
15128  * 'access_bits' represents the access we are closing/downgrading.
15129  *
15130  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
15131  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
15132  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
15133  *
15134  * Errors are returned via the nfs4_error_t.
15135  */
15136 void
15137 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
15138     int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
15139     nfs4_close_type_t close_type, size_t len, uint_t maxprot,
15140     uint_t mmap_flags)
15141 {
15142 	nfs4_open_owner_t *oop;
15143 	nfs4_open_stream_t *osp = NULL;
15144 	int retry = 0;
15145 	int num_retries = NFS4_NUM_RECOV_RETRIES;
15146 	rnode4_t *rp;
15147 	mntinfo4_t *mi;
15148 	nfs4_recov_state_t recov_state;
15149 	cred_t *cred_otw = NULL;
15150 	bool_t recovonly = FALSE;
15151 	int isrecov;
15152 	int force_close;
15153 	int close_failed = 0;
15154 	int did_dec_count = 0;
15155 	int did_start_op = 0;
15156 	int did_force_recovlock = 0;
15157 	int did_start_seqid_sync = 0;
15158 	int have_sync_lock = 0;
15159 
15160 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15161 
15162 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
15163 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
15164 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
15165 	    len, maxprot, mmap_flags, access_bits));
15166 
15167 	nfs4_error_zinit(ep);
15168 	rp = VTOR4(vp);
15169 	mi = VTOMI4(vp);
15170 	isrecov = (close_type == CLOSE_RESEND ||
15171 	    close_type == CLOSE_AFTER_RESEND);
15172 
15173 	/*
15174 	 * First get the open owner.
15175 	 */
15176 	if (!provided_osp) {
15177 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
15178 	} else {
15179 		oop = provided_osp->os_open_owner;
15180 		ASSERT(oop != NULL);
15181 		open_owner_hold(oop);
15182 	}
15183 
15184 	if (!oop) {
15185 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15186 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15187 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15188 		    (void *)provided_osp, close_type));
15189 		ep->error = EIO;
15190 		goto out;
15191 	}
15192 
15193 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15194 recov_retry:
15195 	osp = NULL;
15196 	close_failed = 0;
15197 	force_close = (close_type == CLOSE_FORCE);
15198 	retry = 0;
15199 	did_start_op = 0;
15200 	did_force_recovlock = 0;
15201 	did_start_seqid_sync = 0;
15202 	have_sync_lock = 0;
15203 	recovonly = FALSE;
15204 	recov_state.rs_flags = 0;
15205 	recov_state.rs_num_retry_despite_err = 0;
15206 
15207 	/*
15208 	 * Second synchronize with recovery.
15209 	 */
15210 	if (!isrecov) {
15211 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15212 		    &recov_state, &recovonly);
15213 		if (!ep->error) {
15214 			did_start_op = 1;
15215 		} else {
15216 			close_failed = 1;
15217 			/*
15218 			 * If we couldn't get start_fop, but have to
15219 			 * cleanup state, then at least acquire the
15220 			 * mi_recovlock so we can synchronize with
15221 			 * recovery.
15222 			 */
15223 			if (close_type == CLOSE_FORCE) {
15224 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15225 				    RW_READER, FALSE);
15226 				did_force_recovlock = 1;
15227 			} else
15228 				goto out;
15229 		}
15230 	}
15231 
15232 	/*
15233 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15234 	 * set 'recovonly' to TRUE since most likely this is due to
15235 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15236 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15237 	 * to retry, causing us to loop until recovery finishes.  Plus we
15238 	 * don't need protection over the open seqid since we're not going
15239 	 * OTW, hence don't need to use the seqid.
15240 	 */
15241 	if (recovonly == FALSE) {
15242 		/* need to grab the open owner sync before 'os_sync_lock' */
15243 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15244 		if (ep->error == EAGAIN) {
15245 			ASSERT(!isrecov);
15246 			if (did_start_op)
15247 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15248 				    &recov_state, TRUE);
15249 			if (did_force_recovlock)
15250 				nfs_rw_exit(&mi->mi_recovlock);
15251 			goto recov_retry;
15252 		}
15253 		did_start_seqid_sync = 1;
15254 	}
15255 
15256 	/*
15257 	 * Third get an open stream and acquire 'os_sync_lock' to
15258 	 * sychronize the opening/creating of an open stream with the
15259 	 * closing/destroying of an open stream.
15260 	 */
15261 	if (!provided_osp) {
15262 		/* returns with 'os_sync_lock' held */
15263 		osp = find_open_stream(oop, rp);
15264 		if (!osp) {
15265 			ep->error = EIO;
15266 			goto out;
15267 		}
15268 	} else {
15269 		osp = provided_osp;
15270 		open_stream_hold(osp);
15271 		mutex_enter(&osp->os_sync_lock);
15272 	}
15273 	have_sync_lock = 1;
15274 
15275 	ASSERT(oop == osp->os_open_owner);
15276 
15277 	/*
15278 	 * Fourth, do any special pre-OTW CLOSE processing
15279 	 * based on the specific close type.
15280 	 */
15281 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15282 	    !did_dec_count) {
15283 		ASSERT(osp->os_open_ref_count > 0);
15284 		osp->os_open_ref_count--;
15285 		did_dec_count = 1;
15286 		if (osp->os_open_ref_count == 0)
15287 			osp->os_final_close = 1;
15288 	}
15289 
15290 	if (close_type == CLOSE_FORCE) {
15291 		/* see if somebody reopened the open stream. */
15292 		if (!osp->os_force_close) {
15293 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15294 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15295 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15296 			ep->error = 0;
15297 			ep->stat = NFS4_OK;
15298 			goto out;
15299 		}
15300 
15301 		if (!osp->os_final_close && !did_dec_count) {
15302 			osp->os_open_ref_count--;
15303 			did_dec_count = 1;
15304 		}
15305 
15306 		/*
15307 		 * We can't depend on os_open_ref_count being 0 due to the
15308 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15309 		 */
15310 #ifdef	NOTYET
15311 		ASSERT(osp->os_open_ref_count == 0);
15312 #endif
15313 		if (osp->os_open_ref_count != 0) {
15314 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15315 			    "nfs4close_one: should panic here on an "
15316 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15317 			    "since this is probably the exec problem."));
15318 
15319 			osp->os_open_ref_count = 0;
15320 		}
15321 
15322 		/*
15323 		 * There is the possibility that nfs4close_one()
15324 		 * for close_type == CLOSE_DELMAP couldn't find the
15325 		 * open stream, thus couldn't decrement its os_mapcnt;
15326 		 * therefore we can't use this ASSERT yet.
15327 		 */
15328 #ifdef	NOTYET
15329 		ASSERT(osp->os_mapcnt == 0);
15330 #endif
15331 		osp->os_mapcnt = 0;
15332 	}
15333 
15334 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15335 		ASSERT(osp->os_mapcnt >= btopr(len));
15336 
15337 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15338 			osp->os_mmap_write -= btopr(len);
15339 		if (maxprot & PROT_READ)
15340 			osp->os_mmap_read -= btopr(len);
15341 		if (maxprot & PROT_EXEC)
15342 			osp->os_mmap_read -= btopr(len);
15343 		/* mirror the PROT_NONE check in nfs4_addmap() */
15344 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15345 		    !(maxprot & PROT_EXEC))
15346 			osp->os_mmap_read -= btopr(len);
15347 		osp->os_mapcnt -= btopr(len);
15348 		did_dec_count = 1;
15349 	}
15350 
15351 	if (recovonly) {
15352 		nfs4_lost_rqst_t lost_rqst;
15353 
15354 		/* request should not already be in recovery queue */
15355 		ASSERT(lrp == NULL);
15356 		nfs4_error_init(ep, EINTR);
15357 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15358 		    osp, cred_otw, vp);
15359 		mutex_exit(&osp->os_sync_lock);
15360 		have_sync_lock = 0;
15361 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15362 		    lost_rqst.lr_op == OP_CLOSE ?
15363 		    &lost_rqst : NULL, OP_CLOSE, NULL, NULL, NULL);
15364 		close_failed = 1;
15365 		force_close = 0;
15366 		goto close_cleanup;
15367 	}
15368 
15369 	/*
15370 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15371 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15372 	 * space, which means we stopped operating on the open stream
15373 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15374 	 * stateid could be stale, potentially triggering a false
15375 	 * setclientid), and just clean up the client's internal state.
15376 	 */
15377 	if (osp->os_orig_oo_name != oop->oo_name) {
15378 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15379 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15380 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15381 		    "oo_name %" PRIx64")",
15382 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15383 		    oop->oo_name));
15384 		close_failed = 1;
15385 	}
15386 
15387 	/* If the file failed recovery, just quit. */
15388 	mutex_enter(&rp->r_statelock);
15389 	if (rp->r_flags & R4RECOVERR) {
15390 		close_failed = 1;
15391 	}
15392 	mutex_exit(&rp->r_statelock);
15393 
15394 	/*
15395 	 * If the force close path failed to obtain start_fop
15396 	 * then skip the OTW close and just remove the state.
15397 	 */
15398 	if (close_failed)
15399 		goto close_cleanup;
15400 
15401 	/*
15402 	 * Fifth, check to see if there are still mapped pages or other
15403 	 * opens using this open stream.  If there are then we can't
15404 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15405 	 */
15406 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15407 		nfs4_lost_rqst_t	new_lost_rqst;
15408 		bool_t			needrecov = FALSE;
15409 		cred_t			*odg_cred_otw = NULL;
15410 		seqid4			open_dg_seqid = 0;
15411 
15412 		if (osp->os_delegation) {
15413 			/*
15414 			 * If this open stream was never OPENed OTW then we
15415 			 * surely can't DOWNGRADE it (especially since the
15416 			 * osp->open_stateid is really a delegation stateid
15417 			 * when os_delegation is 1).
15418 			 */
15419 			if (access_bits & FREAD)
15420 				osp->os_share_acc_read--;
15421 			if (access_bits & FWRITE)
15422 				osp->os_share_acc_write--;
15423 			osp->os_share_deny_none--;
15424 			nfs4_error_zinit(ep);
15425 			goto out;
15426 		}
15427 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15428 		    lrp, ep, &odg_cred_otw, &open_dg_seqid);
15429 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15430 		if (needrecov && !isrecov) {
15431 			bool_t abort;
15432 			nfs4_bseqid_entry_t *bsep = NULL;
15433 
15434 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15435 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15436 				    vp, 0,
15437 				    lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15438 				    open_dg_seqid);
15439 
15440 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15441 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15442 			mutex_exit(&osp->os_sync_lock);
15443 			have_sync_lock = 0;
15444 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15445 			    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15446 			    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15447 			    bsep, NULL, NULL);
15448 			if (odg_cred_otw)
15449 				crfree(odg_cred_otw);
15450 			if (bsep)
15451 				kmem_free(bsep, sizeof (*bsep));
15452 
15453 			if (abort == TRUE)
15454 				goto out;
15455 
15456 			if (did_start_seqid_sync) {
15457 				nfs4_end_open_seqid_sync(oop);
15458 				did_start_seqid_sync = 0;
15459 			}
15460 			open_stream_rele(osp, rp);
15461 
15462 			if (did_start_op)
15463 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15464 				    &recov_state, FALSE);
15465 			if (did_force_recovlock)
15466 				nfs_rw_exit(&mi->mi_recovlock);
15467 
15468 			goto recov_retry;
15469 		} else {
15470 			if (odg_cred_otw)
15471 				crfree(odg_cred_otw);
15472 		}
15473 		goto out;
15474 	}
15475 
15476 	/*
15477 	 * If this open stream was created as the results of an open
15478 	 * while holding a delegation, then just release it; no need
15479 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15480 	 */
15481 	if (osp->os_delegation) {
15482 		nfs4close_notw(vp, osp, &have_sync_lock);
15483 		nfs4_error_zinit(ep);
15484 		goto out;
15485 	}
15486 
15487 	/*
15488 	 * If this stream is not valid, we're done.
15489 	 */
15490 	if (!osp->os_valid) {
15491 		nfs4_error_zinit(ep);
15492 		goto out;
15493 	}
15494 
15495 	/*
15496 	 * Last open or mmap ref has vanished, need to do an OTW close.
15497 	 * First check to see if a close is still necessary.
15498 	 */
15499 	if (osp->os_failed_reopen) {
15500 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15501 		    "don't close OTW osp %p since reopen failed.",
15502 		    (void *)osp));
15503 		/*
15504 		 * Reopen of the open stream failed, hence the
15505 		 * stateid of the open stream is invalid/stale, and
15506 		 * sending this OTW would incorrectly cause another
15507 		 * round of recovery.  In this case, we need to set
15508 		 * the 'os_valid' bit to 0 so another thread doesn't
15509 		 * come in and re-open this open stream before
15510 		 * this "closing" thread cleans up state (decrementing
15511 		 * the nfs4_server_t's state_ref_count and decrementing
15512 		 * the os_ref_count).
15513 		 */
15514 		osp->os_valid = 0;
15515 		/*
15516 		 * This removes the reference obtained at OPEN; ie,
15517 		 * when the open stream structure was created.
15518 		 *
15519 		 * We don't have to worry about calling 'open_stream_rele'
15520 		 * since we our currently holding a reference to this
15521 		 * open stream which means the count can not go to 0 with
15522 		 * this decrement.
15523 		 */
15524 		ASSERT(osp->os_ref_count >= 2);
15525 		osp->os_ref_count--;
15526 		nfs4_error_zinit(ep);
15527 		close_failed = 0;
15528 		goto close_cleanup;
15529 	}
15530 
15531 	ASSERT(osp->os_ref_count > 1);
15532 
15533 	/*
15534 	 * Sixth, try the CLOSE OTW.
15535 	 */
15536 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15537 	    close_type, ep, &have_sync_lock);
15538 
15539 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15540 		/*
15541 		 * Let the recovery thread be responsible for
15542 		 * removing the state for CLOSE.
15543 		 */
15544 		close_failed = 1;
15545 		force_close = 0;
15546 		retry = 0;
15547 	}
15548 
15549 	/* See if we need to retry with a different cred */
15550 	if ((ep->error == EACCES ||
15551 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15552 	    cred_otw != cr) {
15553 		crfree(cred_otw);
15554 		cred_otw = cr;
15555 		crhold(cred_otw);
15556 		retry = 1;
15557 	}
15558 
15559 	if (ep->error || ep->stat)
15560 		close_failed = 1;
15561 
15562 	if (retry && !isrecov && num_retries-- > 0) {
15563 		if (have_sync_lock) {
15564 			mutex_exit(&osp->os_sync_lock);
15565 			have_sync_lock = 0;
15566 		}
15567 		if (did_start_seqid_sync) {
15568 			nfs4_end_open_seqid_sync(oop);
15569 			did_start_seqid_sync = 0;
15570 		}
15571 		open_stream_rele(osp, rp);
15572 
15573 		if (did_start_op)
15574 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15575 			    &recov_state, FALSE);
15576 		if (did_force_recovlock)
15577 			nfs_rw_exit(&mi->mi_recovlock);
15578 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15579 		    "nfs4close_one: need to retry the close "
15580 		    "operation"));
15581 		goto recov_retry;
15582 	}
15583 close_cleanup:
15584 	/*
15585 	 * Seventh and lastly, process our results.
15586 	 */
15587 	if (close_failed && force_close) {
15588 		/*
15589 		 * It's ok to drop and regrab the 'os_sync_lock' since
15590 		 * nfs4close_notw() will recheck to make sure the
15591 		 * "close"/removal of state should happen.
15592 		 */
15593 		if (!have_sync_lock) {
15594 			mutex_enter(&osp->os_sync_lock);
15595 			have_sync_lock = 1;
15596 		}
15597 		/*
15598 		 * This is last call, remove the ref on the open
15599 		 * stream created by open and clean everything up.
15600 		 */
15601 		osp->os_pending_close = 0;
15602 		nfs4close_notw(vp, osp, &have_sync_lock);
15603 		nfs4_error_zinit(ep);
15604 	}
15605 
15606 	if (!close_failed) {
15607 		if (have_sync_lock) {
15608 			osp->os_pending_close = 0;
15609 			mutex_exit(&osp->os_sync_lock);
15610 			have_sync_lock = 0;
15611 		} else {
15612 			mutex_enter(&osp->os_sync_lock);
15613 			osp->os_pending_close = 0;
15614 			mutex_exit(&osp->os_sync_lock);
15615 		}
15616 		if (did_start_op && recov_state.rs_sp != NULL) {
15617 			mutex_enter(&recov_state.rs_sp->s_lock);
15618 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15619 			mutex_exit(&recov_state.rs_sp->s_lock);
15620 		} else {
15621 			nfs4_dec_state_ref_count(mi);
15622 		}
15623 		nfs4_error_zinit(ep);
15624 	}
15625 
15626 out:
15627 	if (have_sync_lock)
15628 		mutex_exit(&osp->os_sync_lock);
15629 	if (did_start_op)
15630 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15631 		    recovonly ? TRUE : FALSE);
15632 	if (did_force_recovlock)
15633 		nfs_rw_exit(&mi->mi_recovlock);
15634 	if (cred_otw)
15635 		crfree(cred_otw);
15636 	if (osp)
15637 		open_stream_rele(osp, rp);
15638 	if (oop) {
15639 		if (did_start_seqid_sync)
15640 			nfs4_end_open_seqid_sync(oop);
15641 		open_owner_rele(oop);
15642 	}
15643 }
15644 
15645 /*
15646  * Convert information returned by the server in the LOCK4denied
15647  * structure to the form required by fcntl.
15648  */
15649 static void
15650 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15651 {
15652 	nfs4_lo_name_t *lo;
15653 
15654 #ifdef	DEBUG
15655 	if (denied_to_flk_debug) {
15656 		lockt_denied_debug = lockt_denied;
15657 		debug_enter("lockt_denied");
15658 	}
15659 #endif
15660 
15661 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15662 	flk->l_whence = 0;	/* aka SEEK_SET */
15663 	flk->l_start = lockt_denied->offset;
15664 	flk->l_len = lockt_denied->length;
15665 
15666 	/*
15667 	 * If the blocking clientid matches our client id, then we can
15668 	 * interpret the lockowner (since we built it).  If not, then
15669 	 * fabricate a sysid and pid.  Note that the l_sysid field
15670 	 * in *flk already has the local sysid.
15671 	 */
15672 
15673 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15674 
15675 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15676 			lo = (nfs4_lo_name_t *)
15677 			    lockt_denied->owner.owner_val;
15678 
15679 			flk->l_pid = lo->ln_pid;
15680 		} else {
15681 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15682 			    "denied_to_flk: bad lock owner length\n"));
15683 
15684 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15685 		}
15686 	} else {
15687 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15688 		"denied_to_flk: foreign clientid\n"));
15689 
15690 		/*
15691 		 * Construct a new sysid which should be different from
15692 		 * sysids of other systems.
15693 		 */
15694 
15695 		flk->l_sysid++;
15696 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15697 	}
15698 }
15699 
15700 static pid_t
15701 lo_to_pid(lock_owner4 *lop)
15702 {
15703 	pid_t pid = 0;
15704 	uchar_t *cp;
15705 	int i;
15706 
15707 	cp = (uchar_t *)&lop->clientid;
15708 
15709 	for (i = 0; i < sizeof (lop->clientid); i++)
15710 		pid += (pid_t)*cp++;
15711 
15712 	cp = (uchar_t *)lop->owner_val;
15713 
15714 	for (i = 0; i < lop->owner_len; i++)
15715 		pid += (pid_t)*cp++;
15716 
15717 	return (pid);
15718 }
15719 
15720 /*
15721  * Given a lock pointer, returns the length of that lock.
15722  * "end" is the last locked offset the "l_len" covers from
15723  * the start of the lock.
15724  */
15725 static off64_t
15726 lock_to_end(flock64_t *lock)
15727 {
15728 	off64_t lock_end;
15729 
15730 	if (lock->l_len == 0)
15731 		lock_end = (off64_t)MAXEND;
15732 	else
15733 		lock_end = lock->l_start + lock->l_len - 1;
15734 
15735 	return (lock_end);
15736 }
15737 
15738 /*
15739  * Given the end of a lock, it will return you the length "l_len" for that lock.
15740  */
15741 static off64_t
15742 end_to_len(off64_t start, off64_t end)
15743 {
15744 	off64_t lock_len;
15745 
15746 	ASSERT(end >= start);
15747 	if (end == MAXEND)
15748 		lock_len = 0;
15749 	else
15750 		lock_len = end - start + 1;
15751 
15752 	return (lock_len);
15753 }
15754 
15755 /*
15756  * On given end for a lock it determines if it is the last locked offset
15757  * or not, if so keeps it as is, else adds one to return the length for
15758  * valid start.
15759  */
15760 static off64_t
15761 start_check(off64_t x)
15762 {
15763 	if (x == MAXEND)
15764 		return (x);
15765 	else
15766 		return (x + 1);
15767 }
15768 
15769 /*
15770  * See if these two locks overlap, and if so return 1;
15771  * otherwise, return 0.
15772  */
15773 static int
15774 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15775 {
15776 	off64_t llfp_end, curfp_end;
15777 
15778 	llfp_end = lock_to_end(llfp);
15779 	curfp_end = lock_to_end(curfp);
15780 
15781 	if (((llfp_end >= curfp->l_start) &&
15782 	    (llfp->l_start <= curfp->l_start)) ||
15783 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15784 		return (1);
15785 	return (0);
15786 }
15787 
15788 /*
15789  * Determine what the intersecting lock region is, and add that to the
15790  * 'nl_llpp' locklist in increasing order (by l_start).
15791  */
15792 static void
15793 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15794     locklist_t **nl_llpp, vnode_t *vp)
15795 {
15796 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15797 	off64_t lost_flp_end, local_flp_end, len, start;
15798 
15799 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15800 
15801 	if (!locks_intersect(lost_flp, local_flp))
15802 		return;
15803 
15804 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15805 	    "locks intersect"));
15806 
15807 	lost_flp_end = lock_to_end(lost_flp);
15808 	local_flp_end = lock_to_end(local_flp);
15809 
15810 	/* Find the starting point of the intersecting region */
15811 	if (local_flp->l_start > lost_flp->l_start)
15812 		start = local_flp->l_start;
15813 	else
15814 		start = lost_flp->l_start;
15815 
15816 	/* Find the lenght of the intersecting region */
15817 	if (lost_flp_end < local_flp_end)
15818 		len = end_to_len(start, lost_flp_end);
15819 	else
15820 		len = end_to_len(start, local_flp_end);
15821 
15822 	/*
15823 	 * Prepare the flock structure for the intersection found and insert
15824 	 * it into the new list in increasing l_start order. This list contains
15825 	 * intersections of locks registered by the client with the local host
15826 	 * and the lost lock.
15827 	 * The lock type of this lock is the same as that of the local_flp.
15828 	 */
15829 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15830 	intersect_llp->ll_flock.l_start = start;
15831 	intersect_llp->ll_flock.l_len = len;
15832 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15833 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15834 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15835 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15836 	intersect_llp->ll_vp = vp;
15837 
15838 	tmp_fllp = *nl_llpp;
15839 	cur_fllp = NULL;
15840 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15841 	    intersect_llp->ll_flock.l_start) {
15842 			cur_fllp = tmp_fllp;
15843 			tmp_fllp = tmp_fllp->ll_next;
15844 	}
15845 	if (cur_fllp == NULL) {
15846 		/* first on the list */
15847 		intersect_llp->ll_next = *nl_llpp;
15848 		*nl_llpp = intersect_llp;
15849 	} else {
15850 		intersect_llp->ll_next = cur_fllp->ll_next;
15851 		cur_fllp->ll_next = intersect_llp;
15852 	}
15853 
15854 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15855 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15856 	    intersect_llp->ll_flock.l_start,
15857 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15858 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15859 }
15860 
15861 /*
15862  * Our local locking current state is potentially different than
15863  * what the NFSv4 server thinks we have due to a lost lock that was
15864  * resent and then received.  We need to reset our "NFSv4" locking
15865  * state to match the current local locking state for this pid since
15866  * that is what the user/application sees as what the world is.
15867  *
15868  * We cannot afford to drop the open/lock seqid sync since then we can
15869  * get confused about what the current local locking state "is" versus
15870  * "was".
15871  *
15872  * If we are unable to fix up the locks, we send SIGLOST to the affected
15873  * process.  This is not done if the filesystem has been forcibly
15874  * unmounted, in case the process has already exited and a new process
15875  * exists with the same pid.
15876  */
15877 static void
15878 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15879     nfs4_lock_owner_t *lop)
15880 {
15881 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15882 	mntinfo4_t *mi = VTOMI4(vp);
15883 	const int cmd = F_SETLK;
15884 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15885 	flock64_t ul_fl;
15886 
15887 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15888 	    "nfs4_reinstitute_local_lock_state"));
15889 
15890 	/*
15891 	 * Find active locks for this vp from the local locking code.
15892 	 * Scan through this list and find out the locks that intersect with
15893 	 * the lost lock. Once we find the lock that intersects, add the
15894 	 * intersection area as a new lock to a new list "ri_llp". The lock
15895 	 * type of the intersection region lock added to ri_llp is the same
15896 	 * as that found in the active lock list, "list". The intersecting
15897 	 * region locks are added to ri_llp in increasing l_start order.
15898 	 */
15899 	ASSERT(nfs_zone() == mi->mi_zone);
15900 
15901 	locks = flk_active_locks_for_vp(vp);
15902 	ri_llp = NULL;
15903 
15904 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15905 		ASSERT(llp->ll_vp == vp);
15906 		/*
15907 		 * Pick locks that belong to this pid/lockowner
15908 		 */
15909 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15910 			continue;
15911 
15912 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15913 	}
15914 
15915 	/*
15916 	 * Now we have the list of intersections with the lost lock. These are
15917 	 * the locks that were/are active before the server replied to the
15918 	 * last/lost lock. Issue these locks to the server here. Playing these
15919 	 * locks to the server will re-establish aur current local locking state
15920 	 * with the v4 server.
15921 	 * If we get an error, send SIGLOST to the application for that lock.
15922 	 */
15923 
15924 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15925 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15926 		    "nfs4_reinstitute_local_lock_state: need to issue "
15927 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15928 		    llp->ll_flock.l_start,
15929 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15930 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15931 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15932 		/*
15933 		 * No need to relock what we already have
15934 		 */
15935 		if (llp->ll_flock.l_type == lost_flp->l_type)
15936 			continue;
15937 
15938 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15939 	}
15940 
15941 	/*
15942 	 * Now keeping the start of the lost lock as our reference parse the
15943 	 * newly created ri_llp locklist to find the ranges that we have locked
15944 	 * with the v4 server but not in the current local locking. We need
15945 	 * to unlock these ranges.
15946 	 * These ranges can also be reffered to as those ranges, where the lost
15947 	 * lock does not overlap with the locks in the ri_llp but are locked
15948 	 * since the server replied to the lost lock.
15949 	 */
15950 	cur_start = lost_flp->l_start;
15951 	lost_flp_end = lock_to_end(lost_flp);
15952 
15953 	ul_fl.l_type = F_UNLCK;
15954 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15955 	ul_fl.l_sysid = lost_flp->l_sysid;
15956 	ul_fl.l_pid = lost_flp->l_pid;
15957 
15958 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15959 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15960 
15961 		if (llp->ll_flock.l_start <= cur_start) {
15962 			cur_start = start_check(llp_ll_flock_end);
15963 			continue;
15964 		}
15965 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15966 		    "nfs4_reinstitute_local_lock_state: "
15967 		    "UNLOCK [%"PRIx64" - %"PRIx64"]",
15968 		    cur_start, llp->ll_flock.l_start));
15969 
15970 		ul_fl.l_start = cur_start;
15971 		ul_fl.l_len = end_to_len(cur_start,
15972 		    (llp->ll_flock.l_start - 1));
15973 
15974 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15975 		cur_start = start_check(llp_ll_flock_end);
15976 	}
15977 
15978 	/*
15979 	 * In the case where the lost lock ends after all intersecting locks,
15980 	 * unlock the last part of the lost lock range.
15981 	 */
15982 	if (cur_start != start_check(lost_flp_end)) {
15983 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15984 		    "nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15985 		    "lost lock region [%"PRIx64" - %"PRIx64"]",
15986 		    cur_start, lost_flp->l_start + lost_flp->l_len));
15987 
15988 		ul_fl.l_start = cur_start;
15989 		/*
15990 		 * Is it an to-EOF lock? if so unlock till the end
15991 		 */
15992 		if (lost_flp->l_len == 0)
15993 			ul_fl.l_len = 0;
15994 		else
15995 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15996 
15997 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15998 	}
15999 
16000 	if (locks != NULL)
16001 		flk_free_locklist(locks);
16002 
16003 	/* Free up our newly created locklist */
16004 	for (llp = ri_llp; llp != NULL; ) {
16005 		tmp_llp = llp->ll_next;
16006 		kmem_free(llp, sizeof (locklist_t));
16007 		llp = tmp_llp;
16008 	}
16009 
16010 	/*
16011 	 * Now return back to the original calling nfs4frlock()
16012 	 * and let us naturally drop our seqid syncs.
16013 	 */
16014 }
16015 
16016 /*
16017  * Create a lost state record for the given lock reinstantiation request
16018  * and push it onto the lost state queue.
16019  */
16020 static void
16021 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
16022     nfs4_lock_owner_t *lop)
16023 {
16024 	nfs4_lost_rqst_t req;
16025 	nfs_lock_type4 locktype;
16026 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
16027 
16028 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
16029 
16030 	locktype = flk_to_locktype(cmd, flk->l_type);
16031 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
16032 	    NULL, NULL, lop, flk, &req, cr, vp);
16033 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
16034 	    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
16035 	    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
16036 	    NULL, NULL, NULL);
16037 }
16038