xref: /illumos-gate/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision 5328fc53d11d7151861fa272e4fb0248b8f0e145)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2016 STRATO AG. All rights reserved.
24  */
25 
26 /*
27  * Copyright 2015 Nexenta Systems, Inc.  All rights reserved.
28  */
29 
30 /*
31  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
32  * Use is subject to license terms.
33  */
34 
35 /*
36  *	Copyright 1983,1984,1985,1986,1987,1988,1989 AT&T.
37  *	All Rights Reserved
38  */
39 
40 /*
41  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
42  */
43 
44 #include <sys/param.h>
45 #include <sys/types.h>
46 #include <sys/systm.h>
47 #include <sys/cred.h>
48 #include <sys/time.h>
49 #include <sys/vnode.h>
50 #include <sys/vfs.h>
51 #include <sys/vfs_opreg.h>
52 #include <sys/file.h>
53 #include <sys/filio.h>
54 #include <sys/uio.h>
55 #include <sys/buf.h>
56 #include <sys/mman.h>
57 #include <sys/pathname.h>
58 #include <sys/dirent.h>
59 #include <sys/debug.h>
60 #include <sys/vmsystm.h>
61 #include <sys/fcntl.h>
62 #include <sys/flock.h>
63 #include <sys/swap.h>
64 #include <sys/errno.h>
65 #include <sys/strsubr.h>
66 #include <sys/sysmacros.h>
67 #include <sys/kmem.h>
68 #include <sys/cmn_err.h>
69 #include <sys/pathconf.h>
70 #include <sys/utsname.h>
71 #include <sys/dnlc.h>
72 #include <sys/acl.h>
73 #include <sys/systeminfo.h>
74 #include <sys/policy.h>
75 #include <sys/sdt.h>
76 #include <sys/list.h>
77 #include <sys/stat.h>
78 #include <sys/zone.h>
79 
80 #include <rpc/types.h>
81 #include <rpc/auth.h>
82 #include <rpc/clnt.h>
83 
84 #include <nfs/nfs.h>
85 #include <nfs/nfs_clnt.h>
86 #include <nfs/nfs_acl.h>
87 #include <nfs/lm.h>
88 #include <nfs/nfs4.h>
89 #include <nfs/nfs4_kprot.h>
90 #include <nfs/rnode4.h>
91 #include <nfs/nfs4_clnt.h>
92 
93 #include <vm/hat.h>
94 #include <vm/as.h>
95 #include <vm/page.h>
96 #include <vm/pvn.h>
97 #include <vm/seg.h>
98 #include <vm/seg_map.h>
99 #include <vm/seg_kpm.h>
100 #include <vm/seg_vn.h>
101 
102 #include <fs/fs_subr.h>
103 
104 #include <sys/ddi.h>
105 #include <sys/int_fmtio.h>
106 #include <sys/fs/autofs.h>
107 
108 typedef struct {
109 	nfs4_ga_res_t	*di_garp;
110 	cred_t		*di_cred;
111 	hrtime_t	di_time_call;
112 } dirattr_info_t;
113 
114 typedef enum nfs4_acl_op {
115 	NFS4_ACL_GET,
116 	NFS4_ACL_SET
117 } nfs4_acl_op_t;
118 
119 static struct lm_sysid *nfs4_find_sysid(mntinfo4_t *);
120 
121 static void	nfs4_update_dircaches(change_info4 *, vnode_t *, vnode_t *,
122 			char *, dirattr_info_t *);
123 
124 static void	nfs4close_otw(rnode4_t *, cred_t *, nfs4_open_owner_t *,
125 		    nfs4_open_stream_t *, int *, int *, nfs4_close_type_t,
126 		    nfs4_error_t *, int *);
127 static int	nfs4_rdwrlbn(vnode_t *, page_t *, u_offset_t, size_t, int,
128 			cred_t *);
129 static int	nfs4write(vnode_t *, caddr_t, u_offset_t, int, cred_t *,
130 			stable_how4 *);
131 static int	nfs4read(vnode_t *, caddr_t, offset_t, int, size_t *,
132 			cred_t *, bool_t, struct uio *);
133 static int	nfs4setattr(vnode_t *, struct vattr *, int, cred_t *,
134 			vsecattr_t *);
135 static int	nfs4openattr(vnode_t *, vnode_t **, int, cred_t *);
136 static int	nfs4lookup(vnode_t *, char *, vnode_t **, cred_t *, int);
137 static int	nfs4lookup_xattr(vnode_t *, char *, vnode_t **, int, cred_t *);
138 static int	nfs4lookupvalidate_otw(vnode_t *, char *, vnode_t **, cred_t *);
139 static int	nfs4lookupnew_otw(vnode_t *, char *, vnode_t **, cred_t *);
140 static int	nfs4mknod(vnode_t *, char *, struct vattr *, enum vcexcl,
141 			int, vnode_t **, cred_t *);
142 static int	nfs4open_otw(vnode_t *, char *, struct vattr *, vnode_t **,
143 			cred_t *, int, int, enum createmode4, int);
144 static int	nfs4rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
145 			caller_context_t *);
146 static int	nfs4rename_persistent_fh(vnode_t *, char *, vnode_t *,
147 			vnode_t *, char *, cred_t *, nfsstat4 *);
148 static int	nfs4rename_volatile_fh(vnode_t *, char *, vnode_t *,
149 			vnode_t *, char *, cred_t *, nfsstat4 *);
150 static int	do_nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
151 static void	nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
152 static int	nfs4_bio(struct buf *, stable_how4 *, cred_t *, bool_t);
153 static int	nfs4_getapage(vnode_t *, u_offset_t, size_t, uint_t *,
154 			page_t *[], size_t, struct seg *, caddr_t,
155 			enum seg_rw, cred_t *);
156 static void	nfs4_readahead(vnode_t *, u_offset_t, caddr_t, struct seg *,
157 			cred_t *);
158 static int	nfs4_sync_putapage(vnode_t *, page_t *, u_offset_t, size_t,
159 			int, cred_t *);
160 static int	nfs4_sync_pageio(vnode_t *, page_t *, u_offset_t, size_t,
161 			int, cred_t *);
162 static int	nfs4_commit(vnode_t *, offset4, count4, cred_t *);
163 static void	nfs4_set_mod(vnode_t *);
164 static void	nfs4_get_commit(vnode_t *);
165 static void	nfs4_get_commit_range(vnode_t *, u_offset_t, size_t);
166 static int	nfs4_putpage_commit(vnode_t *, offset_t, size_t, cred_t *);
167 static int	nfs4_commit_vp(vnode_t *, u_offset_t, size_t, cred_t *, int);
168 static int	nfs4_sync_commit(vnode_t *, page_t *, offset3, count3,
169 			cred_t *);
170 static void	do_nfs4_async_commit(vnode_t *, page_t *, offset3, count3,
171 			cred_t *);
172 static int	nfs4_update_attrcache(nfsstat4, nfs4_ga_res_t *,
173 			hrtime_t, vnode_t *, cred_t *);
174 static int	nfs4_open_non_reg_file(vnode_t **, int, cred_t *);
175 static int	nfs4_safelock(vnode_t *, const struct flock64 *, cred_t *);
176 static void	nfs4_register_lock_locally(vnode_t *, struct flock64 *, int,
177 			u_offset_t);
178 static int	nfs4_lockrelease(vnode_t *, int, offset_t, cred_t *);
179 static int	nfs4_block_and_wait(clock_t *, rnode4_t *);
180 static cred_t  *state_to_cred(nfs4_open_stream_t *);
181 static void	denied_to_flk(LOCK4denied *, flock64_t *, LOCKT4args *);
182 static pid_t	lo_to_pid(lock_owner4 *);
183 static void	nfs4_reinstitute_local_lock_state(vnode_t *, flock64_t *,
184 			cred_t *, nfs4_lock_owner_t *);
185 static void	push_reinstate(vnode_t *, int, flock64_t *, cred_t *,
186 			nfs4_lock_owner_t *);
187 static int	open_and_get_osp(vnode_t *, cred_t *, nfs4_open_stream_t **);
188 static void	nfs4_delmap_callback(struct as *, void *, uint_t);
189 static void	nfs4_free_delmapcall(nfs4_delmapcall_t *);
190 static nfs4_delmapcall_t	*nfs4_init_delmapcall();
191 static int	nfs4_find_and_delete_delmapcall(rnode4_t *, int *);
192 static int	nfs4_is_acl_mask_valid(uint_t, nfs4_acl_op_t);
193 static int	nfs4_create_getsecattr_return(vsecattr_t *, vsecattr_t *,
194 			uid_t, gid_t, int);
195 
196 /*
197  * Routines that implement the setting of v4 args for the misc. ops
198  */
199 static void	nfs4args_lock_free(nfs_argop4 *);
200 static void	nfs4args_lockt_free(nfs_argop4 *);
201 static void	nfs4args_setattr(nfs_argop4 *, vattr_t *, vsecattr_t *,
202 			int, rnode4_t *, cred_t *, bitmap4, int *,
203 			nfs4_stateid_types_t *);
204 static void	nfs4args_setattr_free(nfs_argop4 *);
205 static int	nfs4args_verify(nfs_argop4 *, vattr_t *, enum nfs_opnum4,
206 			bitmap4);
207 static void	nfs4args_verify_free(nfs_argop4 *);
208 static void	nfs4args_write(nfs_argop4 *, stable_how4, rnode4_t *, cred_t *,
209 			WRITE4args **, nfs4_stateid_types_t *);
210 
211 /*
212  * These are the vnode ops functions that implement the vnode interface to
213  * the networked file system.  See more comments below at nfs4_vnodeops.
214  */
215 static int	nfs4_open(vnode_t **, int, cred_t *, caller_context_t *);
216 static int	nfs4_close(vnode_t *, int, int, offset_t, cred_t *,
217 			caller_context_t *);
218 static int	nfs4_read(vnode_t *, struct uio *, int, cred_t *,
219 			caller_context_t *);
220 static int	nfs4_write(vnode_t *, struct uio *, int, cred_t *,
221 			caller_context_t *);
222 static int	nfs4_ioctl(vnode_t *, int, intptr_t, int, cred_t *, int *,
223 			caller_context_t *);
224 static int	nfs4_setattr(vnode_t *, struct vattr *, int, cred_t *,
225 			caller_context_t *);
226 static int	nfs4_access(vnode_t *, int, int, cred_t *, caller_context_t *);
227 static int	nfs4_readlink(vnode_t *, struct uio *, cred_t *,
228 			caller_context_t *);
229 static int	nfs4_fsync(vnode_t *, int, cred_t *, caller_context_t *);
230 static int	nfs4_create(vnode_t *, char *, struct vattr *, enum vcexcl,
231 			int, vnode_t **, cred_t *, int, caller_context_t *,
232 			vsecattr_t *);
233 static int	nfs4_remove(vnode_t *, char *, cred_t *, caller_context_t *,
234 			int);
235 static int	nfs4_link(vnode_t *, vnode_t *, char *, cred_t *,
236 			caller_context_t *, int);
237 static int	nfs4_rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
238 			caller_context_t *, int);
239 static int	nfs4_mkdir(vnode_t *, char *, struct vattr *, vnode_t **,
240 			cred_t *, caller_context_t *, int, vsecattr_t *);
241 static int	nfs4_rmdir(vnode_t *, char *, vnode_t *, cred_t *,
242 			caller_context_t *, int);
243 static int	nfs4_symlink(vnode_t *, char *, struct vattr *, char *,
244 			cred_t *, caller_context_t *, int);
245 static int	nfs4_readdir(vnode_t *, struct uio *, cred_t *, int *,
246 			caller_context_t *, int);
247 static int	nfs4_seek(vnode_t *, offset_t, offset_t *, caller_context_t *);
248 static int	nfs4_getpage(vnode_t *, offset_t, size_t, uint_t *,
249 			page_t *[], size_t, struct seg *, caddr_t,
250 			enum seg_rw, cred_t *, caller_context_t *);
251 static int	nfs4_putpage(vnode_t *, offset_t, size_t, int, cred_t *,
252 			caller_context_t *);
253 static int	nfs4_map(vnode_t *, offset_t, struct as *, caddr_t *, size_t,
254 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
255 static int	nfs4_addmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
256 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
257 static int	nfs4_cmp(vnode_t *, vnode_t *, caller_context_t *);
258 static int	nfs4_frlock(vnode_t *, int, struct flock64 *, int, offset_t,
259 			struct flk_callback *, cred_t *, caller_context_t *);
260 static int	nfs4_space(vnode_t *, int, struct flock64 *, int, offset_t,
261 			cred_t *, caller_context_t *);
262 static int	nfs4_delmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
263 			uint_t, uint_t, uint_t, cred_t *, caller_context_t *);
264 static int	nfs4_pageio(vnode_t *, page_t *, u_offset_t, size_t, int,
265 			cred_t *, caller_context_t *);
266 static void	nfs4_dispose(vnode_t *, page_t *, int, int, cred_t *,
267 			caller_context_t *);
268 static int	nfs4_setsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
269 			caller_context_t *);
270 /*
271  * These vnode ops are required to be called from outside this source file,
272  * e.g. by ephemeral mount stub vnode ops, and so may not be declared
273  * as static.
274  */
275 int	nfs4_getattr(vnode_t *, struct vattr *, int, cred_t *,
276 	    caller_context_t *);
277 void	nfs4_inactive(vnode_t *, cred_t *, caller_context_t *);
278 int	nfs4_lookup(vnode_t *, char *, vnode_t **,
279 	    struct pathname *, int, vnode_t *, cred_t *,
280 	    caller_context_t *, int *, pathname_t *);
281 int	nfs4_fid(vnode_t *, fid_t *, caller_context_t *);
282 int	nfs4_rwlock(vnode_t *, int, caller_context_t *);
283 void	nfs4_rwunlock(vnode_t *, int, caller_context_t *);
284 int	nfs4_realvp(vnode_t *, vnode_t **, caller_context_t *);
285 int	nfs4_pathconf(vnode_t *, int, ulong_t *, cred_t *,
286 	    caller_context_t *);
287 int	nfs4_getsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
288 	    caller_context_t *);
289 int	nfs4_shrlock(vnode_t *, int, struct shrlock *, int, cred_t *,
290 	    caller_context_t *);
291 
292 /*
293  * Used for nfs4_commit_vp() to indicate if we should
294  * wait on pending writes.
295  */
296 #define	NFS4_WRITE_NOWAIT	0
297 #define	NFS4_WRITE_WAIT		1
298 
299 #define	NFS4_BASE_WAIT_TIME 1	/* 1 second */
300 
301 /*
302  * Error flags used to pass information about certain special errors
303  * which need to be handled specially.
304  */
305 #define	NFS_EOF			-98
306 #define	NFS_VERF_MISMATCH	-97
307 
308 /*
309  * Flags used to differentiate between which operation drove the
310  * potential CLOSE OTW. (see nfs4_close_otw_if_necessary)
311  */
312 #define	NFS4_CLOSE_OP		0x1
313 #define	NFS4_DELMAP_OP		0x2
314 #define	NFS4_INACTIVE_OP	0x3
315 
316 #define	ISVDEV(t) ((t == VBLK) || (t == VCHR) || (t == VFIFO))
317 
318 /* ALIGN64 aligns the given buffer and adjust buffer size to 64 bit */
319 #define	ALIGN64(x, ptr, sz)						\
320 	x = ((uintptr_t)(ptr)) & (sizeof (uint64_t) - 1);		\
321 	if (x) {							\
322 		x = sizeof (uint64_t) - (x);				\
323 		sz -= (x);						\
324 		ptr += (x);						\
325 	}
326 
327 #ifdef DEBUG
328 int nfs4_client_attr_debug = 0;
329 int nfs4_client_state_debug = 0;
330 int nfs4_client_shadow_debug = 0;
331 int nfs4_client_lock_debug = 0;
332 int nfs4_seqid_sync = 0;
333 int nfs4_client_map_debug = 0;
334 static int nfs4_pageio_debug = 0;
335 int nfs4_client_inactive_debug = 0;
336 int nfs4_client_recov_debug = 0;
337 int nfs4_client_failover_debug = 0;
338 int nfs4_client_call_debug = 0;
339 int nfs4_client_lookup_debug = 0;
340 int nfs4_client_zone_debug = 0;
341 int nfs4_lost_rqst_debug = 0;
342 int nfs4_rdattrerr_debug = 0;
343 int nfs4_open_stream_debug = 0;
344 
345 int nfs4read_error_inject;
346 
347 static int nfs4_create_misses = 0;
348 
349 static int nfs4_readdir_cache_shorts = 0;
350 static int nfs4_readdir_readahead = 0;
351 
352 static int nfs4_bio_do_stop = 0;
353 
354 static int nfs4_lostpage = 0;	/* number of times we lost original page */
355 
356 int nfs4_mmap_debug = 0;
357 
358 static int nfs4_pathconf_cache_hits = 0;
359 static int nfs4_pathconf_cache_misses = 0;
360 
361 int nfs4close_all_cnt;
362 int nfs4close_one_debug = 0;
363 int nfs4close_notw_debug = 0;
364 
365 int denied_to_flk_debug = 0;
366 void *lockt_denied_debug;
367 
368 #endif
369 
370 /*
371  * How long to wait before trying again if OPEN_CONFIRM gets ETIMEDOUT
372  * or NFS4ERR_RESOURCE.
373  */
374 static int confirm_retry_sec = 30;
375 
376 static int nfs4_lookup_neg_cache = 1;
377 
378 /*
379  * number of pages to read ahead
380  * optimized for 100 base-T.
381  */
382 static int nfs4_nra = 4;
383 
384 static int nfs4_do_symlink_cache = 1;
385 
386 static int nfs4_pathconf_disable_cache = 0;
387 
388 /*
389  * These are the vnode ops routines which implement the vnode interface to
390  * the networked file system.  These routines just take their parameters,
391  * make them look networkish by putting the right info into interface structs,
392  * and then calling the appropriate remote routine(s) to do the work.
393  *
394  * Note on directory name lookup cacheing:  If we detect a stale fhandle,
395  * we purge the directory cache relative to that vnode.  This way, the
396  * user won't get burned by the cache repeatedly.  See <nfs/rnode4.h> for
397  * more details on rnode locking.
398  */
399 
400 struct vnodeops *nfs4_vnodeops;
401 
402 const fs_operation_def_t nfs4_vnodeops_template[] = {
403 	VOPNAME_OPEN,		{ .vop_open = nfs4_open },
404 	VOPNAME_CLOSE,		{ .vop_close = nfs4_close },
405 	VOPNAME_READ,		{ .vop_read = nfs4_read },
406 	VOPNAME_WRITE,		{ .vop_write = nfs4_write },
407 	VOPNAME_IOCTL,		{ .vop_ioctl = nfs4_ioctl },
408 	VOPNAME_GETATTR,	{ .vop_getattr = nfs4_getattr },
409 	VOPNAME_SETATTR,	{ .vop_setattr = nfs4_setattr },
410 	VOPNAME_ACCESS,		{ .vop_access = nfs4_access },
411 	VOPNAME_LOOKUP,		{ .vop_lookup = nfs4_lookup },
412 	VOPNAME_CREATE,		{ .vop_create = nfs4_create },
413 	VOPNAME_REMOVE,		{ .vop_remove = nfs4_remove },
414 	VOPNAME_LINK,		{ .vop_link = nfs4_link },
415 	VOPNAME_RENAME,		{ .vop_rename = nfs4_rename },
416 	VOPNAME_MKDIR,		{ .vop_mkdir = nfs4_mkdir },
417 	VOPNAME_RMDIR,		{ .vop_rmdir = nfs4_rmdir },
418 	VOPNAME_READDIR,	{ .vop_readdir = nfs4_readdir },
419 	VOPNAME_SYMLINK,	{ .vop_symlink = nfs4_symlink },
420 	VOPNAME_READLINK,	{ .vop_readlink = nfs4_readlink },
421 	VOPNAME_FSYNC,		{ .vop_fsync = nfs4_fsync },
422 	VOPNAME_INACTIVE,	{ .vop_inactive = nfs4_inactive },
423 	VOPNAME_FID,		{ .vop_fid = nfs4_fid },
424 	VOPNAME_RWLOCK,		{ .vop_rwlock = nfs4_rwlock },
425 	VOPNAME_RWUNLOCK,	{ .vop_rwunlock = nfs4_rwunlock },
426 	VOPNAME_SEEK,		{ .vop_seek = nfs4_seek },
427 	VOPNAME_FRLOCK,		{ .vop_frlock = nfs4_frlock },
428 	VOPNAME_SPACE,		{ .vop_space = nfs4_space },
429 	VOPNAME_REALVP,		{ .vop_realvp = nfs4_realvp },
430 	VOPNAME_GETPAGE,	{ .vop_getpage = nfs4_getpage },
431 	VOPNAME_PUTPAGE,	{ .vop_putpage = nfs4_putpage },
432 	VOPNAME_MAP,		{ .vop_map = nfs4_map },
433 	VOPNAME_ADDMAP,		{ .vop_addmap = nfs4_addmap },
434 	VOPNAME_DELMAP,		{ .vop_delmap = nfs4_delmap },
435 	/* no separate nfs4_dump */
436 	VOPNAME_DUMP,		{ .vop_dump = nfs_dump },
437 	VOPNAME_PATHCONF,	{ .vop_pathconf = nfs4_pathconf },
438 	VOPNAME_PAGEIO,		{ .vop_pageio = nfs4_pageio },
439 	VOPNAME_DISPOSE,	{ .vop_dispose = nfs4_dispose },
440 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = nfs4_setsecattr },
441 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = nfs4_getsecattr },
442 	VOPNAME_SHRLOCK,	{ .vop_shrlock = nfs4_shrlock },
443 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
444 	NULL,			NULL
445 };
446 
447 /*
448  * The following are subroutines and definitions to set args or get res
449  * for the different nfsv4 ops
450  */
451 
452 void
453 nfs4args_lookup_free(nfs_argop4 *argop, int arglen)
454 {
455 	int		i;
456 
457 	for (i = 0; i < arglen; i++) {
458 		if (argop[i].argop == OP_LOOKUP) {
459 			kmem_free(
460 			    argop[i].nfs_argop4_u.oplookup.
461 			    objname.utf8string_val,
462 			    argop[i].nfs_argop4_u.oplookup.
463 			    objname.utf8string_len);
464 		}
465 	}
466 }
467 
468 static void
469 nfs4args_lock_free(nfs_argop4 *argop)
470 {
471 	locker4 *locker = &argop->nfs_argop4_u.oplock.locker;
472 
473 	if (locker->new_lock_owner == TRUE) {
474 		open_to_lock_owner4 *open_owner;
475 
476 		open_owner = &locker->locker4_u.open_owner;
477 		if (open_owner->lock_owner.owner_val != NULL) {
478 			kmem_free(open_owner->lock_owner.owner_val,
479 			    open_owner->lock_owner.owner_len);
480 		}
481 	}
482 }
483 
484 static void
485 nfs4args_lockt_free(nfs_argop4 *argop)
486 {
487 	lock_owner4 *lowner = &argop->nfs_argop4_u.oplockt.owner;
488 
489 	if (lowner->owner_val != NULL) {
490 		kmem_free(lowner->owner_val, lowner->owner_len);
491 	}
492 }
493 
494 static void
495 nfs4args_setattr(nfs_argop4 *argop, vattr_t *vap, vsecattr_t *vsap, int flags,
496     rnode4_t *rp, cred_t *cr, bitmap4 supp, int *error,
497     nfs4_stateid_types_t *sid_types)
498 {
499 	fattr4		*attr = &argop->nfs_argop4_u.opsetattr.obj_attributes;
500 	mntinfo4_t	*mi;
501 
502 	argop->argop = OP_SETATTR;
503 	/*
504 	 * The stateid is set to 0 if client is not modifying the size
505 	 * and otherwise to whatever nfs4_get_stateid() returns.
506 	 *
507 	 * XXX Note: nfs4_get_stateid() returns 0 if no lockowner and/or no
508 	 * state struct could be found for the process/file pair.  We may
509 	 * want to change this in the future (by OPENing the file).  See
510 	 * bug # 4474852.
511 	 */
512 	if (vap->va_mask & AT_SIZE) {
513 
514 		ASSERT(rp != NULL);
515 		mi = VTOMI4(RTOV4(rp));
516 
517 		argop->nfs_argop4_u.opsetattr.stateid =
518 		    nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
519 		    OP_SETATTR, sid_types, FALSE);
520 	} else {
521 		bzero(&argop->nfs_argop4_u.opsetattr.stateid,
522 		    sizeof (stateid4));
523 	}
524 
525 	*error = vattr_to_fattr4(vap, vsap, attr, flags, OP_SETATTR, supp);
526 	if (*error)
527 		bzero(attr, sizeof (*attr));
528 }
529 
530 static void
531 nfs4args_setattr_free(nfs_argop4 *argop)
532 {
533 	nfs4_fattr4_free(&argop->nfs_argop4_u.opsetattr.obj_attributes);
534 }
535 
536 static int
537 nfs4args_verify(nfs_argop4 *argop, vattr_t *vap, enum nfs_opnum4 op,
538     bitmap4 supp)
539 {
540 	fattr4 *attr;
541 	int error = 0;
542 
543 	argop->argop = op;
544 	switch (op) {
545 	case OP_VERIFY:
546 		attr = &argop->nfs_argop4_u.opverify.obj_attributes;
547 		break;
548 	case OP_NVERIFY:
549 		attr = &argop->nfs_argop4_u.opnverify.obj_attributes;
550 		break;
551 	default:
552 		return (EINVAL);
553 	}
554 	if (!error)
555 		error = vattr_to_fattr4(vap, NULL, attr, 0, op, supp);
556 	if (error)
557 		bzero(attr, sizeof (*attr));
558 	return (error);
559 }
560 
561 static void
562 nfs4args_verify_free(nfs_argop4 *argop)
563 {
564 	switch (argop->argop) {
565 	case OP_VERIFY:
566 		nfs4_fattr4_free(&argop->nfs_argop4_u.opverify.obj_attributes);
567 		break;
568 	case OP_NVERIFY:
569 		nfs4_fattr4_free(&argop->nfs_argop4_u.opnverify.obj_attributes);
570 		break;
571 	default:
572 		break;
573 	}
574 }
575 
576 static void
577 nfs4args_write(nfs_argop4 *argop, stable_how4 stable, rnode4_t *rp, cred_t *cr,
578     WRITE4args **wargs_pp, nfs4_stateid_types_t *sid_tp)
579 {
580 	WRITE4args *wargs = &argop->nfs_argop4_u.opwrite;
581 	mntinfo4_t *mi = VTOMI4(RTOV4(rp));
582 
583 	argop->argop = OP_WRITE;
584 	wargs->stable = stable;
585 	wargs->stateid = nfs4_get_w_stateid(cr, rp, curproc->p_pidp->pid_id,
586 	    mi, OP_WRITE, sid_tp);
587 	wargs->mblk = NULL;
588 	*wargs_pp = wargs;
589 }
590 
591 void
592 nfs4args_copen_free(OPEN4cargs *open_args)
593 {
594 	if (open_args->owner.owner_val) {
595 		kmem_free(open_args->owner.owner_val,
596 		    open_args->owner.owner_len);
597 	}
598 	if ((open_args->opentype == OPEN4_CREATE) &&
599 	    (open_args->mode != EXCLUSIVE4)) {
600 		nfs4_fattr4_free(&open_args->createhow4_u.createattrs);
601 	}
602 }
603 
604 /*
605  * XXX:  This is referenced in modstubs.s
606  */
607 struct vnodeops *
608 nfs4_getvnodeops(void)
609 {
610 	return (nfs4_vnodeops);
611 }
612 
613 /*
614  * The OPEN operation opens a regular file.
615  */
616 /*ARGSUSED3*/
617 static int
618 nfs4_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
619 {
620 	vnode_t *dvp = NULL;
621 	rnode4_t *rp, *drp;
622 	int error;
623 	int just_been_created;
624 	char fn[MAXNAMELEN];
625 
626 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4_open: "));
627 	if (nfs_zone() != VTOMI4(*vpp)->mi_zone)
628 		return (EIO);
629 	rp = VTOR4(*vpp);
630 
631 	/*
632 	 * Check to see if opening something besides a regular file;
633 	 * if so skip the OTW call
634 	 */
635 	if ((*vpp)->v_type != VREG) {
636 		error = nfs4_open_non_reg_file(vpp, flag, cr);
637 		return (error);
638 	}
639 
640 	/*
641 	 * XXX - would like a check right here to know if the file is
642 	 * executable or not, so as to skip OTW
643 	 */
644 
645 	if ((error = vtodv(*vpp, &dvp, cr, TRUE)) != 0)
646 		return (error);
647 
648 	drp = VTOR4(dvp);
649 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
650 		return (EINTR);
651 
652 	if ((error = vtoname(*vpp, fn, MAXNAMELEN)) != 0) {
653 		nfs_rw_exit(&drp->r_rwlock);
654 		return (error);
655 	}
656 
657 	/*
658 	 * See if this file has just been CREATEd.
659 	 * If so, clear the flag and update the dnlc, which was previously
660 	 * skipped in nfs4_create.
661 	 * XXX need better serilization on this.
662 	 * XXX move this into the nf4open_otw call, after we have
663 	 * XXX acquired the open owner seqid sync.
664 	 */
665 	mutex_enter(&rp->r_statev4_lock);
666 	if (rp->created_v4) {
667 		rp->created_v4 = 0;
668 		mutex_exit(&rp->r_statev4_lock);
669 
670 		dnlc_update(dvp, fn, *vpp);
671 		/* This is needed so we don't bump the open ref count */
672 		just_been_created = 1;
673 	} else {
674 		mutex_exit(&rp->r_statev4_lock);
675 		just_been_created = 0;
676 	}
677 
678 	/*
679 	 * If caller specified O_TRUNC/FTRUNC, then be sure to set
680 	 * FWRITE (to drive successful setattr(size=0) after open)
681 	 */
682 	if (flag & FTRUNC)
683 		flag |= FWRITE;
684 
685 	error = nfs4open_otw(dvp, fn, NULL, vpp, cr, 0, flag, 0,
686 	    just_been_created);
687 
688 	if (!error && !((*vpp)->v_flag & VROOT))
689 		dnlc_update(dvp, fn, *vpp);
690 
691 	nfs_rw_exit(&drp->r_rwlock);
692 
693 	/* release the hold from vtodv */
694 	VN_RELE(dvp);
695 
696 	/* exchange the shadow for the master vnode, if needed */
697 
698 	if (error == 0 && IS_SHADOW(*vpp, rp))
699 		sv_exchange(vpp);
700 
701 	return (error);
702 }
703 
704 /*
705  * See if there's a "lost open" request to be saved and recovered.
706  */
707 static void
708 nfs4open_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
709     nfs4_open_owner_t *oop, cred_t *cr, vnode_t *vp,
710     vnode_t *dvp, OPEN4cargs *open_args)
711 {
712 	vfs_t *vfsp;
713 	char *srccfp;
714 
715 	vfsp = (dvp ? dvp->v_vfsp : vp->v_vfsp);
716 
717 	if (error != ETIMEDOUT && error != EINTR &&
718 	    !NFS4_FRC_UNMT_ERR(error, vfsp)) {
719 		lost_rqstp->lr_op = 0;
720 		return;
721 	}
722 
723 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
724 	    "nfs4open_save_lost_rqst: error %d", error));
725 
726 	lost_rqstp->lr_op = OP_OPEN;
727 
728 	/*
729 	 * The vp (if it is not NULL) and dvp are held and rele'd via
730 	 * the recovery code.  See nfs4_save_lost_rqst.
731 	 */
732 	lost_rqstp->lr_vp = vp;
733 	lost_rqstp->lr_dvp = dvp;
734 	lost_rqstp->lr_oop = oop;
735 	lost_rqstp->lr_osp = NULL;
736 	lost_rqstp->lr_lop = NULL;
737 	lost_rqstp->lr_cr = cr;
738 	lost_rqstp->lr_flk = NULL;
739 	lost_rqstp->lr_oacc = open_args->share_access;
740 	lost_rqstp->lr_odeny = open_args->share_deny;
741 	lost_rqstp->lr_oclaim = open_args->claim;
742 	if (open_args->claim == CLAIM_DELEGATE_CUR) {
743 		lost_rqstp->lr_ostateid =
744 		    open_args->open_claim4_u.delegate_cur_info.delegate_stateid;
745 		srccfp = open_args->open_claim4_u.delegate_cur_info.cfile;
746 	} else {
747 		srccfp = open_args->open_claim4_u.cfile;
748 	}
749 	lost_rqstp->lr_ofile.utf8string_len = 0;
750 	lost_rqstp->lr_ofile.utf8string_val = NULL;
751 	(void) str_to_utf8(srccfp, &lost_rqstp->lr_ofile);
752 	lost_rqstp->lr_putfirst = FALSE;
753 }
754 
755 struct nfs4_excl_time {
756 	uint32 seconds;
757 	uint32 nseconds;
758 };
759 
760 /*
761  * The OPEN operation creates and/or opens a regular file
762  *
763  * ARGSUSED
764  */
765 static int
766 nfs4open_otw(vnode_t *dvp, char *file_name, struct vattr *in_va,
767     vnode_t **vpp, cred_t *cr, int create_flag, int open_flag,
768     enum createmode4 createmode, int file_just_been_created)
769 {
770 	rnode4_t *rp;
771 	rnode4_t *drp = VTOR4(dvp);
772 	vnode_t *vp = NULL;
773 	vnode_t *vpi = *vpp;
774 	bool_t needrecov = FALSE;
775 
776 	int doqueue = 1;
777 
778 	COMPOUND4args_clnt args;
779 	COMPOUND4res_clnt res;
780 	nfs_argop4 *argop;
781 	nfs_resop4 *resop;
782 	int argoplist_size;
783 	int idx_open, idx_fattr;
784 
785 	GETFH4res *gf_res = NULL;
786 	OPEN4res *op_res = NULL;
787 	nfs4_ga_res_t *garp;
788 	fattr4 *attr = NULL;
789 	struct nfs4_excl_time verf;
790 	bool_t did_excl_setup = FALSE;
791 	int created_osp;
792 
793 	OPEN4cargs *open_args;
794 	nfs4_open_owner_t	*oop = NULL;
795 	nfs4_open_stream_t	*osp = NULL;
796 	seqid4 seqid = 0;
797 	bool_t retry_open = FALSE;
798 	nfs4_recov_state_t recov_state;
799 	nfs4_lost_rqst_t lost_rqst;
800 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
801 	hrtime_t t;
802 	int acc = 0;
803 	cred_t *cred_otw = NULL;	/* cred used to do the RPC call */
804 	cred_t *ncr = NULL;
805 
806 	nfs4_sharedfh_t *otw_sfh;
807 	nfs4_sharedfh_t *orig_sfh;
808 	int fh_differs = 0;
809 	int numops, setgid_flag;
810 	int num_bseqid_retry = NFS4_NUM_RETRY_BAD_SEQID + 1;
811 
812 	/*
813 	 * Make sure we properly deal with setting the right gid on
814 	 * a newly created file to reflect the parent's setgid bit
815 	 */
816 	setgid_flag = 0;
817 	if (create_flag && in_va) {
818 
819 		/*
820 		 * If there is grpid mount flag used or
821 		 * the parent's directory has the setgid bit set
822 		 * _and_ the client was able to get a valid mapping
823 		 * for the parent dir's owner_group, we want to
824 		 * append NVERIFY(owner_group == dva.va_gid) and
825 		 * SETATTR to the CREATE compound.
826 		 */
827 		mutex_enter(&drp->r_statelock);
828 		if ((VTOMI4(dvp)->mi_flags & MI4_GRPID ||
829 		    drp->r_attr.va_mode & VSGID) &&
830 		    drp->r_attr.va_gid != GID_NOBODY) {
831 			in_va->va_mask |= AT_GID;
832 			in_va->va_gid = drp->r_attr.va_gid;
833 			setgid_flag = 1;
834 		}
835 		mutex_exit(&drp->r_statelock);
836 	}
837 
838 	/*
839 	 * Normal/non-create compound:
840 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new)
841 	 *
842 	 * Open(create) compound no setgid:
843 	 * PUTFH(dfh) + SAVEFH + OPEN(create) + GETFH + GETATTR(new) +
844 	 * RESTOREFH + GETATTR
845 	 *
846 	 * Open(create) setgid:
847 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new) +
848 	 * SAVEFH + PUTFH(dfh) + GETATTR(dvp) + RESTOREFH +
849 	 * NVERIFY(grp) + SETATTR
850 	 */
851 	if (setgid_flag) {
852 		numops = 10;
853 		idx_open = 1;
854 		idx_fattr = 3;
855 	} else if (create_flag) {
856 		numops = 7;
857 		idx_open = 2;
858 		idx_fattr = 4;
859 	} else {
860 		numops = 4;
861 		idx_open = 1;
862 		idx_fattr = 3;
863 	}
864 
865 	args.array_len = numops;
866 	argoplist_size = numops * sizeof (nfs_argop4);
867 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
868 
869 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw: "
870 	    "open %s open flag 0x%x cred %p", file_name, open_flag,
871 	    (void *)cr));
872 
873 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
874 	if (create_flag) {
875 		/*
876 		 * We are to create a file.  Initialize the passed in vnode
877 		 * pointer.
878 		 */
879 		vpi = NULL;
880 	} else {
881 		/*
882 		 * Check to see if the client owns a read delegation and is
883 		 * trying to open for write.  If so, then return the delegation
884 		 * to avoid the server doing a cb_recall and returning DELAY.
885 		 * NB - we don't use the statev4_lock here because we'd have
886 		 * to drop the lock anyway and the result would be stale.
887 		 */
888 		if ((open_flag & FWRITE) &&
889 		    VTOR4(vpi)->r_deleg_type == OPEN_DELEGATE_READ)
890 			(void) nfs4delegreturn(VTOR4(vpi), NFS4_DR_REOPEN);
891 
892 		/*
893 		 * If the file has a delegation, then do an access check up
894 		 * front.  This avoids having to an access check later after
895 		 * we've already done start_op, which could deadlock.
896 		 */
897 		if (VTOR4(vpi)->r_deleg_type != OPEN_DELEGATE_NONE) {
898 			if (open_flag & FREAD &&
899 			    nfs4_access(vpi, VREAD, 0, cr, NULL) == 0)
900 				acc |= VREAD;
901 			if (open_flag & FWRITE &&
902 			    nfs4_access(vpi, VWRITE, 0, cr, NULL) == 0)
903 				acc |= VWRITE;
904 		}
905 	}
906 
907 	drp = VTOR4(dvp);
908 
909 	recov_state.rs_flags = 0;
910 	recov_state.rs_num_retry_despite_err = 0;
911 	cred_otw = cr;
912 
913 recov_retry:
914 	fh_differs = 0;
915 	nfs4_error_zinit(&e);
916 
917 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, vpi, &recov_state);
918 	if (e.error) {
919 		if (ncr != NULL)
920 			crfree(ncr);
921 		kmem_free(argop, argoplist_size);
922 		return (e.error);
923 	}
924 
925 	args.ctag = TAG_OPEN;
926 	args.array_len = numops;
927 	args.array = argop;
928 
929 	/* putfh directory fh */
930 	argop[0].argop = OP_CPUTFH;
931 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
932 
933 	/* OPEN: either op 1 or op 2 depending upon create/setgid flags */
934 	argop[idx_open].argop = OP_COPEN;
935 	open_args = &argop[idx_open].nfs_argop4_u.opcopen;
936 	open_args->claim = CLAIM_NULL;
937 
938 	/* name of file */
939 	open_args->open_claim4_u.cfile = file_name;
940 	open_args->owner.owner_len = 0;
941 	open_args->owner.owner_val = NULL;
942 
943 	if (create_flag) {
944 		/* CREATE a file */
945 		open_args->opentype = OPEN4_CREATE;
946 		open_args->mode = createmode;
947 		if (createmode == EXCLUSIVE4) {
948 			if (did_excl_setup == FALSE) {
949 				verf.seconds = zone_get_hostid(NULL);
950 				if (verf.seconds != 0)
951 					verf.nseconds = newnum();
952 				else {
953 					timestruc_t now;
954 
955 					gethrestime(&now);
956 					verf.seconds = now.tv_sec;
957 					verf.nseconds = now.tv_nsec;
958 				}
959 				/*
960 				 * Since the server will use this value for the
961 				 * mtime, make sure that it can't overflow. Zero
962 				 * out the MSB. The actual value does not matter
963 				 * here, only its uniqeness.
964 				 */
965 				verf.seconds &= INT32_MAX;
966 				did_excl_setup = TRUE;
967 			}
968 
969 			/* Now copy over verifier to OPEN4args. */
970 			open_args->createhow4_u.createverf = *(uint64_t *)&verf;
971 		} else {
972 			int v_error;
973 			bitmap4 supp_attrs;
974 			servinfo4_t *svp;
975 
976 			attr = &open_args->createhow4_u.createattrs;
977 
978 			svp = drp->r_server;
979 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
980 			supp_attrs = svp->sv_supp_attrs;
981 			nfs_rw_exit(&svp->sv_lock);
982 
983 			/* GUARDED4 or UNCHECKED4 */
984 			v_error = vattr_to_fattr4(in_va, NULL, attr, 0, OP_OPEN,
985 			    supp_attrs);
986 			if (v_error) {
987 				bzero(attr, sizeof (*attr));
988 				nfs4args_copen_free(open_args);
989 				nfs4_end_op(VTOMI4(dvp), dvp, vpi,
990 				    &recov_state, FALSE);
991 				if (ncr != NULL)
992 					crfree(ncr);
993 				kmem_free(argop, argoplist_size);
994 				return (v_error);
995 			}
996 		}
997 	} else {
998 		/* NO CREATE */
999 		open_args->opentype = OPEN4_NOCREATE;
1000 	}
1001 
1002 	if (recov_state.rs_sp != NULL) {
1003 		mutex_enter(&recov_state.rs_sp->s_lock);
1004 		open_args->owner.clientid = recov_state.rs_sp->clientid;
1005 		mutex_exit(&recov_state.rs_sp->s_lock);
1006 	} else {
1007 		/* XXX should we just fail here? */
1008 		open_args->owner.clientid = 0;
1009 	}
1010 
1011 	/*
1012 	 * This increments oop's ref count or creates a temporary 'just_created'
1013 	 * open owner that will become valid when this OPEN/OPEN_CONFIRM call
1014 	 * completes.
1015 	 */
1016 	mutex_enter(&VTOMI4(dvp)->mi_lock);
1017 
1018 	/* See if a permanent or just created open owner exists */
1019 	oop = find_open_owner_nolock(cr, NFS4_JUST_CREATED, VTOMI4(dvp));
1020 	if (!oop) {
1021 		/*
1022 		 * This open owner does not exist so create a temporary
1023 		 * just created one.
1024 		 */
1025 		oop = create_open_owner(cr, VTOMI4(dvp));
1026 		ASSERT(oop != NULL);
1027 	}
1028 	mutex_exit(&VTOMI4(dvp)->mi_lock);
1029 
1030 	/* this length never changes, do alloc before seqid sync */
1031 	open_args->owner.owner_len = sizeof (oop->oo_name);
1032 	open_args->owner.owner_val =
1033 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1034 
1035 	e.error = nfs4_start_open_seqid_sync(oop, VTOMI4(dvp));
1036 	if (e.error == EAGAIN) {
1037 		open_owner_rele(oop);
1038 		nfs4args_copen_free(open_args);
1039 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1040 		if (ncr != NULL) {
1041 			crfree(ncr);
1042 			ncr = NULL;
1043 		}
1044 		goto recov_retry;
1045 	}
1046 
1047 	/* Check to see if we need to do the OTW call */
1048 	if (!create_flag) {
1049 		if (!nfs4_is_otw_open_necessary(oop, open_flag, vpi,
1050 		    file_just_been_created, &e.error, acc, &recov_state)) {
1051 
1052 			/*
1053 			 * The OTW open is not necessary.  Either
1054 			 * the open can succeed without it (eg.
1055 			 * delegation, error == 0) or the open
1056 			 * must fail due to an access failure
1057 			 * (error != 0).  In either case, tidy
1058 			 * up and return.
1059 			 */
1060 
1061 			nfs4_end_open_seqid_sync(oop);
1062 			open_owner_rele(oop);
1063 			nfs4args_copen_free(open_args);
1064 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, FALSE);
1065 			if (ncr != NULL)
1066 				crfree(ncr);
1067 			kmem_free(argop, argoplist_size);
1068 			return (e.error);
1069 		}
1070 	}
1071 
1072 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1073 	    open_args->owner.owner_len);
1074 
1075 	seqid = nfs4_get_open_seqid(oop) + 1;
1076 	open_args->seqid = seqid;
1077 	open_args->share_access = 0;
1078 	if (open_flag & FREAD)
1079 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1080 	if (open_flag & FWRITE)
1081 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1082 	open_args->share_deny = OPEN4_SHARE_DENY_NONE;
1083 
1084 
1085 
1086 	/*
1087 	 * getfh w/sanity check for idx_open/idx_fattr
1088 	 */
1089 	ASSERT((idx_open + 1) == (idx_fattr - 1));
1090 	argop[idx_open + 1].argop = OP_GETFH;
1091 
1092 	/* getattr */
1093 	argop[idx_fattr].argop = OP_GETATTR;
1094 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1095 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1096 
1097 	if (setgid_flag) {
1098 		vattr_t	_v;
1099 		servinfo4_t *svp;
1100 		bitmap4	supp_attrs;
1101 
1102 		svp = drp->r_server;
1103 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1104 		supp_attrs = svp->sv_supp_attrs;
1105 		nfs_rw_exit(&svp->sv_lock);
1106 
1107 		/*
1108 		 * For setgid case, we need to:
1109 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1110 		 */
1111 		argop[4].argop = OP_SAVEFH;
1112 
1113 		argop[5].argop = OP_CPUTFH;
1114 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
1115 
1116 		argop[6].argop = OP_GETATTR;
1117 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1118 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1119 
1120 		argop[7].argop = OP_RESTOREFH;
1121 
1122 		/*
1123 		 * nverify
1124 		 */
1125 		_v.va_mask = AT_GID;
1126 		_v.va_gid = in_va->va_gid;
1127 		if (!(e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
1128 		    supp_attrs))) {
1129 
1130 			/*
1131 			 * setattr
1132 			 *
1133 			 * We _know_ we're not messing with AT_SIZE or
1134 			 * AT_XTIME, so no need for stateid or flags.
1135 			 * Also we specify NULL rp since we're only
1136 			 * interested in setting owner_group attributes.
1137 			 */
1138 			nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr,
1139 			    supp_attrs, &e.error, 0);
1140 			if (e.error)
1141 				nfs4args_verify_free(&argop[8]);
1142 		}
1143 
1144 		if (e.error) {
1145 			/*
1146 			 * XXX - Revisit the last argument to nfs4_end_op()
1147 			 *	 once 5020486 is fixed.
1148 			 */
1149 			nfs4_end_open_seqid_sync(oop);
1150 			open_owner_rele(oop);
1151 			nfs4args_copen_free(open_args);
1152 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1153 			if (ncr != NULL)
1154 				crfree(ncr);
1155 			kmem_free(argop, argoplist_size);
1156 			return (e.error);
1157 		}
1158 	} else if (create_flag) {
1159 		argop[1].argop = OP_SAVEFH;
1160 
1161 		argop[5].argop = OP_RESTOREFH;
1162 
1163 		argop[6].argop = OP_GETATTR;
1164 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1165 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1166 	}
1167 
1168 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1169 	    "nfs4open_otw: %s call, nm %s, rp %s",
1170 	    needrecov ? "recov" : "first", file_name,
1171 	    rnode4info(VTOR4(dvp))));
1172 
1173 	t = gethrtime();
1174 
1175 	rfs4call(VTOMI4(dvp), &args, &res, cred_otw, &doqueue, 0, &e);
1176 
1177 	if (!e.error && nfs4_need_to_bump_seqid(&res))
1178 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1179 
1180 	needrecov = nfs4_needs_recovery(&e, TRUE, dvp->v_vfsp);
1181 
1182 	if (e.error || needrecov) {
1183 		bool_t abort = FALSE;
1184 
1185 		if (needrecov) {
1186 			nfs4_bseqid_entry_t *bsep = NULL;
1187 
1188 			nfs4open_save_lost_rqst(e.error, &lost_rqst, oop,
1189 			    cred_otw, vpi, dvp, open_args);
1190 
1191 			if (!e.error && res.status == NFS4ERR_BAD_SEQID) {
1192 				bsep = nfs4_create_bseqid_entry(oop, NULL,
1193 				    vpi, 0, args.ctag, open_args->seqid);
1194 				num_bseqid_retry--;
1195 			}
1196 
1197 			abort = nfs4_start_recovery(&e, VTOMI4(dvp), dvp, vpi,
1198 			    NULL, lost_rqst.lr_op == OP_OPEN ?
1199 			    &lost_rqst : NULL, OP_OPEN, bsep, NULL, NULL);
1200 
1201 			if (bsep)
1202 				kmem_free(bsep, sizeof (*bsep));
1203 			/* give up if we keep getting BAD_SEQID */
1204 			if (num_bseqid_retry == 0)
1205 				abort = TRUE;
1206 			if (abort == TRUE && e.error == 0)
1207 				e.error = geterrno4(res.status);
1208 		}
1209 		nfs4_end_open_seqid_sync(oop);
1210 		open_owner_rele(oop);
1211 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1212 		nfs4args_copen_free(open_args);
1213 		if (setgid_flag) {
1214 			nfs4args_verify_free(&argop[8]);
1215 			nfs4args_setattr_free(&argop[9]);
1216 		}
1217 		if (!e.error)
1218 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1219 		if (ncr != NULL) {
1220 			crfree(ncr);
1221 			ncr = NULL;
1222 		}
1223 		if (!needrecov || abort == TRUE || e.error == EINTR ||
1224 		    NFS4_FRC_UNMT_ERR(e.error, dvp->v_vfsp)) {
1225 			kmem_free(argop, argoplist_size);
1226 			return (e.error);
1227 		}
1228 		goto recov_retry;
1229 	}
1230 
1231 	/*
1232 	 * Will check and update lease after checking the rflag for
1233 	 * OPEN_CONFIRM in the successful OPEN call.
1234 	 */
1235 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
1236 
1237 		/*
1238 		 * XXX what if we're crossing mount points from server1:/drp
1239 		 * to server2:/drp/rp.
1240 		 */
1241 
1242 		/* Signal our end of use of the open seqid */
1243 		nfs4_end_open_seqid_sync(oop);
1244 
1245 		/*
1246 		 * This will destroy the open owner if it was just created,
1247 		 * and no one else has put a reference on it.
1248 		 */
1249 		open_owner_rele(oop);
1250 		if (create_flag && (createmode != EXCLUSIVE4) &&
1251 		    res.status == NFS4ERR_BADOWNER)
1252 			nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1253 
1254 		e.error = geterrno4(res.status);
1255 		nfs4args_copen_free(open_args);
1256 		if (setgid_flag) {
1257 			nfs4args_verify_free(&argop[8]);
1258 			nfs4args_setattr_free(&argop[9]);
1259 		}
1260 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1261 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1262 		/*
1263 		 * If the reply is NFS4ERR_ACCESS, it may be because
1264 		 * we are root (no root net access).  If the real uid
1265 		 * is not root, then retry with the real uid instead.
1266 		 */
1267 		if (ncr != NULL) {
1268 			crfree(ncr);
1269 			ncr = NULL;
1270 		}
1271 		if (res.status == NFS4ERR_ACCESS &&
1272 		    (ncr = crnetadjust(cred_otw)) != NULL) {
1273 			cred_otw = ncr;
1274 			goto recov_retry;
1275 		}
1276 		kmem_free(argop, argoplist_size);
1277 		return (e.error);
1278 	}
1279 
1280 	resop = &res.array[idx_open];  /* open res */
1281 	op_res = &resop->nfs_resop4_u.opopen;
1282 
1283 #ifdef DEBUG
1284 	/*
1285 	 * verify attrset bitmap
1286 	 */
1287 	if (create_flag &&
1288 	    (createmode == UNCHECKED4 || createmode == GUARDED4)) {
1289 		/* make sure attrset returned is what we asked for */
1290 		/* XXX Ignore this 'error' for now */
1291 		if (attr->attrmask != op_res->attrset)
1292 			/* EMPTY */;
1293 	}
1294 #endif
1295 
1296 	if (op_res->rflags & OPEN4_RESULT_LOCKTYPE_POSIX) {
1297 		mutex_enter(&VTOMI4(dvp)->mi_lock);
1298 		VTOMI4(dvp)->mi_flags |= MI4_POSIX_LOCK;
1299 		mutex_exit(&VTOMI4(dvp)->mi_lock);
1300 	}
1301 
1302 	resop = &res.array[idx_open + 1];  /* getfh res */
1303 	gf_res = &resop->nfs_resop4_u.opgetfh;
1304 
1305 	otw_sfh = sfh4_get(&gf_res->object, VTOMI4(dvp));
1306 
1307 	/*
1308 	 * The open stateid has been updated on the server but not
1309 	 * on the client yet.  There is a path: makenfs4node->nfs4_attr_cache->
1310 	 * flush_pages->VOP_PUTPAGE->...->nfs4write where we will issue an OTW
1311 	 * WRITE call.  That, however, will use the old stateid, so go ahead
1312 	 * and upate the open stateid now, before any call to makenfs4node.
1313 	 */
1314 	if (vpi) {
1315 		nfs4_open_stream_t	*tmp_osp;
1316 		rnode4_t		*tmp_rp = VTOR4(vpi);
1317 
1318 		tmp_osp = find_open_stream(oop, tmp_rp);
1319 		if (tmp_osp) {
1320 			tmp_osp->open_stateid = op_res->stateid;
1321 			mutex_exit(&tmp_osp->os_sync_lock);
1322 			open_stream_rele(tmp_osp, tmp_rp);
1323 		}
1324 
1325 		/*
1326 		 * We must determine if the file handle given by the otw open
1327 		 * is the same as the file handle which was passed in with
1328 		 * *vpp.  This case can be reached if the file we are trying
1329 		 * to open has been removed and another file has been created
1330 		 * having the same file name.  The passed in vnode is released
1331 		 * later.
1332 		 */
1333 		orig_sfh = VTOR4(vpi)->r_fh;
1334 		fh_differs = nfs4cmpfh(&orig_sfh->sfh_fh, &otw_sfh->sfh_fh);
1335 	}
1336 
1337 	garp = &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res;
1338 
1339 	if (create_flag || fh_differs) {
1340 		int rnode_err = 0;
1341 
1342 		vp = makenfs4node(otw_sfh, garp, dvp->v_vfsp, t, cr,
1343 		    dvp, fn_get(VTOSV(dvp)->sv_name, file_name, otw_sfh));
1344 
1345 		if (e.error)
1346 			PURGE_ATTRCACHE4(vp);
1347 		/*
1348 		 * For the newly created vp case, make sure the rnode
1349 		 * isn't bad before using it.
1350 		 */
1351 		mutex_enter(&(VTOR4(vp))->r_statelock);
1352 		if (VTOR4(vp)->r_flags & R4RECOVERR)
1353 			rnode_err = EIO;
1354 		mutex_exit(&(VTOR4(vp))->r_statelock);
1355 
1356 		if (rnode_err) {
1357 			nfs4_end_open_seqid_sync(oop);
1358 			nfs4args_copen_free(open_args);
1359 			if (setgid_flag) {
1360 				nfs4args_verify_free(&argop[8]);
1361 				nfs4args_setattr_free(&argop[9]);
1362 			}
1363 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1364 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1365 			    needrecov);
1366 			open_owner_rele(oop);
1367 			VN_RELE(vp);
1368 			if (ncr != NULL)
1369 				crfree(ncr);
1370 			sfh4_rele(&otw_sfh);
1371 			kmem_free(argop, argoplist_size);
1372 			return (EIO);
1373 		}
1374 	} else {
1375 		vp = vpi;
1376 	}
1377 	sfh4_rele(&otw_sfh);
1378 
1379 	/*
1380 	 * It seems odd to get a full set of attrs and then not update
1381 	 * the object's attrcache in the non-create case.  Create case uses
1382 	 * the attrs since makenfs4node checks to see if the attrs need to
1383 	 * be updated (and then updates them).  The non-create case should
1384 	 * update attrs also.
1385 	 */
1386 	if (! create_flag && ! fh_differs && !e.error) {
1387 		nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
1388 	}
1389 
1390 	nfs4_error_zinit(&e);
1391 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
1392 		/* This does not do recovery for vp explicitly. */
1393 		nfs4open_confirm(vp, &seqid, &op_res->stateid, cred_otw, FALSE,
1394 		    &retry_open, oop, FALSE, &e, &num_bseqid_retry);
1395 
1396 		if (e.error || e.stat) {
1397 			nfs4_end_open_seqid_sync(oop);
1398 			nfs4args_copen_free(open_args);
1399 			if (setgid_flag) {
1400 				nfs4args_verify_free(&argop[8]);
1401 				nfs4args_setattr_free(&argop[9]);
1402 			}
1403 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1404 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1405 			    needrecov);
1406 			open_owner_rele(oop);
1407 			if (create_flag || fh_differs) {
1408 				/* rele the makenfs4node */
1409 				VN_RELE(vp);
1410 			}
1411 			if (ncr != NULL) {
1412 				crfree(ncr);
1413 				ncr = NULL;
1414 			}
1415 			if (retry_open == TRUE) {
1416 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1417 				    "nfs4open_otw: retry the open since OPEN "
1418 				    "CONFIRM failed with error %d stat %d",
1419 				    e.error, e.stat));
1420 				if (create_flag && createmode == GUARDED4) {
1421 					NFS4_DEBUG(nfs4_client_recov_debug,
1422 					    (CE_NOTE, "nfs4open_otw: switch "
1423 					    "createmode from GUARDED4 to "
1424 					    "UNCHECKED4"));
1425 					createmode = UNCHECKED4;
1426 				}
1427 				goto recov_retry;
1428 			}
1429 			if (!e.error) {
1430 				if (create_flag && (createmode != EXCLUSIVE4) &&
1431 				    e.stat == NFS4ERR_BADOWNER)
1432 					nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1433 
1434 				e.error = geterrno4(e.stat);
1435 			}
1436 			kmem_free(argop, argoplist_size);
1437 			return (e.error);
1438 		}
1439 	}
1440 
1441 	rp = VTOR4(vp);
1442 
1443 	mutex_enter(&rp->r_statev4_lock);
1444 	if (create_flag)
1445 		rp->created_v4 = 1;
1446 	mutex_exit(&rp->r_statev4_lock);
1447 
1448 	mutex_enter(&oop->oo_lock);
1449 	/* Doesn't matter if 'oo_just_created' already was set as this */
1450 	oop->oo_just_created = NFS4_PERM_CREATED;
1451 	if (oop->oo_cred_otw)
1452 		crfree(oop->oo_cred_otw);
1453 	oop->oo_cred_otw = cred_otw;
1454 	crhold(oop->oo_cred_otw);
1455 	mutex_exit(&oop->oo_lock);
1456 
1457 	/* returns with 'os_sync_lock' held */
1458 	osp = find_or_create_open_stream(oop, rp, &created_osp);
1459 	if (!osp) {
1460 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1461 		    "nfs4open_otw: failed to create an open stream"));
1462 		NFS4_DEBUG(nfs4_seqid_sync, (CE_NOTE, "nfs4open_otw: "
1463 		    "signal our end of use of the open seqid"));
1464 
1465 		nfs4_end_open_seqid_sync(oop);
1466 		open_owner_rele(oop);
1467 		nfs4args_copen_free(open_args);
1468 		if (setgid_flag) {
1469 			nfs4args_verify_free(&argop[8]);
1470 			nfs4args_setattr_free(&argop[9]);
1471 		}
1472 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1473 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1474 		if (create_flag || fh_differs)
1475 			VN_RELE(vp);
1476 		if (ncr != NULL)
1477 			crfree(ncr);
1478 
1479 		kmem_free(argop, argoplist_size);
1480 		return (EINVAL);
1481 
1482 	}
1483 
1484 	osp->open_stateid = op_res->stateid;
1485 
1486 	if (open_flag & FREAD)
1487 		osp->os_share_acc_read++;
1488 	if (open_flag & FWRITE)
1489 		osp->os_share_acc_write++;
1490 	osp->os_share_deny_none++;
1491 
1492 	/*
1493 	 * Need to reset this bitfield for the possible case where we were
1494 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
1495 	 * we could retry the CLOSE, OPENed the file again.
1496 	 */
1497 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
1498 	osp->os_final_close = 0;
1499 	osp->os_force_close = 0;
1500 #ifdef DEBUG
1501 	if (osp->os_failed_reopen)
1502 		NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE, "nfs4open_otw:"
1503 		    " clearing os_failed_reopen for osp %p, cr %p, rp %s",
1504 		    (void *)osp, (void *)cr, rnode4info(rp)));
1505 #endif
1506 	osp->os_failed_reopen = 0;
1507 
1508 	mutex_exit(&osp->os_sync_lock);
1509 
1510 	nfs4_end_open_seqid_sync(oop);
1511 
1512 	if (created_osp && recov_state.rs_sp != NULL) {
1513 		mutex_enter(&recov_state.rs_sp->s_lock);
1514 		nfs4_inc_state_ref_count_nolock(recov_state.rs_sp, VTOMI4(dvp));
1515 		mutex_exit(&recov_state.rs_sp->s_lock);
1516 	}
1517 
1518 	/* get rid of our reference to find oop */
1519 	open_owner_rele(oop);
1520 
1521 	open_stream_rele(osp, rp);
1522 
1523 	/* accept delegation, if any */
1524 	nfs4_delegation_accept(rp, CLAIM_NULL, op_res, garp, cred_otw);
1525 
1526 	nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1527 
1528 	if (createmode == EXCLUSIVE4 &&
1529 	    (in_va->va_mask & ~(AT_GID | AT_SIZE))) {
1530 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw:"
1531 		    " EXCLUSIVE4: sending a SETATTR"));
1532 		/*
1533 		 * If doing an exclusive create, then generate
1534 		 * a SETATTR to set the initial attributes.
1535 		 * Try to set the mtime and the atime to the
1536 		 * server's current time.  It is somewhat
1537 		 * expected that these fields will be used to
1538 		 * store the exclusive create cookie.  If not,
1539 		 * server implementors will need to know that
1540 		 * a SETATTR will follow an exclusive create
1541 		 * and the cookie should be destroyed if
1542 		 * appropriate.
1543 		 *
1544 		 * The AT_GID and AT_SIZE bits are turned off
1545 		 * so that the SETATTR request will not attempt
1546 		 * to process these.  The gid will be set
1547 		 * separately if appropriate.  The size is turned
1548 		 * off because it is assumed that a new file will
1549 		 * be created empty and if the file wasn't empty,
1550 		 * then the exclusive create will have failed
1551 		 * because the file must have existed already.
1552 		 * Therefore, no truncate operation is needed.
1553 		 */
1554 		in_va->va_mask &= ~(AT_GID | AT_SIZE);
1555 		in_va->va_mask |= (AT_MTIME | AT_ATIME);
1556 
1557 		e.error = nfs4setattr(vp, in_va, 0, cr, NULL);
1558 		if (e.error) {
1559 			nfs4_error_t err;
1560 
1561 			/*
1562 			 * Couldn't correct the attributes of
1563 			 * the newly created file and the
1564 			 * attributes are wrong.  Remove the
1565 			 * file and return an error to the
1566 			 * application.
1567 			 */
1568 			/* XXX will this take care of client state ? */
1569 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1570 			    "nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1571 			    " remove file", e.error));
1572 
1573 			/*
1574 			 * The file is currently open so try to close it first.
1575 			 *
1576 			 * If we do not close the file explicitly here then the
1577 			 * VN_RELE() would do an (implicit and asynchronous)
1578 			 * close for us.  But such async close could race with
1579 			 * the nfs4_remove() below.  If the async close is
1580 			 * slower than nfs4_remove() then nfs4_remove()
1581 			 * wouldn't remove the file but rename it to .nfsXXXX
1582 			 * instead.
1583 			 */
1584 			nfs4close_one(vp, NULL, cr, open_flag, NULL, &err,
1585 			    CLOSE_NORM, 0, 0, 0);
1586 			VN_RELE(vp);
1587 			(void) nfs4_remove(dvp, file_name, cr, NULL, 0);
1588 
1589 			/*
1590 			 * Since we've reled the vnode and removed
1591 			 * the file we now need to return the error.
1592 			 * At this point we don't want to update the
1593 			 * dircaches, call nfs4_waitfor_purge_complete
1594 			 * or set vpp to vp so we need to skip these
1595 			 * as well.
1596 			 */
1597 			goto skip_update_dircaches;
1598 		}
1599 	}
1600 
1601 	/*
1602 	 * If we created or found the correct vnode, due to create_flag or
1603 	 * fh_differs being set, then update directory cache attribute, readdir
1604 	 * and dnlc caches.
1605 	 */
1606 	if (create_flag || fh_differs) {
1607 		dirattr_info_t dinfo, *dinfop;
1608 
1609 		/*
1610 		 * Make sure getattr succeeded before using results.
1611 		 * note: op 7 is getattr(dir) for both flavors of
1612 		 * open(create).
1613 		 */
1614 		if (create_flag && res.status == NFS4_OK) {
1615 			dinfo.di_time_call = t;
1616 			dinfo.di_cred = cr;
1617 			dinfo.di_garp =
1618 			    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
1619 			dinfop = &dinfo;
1620 		} else {
1621 			dinfop = NULL;
1622 		}
1623 
1624 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1625 		    dinfop);
1626 	}
1627 
1628 	/*
1629 	 * If the page cache for this file was flushed from actions
1630 	 * above, it was done asynchronously and if that is true,
1631 	 * there is a need to wait here for it to complete.  This must
1632 	 * be done outside of start_fop/end_fop.
1633 	 */
1634 	(void) nfs4_waitfor_purge_complete(vp);
1635 
1636 	/*
1637 	 * It is implicit that we are in the open case (create_flag == 0) since
1638 	 * fh_differs can only be set to a non-zero value in the open case.
1639 	 */
1640 	if (fh_differs != 0 && vpi != NULL)
1641 		VN_RELE(vpi);
1642 
1643 	/*
1644 	 * Be sure to set *vpp to the correct value before returning.
1645 	 */
1646 	*vpp = vp;
1647 
1648 skip_update_dircaches:
1649 
1650 	nfs4args_copen_free(open_args);
1651 	if (setgid_flag) {
1652 		nfs4args_verify_free(&argop[8]);
1653 		nfs4args_setattr_free(&argop[9]);
1654 	}
1655 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1656 
1657 	if (ncr)
1658 		crfree(ncr);
1659 	kmem_free(argop, argoplist_size);
1660 	return (e.error);
1661 }
1662 
1663 /*
1664  * Reopen an open instance.  cf. nfs4open_otw().
1665  *
1666  * Errors are returned by the nfs4_error_t parameter.
1667  * - ep->error contains an errno value or zero.
1668  * - if it is zero, ep->stat is set to an NFS status code, if any.
1669  *   If the file could not be reopened, but the caller should continue, the
1670  *   file is marked dead and no error values are returned.  If the caller
1671  *   should stop recovering open files and start over, either the ep->error
1672  *   value or ep->stat will indicate an error (either something that requires
1673  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1674  *   filehandles) may be handled silently by this routine.
1675  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1676  *   will be started, so the caller should not do it.
1677  *
1678  * Gotos:
1679  * - kill_file : reopen failed in such a fashion to constitute marking the
1680  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1681  *   is for cases where recovery is not possible.
1682  * - failed_reopen : same as above, except that the file has already been
1683  *   marked dead, so no need to do it again.
1684  * - bailout : reopen failed but we are able to recover and retry the reopen -
1685  *   either within this function immediately or via the calling function.
1686  */
1687 
1688 void
1689 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1690     open_claim_type4 claim, bool_t frc_use_claim_previous,
1691     bool_t is_recov)
1692 {
1693 	COMPOUND4args_clnt args;
1694 	COMPOUND4res_clnt res;
1695 	nfs_argop4 argop[4];
1696 	nfs_resop4 *resop;
1697 	OPEN4res *op_res = NULL;
1698 	OPEN4cargs *open_args;
1699 	GETFH4res *gf_res;
1700 	rnode4_t *rp = VTOR4(vp);
1701 	int doqueue = 1;
1702 	cred_t *cr = NULL, *cred_otw = NULL;
1703 	nfs4_open_owner_t *oop = NULL;
1704 	seqid4 seqid;
1705 	nfs4_ga_res_t *garp;
1706 	char fn[MAXNAMELEN];
1707 	nfs4_recov_state_t recov = {NULL, 0};
1708 	nfs4_lost_rqst_t lost_rqst;
1709 	mntinfo4_t *mi = VTOMI4(vp);
1710 	bool_t abort;
1711 	char *failed_msg = "";
1712 	int fh_different;
1713 	hrtime_t t;
1714 	nfs4_bseqid_entry_t *bsep = NULL;
1715 
1716 	ASSERT(nfs4_consistent_type(vp));
1717 	ASSERT(nfs_zone() == mi->mi_zone);
1718 
1719 	nfs4_error_zinit(ep);
1720 
1721 	/* this is the cred used to find the open owner */
1722 	cr = state_to_cred(osp);
1723 	if (cr == NULL) {
1724 		failed_msg = "Couldn't reopen: no cred";
1725 		goto kill_file;
1726 	}
1727 	/* use this cred for OTW operations */
1728 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1729 
1730 top:
1731 	nfs4_error_zinit(ep);
1732 
1733 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1734 		/* File system has been unmounted, quit */
1735 		ep->error = EIO;
1736 		failed_msg = "Couldn't reopen: file system has been unmounted";
1737 		goto kill_file;
1738 	}
1739 
1740 	oop = osp->os_open_owner;
1741 
1742 	ASSERT(oop != NULL);
1743 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1744 		failed_msg = "can't reopen: no open owner";
1745 		goto kill_file;
1746 	}
1747 	open_owner_hold(oop);
1748 
1749 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1750 	if (ep->error) {
1751 		open_owner_rele(oop);
1752 		oop = NULL;
1753 		goto bailout;
1754 	}
1755 
1756 	/*
1757 	 * If the rnode has a delegation and the delegation has been
1758 	 * recovered and the server didn't request a recall and the caller
1759 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1760 	 * recovery) and the rnode hasn't been marked dead, then install
1761 	 * the delegation stateid in the open stream.  Otherwise, proceed
1762 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1763 	 */
1764 	mutex_enter(&rp->r_statev4_lock);
1765 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1766 	    !rp->r_deleg_return_pending &&
1767 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1768 	    !rp->r_deleg_needs_recall &&
1769 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1770 	    !(rp->r_flags & R4RECOVERR)) {
1771 		mutex_enter(&osp->os_sync_lock);
1772 		osp->os_delegation = 1;
1773 		osp->open_stateid = rp->r_deleg_stateid;
1774 		mutex_exit(&osp->os_sync_lock);
1775 		mutex_exit(&rp->r_statev4_lock);
1776 		goto bailout;
1777 	}
1778 	mutex_exit(&rp->r_statev4_lock);
1779 
1780 	/*
1781 	 * If the file failed recovery, just quit.  This failure need not
1782 	 * affect other reopens, so don't return an error.
1783 	 */
1784 	mutex_enter(&rp->r_statelock);
1785 	if (rp->r_flags & R4RECOVERR) {
1786 		mutex_exit(&rp->r_statelock);
1787 		ep->error = 0;
1788 		goto failed_reopen;
1789 	}
1790 	mutex_exit(&rp->r_statelock);
1791 
1792 	/*
1793 	 * argop is empty here
1794 	 *
1795 	 * PUTFH, OPEN, GETATTR
1796 	 */
1797 	args.ctag = TAG_REOPEN;
1798 	args.array_len = 4;
1799 	args.array = argop;
1800 
1801 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1802 	    "nfs4_reopen: file is type %d, id %s",
1803 	    vp->v_type, rnode4info(VTOR4(vp))));
1804 
1805 	argop[0].argop = OP_CPUTFH;
1806 
1807 	if (claim != CLAIM_PREVIOUS) {
1808 		/*
1809 		 * if this is a file mount then
1810 		 * use the mntinfo parentfh
1811 		 */
1812 		argop[0].nfs_argop4_u.opcputfh.sfh =
1813 		    (vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1814 		    VTOSV(vp)->sv_dfh;
1815 	} else {
1816 		/* putfh fh to reopen */
1817 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1818 	}
1819 
1820 	argop[1].argop = OP_COPEN;
1821 	open_args = &argop[1].nfs_argop4_u.opcopen;
1822 	open_args->claim = claim;
1823 
1824 	if (claim == CLAIM_NULL) {
1825 
1826 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1827 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1828 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1829 			    (void *)vp);
1830 			failed_msg = "Couldn't reopen: vtoname failed for "
1831 			    "CLAIM_NULL";
1832 			/* nothing allocated yet */
1833 			goto kill_file;
1834 		}
1835 
1836 		open_args->open_claim4_u.cfile = fn;
1837 	} else if (claim == CLAIM_PREVIOUS) {
1838 
1839 		/*
1840 		 * We have two cases to deal with here:
1841 		 * 1) We're being called to reopen files in order to satisfy
1842 		 *    a lock operation request which requires us to explicitly
1843 		 *    reopen files which were opened under a delegation.  If
1844 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1845 		 *    that case, frc_use_claim_previous is TRUE and we must
1846 		 *    use the rnode's current delegation type (r_deleg_type).
1847 		 * 2) We're reopening files during some form of recovery.
1848 		 *    In this case, frc_use_claim_previous is FALSE and we
1849 		 *    use the delegation type appropriate for recovery
1850 		 *    (r_deleg_needs_recovery).
1851 		 */
1852 		mutex_enter(&rp->r_statev4_lock);
1853 		open_args->open_claim4_u.delegate_type =
1854 		    frc_use_claim_previous ?
1855 		    rp->r_deleg_type :
1856 		    rp->r_deleg_needs_recovery;
1857 		mutex_exit(&rp->r_statev4_lock);
1858 
1859 	} else if (claim == CLAIM_DELEGATE_CUR) {
1860 
1861 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1862 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1863 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1864 			    "with %m", (void *)vp);
1865 			failed_msg = "Couldn't reopen: vtoname failed for "
1866 			    "CLAIM_DELEGATE_CUR";
1867 			/* nothing allocated yet */
1868 			goto kill_file;
1869 		}
1870 
1871 		mutex_enter(&rp->r_statev4_lock);
1872 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1873 		    rp->r_deleg_stateid;
1874 		mutex_exit(&rp->r_statev4_lock);
1875 
1876 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1877 	}
1878 	open_args->opentype = OPEN4_NOCREATE;
1879 	open_args->owner.clientid = mi2clientid(mi);
1880 	open_args->owner.owner_len = sizeof (oop->oo_name);
1881 	open_args->owner.owner_val =
1882 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1883 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1884 	    open_args->owner.owner_len);
1885 	open_args->share_access = 0;
1886 	open_args->share_deny = 0;
1887 
1888 	mutex_enter(&osp->os_sync_lock);
1889 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1890 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1891 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1892 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1893 	    osp->os_share_acc_write, osp->os_open_ref_count,
1894 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1895 
1896 	if (osp->os_share_acc_read || osp->os_mmap_read)
1897 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1898 	if (osp->os_share_acc_write || osp->os_mmap_write)
1899 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1900 	if (osp->os_share_deny_read)
1901 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1902 	if (osp->os_share_deny_write)
1903 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1904 	mutex_exit(&osp->os_sync_lock);
1905 
1906 	seqid = nfs4_get_open_seqid(oop) + 1;
1907 	open_args->seqid = seqid;
1908 
1909 	/* Construct the getfh part of the compound */
1910 	argop[2].argop = OP_GETFH;
1911 
1912 	/* Construct the getattr part of the compound */
1913 	argop[3].argop = OP_GETATTR;
1914 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1915 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1916 
1917 	t = gethrtime();
1918 
1919 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1920 
1921 	if (ep->error) {
1922 		if (!is_recov && !frc_use_claim_previous &&
1923 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1924 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1925 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1926 			    cred_otw, vp, NULL, open_args);
1927 			abort = nfs4_start_recovery(ep,
1928 			    VTOMI4(vp), vp, NULL, NULL,
1929 			    lost_rqst.lr_op == OP_OPEN ?
1930 			    &lost_rqst : NULL, OP_OPEN, NULL, NULL, NULL);
1931 			nfs4args_copen_free(open_args);
1932 			goto bailout;
1933 		}
1934 
1935 		nfs4args_copen_free(open_args);
1936 
1937 		if (ep->error == EACCES && cred_otw != cr) {
1938 			crfree(cred_otw);
1939 			cred_otw = cr;
1940 			crhold(cred_otw);
1941 			nfs4_end_open_seqid_sync(oop);
1942 			open_owner_rele(oop);
1943 			oop = NULL;
1944 			goto top;
1945 		}
1946 		if (ep->error == ETIMEDOUT)
1947 			goto bailout;
1948 		failed_msg = "Couldn't reopen: rpc error";
1949 		goto kill_file;
1950 	}
1951 
1952 	if (nfs4_need_to_bump_seqid(&res))
1953 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1954 
1955 	switch (res.status) {
1956 	case NFS4_OK:
1957 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1958 			mutex_enter(&rp->r_statelock);
1959 			rp->r_delay_interval = 0;
1960 			mutex_exit(&rp->r_statelock);
1961 		}
1962 		break;
1963 	case NFS4ERR_BAD_SEQID:
1964 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1965 		    args.ctag, open_args->seqid);
1966 
1967 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1968 		    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1969 		    NULL, OP_OPEN, bsep, NULL, NULL);
1970 
1971 		nfs4args_copen_free(open_args);
1972 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1973 		nfs4_end_open_seqid_sync(oop);
1974 		open_owner_rele(oop);
1975 		oop = NULL;
1976 		kmem_free(bsep, sizeof (*bsep));
1977 
1978 		goto kill_file;
1979 	case NFS4ERR_NO_GRACE:
1980 		nfs4args_copen_free(open_args);
1981 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1982 		nfs4_end_open_seqid_sync(oop);
1983 		open_owner_rele(oop);
1984 		oop = NULL;
1985 		if (claim == CLAIM_PREVIOUS) {
1986 			/*
1987 			 * Retry as a plain open. We don't need to worry about
1988 			 * checking the changeinfo: it is acceptable for a
1989 			 * client to re-open a file and continue processing
1990 			 * (in the absence of locks).
1991 			 */
1992 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1993 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1994 			    "will retry as CLAIM_NULL"));
1995 			claim = CLAIM_NULL;
1996 			nfs4_mi_kstat_inc_no_grace(mi);
1997 			goto top;
1998 		}
1999 		failed_msg =
2000 		    "Couldn't reopen: tried reclaim outside grace period. ";
2001 		goto kill_file;
2002 	case NFS4ERR_GRACE:
2003 		nfs4_set_grace_wait(mi);
2004 		nfs4args_copen_free(open_args);
2005 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2006 		nfs4_end_open_seqid_sync(oop);
2007 		open_owner_rele(oop);
2008 		oop = NULL;
2009 		ep->error = nfs4_wait_for_grace(mi, &recov);
2010 		if (ep->error != 0)
2011 			goto bailout;
2012 		goto top;
2013 	case NFS4ERR_DELAY:
2014 		nfs4_set_delay_wait(vp);
2015 		nfs4args_copen_free(open_args);
2016 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2017 		nfs4_end_open_seqid_sync(oop);
2018 		open_owner_rele(oop);
2019 		oop = NULL;
2020 		ep->error = nfs4_wait_for_delay(vp, &recov);
2021 		nfs4_mi_kstat_inc_delay(mi);
2022 		if (ep->error != 0)
2023 			goto bailout;
2024 		goto top;
2025 	case NFS4ERR_FHEXPIRED:
2026 		/* recover filehandle and retry */
2027 		abort = nfs4_start_recovery(ep,
2028 		    mi, vp, NULL, NULL, NULL, OP_OPEN, NULL, NULL, NULL);
2029 		nfs4args_copen_free(open_args);
2030 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2031 		nfs4_end_open_seqid_sync(oop);
2032 		open_owner_rele(oop);
2033 		oop = NULL;
2034 		if (abort == FALSE)
2035 			goto top;
2036 		failed_msg = "Couldn't reopen: recovery aborted";
2037 		goto kill_file;
2038 	case NFS4ERR_RESOURCE:
2039 	case NFS4ERR_STALE_CLIENTID:
2040 	case NFS4ERR_WRONGSEC:
2041 	case NFS4ERR_EXPIRED:
2042 		/*
2043 		 * Do not mark the file dead and let the calling
2044 		 * function initiate recovery.
2045 		 */
2046 		nfs4args_copen_free(open_args);
2047 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2048 		nfs4_end_open_seqid_sync(oop);
2049 		open_owner_rele(oop);
2050 		oop = NULL;
2051 		goto bailout;
2052 	case NFS4ERR_ACCESS:
2053 		if (cred_otw != cr) {
2054 			crfree(cred_otw);
2055 			cred_otw = cr;
2056 			crhold(cred_otw);
2057 			nfs4args_copen_free(open_args);
2058 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2059 			nfs4_end_open_seqid_sync(oop);
2060 			open_owner_rele(oop);
2061 			oop = NULL;
2062 			goto top;
2063 		}
2064 		/* fall through */
2065 	default:
2066 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2067 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2068 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2069 		    rnode4info(VTOR4(vp))));
2070 		failed_msg = "Couldn't reopen: NFSv4 error";
2071 		nfs4args_copen_free(open_args);
2072 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2073 		goto kill_file;
2074 	}
2075 
2076 	resop = &res.array[1];  /* open res */
2077 	op_res = &resop->nfs_resop4_u.opopen;
2078 
2079 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2080 
2081 	/*
2082 	 * Check if the path we reopened really is the same
2083 	 * file. We could end up in a situation where the file
2084 	 * was removed and a new file created with the same name.
2085 	 */
2086 	resop = &res.array[2];
2087 	gf_res = &resop->nfs_resop4_u.opgetfh;
2088 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2089 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2090 	if (fh_different) {
2091 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2092 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2093 			/* Oops, we don't have the same file */
2094 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2095 				failed_msg = "Couldn't reopen: Persistent "
2096 				    "file handle changed";
2097 			else
2098 				failed_msg = "Couldn't reopen: Volatile "
2099 				    "(no expire on open) file handle changed";
2100 
2101 			nfs4args_copen_free(open_args);
2102 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2103 			nfs_rw_exit(&mi->mi_fh_lock);
2104 			goto kill_file;
2105 
2106 		} else {
2107 			/*
2108 			 * We have volatile file handles that don't compare.
2109 			 * If the fids are the same then we assume that the
2110 			 * file handle expired but the rnode still refers to
2111 			 * the same file object.
2112 			 *
2113 			 * First check that we have fids or not.
2114 			 * If we don't we have a dumb server so we will
2115 			 * just assume every thing is ok for now.
2116 			 */
2117 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2118 			    rp->r_attr.va_mask & AT_NODEID &&
2119 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2120 				/*
2121 				 * We have fids, but they don't
2122 				 * compare. So kill the file.
2123 				 */
2124 				failed_msg =
2125 				    "Couldn't reopen: file handle changed"
2126 				    " due to mismatched fids";
2127 				nfs4args_copen_free(open_args);
2128 				xdr_free(xdr_COMPOUND4res_clnt,
2129 				    (caddr_t)&res);
2130 				nfs_rw_exit(&mi->mi_fh_lock);
2131 				goto kill_file;
2132 			} else {
2133 				/*
2134 				 * We have volatile file handles that refers
2135 				 * to the same file (at least they have the
2136 				 * same fid) or we don't have fids so we
2137 				 * can't tell. :(. We'll be a kind and accepting
2138 				 * client so we'll update the rnode's file
2139 				 * handle with the otw handle.
2140 				 *
2141 				 * We need to drop mi->mi_fh_lock since
2142 				 * sh4_update acquires it. Since there is
2143 				 * only one recovery thread there is no
2144 				 * race.
2145 				 */
2146 				nfs_rw_exit(&mi->mi_fh_lock);
2147 				sfh4_update(rp->r_fh, &gf_res->object);
2148 			}
2149 		}
2150 	} else {
2151 		nfs_rw_exit(&mi->mi_fh_lock);
2152 	}
2153 
2154 	ASSERT(nfs4_consistent_type(vp));
2155 
2156 	/*
2157 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2158 	 * over.  Presumably if there is a persistent error it will show up
2159 	 * when we resend the OPEN.
2160 	 */
2161 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2162 		bool_t retry_open = FALSE;
2163 
2164 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2165 		    cred_otw, is_recov, &retry_open,
2166 		    oop, FALSE, ep, NULL);
2167 		if (ep->error || ep->stat) {
2168 			nfs4args_copen_free(open_args);
2169 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2170 			nfs4_end_open_seqid_sync(oop);
2171 			open_owner_rele(oop);
2172 			oop = NULL;
2173 			goto top;
2174 		}
2175 	}
2176 
2177 	mutex_enter(&osp->os_sync_lock);
2178 	osp->open_stateid = op_res->stateid;
2179 	osp->os_delegation = 0;
2180 	/*
2181 	 * Need to reset this bitfield for the possible case where we were
2182 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2183 	 * we could retry the CLOSE, OPENed the file again.
2184 	 */
2185 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2186 	osp->os_final_close = 0;
2187 	osp->os_force_close = 0;
2188 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2189 		osp->os_dc_openacc = open_args->share_access;
2190 	mutex_exit(&osp->os_sync_lock);
2191 
2192 	nfs4_end_open_seqid_sync(oop);
2193 
2194 	/* accept delegation, if any */
2195 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2196 
2197 	nfs4args_copen_free(open_args);
2198 
2199 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2200 
2201 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2202 
2203 	ASSERT(nfs4_consistent_type(vp));
2204 
2205 	open_owner_rele(oop);
2206 	crfree(cr);
2207 	crfree(cred_otw);
2208 	return;
2209 
2210 kill_file:
2211 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2212 failed_reopen:
2213 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2214 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2215 	    (void *)osp, (void *)cr, rnode4info(rp)));
2216 	mutex_enter(&osp->os_sync_lock);
2217 	osp->os_failed_reopen = 1;
2218 	mutex_exit(&osp->os_sync_lock);
2219 bailout:
2220 	if (oop != NULL) {
2221 		nfs4_end_open_seqid_sync(oop);
2222 		open_owner_rele(oop);
2223 	}
2224 	if (cr != NULL)
2225 		crfree(cr);
2226 	if (cred_otw != NULL)
2227 		crfree(cred_otw);
2228 }
2229 
2230 /* for . and .. OPENs */
2231 /* ARGSUSED */
2232 static int
2233 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2234 {
2235 	rnode4_t *rp;
2236 	nfs4_ga_res_t gar;
2237 
2238 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2239 
2240 	/*
2241 	 * If close-to-open consistency checking is turned off or
2242 	 * if there is no cached data, we can avoid
2243 	 * the over the wire getattr.  Otherwise, force a
2244 	 * call to the server to get fresh attributes and to
2245 	 * check caches. This is required for close-to-open
2246 	 * consistency.
2247 	 */
2248 	rp = VTOR4(*vpp);
2249 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2250 	    (rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2251 		return (0);
2252 
2253 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2254 }
2255 
2256 /*
2257  * CLOSE a file
2258  */
2259 /* ARGSUSED */
2260 static int
2261 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
2262     caller_context_t *ct)
2263 {
2264 	rnode4_t	*rp;
2265 	int		 error = 0;
2266 	int		 r_error = 0;
2267 	int		 n4error = 0;
2268 	nfs4_error_t	 e = { 0, NFS4_OK, RPC_SUCCESS };
2269 
2270 	/*
2271 	 * Remove client state for this (lockowner, file) pair.
2272 	 * Issue otw v4 call to have the server do the same.
2273 	 */
2274 
2275 	rp = VTOR4(vp);
2276 
2277 	/*
2278 	 * zone_enter(2) prevents processes from changing zones with NFS files
2279 	 * open; if we happen to get here from the wrong zone we can't do
2280 	 * anything over the wire.
2281 	 */
2282 	if (VTOMI4(vp)->mi_zone != nfs_zone()) {
2283 		/*
2284 		 * We could attempt to clean up locks, except we're sure
2285 		 * that the current process didn't acquire any locks on
2286 		 * the file: any attempt to lock a file belong to another zone
2287 		 * will fail, and one can't lock an NFS file and then change
2288 		 * zones, as that fails too.
2289 		 *
2290 		 * Returning an error here is the sane thing to do.  A
2291 		 * subsequent call to VN_RELE() which translates to a
2292 		 * nfs4_inactive() will clean up state: if the zone of the
2293 		 * vnode's origin is still alive and kicking, the inactive
2294 		 * thread will handle the request (from the correct zone), and
2295 		 * everything (minus the OTW close call) should be OK.  If the
2296 		 * zone is going away nfs4_async_inactive() will throw away
2297 		 * delegations, open streams and cached pages inline.
2298 		 */
2299 		return (EIO);
2300 	}
2301 
2302 	/*
2303 	 * If we are using local locking for this filesystem, then
2304 	 * release all of the SYSV style record locks.  Otherwise,
2305 	 * we are doing network locking and we need to release all
2306 	 * of the network locks.  All of the locks held by this
2307 	 * process on this file are released no matter what the
2308 	 * incoming reference count is.
2309 	 */
2310 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK) {
2311 		cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
2312 		cleanshares(vp, ttoproc(curthread)->p_pid);
2313 	} else
2314 		e.error = nfs4_lockrelease(vp, flag, offset, cr);
2315 
2316 	if (e.error) {
2317 		struct lm_sysid *lmsid;
2318 		lmsid = nfs4_find_sysid(VTOMI4(vp));
2319 		if (lmsid == NULL) {
2320 			DTRACE_PROBE2(unknown__sysid, int, e.error,
2321 			    vnode_t *, vp);
2322 		} else {
2323 			cleanlocks(vp, ttoproc(curthread)->p_pid,
2324 			    (lm_sysidt(lmsid) | LM_SYSID_CLIENT));
2325 
2326 			lm_rel_sysid(lmsid);
2327 		}
2328 		return (e.error);
2329 	}
2330 
2331 	if (count > 1)
2332 		return (0);
2333 
2334 	/*
2335 	 * If the file has been `unlinked', then purge the
2336 	 * DNLC so that this vnode will get reycled quicker
2337 	 * and the .nfs* file on the server will get removed.
2338 	 */
2339 	if (rp->r_unldvp != NULL)
2340 		dnlc_purge_vp(vp);
2341 
2342 	/*
2343 	 * If the file was open for write and there are pages,
2344 	 * do a synchronous flush and commit of all of the
2345 	 * dirty and uncommitted pages.
2346 	 */
2347 	ASSERT(!e.error);
2348 	if ((flag & FWRITE) && nfs4_has_pages(vp))
2349 		error = nfs4_putpage_commit(vp, 0, 0, cr);
2350 
2351 	mutex_enter(&rp->r_statelock);
2352 	r_error = rp->r_error;
2353 	rp->r_error = 0;
2354 	mutex_exit(&rp->r_statelock);
2355 
2356 	/*
2357 	 * If this file type is one for which no explicit 'open' was
2358 	 * done, then bail now (ie. no need for protocol 'close'). If
2359 	 * there was an error w/the vm subsystem, return _that_ error,
2360 	 * otherwise, return any errors that may've been reported via
2361 	 * the rnode.
2362 	 */
2363 	if (vp->v_type != VREG)
2364 		return (error ? error : r_error);
2365 
2366 	/*
2367 	 * The sync putpage commit may have failed above, but since
2368 	 * we're working w/a regular file, we need to do the protocol
2369 	 * 'close' (nfs4close_one will figure out if an otw close is
2370 	 * needed or not). Report any errors _after_ doing the protocol
2371 	 * 'close'.
2372 	 */
2373 	nfs4close_one(vp, NULL, cr, flag, NULL, &e, CLOSE_NORM, 0, 0, 0);
2374 	n4error = e.error ? e.error : geterrno4(e.stat);
2375 
2376 	/*
2377 	 * Error reporting prio (Hi -> Lo)
2378 	 *
2379 	 *   i) nfs4_putpage_commit (error)
2380 	 *  ii) rnode's (r_error)
2381 	 * iii) nfs4close_one (n4error)
2382 	 */
2383 	return (error ? error : (r_error ? r_error : n4error));
2384 }
2385 
2386 /*
2387  * Initialize *lost_rqstp.
2388  */
2389 
2390 static void
2391 nfs4close_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
2392     nfs4_open_owner_t *oop, nfs4_open_stream_t *osp, cred_t *cr,
2393     vnode_t *vp)
2394 {
2395 	if (error != ETIMEDOUT && error != EINTR &&
2396 	    !NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
2397 		lost_rqstp->lr_op = 0;
2398 		return;
2399 	}
2400 
2401 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
2402 	    "nfs4close_save_lost_rqst: error %d", error));
2403 
2404 	lost_rqstp->lr_op = OP_CLOSE;
2405 	/*
2406 	 * The vp is held and rele'd via the recovery code.
2407 	 * See nfs4_save_lost_rqst.
2408 	 */
2409 	lost_rqstp->lr_vp = vp;
2410 	lost_rqstp->lr_dvp = NULL;
2411 	lost_rqstp->lr_oop = oop;
2412 	lost_rqstp->lr_osp = osp;
2413 	ASSERT(osp != NULL);
2414 	ASSERT(mutex_owned(&osp->os_sync_lock));
2415 	osp->os_pending_close = 1;
2416 	lost_rqstp->lr_lop = NULL;
2417 	lost_rqstp->lr_cr = cr;
2418 	lost_rqstp->lr_flk = NULL;
2419 	lost_rqstp->lr_putfirst = FALSE;
2420 }
2421 
2422 /*
2423  * Assumes you already have the open seqid sync grabbed as well as the
2424  * 'os_sync_lock'.  Note: this will release the open seqid sync and
2425  * 'os_sync_lock' if client recovery starts.  Calling functions have to
2426  * be prepared to handle this.
2427  *
2428  * 'recov' is returned as 1 if the CLOSE operation detected client recovery
2429  * was needed and was started, and that the calling function should retry
2430  * this function; otherwise it is returned as 0.
2431  *
2432  * Errors are returned via the nfs4_error_t parameter.
2433  */
2434 static void
2435 nfs4close_otw(rnode4_t *rp, cred_t *cred_otw, nfs4_open_owner_t *oop,
2436     nfs4_open_stream_t *osp, int *recov, int *did_start_seqid_syncp,
2437     nfs4_close_type_t close_type, nfs4_error_t *ep, int *have_sync_lockp)
2438 {
2439 	COMPOUND4args_clnt args;
2440 	COMPOUND4res_clnt res;
2441 	CLOSE4args *close_args;
2442 	nfs_resop4 *resop;
2443 	nfs_argop4 argop[3];
2444 	int doqueue = 1;
2445 	mntinfo4_t *mi;
2446 	seqid4 seqid;
2447 	vnode_t *vp;
2448 	bool_t needrecov = FALSE;
2449 	nfs4_lost_rqst_t lost_rqst;
2450 	hrtime_t t;
2451 
2452 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
2453 
2454 	ASSERT(MUTEX_HELD(&osp->os_sync_lock));
2455 
2456 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw"));
2457 
2458 	/* Only set this to 1 if recovery is started */
2459 	*recov = 0;
2460 
2461 	/* do the OTW call to close the file */
2462 
2463 	if (close_type == CLOSE_RESEND)
2464 		args.ctag = TAG_CLOSE_LOST;
2465 	else if (close_type == CLOSE_AFTER_RESEND)
2466 		args.ctag = TAG_CLOSE_UNDO;
2467 	else
2468 		args.ctag = TAG_CLOSE;
2469 
2470 	args.array_len = 3;
2471 	args.array = argop;
2472 
2473 	vp = RTOV4(rp);
2474 
2475 	mi = VTOMI4(vp);
2476 
2477 	/* putfh target fh */
2478 	argop[0].argop = OP_CPUTFH;
2479 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
2480 
2481 	argop[1].argop = OP_GETATTR;
2482 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
2483 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
2484 
2485 	argop[2].argop = OP_CLOSE;
2486 	close_args = &argop[2].nfs_argop4_u.opclose;
2487 
2488 	seqid = nfs4_get_open_seqid(oop) + 1;
2489 
2490 	close_args->seqid = seqid;
2491 	close_args->open_stateid = osp->open_stateid;
2492 
2493 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
2494 	    "nfs4close_otw: %s call, rp %s", needrecov ? "recov" : "first",
2495 	    rnode4info(rp)));
2496 
2497 	t = gethrtime();
2498 
2499 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
2500 
2501 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
2502 		nfs4_set_open_seqid(seqid, oop, args.ctag);
2503 	}
2504 
2505 	needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
2506 	if (ep->error && !needrecov) {
2507 		/*
2508 		 * if there was an error and no recovery is to be done
2509 		 * then then set up the file to flush its cache if
2510 		 * needed for the next caller.
2511 		 */
2512 		mutex_enter(&rp->r_statelock);
2513 		PURGE_ATTRCACHE4_LOCKED(rp);
2514 		rp->r_flags &= ~R4WRITEMODIFIED;
2515 		mutex_exit(&rp->r_statelock);
2516 		return;
2517 	}
2518 
2519 	if (needrecov) {
2520 		bool_t abort;
2521 		nfs4_bseqid_entry_t *bsep = NULL;
2522 
2523 		if (close_type != CLOSE_RESEND)
2524 			nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
2525 			    osp, cred_otw, vp);
2526 
2527 		if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
2528 			bsep = nfs4_create_bseqid_entry(oop, NULL, vp,
2529 			    0, args.ctag, close_args->seqid);
2530 
2531 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
2532 		    "nfs4close_otw: initiating recovery. error %d "
2533 		    "res.status %d", ep->error, res.status));
2534 
2535 		/*
2536 		 * Drop the 'os_sync_lock' here so we don't hit
2537 		 * a potential recursive mutex_enter via an
2538 		 * 'open_stream_hold()'.
2539 		 */
2540 		mutex_exit(&osp->os_sync_lock);
2541 		*have_sync_lockp = 0;
2542 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
2543 		    (close_type != CLOSE_RESEND &&
2544 		    lost_rqst.lr_op == OP_CLOSE) ? &lost_rqst : NULL,
2545 		    OP_CLOSE, bsep, NULL, NULL);
2546 
2547 		/* drop open seq sync, and let the calling function regrab it */
2548 		nfs4_end_open_seqid_sync(oop);
2549 		*did_start_seqid_syncp = 0;
2550 
2551 		if (bsep)
2552 			kmem_free(bsep, sizeof (*bsep));
2553 		/*
2554 		 * For signals, the caller wants to quit, so don't say to
2555 		 * retry.  For forced unmount, if it's a user thread, it
2556 		 * wants to quit.  If it's a recovery thread, the retry
2557 		 * will happen higher-up on the call stack.  Either way,
2558 		 * don't say to retry.
2559 		 */
2560 		if (abort == FALSE && ep->error != EINTR &&
2561 		    !NFS4_FRC_UNMT_ERR(ep->error, mi->mi_vfsp) &&
2562 		    close_type != CLOSE_RESEND &&
2563 		    close_type != CLOSE_AFTER_RESEND)
2564 			*recov = 1;
2565 		else
2566 			*recov = 0;
2567 
2568 		if (!ep->error)
2569 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2570 		return;
2571 	}
2572 
2573 	if (res.status) {
2574 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2575 		return;
2576 	}
2577 
2578 	mutex_enter(&rp->r_statev4_lock);
2579 	rp->created_v4 = 0;
2580 	mutex_exit(&rp->r_statev4_lock);
2581 
2582 	resop = &res.array[2];
2583 	osp->open_stateid = resop->nfs_resop4_u.opclose.open_stateid;
2584 	osp->os_valid = 0;
2585 
2586 	/*
2587 	 * This removes the reference obtained at OPEN; ie, when the
2588 	 * open stream structure was created.
2589 	 *
2590 	 * We don't have to worry about calling 'open_stream_rele'
2591 	 * since we our currently holding a reference to the open
2592 	 * stream which means the count cannot go to 0 with this
2593 	 * decrement.
2594 	 */
2595 	ASSERT(osp->os_ref_count >= 2);
2596 	osp->os_ref_count--;
2597 
2598 	if (ep->error == 0) {
2599 		/*
2600 		 * Avoid a deadlock with the r_serial thread waiting for
2601 		 * os_sync_lock in nfs4_get_otw_cred_by_osp() which might be
2602 		 * held by us. We will wait in nfs4_attr_cache() for the
2603 		 * completion of the r_serial thread.
2604 		 */
2605 		mutex_exit(&osp->os_sync_lock);
2606 		*have_sync_lockp = 0;
2607 
2608 		nfs4_attr_cache(vp,
2609 		    &res.array[1].nfs_resop4_u.opgetattr.ga_res,
2610 		    t, cred_otw, TRUE, NULL);
2611 	}
2612 
2613 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw:"
2614 	    " returning %d", ep->error));
2615 
2616 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2617 }
2618 
2619 /* ARGSUSED */
2620 static int
2621 nfs4_read(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2622     caller_context_t *ct)
2623 {
2624 	rnode4_t *rp;
2625 	u_offset_t off;
2626 	offset_t diff;
2627 	uint_t on;
2628 	uint_t n;
2629 	caddr_t base;
2630 	uint_t flags;
2631 	int error;
2632 	mntinfo4_t *mi;
2633 
2634 	rp = VTOR4(vp);
2635 
2636 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2637 
2638 	if (IS_SHADOW(vp, rp))
2639 		vp = RTOV4(rp);
2640 
2641 	if (vp->v_type != VREG)
2642 		return (EISDIR);
2643 
2644 	mi = VTOMI4(vp);
2645 
2646 	if (nfs_zone() != mi->mi_zone)
2647 		return (EIO);
2648 
2649 	if (uiop->uio_resid == 0)
2650 		return (0);
2651 
2652 	if (uiop->uio_loffset < 0 || uiop->uio_loffset + uiop->uio_resid < 0)
2653 		return (EINVAL);
2654 
2655 	mutex_enter(&rp->r_statelock);
2656 	if (rp->r_flags & R4RECOVERRP)
2657 		error = (rp->r_error ? rp->r_error : EIO);
2658 	else
2659 		error = 0;
2660 	mutex_exit(&rp->r_statelock);
2661 	if (error)
2662 		return (error);
2663 
2664 	/*
2665 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2666 	 * using client-side direct I/O and the file is not mmap'd and
2667 	 * there are no cached pages.
2668 	 */
2669 	if ((vp->v_flag & VNOCACHE) ||
2670 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2671 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2672 		size_t resid = 0;
2673 
2674 		return (nfs4read(vp, NULL, uiop->uio_loffset,
2675 		    uiop->uio_resid, &resid, cr, FALSE, uiop));
2676 	}
2677 
2678 	error = 0;
2679 
2680 	do {
2681 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2682 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2683 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2684 
2685 		if (error = nfs4_validate_caches(vp, cr))
2686 			break;
2687 
2688 		mutex_enter(&rp->r_statelock);
2689 		while (rp->r_flags & R4INCACHEPURGE) {
2690 			if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2691 				mutex_exit(&rp->r_statelock);
2692 				return (EINTR);
2693 			}
2694 		}
2695 		diff = rp->r_size - uiop->uio_loffset;
2696 		mutex_exit(&rp->r_statelock);
2697 		if (diff <= 0)
2698 			break;
2699 		if (diff < n)
2700 			n = (uint_t)diff;
2701 
2702 		if (vpm_enable) {
2703 			/*
2704 			 * Copy data.
2705 			 */
2706 			error = vpm_data_copy(vp, off + on, n, uiop,
2707 			    1, NULL, 0, S_READ);
2708 		} else {
2709 			base = segmap_getmapflt(segkmap, vp, off + on, n, 1,
2710 			    S_READ);
2711 
2712 			error = uiomove(base + on, n, UIO_READ, uiop);
2713 		}
2714 
2715 		if (!error) {
2716 			/*
2717 			 * If read a whole block or read to eof,
2718 			 * won't need this buffer again soon.
2719 			 */
2720 			mutex_enter(&rp->r_statelock);
2721 			if (n + on == MAXBSIZE ||
2722 			    uiop->uio_loffset == rp->r_size)
2723 				flags = SM_DONTNEED;
2724 			else
2725 				flags = 0;
2726 			mutex_exit(&rp->r_statelock);
2727 			if (vpm_enable) {
2728 				error = vpm_sync_pages(vp, off, n, flags);
2729 			} else {
2730 				error = segmap_release(segkmap, base, flags);
2731 			}
2732 		} else {
2733 			if (vpm_enable) {
2734 				(void) vpm_sync_pages(vp, off, n, 0);
2735 			} else {
2736 				(void) segmap_release(segkmap, base, 0);
2737 			}
2738 		}
2739 	} while (!error && uiop->uio_resid > 0);
2740 
2741 	return (error);
2742 }
2743 
2744 /* ARGSUSED */
2745 static int
2746 nfs4_write(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2747     caller_context_t *ct)
2748 {
2749 	rlim64_t limit = uiop->uio_llimit;
2750 	rnode4_t *rp;
2751 	u_offset_t off;
2752 	caddr_t base;
2753 	uint_t flags;
2754 	int remainder;
2755 	size_t n;
2756 	int on;
2757 	int error;
2758 	int resid;
2759 	u_offset_t offset;
2760 	mntinfo4_t *mi;
2761 	uint_t bsize;
2762 
2763 	rp = VTOR4(vp);
2764 
2765 	if (IS_SHADOW(vp, rp))
2766 		vp = RTOV4(rp);
2767 
2768 	if (vp->v_type != VREG)
2769 		return (EISDIR);
2770 
2771 	mi = VTOMI4(vp);
2772 
2773 	if (nfs_zone() != mi->mi_zone)
2774 		return (EIO);
2775 
2776 	if (uiop->uio_resid == 0)
2777 		return (0);
2778 
2779 	mutex_enter(&rp->r_statelock);
2780 	if (rp->r_flags & R4RECOVERRP)
2781 		error = (rp->r_error ? rp->r_error : EIO);
2782 	else
2783 		error = 0;
2784 	mutex_exit(&rp->r_statelock);
2785 	if (error)
2786 		return (error);
2787 
2788 	if (ioflag & FAPPEND) {
2789 		struct vattr va;
2790 
2791 		/*
2792 		 * Must serialize if appending.
2793 		 */
2794 		if (nfs_rw_lock_held(&rp->r_rwlock, RW_READER)) {
2795 			nfs_rw_exit(&rp->r_rwlock);
2796 			if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER,
2797 			    INTR4(vp)))
2798 				return (EINTR);
2799 		}
2800 
2801 		va.va_mask = AT_SIZE;
2802 		error = nfs4getattr(vp, &va, cr);
2803 		if (error)
2804 			return (error);
2805 		uiop->uio_loffset = va.va_size;
2806 	}
2807 
2808 	offset = uiop->uio_loffset + uiop->uio_resid;
2809 
2810 	if (uiop->uio_loffset < (offset_t)0 || offset < 0)
2811 		return (EINVAL);
2812 
2813 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
2814 		limit = MAXOFFSET_T;
2815 
2816 	/*
2817 	 * Check to make sure that the process will not exceed
2818 	 * its limit on file size.  It is okay to write up to
2819 	 * the limit, but not beyond.  Thus, the write which
2820 	 * reaches the limit will be short and the next write
2821 	 * will return an error.
2822 	 */
2823 	remainder = 0;
2824 	if (offset > uiop->uio_llimit) {
2825 		remainder = offset - uiop->uio_llimit;
2826 		uiop->uio_resid = uiop->uio_llimit - uiop->uio_loffset;
2827 		if (uiop->uio_resid <= 0) {
2828 			proc_t *p = ttoproc(curthread);
2829 
2830 			uiop->uio_resid += remainder;
2831 			mutex_enter(&p->p_lock);
2832 			(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE],
2833 			    p->p_rctls, p, RCA_UNSAFE_SIGINFO);
2834 			mutex_exit(&p->p_lock);
2835 			return (EFBIG);
2836 		}
2837 	}
2838 
2839 	/* update the change attribute, if we have a write delegation */
2840 
2841 	mutex_enter(&rp->r_statev4_lock);
2842 	if (rp->r_deleg_type == OPEN_DELEGATE_WRITE)
2843 		rp->r_deleg_change++;
2844 
2845 	mutex_exit(&rp->r_statev4_lock);
2846 
2847 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
2848 		return (EINTR);
2849 
2850 	/*
2851 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2852 	 * using client-side direct I/O and the file is not mmap'd and
2853 	 * there are no cached pages.
2854 	 */
2855 	if ((vp->v_flag & VNOCACHE) ||
2856 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2857 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2858 		size_t bufsize;
2859 		int count;
2860 		u_offset_t org_offset;
2861 		stable_how4 stab_comm;
2862 nfs4_fwrite:
2863 		if (rp->r_flags & R4STALE) {
2864 			resid = uiop->uio_resid;
2865 			offset = uiop->uio_loffset;
2866 			error = rp->r_error;
2867 			/*
2868 			 * A close may have cleared r_error, if so,
2869 			 * propagate ESTALE error return properly
2870 			 */
2871 			if (error == 0)
2872 				error = ESTALE;
2873 			goto bottom;
2874 		}
2875 
2876 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2877 		base = kmem_alloc(bufsize, KM_SLEEP);
2878 		do {
2879 			if (ioflag & FDSYNC)
2880 				stab_comm = DATA_SYNC4;
2881 			else
2882 				stab_comm = FILE_SYNC4;
2883 			resid = uiop->uio_resid;
2884 			offset = uiop->uio_loffset;
2885 			count = MIN(uiop->uio_resid, bufsize);
2886 			org_offset = uiop->uio_loffset;
2887 			error = uiomove(base, count, UIO_WRITE, uiop);
2888 			if (!error) {
2889 				error = nfs4write(vp, base, org_offset,
2890 				    count, cr, &stab_comm);
2891 				if (!error) {
2892 					mutex_enter(&rp->r_statelock);
2893 					if (rp->r_size < uiop->uio_loffset)
2894 						rp->r_size = uiop->uio_loffset;
2895 					mutex_exit(&rp->r_statelock);
2896 				}
2897 			}
2898 		} while (!error && uiop->uio_resid > 0);
2899 		kmem_free(base, bufsize);
2900 		goto bottom;
2901 	}
2902 
2903 	bsize = vp->v_vfsp->vfs_bsize;
2904 
2905 	do {
2906 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2907 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2908 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2909 
2910 		resid = uiop->uio_resid;
2911 		offset = uiop->uio_loffset;
2912 
2913 		if (rp->r_flags & R4STALE) {
2914 			error = rp->r_error;
2915 			/*
2916 			 * A close may have cleared r_error, if so,
2917 			 * propagate ESTALE error return properly
2918 			 */
2919 			if (error == 0)
2920 				error = ESTALE;
2921 			break;
2922 		}
2923 
2924 		/*
2925 		 * Don't create dirty pages faster than they
2926 		 * can be cleaned so that the system doesn't
2927 		 * get imbalanced.  If the async queue is
2928 		 * maxed out, then wait for it to drain before
2929 		 * creating more dirty pages.  Also, wait for
2930 		 * any threads doing pagewalks in the vop_getattr
2931 		 * entry points so that they don't block for
2932 		 * long periods.
2933 		 */
2934 		mutex_enter(&rp->r_statelock);
2935 		while ((mi->mi_max_threads != 0 &&
2936 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2937 		    rp->r_gcount > 0) {
2938 			if (INTR4(vp)) {
2939 				klwp_t *lwp = ttolwp(curthread);
2940 
2941 				if (lwp != NULL)
2942 					lwp->lwp_nostop++;
2943 				if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2944 					mutex_exit(&rp->r_statelock);
2945 					if (lwp != NULL)
2946 						lwp->lwp_nostop--;
2947 					error = EINTR;
2948 					goto bottom;
2949 				}
2950 				if (lwp != NULL)
2951 					lwp->lwp_nostop--;
2952 			} else
2953 				cv_wait(&rp->r_cv, &rp->r_statelock);
2954 		}
2955 		mutex_exit(&rp->r_statelock);
2956 
2957 		/*
2958 		 * Touch the page and fault it in if it is not in core
2959 		 * before segmap_getmapflt or vpm_data_copy can lock it.
2960 		 * This is to avoid the deadlock if the buffer is mapped
2961 		 * to the same file through mmap which we want to write.
2962 		 */
2963 		uio_prefaultpages((long)n, uiop);
2964 
2965 		if (vpm_enable) {
2966 			/*
2967 			 * It will use kpm mappings, so no need to
2968 			 * pass an address.
2969 			 */
2970 			error = writerp4(rp, NULL, n, uiop, 0);
2971 		} else  {
2972 			if (segmap_kpm) {
2973 				int pon = uiop->uio_loffset & PAGEOFFSET;
2974 				size_t pn = MIN(PAGESIZE - pon,
2975 				    uiop->uio_resid);
2976 				int pagecreate;
2977 
2978 				mutex_enter(&rp->r_statelock);
2979 				pagecreate = (pon == 0) && (pn == PAGESIZE ||
2980 				    uiop->uio_loffset + pn >= rp->r_size);
2981 				mutex_exit(&rp->r_statelock);
2982 
2983 				base = segmap_getmapflt(segkmap, vp, off + on,
2984 				    pn, !pagecreate, S_WRITE);
2985 
2986 				error = writerp4(rp, base + pon, n, uiop,
2987 				    pagecreate);
2988 
2989 			} else {
2990 				base = segmap_getmapflt(segkmap, vp, off + on,
2991 				    n, 0, S_READ);
2992 				error = writerp4(rp, base + on, n, uiop, 0);
2993 			}
2994 		}
2995 
2996 		if (!error) {
2997 			if (mi->mi_flags & MI4_NOAC)
2998 				flags = SM_WRITE;
2999 			else if ((uiop->uio_loffset % bsize) == 0 ||
3000 			    IS_SWAPVP(vp)) {
3001 				/*
3002 				 * Have written a whole block.
3003 				 * Start an asynchronous write
3004 				 * and mark the buffer to
3005 				 * indicate that it won't be
3006 				 * needed again soon.
3007 				 */
3008 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
3009 			} else
3010 				flags = 0;
3011 			if ((ioflag & (FSYNC|FDSYNC)) ||
3012 			    (rp->r_flags & R4OUTOFSPACE)) {
3013 				flags &= ~SM_ASYNC;
3014 				flags |= SM_WRITE;
3015 			}
3016 			if (vpm_enable) {
3017 				error = vpm_sync_pages(vp, off, n, flags);
3018 			} else {
3019 				error = segmap_release(segkmap, base, flags);
3020 			}
3021 		} else {
3022 			if (vpm_enable) {
3023 				(void) vpm_sync_pages(vp, off, n, 0);
3024 			} else {
3025 				(void) segmap_release(segkmap, base, 0);
3026 			}
3027 			/*
3028 			 * In the event that we got an access error while
3029 			 * faulting in a page for a write-only file just
3030 			 * force a write.
3031 			 */
3032 			if (error == EACCES)
3033 				goto nfs4_fwrite;
3034 		}
3035 	} while (!error && uiop->uio_resid > 0);
3036 
3037 bottom:
3038 	if (error) {
3039 		uiop->uio_resid = resid + remainder;
3040 		uiop->uio_loffset = offset;
3041 	} else {
3042 		uiop->uio_resid += remainder;
3043 
3044 		mutex_enter(&rp->r_statev4_lock);
3045 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
3046 			gethrestime(&rp->r_attr.va_mtime);
3047 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3048 		}
3049 		mutex_exit(&rp->r_statev4_lock);
3050 	}
3051 
3052 	nfs_rw_exit(&rp->r_lkserlock);
3053 
3054 	return (error);
3055 }
3056 
3057 /*
3058  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
3059  */
3060 static int
3061 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
3062     int flags, cred_t *cr)
3063 {
3064 	struct buf *bp;
3065 	int error;
3066 	page_t *savepp;
3067 	uchar_t fsdata;
3068 	stable_how4 stab_comm;
3069 
3070 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3071 	bp = pageio_setup(pp, len, vp, flags);
3072 	ASSERT(bp != NULL);
3073 
3074 	/*
3075 	 * pageio_setup should have set b_addr to 0.  This
3076 	 * is correct since we want to do I/O on a page
3077 	 * boundary.  bp_mapin will use this addr to calculate
3078 	 * an offset, and then set b_addr to the kernel virtual
3079 	 * address it allocated for us.
3080 	 */
3081 	ASSERT(bp->b_un.b_addr == 0);
3082 
3083 	bp->b_edev = 0;
3084 	bp->b_dev = 0;
3085 	bp->b_lblkno = lbtodb(off);
3086 	bp->b_file = vp;
3087 	bp->b_offset = (offset_t)off;
3088 	bp_mapin(bp);
3089 
3090 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
3091 	    freemem > desfree)
3092 		stab_comm = UNSTABLE4;
3093 	else
3094 		stab_comm = FILE_SYNC4;
3095 
3096 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
3097 
3098 	bp_mapout(bp);
3099 	pageio_done(bp);
3100 
3101 	if (stab_comm == UNSTABLE4)
3102 		fsdata = C_DELAYCOMMIT;
3103 	else
3104 		fsdata = C_NOCOMMIT;
3105 
3106 	savepp = pp;
3107 	do {
3108 		pp->p_fsdata = fsdata;
3109 	} while ((pp = pp->p_next) != savepp);
3110 
3111 	return (error);
3112 }
3113 
3114 /*
3115  */
3116 static int
3117 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
3118 {
3119 	nfs4_open_owner_t	*oop;
3120 	nfs4_open_stream_t	*osp;
3121 	rnode4_t		*rp = VTOR4(vp);
3122 	mntinfo4_t		*mi = VTOMI4(vp);
3123 	int			reopen_needed;
3124 
3125 	ASSERT(nfs_zone() == mi->mi_zone);
3126 
3127 
3128 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
3129 	if (!oop)
3130 		return (EIO);
3131 
3132 	/* returns with 'os_sync_lock' held */
3133 	osp = find_open_stream(oop, rp);
3134 	if (!osp) {
3135 		open_owner_rele(oop);
3136 		return (EIO);
3137 	}
3138 
3139 	if (osp->os_failed_reopen) {
3140 		mutex_exit(&osp->os_sync_lock);
3141 		open_stream_rele(osp, rp);
3142 		open_owner_rele(oop);
3143 		return (EIO);
3144 	}
3145 
3146 	/*
3147 	 * Determine whether a reopen is needed.  If this
3148 	 * is a delegation open stream, then the os_delegation bit
3149 	 * should be set.
3150 	 */
3151 
3152 	reopen_needed = osp->os_delegation;
3153 
3154 	mutex_exit(&osp->os_sync_lock);
3155 	open_owner_rele(oop);
3156 
3157 	if (reopen_needed) {
3158 		nfs4_error_zinit(ep);
3159 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
3160 		mutex_enter(&osp->os_sync_lock);
3161 		if (ep->error || ep->stat || osp->os_failed_reopen) {
3162 			mutex_exit(&osp->os_sync_lock);
3163 			open_stream_rele(osp, rp);
3164 			return (EIO);
3165 		}
3166 		mutex_exit(&osp->os_sync_lock);
3167 	}
3168 	open_stream_rele(osp, rp);
3169 
3170 	return (0);
3171 }
3172 
3173 /*
3174  * Write to file.  Writes to remote server in largest size
3175  * chunks that the server can handle.  Write is synchronous.
3176  */
3177 static int
3178 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3179     stable_how4 *stab_comm)
3180 {
3181 	mntinfo4_t *mi;
3182 	COMPOUND4args_clnt args;
3183 	COMPOUND4res_clnt res;
3184 	WRITE4args *wargs;
3185 	WRITE4res *wres;
3186 	nfs_argop4 argop[2];
3187 	nfs_resop4 *resop;
3188 	int tsize;
3189 	stable_how4 stable;
3190 	rnode4_t *rp;
3191 	int doqueue = 1;
3192 	bool_t needrecov;
3193 	nfs4_recov_state_t recov_state;
3194 	nfs4_stateid_types_t sid_types;
3195 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3196 	int recov;
3197 
3198 	rp = VTOR4(vp);
3199 	mi = VTOMI4(vp);
3200 
3201 	ASSERT(nfs_zone() == mi->mi_zone);
3202 
3203 	stable = *stab_comm;
3204 	*stab_comm = FILE_SYNC4;
3205 
3206 	needrecov = FALSE;
3207 	recov_state.rs_flags = 0;
3208 	recov_state.rs_num_retry_despite_err = 0;
3209 	nfs4_init_stateid_types(&sid_types);
3210 
3211 	/* Is curthread the recovery thread? */
3212 	mutex_enter(&mi->mi_lock);
3213 	recov = (mi->mi_recovthread == curthread);
3214 	mutex_exit(&mi->mi_lock);
3215 
3216 recov_retry:
3217 	args.ctag = TAG_WRITE;
3218 	args.array_len = 2;
3219 	args.array = argop;
3220 
3221 	if (!recov) {
3222 		e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3223 		    &recov_state, NULL);
3224 		if (e.error)
3225 			return (e.error);
3226 	}
3227 
3228 	/* 0. putfh target fh */
3229 	argop[0].argop = OP_CPUTFH;
3230 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3231 
3232 	/* 1. write */
3233 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3234 
3235 	do {
3236 
3237 		wargs->offset = (offset4)offset;
3238 		wargs->data_val = base;
3239 
3240 		if (mi->mi_io_kstats) {
3241 			mutex_enter(&mi->mi_lock);
3242 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3243 			mutex_exit(&mi->mi_lock);
3244 		}
3245 
3246 		if ((vp->v_flag & VNOCACHE) ||
3247 		    (rp->r_flags & R4DIRECTIO) ||
3248 		    (mi->mi_flags & MI4_DIRECTIO))
3249 			tsize = MIN(mi->mi_stsize, count);
3250 		else
3251 			tsize = MIN(mi->mi_curwrite, count);
3252 		wargs->data_len = (uint_t)tsize;
3253 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3254 
3255 		if (mi->mi_io_kstats) {
3256 			mutex_enter(&mi->mi_lock);
3257 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3258 			mutex_exit(&mi->mi_lock);
3259 		}
3260 
3261 		if (!recov) {
3262 			needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3263 			if (e.error && !needrecov) {
3264 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3265 				    &recov_state, needrecov);
3266 				return (e.error);
3267 			}
3268 		} else {
3269 			if (e.error)
3270 				return (e.error);
3271 		}
3272 
3273 		/*
3274 		 * Do handling of OLD_STATEID outside
3275 		 * of the normal recovery framework.
3276 		 *
3277 		 * If write receives a BAD stateid error while using a
3278 		 * delegation stateid, retry using the open stateid (if it
3279 		 * exists).  If it doesn't have an open stateid, reopen the
3280 		 * file first, then retry.
3281 		 */
3282 		if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3283 		    sid_types.cur_sid_type != SPEC_SID) {
3284 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3285 			if (!recov)
3286 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3287 				    &recov_state, needrecov);
3288 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3289 			goto recov_retry;
3290 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3291 		    sid_types.cur_sid_type == DEL_SID) {
3292 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3293 			mutex_enter(&rp->r_statev4_lock);
3294 			rp->r_deleg_return_pending = TRUE;
3295 			mutex_exit(&rp->r_statev4_lock);
3296 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3297 				if (!recov)
3298 					nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3299 					    &recov_state, needrecov);
3300 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3301 				return (EIO);
3302 			}
3303 			if (!recov)
3304 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3305 				    &recov_state, needrecov);
3306 			/* hold needed for nfs4delegreturn_thread */
3307 			VN_HOLD(vp);
3308 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3309 			    NFS4_DR_DISCARD), FALSE);
3310 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3311 			goto recov_retry;
3312 		}
3313 
3314 		if (needrecov) {
3315 			bool_t abort;
3316 
3317 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3318 			    "nfs4write: client got error %d, res.status %d"
3319 			    ", so start recovery", e.error, res.status));
3320 
3321 			abort = nfs4_start_recovery(&e,
3322 			    VTOMI4(vp), vp, NULL, &wargs->stateid,
3323 			    NULL, OP_WRITE, NULL, NULL, NULL);
3324 			if (!e.error) {
3325 				e.error = geterrno4(res.status);
3326 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3327 			}
3328 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3329 			    &recov_state, needrecov);
3330 			if (abort == FALSE)
3331 				goto recov_retry;
3332 			return (e.error);
3333 		}
3334 
3335 		if (res.status) {
3336 			e.error = geterrno4(res.status);
3337 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3338 			if (!recov)
3339 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3340 				    &recov_state, needrecov);
3341 			return (e.error);
3342 		}
3343 
3344 		resop = &res.array[1];	/* write res */
3345 		wres = &resop->nfs_resop4_u.opwrite;
3346 
3347 		if ((int)wres->count > tsize) {
3348 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3349 
3350 			zcmn_err(getzoneid(), CE_WARN,
3351 			    "nfs4write: server wrote %u, requested was %u",
3352 			    (int)wres->count, tsize);
3353 			if (!recov)
3354 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3355 				    &recov_state, needrecov);
3356 			return (EIO);
3357 		}
3358 		if (wres->committed == UNSTABLE4) {
3359 			*stab_comm = UNSTABLE4;
3360 			if (wargs->stable == DATA_SYNC4 ||
3361 			    wargs->stable == FILE_SYNC4) {
3362 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3363 				zcmn_err(getzoneid(), CE_WARN,
3364 				    "nfs4write: server %s did not commit "
3365 				    "to stable storage",
3366 				    rp->r_server->sv_hostname);
3367 				if (!recov)
3368 					nfs4_end_fop(VTOMI4(vp), vp, NULL,
3369 					    OH_WRITE, &recov_state, needrecov);
3370 				return (EIO);
3371 			}
3372 		}
3373 
3374 		tsize = (int)wres->count;
3375 		count -= tsize;
3376 		base += tsize;
3377 		offset += tsize;
3378 		if (mi->mi_io_kstats) {
3379 			mutex_enter(&mi->mi_lock);
3380 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3381 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3382 			    tsize;
3383 			mutex_exit(&mi->mi_lock);
3384 		}
3385 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3386 		mutex_enter(&rp->r_statelock);
3387 		if (rp->r_flags & R4HAVEVERF) {
3388 			if (rp->r_writeverf != wres->writeverf) {
3389 				nfs4_set_mod(vp);
3390 				rp->r_writeverf = wres->writeverf;
3391 			}
3392 		} else {
3393 			rp->r_writeverf = wres->writeverf;
3394 			rp->r_flags |= R4HAVEVERF;
3395 		}
3396 		PURGE_ATTRCACHE4_LOCKED(rp);
3397 		rp->r_flags |= R4WRITEMODIFIED;
3398 		gethrestime(&rp->r_attr.va_mtime);
3399 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3400 		mutex_exit(&rp->r_statelock);
3401 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3402 	} while (count);
3403 
3404 	if (!recov)
3405 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state,
3406 		    needrecov);
3407 
3408 	return (e.error);
3409 }
3410 
3411 /*
3412  * Read from a file.  Reads data in largest chunks our interface can handle.
3413  */
3414 static int
3415 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3416     size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3417 {
3418 	mntinfo4_t *mi;
3419 	COMPOUND4args_clnt args;
3420 	COMPOUND4res_clnt res;
3421 	READ4args *rargs;
3422 	nfs_argop4 argop[2];
3423 	int tsize;
3424 	int doqueue;
3425 	rnode4_t *rp;
3426 	int data_len;
3427 	bool_t is_eof;
3428 	bool_t needrecov = FALSE;
3429 	nfs4_recov_state_t recov_state;
3430 	nfs4_stateid_types_t sid_types;
3431 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3432 
3433 	rp = VTOR4(vp);
3434 	mi = VTOMI4(vp);
3435 	doqueue = 1;
3436 
3437 	ASSERT(nfs_zone() == mi->mi_zone);
3438 
3439 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3440 
3441 	args.array_len = 2;
3442 	args.array = argop;
3443 
3444 	nfs4_init_stateid_types(&sid_types);
3445 
3446 	recov_state.rs_flags = 0;
3447 	recov_state.rs_num_retry_despite_err = 0;
3448 
3449 recov_retry:
3450 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3451 	    &recov_state, NULL);
3452 	if (e.error)
3453 		return (e.error);
3454 
3455 	/* putfh target fh */
3456 	argop[0].argop = OP_CPUTFH;
3457 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3458 
3459 	/* read */
3460 	argop[1].argop = OP_READ;
3461 	rargs = &argop[1].nfs_argop4_u.opread;
3462 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3463 	    OP_READ, &sid_types, async);
3464 
3465 	do {
3466 		if (mi->mi_io_kstats) {
3467 			mutex_enter(&mi->mi_lock);
3468 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3469 			mutex_exit(&mi->mi_lock);
3470 		}
3471 
3472 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3473 		    "nfs4read: %s call, rp %s",
3474 		    needrecov ? "recov" : "first",
3475 		    rnode4info(rp)));
3476 
3477 		if ((vp->v_flag & VNOCACHE) ||
3478 		    (rp->r_flags & R4DIRECTIO) ||
3479 		    (mi->mi_flags & MI4_DIRECTIO))
3480 			tsize = MIN(mi->mi_tsize, count);
3481 		else
3482 			tsize = MIN(mi->mi_curread, count);
3483 
3484 		rargs->offset = (offset4)offset;
3485 		rargs->count = (count4)tsize;
3486 		rargs->res_data_val_alt = NULL;
3487 		rargs->res_mblk = NULL;
3488 		rargs->res_uiop = NULL;
3489 		rargs->res_maxsize = 0;
3490 		rargs->wlist = NULL;
3491 
3492 		if (uiop)
3493 			rargs->res_uiop = uiop;
3494 		else
3495 			rargs->res_data_val_alt = base;
3496 		rargs->res_maxsize = tsize;
3497 
3498 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3499 #ifdef	DEBUG
3500 		if (nfs4read_error_inject) {
3501 			res.status = nfs4read_error_inject;
3502 			nfs4read_error_inject = 0;
3503 		}
3504 #endif
3505 
3506 		if (mi->mi_io_kstats) {
3507 			mutex_enter(&mi->mi_lock);
3508 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3509 			mutex_exit(&mi->mi_lock);
3510 		}
3511 
3512 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3513 		if (e.error != 0 && !needrecov) {
3514 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3515 			    &recov_state, needrecov);
3516 			return (e.error);
3517 		}
3518 
3519 		/*
3520 		 * Do proper retry for OLD and BAD stateid errors outside
3521 		 * of the normal recovery framework.  There are two differences
3522 		 * between async and sync reads.  The first is that we allow
3523 		 * retry on BAD_STATEID for async reads, but not sync reads.
3524 		 * The second is that we mark the file dead for a failed
3525 		 * attempt with a special stateid for sync reads, but just
3526 		 * return EIO for async reads.
3527 		 *
3528 		 * If a sync read receives a BAD stateid error while using a
3529 		 * delegation stateid, retry using the open stateid (if it
3530 		 * exists).  If it doesn't have an open stateid, reopen the
3531 		 * file first, then retry.
3532 		 */
3533 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3534 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3535 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3536 			    &recov_state, needrecov);
3537 			if (sid_types.cur_sid_type == SPEC_SID) {
3538 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3539 				return (EIO);
3540 			}
3541 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3542 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3543 			goto recov_retry;
3544 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3545 		    !async && sid_types.cur_sid_type != SPEC_SID) {
3546 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3547 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3548 			    &recov_state, needrecov);
3549 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3550 			goto recov_retry;
3551 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3552 		    sid_types.cur_sid_type == DEL_SID) {
3553 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3554 			mutex_enter(&rp->r_statev4_lock);
3555 			rp->r_deleg_return_pending = TRUE;
3556 			mutex_exit(&rp->r_statev4_lock);
3557 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3558 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3559 				    &recov_state, needrecov);
3560 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3561 				return (EIO);
3562 			}
3563 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3564 			    &recov_state, needrecov);
3565 			/* hold needed for nfs4delegreturn_thread */
3566 			VN_HOLD(vp);
3567 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3568 			    NFS4_DR_DISCARD), FALSE);
3569 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3570 			goto recov_retry;
3571 		}
3572 		if (needrecov) {
3573 			bool_t abort;
3574 
3575 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3576 			    "nfs4read: initiating recovery\n"));
3577 			abort = nfs4_start_recovery(&e,
3578 			    mi, vp, NULL, &rargs->stateid,
3579 			    NULL, OP_READ, NULL, NULL, NULL);
3580 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3581 			    &recov_state, needrecov);
3582 			/*
3583 			 * Do not retry if we got OLD_STATEID using a special
3584 			 * stateid.  This avoids looping with a broken server.
3585 			 */
3586 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3587 			    sid_types.cur_sid_type == SPEC_SID)
3588 				abort = TRUE;
3589 
3590 			if (abort == FALSE) {
3591 				/*
3592 				 * Need to retry all possible stateids in
3593 				 * case the recovery error wasn't stateid
3594 				 * related or the stateids have become
3595 				 * stale (server reboot).
3596 				 */
3597 				nfs4_init_stateid_types(&sid_types);
3598 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3599 				goto recov_retry;
3600 			}
3601 
3602 			if (!e.error) {
3603 				e.error = geterrno4(res.status);
3604 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3605 			}
3606 			return (e.error);
3607 		}
3608 
3609 		if (res.status) {
3610 			e.error = geterrno4(res.status);
3611 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3612 			    &recov_state, needrecov);
3613 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3614 			return (e.error);
3615 		}
3616 
3617 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3618 		count -= data_len;
3619 		if (base)
3620 			base += data_len;
3621 		offset += data_len;
3622 		if (mi->mi_io_kstats) {
3623 			mutex_enter(&mi->mi_lock);
3624 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3625 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3626 			mutex_exit(&mi->mi_lock);
3627 		}
3628 		lwp_stat_update(LWP_STAT_INBLK, 1);
3629 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3630 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3631 
3632 	} while (count && !is_eof);
3633 
3634 	*residp = count;
3635 
3636 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3637 
3638 	return (e.error);
3639 }
3640 
3641 /* ARGSUSED */
3642 static int
3643 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp,
3644     caller_context_t *ct)
3645 {
3646 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3647 		return (EIO);
3648 	switch (cmd) {
3649 		case _FIODIRECTIO:
3650 			return (nfs4_directio(vp, (int)arg, cr));
3651 		default:
3652 			return (ENOTTY);
3653 	}
3654 }
3655 
3656 /* ARGSUSED */
3657 int
3658 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3659     caller_context_t *ct)
3660 {
3661 	int error;
3662 	rnode4_t *rp = VTOR4(vp);
3663 
3664 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3665 		return (EIO);
3666 	/*
3667 	 * If it has been specified that the return value will
3668 	 * just be used as a hint, and we are only being asked
3669 	 * for size, fsid or rdevid, then return the client's
3670 	 * notion of these values without checking to make sure
3671 	 * that the attribute cache is up to date.
3672 	 * The whole point is to avoid an over the wire GETATTR
3673 	 * call.
3674 	 */
3675 	if (flags & ATTR_HINT) {
3676 		if (!(vap->va_mask & ~(AT_SIZE | AT_FSID | AT_RDEV))) {
3677 			mutex_enter(&rp->r_statelock);
3678 			if (vap->va_mask & AT_SIZE)
3679 				vap->va_size = rp->r_size;
3680 			if (vap->va_mask & AT_FSID)
3681 				vap->va_fsid = rp->r_attr.va_fsid;
3682 			if (vap->va_mask & AT_RDEV)
3683 				vap->va_rdev = rp->r_attr.va_rdev;
3684 			mutex_exit(&rp->r_statelock);
3685 			return (0);
3686 		}
3687 	}
3688 
3689 	/*
3690 	 * Only need to flush pages if asking for the mtime
3691 	 * and if there any dirty pages or any outstanding
3692 	 * asynchronous (write) requests for this file.
3693 	 */
3694 	if (vap->va_mask & AT_MTIME) {
3695 		rp = VTOR4(vp);
3696 		if (nfs4_has_pages(vp)) {
3697 			mutex_enter(&rp->r_statev4_lock);
3698 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3699 				mutex_exit(&rp->r_statev4_lock);
3700 				if (rp->r_flags & R4DIRTY ||
3701 				    rp->r_awcount > 0) {
3702 					mutex_enter(&rp->r_statelock);
3703 					rp->r_gcount++;
3704 					mutex_exit(&rp->r_statelock);
3705 					error =
3706 					    nfs4_putpage(vp, (u_offset_t)0,
3707 					    0, 0, cr, NULL);
3708 					mutex_enter(&rp->r_statelock);
3709 					if (error && (error == ENOSPC ||
3710 					    error == EDQUOT)) {
3711 						if (!rp->r_error)
3712 							rp->r_error = error;
3713 					}
3714 					if (--rp->r_gcount == 0)
3715 						cv_broadcast(&rp->r_cv);
3716 					mutex_exit(&rp->r_statelock);
3717 				}
3718 			} else {
3719 				mutex_exit(&rp->r_statev4_lock);
3720 			}
3721 		}
3722 	}
3723 	return (nfs4getattr(vp, vap, cr));
3724 }
3725 
3726 int
3727 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3728 {
3729 	/*
3730 	 * If these are the only two bits cleared
3731 	 * on the server then return 0 (OK) else
3732 	 * return 1 (BAD).
3733 	 */
3734 	on_client &= ~(S_ISUID|S_ISGID);
3735 	if (on_client == from_server)
3736 		return (0);
3737 	else
3738 		return (1);
3739 }
3740 
3741 /*ARGSUSED4*/
3742 static int
3743 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3744     caller_context_t *ct)
3745 {
3746 	int error;
3747 
3748 	if (vap->va_mask & AT_NOSET)
3749 		return (EINVAL);
3750 
3751 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3752 		return (EIO);
3753 
3754 	/*
3755 	 * Don't call secpolicy_vnode_setattr, the client cannot
3756 	 * use its cached attributes to make security decisions
3757 	 * as the server may be faking mode bits or mapping uid/gid.
3758 	 * Always just let the server to the checking.
3759 	 * If we provide the ability to remove basic priviledges
3760 	 * to setattr (e.g. basic without chmod) then we will
3761 	 * need to add a check here before calling the server.
3762 	 */
3763 	error = nfs4setattr(vp, vap, flags, cr, NULL);
3764 
3765 	if (error == 0 && (vap->va_mask & AT_SIZE) && vap->va_size == 0)
3766 		vnevent_truncate(vp, ct);
3767 
3768 	return (error);
3769 }
3770 
3771 /*
3772  * To replace the "guarded" version 3 setattr, we use two types of compound
3773  * setattr requests:
3774  * 1. The "normal" setattr, used when the size of the file isn't being
3775  *    changed - { Putfh <fh>; Setattr; Getattr }/
3776  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3777  *    with only ctime as the argument. If the server ctime differs from
3778  *    what is cached on the client, the verify will fail, but we would
3779  *    already have the ctime from the preceding getattr, so just set it
3780  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3781  *	Setattr; Getattr }.
3782  *
3783  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3784  * this setattr and NULL if they are not.
3785  */
3786 static int
3787 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3788     vsecattr_t *vsap)
3789 {
3790 	COMPOUND4args_clnt args;
3791 	COMPOUND4res_clnt res, *resp = NULL;
3792 	nfs4_ga_res_t *garp = NULL;
3793 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3794 	nfs_argop4 argop[5];
3795 	int verify_argop = -1;
3796 	int setattr_argop = 1;
3797 	nfs_resop4 *resop;
3798 	vattr_t va;
3799 	rnode4_t *rp;
3800 	int doqueue = 1;
3801 	uint_t mask = vap->va_mask;
3802 	mode_t omode;
3803 	vsecattr_t *vsp;
3804 	timestruc_t ctime;
3805 	bool_t needrecov = FALSE;
3806 	nfs4_recov_state_t recov_state;
3807 	nfs4_stateid_types_t sid_types;
3808 	stateid4 stateid;
3809 	hrtime_t t;
3810 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3811 	servinfo4_t *svp;
3812 	bitmap4 supp_attrs;
3813 
3814 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3815 	rp = VTOR4(vp);
3816 	nfs4_init_stateid_types(&sid_types);
3817 
3818 	/*
3819 	 * Only need to flush pages if there are any pages and
3820 	 * if the file is marked as dirty in some fashion.  The
3821 	 * file must be flushed so that we can accurately
3822 	 * determine the size of the file and the cached data
3823 	 * after the SETATTR returns.  A file is considered to
3824 	 * be dirty if it is either marked with R4DIRTY, has
3825 	 * outstanding i/o's active, or is mmap'd.  In this
3826 	 * last case, we can't tell whether there are dirty
3827 	 * pages, so we flush just to be sure.
3828 	 */
3829 	if (nfs4_has_pages(vp) &&
3830 	    ((rp->r_flags & R4DIRTY) ||
3831 	    rp->r_count > 0 ||
3832 	    rp->r_mapcnt > 0)) {
3833 		ASSERT(vp->v_type != VCHR);
3834 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr, NULL);
3835 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3836 			mutex_enter(&rp->r_statelock);
3837 			if (!rp->r_error)
3838 				rp->r_error = e.error;
3839 			mutex_exit(&rp->r_statelock);
3840 		}
3841 	}
3842 
3843 	if (mask & AT_SIZE) {
3844 		/*
3845 		 * Verification setattr compound for non-deleg AT_SIZE:
3846 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3847 		 * Set ctime local here (outside the do_again label)
3848 		 * so that subsequent retries (after failed VERIFY)
3849 		 * will use ctime from GETATTR results (from failed
3850 		 * verify compound) as VERIFY arg.
3851 		 * If file has delegation, then VERIFY(time_metadata)
3852 		 * is of little added value, so don't bother.
3853 		 */
3854 		mutex_enter(&rp->r_statev4_lock);
3855 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3856 		    rp->r_deleg_return_pending) {
3857 			numops = 5;
3858 			ctime = rp->r_attr.va_ctime;
3859 		}
3860 		mutex_exit(&rp->r_statev4_lock);
3861 	}
3862 
3863 	recov_state.rs_flags = 0;
3864 	recov_state.rs_num_retry_despite_err = 0;
3865 
3866 	args.ctag = TAG_SETATTR;
3867 do_again:
3868 recov_retry:
3869 	setattr_argop = numops - 2;
3870 
3871 	args.array = argop;
3872 	args.array_len = numops;
3873 
3874 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3875 	if (e.error)
3876 		return (e.error);
3877 
3878 
3879 	/* putfh target fh */
3880 	argop[0].argop = OP_CPUTFH;
3881 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3882 
3883 	if (numops == 5) {
3884 		/*
3885 		 * We only care about the ctime, but need to get mtime
3886 		 * and size for proper cache update.
3887 		 */
3888 		/* getattr */
3889 		argop[1].argop = OP_GETATTR;
3890 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3891 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3892 
3893 		/* verify - set later in loop */
3894 		verify_argop = 2;
3895 	}
3896 
3897 	/* setattr */
3898 	svp = rp->r_server;
3899 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3900 	supp_attrs = svp->sv_supp_attrs;
3901 	nfs_rw_exit(&svp->sv_lock);
3902 
3903 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3904 	    supp_attrs, &e.error, &sid_types);
3905 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3906 	if (e.error) {
3907 		/* req time field(s) overflow - return immediately */
3908 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3909 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3910 		    opsetattr.obj_attributes);
3911 		return (e.error);
3912 	}
3913 	omode = rp->r_attr.va_mode;
3914 
3915 	/* getattr */
3916 	argop[numops-1].argop = OP_GETATTR;
3917 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3918 	/*
3919 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3920 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3921 	 * used in updating the ACL cache.
3922 	 */
3923 	if (vsap != NULL)
3924 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3925 		    FATTR4_ACL_MASK;
3926 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3927 
3928 	/*
3929 	 * setattr iterates if the object size is set and the cached ctime
3930 	 * does not match the file ctime. In that case, verify the ctime first.
3931 	 */
3932 
3933 	do {
3934 		if (verify_argop != -1) {
3935 			/*
3936 			 * Verify that the ctime match before doing setattr.
3937 			 */
3938 			va.va_mask = AT_CTIME;
3939 			va.va_ctime = ctime;
3940 			svp = rp->r_server;
3941 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3942 			supp_attrs = svp->sv_supp_attrs;
3943 			nfs_rw_exit(&svp->sv_lock);
3944 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3945 			    OP_VERIFY, supp_attrs);
3946 			if (e.error) {
3947 				/* req time field(s) overflow - return */
3948 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3949 				    needrecov);
3950 				break;
3951 			}
3952 		}
3953 
3954 		doqueue = 1;
3955 
3956 		t = gethrtime();
3957 
3958 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3959 
3960 		/*
3961 		 * Purge the access cache and ACL cache if changing either the
3962 		 * owner of the file, the group owner, or the mode.  These may
3963 		 * change the access permissions of the file, so purge old
3964 		 * information and start over again.
3965 		 */
3966 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3967 			(void) nfs4_access_purge_rp(rp);
3968 			if (rp->r_secattr != NULL) {
3969 				mutex_enter(&rp->r_statelock);
3970 				vsp = rp->r_secattr;
3971 				rp->r_secattr = NULL;
3972 				mutex_exit(&rp->r_statelock);
3973 				if (vsp != NULL)
3974 					nfs4_acl_free_cache(vsp);
3975 			}
3976 		}
3977 
3978 		/*
3979 		 * If res.array_len == numops, then everything succeeded,
3980 		 * except for possibly the final getattr.  If only the
3981 		 * last getattr failed, give up, and don't try recovery.
3982 		 */
3983 		if (res.array_len == numops) {
3984 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3985 			    needrecov);
3986 			if (! e.error)
3987 				resp = &res;
3988 			break;
3989 		}
3990 
3991 		/*
3992 		 * if either rpc call failed or completely succeeded - done
3993 		 */
3994 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
3995 		if (e.error) {
3996 			PURGE_ATTRCACHE4(vp);
3997 			if (!needrecov) {
3998 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3999 				    needrecov);
4000 				break;
4001 			}
4002 		}
4003 
4004 		/*
4005 		 * Do proper retry for OLD_STATEID outside of the normal
4006 		 * recovery framework.
4007 		 */
4008 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
4009 		    sid_types.cur_sid_type != SPEC_SID &&
4010 		    sid_types.cur_sid_type != NO_SID) {
4011 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4012 			    needrecov);
4013 			nfs4_save_stateid(&stateid, &sid_types);
4014 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4015 			    opsetattr.obj_attributes);
4016 			if (verify_argop != -1) {
4017 				nfs4args_verify_free(&argop[verify_argop]);
4018 				verify_argop = -1;
4019 			}
4020 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4021 			goto recov_retry;
4022 		}
4023 
4024 		if (needrecov) {
4025 			bool_t abort;
4026 
4027 			abort = nfs4_start_recovery(&e,
4028 			    VTOMI4(vp), vp, NULL, NULL, NULL,
4029 			    OP_SETATTR, NULL, NULL, NULL);
4030 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4031 			    needrecov);
4032 			/*
4033 			 * Do not retry if we failed with OLD_STATEID using
4034 			 * a special stateid.  This is done to avoid looping
4035 			 * with a broken server.
4036 			 */
4037 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
4038 			    (sid_types.cur_sid_type == SPEC_SID ||
4039 			    sid_types.cur_sid_type == NO_SID))
4040 				abort = TRUE;
4041 			if (!e.error) {
4042 				if (res.status == NFS4ERR_BADOWNER)
4043 					nfs4_log_badowner(VTOMI4(vp),
4044 					    OP_SETATTR);
4045 
4046 				e.error = geterrno4(res.status);
4047 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4048 			}
4049 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4050 			    opsetattr.obj_attributes);
4051 			if (verify_argop != -1) {
4052 				nfs4args_verify_free(&argop[verify_argop]);
4053 				verify_argop = -1;
4054 			}
4055 			if (abort == FALSE) {
4056 				/*
4057 				 * Need to retry all possible stateids in
4058 				 * case the recovery error wasn't stateid
4059 				 * related or the stateids have become
4060 				 * stale (server reboot).
4061 				 */
4062 				nfs4_init_stateid_types(&sid_types);
4063 				goto recov_retry;
4064 			}
4065 			return (e.error);
4066 		}
4067 
4068 		/*
4069 		 * Need to call nfs4_end_op before nfs4getattr to
4070 		 * avoid potential nfs4_start_op deadlock. See RFE
4071 		 * 4777612.  Calls to nfs4_invalidate_pages() and
4072 		 * nfs4_purge_stale_fh() might also generate over the
4073 		 * wire calls which my cause nfs4_start_op() deadlock.
4074 		 */
4075 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4076 
4077 		/*
4078 		 * Check to update lease.
4079 		 */
4080 		resp = &res;
4081 		if (res.status == NFS4_OK) {
4082 			break;
4083 		}
4084 
4085 		/*
4086 		 * Check if verify failed to see if try again
4087 		 */
4088 		if ((verify_argop == -1) || (res.array_len != 3)) {
4089 			/*
4090 			 * can't continue...
4091 			 */
4092 			if (res.status == NFS4ERR_BADOWNER)
4093 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
4094 
4095 			e.error = geterrno4(res.status);
4096 		} else {
4097 			/*
4098 			 * When the verify request fails, the client ctime is
4099 			 * not in sync with the server. This is the same as
4100 			 * the version 3 "not synchronized" error, and we
4101 			 * handle it in a similar manner (XXX do we need to???).
4102 			 * Use the ctime returned in the first getattr for
4103 			 * the input to the next verify.
4104 			 * If we couldn't get the attributes, then we give up
4105 			 * because we can't complete the operation as required.
4106 			 */
4107 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
4108 		}
4109 		if (e.error) {
4110 			PURGE_ATTRCACHE4(vp);
4111 			nfs4_purge_stale_fh(e.error, vp, cr);
4112 		} else {
4113 			/*
4114 			 * retry with a new verify value
4115 			 */
4116 			ctime = garp->n4g_va.va_ctime;
4117 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4118 			resp = NULL;
4119 		}
4120 		if (!e.error) {
4121 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4122 			    opsetattr.obj_attributes);
4123 			if (verify_argop != -1) {
4124 				nfs4args_verify_free(&argop[verify_argop]);
4125 				verify_argop = -1;
4126 			}
4127 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4128 			goto do_again;
4129 		}
4130 	} while (!e.error);
4131 
4132 	if (e.error) {
4133 		/*
4134 		 * If we are here, rfs4call has an irrecoverable error - return
4135 		 */
4136 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4137 		    opsetattr.obj_attributes);
4138 		if (verify_argop != -1) {
4139 			nfs4args_verify_free(&argop[verify_argop]);
4140 			verify_argop = -1;
4141 		}
4142 		if (resp)
4143 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4144 		return (e.error);
4145 	}
4146 
4147 
4148 
4149 	/*
4150 	 * If changing the size of the file, invalidate
4151 	 * any local cached data which is no longer part
4152 	 * of the file.  We also possibly invalidate the
4153 	 * last page in the file.  We could use
4154 	 * pvn_vpzero(), but this would mark the page as
4155 	 * modified and require it to be written back to
4156 	 * the server for no particularly good reason.
4157 	 * This way, if we access it, then we bring it
4158 	 * back in.  A read should be cheaper than a
4159 	 * write.
4160 	 */
4161 	if (mask & AT_SIZE) {
4162 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
4163 	}
4164 
4165 	/* either no error or one of the postop getattr failed */
4166 
4167 	/*
4168 	 * XXX Perform a simplified version of wcc checking. Instead of
4169 	 * have another getattr to get pre-op, just purge cache if
4170 	 * any of the ops prior to and including the getattr failed.
4171 	 * If the getattr succeeded then update the attrcache accordingly.
4172 	 */
4173 
4174 	garp = NULL;
4175 	if (res.status == NFS4_OK) {
4176 		/*
4177 		 * Last getattr
4178 		 */
4179 		resop = &res.array[numops - 1];
4180 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4181 	}
4182 	/*
4183 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
4184 	 * rather than filling it.  See the function itself for details.
4185 	 */
4186 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4187 	if (garp != NULL) {
4188 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
4189 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
4190 			vs_ace4_destroy(&garp->n4g_vsa);
4191 		} else {
4192 			if (vsap != NULL) {
4193 				/*
4194 				 * The ACL was supposed to be set and to be
4195 				 * returned in the last getattr of this
4196 				 * compound, but for some reason the getattr
4197 				 * result doesn't contain the ACL.  In this
4198 				 * case, purge the ACL cache.
4199 				 */
4200 				if (rp->r_secattr != NULL) {
4201 					mutex_enter(&rp->r_statelock);
4202 					vsp = rp->r_secattr;
4203 					rp->r_secattr = NULL;
4204 					mutex_exit(&rp->r_statelock);
4205 					if (vsp != NULL)
4206 						nfs4_acl_free_cache(vsp);
4207 				}
4208 			}
4209 		}
4210 	}
4211 
4212 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4213 		/*
4214 		 * Set the size, rather than relying on getting it updated
4215 		 * via a GETATTR.  With delegations the client tries to
4216 		 * suppress GETATTR calls.
4217 		 */
4218 		mutex_enter(&rp->r_statelock);
4219 		rp->r_size = vap->va_size;
4220 		mutex_exit(&rp->r_statelock);
4221 	}
4222 
4223 	/*
4224 	 * Can free up request args and res
4225 	 */
4226 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4227 	    opsetattr.obj_attributes);
4228 	if (verify_argop != -1) {
4229 		nfs4args_verify_free(&argop[verify_argop]);
4230 		verify_argop = -1;
4231 	}
4232 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4233 
4234 	/*
4235 	 * Some servers will change the mode to clear the setuid
4236 	 * and setgid bits when changing the uid or gid.  The
4237 	 * client needs to compensate appropriately.
4238 	 */
4239 	if (mask & (AT_UID | AT_GID)) {
4240 		int terror, do_setattr;
4241 
4242 		do_setattr = 0;
4243 		va.va_mask = AT_MODE;
4244 		terror = nfs4getattr(vp, &va, cr);
4245 		if (!terror &&
4246 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4247 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4248 			va.va_mask = AT_MODE;
4249 			if (mask & AT_MODE) {
4250 				/*
4251 				 * We asked the mode to be changed and what
4252 				 * we just got from the server in getattr is
4253 				 * not what we wanted it to be, so set it now.
4254 				 */
4255 				va.va_mode = vap->va_mode;
4256 				do_setattr = 1;
4257 			} else {
4258 				/*
4259 				 * We did not ask the mode to be changed,
4260 				 * Check to see that the server just cleared
4261 				 * I_SUID and I_GUID from it. If not then
4262 				 * set mode to omode with UID/GID cleared.
4263 				 */
4264 				if (nfs4_compare_modes(va.va_mode, omode)) {
4265 					omode &= ~(S_ISUID|S_ISGID);
4266 					va.va_mode = omode;
4267 					do_setattr = 1;
4268 				}
4269 			}
4270 
4271 			if (do_setattr)
4272 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4273 		}
4274 	}
4275 
4276 	return (e.error);
4277 }
4278 
4279 /* ARGSUSED */
4280 static int
4281 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr, caller_context_t *ct)
4282 {
4283 	COMPOUND4args_clnt args;
4284 	COMPOUND4res_clnt res;
4285 	int doqueue;
4286 	uint32_t acc, resacc, argacc;
4287 	rnode4_t *rp;
4288 	cred_t *cred, *ncr, *ncrfree = NULL;
4289 	nfs4_access_type_t cacc;
4290 	int num_ops;
4291 	nfs_argop4 argop[3];
4292 	nfs_resop4 *resop;
4293 	bool_t needrecov = FALSE, do_getattr;
4294 	nfs4_recov_state_t recov_state;
4295 	int rpc_error;
4296 	hrtime_t t;
4297 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4298 	mntinfo4_t *mi = VTOMI4(vp);
4299 
4300 	if (nfs_zone() != mi->mi_zone)
4301 		return (EIO);
4302 
4303 	acc = 0;
4304 	if (mode & VREAD)
4305 		acc |= ACCESS4_READ;
4306 	if (mode & VWRITE) {
4307 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4308 			return (EROFS);
4309 		if (vp->v_type == VDIR)
4310 			acc |= ACCESS4_DELETE;
4311 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4312 	}
4313 	if (mode & VEXEC) {
4314 		if (vp->v_type == VDIR)
4315 			acc |= ACCESS4_LOOKUP;
4316 		else
4317 			acc |= ACCESS4_EXECUTE;
4318 	}
4319 
4320 	if (VTOR4(vp)->r_acache != NULL) {
4321 		e.error = nfs4_validate_caches(vp, cr);
4322 		if (e.error)
4323 			return (e.error);
4324 	}
4325 
4326 	rp = VTOR4(vp);
4327 	if (vp->v_type == VDIR)
4328 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4329 		    ACCESS4_EXTEND | ACCESS4_LOOKUP;
4330 	else
4331 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4332 		    ACCESS4_EXECUTE;
4333 	recov_state.rs_flags = 0;
4334 	recov_state.rs_num_retry_despite_err = 0;
4335 
4336 	cred = cr;
4337 	/*
4338 	 * ncr and ncrfree both initially
4339 	 * point to the memory area returned
4340 	 * by crnetadjust();
4341 	 * ncrfree not NULL when exiting means
4342 	 * that we need to release it
4343 	 */
4344 	ncr = crnetadjust(cred);
4345 	ncrfree = ncr;
4346 
4347 tryagain:
4348 	cacc = nfs4_access_check(rp, acc, cred);
4349 	if (cacc == NFS4_ACCESS_ALLOWED) {
4350 		if (ncrfree != NULL)
4351 			crfree(ncrfree);
4352 		return (0);
4353 	}
4354 	if (cacc == NFS4_ACCESS_DENIED) {
4355 		/*
4356 		 * If the cred can be adjusted, try again
4357 		 * with the new cred.
4358 		 */
4359 		if (ncr != NULL) {
4360 			cred = ncr;
4361 			ncr = NULL;
4362 			goto tryagain;
4363 		}
4364 		if (ncrfree != NULL)
4365 			crfree(ncrfree);
4366 		return (EACCES);
4367 	}
4368 
4369 recov_retry:
4370 	/*
4371 	 * Don't take with r_statev4_lock here. r_deleg_type could
4372 	 * change as soon as lock is released.  Since it is an int,
4373 	 * there is no atomicity issue.
4374 	 */
4375 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4376 	num_ops = do_getattr ? 3 : 2;
4377 
4378 	args.ctag = TAG_ACCESS;
4379 
4380 	args.array_len = num_ops;
4381 	args.array = argop;
4382 
4383 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4384 	    &recov_state, NULL)) {
4385 		if (ncrfree != NULL)
4386 			crfree(ncrfree);
4387 		return (e.error);
4388 	}
4389 
4390 	/* putfh target fh */
4391 	argop[0].argop = OP_CPUTFH;
4392 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4393 
4394 	/* access */
4395 	argop[1].argop = OP_ACCESS;
4396 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4397 
4398 	/* getattr */
4399 	if (do_getattr) {
4400 		argop[2].argop = OP_GETATTR;
4401 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4402 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4403 	}
4404 
4405 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4406 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4407 	    rnode4info(VTOR4(vp))));
4408 
4409 	doqueue = 1;
4410 	t = gethrtime();
4411 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4412 	rpc_error = e.error;
4413 
4414 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4415 	if (needrecov) {
4416 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4417 		    "nfs4_access: initiating recovery\n"));
4418 
4419 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4420 		    NULL, OP_ACCESS, NULL, NULL, NULL) == FALSE) {
4421 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4422 			    &recov_state, needrecov);
4423 			if (!e.error)
4424 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4425 			goto recov_retry;
4426 		}
4427 	}
4428 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4429 
4430 	if (e.error)
4431 		goto out;
4432 
4433 	if (res.status) {
4434 		e.error = geterrno4(res.status);
4435 		/*
4436 		 * This might generate over the wire calls throught
4437 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4438 		 * here to avoid a deadlock.
4439 		 */
4440 		nfs4_purge_stale_fh(e.error, vp, cr);
4441 		goto out;
4442 	}
4443 	resop = &res.array[1];	/* access res */
4444 
4445 	resacc = resop->nfs_resop4_u.opaccess.access;
4446 
4447 	if (do_getattr) {
4448 		resop++;	/* getattr res */
4449 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4450 		    t, cr, FALSE, NULL);
4451 	}
4452 
4453 	if (!e.error) {
4454 		nfs4_access_cache(rp, argacc, resacc, cred);
4455 		/*
4456 		 * we just cached results with cred; if cred is the
4457 		 * adjusted credentials from crnetadjust, we do not want
4458 		 * to release them before exiting: hence setting ncrfree
4459 		 * to NULL
4460 		 */
4461 		if (cred != cr)
4462 			ncrfree = NULL;
4463 		/* XXX check the supported bits too? */
4464 		if ((acc & resacc) != acc) {
4465 			/*
4466 			 * The following code implements the semantic
4467 			 * that a setuid root program has *at least* the
4468 			 * permissions of the user that is running the
4469 			 * program.  See rfs3call() for more portions
4470 			 * of the implementation of this functionality.
4471 			 */
4472 			/* XXX-LP */
4473 			if (ncr != NULL) {
4474 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4475 				cred = ncr;
4476 				ncr = NULL;
4477 				goto tryagain;
4478 			}
4479 			e.error = EACCES;
4480 		}
4481 	}
4482 
4483 out:
4484 	if (!rpc_error)
4485 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4486 
4487 	if (ncrfree != NULL)
4488 		crfree(ncrfree);
4489 
4490 	return (e.error);
4491 }
4492 
4493 /* ARGSUSED */
4494 static int
4495 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr, caller_context_t *ct)
4496 {
4497 	COMPOUND4args_clnt args;
4498 	COMPOUND4res_clnt res;
4499 	int doqueue;
4500 	rnode4_t *rp;
4501 	nfs_argop4 argop[3];
4502 	nfs_resop4 *resop;
4503 	READLINK4res *lr_res;
4504 	nfs4_ga_res_t *garp;
4505 	uint_t len;
4506 	char *linkdata;
4507 	bool_t needrecov = FALSE;
4508 	nfs4_recov_state_t recov_state;
4509 	hrtime_t t;
4510 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4511 
4512 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4513 		return (EIO);
4514 	/*
4515 	 * Can't readlink anything other than a symbolic link.
4516 	 */
4517 	if (vp->v_type != VLNK)
4518 		return (EINVAL);
4519 
4520 	rp = VTOR4(vp);
4521 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4522 		e.error = nfs4_validate_caches(vp, cr);
4523 		if (e.error)
4524 			return (e.error);
4525 		mutex_enter(&rp->r_statelock);
4526 		if (rp->r_symlink.contents != NULL) {
4527 			e.error = uiomove(rp->r_symlink.contents,
4528 			    rp->r_symlink.len, UIO_READ, uiop);
4529 			mutex_exit(&rp->r_statelock);
4530 			return (e.error);
4531 		}
4532 		mutex_exit(&rp->r_statelock);
4533 	}
4534 	recov_state.rs_flags = 0;
4535 	recov_state.rs_num_retry_despite_err = 0;
4536 
4537 recov_retry:
4538 	args.array_len = 3;
4539 	args.array = argop;
4540 	args.ctag = TAG_READLINK;
4541 
4542 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4543 	if (e.error) {
4544 		return (e.error);
4545 	}
4546 
4547 	/* 0. putfh symlink fh */
4548 	argop[0].argop = OP_CPUTFH;
4549 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4550 
4551 	/* 1. readlink */
4552 	argop[1].argop = OP_READLINK;
4553 
4554 	/* 2. getattr */
4555 	argop[2].argop = OP_GETATTR;
4556 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4557 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4558 
4559 	doqueue = 1;
4560 
4561 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4562 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4563 	    rnode4info(VTOR4(vp))));
4564 
4565 	t = gethrtime();
4566 
4567 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4568 
4569 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4570 	if (needrecov) {
4571 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4572 		    "nfs4_readlink: initiating recovery\n"));
4573 
4574 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4575 		    NULL, OP_READLINK, NULL, NULL, NULL) == FALSE) {
4576 			if (!e.error)
4577 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4578 
4579 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4580 			    needrecov);
4581 			goto recov_retry;
4582 		}
4583 	}
4584 
4585 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4586 
4587 	if (e.error)
4588 		return (e.error);
4589 
4590 	/*
4591 	 * There is an path in the code below which calls
4592 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4593 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4594 	 * here to avoid nfs4_start_op() deadlock.
4595 	 */
4596 
4597 	if (res.status && (res.array_len < args.array_len)) {
4598 		/*
4599 		 * either Putfh or Link failed
4600 		 */
4601 		e.error = geterrno4(res.status);
4602 		nfs4_purge_stale_fh(e.error, vp, cr);
4603 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4604 		return (e.error);
4605 	}
4606 
4607 	resop = &res.array[1];	/* readlink res */
4608 	lr_res = &resop->nfs_resop4_u.opreadlink;
4609 
4610 	/*
4611 	 * treat symlink names as data
4612 	 */
4613 	linkdata = utf8_to_str((utf8string *)&lr_res->link, &len, NULL);
4614 	if (linkdata != NULL) {
4615 		int uio_len = len - 1;
4616 		/* len includes null byte, which we won't uiomove */
4617 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4618 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4619 			mutex_enter(&rp->r_statelock);
4620 			if (rp->r_symlink.contents == NULL) {
4621 				rp->r_symlink.contents = linkdata;
4622 				rp->r_symlink.len = uio_len;
4623 				rp->r_symlink.size = len;
4624 				mutex_exit(&rp->r_statelock);
4625 			} else {
4626 				mutex_exit(&rp->r_statelock);
4627 				kmem_free(linkdata, len);
4628 			}
4629 		} else {
4630 			kmem_free(linkdata, len);
4631 		}
4632 	}
4633 	if (res.status == NFS4_OK) {
4634 		resop++;	/* getattr res */
4635 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4636 	}
4637 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4638 
4639 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4640 
4641 	/*
4642 	 * The over the wire error for attempting to readlink something
4643 	 * other than a symbolic link is ENXIO.  However, we need to
4644 	 * return EINVAL instead of ENXIO, so we map it here.
4645 	 */
4646 	return (e.error == ENXIO ? EINVAL : e.error);
4647 }
4648 
4649 /*
4650  * Flush local dirty pages to stable storage on the server.
4651  *
4652  * If FNODSYNC is specified, then there is nothing to do because
4653  * metadata changes are not cached on the client before being
4654  * sent to the server.
4655  */
4656 /* ARGSUSED */
4657 static int
4658 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
4659 {
4660 	int error;
4661 
4662 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4663 		return (0);
4664 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4665 		return (EIO);
4666 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4667 	if (!error)
4668 		error = VTOR4(vp)->r_error;
4669 	return (error);
4670 }
4671 
4672 /*
4673  * Weirdness: if the file was removed or the target of a rename
4674  * operation while it was open, it got renamed instead.  Here we
4675  * remove the renamed file.
4676  */
4677 /* ARGSUSED */
4678 void
4679 nfs4_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4680 {
4681 	rnode4_t *rp;
4682 
4683 	ASSERT(vp != DNLC_NO_VNODE);
4684 
4685 	rp = VTOR4(vp);
4686 
4687 	if (IS_SHADOW(vp, rp)) {
4688 		sv_inactive(vp);
4689 		return;
4690 	}
4691 
4692 	/*
4693 	 * If this is coming from the wrong zone, we let someone in the right
4694 	 * zone take care of it asynchronously.  We can get here due to
4695 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4696 	 * potentially turn into an expensive no-op if, for instance, v_count
4697 	 * gets incremented in the meantime, but it's still correct.
4698 	 */
4699 	if (nfs_zone() != VTOMI4(vp)->mi_zone) {
4700 		nfs4_async_inactive(vp, cr);
4701 		return;
4702 	}
4703 
4704 	/*
4705 	 * Some of the cleanup steps might require over-the-wire
4706 	 * operations.  Since VOP_INACTIVE can get called as a result of
4707 	 * other over-the-wire operations (e.g., an attribute cache update
4708 	 * can lead to a DNLC purge), doing those steps now would lead to a
4709 	 * nested call to the recovery framework, which can deadlock.  So
4710 	 * do any over-the-wire cleanups asynchronously, in a separate
4711 	 * thread.
4712 	 */
4713 
4714 	mutex_enter(&rp->r_os_lock);
4715 	mutex_enter(&rp->r_statelock);
4716 	mutex_enter(&rp->r_statev4_lock);
4717 
4718 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4719 		mutex_exit(&rp->r_statev4_lock);
4720 		mutex_exit(&rp->r_statelock);
4721 		mutex_exit(&rp->r_os_lock);
4722 		nfs4_async_inactive(vp, cr);
4723 		return;
4724 	}
4725 
4726 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4727 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4728 		mutex_exit(&rp->r_statev4_lock);
4729 		mutex_exit(&rp->r_statelock);
4730 		mutex_exit(&rp->r_os_lock);
4731 		nfs4_async_inactive(vp, cr);
4732 		return;
4733 	}
4734 
4735 	if (rp->r_unldvp != NULL) {
4736 		mutex_exit(&rp->r_statev4_lock);
4737 		mutex_exit(&rp->r_statelock);
4738 		mutex_exit(&rp->r_os_lock);
4739 		nfs4_async_inactive(vp, cr);
4740 		return;
4741 	}
4742 	mutex_exit(&rp->r_statev4_lock);
4743 	mutex_exit(&rp->r_statelock);
4744 	mutex_exit(&rp->r_os_lock);
4745 
4746 	rp4_addfree(rp, cr);
4747 }
4748 
4749 /*
4750  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4751  * various bits of state.  The caller must not refer to vp after this call.
4752  */
4753 
4754 void
4755 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4756 {
4757 	rnode4_t *rp = VTOR4(vp);
4758 	nfs4_recov_state_t recov_state;
4759 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4760 	vnode_t *unldvp;
4761 	char *unlname;
4762 	cred_t *unlcred;
4763 	COMPOUND4args_clnt args;
4764 	COMPOUND4res_clnt res, *resp;
4765 	nfs_argop4 argop[2];
4766 	int doqueue;
4767 #ifdef DEBUG
4768 	char *name;
4769 #endif
4770 
4771 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
4772 	ASSERT(!IS_SHADOW(vp, rp));
4773 
4774 #ifdef DEBUG
4775 	name = fn_name(VTOSV(vp)->sv_name);
4776 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4777 	    "release vnode %s", name));
4778 	kmem_free(name, MAXNAMELEN);
4779 #endif
4780 
4781 	if (vp->v_type == VREG) {
4782 		bool_t recov_failed = FALSE;
4783 
4784 		e.error = nfs4close_all(vp, cr);
4785 		if (e.error) {
4786 			/* Check to see if recovery failed */
4787 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4788 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4789 				recov_failed = TRUE;
4790 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4791 			if (!recov_failed) {
4792 				mutex_enter(&rp->r_statelock);
4793 				if (rp->r_flags & R4RECOVERR)
4794 					recov_failed = TRUE;
4795 				mutex_exit(&rp->r_statelock);
4796 			}
4797 			if (recov_failed) {
4798 				NFS4_DEBUG(nfs4_client_recov_debug,
4799 				    (CE_NOTE, "nfs4_inactive_otw: "
4800 				    "close failed (recovery failure)"));
4801 			}
4802 		}
4803 	}
4804 
4805 redo:
4806 	if (rp->r_unldvp == NULL) {
4807 		rp4_addfree(rp, cr);
4808 		return;
4809 	}
4810 
4811 	/*
4812 	 * Save the vnode pointer for the directory where the
4813 	 * unlinked-open file got renamed, then set it to NULL
4814 	 * to prevent another thread from getting here before
4815 	 * we're done with the remove.  While we have the
4816 	 * statelock, make local copies of the pertinent rnode
4817 	 * fields.  If we weren't to do this in an atomic way, the
4818 	 * the unl* fields could become inconsistent with respect
4819 	 * to each other due to a race condition between this
4820 	 * code and nfs_remove().  See bug report 1034328.
4821 	 */
4822 	mutex_enter(&rp->r_statelock);
4823 	if (rp->r_unldvp == NULL) {
4824 		mutex_exit(&rp->r_statelock);
4825 		rp4_addfree(rp, cr);
4826 		return;
4827 	}
4828 
4829 	unldvp = rp->r_unldvp;
4830 	rp->r_unldvp = NULL;
4831 	unlname = rp->r_unlname;
4832 	rp->r_unlname = NULL;
4833 	unlcred = rp->r_unlcred;
4834 	rp->r_unlcred = NULL;
4835 	mutex_exit(&rp->r_statelock);
4836 
4837 	/*
4838 	 * If there are any dirty pages left, then flush
4839 	 * them.  This is unfortunate because they just
4840 	 * may get thrown away during the remove operation,
4841 	 * but we have to do this for correctness.
4842 	 */
4843 	if (nfs4_has_pages(vp) &&
4844 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4845 		ASSERT(vp->v_type != VCHR);
4846 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, NULL);
4847 		if (e.error) {
4848 			mutex_enter(&rp->r_statelock);
4849 			if (!rp->r_error)
4850 				rp->r_error = e.error;
4851 			mutex_exit(&rp->r_statelock);
4852 		}
4853 	}
4854 
4855 	recov_state.rs_flags = 0;
4856 	recov_state.rs_num_retry_despite_err = 0;
4857 recov_retry_remove:
4858 	/*
4859 	 * Do the remove operation on the renamed file
4860 	 */
4861 	args.ctag = TAG_INACTIVE;
4862 
4863 	/*
4864 	 * Remove ops: putfh dir; remove
4865 	 */
4866 	args.array_len = 2;
4867 	args.array = argop;
4868 
4869 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4870 	if (e.error) {
4871 		kmem_free(unlname, MAXNAMELEN);
4872 		crfree(unlcred);
4873 		VN_RELE(unldvp);
4874 		/*
4875 		 * Try again; this time around r_unldvp will be NULL, so we'll
4876 		 * just call rp4_addfree() and return.
4877 		 */
4878 		goto redo;
4879 	}
4880 
4881 	/* putfh directory */
4882 	argop[0].argop = OP_CPUTFH;
4883 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4884 
4885 	/* remove */
4886 	argop[1].argop = OP_CREMOVE;
4887 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4888 
4889 	doqueue = 1;
4890 	resp = &res;
4891 
4892 #if 0 /* notyet */
4893 	/*
4894 	 * Can't do this yet.  We may be being called from
4895 	 * dnlc_purge_XXX while that routine is holding a
4896 	 * mutex lock to the nc_rele list.  The calls to
4897 	 * nfs3_cache_wcc_data may result in calls to
4898 	 * dnlc_purge_XXX.  This will result in a deadlock.
4899 	 */
4900 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4901 	if (e.error) {
4902 		PURGE_ATTRCACHE4(unldvp);
4903 		resp = NULL;
4904 	} else if (res.status) {
4905 		e.error = geterrno4(res.status);
4906 		PURGE_ATTRCACHE4(unldvp);
4907 		/*
4908 		 * This code is inactive right now
4909 		 * but if made active there should
4910 		 * be a nfs4_end_op() call before
4911 		 * nfs4_purge_stale_fh to avoid start_op()
4912 		 * deadlock. See BugId: 4948726
4913 		 */
4914 		nfs4_purge_stale_fh(error, unldvp, cr);
4915 	} else {
4916 		nfs_resop4 *resop;
4917 		REMOVE4res *rm_res;
4918 
4919 		resop = &res.array[1];
4920 		rm_res = &resop->nfs_resop4_u.opremove;
4921 		/*
4922 		 * Update directory cache attribute,
4923 		 * readdir and dnlc caches.
4924 		 */
4925 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4926 	}
4927 #else
4928 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4929 
4930 	PURGE_ATTRCACHE4(unldvp);
4931 #endif
4932 
4933 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4934 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4935 		    NULL, NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
4936 			if (!e.error)
4937 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4938 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4939 			    &recov_state, TRUE);
4940 			goto recov_retry_remove;
4941 		}
4942 	}
4943 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4944 
4945 	/*
4946 	 * Release stuff held for the remove
4947 	 */
4948 	VN_RELE(unldvp);
4949 	if (!e.error && resp)
4950 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4951 
4952 	kmem_free(unlname, MAXNAMELEN);
4953 	crfree(unlcred);
4954 	goto redo;
4955 }
4956 
4957 /*
4958  * Remote file system operations having to do with directory manipulation.
4959  */
4960 /* ARGSUSED3 */
4961 int
4962 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4963     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
4964     int *direntflags, pathname_t *realpnp)
4965 {
4966 	int error;
4967 	vnode_t *vp, *avp = NULL;
4968 	rnode4_t *drp;
4969 
4970 	*vpp = NULL;
4971 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4972 		return (EPERM);
4973 	/*
4974 	 * if LOOKUP_XATTR, must replace dvp (object) with
4975 	 * object's attrdir before continuing with lookup
4976 	 */
4977 	if (flags & LOOKUP_XATTR) {
4978 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4979 		if (error)
4980 			return (error);
4981 
4982 		dvp = avp;
4983 
4984 		/*
4985 		 * If lookup is for "", just return dvp now.  The attrdir
4986 		 * has already been activated (from nfs4lookup_xattr), and
4987 		 * the caller will RELE the original dvp -- not
4988 		 * the attrdir.  So, set vpp and return.
4989 		 * Currently, when the LOOKUP_XATTR flag is
4990 		 * passed to VOP_LOOKUP, the name is always empty, and
4991 		 * shortcircuiting here avoids 3 unneeded lock/unlock
4992 		 * pairs.
4993 		 *
4994 		 * If a non-empty name was provided, then it is the
4995 		 * attribute name, and it will be looked up below.
4996 		 */
4997 		if (*nm == '\0') {
4998 			*vpp = dvp;
4999 			return (0);
5000 		}
5001 
5002 		/*
5003 		 * The vfs layer never sends a name when asking for the
5004 		 * attrdir, so we should never get here (unless of course
5005 		 * name is passed at some time in future -- at which time
5006 		 * we'll blow up here).
5007 		 */
5008 		ASSERT(0);
5009 	}
5010 
5011 	drp = VTOR4(dvp);
5012 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
5013 		return (EINTR);
5014 
5015 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
5016 	nfs_rw_exit(&drp->r_rwlock);
5017 
5018 	/*
5019 	 * If vnode is a device, create special vnode.
5020 	 */
5021 	if (!error && ISVDEV((*vpp)->v_type)) {
5022 		vp = *vpp;
5023 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
5024 		VN_RELE(vp);
5025 	}
5026 
5027 	return (error);
5028 }
5029 
5030 /* ARGSUSED */
5031 static int
5032 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
5033 {
5034 	int error;
5035 	rnode4_t *drp;
5036 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
5037 	mntinfo4_t *mi;
5038 
5039 	mi = VTOMI4(dvp);
5040 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR) &&
5041 	    !vfs_has_feature(mi->mi_vfsp, VFSFT_SYSATTR_VIEWS))
5042 		return (EINVAL);
5043 
5044 	drp = VTOR4(dvp);
5045 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
5046 		return (EINTR);
5047 
5048 	mutex_enter(&drp->r_statelock);
5049 	/*
5050 	 * If the server doesn't support xattrs just return EINVAL
5051 	 */
5052 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
5053 		mutex_exit(&drp->r_statelock);
5054 		nfs_rw_exit(&drp->r_rwlock);
5055 		return (EINVAL);
5056 	}
5057 
5058 	/*
5059 	 * If there is a cached xattr directory entry,
5060 	 * use it as long as the attributes are valid. If the
5061 	 * attributes are not valid, take the simple approach and
5062 	 * free the cached value and re-fetch a new value.
5063 	 *
5064 	 * We don't negative entry cache for now, if we did we
5065 	 * would need to check if the file has changed on every
5066 	 * lookup. But xattrs don't exist very often and failing
5067 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
5068 	 * so do an openattr over the wire for now.
5069 	 */
5070 	if (drp->r_xattr_dir != NULL) {
5071 		if (ATTRCACHE4_VALID(dvp)) {
5072 			VN_HOLD(drp->r_xattr_dir);
5073 			*vpp = drp->r_xattr_dir;
5074 			mutex_exit(&drp->r_statelock);
5075 			nfs_rw_exit(&drp->r_rwlock);
5076 			return (0);
5077 		}
5078 		VN_RELE(drp->r_xattr_dir);
5079 		drp->r_xattr_dir = NULL;
5080 	}
5081 	mutex_exit(&drp->r_statelock);
5082 
5083 	error = nfs4openattr(dvp, vpp, cflag, cr);
5084 
5085 	nfs_rw_exit(&drp->r_rwlock);
5086 
5087 	return (error);
5088 }
5089 
5090 static int
5091 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
5092 {
5093 	int error;
5094 	rnode4_t *drp;
5095 
5096 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5097 
5098 	/*
5099 	 * If lookup is for "", just return dvp.  Don't need
5100 	 * to send it over the wire, look it up in the dnlc,
5101 	 * or perform any access checks.
5102 	 */
5103 	if (*nm == '\0') {
5104 		VN_HOLD(dvp);
5105 		*vpp = dvp;
5106 		return (0);
5107 	}
5108 
5109 	/*
5110 	 * Can't do lookups in non-directories.
5111 	 */
5112 	if (dvp->v_type != VDIR)
5113 		return (ENOTDIR);
5114 
5115 	/*
5116 	 * If lookup is for ".", just return dvp.  Don't need
5117 	 * to send it over the wire or look it up in the dnlc,
5118 	 * just need to check access.
5119 	 */
5120 	if (nm[0] == '.' && nm[1] == '\0') {
5121 		error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5122 		if (error)
5123 			return (error);
5124 		VN_HOLD(dvp);
5125 		*vpp = dvp;
5126 		return (0);
5127 	}
5128 
5129 	drp = VTOR4(dvp);
5130 	if (!(drp->r_flags & R4LOOKUP)) {
5131 		mutex_enter(&drp->r_statelock);
5132 		drp->r_flags |= R4LOOKUP;
5133 		mutex_exit(&drp->r_statelock);
5134 	}
5135 
5136 	*vpp = NULL;
5137 	/*
5138 	 * Lookup this name in the DNLC.  If there is no entry
5139 	 * lookup over the wire.
5140 	 */
5141 	if (!skipdnlc)
5142 		*vpp = dnlc_lookup(dvp, nm);
5143 	if (*vpp == NULL) {
5144 		/*
5145 		 * We need to go over the wire to lookup the name.
5146 		 */
5147 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
5148 	}
5149 
5150 	/*
5151 	 * We hit on the dnlc
5152 	 */
5153 	if (*vpp != DNLC_NO_VNODE ||
5154 	    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
5155 		/*
5156 		 * But our attrs may not be valid.
5157 		 */
5158 		if (ATTRCACHE4_VALID(dvp)) {
5159 			error = nfs4_waitfor_purge_complete(dvp);
5160 			if (error) {
5161 				VN_RELE(*vpp);
5162 				*vpp = NULL;
5163 				return (error);
5164 			}
5165 
5166 			/*
5167 			 * If after the purge completes, check to make sure
5168 			 * our attrs are still valid.
5169 			 */
5170 			if (ATTRCACHE4_VALID(dvp)) {
5171 				/*
5172 				 * If we waited for a purge we may have
5173 				 * lost our vnode so look it up again.
5174 				 */
5175 				VN_RELE(*vpp);
5176 				*vpp = dnlc_lookup(dvp, nm);
5177 				if (*vpp == NULL)
5178 					return (nfs4lookupnew_otw(dvp,
5179 					    nm, vpp, cr));
5180 
5181 				/*
5182 				 * The access cache should almost always hit
5183 				 */
5184 				error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5185 
5186 				if (error) {
5187 					VN_RELE(*vpp);
5188 					*vpp = NULL;
5189 					return (error);
5190 				}
5191 				if (*vpp == DNLC_NO_VNODE) {
5192 					VN_RELE(*vpp);
5193 					*vpp = NULL;
5194 					return (ENOENT);
5195 				}
5196 				return (0);
5197 			}
5198 		}
5199 	}
5200 
5201 	ASSERT(*vpp != NULL);
5202 
5203 	/*
5204 	 * We may have gotten here we have one of the following cases:
5205 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5206 	 *		need to validate them.
5207 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5208 	 *		must validate.
5209 	 *
5210 	 * Go to the server and check if the directory has changed, if
5211 	 * it hasn't we are done and can use the dnlc entry.
5212 	 */
5213 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5214 }
5215 
5216 /*
5217  * Go to the server and check if the directory has changed, if
5218  * it hasn't we are done and can use the dnlc entry.  If it
5219  * has changed we get a new copy of its attributes and check
5220  * the access for VEXEC, then relookup the filename and
5221  * get its filehandle and attributes.
5222  *
5223  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5224  *	if the NVERIFY failed we must
5225  *		purge the caches
5226  *		cache new attributes (will set r_time_attr_inval)
5227  *		cache new access
5228  *		recheck VEXEC access
5229  *		add name to dnlc, possibly negative
5230  *		if LOOKUP succeeded
5231  *			cache new attributes
5232  *	else
5233  *		set a new r_time_attr_inval for dvp
5234  *		check to make sure we have access
5235  *
5236  * The vpp returned is the vnode passed in if the directory is valid,
5237  * a new vnode if successful lookup, or NULL on error.
5238  */
5239 static int
5240 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5241 {
5242 	COMPOUND4args_clnt args;
5243 	COMPOUND4res_clnt res;
5244 	fattr4 *ver_fattr;
5245 	fattr4_change dchange;
5246 	int32_t *ptr;
5247 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5248 	nfs_argop4 *argop;
5249 	int doqueue;
5250 	mntinfo4_t *mi;
5251 	nfs4_recov_state_t recov_state;
5252 	hrtime_t t;
5253 	int isdotdot;
5254 	vnode_t *nvp;
5255 	nfs_fh4 *fhp;
5256 	nfs4_sharedfh_t *sfhp;
5257 	nfs4_access_type_t cacc;
5258 	rnode4_t *nrp;
5259 	rnode4_t *drp = VTOR4(dvp);
5260 	nfs4_ga_res_t *garp = NULL;
5261 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5262 
5263 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5264 	ASSERT(nm != NULL);
5265 	ASSERT(nm[0] != '\0');
5266 	ASSERT(dvp->v_type == VDIR);
5267 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5268 	ASSERT(*vpp != NULL);
5269 
5270 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5271 		isdotdot = 1;
5272 		args.ctag = TAG_LOOKUP_VPARENT;
5273 	} else {
5274 		/*
5275 		 * If dvp were a stub, it should have triggered and caused
5276 		 * a mount for us to get this far.
5277 		 */
5278 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5279 
5280 		isdotdot = 0;
5281 		args.ctag = TAG_LOOKUP_VALID;
5282 	}
5283 
5284 	mi = VTOMI4(dvp);
5285 	recov_state.rs_flags = 0;
5286 	recov_state.rs_num_retry_despite_err = 0;
5287 
5288 	nvp = NULL;
5289 
5290 	/* Save the original mount point security information */
5291 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5292 
5293 recov_retry:
5294 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5295 	    &recov_state, NULL);
5296 	if (e.error) {
5297 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5298 		VN_RELE(*vpp);
5299 		*vpp = NULL;
5300 		return (e.error);
5301 	}
5302 
5303 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5304 
5305 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5306 	args.array_len = 7;
5307 	args.array = argop;
5308 
5309 	/* 0. putfh file */
5310 	argop[0].argop = OP_CPUTFH;
5311 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5312 
5313 	/* 1. nverify the change info */
5314 	argop[1].argop = OP_NVERIFY;
5315 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5316 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5317 	ver_fattr->attrlist4 = (char *)&dchange;
5318 	ptr = (int32_t *)&dchange;
5319 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5320 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5321 
5322 	/* 2. getattr directory */
5323 	argop[2].argop = OP_GETATTR;
5324 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5325 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5326 
5327 	/* 3. access directory */
5328 	argop[3].argop = OP_ACCESS;
5329 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5330 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5331 
5332 	/* 4. lookup name */
5333 	if (isdotdot) {
5334 		argop[4].argop = OP_LOOKUPP;
5335 	} else {
5336 		argop[4].argop = OP_CLOOKUP;
5337 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5338 	}
5339 
5340 	/* 5. resulting file handle */
5341 	argop[5].argop = OP_GETFH;
5342 
5343 	/* 6. resulting file attributes */
5344 	argop[6].argop = OP_GETATTR;
5345 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5346 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5347 
5348 	doqueue = 1;
5349 	t = gethrtime();
5350 
5351 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5352 
5353 	if (!isdotdot && res.status == NFS4ERR_MOVED) {
5354 		e.error = nfs4_setup_referral(dvp, nm, vpp, cr);
5355 		if (e.error != 0 && *vpp != NULL)
5356 			VN_RELE(*vpp);
5357 		nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5358 		    &recov_state, FALSE);
5359 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5360 		kmem_free(argop, argoplist_size);
5361 		return (e.error);
5362 	}
5363 
5364 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5365 		/*
5366 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5367 		 * from this thread, do not go thru the recovery thread since
5368 		 * we need the nm information.
5369 		 *
5370 		 * Not doing dotdot case because there is no specification
5371 		 * for (PUTFH, SECINFO "..") yet.
5372 		 */
5373 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5374 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5375 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5376 				    &recov_state, FALSE);
5377 			else
5378 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5379 				    &recov_state, TRUE);
5380 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5381 			kmem_free(argop, argoplist_size);
5382 			if (!e.error)
5383 				goto recov_retry;
5384 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5385 			VN_RELE(*vpp);
5386 			*vpp = NULL;
5387 			return (e.error);
5388 		}
5389 
5390 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5391 		    OP_LOOKUP, NULL, NULL, NULL) == FALSE) {
5392 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5393 			    &recov_state, TRUE);
5394 
5395 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5396 			kmem_free(argop, argoplist_size);
5397 			goto recov_retry;
5398 		}
5399 	}
5400 
5401 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5402 
5403 	if (e.error || res.array_len == 0) {
5404 		/*
5405 		 * If e.error isn't set, then reply has no ops (or we couldn't
5406 		 * be here).  The only legal way to reply without an op array
5407 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5408 		 * be in the reply for all other status values.
5409 		 *
5410 		 * For valid replies without an ops array, return ENOTSUP
5411 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5412 		 * return EIO -- don't trust status.
5413 		 */
5414 		if (e.error == 0)
5415 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5416 			    ENOTSUP : EIO;
5417 		VN_RELE(*vpp);
5418 		*vpp = NULL;
5419 		kmem_free(argop, argoplist_size);
5420 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5421 		return (e.error);
5422 	}
5423 
5424 	if (res.status != NFS4ERR_SAME) {
5425 		e.error = geterrno4(res.status);
5426 
5427 		/*
5428 		 * The NVERIFY "failed" so the directory has changed
5429 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5430 		 * cleanly.
5431 		 */
5432 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5433 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5434 			nfs4_purge_stale_fh(e.error, dvp, cr);
5435 			VN_RELE(*vpp);
5436 			*vpp = NULL;
5437 			goto exit;
5438 		}
5439 
5440 		/*
5441 		 * We know the NVERIFY "failed" so we must:
5442 		 *	purge the caches (access and indirectly dnlc if needed)
5443 		 */
5444 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5445 
5446 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5447 			nfs4_purge_stale_fh(e.error, dvp, cr);
5448 			VN_RELE(*vpp);
5449 			*vpp = NULL;
5450 			goto exit;
5451 		}
5452 
5453 		/*
5454 		 * Install new cached attributes for the directory
5455 		 */
5456 		nfs4_attr_cache(dvp,
5457 		    &res.array[2].nfs_resop4_u.opgetattr.ga_res,
5458 		    t, cr, FALSE, NULL);
5459 
5460 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5461 			nfs4_purge_stale_fh(e.error, dvp, cr);
5462 			VN_RELE(*vpp);
5463 			*vpp = NULL;
5464 			e.error = geterrno4(res.status);
5465 			goto exit;
5466 		}
5467 
5468 		/*
5469 		 * Now we know the directory is valid,
5470 		 * cache new directory access
5471 		 */
5472 		nfs4_access_cache(drp,
5473 		    args.array[3].nfs_argop4_u.opaccess.access,
5474 		    res.array[3].nfs_resop4_u.opaccess.access, cr);
5475 
5476 		/*
5477 		 * recheck VEXEC access
5478 		 */
5479 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5480 		if (cacc != NFS4_ACCESS_ALLOWED) {
5481 			/*
5482 			 * Directory permissions might have been revoked
5483 			 */
5484 			if (cacc == NFS4_ACCESS_DENIED) {
5485 				e.error = EACCES;
5486 				VN_RELE(*vpp);
5487 				*vpp = NULL;
5488 				goto exit;
5489 			}
5490 
5491 			/*
5492 			 * Somehow we must not have asked for enough
5493 			 * so try a singleton ACCESS, should never happen.
5494 			 */
5495 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5496 			if (e.error) {
5497 				VN_RELE(*vpp);
5498 				*vpp = NULL;
5499 				goto exit;
5500 			}
5501 		}
5502 
5503 		e.error = geterrno4(res.status);
5504 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5505 			/*
5506 			 * The lookup failed, probably no entry
5507 			 */
5508 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5509 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5510 			} else {
5511 				/*
5512 				 * Might be some other error, so remove
5513 				 * the dnlc entry to make sure we start all
5514 				 * over again, next time.
5515 				 */
5516 				dnlc_remove(dvp, nm);
5517 			}
5518 			VN_RELE(*vpp);
5519 			*vpp = NULL;
5520 			goto exit;
5521 		}
5522 
5523 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5524 			/*
5525 			 * The file exists but we can't get its fh for
5526 			 * some unknown reason.  Remove it from the dnlc
5527 			 * and error out to be safe.
5528 			 */
5529 			dnlc_remove(dvp, nm);
5530 			VN_RELE(*vpp);
5531 			*vpp = NULL;
5532 			goto exit;
5533 		}
5534 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5535 		if (fhp->nfs_fh4_len == 0) {
5536 			/*
5537 			 * The file exists but a bogus fh
5538 			 * some unknown reason.  Remove it from the dnlc
5539 			 * and error out to be safe.
5540 			 */
5541 			e.error = ENOENT;
5542 			dnlc_remove(dvp, nm);
5543 			VN_RELE(*vpp);
5544 			*vpp = NULL;
5545 			goto exit;
5546 		}
5547 		sfhp = sfh4_get(fhp, mi);
5548 
5549 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5550 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5551 
5552 		/*
5553 		 * Make the new rnode
5554 		 */
5555 		if (isdotdot) {
5556 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5557 			if (e.error) {
5558 				sfh4_rele(&sfhp);
5559 				VN_RELE(*vpp);
5560 				*vpp = NULL;
5561 				goto exit;
5562 			}
5563 			/*
5564 			 * XXX if nfs4_make_dotdot uses an existing rnode
5565 			 * XXX it doesn't update the attributes.
5566 			 * XXX for now just save them again to save an OTW
5567 			 */
5568 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5569 		} else {
5570 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5571 			    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
5572 			/*
5573 			 * If v_type == VNON, then garp was NULL because
5574 			 * the last op in the compound failed and makenfs4node
5575 			 * could not find the vnode for sfhp. It created
5576 			 * a new vnode, so we have nothing to purge here.
5577 			 */
5578 			if (nvp->v_type == VNON) {
5579 				vattr_t vattr;
5580 
5581 				vattr.va_mask = AT_TYPE;
5582 				/*
5583 				 * N.B. We've already called nfs4_end_fop above.
5584 				 */
5585 				e.error = nfs4getattr(nvp, &vattr, cr);
5586 				if (e.error) {
5587 					sfh4_rele(&sfhp);
5588 					VN_RELE(*vpp);
5589 					*vpp = NULL;
5590 					VN_RELE(nvp);
5591 					goto exit;
5592 				}
5593 				nvp->v_type = vattr.va_type;
5594 			}
5595 		}
5596 		sfh4_rele(&sfhp);
5597 
5598 		nrp = VTOR4(nvp);
5599 		mutex_enter(&nrp->r_statev4_lock);
5600 		if (!nrp->created_v4) {
5601 			mutex_exit(&nrp->r_statev4_lock);
5602 			dnlc_update(dvp, nm, nvp);
5603 		} else
5604 			mutex_exit(&nrp->r_statev4_lock);
5605 
5606 		VN_RELE(*vpp);
5607 		*vpp = nvp;
5608 	} else {
5609 		hrtime_t now;
5610 		hrtime_t delta = 0;
5611 
5612 		e.error = 0;
5613 
5614 		/*
5615 		 * Because the NVERIFY "succeeded" we know that the
5616 		 * directory attributes are still valid
5617 		 * so update r_time_attr_inval
5618 		 */
5619 		now = gethrtime();
5620 		mutex_enter(&drp->r_statelock);
5621 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5622 			delta = now - drp->r_time_attr_saved;
5623 			if (delta < mi->mi_acdirmin)
5624 				delta = mi->mi_acdirmin;
5625 			else if (delta > mi->mi_acdirmax)
5626 				delta = mi->mi_acdirmax;
5627 		}
5628 		drp->r_time_attr_inval = now + delta;
5629 		mutex_exit(&drp->r_statelock);
5630 		dnlc_update(dvp, nm, *vpp);
5631 
5632 		/*
5633 		 * Even though we have a valid directory attr cache
5634 		 * and dnlc entry, we may not have access.
5635 		 * This should almost always hit the cache.
5636 		 */
5637 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5638 		if (e.error) {
5639 			VN_RELE(*vpp);
5640 			*vpp = NULL;
5641 		}
5642 
5643 		if (*vpp == DNLC_NO_VNODE) {
5644 			VN_RELE(*vpp);
5645 			*vpp = NULL;
5646 			e.error = ENOENT;
5647 		}
5648 	}
5649 
5650 exit:
5651 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5652 	kmem_free(argop, argoplist_size);
5653 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5654 	return (e.error);
5655 }
5656 
5657 /*
5658  * We need to go over the wire to lookup the name, but
5659  * while we are there verify the directory has not
5660  * changed but if it has, get new attributes and check access
5661  *
5662  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5663  *					NVERIFY GETATTR ACCESS
5664  *
5665  * With the results:
5666  *	if the NVERIFY failed we must purge the caches, add new attributes,
5667  *		and cache new access.
5668  *	set a new r_time_attr_inval
5669  *	add name to dnlc, possibly negative
5670  *	if LOOKUP succeeded
5671  *		cache new attributes
5672  */
5673 static int
5674 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5675 {
5676 	COMPOUND4args_clnt args;
5677 	COMPOUND4res_clnt res;
5678 	fattr4 *ver_fattr;
5679 	fattr4_change dchange;
5680 	int32_t *ptr;
5681 	nfs4_ga_res_t *garp = NULL;
5682 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5683 	nfs_argop4 *argop;
5684 	int doqueue;
5685 	mntinfo4_t *mi;
5686 	nfs4_recov_state_t recov_state;
5687 	hrtime_t t;
5688 	int isdotdot;
5689 	vnode_t *nvp;
5690 	nfs_fh4 *fhp;
5691 	nfs4_sharedfh_t *sfhp;
5692 	nfs4_access_type_t cacc;
5693 	rnode4_t *nrp;
5694 	rnode4_t *drp = VTOR4(dvp);
5695 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5696 
5697 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5698 	ASSERT(nm != NULL);
5699 	ASSERT(nm[0] != '\0');
5700 	ASSERT(dvp->v_type == VDIR);
5701 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5702 	ASSERT(*vpp == NULL);
5703 
5704 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5705 		isdotdot = 1;
5706 		args.ctag = TAG_LOOKUP_PARENT;
5707 	} else {
5708 		/*
5709 		 * If dvp were a stub, it should have triggered and caused
5710 		 * a mount for us to get this far.
5711 		 */
5712 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5713 
5714 		isdotdot = 0;
5715 		args.ctag = TAG_LOOKUP;
5716 	}
5717 
5718 	mi = VTOMI4(dvp);
5719 	recov_state.rs_flags = 0;
5720 	recov_state.rs_num_retry_despite_err = 0;
5721 
5722 	nvp = NULL;
5723 
5724 	/* Save the original mount point security information */
5725 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5726 
5727 recov_retry:
5728 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5729 	    &recov_state, NULL);
5730 	if (e.error) {
5731 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5732 		return (e.error);
5733 	}
5734 
5735 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5736 
5737 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5738 	args.array_len = 9;
5739 	args.array = argop;
5740 
5741 	/* 0. putfh file */
5742 	argop[0].argop = OP_CPUTFH;
5743 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5744 
5745 	/* 1. savefh for the nverify */
5746 	argop[1].argop = OP_SAVEFH;
5747 
5748 	/* 2. lookup name */
5749 	if (isdotdot) {
5750 		argop[2].argop = OP_LOOKUPP;
5751 	} else {
5752 		argop[2].argop = OP_CLOOKUP;
5753 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5754 	}
5755 
5756 	/* 3. resulting file handle */
5757 	argop[3].argop = OP_GETFH;
5758 
5759 	/* 4. resulting file attributes */
5760 	argop[4].argop = OP_GETATTR;
5761 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5762 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5763 
5764 	/* 5. restorefh back the directory for the nverify */
5765 	argop[5].argop = OP_RESTOREFH;
5766 
5767 	/* 6. nverify the change info */
5768 	argop[6].argop = OP_NVERIFY;
5769 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5770 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5771 	ver_fattr->attrlist4 = (char *)&dchange;
5772 	ptr = (int32_t *)&dchange;
5773 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5774 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5775 
5776 	/* 7. getattr directory */
5777 	argop[7].argop = OP_GETATTR;
5778 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5779 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5780 
5781 	/* 8. access directory */
5782 	argop[8].argop = OP_ACCESS;
5783 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5784 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5785 
5786 	doqueue = 1;
5787 	t = gethrtime();
5788 
5789 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5790 
5791 	if (!isdotdot && res.status == NFS4ERR_MOVED) {
5792 		e.error = nfs4_setup_referral(dvp, nm, vpp, cr);
5793 		if (e.error != 0 && *vpp != NULL)
5794 			VN_RELE(*vpp);
5795 		nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5796 		    &recov_state, FALSE);
5797 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5798 		kmem_free(argop, argoplist_size);
5799 		return (e.error);
5800 	}
5801 
5802 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5803 		/*
5804 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5805 		 * from this thread, do not go thru the recovery thread since
5806 		 * we need the nm information.
5807 		 *
5808 		 * Not doing dotdot case because there is no specification
5809 		 * for (PUTFH, SECINFO "..") yet.
5810 		 */
5811 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5812 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5813 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5814 				    &recov_state, FALSE);
5815 			else
5816 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5817 				    &recov_state, TRUE);
5818 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5819 			kmem_free(argop, argoplist_size);
5820 			if (!e.error)
5821 				goto recov_retry;
5822 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5823 			return (e.error);
5824 		}
5825 
5826 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5827 		    OP_LOOKUP, NULL, NULL, NULL) == FALSE) {
5828 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5829 			    &recov_state, TRUE);
5830 
5831 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5832 			kmem_free(argop, argoplist_size);
5833 			goto recov_retry;
5834 		}
5835 	}
5836 
5837 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5838 
5839 	if (e.error || res.array_len == 0) {
5840 		/*
5841 		 * If e.error isn't set, then reply has no ops (or we couldn't
5842 		 * be here).  The only legal way to reply without an op array
5843 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5844 		 * be in the reply for all other status values.
5845 		 *
5846 		 * For valid replies without an ops array, return ENOTSUP
5847 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5848 		 * return EIO -- don't trust status.
5849 		 */
5850 		if (e.error == 0)
5851 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5852 			    ENOTSUP : EIO;
5853 
5854 		kmem_free(argop, argoplist_size);
5855 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5856 		return (e.error);
5857 	}
5858 
5859 	e.error = geterrno4(res.status);
5860 
5861 	/*
5862 	 * The PUTFH and SAVEFH may have failed.
5863 	 */
5864 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5865 	    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5866 		nfs4_purge_stale_fh(e.error, dvp, cr);
5867 		goto exit;
5868 	}
5869 
5870 	/*
5871 	 * Check if the file exists, if it does delay entering
5872 	 * into the dnlc until after we update the directory
5873 	 * attributes so we don't cause it to get purged immediately.
5874 	 */
5875 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5876 		/*
5877 		 * The lookup failed, probably no entry
5878 		 */
5879 		if (e.error == ENOENT && nfs4_lookup_neg_cache)
5880 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5881 		goto exit;
5882 	}
5883 
5884 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5885 		/*
5886 		 * The file exists but we can't get its fh for
5887 		 * some unknown reason. Error out to be safe.
5888 		 */
5889 		goto exit;
5890 	}
5891 
5892 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5893 	if (fhp->nfs_fh4_len == 0) {
5894 		/*
5895 		 * The file exists but a bogus fh
5896 		 * some unknown reason.  Error out to be safe.
5897 		 */
5898 		e.error = EIO;
5899 		goto exit;
5900 	}
5901 	sfhp = sfh4_get(fhp, mi);
5902 
5903 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5904 		sfh4_rele(&sfhp);
5905 		goto exit;
5906 	}
5907 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5908 
5909 	/*
5910 	 * The RESTOREFH may have failed
5911 	 */
5912 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5913 		sfh4_rele(&sfhp);
5914 		e.error = EIO;
5915 		goto exit;
5916 	}
5917 
5918 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5919 		/*
5920 		 * First make sure the NVERIFY failed as we expected,
5921 		 * if it didn't then be conservative and error out
5922 		 * as we can't trust the directory.
5923 		 */
5924 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5925 			sfh4_rele(&sfhp);
5926 			e.error = EIO;
5927 			goto exit;
5928 		}
5929 
5930 		/*
5931 		 * We know the NVERIFY "failed" so the directory has changed,
5932 		 * so we must:
5933 		 *	purge the caches (access and indirectly dnlc if needed)
5934 		 */
5935 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5936 
5937 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5938 			sfh4_rele(&sfhp);
5939 			goto exit;
5940 		}
5941 		nfs4_attr_cache(dvp,
5942 		    &res.array[7].nfs_resop4_u.opgetattr.ga_res,
5943 		    t, cr, FALSE, NULL);
5944 
5945 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5946 			nfs4_purge_stale_fh(e.error, dvp, cr);
5947 			sfh4_rele(&sfhp);
5948 			e.error = geterrno4(res.status);
5949 			goto exit;
5950 		}
5951 
5952 		/*
5953 		 * Now we know the directory is valid,
5954 		 * cache new directory access
5955 		 */
5956 		nfs4_access_cache(drp,
5957 		    args.array[8].nfs_argop4_u.opaccess.access,
5958 		    res.array[8].nfs_resop4_u.opaccess.access, cr);
5959 
5960 		/*
5961 		 * recheck VEXEC access
5962 		 */
5963 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5964 		if (cacc != NFS4_ACCESS_ALLOWED) {
5965 			/*
5966 			 * Directory permissions might have been revoked
5967 			 */
5968 			if (cacc == NFS4_ACCESS_DENIED) {
5969 				sfh4_rele(&sfhp);
5970 				e.error = EACCES;
5971 				goto exit;
5972 			}
5973 
5974 			/*
5975 			 * Somehow we must not have asked for enough
5976 			 * so try a singleton ACCESS should never happen
5977 			 */
5978 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5979 			if (e.error) {
5980 				sfh4_rele(&sfhp);
5981 				goto exit;
5982 			}
5983 		}
5984 
5985 		e.error = geterrno4(res.status);
5986 	} else {
5987 		hrtime_t now;
5988 		hrtime_t delta = 0;
5989 
5990 		e.error = 0;
5991 
5992 		/*
5993 		 * Because the NVERIFY "succeeded" we know that the
5994 		 * directory attributes are still valid
5995 		 * so update r_time_attr_inval
5996 		 */
5997 		now = gethrtime();
5998 		mutex_enter(&drp->r_statelock);
5999 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
6000 			delta = now - drp->r_time_attr_saved;
6001 			if (delta < mi->mi_acdirmin)
6002 				delta = mi->mi_acdirmin;
6003 			else if (delta > mi->mi_acdirmax)
6004 				delta = mi->mi_acdirmax;
6005 		}
6006 		drp->r_time_attr_inval = now + delta;
6007 		mutex_exit(&drp->r_statelock);
6008 
6009 		/*
6010 		 * Even though we have a valid directory attr cache,
6011 		 * we may not have access.
6012 		 * This should almost always hit the cache.
6013 		 */
6014 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
6015 		if (e.error) {
6016 			sfh4_rele(&sfhp);
6017 			goto exit;
6018 		}
6019 	}
6020 
6021 	/*
6022 	 * Now we have successfully completed the lookup, if the
6023 	 * directory has changed we now have the valid attributes.
6024 	 * We also know we have directory access.
6025 	 * Create the new rnode and insert it in the dnlc.
6026 	 */
6027 	if (isdotdot) {
6028 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
6029 		if (e.error) {
6030 			sfh4_rele(&sfhp);
6031 			goto exit;
6032 		}
6033 		/*
6034 		 * XXX if nfs4_make_dotdot uses an existing rnode
6035 		 * XXX it doesn't update the attributes.
6036 		 * XXX for now just save them again to save an OTW
6037 		 */
6038 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
6039 	} else {
6040 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
6041 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
6042 	}
6043 	sfh4_rele(&sfhp);
6044 
6045 	nrp = VTOR4(nvp);
6046 	mutex_enter(&nrp->r_statev4_lock);
6047 	if (!nrp->created_v4) {
6048 		mutex_exit(&nrp->r_statev4_lock);
6049 		dnlc_update(dvp, nm, nvp);
6050 	} else
6051 		mutex_exit(&nrp->r_statev4_lock);
6052 
6053 	*vpp = nvp;
6054 
6055 exit:
6056 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6057 	kmem_free(argop, argoplist_size);
6058 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
6059 	return (e.error);
6060 }
6061 
6062 #ifdef DEBUG
6063 void
6064 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
6065 {
6066 	uint_t i, len;
6067 	zoneid_t zoneid = getzoneid();
6068 	char *s;
6069 
6070 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
6071 	for (i = 0; i < argcnt; i++) {
6072 		nfs_argop4 *op = &argbase[i];
6073 		switch (op->argop) {
6074 		case OP_CPUTFH:
6075 		case OP_PUTFH:
6076 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
6077 			break;
6078 		case OP_PUTROOTFH:
6079 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
6080 			break;
6081 		case OP_CLOOKUP:
6082 			s = op->nfs_argop4_u.opclookup.cname;
6083 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6084 			break;
6085 		case OP_LOOKUP:
6086 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
6087 			    &len, NULL);
6088 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6089 			kmem_free(s, len);
6090 			break;
6091 		case OP_LOOKUPP:
6092 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
6093 			break;
6094 		case OP_GETFH:
6095 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
6096 			break;
6097 		case OP_GETATTR:
6098 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
6099 			break;
6100 		case OP_OPENATTR:
6101 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
6102 			break;
6103 		default:
6104 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
6105 			    op->argop);
6106 			break;
6107 		}
6108 	}
6109 }
6110 #endif
6111 
6112 /*
6113  * nfs4lookup_setup - constructs a multi-lookup compound request.
6114  *
6115  * Given the path "nm1/nm2/.../nmn", the following compound requests
6116  * may be created:
6117  *
6118  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
6119  * is faster, for now.
6120  *
6121  * l4_getattrs indicates the type of compound requested.
6122  *
6123  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
6124  *
6125  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
6126  *
6127  *   total number of ops is n + 1.
6128  *
6129  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
6130  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
6131  *      before the last component, and only get attributes
6132  *      for the last component.  Note that the second-to-last
6133  *	pathname component is XATTR_RPATH, which does NOT go
6134  *	over-the-wire as a lookup.
6135  *
6136  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
6137  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
6138  *
6139  *   and total number of ops is n + 5.
6140  *
6141  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
6142  *      attribute directory: create lookups plus an OPENATTR
6143  *	replacing the last lookup.  Note that the last pathname
6144  *	component is XATTR_RPATH, which does NOT go over-the-wire
6145  *	as a lookup.
6146  *
6147  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
6148  *		Openattr; Getfh; Getattr }
6149  *
6150  *   and total number of ops is n + 5.
6151  *
6152  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6153  *	nodes too.
6154  *
6155  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6156  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6157  *
6158  *   and total number of ops is 3*n + 1.
6159  *
6160  * All cases: returns the index in the arg array of the final LOOKUP op, or
6161  * -1 if no LOOKUPs were used.
6162  */
6163 int
6164 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6165 {
6166 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6167 	nfs_argop4 *argbase, *argop;
6168 	int arglen, argcnt;
6169 	int n = 1;	/* number of components */
6170 	int nga = 1;	/* number of Getattr's in request */
6171 	char c = '\0', *s, *p;
6172 	int lookup_idx = -1;
6173 	int argoplist_size;
6174 
6175 	/* set lookuparg response result to 0 */
6176 	lookupargp->resp->status = NFS4_OK;
6177 
6178 	/* skip leading "/" or "." e.g. ".//./" if there is */
6179 	for (; ; nm++) {
6180 		if (*nm != '/' && *nm != '.')
6181 			break;
6182 
6183 		/* ".." is counted as 1 component */
6184 		if (*nm == '.' && *(nm + 1) != '/')
6185 			break;
6186 	}
6187 
6188 	/*
6189 	 * Find n = number of components - nm must be null terminated
6190 	 * Skip "." components.
6191 	 */
6192 	if (*nm != '\0')
6193 		for (n = 1, s = nm; *s != '\0'; s++) {
6194 			if ((*s == '/') && (*(s + 1) != '/') &&
6195 			    (*(s + 1) != '\0') &&
6196 			    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6197 			    *(s + 2) == '\0')))
6198 				n++;
6199 		}
6200 	else
6201 		n = 0;
6202 
6203 	/*
6204 	 * nga is number of components that need Getfh+Getattr
6205 	 */
6206 	switch (l4_getattrs) {
6207 	case LKP4_NO_ATTRIBUTES:
6208 		nga = 0;
6209 		break;
6210 	case LKP4_ALL_ATTRIBUTES:
6211 		nga = n;
6212 		/*
6213 		 * Always have at least 1 getfh, getattr pair
6214 		 */
6215 		if (nga == 0)
6216 			nga++;
6217 		break;
6218 	case LKP4_LAST_ATTRDIR:
6219 	case LKP4_LAST_NAMED_ATTR:
6220 		nga = n+1;
6221 		break;
6222 	}
6223 
6224 	/*
6225 	 * If change to use the filehandle attr instead of getfh
6226 	 * the following line can be deleted.
6227 	 */
6228 	nga *= 2;
6229 
6230 	/*
6231 	 * calculate number of ops in request as
6232 	 * header + trailer + lookups + getattrs
6233 	 */
6234 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6235 
6236 	argoplist_size = arglen * sizeof (nfs_argop4);
6237 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6238 	lookupargp->argsp->array = argop;
6239 
6240 	argcnt = lookupargp->header_len;
6241 	argop += argcnt;
6242 
6243 	/*
6244 	 * loop and create a lookup op and possibly getattr/getfh for
6245 	 * each component. Skip "." components.
6246 	 */
6247 	for (s = nm; *s != '\0'; s = p) {
6248 		/*
6249 		 * Set up a pathname struct for each component if needed
6250 		 */
6251 		while (*s == '/')
6252 			s++;
6253 		if (*s == '\0')
6254 			break;
6255 
6256 		for (p = s; (*p != '/') && (*p != '\0'); p++)
6257 			;
6258 		c = *p;
6259 		*p = '\0';
6260 
6261 		if (s[0] == '.' && s[1] == '\0') {
6262 			*p = c;
6263 			continue;
6264 		}
6265 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6266 		    strcmp(s, XATTR_RPATH) == 0) {
6267 			/* getfh XXX may not be needed in future */
6268 			argop->argop = OP_GETFH;
6269 			argop++;
6270 			argcnt++;
6271 
6272 			/* getattr */
6273 			argop->argop = OP_GETATTR;
6274 			argop->nfs_argop4_u.opgetattr.attr_request =
6275 			    lookupargp->ga_bits;
6276 			argop->nfs_argop4_u.opgetattr.mi =
6277 			    lookupargp->mi;
6278 			argop++;
6279 			argcnt++;
6280 
6281 			/* openattr */
6282 			argop->argop = OP_OPENATTR;
6283 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6284 		    strcmp(s, XATTR_RPATH) == 0) {
6285 			/* openattr */
6286 			argop->argop = OP_OPENATTR;
6287 			argop++;
6288 			argcnt++;
6289 
6290 			/* getfh XXX may not be needed in future */
6291 			argop->argop = OP_GETFH;
6292 			argop++;
6293 			argcnt++;
6294 
6295 			/* getattr */
6296 			argop->argop = OP_GETATTR;
6297 			argop->nfs_argop4_u.opgetattr.attr_request =
6298 			    lookupargp->ga_bits;
6299 			argop->nfs_argop4_u.opgetattr.mi =
6300 			    lookupargp->mi;
6301 			argop++;
6302 			argcnt++;
6303 			*p = c;
6304 			continue;
6305 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6306 			/* lookupp */
6307 			argop->argop = OP_LOOKUPP;
6308 		} else {
6309 			/* lookup */
6310 			argop->argop = OP_LOOKUP;
6311 			(void) str_to_utf8(s,
6312 			    &argop->nfs_argop4_u.oplookup.objname);
6313 		}
6314 		lookup_idx = argcnt;
6315 		argop++;
6316 		argcnt++;
6317 
6318 		*p = c;
6319 
6320 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6321 			/* getfh XXX may not be needed in future */
6322 			argop->argop = OP_GETFH;
6323 			argop++;
6324 			argcnt++;
6325 
6326 			/* getattr */
6327 			argop->argop = OP_GETATTR;
6328 			argop->nfs_argop4_u.opgetattr.attr_request =
6329 			    lookupargp->ga_bits;
6330 			argop->nfs_argop4_u.opgetattr.mi =
6331 			    lookupargp->mi;
6332 			argop++;
6333 			argcnt++;
6334 		}
6335 	}
6336 
6337 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6338 	    ((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6339 		if (needgetfh) {
6340 			/* stick in a post-lookup getfh */
6341 			argop->argop = OP_GETFH;
6342 			argcnt++;
6343 			argop++;
6344 		}
6345 		/* post-lookup getattr */
6346 		argop->argop = OP_GETATTR;
6347 		argop->nfs_argop4_u.opgetattr.attr_request =
6348 		    lookupargp->ga_bits;
6349 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6350 		argcnt++;
6351 	}
6352 	argcnt += lookupargp->trailer_len;	/* actual op count */
6353 	lookupargp->argsp->array_len = argcnt;
6354 	lookupargp->arglen = arglen;
6355 
6356 #ifdef DEBUG
6357 	if (nfs4_client_lookup_debug)
6358 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6359 #endif
6360 
6361 	return (lookup_idx);
6362 }
6363 
6364 static int
6365 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6366 {
6367 	COMPOUND4args_clnt	args;
6368 	COMPOUND4res_clnt	res;
6369 	GETFH4res	*gf_res = NULL;
6370 	nfs_argop4	argop[4];
6371 	nfs_resop4	*resop = NULL;
6372 	nfs4_sharedfh_t *sfhp;
6373 	hrtime_t t;
6374 	nfs4_error_t	e;
6375 
6376 	rnode4_t	*drp;
6377 	int		doqueue = 1;
6378 	vnode_t		*vp;
6379 	int		needrecov = 0;
6380 	nfs4_recov_state_t recov_state;
6381 
6382 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6383 
6384 	*avp = NULL;
6385 	recov_state.rs_flags = 0;
6386 	recov_state.rs_num_retry_despite_err = 0;
6387 
6388 recov_retry:
6389 	/* COMPOUND: putfh, openattr, getfh, getattr */
6390 	args.array_len = 4;
6391 	args.array = argop;
6392 	args.ctag = TAG_OPENATTR;
6393 
6394 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6395 	if (e.error)
6396 		return (e.error);
6397 
6398 	drp = VTOR4(dvp);
6399 
6400 	/* putfh */
6401 	argop[0].argop = OP_CPUTFH;
6402 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6403 
6404 	/* openattr */
6405 	argop[1].argop = OP_OPENATTR;
6406 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6407 
6408 	/* getfh */
6409 	argop[2].argop = OP_GETFH;
6410 
6411 	/* getattr */
6412 	argop[3].argop = OP_GETATTR;
6413 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6414 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6415 
6416 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6417 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6418 	    rnode4info(drp)));
6419 
6420 	t = gethrtime();
6421 
6422 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6423 
6424 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6425 	if (needrecov) {
6426 		bool_t abort;
6427 
6428 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6429 		    "nfs4openattr: initiating recovery\n"));
6430 
6431 		abort = nfs4_start_recovery(&e,
6432 		    VTOMI4(dvp), dvp, NULL, NULL, NULL,
6433 		    OP_OPENATTR, NULL, NULL, NULL);
6434 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6435 		if (!e.error) {
6436 			e.error = geterrno4(res.status);
6437 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6438 		}
6439 		if (abort == FALSE)
6440 			goto recov_retry;
6441 		return (e.error);
6442 	}
6443 
6444 	if (e.error) {
6445 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6446 		return (e.error);
6447 	}
6448 
6449 	if (res.status) {
6450 		/*
6451 		 * If OTW errro is NOTSUPP, then it should be
6452 		 * translated to EINVAL.  All Solaris file system
6453 		 * implementations return EINVAL to the syscall layer
6454 		 * when the attrdir cannot be created due to an
6455 		 * implementation restriction or noxattr mount option.
6456 		 */
6457 		if (res.status == NFS4ERR_NOTSUPP) {
6458 			mutex_enter(&drp->r_statelock);
6459 			if (drp->r_xattr_dir)
6460 				VN_RELE(drp->r_xattr_dir);
6461 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6462 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6463 			mutex_exit(&drp->r_statelock);
6464 
6465 			e.error = EINVAL;
6466 		} else {
6467 			e.error = geterrno4(res.status);
6468 		}
6469 
6470 		if (e.error) {
6471 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6472 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6473 			    needrecov);
6474 			return (e.error);
6475 		}
6476 	}
6477 
6478 	resop = &res.array[0];  /* putfh res */
6479 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6480 
6481 	resop = &res.array[1];  /* openattr res */
6482 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6483 
6484 	resop = &res.array[2];  /* getfh res */
6485 	gf_res = &resop->nfs_resop4_u.opgetfh;
6486 	if (gf_res->object.nfs_fh4_len == 0) {
6487 		*avp = NULL;
6488 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6489 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6490 		return (ENOENT);
6491 	}
6492 
6493 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6494 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6495 	    dvp->v_vfsp, t, cr, dvp,
6496 	    fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH, sfhp));
6497 	sfh4_rele(&sfhp);
6498 
6499 	if (e.error)
6500 		PURGE_ATTRCACHE4(vp);
6501 
6502 	mutex_enter(&vp->v_lock);
6503 	vp->v_flag |= V_XATTRDIR;
6504 	mutex_exit(&vp->v_lock);
6505 
6506 	*avp = vp;
6507 
6508 	mutex_enter(&drp->r_statelock);
6509 	if (drp->r_xattr_dir)
6510 		VN_RELE(drp->r_xattr_dir);
6511 	VN_HOLD(vp);
6512 	drp->r_xattr_dir = vp;
6513 
6514 	/*
6515 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6516 	 * NULL.  xattrs could be created at any time, and we have no
6517 	 * way to update pc4_xattr_exists in the base object if/when
6518 	 * it happens.
6519 	 */
6520 	drp->r_pathconf.pc4_xattr_valid = 0;
6521 
6522 	mutex_exit(&drp->r_statelock);
6523 
6524 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6525 
6526 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6527 
6528 	return (0);
6529 }
6530 
6531 /* ARGSUSED */
6532 static int
6533 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6534     int mode, vnode_t **vpp, cred_t *cr, int flags, caller_context_t *ct,
6535     vsecattr_t *vsecp)
6536 {
6537 	int error;
6538 	vnode_t *vp = NULL;
6539 	rnode4_t *rp;
6540 	struct vattr vattr;
6541 	rnode4_t *drp;
6542 	vnode_t *tempvp;
6543 	enum createmode4 createmode;
6544 	bool_t must_trunc = FALSE;
6545 	int	truncating = 0;
6546 
6547 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6548 		return (EPERM);
6549 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6550 		return (EINVAL);
6551 	}
6552 
6553 	/* . and .. have special meaning in the protocol, reject them. */
6554 
6555 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6556 		return (EISDIR);
6557 
6558 	drp = VTOR4(dvp);
6559 
6560 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6561 		return (EINTR);
6562 
6563 top:
6564 	/*
6565 	 * We make a copy of the attributes because the caller does not
6566 	 * expect us to change what va points to.
6567 	 */
6568 	vattr = *va;
6569 
6570 	/*
6571 	 * If the pathname is "", then dvp is the root vnode of
6572 	 * a remote file mounted over a local directory.
6573 	 * All that needs to be done is access
6574 	 * checking and truncation.  Note that we avoid doing
6575 	 * open w/ create because the parent directory might
6576 	 * be in pseudo-fs and the open would fail.
6577 	 */
6578 	if (*nm == '\0') {
6579 		error = 0;
6580 		VN_HOLD(dvp);
6581 		vp = dvp;
6582 		must_trunc = TRUE;
6583 	} else {
6584 		/*
6585 		 * We need to go over the wire, just to be sure whether the
6586 		 * file exists or not.  Using the DNLC can be dangerous in
6587 		 * this case when making a decision regarding existence.
6588 		 */
6589 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6590 	}
6591 
6592 	if (exclusive)
6593 		createmode = EXCLUSIVE4;
6594 	else
6595 		createmode = GUARDED4;
6596 
6597 	/*
6598 	 * error would be set if the file does not exist on the
6599 	 * server, so lets go create it.
6600 	 */
6601 	if (error) {
6602 		goto create_otw;
6603 	}
6604 
6605 	/*
6606 	 * File does exist on the server
6607 	 */
6608 	if (exclusive == EXCL)
6609 		error = EEXIST;
6610 	else if (vp->v_type == VDIR && (mode & VWRITE))
6611 		error = EISDIR;
6612 	else {
6613 		/*
6614 		 * If vnode is a device, create special vnode.
6615 		 */
6616 		if (ISVDEV(vp->v_type)) {
6617 			tempvp = vp;
6618 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6619 			VN_RELE(tempvp);
6620 		}
6621 		if (!(error = VOP_ACCESS(vp, mode, 0, cr, ct))) {
6622 			if ((vattr.va_mask & AT_SIZE) &&
6623 			    vp->v_type == VREG) {
6624 				rp = VTOR4(vp);
6625 				/*
6626 				 * Check here for large file handled
6627 				 * by LF-unaware process (as
6628 				 * ufs_create() does)
6629 				 */
6630 				if (!(flags & FOFFMAX)) {
6631 					mutex_enter(&rp->r_statelock);
6632 					if (rp->r_size > MAXOFF32_T)
6633 						error = EOVERFLOW;
6634 					mutex_exit(&rp->r_statelock);
6635 				}
6636 
6637 				/* if error is set then we need to return */
6638 				if (error) {
6639 					nfs_rw_exit(&drp->r_rwlock);
6640 					VN_RELE(vp);
6641 					return (error);
6642 				}
6643 
6644 				if (must_trunc) {
6645 					vattr.va_mask = AT_SIZE;
6646 					error = nfs4setattr(vp, &vattr, 0, cr,
6647 					    NULL);
6648 				} else {
6649 				/*
6650 				 * we know we have a regular file that already
6651 				 * exists and we may end up truncating the file
6652 				 * as a result of the open_otw, so flush out
6653 				 * any dirty pages for this file first.
6654 				 */
6655 					if (nfs4_has_pages(vp) &&
6656 					    ((rp->r_flags & R4DIRTY) ||
6657 					    rp->r_count > 0 ||
6658 					    rp->r_mapcnt > 0)) {
6659 						error = nfs4_putpage(vp,
6660 						    (offset_t)0, 0, 0, cr, ct);
6661 						if (error && (error == ENOSPC ||
6662 						    error == EDQUOT)) {
6663 							mutex_enter(
6664 							    &rp->r_statelock);
6665 							if (!rp->r_error)
6666 								rp->r_error =
6667 								    error;
6668 							mutex_exit(
6669 							    &rp->r_statelock);
6670 						}
6671 					}
6672 					vattr.va_mask = (AT_SIZE |
6673 					    AT_TYPE | AT_MODE);
6674 					vattr.va_type = VREG;
6675 					createmode = UNCHECKED4;
6676 					truncating = 1;
6677 					goto create_otw;
6678 				}
6679 			}
6680 		}
6681 	}
6682 	nfs_rw_exit(&drp->r_rwlock);
6683 	if (error) {
6684 		VN_RELE(vp);
6685 	} else {
6686 		vnode_t *tvp;
6687 		rnode4_t *trp;
6688 		tvp = vp;
6689 		if (vp->v_type == VREG) {
6690 			trp = VTOR4(vp);
6691 			if (IS_SHADOW(vp, trp))
6692 				tvp = RTOV4(trp);
6693 		}
6694 
6695 		if (must_trunc) {
6696 			/*
6697 			 * existing file got truncated, notify.
6698 			 */
6699 			vnevent_create(tvp, ct);
6700 		}
6701 
6702 		*vpp = vp;
6703 	}
6704 	return (error);
6705 
6706 create_otw:
6707 	dnlc_remove(dvp, nm);
6708 
6709 	ASSERT(vattr.va_mask & AT_TYPE);
6710 
6711 	/*
6712 	 * If not a regular file let nfs4mknod() handle it.
6713 	 */
6714 	if (vattr.va_type != VREG) {
6715 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6716 		nfs_rw_exit(&drp->r_rwlock);
6717 		return (error);
6718 	}
6719 
6720 	/*
6721 	 * It _is_ a regular file.
6722 	 */
6723 	ASSERT(vattr.va_mask & AT_MODE);
6724 	if (MANDMODE(vattr.va_mode)) {
6725 		nfs_rw_exit(&drp->r_rwlock);
6726 		return (EACCES);
6727 	}
6728 
6729 	/*
6730 	 * If this happens to be a mknod of a regular file, then flags will
6731 	 * have neither FREAD or FWRITE.  However, we must set at least one
6732 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6733 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6734 	 * set (based on openmode specified by app).
6735 	 */
6736 	if ((flags & (FREAD|FWRITE)) == 0)
6737 		flags |= (FREAD|FWRITE);
6738 
6739 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6740 
6741 	if (vp != NULL) {
6742 		/* if create was successful, throw away the file's pages */
6743 		if (!error && (vattr.va_mask & AT_SIZE))
6744 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6745 			    cr);
6746 		/* release the lookup hold */
6747 		VN_RELE(vp);
6748 		vp = NULL;
6749 	}
6750 
6751 	/*
6752 	 * validate that we opened a regular file. This handles a misbehaving
6753 	 * server that returns an incorrect FH.
6754 	 */
6755 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6756 		error = EISDIR;
6757 		VN_RELE(*vpp);
6758 	}
6759 
6760 	/*
6761 	 * If this is not an exclusive create, then the CREATE
6762 	 * request will be made with the GUARDED mode set.  This
6763 	 * means that the server will return EEXIST if the file
6764 	 * exists.  The file could exist because of a retransmitted
6765 	 * request.  In this case, we recover by starting over and
6766 	 * checking to see whether the file exists.  This second
6767 	 * time through it should and a CREATE request will not be
6768 	 * sent.
6769 	 *
6770 	 * This handles the problem of a dangling CREATE request
6771 	 * which contains attributes which indicate that the file
6772 	 * should be truncated.  This retransmitted request could
6773 	 * possibly truncate valid data in the file if not caught
6774 	 * by the duplicate request mechanism on the server or if
6775 	 * not caught by other means.  The scenario is:
6776 	 *
6777 	 * Client transmits CREATE request with size = 0
6778 	 * Client times out, retransmits request.
6779 	 * Response to the first request arrives from the server
6780 	 *  and the client proceeds on.
6781 	 * Client writes data to the file.
6782 	 * The server now processes retransmitted CREATE request
6783 	 *  and truncates file.
6784 	 *
6785 	 * The use of the GUARDED CREATE request prevents this from
6786 	 * happening because the retransmitted CREATE would fail
6787 	 * with EEXIST and would not truncate the file.
6788 	 */
6789 	if (error == EEXIST && exclusive == NONEXCL) {
6790 #ifdef DEBUG
6791 		nfs4_create_misses++;
6792 #endif
6793 		goto top;
6794 	}
6795 	nfs_rw_exit(&drp->r_rwlock);
6796 	if (truncating && !error && *vpp) {
6797 		vnode_t *tvp;
6798 		rnode4_t *trp;
6799 		/*
6800 		 * existing file got truncated, notify.
6801 		 */
6802 		tvp = *vpp;
6803 		trp = VTOR4(tvp);
6804 		if (IS_SHADOW(tvp, trp))
6805 			tvp = RTOV4(trp);
6806 		vnevent_create(tvp, ct);
6807 	}
6808 	return (error);
6809 }
6810 
6811 /*
6812  * Create compound (for mkdir, mknod, symlink):
6813  * { Putfh <dfh>; Create; Getfh; Getattr }
6814  * It's okay if setattr failed to set gid - this is not considered
6815  * an error, but purge attrs in that case.
6816  */
6817 static int
6818 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6819     vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6820 {
6821 	int need_end_op = FALSE;
6822 	COMPOUND4args_clnt args;
6823 	COMPOUND4res_clnt res, *resp = NULL;
6824 	nfs_argop4 *argop;
6825 	nfs_resop4 *resop;
6826 	int doqueue;
6827 	mntinfo4_t *mi;
6828 	rnode4_t *drp = VTOR4(dvp);
6829 	change_info4 *cinfo;
6830 	GETFH4res *gf_res;
6831 	struct vattr vattr;
6832 	vnode_t *vp;
6833 	fattr4 *crattr;
6834 	bool_t needrecov = FALSE;
6835 	nfs4_recov_state_t recov_state;
6836 	nfs4_sharedfh_t *sfhp = NULL;
6837 	hrtime_t t;
6838 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6839 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6840 	dirattr_info_t dinfo, *dinfop;
6841 	servinfo4_t *svp;
6842 	bitmap4 supp_attrs;
6843 
6844 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6845 	    type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6846 
6847 	mi = VTOMI4(dvp);
6848 
6849 	/*
6850 	 * Make sure we properly deal with setting the right gid
6851 	 * on a new directory to reflect the parent's setgid bit
6852 	 */
6853 	setgid_flag = 0;
6854 	if (type == NF4DIR) {
6855 		struct vattr dva;
6856 
6857 		va->va_mode &= ~VSGID;
6858 		dva.va_mask = AT_MODE | AT_GID;
6859 		if (VOP_GETATTR(dvp, &dva, 0, cr, NULL) == 0) {
6860 
6861 			/*
6862 			 * If the parent's directory has the setgid bit set
6863 			 * _and_ the client was able to get a valid mapping
6864 			 * for the parent dir's owner_group, we want to
6865 			 * append NVERIFY(owner_group == dva.va_gid) and
6866 			 * SETTATTR to the CREATE compound.
6867 			 */
6868 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6869 				setgid_flag = 1;
6870 				va->va_mode |= VSGID;
6871 				if (dva.va_gid != GID_NOBODY) {
6872 					va->va_mask |= AT_GID;
6873 					va->va_gid = dva.va_gid;
6874 				}
6875 			}
6876 		}
6877 	}
6878 
6879 	/*
6880 	 * Create ops:
6881 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6882 	 *	5:restorefh(dir) 6:getattr(dir)
6883 	 *
6884 	 * if (setgid)
6885 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6886 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6887 	 *	8:nverify 9:setattr
6888 	 */
6889 	if (setgid_flag) {
6890 		numops = 10;
6891 		idx_create = 1;
6892 		idx_fattr = 3;
6893 	} else {
6894 		numops = 7;
6895 		idx_create = 2;
6896 		idx_fattr = 4;
6897 	}
6898 
6899 	ASSERT(nfs_zone() == mi->mi_zone);
6900 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6901 		return (EINTR);
6902 	}
6903 	recov_state.rs_flags = 0;
6904 	recov_state.rs_num_retry_despite_err = 0;
6905 
6906 	argoplist_size = numops * sizeof (nfs_argop4);
6907 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6908 
6909 recov_retry:
6910 	if (type == NF4LNK)
6911 		args.ctag = TAG_SYMLINK;
6912 	else if (type == NF4DIR)
6913 		args.ctag = TAG_MKDIR;
6914 	else
6915 		args.ctag = TAG_MKNOD;
6916 
6917 	args.array_len = numops;
6918 	args.array = argop;
6919 
6920 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6921 		nfs_rw_exit(&drp->r_rwlock);
6922 		kmem_free(argop, argoplist_size);
6923 		return (e.error);
6924 	}
6925 	need_end_op = TRUE;
6926 
6927 
6928 	/* 0: putfh directory */
6929 	argop[0].argop = OP_CPUTFH;
6930 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6931 
6932 	/* 1/2: Create object */
6933 	argop[idx_create].argop = OP_CCREATE;
6934 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6935 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6936 	if (type == NF4LNK) {
6937 		/*
6938 		 * symlink, treat name as data
6939 		 */
6940 		ASSERT(data != NULL);
6941 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6942 		    (char *)data;
6943 	}
6944 	if (type == NF4BLK || type == NF4CHR) {
6945 		ASSERT(data != NULL);
6946 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6947 		    *((specdata4 *)data);
6948 	}
6949 
6950 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6951 
6952 	svp = drp->r_server;
6953 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6954 	supp_attrs = svp->sv_supp_attrs;
6955 	nfs_rw_exit(&svp->sv_lock);
6956 
6957 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6958 		nfs_rw_exit(&drp->r_rwlock);
6959 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6960 		e.error = EINVAL;
6961 		kmem_free(argop, argoplist_size);
6962 		return (e.error);
6963 	}
6964 
6965 	/* 2/3: getfh fh of created object */
6966 	ASSERT(idx_create + 1 == idx_fattr - 1);
6967 	argop[idx_create + 1].argop = OP_GETFH;
6968 
6969 	/* 3/4: getattr of new object */
6970 	argop[idx_fattr].argop = OP_GETATTR;
6971 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6972 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6973 
6974 	if (setgid_flag) {
6975 		vattr_t	_v;
6976 
6977 		argop[4].argop = OP_SAVEFH;
6978 
6979 		argop[5].argop = OP_CPUTFH;
6980 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6981 
6982 		argop[6].argop = OP_GETATTR;
6983 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6984 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6985 
6986 		argop[7].argop = OP_RESTOREFH;
6987 
6988 		/*
6989 		 * nverify
6990 		 *
6991 		 * XXX - Revisit the last argument to nfs4_end_op()
6992 		 *	 once 5020486 is fixed.
6993 		 */
6994 		_v.va_mask = AT_GID;
6995 		_v.va_gid = va->va_gid;
6996 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6997 		    supp_attrs)) {
6998 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6999 			nfs_rw_exit(&drp->r_rwlock);
7000 			nfs4_fattr4_free(crattr);
7001 			kmem_free(argop, argoplist_size);
7002 			return (e.error);
7003 		}
7004 
7005 		/*
7006 		 * setattr
7007 		 *
7008 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
7009 		 * so no need for stateid or flags. Also we specify NULL
7010 		 * rp since we're only interested in setting owner_group
7011 		 * attributes.
7012 		 */
7013 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
7014 		    &e.error, 0);
7015 
7016 		if (e.error) {
7017 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
7018 			nfs_rw_exit(&drp->r_rwlock);
7019 			nfs4_fattr4_free(crattr);
7020 			nfs4args_verify_free(&argop[8]);
7021 			kmem_free(argop, argoplist_size);
7022 			return (e.error);
7023 		}
7024 	} else {
7025 		argop[1].argop = OP_SAVEFH;
7026 
7027 		argop[5].argop = OP_RESTOREFH;
7028 
7029 		argop[6].argop = OP_GETATTR;
7030 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7031 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
7032 	}
7033 
7034 	dnlc_remove(dvp, nm);
7035 
7036 	doqueue = 1;
7037 	t = gethrtime();
7038 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7039 
7040 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7041 	if (e.error) {
7042 		PURGE_ATTRCACHE4(dvp);
7043 		if (!needrecov)
7044 			goto out;
7045 	}
7046 
7047 	if (needrecov) {
7048 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
7049 		    OP_CREATE, NULL, NULL, NULL) == FALSE) {
7050 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7051 			    needrecov);
7052 			need_end_op = FALSE;
7053 			nfs4_fattr4_free(crattr);
7054 			if (setgid_flag) {
7055 				nfs4args_verify_free(&argop[8]);
7056 				nfs4args_setattr_free(&argop[9]);
7057 			}
7058 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
7059 			goto recov_retry;
7060 		}
7061 	}
7062 
7063 	resp = &res;
7064 
7065 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
7066 
7067 		if (res.status == NFS4ERR_BADOWNER)
7068 			nfs4_log_badowner(mi, OP_CREATE);
7069 
7070 		e.error = geterrno4(res.status);
7071 
7072 		/*
7073 		 * This check is left over from when create was implemented
7074 		 * using a setattr op (instead of createattrs).  If the
7075 		 * putfh/create/getfh failed, the error was returned.  If
7076 		 * setattr/getattr failed, we keep going.
7077 		 *
7078 		 * It might be better to get rid of the GETFH also, and just
7079 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
7080 		 * Then if any of the operations failed, we could return the
7081 		 * error now, and remove much of the error code below.
7082 		 */
7083 		if (res.array_len <= idx_fattr) {
7084 			/*
7085 			 * Either Putfh, Create or Getfh failed.
7086 			 */
7087 			PURGE_ATTRCACHE4(dvp);
7088 			/*
7089 			 * nfs4_purge_stale_fh() may generate otw calls through
7090 			 * nfs4_invalidate_pages. Hence the need to call
7091 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
7092 			 */
7093 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7094 			    needrecov);
7095 			need_end_op = FALSE;
7096 			nfs4_purge_stale_fh(e.error, dvp, cr);
7097 			goto out;
7098 		}
7099 	}
7100 
7101 	resop = &res.array[idx_create];	/* create res */
7102 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
7103 
7104 	resop = &res.array[idx_create + 1]; /* getfh res */
7105 	gf_res = &resop->nfs_resop4_u.opgetfh;
7106 
7107 	sfhp = sfh4_get(&gf_res->object, mi);
7108 	if (e.error) {
7109 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
7110 		    fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7111 		if (vp->v_type == VNON) {
7112 			vattr.va_mask = AT_TYPE;
7113 			/*
7114 			 * Need to call nfs4_end_op before nfs4getattr to avoid
7115 			 * potential nfs4_start_op deadlock. See RFE 4777612.
7116 			 */
7117 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7118 			    needrecov);
7119 			need_end_op = FALSE;
7120 			e.error = nfs4getattr(vp, &vattr, cr);
7121 			if (e.error) {
7122 				VN_RELE(vp);
7123 				*vpp = NULL;
7124 				goto out;
7125 			}
7126 			vp->v_type = vattr.va_type;
7127 		}
7128 		e.error = 0;
7129 	} else {
7130 		*vpp = vp = makenfs4node(sfhp,
7131 		    &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
7132 		    dvp->v_vfsp, t, cr,
7133 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7134 	}
7135 
7136 	/*
7137 	 * If compound succeeded, then update dir attrs
7138 	 */
7139 	if (res.status == NFS4_OK) {
7140 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
7141 		dinfo.di_cred = cr;
7142 		dinfo.di_time_call = t;
7143 		dinfop = &dinfo;
7144 	} else
7145 		dinfop = NULL;
7146 
7147 	/* Update directory cache attribute, readdir and dnlc caches */
7148 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
7149 
7150 out:
7151 	if (sfhp != NULL)
7152 		sfh4_rele(&sfhp);
7153 	nfs_rw_exit(&drp->r_rwlock);
7154 	nfs4_fattr4_free(crattr);
7155 	if (setgid_flag) {
7156 		nfs4args_verify_free(&argop[8]);
7157 		nfs4args_setattr_free(&argop[9]);
7158 	}
7159 	if (resp)
7160 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7161 	if (need_end_op)
7162 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7163 
7164 	kmem_free(argop, argoplist_size);
7165 	return (e.error);
7166 }
7167 
7168 /* ARGSUSED */
7169 static int
7170 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7171     int mode, vnode_t **vpp, cred_t *cr)
7172 {
7173 	int error;
7174 	vnode_t *vp;
7175 	nfs_ftype4 type;
7176 	specdata4 spec, *specp = NULL;
7177 
7178 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7179 
7180 	switch (va->va_type) {
7181 	case VCHR:
7182 	case VBLK:
7183 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7184 		spec.specdata1 = getmajor(va->va_rdev);
7185 		spec.specdata2 = getminor(va->va_rdev);
7186 		specp = &spec;
7187 		break;
7188 
7189 	case VFIFO:
7190 		type = NF4FIFO;
7191 		break;
7192 	case VSOCK:
7193 		type = NF4SOCK;
7194 		break;
7195 
7196 	default:
7197 		return (EINVAL);
7198 	}
7199 
7200 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7201 	if (error) {
7202 		return (error);
7203 	}
7204 
7205 	/*
7206 	 * This might not be needed any more; special case to deal
7207 	 * with problematic v2/v3 servers.  Since create was unable
7208 	 * to set group correctly, not sure what hope setattr has.
7209 	 */
7210 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7211 		va->va_mask = AT_GID;
7212 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7213 	}
7214 
7215 	/*
7216 	 * If vnode is a device create special vnode
7217 	 */
7218 	if (ISVDEV(vp->v_type)) {
7219 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7220 		VN_RELE(vp);
7221 	} else {
7222 		*vpp = vp;
7223 	}
7224 	return (error);
7225 }
7226 
7227 /*
7228  * Remove requires that the current fh be the target directory.
7229  * After the operation, the current fh is unchanged.
7230  * The compound op structure is:
7231  *      PUTFH(targetdir), REMOVE
7232  *
7233  * Weirdness: if the vnode to be removed is open
7234  * we rename it instead of removing it and nfs_inactive
7235  * will remove the new name.
7236  */
7237 /* ARGSUSED */
7238 static int
7239 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr, caller_context_t *ct, int flags)
7240 {
7241 	COMPOUND4args_clnt args;
7242 	COMPOUND4res_clnt res, *resp = NULL;
7243 	REMOVE4res *rm_res;
7244 	nfs_argop4 argop[3];
7245 	nfs_resop4 *resop;
7246 	vnode_t *vp;
7247 	char *tmpname;
7248 	int doqueue;
7249 	mntinfo4_t *mi;
7250 	rnode4_t *rp;
7251 	rnode4_t *drp;
7252 	int needrecov = 0;
7253 	nfs4_recov_state_t recov_state;
7254 	int isopen;
7255 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7256 	dirattr_info_t dinfo;
7257 
7258 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7259 		return (EPERM);
7260 	drp = VTOR4(dvp);
7261 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7262 		return (EINTR);
7263 
7264 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7265 	if (e.error) {
7266 		nfs_rw_exit(&drp->r_rwlock);
7267 		return (e.error);
7268 	}
7269 
7270 	if (vp->v_type == VDIR) {
7271 		VN_RELE(vp);
7272 		nfs_rw_exit(&drp->r_rwlock);
7273 		return (EISDIR);
7274 	}
7275 
7276 	/*
7277 	 * First just remove the entry from the name cache, as it
7278 	 * is most likely the only entry for this vp.
7279 	 */
7280 	dnlc_remove(dvp, nm);
7281 
7282 	rp = VTOR4(vp);
7283 
7284 	/*
7285 	 * For regular file types, check to see if the file is open by looking
7286 	 * at the open streams.
7287 	 * For all other types, check the reference count on the vnode.  Since
7288 	 * they are not opened OTW they never have an open stream.
7289 	 *
7290 	 * If the file is open, rename it to .nfsXXXX.
7291 	 */
7292 	if (vp->v_type != VREG) {
7293 		/*
7294 		 * If the file has a v_count > 1 then there may be more than one
7295 		 * entry in the name cache due multiple links or an open file,
7296 		 * but we don't have the real reference count so flush all
7297 		 * possible entries.
7298 		 */
7299 		if (vp->v_count > 1)
7300 			dnlc_purge_vp(vp);
7301 
7302 		/*
7303 		 * Now we have the real reference count.
7304 		 */
7305 		isopen = vp->v_count > 1;
7306 	} else {
7307 		mutex_enter(&rp->r_os_lock);
7308 		isopen = list_head(&rp->r_open_streams) != NULL;
7309 		mutex_exit(&rp->r_os_lock);
7310 	}
7311 
7312 	mutex_enter(&rp->r_statelock);
7313 	if (isopen &&
7314 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7315 		mutex_exit(&rp->r_statelock);
7316 		tmpname = newname();
7317 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr, ct);
7318 		if (e.error)
7319 			kmem_free(tmpname, MAXNAMELEN);
7320 		else {
7321 			mutex_enter(&rp->r_statelock);
7322 			if (rp->r_unldvp == NULL) {
7323 				VN_HOLD(dvp);
7324 				rp->r_unldvp = dvp;
7325 				if (rp->r_unlcred != NULL)
7326 					crfree(rp->r_unlcred);
7327 				crhold(cr);
7328 				rp->r_unlcred = cr;
7329 				rp->r_unlname = tmpname;
7330 			} else {
7331 				kmem_free(rp->r_unlname, MAXNAMELEN);
7332 				rp->r_unlname = tmpname;
7333 			}
7334 			mutex_exit(&rp->r_statelock);
7335 		}
7336 		VN_RELE(vp);
7337 		nfs_rw_exit(&drp->r_rwlock);
7338 		return (e.error);
7339 	}
7340 	/*
7341 	 * Actually remove the file/dir
7342 	 */
7343 	mutex_exit(&rp->r_statelock);
7344 
7345 	/*
7346 	 * We need to flush any dirty pages which happen to
7347 	 * be hanging around before removing the file.
7348 	 * This shouldn't happen very often since in NFSv4
7349 	 * we should be close to open consistent.
7350 	 */
7351 	if (nfs4_has_pages(vp) &&
7352 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7353 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, ct);
7354 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7355 			mutex_enter(&rp->r_statelock);
7356 			if (!rp->r_error)
7357 				rp->r_error = e.error;
7358 			mutex_exit(&rp->r_statelock);
7359 		}
7360 	}
7361 
7362 	mi = VTOMI4(dvp);
7363 
7364 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7365 	recov_state.rs_flags = 0;
7366 	recov_state.rs_num_retry_despite_err = 0;
7367 
7368 recov_retry:
7369 	/*
7370 	 * Remove ops: putfh dir; remove
7371 	 */
7372 	args.ctag = TAG_REMOVE;
7373 	args.array_len = 3;
7374 	args.array = argop;
7375 
7376 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7377 	if (e.error) {
7378 		nfs_rw_exit(&drp->r_rwlock);
7379 		VN_RELE(vp);
7380 		return (e.error);
7381 	}
7382 
7383 	/* putfh directory */
7384 	argop[0].argop = OP_CPUTFH;
7385 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7386 
7387 	/* remove */
7388 	argop[1].argop = OP_CREMOVE;
7389 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7390 
7391 	/* getattr dir */
7392 	argop[2].argop = OP_GETATTR;
7393 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7394 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7395 
7396 	doqueue = 1;
7397 	dinfo.di_time_call = gethrtime();
7398 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7399 
7400 	PURGE_ATTRCACHE4(vp);
7401 
7402 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7403 	if (e.error)
7404 		PURGE_ATTRCACHE4(dvp);
7405 
7406 	if (needrecov) {
7407 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7408 		    NULL, NULL, NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
7409 			if (!e.error)
7410 				xdr_free(xdr_COMPOUND4res_clnt, (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 		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 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
7588 			goto recov_retry;
7589 		} else {
7590 			if (e.error != 0) {
7591 				PURGE_ATTRCACHE4(tdvp);
7592 				PURGE_ATTRCACHE4(svp);
7593 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7594 				    &recov_state, needrecov);
7595 				goto out;
7596 			}
7597 			/* fall through for res.status case */
7598 		}
7599 	}
7600 
7601 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7602 
7603 	resp = &res;
7604 	if (res.status) {
7605 		/* If link succeeded, then don't return error */
7606 		e.error = geterrno4(res.status);
7607 		if (res.array_len <= 4) {
7608 			/*
7609 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7610 			 */
7611 			PURGE_ATTRCACHE4(svp);
7612 			PURGE_ATTRCACHE4(tdvp);
7613 			if (e.error == EOPNOTSUPP) {
7614 				mutex_enter(&mi->mi_lock);
7615 				mi->mi_flags &= ~MI4_LINK;
7616 				mutex_exit(&mi->mi_lock);
7617 			}
7618 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7619 			/* XXX-LP */
7620 			if (e.error == EISDIR && crgetuid(cr) != 0)
7621 				e.error = EPERM;
7622 			goto out;
7623 		}
7624 	}
7625 
7626 	/* either no error or one of the postop getattr failed */
7627 
7628 	/*
7629 	 * XXX - if LINK succeeded, but no attrs were returned for link
7630 	 * file, purge its cache.
7631 	 *
7632 	 * XXX Perform a simplified version of wcc checking. Instead of
7633 	 * have another getattr to get pre-op, just purge cache if
7634 	 * any of the ops prior to and including the getattr failed.
7635 	 * If the getattr succeeded then update the attrcache accordingly.
7636 	 */
7637 
7638 	/*
7639 	 * update cache with link file postattrs.
7640 	 * Note: at this point resop points to link res.
7641 	 */
7642 	resop = &res.array[3];	/* link res */
7643 	ln_res = &resop->nfs_resop4_u.oplink;
7644 	if (res.status == NFS4_OK)
7645 		e.error = nfs4_update_attrcache(res.status,
7646 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res,
7647 		    t, svp, cr);
7648 
7649 	/*
7650 	 * Call makenfs4node to create the new shadow vp for tnm.
7651 	 * We pass NULL attrs because we just cached attrs for
7652 	 * the src object.  All we're trying to accomplish is to
7653 	 * to create the new shadow vnode.
7654 	 */
7655 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7656 	    tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm, VTOR4(svp)->r_fh));
7657 
7658 	/* Update target cache attribute, readdir and dnlc caches */
7659 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7660 	dinfo.di_time_call = t;
7661 	dinfo.di_cred = cr;
7662 
7663 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7664 	ASSERT(nfs4_consistent_type(tdvp));
7665 	ASSERT(nfs4_consistent_type(svp));
7666 	ASSERT(nfs4_consistent_type(nvp));
7667 	VN_RELE(nvp);
7668 
7669 	if (!e.error) {
7670 		vnode_t *tvp;
7671 		rnode4_t *trp;
7672 		/*
7673 		 * Notify the source file of this link operation.
7674 		 */
7675 		trp = VTOR4(svp);
7676 		tvp = svp;
7677 		if (IS_SHADOW(svp, trp))
7678 			tvp = RTOV4(trp);
7679 		vnevent_link(tvp, ct);
7680 	}
7681 out:
7682 	kmem_free(argop, argoplist_size);
7683 	if (resp)
7684 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7685 
7686 	nfs_rw_exit(&tdrp->r_rwlock);
7687 
7688 	return (e.error);
7689 }
7690 
7691 /* ARGSUSED */
7692 static int
7693 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7694     caller_context_t *ct, int flags)
7695 {
7696 	vnode_t *realvp;
7697 
7698 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7699 		return (EPERM);
7700 	if (VOP_REALVP(ndvp, &realvp, ct) == 0)
7701 		ndvp = realvp;
7702 
7703 	return (nfs4rename(odvp, onm, ndvp, nnm, cr, ct));
7704 }
7705 
7706 /*
7707  * nfs4rename does the real work of renaming in NFS Version 4.
7708  *
7709  * A file handle is considered volatile for renaming purposes if either
7710  * of the volatile bits are turned on. However, the compound may differ
7711  * based on the likelihood of the filehandle to change during rename.
7712  */
7713 static int
7714 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7715     caller_context_t *ct)
7716 {
7717 	int error;
7718 	mntinfo4_t *mi;
7719 	vnode_t *nvp = NULL;
7720 	vnode_t *ovp = NULL;
7721 	char *tmpname = NULL;
7722 	rnode4_t *rp;
7723 	rnode4_t *odrp;
7724 	rnode4_t *ndrp;
7725 	int did_link = 0;
7726 	int do_link = 1;
7727 	nfsstat4 stat = NFS4_OK;
7728 
7729 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7730 	ASSERT(nfs4_consistent_type(odvp));
7731 	ASSERT(nfs4_consistent_type(ndvp));
7732 
7733 	if (onm[0] == '.' && (onm[1] == '\0' ||
7734 	    (onm[1] == '.' && onm[2] == '\0')))
7735 		return (EINVAL);
7736 
7737 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7738 	    (nnm[1] == '.' && nnm[2] == '\0')))
7739 		return (EINVAL);
7740 
7741 	odrp = VTOR4(odvp);
7742 	ndrp = VTOR4(ndvp);
7743 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7744 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7745 			return (EINTR);
7746 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7747 			nfs_rw_exit(&odrp->r_rwlock);
7748 			return (EINTR);
7749 		}
7750 	} else {
7751 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7752 			return (EINTR);
7753 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7754 			nfs_rw_exit(&ndrp->r_rwlock);
7755 			return (EINTR);
7756 		}
7757 	}
7758 
7759 	/*
7760 	 * Lookup the target file.  If it exists, it needs to be
7761 	 * checked to see whether it is a mount point and whether
7762 	 * it is active (open).
7763 	 */
7764 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7765 	if (!error) {
7766 		int	isactive;
7767 
7768 		ASSERT(nfs4_consistent_type(nvp));
7769 		/*
7770 		 * If this file has been mounted on, then just
7771 		 * return busy because renaming to it would remove
7772 		 * the mounted file system from the name space.
7773 		 */
7774 		if (vn_ismntpt(nvp)) {
7775 			VN_RELE(nvp);
7776 			nfs_rw_exit(&odrp->r_rwlock);
7777 			nfs_rw_exit(&ndrp->r_rwlock);
7778 			return (EBUSY);
7779 		}
7780 
7781 		/*
7782 		 * First just remove the entry from the name cache, as it
7783 		 * is most likely the only entry for this vp.
7784 		 */
7785 		dnlc_remove(ndvp, nnm);
7786 
7787 		rp = VTOR4(nvp);
7788 
7789 		if (nvp->v_type != VREG) {
7790 			/*
7791 			 * Purge the name cache of all references to this vnode
7792 			 * so that we can check the reference count to infer
7793 			 * whether it is active or not.
7794 			 */
7795 			if (nvp->v_count > 1)
7796 				dnlc_purge_vp(nvp);
7797 
7798 			isactive = nvp->v_count > 1;
7799 		} else {
7800 			mutex_enter(&rp->r_os_lock);
7801 			isactive = list_head(&rp->r_open_streams) != NULL;
7802 			mutex_exit(&rp->r_os_lock);
7803 		}
7804 
7805 		/*
7806 		 * If the vnode is active and is not a directory,
7807 		 * arrange to rename it to a
7808 		 * temporary file so that it will continue to be
7809 		 * accessible.  This implements the "unlink-open-file"
7810 		 * semantics for the target of a rename operation.
7811 		 * Before doing this though, make sure that the
7812 		 * source and target files are not already the same.
7813 		 */
7814 		if (isactive && nvp->v_type != VDIR) {
7815 			/*
7816 			 * Lookup the source name.
7817 			 */
7818 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7819 
7820 			/*
7821 			 * The source name *should* already exist.
7822 			 */
7823 			if (error) {
7824 				VN_RELE(nvp);
7825 				nfs_rw_exit(&odrp->r_rwlock);
7826 				nfs_rw_exit(&ndrp->r_rwlock);
7827 				return (error);
7828 			}
7829 
7830 			ASSERT(nfs4_consistent_type(ovp));
7831 
7832 			/*
7833 			 * Compare the two vnodes.  If they are the same,
7834 			 * just release all held vnodes and return success.
7835 			 */
7836 			if (VN_CMP(ovp, nvp)) {
7837 				VN_RELE(ovp);
7838 				VN_RELE(nvp);
7839 				nfs_rw_exit(&odrp->r_rwlock);
7840 				nfs_rw_exit(&ndrp->r_rwlock);
7841 				return (0);
7842 			}
7843 
7844 			/*
7845 			 * Can't mix and match directories and non-
7846 			 * directories in rename operations.  We already
7847 			 * know that the target is not a directory.  If
7848 			 * the source is a directory, return an error.
7849 			 */
7850 			if (ovp->v_type == VDIR) {
7851 				VN_RELE(ovp);
7852 				VN_RELE(nvp);
7853 				nfs_rw_exit(&odrp->r_rwlock);
7854 				nfs_rw_exit(&ndrp->r_rwlock);
7855 				return (ENOTDIR);
7856 			}
7857 link_call:
7858 			/*
7859 			 * The target file exists, is not the same as
7860 			 * the source file, and is active.  We first
7861 			 * try to Link it to a temporary filename to
7862 			 * avoid having the server removing the file
7863 			 * completely (which could cause data loss to
7864 			 * the user's POV in the event the Rename fails
7865 			 * -- see bug 1165874).
7866 			 */
7867 			/*
7868 			 * The do_link and did_link booleans are
7869 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7870 			 * returned for the Rename.  Some servers can
7871 			 * not Rename over an Open file, so they return
7872 			 * this error.  The client needs to Remove the
7873 			 * newly created Link and do two Renames, just
7874 			 * as if the server didn't support LINK.
7875 			 */
7876 			tmpname = newname();
7877 			error = 0;
7878 
7879 			if (do_link) {
7880 				error = nfs4_link(ndvp, nvp, tmpname, cr,
7881 				    NULL, 0);
7882 			}
7883 			if (error == EOPNOTSUPP || !do_link) {
7884 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7885 				    cr, NULL, 0);
7886 				did_link = 0;
7887 			} else {
7888 				did_link = 1;
7889 			}
7890 			if (error) {
7891 				kmem_free(tmpname, MAXNAMELEN);
7892 				VN_RELE(ovp);
7893 				VN_RELE(nvp);
7894 				nfs_rw_exit(&odrp->r_rwlock);
7895 				nfs_rw_exit(&ndrp->r_rwlock);
7896 				return (error);
7897 			}
7898 
7899 			mutex_enter(&rp->r_statelock);
7900 			if (rp->r_unldvp == NULL) {
7901 				VN_HOLD(ndvp);
7902 				rp->r_unldvp = ndvp;
7903 				if (rp->r_unlcred != NULL)
7904 					crfree(rp->r_unlcred);
7905 				crhold(cr);
7906 				rp->r_unlcred = cr;
7907 				rp->r_unlname = tmpname;
7908 			} else {
7909 				if (rp->r_unlname)
7910 					kmem_free(rp->r_unlname, MAXNAMELEN);
7911 				rp->r_unlname = tmpname;
7912 			}
7913 			mutex_exit(&rp->r_statelock);
7914 		}
7915 
7916 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7917 
7918 		ASSERT(nfs4_consistent_type(nvp));
7919 	}
7920 
7921 	if (ovp == NULL) {
7922 		/*
7923 		 * When renaming directories to be a subdirectory of a
7924 		 * different parent, the dnlc entry for ".." will no
7925 		 * longer be valid, so it must be removed.
7926 		 *
7927 		 * We do a lookup here to determine whether we are renaming
7928 		 * a directory and we need to check if we are renaming
7929 		 * an unlinked file.  This might have already been done
7930 		 * in previous code, so we check ovp == NULL to avoid
7931 		 * doing it twice.
7932 		 */
7933 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7934 		/*
7935 		 * The source name *should* already exist.
7936 		 */
7937 		if (error) {
7938 			nfs_rw_exit(&odrp->r_rwlock);
7939 			nfs_rw_exit(&ndrp->r_rwlock);
7940 			if (nvp) {
7941 				VN_RELE(nvp);
7942 			}
7943 			return (error);
7944 		}
7945 		ASSERT(ovp != NULL);
7946 		ASSERT(nfs4_consistent_type(ovp));
7947 	}
7948 
7949 	/*
7950 	 * Is the object being renamed a dir, and if so, is
7951 	 * it being renamed to a child of itself?  The underlying
7952 	 * fs should ultimately return EINVAL for this case;
7953 	 * however, buggy beta non-Solaris NFSv4 servers at
7954 	 * interop testing events have allowed this behavior,
7955 	 * and it caused our client to panic due to a recursive
7956 	 * mutex_enter in fn_move.
7957 	 *
7958 	 * The tedious locking in fn_move could be changed to
7959 	 * deal with this case, and the client could avoid the
7960 	 * panic; however, the client would just confuse itself
7961 	 * later and misbehave.  A better way to handle the broken
7962 	 * server is to detect this condition and return EINVAL
7963 	 * without ever sending the the bogus rename to the server.
7964 	 * We know the rename is invalid -- just fail it now.
7965 	 */
7966 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7967 		VN_RELE(ovp);
7968 		nfs_rw_exit(&odrp->r_rwlock);
7969 		nfs_rw_exit(&ndrp->r_rwlock);
7970 		if (nvp) {
7971 			VN_RELE(nvp);
7972 		}
7973 		return (EINVAL);
7974 	}
7975 
7976 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7977 
7978 	/*
7979 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7980 	 * possible for the filehandle to change due to the rename.
7981 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7982 	 * the fh will not change because of the rename, but we still need
7983 	 * to update its rnode entry with the new name for
7984 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7985 	 * has no effect on these for now, but for future improvements,
7986 	 * we might want to use it too to simplify handling of files
7987 	 * that are open with that flag on. (XXX)
7988 	 */
7989 	mi = VTOMI4(odvp);
7990 	if (NFS4_VOLATILE_FH(mi))
7991 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7992 		    &stat);
7993 	else
7994 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7995 		    &stat);
7996 
7997 	ASSERT(nfs4_consistent_type(odvp));
7998 	ASSERT(nfs4_consistent_type(ndvp));
7999 	ASSERT(nfs4_consistent_type(ovp));
8000 
8001 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
8002 		do_link = 0;
8003 		/*
8004 		 * Before the 'link_call' code, we did a nfs4_lookup
8005 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
8006 		 * call we call VN_RELE to match that hold.  We need
8007 		 * to place an additional VN_HOLD here since we will
8008 		 * be hitting that VN_RELE again.
8009 		 */
8010 		VN_HOLD(nvp);
8011 
8012 		(void) nfs4_remove(ndvp, tmpname, cr, NULL, 0);
8013 
8014 		/* Undo the unlinked file naming stuff we just did */
8015 		mutex_enter(&rp->r_statelock);
8016 		if (rp->r_unldvp) {
8017 			VN_RELE(ndvp);
8018 			rp->r_unldvp = NULL;
8019 			if (rp->r_unlcred != NULL)
8020 				crfree(rp->r_unlcred);
8021 			rp->r_unlcred = NULL;
8022 			/* rp->r_unlanme points to tmpname */
8023 			if (rp->r_unlname)
8024 				kmem_free(rp->r_unlname, MAXNAMELEN);
8025 			rp->r_unlname = NULL;
8026 		}
8027 		mutex_exit(&rp->r_statelock);
8028 
8029 		if (nvp) {
8030 			VN_RELE(nvp);
8031 		}
8032 		goto link_call;
8033 	}
8034 
8035 	if (error) {
8036 		VN_RELE(ovp);
8037 		nfs_rw_exit(&odrp->r_rwlock);
8038 		nfs_rw_exit(&ndrp->r_rwlock);
8039 		if (nvp) {
8040 			VN_RELE(nvp);
8041 		}
8042 		return (error);
8043 	}
8044 
8045 	/*
8046 	 * when renaming directories to be a subdirectory of a
8047 	 * different parent, the dnlc entry for ".." will no
8048 	 * longer be valid, so it must be removed
8049 	 */
8050 	rp = VTOR4(ovp);
8051 	if (ndvp != odvp) {
8052 		if (ovp->v_type == VDIR) {
8053 			dnlc_remove(ovp, "..");
8054 			if (rp->r_dir != NULL)
8055 				nfs4_purge_rddir_cache(ovp);
8056 		}
8057 	}
8058 
8059 	/*
8060 	 * If we are renaming the unlinked file, update the
8061 	 * r_unldvp and r_unlname as needed.
8062 	 */
8063 	mutex_enter(&rp->r_statelock);
8064 	if (rp->r_unldvp != NULL) {
8065 		if (strcmp(rp->r_unlname, onm) == 0) {
8066 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
8067 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
8068 			if (ndvp != rp->r_unldvp) {
8069 				VN_RELE(rp->r_unldvp);
8070 				rp->r_unldvp = ndvp;
8071 				VN_HOLD(ndvp);
8072 			}
8073 		}
8074 	}
8075 	mutex_exit(&rp->r_statelock);
8076 
8077 	/*
8078 	 * Notify the rename vnevents to source vnode, and to the target
8079 	 * vnode if it already existed.
8080 	 */
8081 	if (error == 0) {
8082 		vnode_t *tvp;
8083 		rnode4_t *trp;
8084 		/*
8085 		 * Notify the vnode. Each links is represented by
8086 		 * a different vnode, in nfsv4.
8087 		 */
8088 		if (nvp) {
8089 			trp = VTOR4(nvp);
8090 			tvp = nvp;
8091 			if (IS_SHADOW(nvp, trp))
8092 				tvp = RTOV4(trp);
8093 			vnevent_rename_dest(tvp, ndvp, nnm, ct);
8094 		}
8095 
8096 		/*
8097 		 * if the source and destination directory are not the
8098 		 * same notify the destination directory.
8099 		 */
8100 		if (VTOR4(odvp) != VTOR4(ndvp)) {
8101 			trp = VTOR4(ndvp);
8102 			tvp = ndvp;
8103 			if (IS_SHADOW(ndvp, trp))
8104 				tvp = RTOV4(trp);
8105 			vnevent_rename_dest_dir(tvp, ct);
8106 		}
8107 
8108 		trp = VTOR4(ovp);
8109 		tvp = ovp;
8110 		if (IS_SHADOW(ovp, trp))
8111 			tvp = RTOV4(trp);
8112 		vnevent_rename_src(tvp, odvp, onm, ct);
8113 	}
8114 
8115 	if (nvp) {
8116 		VN_RELE(nvp);
8117 	}
8118 	VN_RELE(ovp);
8119 
8120 	nfs_rw_exit(&odrp->r_rwlock);
8121 	nfs_rw_exit(&ndrp->r_rwlock);
8122 
8123 	return (error);
8124 }
8125 
8126 /*
8127  * When the parent directory has changed, sv_dfh must be updated
8128  */
8129 static void
8130 update_parentdir_sfh(vnode_t *vp, vnode_t *ndvp)
8131 {
8132 	svnode_t *sv = VTOSV(vp);
8133 	nfs4_sharedfh_t *old_dfh = sv->sv_dfh;
8134 	nfs4_sharedfh_t *new_dfh = VTOR4(ndvp)->r_fh;
8135 
8136 	sfh4_hold(new_dfh);
8137 	sv->sv_dfh = new_dfh;
8138 	sfh4_rele(&old_dfh);
8139 }
8140 
8141 /*
8142  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
8143  * when it is known that the filehandle is persistent through rename.
8144  *
8145  * Rename requires that the current fh be the target directory and the
8146  * saved fh be the source directory. After the operation, the current fh
8147  * is unchanged.
8148  * The compound op structure for persistent fh rename is:
8149  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
8150  * Rather than bother with the directory postop args, we'll simply
8151  * update that a change occurred in the cache, so no post-op getattrs.
8152  */
8153 static int
8154 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
8155     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8156 {
8157 	COMPOUND4args_clnt args;
8158 	COMPOUND4res_clnt res, *resp = NULL;
8159 	nfs_argop4 *argop;
8160 	nfs_resop4 *resop;
8161 	int doqueue, argoplist_size;
8162 	mntinfo4_t *mi;
8163 	rnode4_t *odrp = VTOR4(odvp);
8164 	rnode4_t *ndrp = VTOR4(ndvp);
8165 	RENAME4res *rn_res;
8166 	bool_t needrecov;
8167 	nfs4_recov_state_t recov_state;
8168 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8169 	dirattr_info_t dinfo, *dinfop;
8170 
8171 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8172 
8173 	recov_state.rs_flags = 0;
8174 	recov_state.rs_num_retry_despite_err = 0;
8175 
8176 	/*
8177 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
8178 	 *
8179 	 * If source/target are different dirs, then append putfh(src); getattr
8180 	 */
8181 	args.array_len = (odvp == ndvp) ? 5 : 7;
8182 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8183 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8184 
8185 recov_retry:
8186 	*statp = NFS4_OK;
8187 
8188 	/* No need to Lookup the file, persistent fh */
8189 	args.ctag = TAG_RENAME;
8190 
8191 	mi = VTOMI4(odvp);
8192 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8193 	if (e.error) {
8194 		kmem_free(argop, argoplist_size);
8195 		return (e.error);
8196 	}
8197 
8198 	/* 0: putfh source directory */
8199 	argop[0].argop = OP_CPUTFH;
8200 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8201 
8202 	/* 1: Save source fh to free up current for target */
8203 	argop[1].argop = OP_SAVEFH;
8204 
8205 	/* 2: putfh targetdir */
8206 	argop[2].argop = OP_CPUTFH;
8207 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8208 
8209 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8210 	argop[3].argop = OP_CRENAME;
8211 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8212 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8213 
8214 	/* 4: getattr (targetdir) */
8215 	argop[4].argop = OP_GETATTR;
8216 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8217 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8218 
8219 	if (ndvp != odvp) {
8220 
8221 		/* 5: putfh (sourcedir) */
8222 		argop[5].argop = OP_CPUTFH;
8223 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8224 
8225 		/* 6: getattr (sourcedir) */
8226 		argop[6].argop = OP_GETATTR;
8227 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8228 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8229 	}
8230 
8231 	dnlc_remove(odvp, onm);
8232 	dnlc_remove(ndvp, nnm);
8233 
8234 	doqueue = 1;
8235 	dinfo.di_time_call = gethrtime();
8236 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8237 
8238 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8239 	if (e.error) {
8240 		PURGE_ATTRCACHE4(odvp);
8241 		PURGE_ATTRCACHE4(ndvp);
8242 	} else {
8243 		*statp = res.status;
8244 	}
8245 
8246 	if (needrecov) {
8247 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8248 		    OP_RENAME, NULL, NULL, NULL) == FALSE) {
8249 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8250 			if (!e.error)
8251 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
8252 			goto recov_retry;
8253 		}
8254 	}
8255 
8256 	if (!e.error) {
8257 		resp = &res;
8258 		/*
8259 		 * as long as OP_RENAME
8260 		 */
8261 		if (res.status != NFS4_OK && res.array_len <= 4) {
8262 			e.error = geterrno4(res.status);
8263 			PURGE_ATTRCACHE4(odvp);
8264 			PURGE_ATTRCACHE4(ndvp);
8265 			/*
8266 			 * System V defines rename to return EEXIST, not
8267 			 * ENOTEMPTY if the target directory is not empty.
8268 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8269 			 * which geterrno4 maps to ENOTEMPTY.
8270 			 */
8271 			if (e.error == ENOTEMPTY)
8272 				e.error = EEXIST;
8273 		} else {
8274 
8275 			resop = &res.array[3];	/* rename res */
8276 			rn_res = &resop->nfs_resop4_u.oprename;
8277 
8278 			if (res.status == NFS4_OK) {
8279 				/*
8280 				 * Update target attribute, readdir and dnlc
8281 				 * caches.
8282 				 */
8283 				dinfo.di_garp =
8284 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8285 				dinfo.di_cred = cr;
8286 				dinfop = &dinfo;
8287 			} else
8288 				dinfop = NULL;
8289 
8290 			nfs4_update_dircaches(&rn_res->target_cinfo,
8291 			    ndvp, NULL, NULL, dinfop);
8292 
8293 			/*
8294 			 * Update source attribute, readdir and dnlc caches
8295 			 *
8296 			 */
8297 			if (ndvp != odvp) {
8298 				update_parentdir_sfh(renvp, ndvp);
8299 
8300 				if (dinfop)
8301 					dinfo.di_garp =
8302 					    &(res.array[6].nfs_resop4_u.
8303 					    opgetattr.ga_res);
8304 
8305 				nfs4_update_dircaches(&rn_res->source_cinfo,
8306 				    odvp, NULL, NULL, dinfop);
8307 			}
8308 
8309 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8310 			    nnm);
8311 		}
8312 	}
8313 
8314 	if (resp)
8315 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8316 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8317 	kmem_free(argop, argoplist_size);
8318 
8319 	return (e.error);
8320 }
8321 
8322 /*
8323  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8324  * it is possible for the filehandle to change due to the rename.
8325  *
8326  * The compound req in this case includes a post-rename lookup and getattr
8327  * to ensure that we have the correct fh and attributes for the object.
8328  *
8329  * Rename requires that the current fh be the target directory and the
8330  * saved fh be the source directory. After the operation, the current fh
8331  * is unchanged.
8332  *
8333  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8334  * update the filehandle for the renamed object.  We also get the old
8335  * filehandle for historical reasons; this should be taken out sometime.
8336  * This results in a rather cumbersome compound...
8337  *
8338  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8339  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8340  *
8341  */
8342 static int
8343 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8344     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8345 {
8346 	COMPOUND4args_clnt args;
8347 	COMPOUND4res_clnt res, *resp = NULL;
8348 	int argoplist_size;
8349 	nfs_argop4 *argop;
8350 	nfs_resop4 *resop;
8351 	int doqueue;
8352 	mntinfo4_t *mi;
8353 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8354 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8355 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8356 	RENAME4res *rn_res;
8357 	GETFH4res *ngf_res;
8358 	bool_t needrecov;
8359 	nfs4_recov_state_t recov_state;
8360 	hrtime_t t;
8361 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8362 	dirattr_info_t dinfo, *dinfop = &dinfo;
8363 
8364 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8365 
8366 	recov_state.rs_flags = 0;
8367 	recov_state.rs_num_retry_despite_err = 0;
8368 
8369 recov_retry:
8370 	*statp = NFS4_OK;
8371 
8372 	/*
8373 	 * There is a window between the RPC and updating the path and
8374 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8375 	 * code, so that it doesn't try to use the old path during that
8376 	 * window.
8377 	 */
8378 	mutex_enter(&orp->r_statelock);
8379 	while (orp->r_flags & R4RECEXPFH) {
8380 		klwp_t *lwp = ttolwp(curthread);
8381 
8382 		if (lwp != NULL)
8383 			lwp->lwp_nostop++;
8384 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8385 			mutex_exit(&orp->r_statelock);
8386 			if (lwp != NULL)
8387 				lwp->lwp_nostop--;
8388 			return (EINTR);
8389 		}
8390 		if (lwp != NULL)
8391 			lwp->lwp_nostop--;
8392 	}
8393 	orp->r_flags |= R4RECEXPFH;
8394 	mutex_exit(&orp->r_statelock);
8395 
8396 	mi = VTOMI4(odvp);
8397 
8398 	args.ctag = TAG_RENAME_VFH;
8399 	args.array_len = (odvp == ndvp) ? 10 : 12;
8400 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8401 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8402 
8403 	/*
8404 	 * Rename ops:
8405 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8406 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8407 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8408 	 *
8409 	 *    if (odvp != ndvp)
8410 	 *	add putfh(sourcedir), getattr(sourcedir) }
8411 	 */
8412 	args.array = argop;
8413 
8414 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8415 	    &recov_state, NULL);
8416 	if (e.error) {
8417 		kmem_free(argop, argoplist_size);
8418 		mutex_enter(&orp->r_statelock);
8419 		orp->r_flags &= ~R4RECEXPFH;
8420 		cv_broadcast(&orp->r_cv);
8421 		mutex_exit(&orp->r_statelock);
8422 		return (e.error);
8423 	}
8424 
8425 	/* 0: putfh source directory */
8426 	argop[0].argop = OP_CPUTFH;
8427 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8428 
8429 	/* 1: Save source fh to free up current for target */
8430 	argop[1].argop = OP_SAVEFH;
8431 
8432 	/* 2: Lookup pre-rename fh of renamed object */
8433 	argop[2].argop = OP_CLOOKUP;
8434 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8435 
8436 	/* 3: getfh fh of renamed object (before rename) */
8437 	argop[3].argop = OP_GETFH;
8438 
8439 	/* 4: putfh targetdir */
8440 	argop[4].argop = OP_CPUTFH;
8441 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8442 
8443 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8444 	argop[5].argop = OP_CRENAME;
8445 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8446 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8447 
8448 	/* 6: getattr of target dir (post op attrs) */
8449 	argop[6].argop = OP_GETATTR;
8450 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8451 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8452 
8453 	/* 7: Lookup post-rename fh of renamed object */
8454 	argop[7].argop = OP_CLOOKUP;
8455 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8456 
8457 	/* 8: getfh fh of renamed object (after rename) */
8458 	argop[8].argop = OP_GETFH;
8459 
8460 	/* 9: getattr of renamed object */
8461 	argop[9].argop = OP_GETATTR;
8462 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8463 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8464 
8465 	/*
8466 	 * If source/target dirs are different, then get new post-op
8467 	 * attrs for source dir also.
8468 	 */
8469 	if (ndvp != odvp) {
8470 		/* 10: putfh (sourcedir) */
8471 		argop[10].argop = OP_CPUTFH;
8472 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8473 
8474 		/* 11: getattr (sourcedir) */
8475 		argop[11].argop = OP_GETATTR;
8476 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8477 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8478 	}
8479 
8480 	dnlc_remove(odvp, onm);
8481 	dnlc_remove(ndvp, nnm);
8482 
8483 	doqueue = 1;
8484 	t = gethrtime();
8485 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8486 
8487 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8488 	if (e.error) {
8489 		PURGE_ATTRCACHE4(odvp);
8490 		PURGE_ATTRCACHE4(ndvp);
8491 		if (!needrecov) {
8492 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8493 			    &recov_state, needrecov);
8494 			goto out;
8495 		}
8496 	} else {
8497 		*statp = res.status;
8498 	}
8499 
8500 	if (needrecov) {
8501 		bool_t abort;
8502 
8503 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8504 		    OP_RENAME, NULL, NULL, NULL);
8505 		if (abort == FALSE) {
8506 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8507 			    &recov_state, needrecov);
8508 			kmem_free(argop, argoplist_size);
8509 			if (!e.error)
8510 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
8511 			mutex_enter(&orp->r_statelock);
8512 			orp->r_flags &= ~R4RECEXPFH;
8513 			cv_broadcast(&orp->r_cv);
8514 			mutex_exit(&orp->r_statelock);
8515 			goto recov_retry;
8516 		} else {
8517 			if (e.error != 0) {
8518 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8519 				    &recov_state, needrecov);
8520 				goto out;
8521 			}
8522 			/* fall through for res.status case */
8523 		}
8524 	}
8525 
8526 	resp = &res;
8527 	/*
8528 	 * If OP_RENAME (or any prev op) failed, then return an error.
8529 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8530 	 */
8531 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8532 		/*
8533 		 * Error in an op other than last Getattr
8534 		 */
8535 		e.error = geterrno4(res.status);
8536 		PURGE_ATTRCACHE4(odvp);
8537 		PURGE_ATTRCACHE4(ndvp);
8538 		/*
8539 		 * System V defines rename to return EEXIST, not
8540 		 * ENOTEMPTY if the target directory is not empty.
8541 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8542 		 * which geterrno4 maps to ENOTEMPTY.
8543 		 */
8544 		if (e.error == ENOTEMPTY)
8545 			e.error = EEXIST;
8546 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8547 		    needrecov);
8548 		goto out;
8549 	}
8550 
8551 	/* rename results */
8552 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8553 
8554 	if (res.status == NFS4_OK) {
8555 		/* Update target attribute, readdir and dnlc caches */
8556 		dinfo.di_garp =
8557 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
8558 		dinfo.di_cred = cr;
8559 		dinfo.di_time_call = t;
8560 	} else
8561 		dinfop = NULL;
8562 
8563 	/* Update source cache attribute, readdir and dnlc caches */
8564 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8565 
8566 	/* Update source cache attribute, readdir and dnlc caches */
8567 	if (ndvp != odvp) {
8568 		update_parentdir_sfh(ovp, ndvp);
8569 
8570 		/*
8571 		 * If dinfop is non-NULL, then compound succeded, so
8572 		 * set di_garp to attrs for source dir.  dinfop is only
8573 		 * set to NULL when compound fails.
8574 		 */
8575 		if (dinfop)
8576 			dinfo.di_garp =
8577 			    &res.array[11].nfs_resop4_u.opgetattr.ga_res;
8578 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8579 		    dinfop);
8580 	}
8581 
8582 	/*
8583 	 * Update the rnode with the new component name and args,
8584 	 * and if the file handle changed, also update it with the new fh.
8585 	 * This is only necessary if the target object has an rnode
8586 	 * entry and there is no need to create one for it.
8587 	 */
8588 	resop = &res.array[8];	/* getfh new res */
8589 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8590 
8591 	/*
8592 	 * Update the path and filehandle for the renamed object.
8593 	 */
8594 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8595 
8596 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8597 
8598 	if (res.status == NFS4_OK) {
8599 		resop++;	/* getattr res */
8600 		e.error = nfs4_update_attrcache(res.status,
8601 		    &resop->nfs_resop4_u.opgetattr.ga_res,
8602 		    t, ovp, cr);
8603 	}
8604 
8605 out:
8606 	kmem_free(argop, argoplist_size);
8607 	if (resp)
8608 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8609 	mutex_enter(&orp->r_statelock);
8610 	orp->r_flags &= ~R4RECEXPFH;
8611 	cv_broadcast(&orp->r_cv);
8612 	mutex_exit(&orp->r_statelock);
8613 
8614 	return (e.error);
8615 }
8616 
8617 /* ARGSUSED */
8618 static int
8619 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr,
8620     caller_context_t *ct, int flags, vsecattr_t *vsecp)
8621 {
8622 	int error;
8623 	vnode_t *vp;
8624 
8625 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8626 		return (EPERM);
8627 	/*
8628 	 * As ".." has special meaning and rather than send a mkdir
8629 	 * over the wire to just let the server freak out, we just
8630 	 * short circuit it here and return EEXIST
8631 	 */
8632 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8633 		return (EEXIST);
8634 
8635 	/*
8636 	 * Decision to get the right gid and setgid bit of the
8637 	 * new directory is now made in call_nfs4_create_req.
8638 	 */
8639 	va->va_mask |= AT_MODE;
8640 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8641 	if (error)
8642 		return (error);
8643 
8644 	*vpp = vp;
8645 	return (0);
8646 }
8647 
8648 
8649 /*
8650  * rmdir is using the same remove v4 op as does remove.
8651  * Remove requires that the current fh be the target directory.
8652  * After the operation, the current fh is unchanged.
8653  * The compound op structure is:
8654  *      PUTFH(targetdir), REMOVE
8655  */
8656 /*ARGSUSED4*/
8657 static int
8658 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr,
8659     caller_context_t *ct, int flags)
8660 {
8661 	int need_end_op = FALSE;
8662 	COMPOUND4args_clnt args;
8663 	COMPOUND4res_clnt res, *resp = NULL;
8664 	REMOVE4res *rm_res;
8665 	nfs_argop4 argop[3];
8666 	nfs_resop4 *resop;
8667 	vnode_t *vp;
8668 	int doqueue;
8669 	mntinfo4_t *mi;
8670 	rnode4_t *drp;
8671 	bool_t needrecov = FALSE;
8672 	nfs4_recov_state_t recov_state;
8673 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8674 	dirattr_info_t dinfo, *dinfop;
8675 
8676 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8677 		return (EPERM);
8678 	/*
8679 	 * As ".." has special meaning and rather than send a rmdir
8680 	 * over the wire to just let the server freak out, we just
8681 	 * short circuit it here and return EEXIST
8682 	 */
8683 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8684 		return (EEXIST);
8685 
8686 	drp = VTOR4(dvp);
8687 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8688 		return (EINTR);
8689 
8690 	/*
8691 	 * Attempt to prevent a rmdir(".") from succeeding.
8692 	 */
8693 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8694 	if (e.error) {
8695 		nfs_rw_exit(&drp->r_rwlock);
8696 		return (e.error);
8697 	}
8698 	if (vp == cdir) {
8699 		VN_RELE(vp);
8700 		nfs_rw_exit(&drp->r_rwlock);
8701 		return (EINVAL);
8702 	}
8703 
8704 	/*
8705 	 * Since nfsv4 remove op works on both files and directories,
8706 	 * check that the removed object is indeed a directory.
8707 	 */
8708 	if (vp->v_type != VDIR) {
8709 		VN_RELE(vp);
8710 		nfs_rw_exit(&drp->r_rwlock);
8711 		return (ENOTDIR);
8712 	}
8713 
8714 	/*
8715 	 * First just remove the entry from the name cache, as it
8716 	 * is most likely an entry for this vp.
8717 	 */
8718 	dnlc_remove(dvp, nm);
8719 
8720 	/*
8721 	 * If there vnode reference count is greater than one, then
8722 	 * there may be additional references in the DNLC which will
8723 	 * need to be purged.  First, trying removing the entry for
8724 	 * the parent directory and see if that removes the additional
8725 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8726 	 * to completely remove any references to the directory which
8727 	 * might still exist in the DNLC.
8728 	 */
8729 	if (vp->v_count > 1) {
8730 		dnlc_remove(vp, "..");
8731 		if (vp->v_count > 1)
8732 			dnlc_purge_vp(vp);
8733 	}
8734 
8735 	mi = VTOMI4(dvp);
8736 	recov_state.rs_flags = 0;
8737 	recov_state.rs_num_retry_despite_err = 0;
8738 
8739 recov_retry:
8740 	args.ctag = TAG_RMDIR;
8741 
8742 	/*
8743 	 * Rmdir ops: putfh dir; remove
8744 	 */
8745 	args.array_len = 3;
8746 	args.array = argop;
8747 
8748 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8749 	if (e.error) {
8750 		nfs_rw_exit(&drp->r_rwlock);
8751 		return (e.error);
8752 	}
8753 	need_end_op = TRUE;
8754 
8755 	/* putfh directory */
8756 	argop[0].argop = OP_CPUTFH;
8757 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8758 
8759 	/* remove */
8760 	argop[1].argop = OP_CREMOVE;
8761 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8762 
8763 	/* getattr (postop attrs for dir that contained removed dir) */
8764 	argop[2].argop = OP_GETATTR;
8765 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8766 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8767 
8768 	dinfo.di_time_call = gethrtime();
8769 	doqueue = 1;
8770 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8771 
8772 	PURGE_ATTRCACHE4(vp);
8773 
8774 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8775 	if (e.error) {
8776 		PURGE_ATTRCACHE4(dvp);
8777 	}
8778 
8779 	if (needrecov) {
8780 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8781 		    NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
8782 			if (!e.error)
8783 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
8784 
8785 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8786 			    needrecov);
8787 			need_end_op = FALSE;
8788 			goto recov_retry;
8789 		}
8790 	}
8791 
8792 	if (!e.error) {
8793 		resp = &res;
8794 
8795 		/*
8796 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8797 		 * failed.
8798 		 */
8799 		if (res.status != NFS4_OK && res.array_len <= 2) {
8800 			e.error = geterrno4(res.status);
8801 			PURGE_ATTRCACHE4(dvp);
8802 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8803 			    &recov_state, needrecov);
8804 			need_end_op = FALSE;
8805 			nfs4_purge_stale_fh(e.error, dvp, cr);
8806 			/*
8807 			 * System V defines rmdir to return EEXIST, not
8808 			 * ENOTEMPTY if the directory is not empty.  Over
8809 			 * the wire, the error is NFSERR_ENOTEMPTY which
8810 			 * geterrno4 maps to ENOTEMPTY.
8811 			 */
8812 			if (e.error == ENOTEMPTY)
8813 				e.error = EEXIST;
8814 		} else {
8815 			resop = &res.array[1];	/* remove res */
8816 			rm_res = &resop->nfs_resop4_u.opremove;
8817 
8818 			if (res.status == NFS4_OK) {
8819 				resop = &res.array[2];	/* dir attrs */
8820 				dinfo.di_garp =
8821 				    &resop->nfs_resop4_u.opgetattr.ga_res;
8822 				dinfo.di_cred = cr;
8823 				dinfop = &dinfo;
8824 			} else
8825 				dinfop = NULL;
8826 
8827 			/* Update dir attribute, readdir and dnlc caches */
8828 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8829 			    dinfop);
8830 
8831 			/* destroy rddir cache for dir that was removed */
8832 			if (VTOR4(vp)->r_dir != NULL)
8833 				nfs4_purge_rddir_cache(vp);
8834 		}
8835 	}
8836 
8837 	if (need_end_op)
8838 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8839 
8840 	nfs_rw_exit(&drp->r_rwlock);
8841 
8842 	if (resp)
8843 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8844 
8845 	if (e.error == 0) {
8846 		vnode_t *tvp;
8847 		rnode4_t *trp;
8848 		trp = VTOR4(vp);
8849 		tvp = vp;
8850 		if (IS_SHADOW(vp, trp))
8851 			tvp = RTOV4(trp);
8852 		vnevent_rmdir(tvp, dvp, nm, ct);
8853 	}
8854 
8855 	VN_RELE(vp);
8856 
8857 	return (e.error);
8858 }
8859 
8860 /* ARGSUSED */
8861 static int
8862 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr,
8863     caller_context_t *ct, int flags)
8864 {
8865 	int error;
8866 	vnode_t *vp;
8867 	rnode4_t *rp;
8868 	char *contents;
8869 	mntinfo4_t *mi = VTOMI4(dvp);
8870 
8871 	if (nfs_zone() != mi->mi_zone)
8872 		return (EPERM);
8873 	if (!(mi->mi_flags & MI4_SYMLINK))
8874 		return (EOPNOTSUPP);
8875 
8876 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8877 	if (error)
8878 		return (error);
8879 
8880 	ASSERT(nfs4_consistent_type(vp));
8881 	rp = VTOR4(vp);
8882 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8883 
8884 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8885 
8886 		if (contents != NULL) {
8887 			mutex_enter(&rp->r_statelock);
8888 			if (rp->r_symlink.contents == NULL) {
8889 				rp->r_symlink.len = strlen(tnm);
8890 				bcopy(tnm, contents, rp->r_symlink.len);
8891 				rp->r_symlink.contents = contents;
8892 				rp->r_symlink.size = MAXPATHLEN;
8893 				mutex_exit(&rp->r_statelock);
8894 			} else {
8895 				mutex_exit(&rp->r_statelock);
8896 				kmem_free((void *)contents, MAXPATHLEN);
8897 			}
8898 		}
8899 	}
8900 	VN_RELE(vp);
8901 
8902 	return (error);
8903 }
8904 
8905 
8906 /*
8907  * Read directory entries.
8908  * There are some weird things to look out for here.  The uio_loffset
8909  * field is either 0 or it is the offset returned from a previous
8910  * readdir.  It is an opaque value used by the server to find the
8911  * correct directory block to read. The count field is the number
8912  * of blocks to read on the server.  This is advisory only, the server
8913  * may return only one block's worth of entries.  Entries may be compressed
8914  * on the server.
8915  */
8916 /* ARGSUSED */
8917 static int
8918 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp,
8919     caller_context_t *ct, int flags)
8920 {
8921 	int error;
8922 	uint_t count;
8923 	rnode4_t *rp;
8924 	rddir4_cache *rdc;
8925 	rddir4_cache *rrdc;
8926 
8927 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8928 		return (EIO);
8929 	rp = VTOR4(vp);
8930 
8931 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8932 
8933 	/*
8934 	 * Make sure that the directory cache is valid.
8935 	 */
8936 	if (rp->r_dir != NULL) {
8937 		if (nfs_disable_rddir_cache != 0) {
8938 			/*
8939 			 * Setting nfs_disable_rddir_cache in /etc/system
8940 			 * allows interoperability with servers that do not
8941 			 * properly update the attributes of directories.
8942 			 * Any cached information gets purged before an
8943 			 * access is made to it.
8944 			 */
8945 			nfs4_purge_rddir_cache(vp);
8946 		}
8947 
8948 		error = nfs4_validate_caches(vp, cr);
8949 		if (error)
8950 			return (error);
8951 	}
8952 
8953 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8954 
8955 	/*
8956 	 * Short circuit last readdir which always returns 0 bytes.
8957 	 * This can be done after the directory has been read through
8958 	 * completely at least once.  This will set r_direof which
8959 	 * can be used to find the value of the last cookie.
8960 	 */
8961 	mutex_enter(&rp->r_statelock);
8962 	if (rp->r_direof != NULL &&
8963 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8964 		mutex_exit(&rp->r_statelock);
8965 #ifdef DEBUG
8966 		nfs4_readdir_cache_shorts++;
8967 #endif
8968 		if (eofp)
8969 			*eofp = 1;
8970 		return (0);
8971 	}
8972 
8973 	/*
8974 	 * Look for a cache entry.  Cache entries are identified
8975 	 * by the NFS cookie value and the byte count requested.
8976 	 */
8977 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8978 
8979 	/*
8980 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8981 	 */
8982 	if (rdc == NULL) {
8983 		mutex_exit(&rp->r_statelock);
8984 		return (EINTR);
8985 	}
8986 
8987 	/*
8988 	 * Check to see if we need to fill this entry in.
8989 	 */
8990 	if (rdc->flags & RDDIRREQ) {
8991 		rdc->flags &= ~RDDIRREQ;
8992 		rdc->flags |= RDDIR;
8993 		mutex_exit(&rp->r_statelock);
8994 
8995 		/*
8996 		 * Do the readdir.
8997 		 */
8998 		nfs4readdir(vp, rdc, cr);
8999 
9000 		/*
9001 		 * Reacquire the lock, so that we can continue
9002 		 */
9003 		mutex_enter(&rp->r_statelock);
9004 		/*
9005 		 * The entry is now complete
9006 		 */
9007 		rdc->flags &= ~RDDIR;
9008 	}
9009 
9010 	ASSERT(!(rdc->flags & RDDIR));
9011 
9012 	/*
9013 	 * If an error occurred while attempting
9014 	 * to fill the cache entry, mark the entry invalid and
9015 	 * just return the error.
9016 	 */
9017 	if (rdc->error) {
9018 		error = rdc->error;
9019 		rdc->flags |= RDDIRREQ;
9020 		rddir4_cache_rele(rp, rdc);
9021 		mutex_exit(&rp->r_statelock);
9022 		return (error);
9023 	}
9024 
9025 	/*
9026 	 * The cache entry is complete and good,
9027 	 * copyout the dirent structs to the calling
9028 	 * thread.
9029 	 */
9030 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
9031 
9032 	/*
9033 	 * If no error occurred during the copyout,
9034 	 * update the offset in the uio struct to
9035 	 * contain the value of the next NFS 4 cookie
9036 	 * and set the eof value appropriately.
9037 	 */
9038 	if (!error) {
9039 		uiop->uio_loffset = rdc->nfs4_ncookie;
9040 		if (eofp)
9041 			*eofp = rdc->eof;
9042 	}
9043 
9044 	/*
9045 	 * Decide whether to do readahead.  Don't if we
9046 	 * have already read to the end of directory.
9047 	 */
9048 	if (rdc->eof) {
9049 		/*
9050 		 * Make the entry the direof only if it is cached
9051 		 */
9052 		if (rdc->flags & RDDIRCACHED)
9053 			rp->r_direof = rdc;
9054 		rddir4_cache_rele(rp, rdc);
9055 		mutex_exit(&rp->r_statelock);
9056 		return (error);
9057 	}
9058 
9059 	/* Determine if a readdir readahead should be done */
9060 	if (!(rp->r_flags & R4LOOKUP)) {
9061 		rddir4_cache_rele(rp, rdc);
9062 		mutex_exit(&rp->r_statelock);
9063 		return (error);
9064 	}
9065 
9066 	/*
9067 	 * Now look for a readahead entry.
9068 	 *
9069 	 * Check to see whether we found an entry for the readahead.
9070 	 * If so, we don't need to do anything further, so free the new
9071 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
9072 	 * it to the cache, and then initiate an asynchronous readdir
9073 	 * operation to fill it.
9074 	 */
9075 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
9076 
9077 	/*
9078 	 * A readdir cache entry could not be obtained for the readahead.  In
9079 	 * this case we skip the readahead and return.
9080 	 */
9081 	if (rrdc == NULL) {
9082 		rddir4_cache_rele(rp, rdc);
9083 		mutex_exit(&rp->r_statelock);
9084 		return (error);
9085 	}
9086 
9087 	/*
9088 	 * Check to see if we need to fill this entry in.
9089 	 */
9090 	if (rrdc->flags & RDDIRREQ) {
9091 		rrdc->flags &= ~RDDIRREQ;
9092 		rrdc->flags |= RDDIR;
9093 		rddir4_cache_rele(rp, rdc);
9094 		mutex_exit(&rp->r_statelock);
9095 #ifdef DEBUG
9096 		nfs4_readdir_readahead++;
9097 #endif
9098 		/*
9099 		 * Do the readdir.
9100 		 */
9101 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
9102 		return (error);
9103 	}
9104 
9105 	rddir4_cache_rele(rp, rrdc);
9106 	rddir4_cache_rele(rp, rdc);
9107 	mutex_exit(&rp->r_statelock);
9108 	return (error);
9109 }
9110 
9111 static int
9112 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9113 {
9114 	int error;
9115 	rnode4_t *rp;
9116 
9117 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9118 
9119 	rp = VTOR4(vp);
9120 
9121 	/*
9122 	 * Obtain the readdir results for the caller.
9123 	 */
9124 	nfs4readdir(vp, rdc, cr);
9125 
9126 	mutex_enter(&rp->r_statelock);
9127 	/*
9128 	 * The entry is now complete
9129 	 */
9130 	rdc->flags &= ~RDDIR;
9131 
9132 	error = rdc->error;
9133 	if (error)
9134 		rdc->flags |= RDDIRREQ;
9135 	rddir4_cache_rele(rp, rdc);
9136 	mutex_exit(&rp->r_statelock);
9137 
9138 	return (error);
9139 }
9140 
9141 /*
9142  * Read directory entries.
9143  * There are some weird things to look out for here.  The uio_loffset
9144  * field is either 0 or it is the offset returned from a previous
9145  * readdir.  It is an opaque value used by the server to find the
9146  * correct directory block to read. The count field is the number
9147  * of blocks to read on the server.  This is advisory only, the server
9148  * may return only one block's worth of entries.  Entries may be compressed
9149  * on the server.
9150  *
9151  * Generates the following compound request:
9152  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9153  *    must include a Lookupp as well. In this case, send:
9154  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9155  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9156  *
9157  * Get complete attributes and filehandles for entries if this is the
9158  * first read of the directory. Otherwise, just get fileid's.
9159  */
9160 static void
9161 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9162 {
9163 	COMPOUND4args_clnt args;
9164 	COMPOUND4res_clnt res;
9165 	READDIR4args *rargs;
9166 	READDIR4res_clnt *rd_res;
9167 	bitmap4 rd_bitsval;
9168 	nfs_argop4 argop[5];
9169 	nfs_resop4 *resop;
9170 	rnode4_t *rp = VTOR4(vp);
9171 	mntinfo4_t *mi = VTOMI4(vp);
9172 	int doqueue;
9173 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9174 	vnode_t *dvp;
9175 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9176 	int num_ops, res_opcnt;
9177 	bool_t needrecov = FALSE;
9178 	nfs4_recov_state_t recov_state;
9179 	hrtime_t t;
9180 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9181 
9182 	ASSERT(nfs_zone() == mi->mi_zone);
9183 	ASSERT(rdc->flags & RDDIR);
9184 	ASSERT(rdc->entries == NULL);
9185 
9186 	/*
9187 	 * If rp were a stub, it should have triggered and caused
9188 	 * a mount for us to get this far.
9189 	 */
9190 	ASSERT(!RP_ISSTUB(rp));
9191 
9192 	num_ops = 2;
9193 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9194 		/*
9195 		 * Since nfsv4 readdir may not return entries for "." and "..",
9196 		 * the client must recreate them:
9197 		 * To find the correct nodeid, do the following:
9198 		 * For current node, get nodeid from dnlc.
9199 		 * - if current node is rootvp, set pnodeid to nodeid.
9200 		 * - else if parent is in the dnlc, get its nodeid from there.
9201 		 * - else add LOOKUPP+GETATTR to compound.
9202 		 */
9203 		nodeid = rp->r_attr.va_nodeid;
9204 		if (vp->v_flag & VROOT) {
9205 			pnodeid = nodeid;	/* root of mount point */
9206 		} else {
9207 			dvp = dnlc_lookup(vp, "..");
9208 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9209 				/* parent in dnlc cache - no need for otw */
9210 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9211 			} else {
9212 				/*
9213 				 * parent not in dnlc cache,
9214 				 * do lookupp to get its id
9215 				 */
9216 				num_ops = 5;
9217 				pnodeid = 0; /* set later by getattr parent */
9218 			}
9219 			if (dvp)
9220 				VN_RELE(dvp);
9221 		}
9222 	}
9223 	recov_state.rs_flags = 0;
9224 	recov_state.rs_num_retry_despite_err = 0;
9225 
9226 	/* Save the original mount point security flavor */
9227 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9228 
9229 recov_retry:
9230 	args.ctag = TAG_READDIR;
9231 
9232 	args.array = argop;
9233 	args.array_len = num_ops;
9234 
9235 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9236 	    &recov_state, NULL)) {
9237 		/*
9238 		 * If readdir a node that is a stub for a crossed mount point,
9239 		 * keep the original secinfo flavor for the current file
9240 		 * system, not the crossed one.
9241 		 */
9242 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9243 		rdc->error = e.error;
9244 		return;
9245 	}
9246 
9247 	/*
9248 	 * Determine which attrs to request for dirents.  This code
9249 	 * must be protected by nfs4_start/end_fop because of r_server
9250 	 * (which will change during failover recovery).
9251 	 *
9252 	 */
9253 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9254 		/*
9255 		 * Get all vattr attrs plus filehandle and rdattr_error
9256 		 */
9257 		rd_bitsval = NFS4_VATTR_MASK |
9258 		    FATTR4_RDATTR_ERROR_MASK |
9259 		    FATTR4_FILEHANDLE_MASK;
9260 
9261 		if (rp->r_flags & R4READDIRWATTR) {
9262 			mutex_enter(&rp->r_statelock);
9263 			rp->r_flags &= ~R4READDIRWATTR;
9264 			mutex_exit(&rp->r_statelock);
9265 		}
9266 	} else {
9267 		servinfo4_t *svp = rp->r_server;
9268 
9269 		/*
9270 		 * Already read directory. Use readdir with
9271 		 * no attrs (except for mounted_on_fileid) for updates.
9272 		 */
9273 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9274 
9275 		/*
9276 		 * request mounted on fileid if supported, else request
9277 		 * fileid.  maybe we should verify that fileid is supported
9278 		 * and request something else if not.
9279 		 */
9280 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9281 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9282 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9283 		nfs_rw_exit(&svp->sv_lock);
9284 	}
9285 
9286 	/* putfh directory fh */
9287 	argop[0].argop = OP_CPUTFH;
9288 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9289 
9290 	argop[1].argop = OP_READDIR;
9291 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9292 	/*
9293 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9294 	 * cookie 0 should be used over-the-wire to start reading at
9295 	 * the beginning of the directory excluding "." and "..".
9296 	 */
9297 	if (rdc->nfs4_cookie == 0 ||
9298 	    rdc->nfs4_cookie == 1 ||
9299 	    rdc->nfs4_cookie == 2) {
9300 		rargs->cookie = (nfs_cookie4)0;
9301 		rargs->cookieverf = 0;
9302 	} else {
9303 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9304 		mutex_enter(&rp->r_statelock);
9305 		rargs->cookieverf = rp->r_cookieverf4;
9306 		mutex_exit(&rp->r_statelock);
9307 	}
9308 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9309 	rargs->maxcount = mi->mi_tsize;
9310 	rargs->attr_request = rd_bitsval;
9311 	rargs->rdc = rdc;
9312 	rargs->dvp = vp;
9313 	rargs->mi = mi;
9314 	rargs->cr = cr;
9315 
9316 
9317 	/*
9318 	 * If count < than the minimum required, we return no entries
9319 	 * and fail with EINVAL
9320 	 */
9321 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9322 		rdc->error = EINVAL;
9323 		goto out;
9324 	}
9325 
9326 	if (args.array_len == 5) {
9327 		/*
9328 		 * Add lookupp and getattr for parent nodeid.
9329 		 */
9330 		argop[2].argop = OP_LOOKUPP;
9331 
9332 		argop[3].argop = OP_GETFH;
9333 
9334 		/* getattr parent */
9335 		argop[4].argop = OP_GETATTR;
9336 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9337 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9338 	}
9339 
9340 	doqueue = 1;
9341 
9342 	if (mi->mi_io_kstats) {
9343 		mutex_enter(&mi->mi_lock);
9344 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9345 		mutex_exit(&mi->mi_lock);
9346 	}
9347 
9348 	/* capture the time of this call */
9349 	rargs->t = t = gethrtime();
9350 
9351 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9352 
9353 	if (mi->mi_io_kstats) {
9354 		mutex_enter(&mi->mi_lock);
9355 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9356 		mutex_exit(&mi->mi_lock);
9357 	}
9358 
9359 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9360 
9361 	/*
9362 	 * If RPC error occurred and it isn't an error that
9363 	 * triggers recovery, then go ahead and fail now.
9364 	 */
9365 	if (e.error != 0 && !needrecov) {
9366 		rdc->error = e.error;
9367 		goto out;
9368 	}
9369 
9370 	if (needrecov) {
9371 		bool_t abort;
9372 
9373 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9374 		    "nfs4readdir: initiating recovery.\n"));
9375 
9376 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9377 		    NULL, OP_READDIR, NULL, NULL, NULL);
9378 		if (abort == FALSE) {
9379 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9380 			    &recov_state, needrecov);
9381 			if (!e.error)
9382 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9383 			if (rdc->entries != NULL) {
9384 				kmem_free(rdc->entries, rdc->entlen);
9385 				rdc->entries = NULL;
9386 			}
9387 			goto recov_retry;
9388 		}
9389 
9390 		if (e.error != 0) {
9391 			rdc->error = e.error;
9392 			goto out;
9393 		}
9394 
9395 		/* fall through for res.status case */
9396 	}
9397 
9398 	res_opcnt = res.array_len;
9399 
9400 	/*
9401 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9402 	 * failure here.  Subsequent ops are for filling out dot-dot
9403 	 * dirent, and if they fail, we still want to give the caller
9404 	 * the dirents returned by (the successful) READDIR op, so we need
9405 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9406 	 *
9407 	 * One example where PUTFH+READDIR ops would succeed but
9408 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9409 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9410 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9411 	 * x perm.  We need to come up with a non-vendor-specific way
9412 	 * for a POSIX server to return d_ino from dotdot's dirent if
9413 	 * client only requests mounted_on_fileid, and just say the
9414 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9415 	 * client requested any mandatory attrs, server would be required
9416 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9417 	 * for dotdot.
9418 	 */
9419 
9420 	if (res.status) {
9421 		if (res_opcnt <= 2) {
9422 			e.error = geterrno4(res.status);
9423 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9424 			    &recov_state, needrecov);
9425 			nfs4_purge_stale_fh(e.error, vp, cr);
9426 			rdc->error = e.error;
9427 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9428 			if (rdc->entries != NULL) {
9429 				kmem_free(rdc->entries, rdc->entlen);
9430 				rdc->entries = NULL;
9431 			}
9432 			/*
9433 			 * If readdir a node that is a stub for a
9434 			 * crossed mount point, keep the original
9435 			 * secinfo flavor for the current file system,
9436 			 * not the crossed one.
9437 			 */
9438 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9439 			return;
9440 		}
9441 	}
9442 
9443 	resop = &res.array[1];	/* readdir res */
9444 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9445 
9446 	mutex_enter(&rp->r_statelock);
9447 	rp->r_cookieverf4 = rd_res->cookieverf;
9448 	mutex_exit(&rp->r_statelock);
9449 
9450 	/*
9451 	 * For "." and ".." entries
9452 	 * e.g.
9453 	 *	seek(cookie=0) -> "." entry with d_off = 1
9454 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9455 	 */
9456 	if (cookie == (nfs_cookie4) 0) {
9457 		if (rd_res->dotp)
9458 			rd_res->dotp->d_ino = nodeid;
9459 		if (rd_res->dotdotp)
9460 			rd_res->dotdotp->d_ino = pnodeid;
9461 	}
9462 	if (cookie == (nfs_cookie4) 1) {
9463 		if (rd_res->dotdotp)
9464 			rd_res->dotdotp->d_ino = pnodeid;
9465 	}
9466 
9467 
9468 	/* LOOKUPP+GETATTR attemped */
9469 	if (args.array_len == 5 && rd_res->dotdotp) {
9470 		if (res.status == NFS4_OK && res_opcnt == 5) {
9471 			nfs_fh4 *fhp;
9472 			nfs4_sharedfh_t *sfhp;
9473 			vnode_t *pvp;
9474 			nfs4_ga_res_t *garp;
9475 
9476 			resop++;	/* lookupp */
9477 			resop++;	/* getfh   */
9478 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9479 
9480 			resop++;	/* getattr of parent */
9481 
9482 			/*
9483 			 * First, take care of finishing the
9484 			 * readdir results.
9485 			 */
9486 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9487 			/*
9488 			 * The d_ino of .. must be the inode number
9489 			 * of the mounted filesystem.
9490 			 */
9491 			if (garp->n4g_va.va_mask & AT_NODEID)
9492 				rd_res->dotdotp->d_ino =
9493 				    garp->n4g_va.va_nodeid;
9494 
9495 
9496 			/*
9497 			 * Next, create the ".." dnlc entry
9498 			 */
9499 			sfhp = sfh4_get(fhp, mi);
9500 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9501 				dnlc_update(vp, "..", pvp);
9502 				VN_RELE(pvp);
9503 			}
9504 			sfh4_rele(&sfhp);
9505 		}
9506 	}
9507 
9508 	if (mi->mi_io_kstats) {
9509 		mutex_enter(&mi->mi_lock);
9510 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9511 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9512 		mutex_exit(&mi->mi_lock);
9513 	}
9514 
9515 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9516 
9517 out:
9518 	/*
9519 	 * If readdir a node that is a stub for a crossed mount point,
9520 	 * keep the original secinfo flavor for the current file system,
9521 	 * not the crossed one.
9522 	 */
9523 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9524 
9525 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9526 }
9527 
9528 
9529 static int
9530 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9531 {
9532 	rnode4_t *rp = VTOR4(bp->b_vp);
9533 	int count;
9534 	int error;
9535 	cred_t *cred_otw = NULL;
9536 	offset_t offset;
9537 	nfs4_open_stream_t *osp = NULL;
9538 	bool_t first_time = TRUE;	/* first time getting otw cred */
9539 	bool_t last_time = FALSE;	/* last time getting otw cred */
9540 
9541 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9542 
9543 	DTRACE_IO1(start, struct buf *, bp);
9544 	offset = ldbtob(bp->b_lblkno);
9545 
9546 	if (bp->b_flags & B_READ) {
9547 	read_again:
9548 		/*
9549 		 * Releases the osp, if it is provided.
9550 		 * Puts a hold on the cred_otw and the new osp (if found).
9551 		 */
9552 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9553 		    &first_time, &last_time);
9554 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9555 		    offset, bp->b_bcount, &bp->b_resid, cred_otw,
9556 		    readahead, NULL);
9557 		crfree(cred_otw);
9558 		if (!error) {
9559 			if (bp->b_resid) {
9560 				/*
9561 				 * Didn't get it all because we hit EOF,
9562 				 * zero all the memory beyond the EOF.
9563 				 */
9564 				/* bzero(rdaddr + */
9565 				bzero(bp->b_un.b_addr +
9566 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9567 			}
9568 			mutex_enter(&rp->r_statelock);
9569 			if (bp->b_resid == bp->b_bcount &&
9570 			    offset >= rp->r_size) {
9571 				/*
9572 				 * We didn't read anything at all as we are
9573 				 * past EOF.  Return an error indicator back
9574 				 * but don't destroy the pages (yet).
9575 				 */
9576 				error = NFS_EOF;
9577 			}
9578 			mutex_exit(&rp->r_statelock);
9579 		} else if (error == EACCES && last_time == FALSE) {
9580 				goto read_again;
9581 		}
9582 	} else {
9583 		if (!(rp->r_flags & R4STALE)) {
9584 write_again:
9585 			/*
9586 			 * Releases the osp, if it is provided.
9587 			 * Puts a hold on the cred_otw and the new
9588 			 * osp (if found).
9589 			 */
9590 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9591 			    &first_time, &last_time);
9592 			mutex_enter(&rp->r_statelock);
9593 			count = MIN(bp->b_bcount, rp->r_size - offset);
9594 			mutex_exit(&rp->r_statelock);
9595 			if (count < 0)
9596 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9597 #ifdef DEBUG
9598 			if (count == 0) {
9599 				zoneid_t zoneid = getzoneid();
9600 
9601 				zcmn_err(zoneid, CE_WARN,
9602 				    "nfs4_bio: zero length write at %lld",
9603 				    offset);
9604 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9605 				    "b_bcount=%ld, file size=%lld",
9606 				    rp->r_flags, (long)bp->b_bcount,
9607 				    rp->r_size);
9608 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9609 				if (nfs4_bio_do_stop)
9610 					debug_enter("nfs4_bio");
9611 			}
9612 #endif
9613 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9614 			    count, cred_otw, stab_comm);
9615 			if (error == EACCES && last_time == FALSE) {
9616 				crfree(cred_otw);
9617 				goto write_again;
9618 			}
9619 			bp->b_error = error;
9620 			if (error && error != EINTR &&
9621 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9622 				/*
9623 				 * Don't print EDQUOT errors on the console.
9624 				 * Don't print asynchronous EACCES errors.
9625 				 * Don't print EFBIG errors.
9626 				 * Print all other write errors.
9627 				 */
9628 				if (error != EDQUOT && error != EFBIG &&
9629 				    (error != EACCES ||
9630 				    !(bp->b_flags & B_ASYNC)))
9631 					nfs4_write_error(bp->b_vp,
9632 					    error, cred_otw);
9633 				/*
9634 				 * Update r_error and r_flags as appropriate.
9635 				 * If the error was ESTALE, then mark the
9636 				 * rnode as not being writeable and save
9637 				 * the error status.  Otherwise, save any
9638 				 * errors which occur from asynchronous
9639 				 * page invalidations.  Any errors occurring
9640 				 * from other operations should be saved
9641 				 * by the caller.
9642 				 */
9643 				mutex_enter(&rp->r_statelock);
9644 				if (error == ESTALE) {
9645 					rp->r_flags |= R4STALE;
9646 					if (!rp->r_error)
9647 						rp->r_error = error;
9648 				} else if (!rp->r_error &&
9649 				    (bp->b_flags &
9650 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9651 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9652 					rp->r_error = error;
9653 				}
9654 				mutex_exit(&rp->r_statelock);
9655 			}
9656 			crfree(cred_otw);
9657 		} else {
9658 			error = rp->r_error;
9659 			/*
9660 			 * A close may have cleared r_error, if so,
9661 			 * propagate ESTALE error return properly
9662 			 */
9663 			if (error == 0)
9664 				error = ESTALE;
9665 		}
9666 	}
9667 
9668 	if (error != 0 && error != NFS_EOF)
9669 		bp->b_flags |= B_ERROR;
9670 
9671 	if (osp)
9672 		open_stream_rele(osp, rp);
9673 
9674 	DTRACE_IO1(done, struct buf *, bp);
9675 
9676 	return (error);
9677 }
9678 
9679 /* ARGSUSED */
9680 int
9681 nfs4_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
9682 {
9683 	return (EREMOTE);
9684 }
9685 
9686 /* ARGSUSED2 */
9687 int
9688 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9689 {
9690 	rnode4_t *rp = VTOR4(vp);
9691 
9692 	if (!write_lock) {
9693 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9694 		return (V_WRITELOCK_FALSE);
9695 	}
9696 
9697 	if ((rp->r_flags & R4DIRECTIO) ||
9698 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9699 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9700 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9701 			return (V_WRITELOCK_FALSE);
9702 		nfs_rw_exit(&rp->r_rwlock);
9703 	}
9704 
9705 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9706 	return (V_WRITELOCK_TRUE);
9707 }
9708 
9709 /* ARGSUSED */
9710 void
9711 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9712 {
9713 	rnode4_t *rp = VTOR4(vp);
9714 
9715 	nfs_rw_exit(&rp->r_rwlock);
9716 }
9717 
9718 /* ARGSUSED */
9719 static int
9720 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp, caller_context_t *ct)
9721 {
9722 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9723 		return (EIO);
9724 
9725 	/*
9726 	 * Because we stuff the readdir cookie into the offset field
9727 	 * someone may attempt to do an lseek with the cookie which
9728 	 * we want to succeed.
9729 	 */
9730 	if (vp->v_type == VDIR)
9731 		return (0);
9732 	if (*noffp < 0)
9733 		return (EINVAL);
9734 	return (0);
9735 }
9736 
9737 
9738 /*
9739  * Return all the pages from [off..off+len) in file
9740  */
9741 /* ARGSUSED */
9742 static int
9743 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9744     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9745     enum seg_rw rw, cred_t *cr, caller_context_t *ct)
9746 {
9747 	rnode4_t *rp;
9748 	int error;
9749 	mntinfo4_t *mi;
9750 
9751 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9752 		return (EIO);
9753 	rp = VTOR4(vp);
9754 	if (IS_SHADOW(vp, rp))
9755 		vp = RTOV4(rp);
9756 
9757 	if (vp->v_flag & VNOMAP)
9758 		return (ENOSYS);
9759 
9760 	if (protp != NULL)
9761 		*protp = PROT_ALL;
9762 
9763 	/*
9764 	 * Now validate that the caches are up to date.
9765 	 */
9766 	if (error = nfs4_validate_caches(vp, cr))
9767 		return (error);
9768 
9769 	mi = VTOMI4(vp);
9770 retry:
9771 	mutex_enter(&rp->r_statelock);
9772 
9773 	/*
9774 	 * Don't create dirty pages faster than they
9775 	 * can be cleaned so that the system doesn't
9776 	 * get imbalanced.  If the async queue is
9777 	 * maxed out, then wait for it to drain before
9778 	 * creating more dirty pages.  Also, wait for
9779 	 * any threads doing pagewalks in the vop_getattr
9780 	 * entry points so that they don't block for
9781 	 * long periods.
9782 	 */
9783 	if (rw == S_CREATE) {
9784 		while ((mi->mi_max_threads != 0 &&
9785 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
9786 		    rp->r_gcount > 0)
9787 			cv_wait(&rp->r_cv, &rp->r_statelock);
9788 	}
9789 
9790 	/*
9791 	 * If we are getting called as a side effect of an nfs_write()
9792 	 * operation the local file size might not be extended yet.
9793 	 * In this case we want to be able to return pages of zeroes.
9794 	 */
9795 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9796 		NFS4_DEBUG(nfs4_pageio_debug,
9797 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9798 		    "len=%llu, size=%llu, attrsize =%llu", off,
9799 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9800 		mutex_exit(&rp->r_statelock);
9801 		return (EFAULT);		/* beyond EOF */
9802 	}
9803 
9804 	mutex_exit(&rp->r_statelock);
9805 
9806 	error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9807 	    pl, plsz, seg, addr, rw, cr);
9808 	NFS4_DEBUG(nfs4_pageio_debug && error,
9809 	    (CE_NOTE, "getpages error %d; off=%lld, len=%lld",
9810 	    error, off, (u_longlong_t)len));
9811 
9812 	switch (error) {
9813 	case NFS_EOF:
9814 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9815 		goto retry;
9816 	case ESTALE:
9817 		nfs4_purge_stale_fh(error, vp, cr);
9818 	}
9819 
9820 	return (error);
9821 }
9822 
9823 /*
9824  * Called from pvn_getpages to get a particular page.
9825  */
9826 /* ARGSUSED */
9827 static int
9828 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9829     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9830     enum seg_rw rw, cred_t *cr)
9831 {
9832 	rnode4_t *rp;
9833 	uint_t bsize;
9834 	struct buf *bp;
9835 	page_t *pp;
9836 	u_offset_t lbn;
9837 	u_offset_t io_off;
9838 	u_offset_t blkoff;
9839 	u_offset_t rablkoff;
9840 	size_t io_len;
9841 	uint_t blksize;
9842 	int error;
9843 	int readahead;
9844 	int readahead_issued = 0;
9845 	int ra_window; /* readahead window */
9846 	page_t *pagefound;
9847 	page_t *savepp;
9848 
9849 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9850 		return (EIO);
9851 
9852 	rp = VTOR4(vp);
9853 	ASSERT(!IS_SHADOW(vp, rp));
9854 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9855 
9856 reread:
9857 	bp = NULL;
9858 	pp = NULL;
9859 	pagefound = NULL;
9860 
9861 	if (pl != NULL)
9862 		pl[0] = NULL;
9863 
9864 	error = 0;
9865 	lbn = off / bsize;
9866 	blkoff = lbn * bsize;
9867 
9868 	/*
9869 	 * Queueing up the readahead before doing the synchronous read
9870 	 * results in a significant increase in read throughput because
9871 	 * of the increased parallelism between the async threads and
9872 	 * the process context.
9873 	 */
9874 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9875 	    rw != S_CREATE &&
9876 	    !(vp->v_flag & VNOCACHE)) {
9877 		mutex_enter(&rp->r_statelock);
9878 
9879 		/*
9880 		 * Calculate the number of readaheads to do.
9881 		 * a) No readaheads at offset = 0.
9882 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9883 		 *    window is closed.
9884 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9885 		 *    upon how far the readahead window is open or close.
9886 		 * d) No readaheads if rp->r_nextr is not within the scope
9887 		 *    of the readahead window (random i/o).
9888 		 */
9889 
9890 		if (off == 0)
9891 			readahead = 0;
9892 		else if (blkoff == rp->r_nextr)
9893 			readahead = nfs4_nra;
9894 		else if (rp->r_nextr > blkoff &&
9895 		    ((ra_window = (rp->r_nextr - blkoff) / bsize)
9896 		    <= (nfs4_nra - 1)))
9897 			readahead = nfs4_nra - ra_window;
9898 		else
9899 			readahead = 0;
9900 
9901 		rablkoff = rp->r_nextr;
9902 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9903 			mutex_exit(&rp->r_statelock);
9904 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9905 			    addr + (rablkoff + bsize - off),
9906 			    seg, cr, nfs4_readahead) < 0) {
9907 				mutex_enter(&rp->r_statelock);
9908 				break;
9909 			}
9910 			readahead--;
9911 			rablkoff += bsize;
9912 			/*
9913 			 * Indicate that we did a readahead so
9914 			 * readahead offset is not updated
9915 			 * by the synchronous read below.
9916 			 */
9917 			readahead_issued = 1;
9918 			mutex_enter(&rp->r_statelock);
9919 			/*
9920 			 * set readahead offset to
9921 			 * offset of last async readahead
9922 			 * request.
9923 			 */
9924 			rp->r_nextr = rablkoff;
9925 		}
9926 		mutex_exit(&rp->r_statelock);
9927 	}
9928 
9929 again:
9930 	if ((pagefound = page_exists(vp, off)) == NULL) {
9931 		if (pl == NULL) {
9932 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9933 			    nfs4_readahead);
9934 		} else if (rw == S_CREATE) {
9935 			/*
9936 			 * Block for this page is not allocated, or the offset
9937 			 * is beyond the current allocation size, or we're
9938 			 * allocating a swap slot and the page was not found,
9939 			 * so allocate it and return a zero page.
9940 			 */
9941 			if ((pp = page_create_va(vp, off,
9942 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9943 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9944 			io_len = PAGESIZE;
9945 			mutex_enter(&rp->r_statelock);
9946 			rp->r_nextr = off + PAGESIZE;
9947 			mutex_exit(&rp->r_statelock);
9948 		} else {
9949 			/*
9950 			 * Need to go to server to get a block
9951 			 */
9952 			mutex_enter(&rp->r_statelock);
9953 			if (blkoff < rp->r_size &&
9954 			    blkoff + bsize > rp->r_size) {
9955 				/*
9956 				 * If less than a block left in
9957 				 * file read less than a block.
9958 				 */
9959 				if (rp->r_size <= off) {
9960 					/*
9961 					 * Trying to access beyond EOF,
9962 					 * set up to get at least one page.
9963 					 */
9964 					blksize = off + PAGESIZE - blkoff;
9965 				} else
9966 					blksize = rp->r_size - blkoff;
9967 			} else if ((off == 0) ||
9968 			    (off != rp->r_nextr && !readahead_issued)) {
9969 				blksize = PAGESIZE;
9970 				blkoff = off; /* block = page here */
9971 			} else
9972 				blksize = bsize;
9973 			mutex_exit(&rp->r_statelock);
9974 
9975 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9976 			    &io_len, blkoff, blksize, 0);
9977 
9978 			/*
9979 			 * Some other thread has entered the page,
9980 			 * so just use it.
9981 			 */
9982 			if (pp == NULL)
9983 				goto again;
9984 
9985 			/*
9986 			 * Now round the request size up to page boundaries.
9987 			 * This ensures that the entire page will be
9988 			 * initialized to zeroes if EOF is encountered.
9989 			 */
9990 			io_len = ptob(btopr(io_len));
9991 
9992 			bp = pageio_setup(pp, io_len, vp, B_READ);
9993 			ASSERT(bp != NULL);
9994 
9995 			/*
9996 			 * pageio_setup should have set b_addr to 0.  This
9997 			 * is correct since we want to do I/O on a page
9998 			 * boundary.  bp_mapin will use this addr to calculate
9999 			 * an offset, and then set b_addr to the kernel virtual
10000 			 * address it allocated for us.
10001 			 */
10002 			ASSERT(bp->b_un.b_addr == 0);
10003 
10004 			bp->b_edev = 0;
10005 			bp->b_dev = 0;
10006 			bp->b_lblkno = lbtodb(io_off);
10007 			bp->b_file = vp;
10008 			bp->b_offset = (offset_t)off;
10009 			bp_mapin(bp);
10010 
10011 			/*
10012 			 * If doing a write beyond what we believe is EOF,
10013 			 * don't bother trying to read the pages from the
10014 			 * server, we'll just zero the pages here.  We
10015 			 * don't check that the rw flag is S_WRITE here
10016 			 * because some implementations may attempt a
10017 			 * read access to the buffer before copying data.
10018 			 */
10019 			mutex_enter(&rp->r_statelock);
10020 			if (io_off >= rp->r_size && seg == segkmap) {
10021 				mutex_exit(&rp->r_statelock);
10022 				bzero(bp->b_un.b_addr, io_len);
10023 			} else {
10024 				mutex_exit(&rp->r_statelock);
10025 				error = nfs4_bio(bp, NULL, cr, FALSE);
10026 			}
10027 
10028 			/*
10029 			 * Unmap the buffer before freeing it.
10030 			 */
10031 			bp_mapout(bp);
10032 			pageio_done(bp);
10033 
10034 			savepp = pp;
10035 			do {
10036 				pp->p_fsdata = C_NOCOMMIT;
10037 			} while ((pp = pp->p_next) != savepp);
10038 
10039 			if (error == NFS_EOF) {
10040 				/*
10041 				 * If doing a write system call just return
10042 				 * zeroed pages, else user tried to get pages
10043 				 * beyond EOF, return error.  We don't check
10044 				 * that the rw flag is S_WRITE here because
10045 				 * some implementations may attempt a read
10046 				 * access to the buffer before copying data.
10047 				 */
10048 				if (seg == segkmap)
10049 					error = 0;
10050 				else
10051 					error = EFAULT;
10052 			}
10053 
10054 			if (!readahead_issued && !error) {
10055 				mutex_enter(&rp->r_statelock);
10056 				rp->r_nextr = io_off + io_len;
10057 				mutex_exit(&rp->r_statelock);
10058 			}
10059 		}
10060 	}
10061 
10062 out:
10063 	if (pl == NULL)
10064 		return (error);
10065 
10066 	if (error) {
10067 		if (pp != NULL)
10068 			pvn_read_done(pp, B_ERROR);
10069 		return (error);
10070 	}
10071 
10072 	if (pagefound) {
10073 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
10074 
10075 		/*
10076 		 * Page exists in the cache, acquire the appropriate lock.
10077 		 * If this fails, start all over again.
10078 		 */
10079 		if ((pp = page_lookup(vp, off, se)) == NULL) {
10080 #ifdef DEBUG
10081 			nfs4_lostpage++;
10082 #endif
10083 			goto reread;
10084 		}
10085 		pl[0] = pp;
10086 		pl[1] = NULL;
10087 		return (0);
10088 	}
10089 
10090 	if (pp != NULL)
10091 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
10092 
10093 	return (error);
10094 }
10095 
10096 static void
10097 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
10098     cred_t *cr)
10099 {
10100 	int error;
10101 	page_t *pp;
10102 	u_offset_t io_off;
10103 	size_t io_len;
10104 	struct buf *bp;
10105 	uint_t bsize, blksize;
10106 	rnode4_t *rp = VTOR4(vp);
10107 	page_t *savepp;
10108 
10109 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10110 
10111 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10112 
10113 	mutex_enter(&rp->r_statelock);
10114 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
10115 		/*
10116 		 * If less than a block left in file read less
10117 		 * than a block.
10118 		 */
10119 		blksize = rp->r_size - blkoff;
10120 	} else
10121 		blksize = bsize;
10122 	mutex_exit(&rp->r_statelock);
10123 
10124 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
10125 	    &io_off, &io_len, blkoff, blksize, 1);
10126 	/*
10127 	 * The isra flag passed to the kluster function is 1, we may have
10128 	 * gotten a return value of NULL for a variety of reasons (# of free
10129 	 * pages < minfree, someone entered the page on the vnode etc). In all
10130 	 * cases, we want to punt on the readahead.
10131 	 */
10132 	if (pp == NULL)
10133 		return;
10134 
10135 	/*
10136 	 * Now round the request size up to page boundaries.
10137 	 * This ensures that the entire page will be
10138 	 * initialized to zeroes if EOF is encountered.
10139 	 */
10140 	io_len = ptob(btopr(io_len));
10141 
10142 	bp = pageio_setup(pp, io_len, vp, B_READ);
10143 	ASSERT(bp != NULL);
10144 
10145 	/*
10146 	 * pageio_setup should have set b_addr to 0.  This is correct since
10147 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10148 	 * to calculate an offset, and then set b_addr to the kernel virtual
10149 	 * address it allocated for us.
10150 	 */
10151 	ASSERT(bp->b_un.b_addr == 0);
10152 
10153 	bp->b_edev = 0;
10154 	bp->b_dev = 0;
10155 	bp->b_lblkno = lbtodb(io_off);
10156 	bp->b_file = vp;
10157 	bp->b_offset = (offset_t)blkoff;
10158 	bp_mapin(bp);
10159 
10160 	/*
10161 	 * If doing a write beyond what we believe is EOF, don't bother trying
10162 	 * to read the pages from the server, we'll just zero the pages here.
10163 	 * We don't check that the rw flag is S_WRITE here because some
10164 	 * implementations may attempt a read access to the buffer before
10165 	 * copying data.
10166 	 */
10167 	mutex_enter(&rp->r_statelock);
10168 	if (io_off >= rp->r_size && seg == segkmap) {
10169 		mutex_exit(&rp->r_statelock);
10170 		bzero(bp->b_un.b_addr, io_len);
10171 		error = 0;
10172 	} else {
10173 		mutex_exit(&rp->r_statelock);
10174 		error = nfs4_bio(bp, NULL, cr, TRUE);
10175 		if (error == NFS_EOF)
10176 			error = 0;
10177 	}
10178 
10179 	/*
10180 	 * Unmap the buffer before freeing it.
10181 	 */
10182 	bp_mapout(bp);
10183 	pageio_done(bp);
10184 
10185 	savepp = pp;
10186 	do {
10187 		pp->p_fsdata = C_NOCOMMIT;
10188 	} while ((pp = pp->p_next) != savepp);
10189 
10190 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10191 
10192 	/*
10193 	 * In case of error set readahead offset
10194 	 * to the lowest offset.
10195 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10196 	 */
10197 	if (error && rp->r_nextr > io_off) {
10198 		mutex_enter(&rp->r_statelock);
10199 		if (rp->r_nextr > io_off)
10200 			rp->r_nextr = io_off;
10201 		mutex_exit(&rp->r_statelock);
10202 	}
10203 }
10204 
10205 /*
10206  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10207  * If len == 0, do from off to EOF.
10208  *
10209  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10210  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10211  * (from pageout).
10212  */
10213 /* ARGSUSED */
10214 static int
10215 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
10216     caller_context_t *ct)
10217 {
10218 	int error;
10219 	rnode4_t *rp;
10220 
10221 	ASSERT(cr != NULL);
10222 
10223 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10224 		return (EIO);
10225 
10226 	rp = VTOR4(vp);
10227 	if (IS_SHADOW(vp, rp))
10228 		vp = RTOV4(rp);
10229 
10230 	/*
10231 	 * XXX - Why should this check be made here?
10232 	 */
10233 	if (vp->v_flag & VNOMAP)
10234 		return (ENOSYS);
10235 
10236 	if (len == 0 && !(flags & B_INVAL) &&
10237 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10238 		return (0);
10239 
10240 	mutex_enter(&rp->r_statelock);
10241 	rp->r_count++;
10242 	mutex_exit(&rp->r_statelock);
10243 	error = nfs4_putpages(vp, off, len, flags, cr);
10244 	mutex_enter(&rp->r_statelock);
10245 	rp->r_count--;
10246 	cv_broadcast(&rp->r_cv);
10247 	mutex_exit(&rp->r_statelock);
10248 
10249 	return (error);
10250 }
10251 
10252 /*
10253  * Write out a single page, possibly klustering adjacent dirty pages.
10254  */
10255 int
10256 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10257     int flags, cred_t *cr)
10258 {
10259 	u_offset_t io_off;
10260 	u_offset_t lbn_off;
10261 	u_offset_t lbn;
10262 	size_t io_len;
10263 	uint_t bsize;
10264 	int error;
10265 	rnode4_t *rp;
10266 
10267 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10268 	ASSERT(pp != NULL);
10269 	ASSERT(cr != NULL);
10270 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10271 
10272 	rp = VTOR4(vp);
10273 	ASSERT(rp->r_count > 0);
10274 	ASSERT(!IS_SHADOW(vp, rp));
10275 
10276 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10277 	lbn = pp->p_offset / bsize;
10278 	lbn_off = lbn * bsize;
10279 
10280 	/*
10281 	 * Find a kluster that fits in one block, or in
10282 	 * one page if pages are bigger than blocks.  If
10283 	 * there is less file space allocated than a whole
10284 	 * page, we'll shorten the i/o request below.
10285 	 */
10286 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10287 	    roundup(bsize, PAGESIZE), flags);
10288 
10289 	/*
10290 	 * pvn_write_kluster shouldn't have returned a page with offset
10291 	 * behind the original page we were given.  Verify that.
10292 	 */
10293 	ASSERT((pp->p_offset / bsize) >= lbn);
10294 
10295 	/*
10296 	 * Now pp will have the list of kept dirty pages marked for
10297 	 * write back.  It will also handle invalidation and freeing
10298 	 * of pages that are not dirty.  Check for page length rounding
10299 	 * problems.
10300 	 */
10301 	if (io_off + io_len > lbn_off + bsize) {
10302 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10303 		io_len = lbn_off + bsize - io_off;
10304 	}
10305 	/*
10306 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10307 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10308 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10309 	 * progress and the r_size has not been made consistent with the
10310 	 * new size of the file. When the uiomove() completes the r_size is
10311 	 * updated and the R4MODINPROGRESS flag is cleared.
10312 	 *
10313 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10314 	 * consistent value of r_size. Without this handshaking, it is
10315 	 * possible that nfs4_bio() picks  up the old value of r_size
10316 	 * before the uiomove() in writerp4() completes. This will result
10317 	 * in the write through nfs4_bio() being dropped.
10318 	 *
10319 	 * More precisely, there is a window between the time the uiomove()
10320 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10321 	 * operation intervenes in this window, the page will be picked up,
10322 	 * because it is dirty (it will be unlocked, unless it was
10323 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10324 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10325 	 * checked. This will still be the old size. Therefore the page will
10326 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10327 	 * the page will be found to be clean and the write will be dropped.
10328 	 */
10329 	if (rp->r_flags & R4MODINPROGRESS) {
10330 		mutex_enter(&rp->r_statelock);
10331 		if ((rp->r_flags & R4MODINPROGRESS) &&
10332 		    rp->r_modaddr + MAXBSIZE > io_off &&
10333 		    rp->r_modaddr < io_off + io_len) {
10334 			page_t *plist;
10335 			/*
10336 			 * A write is in progress for this region of the file.
10337 			 * If we did not detect R4MODINPROGRESS here then this
10338 			 * path through nfs_putapage() would eventually go to
10339 			 * nfs4_bio() and may not write out all of the data
10340 			 * in the pages. We end up losing data. So we decide
10341 			 * to set the modified bit on each page in the page
10342 			 * list and mark the rnode with R4DIRTY. This write
10343 			 * will be restarted at some later time.
10344 			 */
10345 			plist = pp;
10346 			while (plist != NULL) {
10347 				pp = plist;
10348 				page_sub(&plist, pp);
10349 				hat_setmod(pp);
10350 				page_io_unlock(pp);
10351 				page_unlock(pp);
10352 			}
10353 			rp->r_flags |= R4DIRTY;
10354 			mutex_exit(&rp->r_statelock);
10355 			if (offp)
10356 				*offp = io_off;
10357 			if (lenp)
10358 				*lenp = io_len;
10359 			return (0);
10360 		}
10361 		mutex_exit(&rp->r_statelock);
10362 	}
10363 
10364 	if (flags & B_ASYNC) {
10365 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10366 		    nfs4_sync_putapage);
10367 	} else
10368 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10369 
10370 	if (offp)
10371 		*offp = io_off;
10372 	if (lenp)
10373 		*lenp = io_len;
10374 	return (error);
10375 }
10376 
10377 static int
10378 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10379     int flags, cred_t *cr)
10380 {
10381 	int error;
10382 	rnode4_t *rp;
10383 
10384 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10385 
10386 	flags |= B_WRITE;
10387 
10388 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10389 
10390 	rp = VTOR4(vp);
10391 
10392 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10393 	    error == EACCES) &&
10394 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10395 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10396 			mutex_enter(&rp->r_statelock);
10397 			rp->r_flags |= R4OUTOFSPACE;
10398 			mutex_exit(&rp->r_statelock);
10399 		}
10400 		flags |= B_ERROR;
10401 		pvn_write_done(pp, flags);
10402 		/*
10403 		 * If this was not an async thread, then try again to
10404 		 * write out the pages, but this time, also destroy
10405 		 * them whether or not the write is successful.  This
10406 		 * will prevent memory from filling up with these
10407 		 * pages and destroying them is the only alternative
10408 		 * if they can't be written out.
10409 		 *
10410 		 * Don't do this if this is an async thread because
10411 		 * when the pages are unlocked in pvn_write_done,
10412 		 * some other thread could have come along, locked
10413 		 * them, and queued for an async thread.  It would be
10414 		 * possible for all of the async threads to be tied
10415 		 * up waiting to lock the pages again and they would
10416 		 * all already be locked and waiting for an async
10417 		 * thread to handle them.  Deadlock.
10418 		 */
10419 		if (!(flags & B_ASYNC)) {
10420 			error = nfs4_putpage(vp, io_off, io_len,
10421 			    B_INVAL | B_FORCE, cr, NULL);
10422 		}
10423 	} else {
10424 		if (error)
10425 			flags |= B_ERROR;
10426 		else if (rp->r_flags & R4OUTOFSPACE) {
10427 			mutex_enter(&rp->r_statelock);
10428 			rp->r_flags &= ~R4OUTOFSPACE;
10429 			mutex_exit(&rp->r_statelock);
10430 		}
10431 		pvn_write_done(pp, flags);
10432 		if (freemem < desfree)
10433 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10434 			    NFS4_WRITE_NOWAIT);
10435 	}
10436 
10437 	return (error);
10438 }
10439 
10440 #ifdef DEBUG
10441 int nfs4_force_open_before_mmap = 0;
10442 #endif
10443 
10444 /* ARGSUSED */
10445 static int
10446 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10447     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10448     caller_context_t *ct)
10449 {
10450 	struct segvn_crargs vn_a;
10451 	int error = 0;
10452 	rnode4_t *rp = VTOR4(vp);
10453 	mntinfo4_t *mi = VTOMI4(vp);
10454 
10455 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10456 		return (EIO);
10457 
10458 	if (vp->v_flag & VNOMAP)
10459 		return (ENOSYS);
10460 
10461 	if (off < 0 || (off + len) < 0)
10462 		return (ENXIO);
10463 
10464 	if (vp->v_type != VREG)
10465 		return (ENODEV);
10466 
10467 	/*
10468 	 * If the file is delegated to the client don't do anything.
10469 	 * If the file is not delegated, then validate the data cache.
10470 	 */
10471 	mutex_enter(&rp->r_statev4_lock);
10472 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10473 		mutex_exit(&rp->r_statev4_lock);
10474 		error = nfs4_validate_caches(vp, cr);
10475 		if (error)
10476 			return (error);
10477 	} else {
10478 		mutex_exit(&rp->r_statev4_lock);
10479 	}
10480 
10481 	/*
10482 	 * Check to see if the vnode is currently marked as not cachable.
10483 	 * This means portions of the file are locked (through VOP_FRLOCK).
10484 	 * In this case the map request must be refused.  We use
10485 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10486 	 *
10487 	 * Atomically increment r_inmap after acquiring r_rwlock. The
10488 	 * idea here is to acquire r_rwlock to block read/write and
10489 	 * not to protect r_inmap. r_inmap will inform nfs4_read/write()
10490 	 * that we are in nfs4_map(). Now, r_rwlock is acquired in order
10491 	 * and we can prevent the deadlock that would have occurred
10492 	 * when nfs4_addmap() would have acquired it out of order.
10493 	 *
10494 	 * Since we are not protecting r_inmap by any lock, we do not
10495 	 * hold any lock when we decrement it. We atomically decrement
10496 	 * r_inmap after we release r_lkserlock.
10497 	 */
10498 
10499 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR4(vp)))
10500 		return (EINTR);
10501 	atomic_inc_uint(&rp->r_inmap);
10502 	nfs_rw_exit(&rp->r_rwlock);
10503 
10504 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp))) {
10505 		atomic_dec_uint(&rp->r_inmap);
10506 		return (EINTR);
10507 	}
10508 
10509 	if (vp->v_flag & VNOCACHE) {
10510 		error = EAGAIN;
10511 		goto done;
10512 	}
10513 
10514 	/*
10515 	 * Don't allow concurrent locks and mapping if mandatory locking is
10516 	 * enabled.
10517 	 */
10518 	if (flk_has_remote_locks(vp)) {
10519 		struct vattr va;
10520 		va.va_mask = AT_MODE;
10521 		error = nfs4getattr(vp, &va, cr);
10522 		if (error != 0)
10523 			goto done;
10524 		if (MANDLOCK(vp, va.va_mode)) {
10525 			error = EAGAIN;
10526 			goto done;
10527 		}
10528 	}
10529 
10530 	/*
10531 	 * It is possible that the rnode has a lost lock request that we
10532 	 * are still trying to recover, and that the request conflicts with
10533 	 * this map request.
10534 	 *
10535 	 * An alternative approach would be for nfs4_safemap() to consider
10536 	 * queued lock requests when deciding whether to set or clear
10537 	 * VNOCACHE.  This would require the frlock code path to call
10538 	 * nfs4_safemap() after enqueing a lost request.
10539 	 */
10540 	if (nfs4_map_lost_lock_conflict(vp)) {
10541 		error = EAGAIN;
10542 		goto done;
10543 	}
10544 
10545 	as_rangelock(as);
10546 	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
10547 	if (error != 0) {
10548 		as_rangeunlock(as);
10549 		goto done;
10550 	}
10551 
10552 	if (vp->v_type == VREG) {
10553 		/*
10554 		 * We need to retrieve the open stream
10555 		 */
10556 		nfs4_open_stream_t	*osp = NULL;
10557 		nfs4_open_owner_t	*oop = NULL;
10558 
10559 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10560 		if (oop != NULL) {
10561 			/* returns with 'os_sync_lock' held */
10562 			osp = find_open_stream(oop, rp);
10563 			open_owner_rele(oop);
10564 		}
10565 		if (osp == NULL) {
10566 #ifdef DEBUG
10567 			if (nfs4_force_open_before_mmap) {
10568 				error = EIO;
10569 				goto done;
10570 			}
10571 #endif
10572 			/* returns with 'os_sync_lock' held */
10573 			error = open_and_get_osp(vp, cr, &osp);
10574 			if (osp == NULL) {
10575 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10576 				    "nfs4_map: we tried to OPEN the file "
10577 				    "but again no osp, so fail with EIO"));
10578 				goto done;
10579 			}
10580 		}
10581 
10582 		if (osp->os_failed_reopen) {
10583 			mutex_exit(&osp->os_sync_lock);
10584 			open_stream_rele(osp, rp);
10585 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10586 			    "nfs4_map: os_failed_reopen set on "
10587 			    "osp %p, cr %p, rp %s", (void *)osp,
10588 			    (void *)cr, rnode4info(rp)));
10589 			error = EIO;
10590 			goto done;
10591 		}
10592 		mutex_exit(&osp->os_sync_lock);
10593 		open_stream_rele(osp, rp);
10594 	}
10595 
10596 	vn_a.vp = vp;
10597 	vn_a.offset = off;
10598 	vn_a.type = (flags & MAP_TYPE);
10599 	vn_a.prot = (uchar_t)prot;
10600 	vn_a.maxprot = (uchar_t)maxprot;
10601 	vn_a.flags = (flags & ~MAP_TYPE);
10602 	vn_a.cred = cr;
10603 	vn_a.amp = NULL;
10604 	vn_a.szc = 0;
10605 	vn_a.lgrp_mem_policy_flags = 0;
10606 
10607 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10608 	as_rangeunlock(as);
10609 
10610 done:
10611 	nfs_rw_exit(&rp->r_lkserlock);
10612 	atomic_dec_uint(&rp->r_inmap);
10613 	return (error);
10614 }
10615 
10616 /*
10617  * We're most likely dealing with a kernel module that likes to READ
10618  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10619  * officially OPEN the file to create the necessary client state
10620  * for bookkeeping of os_mmap_read/write counts.
10621  *
10622  * Since VOP_MAP only passes in a pointer to the vnode rather than
10623  * a double pointer, we can't handle the case where nfs4open_otw()
10624  * returns a different vnode than the one passed into VOP_MAP (since
10625  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10626  * we return NULL and let nfs4_map() fail.  Note: the only case where
10627  * this should happen is if the file got removed and replaced with the
10628  * same name on the server (in addition to the fact that we're trying
10629  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10630  */
10631 static int
10632 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10633 {
10634 	rnode4_t		*rp, *drp;
10635 	vnode_t			*dvp, *open_vp;
10636 	char			file_name[MAXNAMELEN];
10637 	int			just_created;
10638 	nfs4_open_stream_t	*osp;
10639 	nfs4_open_owner_t	*oop;
10640 	int			error;
10641 
10642 	*ospp = NULL;
10643 	open_vp = map_vp;
10644 
10645 	rp = VTOR4(open_vp);
10646 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10647 		return (error);
10648 	drp = VTOR4(dvp);
10649 
10650 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10651 		VN_RELE(dvp);
10652 		return (EINTR);
10653 	}
10654 
10655 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10656 		nfs_rw_exit(&drp->r_rwlock);
10657 		VN_RELE(dvp);
10658 		return (error);
10659 	}
10660 
10661 	mutex_enter(&rp->r_statev4_lock);
10662 	if (rp->created_v4) {
10663 		rp->created_v4 = 0;
10664 		mutex_exit(&rp->r_statev4_lock);
10665 
10666 		dnlc_update(dvp, file_name, open_vp);
10667 		/* This is needed so we don't bump the open ref count */
10668 		just_created = 1;
10669 	} else {
10670 		mutex_exit(&rp->r_statev4_lock);
10671 		just_created = 0;
10672 	}
10673 
10674 	VN_HOLD(map_vp);
10675 
10676 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10677 	    just_created);
10678 	if (error) {
10679 		nfs_rw_exit(&drp->r_rwlock);
10680 		VN_RELE(dvp);
10681 		VN_RELE(map_vp);
10682 		return (error);
10683 	}
10684 
10685 	nfs_rw_exit(&drp->r_rwlock);
10686 	VN_RELE(dvp);
10687 
10688 	/*
10689 	 * If nfs4open_otw() returned a different vnode then "undo"
10690 	 * the open and return failure to the caller.
10691 	 */
10692 	if (!VN_CMP(open_vp, map_vp)) {
10693 		nfs4_error_t e;
10694 
10695 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10696 		    "open returned a different vnode"));
10697 		/*
10698 		 * If there's an error, ignore it,
10699 		 * and let VOP_INACTIVE handle it.
10700 		 */
10701 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10702 		    CLOSE_NORM, 0, 0, 0);
10703 		VN_RELE(map_vp);
10704 		return (EIO);
10705 	}
10706 
10707 	VN_RELE(map_vp);
10708 
10709 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10710 	if (!oop) {
10711 		nfs4_error_t e;
10712 
10713 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10714 		    "no open owner"));
10715 		/*
10716 		 * If there's an error, ignore it,
10717 		 * and let VOP_INACTIVE handle it.
10718 		 */
10719 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10720 		    CLOSE_NORM, 0, 0, 0);
10721 		return (EIO);
10722 	}
10723 	osp = find_open_stream(oop, rp);
10724 	open_owner_rele(oop);
10725 	*ospp = osp;
10726 	return (0);
10727 }
10728 
10729 /*
10730  * Please be aware that when this function is called, the address space write
10731  * a_lock is held.  Do not put over the wire calls in this function.
10732  */
10733 /* ARGSUSED */
10734 static int
10735 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10736     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10737     caller_context_t *ct)
10738 {
10739 	rnode4_t		*rp;
10740 	int			error = 0;
10741 	mntinfo4_t		*mi;
10742 
10743 	mi = VTOMI4(vp);
10744 	rp = VTOR4(vp);
10745 
10746 	if (nfs_zone() != mi->mi_zone)
10747 		return (EIO);
10748 	if (vp->v_flag & VNOMAP)
10749 		return (ENOSYS);
10750 
10751 	/*
10752 	 * Don't need to update the open stream first, since this
10753 	 * mmap can't add any additional share access that isn't
10754 	 * already contained in the open stream (for the case where we
10755 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10756 	 * take into account os_mmap_read[write] counts).
10757 	 */
10758 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10759 
10760 	if (vp->v_type == VREG) {
10761 		/*
10762 		 * We need to retrieve the open stream and update the counts.
10763 		 * If there is no open stream here, something is wrong.
10764 		 */
10765 		nfs4_open_stream_t	*osp = NULL;
10766 		nfs4_open_owner_t	*oop = NULL;
10767 
10768 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10769 		if (oop != NULL) {
10770 			/* returns with 'os_sync_lock' held */
10771 			osp = find_open_stream(oop, rp);
10772 			open_owner_rele(oop);
10773 		}
10774 		if (osp == NULL) {
10775 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10776 			    "nfs4_addmap: we should have an osp"
10777 			    "but we don't, so fail with EIO"));
10778 			error = EIO;
10779 			goto out;
10780 		}
10781 
10782 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10783 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10784 
10785 		/*
10786 		 * Update the map count in the open stream.
10787 		 * This is necessary in the case where we
10788 		 * open/mmap/close/, then the server reboots, and we
10789 		 * attempt to reopen.  If the mmap doesn't add share
10790 		 * access then we send an invalid reopen with
10791 		 * access = NONE.
10792 		 *
10793 		 * We need to specifically check each PROT_* so a mmap
10794 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10795 		 * read and write access.  A simple comparison of prot
10796 		 * to ~PROT_WRITE to determine read access is insufficient
10797 		 * since prot can be |= with PROT_USER, etc.
10798 		 */
10799 
10800 		/*
10801 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10802 		 */
10803 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10804 			osp->os_mmap_write += btopr(len);
10805 		if (maxprot & PROT_READ)
10806 			osp->os_mmap_read += btopr(len);
10807 		if (maxprot & PROT_EXEC)
10808 			osp->os_mmap_read += btopr(len);
10809 		/*
10810 		 * Ensure that os_mmap_read gets incremented, even if
10811 		 * maxprot were to look like PROT_NONE.
10812 		 */
10813 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10814 		    !(maxprot & PROT_EXEC))
10815 			osp->os_mmap_read += btopr(len);
10816 		osp->os_mapcnt += btopr(len);
10817 		mutex_exit(&osp->os_sync_lock);
10818 		open_stream_rele(osp, rp);
10819 	}
10820 
10821 out:
10822 	/*
10823 	 * If we got an error, then undo our
10824 	 * incrementing of 'r_mapcnt'.
10825 	 */
10826 
10827 	if (error) {
10828 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10829 		ASSERT(rp->r_mapcnt >= 0);
10830 	}
10831 	return (error);
10832 }
10833 
10834 /* ARGSUSED */
10835 static int
10836 nfs4_cmp(vnode_t *vp1, vnode_t *vp2, caller_context_t *ct)
10837 {
10838 
10839 	return (VTOR4(vp1) == VTOR4(vp2));
10840 }
10841 
10842 /* ARGSUSED */
10843 static int
10844 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10845     offset_t offset, struct flk_callback *flk_cbp, cred_t *cr,
10846     caller_context_t *ct)
10847 {
10848 	int rc;
10849 	u_offset_t start, end;
10850 	rnode4_t *rp;
10851 	int error = 0, intr = INTR4(vp);
10852 	nfs4_error_t e;
10853 
10854 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10855 		return (EIO);
10856 
10857 	/* check for valid cmd parameter */
10858 	if (cmd != F_GETLK && cmd != F_SETLK && cmd != F_SETLKW)
10859 		return (EINVAL);
10860 
10861 	/* Verify l_type. */
10862 	switch (bfp->l_type) {
10863 	case F_RDLCK:
10864 		if (cmd != F_GETLK && !(flag & FREAD))
10865 			return (EBADF);
10866 		break;
10867 	case F_WRLCK:
10868 		if (cmd != F_GETLK && !(flag & FWRITE))
10869 			return (EBADF);
10870 		break;
10871 	case F_UNLCK:
10872 		intr = 0;
10873 		break;
10874 
10875 	default:
10876 		return (EINVAL);
10877 	}
10878 
10879 	/* check the validity of the lock range */
10880 	if (rc = flk_convert_lock_data(vp, bfp, &start, &end, offset))
10881 		return (rc);
10882 	if (rc = flk_check_lock_data(start, end, MAXEND))
10883 		return (rc);
10884 
10885 	/*
10886 	 * If the filesystem is mounted using local locking, pass the
10887 	 * request off to the local locking code.
10888 	 */
10889 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10890 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10891 			/*
10892 			 * For complete safety, we should be holding
10893 			 * r_lkserlock.  However, we can't call
10894 			 * nfs4_safelock and then fs_frlock while
10895 			 * holding r_lkserlock, so just invoke
10896 			 * nfs4_safelock and expect that this will
10897 			 * catch enough of the cases.
10898 			 */
10899 			if (!nfs4_safelock(vp, bfp, cr))
10900 				return (EAGAIN);
10901 		}
10902 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
10903 	}
10904 
10905 	rp = VTOR4(vp);
10906 
10907 	/*
10908 	 * Check whether the given lock request can proceed, given the
10909 	 * current file mappings.
10910 	 */
10911 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr))
10912 		return (EINTR);
10913 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10914 		if (!nfs4_safelock(vp, bfp, cr)) {
10915 			rc = EAGAIN;
10916 			goto done;
10917 		}
10918 	}
10919 
10920 	/*
10921 	 * Flush the cache after waiting for async I/O to finish.  For new
10922 	 * locks, this is so that the process gets the latest bits from the
10923 	 * server.  For unlocks, this is so that other clients see the
10924 	 * latest bits once the file has been unlocked.  If currently dirty
10925 	 * pages can't be flushed, then don't allow a lock to be set.  But
10926 	 * allow unlocks to succeed, to avoid having orphan locks on the
10927 	 * server.
10928 	 */
10929 	if (cmd != F_GETLK) {
10930 		mutex_enter(&rp->r_statelock);
10931 		while (rp->r_count > 0) {
10932 			if (intr) {
10933 				klwp_t *lwp = ttolwp(curthread);
10934 
10935 				if (lwp != NULL)
10936 					lwp->lwp_nostop++;
10937 				if (cv_wait_sig(&rp->r_cv,
10938 				    &rp->r_statelock) == 0) {
10939 					if (lwp != NULL)
10940 						lwp->lwp_nostop--;
10941 					rc = EINTR;
10942 					break;
10943 				}
10944 				if (lwp != NULL)
10945 					lwp->lwp_nostop--;
10946 			} else {
10947 				cv_wait(&rp->r_cv, &rp->r_statelock);
10948 			}
10949 		}
10950 		mutex_exit(&rp->r_statelock);
10951 		if (rc != 0)
10952 			goto done;
10953 		error = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr, ct);
10954 		if (error) {
10955 			if (error == ENOSPC || error == EDQUOT) {
10956 				mutex_enter(&rp->r_statelock);
10957 				if (!rp->r_error)
10958 					rp->r_error = error;
10959 				mutex_exit(&rp->r_statelock);
10960 			}
10961 			if (bfp->l_type != F_UNLCK) {
10962 				rc = ENOLCK;
10963 				goto done;
10964 			}
10965 		}
10966 	}
10967 
10968 	/*
10969 	 * Call the lock manager to do the real work of contacting
10970 	 * the server and obtaining the lock.
10971 	 */
10972 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, flag, offset,
10973 	    cr, &e, NULL, NULL);
10974 	rc = e.error;
10975 
10976 	if (rc == 0)
10977 		nfs4_lockcompletion(vp, cmd);
10978 
10979 done:
10980 	nfs_rw_exit(&rp->r_lkserlock);
10981 
10982 	return (rc);
10983 }
10984 
10985 /*
10986  * Free storage space associated with the specified vnode.  The portion
10987  * to be freed is specified by bfp->l_start and bfp->l_len (already
10988  * normalized to a "whence" of 0).
10989  *
10990  * This is an experimental facility whose continued existence is not
10991  * guaranteed.  Currently, we only support the special case
10992  * of l_len == 0, meaning free to end of file.
10993  */
10994 /* ARGSUSED */
10995 static int
10996 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10997     offset_t offset, cred_t *cr, caller_context_t *ct)
10998 {
10999 	int error;
11000 
11001 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11002 		return (EIO);
11003 	ASSERT(vp->v_type == VREG);
11004 	if (cmd != F_FREESP)
11005 		return (EINVAL);
11006 
11007 	error = convoff(vp, bfp, 0, offset);
11008 	if (!error) {
11009 		ASSERT(bfp->l_start >= 0);
11010 		if (bfp->l_len == 0) {
11011 			struct vattr va;
11012 
11013 			va.va_mask = AT_SIZE;
11014 			va.va_size = bfp->l_start;
11015 			error = nfs4setattr(vp, &va, 0, cr, NULL);
11016 
11017 			if (error == 0 && bfp->l_start == 0)
11018 				vnevent_truncate(vp, ct);
11019 		} else
11020 			error = EINVAL;
11021 	}
11022 
11023 	return (error);
11024 }
11025 
11026 /* ARGSUSED */
11027 int
11028 nfs4_realvp(vnode_t *vp, vnode_t **vpp, caller_context_t *ct)
11029 {
11030 	rnode4_t *rp;
11031 	rp = VTOR4(vp);
11032 
11033 	if (vp->v_type == VREG && IS_SHADOW(vp, rp)) {
11034 		vp = RTOV4(rp);
11035 	}
11036 	*vpp = vp;
11037 	return (0);
11038 }
11039 
11040 /*
11041  * Setup and add an address space callback to do the work of the delmap call.
11042  * The callback will (and must be) deleted in the actual callback function.
11043  *
11044  * This is done in order to take care of the problem that we have with holding
11045  * the address space's a_lock for a long period of time (e.g. if the NFS server
11046  * is down).  Callbacks will be executed in the address space code while the
11047  * a_lock is not held.  Holding the address space's a_lock causes things such
11048  * as ps and fork to hang because they are trying to acquire this lock as well.
11049  */
11050 /* ARGSUSED */
11051 static int
11052 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
11053     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
11054     caller_context_t *ct)
11055 {
11056 	int			caller_found;
11057 	int			error;
11058 	rnode4_t		*rp;
11059 	nfs4_delmap_args_t	*dmapp;
11060 	nfs4_delmapcall_t	*delmap_call;
11061 
11062 	if (vp->v_flag & VNOMAP)
11063 		return (ENOSYS);
11064 
11065 	/*
11066 	 * A process may not change zones if it has NFS pages mmap'ed
11067 	 * in, so we can't legitimately get here from the wrong zone.
11068 	 */
11069 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11070 
11071 	rp = VTOR4(vp);
11072 
11073 	/*
11074 	 * The way that the address space of this process deletes its mapping
11075 	 * of this file is via the following call chains:
11076 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11077 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11078 	 *
11079 	 * With the use of address space callbacks we are allowed to drop the
11080 	 * address space lock, a_lock, while executing the NFS operations that
11081 	 * need to go over the wire.  Returning EAGAIN to the caller of this
11082 	 * function is what drives the execution of the callback that we add
11083 	 * below.  The callback will be executed by the address space code
11084 	 * after dropping the a_lock.  When the callback is finished, since
11085 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
11086 	 * is called again on the same segment to finish the rest of the work
11087 	 * that needs to happen during unmapping.
11088 	 *
11089 	 * This action of calling back into the segment driver causes
11090 	 * nfs4_delmap() to get called again, but since the callback was
11091 	 * already executed at this point, it already did the work and there
11092 	 * is nothing left for us to do.
11093 	 *
11094 	 * To Summarize:
11095 	 * - The first time nfs4_delmap is called by the current thread is when
11096 	 * we add the caller associated with this delmap to the delmap caller
11097 	 * list, add the callback, and return EAGAIN.
11098 	 * - The second time in this call chain when nfs4_delmap is called we
11099 	 * will find this caller in the delmap caller list and realize there
11100 	 * is no more work to do thus removing this caller from the list and
11101 	 * returning the error that was set in the callback execution.
11102 	 */
11103 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
11104 	if (caller_found) {
11105 		/*
11106 		 * 'error' is from the actual delmap operations.  To avoid
11107 		 * hangs, we need to handle the return of EAGAIN differently
11108 		 * since this is what drives the callback execution.
11109 		 * In this case, we don't want to return EAGAIN and do the
11110 		 * callback execution because there are none to execute.
11111 		 */
11112 		if (error == EAGAIN)
11113 			return (0);
11114 		else
11115 			return (error);
11116 	}
11117 
11118 	/* current caller was not in the list */
11119 	delmap_call = nfs4_init_delmapcall();
11120 
11121 	mutex_enter(&rp->r_statelock);
11122 	list_insert_tail(&rp->r_indelmap, delmap_call);
11123 	mutex_exit(&rp->r_statelock);
11124 
11125 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
11126 
11127 	dmapp->vp = vp;
11128 	dmapp->off = off;
11129 	dmapp->addr = addr;
11130 	dmapp->len = len;
11131 	dmapp->prot = prot;
11132 	dmapp->maxprot = maxprot;
11133 	dmapp->flags = flags;
11134 	dmapp->cr = cr;
11135 	dmapp->caller = delmap_call;
11136 
11137 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
11138 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
11139 
11140 	return (error ? error : EAGAIN);
11141 }
11142 
11143 static nfs4_delmapcall_t *
11144 nfs4_init_delmapcall()
11145 {
11146 	nfs4_delmapcall_t	*delmap_call;
11147 
11148 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
11149 	delmap_call->call_id = curthread;
11150 	delmap_call->error = 0;
11151 
11152 	return (delmap_call);
11153 }
11154 
11155 static void
11156 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11157 {
11158 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11159 }
11160 
11161 /*
11162  * Searches for the current delmap caller (based on curthread) in the list of
11163  * callers.  If it is found, we remove it and free the delmap caller.
11164  * Returns:
11165  *      0 if the caller wasn't found
11166  *      1 if the caller was found, removed and freed.  *errp will be set
11167  *	to what the result of the delmap was.
11168  */
11169 static int
11170 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11171 {
11172 	nfs4_delmapcall_t	*delmap_call;
11173 
11174 	/*
11175 	 * If the list doesn't exist yet, we create it and return
11176 	 * that the caller wasn't found.  No list = no callers.
11177 	 */
11178 	mutex_enter(&rp->r_statelock);
11179 	if (!(rp->r_flags & R4DELMAPLIST)) {
11180 		/* The list does not exist */
11181 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11182 		    offsetof(nfs4_delmapcall_t, call_node));
11183 		rp->r_flags |= R4DELMAPLIST;
11184 		mutex_exit(&rp->r_statelock);
11185 		return (0);
11186 	} else {
11187 		/* The list exists so search it */
11188 		for (delmap_call = list_head(&rp->r_indelmap);
11189 		    delmap_call != NULL;
11190 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11191 			if (delmap_call->call_id == curthread) {
11192 				/* current caller is in the list */
11193 				*errp = delmap_call->error;
11194 				list_remove(&rp->r_indelmap, delmap_call);
11195 				mutex_exit(&rp->r_statelock);
11196 				nfs4_free_delmapcall(delmap_call);
11197 				return (1);
11198 			}
11199 		}
11200 	}
11201 	mutex_exit(&rp->r_statelock);
11202 	return (0);
11203 }
11204 
11205 /*
11206  * Remove some pages from an mmap'd vnode.  Just update the
11207  * count of pages.  If doing close-to-open, then flush and
11208  * commit all of the pages associated with this file.
11209  * Otherwise, start an asynchronous page flush to write out
11210  * any dirty pages.  This will also associate a credential
11211  * with the rnode which can be used to write the pages.
11212  */
11213 /* ARGSUSED */
11214 static void
11215 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11216 {
11217 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11218 	rnode4_t		*rp;
11219 	mntinfo4_t		*mi;
11220 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11221 
11222 	rp = VTOR4(dmapp->vp);
11223 	mi = VTOMI4(dmapp->vp);
11224 
11225 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11226 	ASSERT(rp->r_mapcnt >= 0);
11227 
11228 	/*
11229 	 * Initiate a page flush and potential commit if there are
11230 	 * pages, the file system was not mounted readonly, the segment
11231 	 * was mapped shared, and the pages themselves were writeable.
11232 	 */
11233 	if (nfs4_has_pages(dmapp->vp) &&
11234 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11235 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11236 		mutex_enter(&rp->r_statelock);
11237 		rp->r_flags |= R4DIRTY;
11238 		mutex_exit(&rp->r_statelock);
11239 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11240 		    dmapp->len, dmapp->cr);
11241 		if (!e.error) {
11242 			mutex_enter(&rp->r_statelock);
11243 			e.error = rp->r_error;
11244 			rp->r_error = 0;
11245 			mutex_exit(&rp->r_statelock);
11246 		}
11247 	} else
11248 		e.error = 0;
11249 
11250 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11251 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11252 		    B_INVAL, dmapp->cr, NULL);
11253 
11254 	if (e.error) {
11255 		e.stat = puterrno4(e.error);
11256 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11257 		    OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11258 		dmapp->caller->error = e.error;
11259 	}
11260 
11261 	/* Check to see if we need to close the file */
11262 
11263 	if (dmapp->vp->v_type == VREG) {
11264 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11265 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11266 
11267 		if (e.error != 0 || e.stat != NFS4_OK) {
11268 			/*
11269 			 * Since it is possible that e.error == 0 and
11270 			 * e.stat != NFS4_OK (and vice versa),
11271 			 * we do the proper checking in order to get both
11272 			 * e.error and e.stat reporting the correct info.
11273 			 */
11274 			if (e.stat == NFS4_OK)
11275 				e.stat = puterrno4(e.error);
11276 			if (e.error == 0)
11277 				e.error = geterrno4(e.stat);
11278 
11279 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11280 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11281 			dmapp->caller->error = e.error;
11282 		}
11283 	}
11284 
11285 	(void) as_delete_callback(as, arg);
11286 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11287 }
11288 
11289 
11290 static uint_t
11291 fattr4_maxfilesize_to_bits(uint64_t ll)
11292 {
11293 	uint_t l = 1;
11294 
11295 	if (ll == 0) {
11296 		return (0);
11297 	}
11298 
11299 	if (ll & 0xffffffff00000000) {
11300 		l += 32; ll >>= 32;
11301 	}
11302 	if (ll & 0xffff0000) {
11303 		l += 16; ll >>= 16;
11304 	}
11305 	if (ll & 0xff00) {
11306 		l += 8; ll >>= 8;
11307 	}
11308 	if (ll & 0xf0) {
11309 		l += 4; ll >>= 4;
11310 	}
11311 	if (ll & 0xc) {
11312 		l += 2; ll >>= 2;
11313 	}
11314 	if (ll & 0x2) {
11315 		l += 1;
11316 	}
11317 	return (l);
11318 }
11319 
11320 static int
11321 nfs4_have_xattrs(vnode_t *vp, ulong_t *valp, cred_t *cr)
11322 {
11323 	vnode_t *avp = NULL;
11324 	int error;
11325 
11326 	if ((error = nfs4lookup_xattr(vp, "", &avp,
11327 	    LOOKUP_XATTR, cr)) == 0)
11328 		error = do_xattr_exists_check(avp, valp, cr);
11329 	if (avp)
11330 		VN_RELE(avp);
11331 
11332 	return (error);
11333 }
11334 
11335 /* ARGSUSED */
11336 int
11337 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
11338     caller_context_t *ct)
11339 {
11340 	int error;
11341 	hrtime_t t;
11342 	rnode4_t *rp;
11343 	nfs4_ga_res_t gar;
11344 	nfs4_ga_ext_res_t ger;
11345 
11346 	gar.n4g_ext_res = &ger;
11347 
11348 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11349 		return (EIO);
11350 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11351 		*valp = MAXPATHLEN;
11352 		return (0);
11353 	}
11354 	if (cmd == _PC_ACL_ENABLED) {
11355 		*valp = _ACL_ACE_ENABLED;
11356 		return (0);
11357 	}
11358 
11359 	rp = VTOR4(vp);
11360 	if (cmd == _PC_XATTR_EXISTS) {
11361 		/*
11362 		 * The existence of the xattr directory is not sufficient
11363 		 * for determining whether generic user attributes exists.
11364 		 * The attribute directory could only be a transient directory
11365 		 * used for Solaris sysattr support.  Do a small readdir
11366 		 * to verify if the only entries are sysattrs or not.
11367 		 *
11368 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11369 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11370 		 * and we don't have any way to update the "base" object's
11371 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11372 		 * could help out.
11373 		 */
11374 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11375 		    rp->r_xattr_dir == NULL) {
11376 			return (nfs4_have_xattrs(vp, valp, cr));
11377 		}
11378 	} else {  /* OLD CODE */
11379 		if (ATTRCACHE4_VALID(vp)) {
11380 			mutex_enter(&rp->r_statelock);
11381 			if (rp->r_pathconf.pc4_cache_valid) {
11382 				error = 0;
11383 				switch (cmd) {
11384 				case _PC_FILESIZEBITS:
11385 					*valp =
11386 					    rp->r_pathconf.pc4_filesizebits;
11387 					break;
11388 				case _PC_LINK_MAX:
11389 					*valp =
11390 					    rp->r_pathconf.pc4_link_max;
11391 					break;
11392 				case _PC_NAME_MAX:
11393 					*valp =
11394 					    rp->r_pathconf.pc4_name_max;
11395 					break;
11396 				case _PC_CHOWN_RESTRICTED:
11397 					*valp =
11398 					    rp->r_pathconf.pc4_chown_restricted;
11399 					break;
11400 				case _PC_NO_TRUNC:
11401 					*valp =
11402 					    rp->r_pathconf.pc4_no_trunc;
11403 					break;
11404 				default:
11405 					error = EINVAL;
11406 					break;
11407 				}
11408 				mutex_exit(&rp->r_statelock);
11409 #ifdef DEBUG
11410 				nfs4_pathconf_cache_hits++;
11411 #endif
11412 				return (error);
11413 			}
11414 			mutex_exit(&rp->r_statelock);
11415 		}
11416 	}
11417 #ifdef DEBUG
11418 	nfs4_pathconf_cache_misses++;
11419 #endif
11420 
11421 	t = gethrtime();
11422 
11423 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11424 
11425 	if (error) {
11426 		mutex_enter(&rp->r_statelock);
11427 		rp->r_pathconf.pc4_cache_valid = FALSE;
11428 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11429 		mutex_exit(&rp->r_statelock);
11430 		return (error);
11431 	}
11432 
11433 	/* interpret the max filesize */
11434 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11435 	    fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11436 
11437 	/* Store the attributes we just received */
11438 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11439 
11440 	switch (cmd) {
11441 	case _PC_FILESIZEBITS:
11442 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11443 		break;
11444 	case _PC_LINK_MAX:
11445 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11446 		break;
11447 	case _PC_NAME_MAX:
11448 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11449 		break;
11450 	case _PC_CHOWN_RESTRICTED:
11451 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11452 		break;
11453 	case _PC_NO_TRUNC:
11454 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11455 		break;
11456 	case _PC_XATTR_EXISTS:
11457 		if (gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists) {
11458 			if (error = nfs4_have_xattrs(vp, valp, cr))
11459 				return (error);
11460 		}
11461 		break;
11462 	default:
11463 		return (EINVAL);
11464 	}
11465 
11466 	return (0);
11467 }
11468 
11469 /*
11470  * Called by async thread to do synchronous pageio. Do the i/o, wait
11471  * for it to complete, and cleanup the page list when done.
11472  */
11473 static int
11474 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11475     int flags, cred_t *cr)
11476 {
11477 	int error;
11478 
11479 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11480 
11481 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11482 	if (flags & B_READ)
11483 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11484 	else
11485 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11486 	return (error);
11487 }
11488 
11489 /* ARGSUSED */
11490 static int
11491 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11492     int flags, cred_t *cr, caller_context_t *ct)
11493 {
11494 	int error;
11495 	rnode4_t *rp;
11496 
11497 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11498 		return (EIO);
11499 
11500 	if (pp == NULL)
11501 		return (EINVAL);
11502 
11503 	rp = VTOR4(vp);
11504 	mutex_enter(&rp->r_statelock);
11505 	rp->r_count++;
11506 	mutex_exit(&rp->r_statelock);
11507 
11508 	if (flags & B_ASYNC) {
11509 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11510 		    nfs4_sync_pageio);
11511 	} else
11512 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11513 	mutex_enter(&rp->r_statelock);
11514 	rp->r_count--;
11515 	cv_broadcast(&rp->r_cv);
11516 	mutex_exit(&rp->r_statelock);
11517 	return (error);
11518 }
11519 
11520 /* ARGSUSED */
11521 static void
11522 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr,
11523     caller_context_t *ct)
11524 {
11525 	int error;
11526 	rnode4_t *rp;
11527 	page_t *plist;
11528 	page_t *pptr;
11529 	offset3 offset;
11530 	count3 len;
11531 	k_sigset_t smask;
11532 
11533 	/*
11534 	 * We should get called with fl equal to either B_FREE or
11535 	 * B_INVAL.  Any other value is illegal.
11536 	 *
11537 	 * The page that we are either supposed to free or destroy
11538 	 * should be exclusive locked and its io lock should not
11539 	 * be held.
11540 	 */
11541 	ASSERT(fl == B_FREE || fl == B_INVAL);
11542 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11543 
11544 	rp = VTOR4(vp);
11545 
11546 	/*
11547 	 * If the page doesn't need to be committed or we shouldn't
11548 	 * even bother attempting to commit it, then just make sure
11549 	 * that the p_fsdata byte is clear and then either free or
11550 	 * destroy the page as appropriate.
11551 	 */
11552 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11553 		pp->p_fsdata = C_NOCOMMIT;
11554 		if (fl == B_FREE)
11555 			page_free(pp, dn);
11556 		else
11557 			page_destroy(pp, dn);
11558 		return;
11559 	}
11560 
11561 	/*
11562 	 * If there is a page invalidation operation going on, then
11563 	 * if this is one of the pages being destroyed, then just
11564 	 * clear the p_fsdata byte and then either free or destroy
11565 	 * the page as appropriate.
11566 	 */
11567 	mutex_enter(&rp->r_statelock);
11568 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11569 		mutex_exit(&rp->r_statelock);
11570 		pp->p_fsdata = C_NOCOMMIT;
11571 		if (fl == B_FREE)
11572 			page_free(pp, dn);
11573 		else
11574 			page_destroy(pp, dn);
11575 		return;
11576 	}
11577 
11578 	/*
11579 	 * If we are freeing this page and someone else is already
11580 	 * waiting to do a commit, then just unlock the page and
11581 	 * return.  That other thread will take care of commiting
11582 	 * this page.  The page can be freed sometime after the
11583 	 * commit has finished.  Otherwise, if the page is marked
11584 	 * as delay commit, then we may be getting called from
11585 	 * pvn_write_done, one page at a time.   This could result
11586 	 * in one commit per page, so we end up doing lots of small
11587 	 * commits instead of fewer larger commits.  This is bad,
11588 	 * we want do as few commits as possible.
11589 	 */
11590 	if (fl == B_FREE) {
11591 		if (rp->r_flags & R4COMMITWAIT) {
11592 			page_unlock(pp);
11593 			mutex_exit(&rp->r_statelock);
11594 			return;
11595 		}
11596 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11597 			pp->p_fsdata = C_COMMIT;
11598 			page_unlock(pp);
11599 			mutex_exit(&rp->r_statelock);
11600 			return;
11601 		}
11602 	}
11603 
11604 	/*
11605 	 * Check to see if there is a signal which would prevent an
11606 	 * attempt to commit the pages from being successful.  If so,
11607 	 * then don't bother with all of the work to gather pages and
11608 	 * generate the unsuccessful RPC.  Just return from here and
11609 	 * let the page be committed at some later time.
11610 	 */
11611 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11612 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11613 		sigunintr(&smask);
11614 		page_unlock(pp);
11615 		mutex_exit(&rp->r_statelock);
11616 		return;
11617 	}
11618 	sigunintr(&smask);
11619 
11620 	/*
11621 	 * We are starting to need to commit pages, so let's try
11622 	 * to commit as many as possible at once to reduce the
11623 	 * overhead.
11624 	 *
11625 	 * Set the `commit inprogress' state bit.  We must
11626 	 * first wait until any current one finishes.  Then
11627 	 * we initialize the c_pages list with this page.
11628 	 */
11629 	while (rp->r_flags & R4COMMIT) {
11630 		rp->r_flags |= R4COMMITWAIT;
11631 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11632 		rp->r_flags &= ~R4COMMITWAIT;
11633 	}
11634 	rp->r_flags |= R4COMMIT;
11635 	mutex_exit(&rp->r_statelock);
11636 	ASSERT(rp->r_commit.c_pages == NULL);
11637 	rp->r_commit.c_pages = pp;
11638 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11639 	rp->r_commit.c_commlen = PAGESIZE;
11640 
11641 	/*
11642 	 * Gather together all other pages which can be committed.
11643 	 * They will all be chained off r_commit.c_pages.
11644 	 */
11645 	nfs4_get_commit(vp);
11646 
11647 	/*
11648 	 * Clear the `commit inprogress' status and disconnect
11649 	 * the list of pages to be committed from the rnode.
11650 	 * At this same time, we also save the starting offset
11651 	 * and length of data to be committed on the server.
11652 	 */
11653 	plist = rp->r_commit.c_pages;
11654 	rp->r_commit.c_pages = NULL;
11655 	offset = rp->r_commit.c_commbase;
11656 	len = rp->r_commit.c_commlen;
11657 	mutex_enter(&rp->r_statelock);
11658 	rp->r_flags &= ~R4COMMIT;
11659 	cv_broadcast(&rp->r_commit.c_cv);
11660 	mutex_exit(&rp->r_statelock);
11661 
11662 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11663 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11664 		nfs4_async_commit(vp, plist, offset, len,
11665 		    cr, do_nfs4_async_commit);
11666 		return;
11667 	}
11668 
11669 	/*
11670 	 * Actually generate the COMMIT op over the wire operation.
11671 	 */
11672 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11673 
11674 	/*
11675 	 * If we got an error during the commit, just unlock all
11676 	 * of the pages.  The pages will get retransmitted to the
11677 	 * server during a putpage operation.
11678 	 */
11679 	if (error) {
11680 		while (plist != NULL) {
11681 			pptr = plist;
11682 			page_sub(&plist, pptr);
11683 			page_unlock(pptr);
11684 		}
11685 		return;
11686 	}
11687 
11688 	/*
11689 	 * We've tried as hard as we can to commit the data to stable
11690 	 * storage on the server.  We just unlock the rest of the pages
11691 	 * and clear the commit required state.  They will be put
11692 	 * onto the tail of the cachelist if they are nolonger
11693 	 * mapped.
11694 	 */
11695 	while (plist != pp) {
11696 		pptr = plist;
11697 		page_sub(&plist, pptr);
11698 		pptr->p_fsdata = C_NOCOMMIT;
11699 		page_unlock(pptr);
11700 	}
11701 
11702 	/*
11703 	 * It is possible that nfs4_commit didn't return error but
11704 	 * some other thread has modified the page we are going
11705 	 * to free/destroy.
11706 	 *    In this case we need to rewrite the page. Do an explicit check
11707 	 * before attempting to free/destroy the page. If modified, needs to
11708 	 * be rewritten so unlock the page and return.
11709 	 */
11710 	if (hat_ismod(pp)) {
11711 		pp->p_fsdata = C_NOCOMMIT;
11712 		page_unlock(pp);
11713 		return;
11714 	}
11715 
11716 	/*
11717 	 * Now, as appropriate, either free or destroy the page
11718 	 * that we were called with.
11719 	 */
11720 	pp->p_fsdata = C_NOCOMMIT;
11721 	if (fl == B_FREE)
11722 		page_free(pp, dn);
11723 	else
11724 		page_destroy(pp, dn);
11725 }
11726 
11727 /*
11728  * Commit requires that the current fh be the file written to.
11729  * The compound op structure is:
11730  *      PUTFH(file), COMMIT
11731  */
11732 static int
11733 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11734 {
11735 	COMPOUND4args_clnt args;
11736 	COMPOUND4res_clnt res;
11737 	COMMIT4res *cm_res;
11738 	nfs_argop4 argop[2];
11739 	nfs_resop4 *resop;
11740 	int doqueue;
11741 	mntinfo4_t *mi;
11742 	rnode4_t *rp;
11743 	cred_t *cred_otw = NULL;
11744 	bool_t needrecov = FALSE;
11745 	nfs4_recov_state_t recov_state;
11746 	nfs4_open_stream_t *osp = NULL;
11747 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11748 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11749 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11750 
11751 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11752 
11753 	rp = VTOR4(vp);
11754 
11755 	mi = VTOMI4(vp);
11756 	recov_state.rs_flags = 0;
11757 	recov_state.rs_num_retry_despite_err = 0;
11758 get_commit_cred:
11759 	/*
11760 	 * Releases the osp, if a valid open stream is provided.
11761 	 * Puts a hold on the cred_otw and the new osp (if found).
11762 	 */
11763 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11764 	    &first_time, &last_time);
11765 	args.ctag = TAG_COMMIT;
11766 recov_retry:
11767 	/*
11768 	 * Commit ops: putfh file; commit
11769 	 */
11770 	args.array_len = 2;
11771 	args.array = argop;
11772 
11773 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11774 	    &recov_state, NULL);
11775 	if (e.error) {
11776 		crfree(cred_otw);
11777 		if (osp != NULL)
11778 			open_stream_rele(osp, rp);
11779 		return (e.error);
11780 	}
11781 
11782 	/* putfh directory */
11783 	argop[0].argop = OP_CPUTFH;
11784 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11785 
11786 	/* commit */
11787 	argop[1].argop = OP_COMMIT;
11788 	argop[1].nfs_argop4_u.opcommit.offset = offset;
11789 	argop[1].nfs_argop4_u.opcommit.count = count;
11790 
11791 	doqueue = 1;
11792 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
11793 
11794 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
11795 	if (!needrecov && e.error) {
11796 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
11797 		    needrecov);
11798 		crfree(cred_otw);
11799 		if (e.error == EACCES && last_time == FALSE)
11800 			goto get_commit_cred;
11801 		if (osp != NULL)
11802 			open_stream_rele(osp, rp);
11803 		return (e.error);
11804 	}
11805 
11806 	if (needrecov) {
11807 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
11808 		    NULL, OP_COMMIT, NULL, NULL, NULL) == FALSE) {
11809 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11810 			    &recov_state, needrecov);
11811 			if (!e.error)
11812 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11813 			goto recov_retry;
11814 		}
11815 		if (e.error) {
11816 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11817 			    &recov_state, needrecov);
11818 			crfree(cred_otw);
11819 			if (osp != NULL)
11820 				open_stream_rele(osp, rp);
11821 			return (e.error);
11822 		}
11823 		/* fall through for res.status case */
11824 	}
11825 
11826 	if (res.status) {
11827 		e.error = geterrno4(res.status);
11828 		if (e.error == EACCES && last_time == FALSE) {
11829 			crfree(cred_otw);
11830 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11831 			    &recov_state, needrecov);
11832 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11833 			goto get_commit_cred;
11834 		}
11835 		/*
11836 		 * Can't do a nfs4_purge_stale_fh here because this
11837 		 * can cause a deadlock.  nfs4_commit can
11838 		 * be called from nfs4_dispose which can be called
11839 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
11840 		 * can call back to pvn_vplist_dirty.
11841 		 */
11842 		if (e.error == ESTALE) {
11843 			mutex_enter(&rp->r_statelock);
11844 			rp->r_flags |= R4STALE;
11845 			if (!rp->r_error)
11846 				rp->r_error = e.error;
11847 			mutex_exit(&rp->r_statelock);
11848 			PURGE_ATTRCACHE4(vp);
11849 		} else {
11850 			mutex_enter(&rp->r_statelock);
11851 			if (!rp->r_error)
11852 				rp->r_error = e.error;
11853 			mutex_exit(&rp->r_statelock);
11854 		}
11855 	} else {
11856 		ASSERT(rp->r_flags & R4HAVEVERF);
11857 		resop = &res.array[1];	/* commit res */
11858 		cm_res = &resop->nfs_resop4_u.opcommit;
11859 		mutex_enter(&rp->r_statelock);
11860 		if (cm_res->writeverf == rp->r_writeverf) {
11861 			mutex_exit(&rp->r_statelock);
11862 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11863 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11864 			    &recov_state, needrecov);
11865 			crfree(cred_otw);
11866 			if (osp != NULL)
11867 				open_stream_rele(osp, rp);
11868 			return (0);
11869 		}
11870 		nfs4_set_mod(vp);
11871 		rp->r_writeverf = cm_res->writeverf;
11872 		mutex_exit(&rp->r_statelock);
11873 		e.error = NFS_VERF_MISMATCH;
11874 	}
11875 
11876 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11877 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
11878 	crfree(cred_otw);
11879 	if (osp != NULL)
11880 		open_stream_rele(osp, rp);
11881 
11882 	return (e.error);
11883 }
11884 
11885 static void
11886 nfs4_set_mod(vnode_t *vp)
11887 {
11888 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11889 
11890 	/* make sure we're looking at the master vnode, not a shadow */
11891 	pvn_vplist_setdirty(RTOV4(VTOR4(vp)), nfs_setmod_check);
11892 }
11893 
11894 /*
11895  * This function is used to gather a page list of the pages which
11896  * can be committed on the server.
11897  *
11898  * The calling thread must have set R4COMMIT.  This bit is used to
11899  * serialize access to the commit structure in the rnode.  As long
11900  * as the thread has set R4COMMIT, then it can manipulate the commit
11901  * structure without requiring any other locks.
11902  *
11903  * When this function is called from nfs4_dispose() the page passed
11904  * into nfs4_dispose() will be SE_EXCL locked, and so this function
11905  * will skip it. This is not a problem since we initially add the
11906  * page to the r_commit page list.
11907  *
11908  */
11909 static void
11910 nfs4_get_commit(vnode_t *vp)
11911 {
11912 	rnode4_t *rp;
11913 	page_t *pp;
11914 	kmutex_t *vphm;
11915 
11916 	rp = VTOR4(vp);
11917 
11918 	ASSERT(rp->r_flags & R4COMMIT);
11919 
11920 	/* make sure we're looking at the master vnode, not a shadow */
11921 
11922 	if (IS_SHADOW(vp, rp))
11923 		vp = RTOV4(rp);
11924 
11925 	vphm = page_vnode_mutex(vp);
11926 	mutex_enter(vphm);
11927 
11928 	/*
11929 	 * If there are no pages associated with this vnode, then
11930 	 * just return.
11931 	 */
11932 	if ((pp = vp->v_pages) == NULL) {
11933 		mutex_exit(vphm);
11934 		return;
11935 	}
11936 
11937 	/*
11938 	 * Step through all of the pages associated with this vnode
11939 	 * looking for pages which need to be committed.
11940 	 */
11941 	do {
11942 		/* Skip marker pages. */
11943 		if (pp->p_hash == PVN_VPLIST_HASH_TAG)
11944 			continue;
11945 
11946 		/*
11947 		 * First short-cut everything (without the page_lock)
11948 		 * and see if this page does not need to be committed
11949 		 * or is modified if so then we'll just skip it.
11950 		 */
11951 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
11952 			continue;
11953 
11954 		/*
11955 		 * Attempt to lock the page.  If we can't, then
11956 		 * someone else is messing with it or we have been
11957 		 * called from nfs4_dispose and this is the page that
11958 		 * nfs4_dispose was called with.. anyway just skip it.
11959 		 */
11960 		if (!page_trylock(pp, SE_EXCL))
11961 			continue;
11962 
11963 		/*
11964 		 * Lets check again now that we have the page lock.
11965 		 */
11966 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11967 			page_unlock(pp);
11968 			continue;
11969 		}
11970 
11971 		/* this had better not be a free page */
11972 		ASSERT(PP_ISFREE(pp) == 0);
11973 
11974 		/*
11975 		 * The page needs to be committed and we locked it.
11976 		 * Update the base and length parameters and add it
11977 		 * to r_pages.
11978 		 */
11979 		if (rp->r_commit.c_pages == NULL) {
11980 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11981 			rp->r_commit.c_commlen = PAGESIZE;
11982 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
11983 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
11984 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
11985 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11986 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
11987 		    <= pp->p_offset) {
11988 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11989 			    rp->r_commit.c_commbase + PAGESIZE;
11990 		}
11991 		page_add(&rp->r_commit.c_pages, pp);
11992 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11993 
11994 	mutex_exit(vphm);
11995 }
11996 
11997 /*
11998  * This routine is used to gather together a page list of the pages
11999  * which are to be committed on the server.  This routine must not
12000  * be called if the calling thread holds any locked pages.
12001  *
12002  * The calling thread must have set R4COMMIT.  This bit is used to
12003  * serialize access to the commit structure in the rnode.  As long
12004  * as the thread has set R4COMMIT, then it can manipulate the commit
12005  * structure without requiring any other locks.
12006  */
12007 static void
12008 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
12009 {
12010 
12011 	rnode4_t *rp;
12012 	page_t *pp;
12013 	u_offset_t end;
12014 	u_offset_t off;
12015 	ASSERT(len != 0);
12016 	rp = VTOR4(vp);
12017 	ASSERT(rp->r_flags & R4COMMIT);
12018 
12019 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12020 
12021 	/* make sure we're looking at the master vnode, not a shadow */
12022 
12023 	if (IS_SHADOW(vp, rp))
12024 		vp = RTOV4(rp);
12025 
12026 	/*
12027 	 * If there are no pages associated with this vnode, then
12028 	 * just return.
12029 	 */
12030 	if ((pp = vp->v_pages) == NULL)
12031 		return;
12032 	/*
12033 	 * Calculate the ending offset.
12034 	 */
12035 	end = soff + len;
12036 	for (off = soff; off < end; off += PAGESIZE) {
12037 		/*
12038 		 * Lookup each page by vp, offset.
12039 		 */
12040 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
12041 			continue;
12042 		/*
12043 		 * If this page does not need to be committed or is
12044 		 * modified, then just skip it.
12045 		 */
12046 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
12047 			page_unlock(pp);
12048 			continue;
12049 		}
12050 
12051 		ASSERT(PP_ISFREE(pp) == 0);
12052 		/*
12053 		 * The page needs to be committed and we locked it.
12054 		 * Update the base and length parameters and add it
12055 		 * to r_pages.
12056 		 */
12057 		if (rp->r_commit.c_pages == NULL) {
12058 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
12059 			rp->r_commit.c_commlen = PAGESIZE;
12060 		} else {
12061 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
12062 			    rp->r_commit.c_commbase + PAGESIZE;
12063 		}
12064 		page_add(&rp->r_commit.c_pages, pp);
12065 	}
12066 }
12067 
12068 /*
12069  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
12070  * Flushes and commits data to the server.
12071  */
12072 static int
12073 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
12074 {
12075 	int error;
12076 	verifier4 write_verf;
12077 	rnode4_t *rp = VTOR4(vp);
12078 
12079 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12080 
12081 	/*
12082 	 * Flush the data portion of the file and then commit any
12083 	 * portions which need to be committed.  This may need to
12084 	 * be done twice if the server has changed state since
12085 	 * data was last written.  The data will need to be
12086 	 * rewritten to the server and then a new commit done.
12087 	 *
12088 	 * In fact, this may need to be done several times if the
12089 	 * server is having problems and crashing while we are
12090 	 * attempting to do this.
12091 	 */
12092 
12093 top:
12094 	/*
12095 	 * Do a flush based on the poff and plen arguments.  This
12096 	 * will synchronously write out any modified pages in the
12097 	 * range specified by (poff, plen). This starts all of the
12098 	 * i/o operations which will be waited for in the next
12099 	 * call to nfs4_putpage
12100 	 */
12101 
12102 	mutex_enter(&rp->r_statelock);
12103 	write_verf = rp->r_writeverf;
12104 	mutex_exit(&rp->r_statelock);
12105 
12106 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr, NULL);
12107 	if (error == EAGAIN)
12108 		error = 0;
12109 
12110 	/*
12111 	 * Do a flush based on the poff and plen arguments.  This
12112 	 * will synchronously write out any modified pages in the
12113 	 * range specified by (poff, plen) and wait until all of
12114 	 * the asynchronous i/o's in that range are done as well.
12115 	 */
12116 	if (!error)
12117 		error = nfs4_putpage(vp, poff, plen, 0, cr, NULL);
12118 
12119 	if (error)
12120 		return (error);
12121 
12122 	mutex_enter(&rp->r_statelock);
12123 	if (rp->r_writeverf != write_verf) {
12124 		mutex_exit(&rp->r_statelock);
12125 		goto top;
12126 	}
12127 	mutex_exit(&rp->r_statelock);
12128 
12129 	/*
12130 	 * Now commit any pages which might need to be committed.
12131 	 * If the error, NFS_VERF_MISMATCH, is returned, then
12132 	 * start over with the flush operation.
12133 	 */
12134 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
12135 
12136 	if (error == NFS_VERF_MISMATCH)
12137 		goto top;
12138 
12139 	return (error);
12140 }
12141 
12142 /*
12143  * nfs4_commit_vp()  will wait for other pending commits and
12144  * will either commit the whole file or a range, plen dictates
12145  * if we commit whole file. a value of zero indicates the whole
12146  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
12147  */
12148 static int
12149 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12150     cred_t *cr, int wait_on_writes)
12151 {
12152 	rnode4_t *rp;
12153 	page_t *plist;
12154 	offset3 offset;
12155 	count3 len;
12156 
12157 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12158 
12159 	rp = VTOR4(vp);
12160 
12161 	/*
12162 	 *  before we gather commitable pages make
12163 	 *  sure there are no outstanding async writes
12164 	 */
12165 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12166 		mutex_enter(&rp->r_statelock);
12167 		while (rp->r_count > 0) {
12168 			cv_wait(&rp->r_cv, &rp->r_statelock);
12169 		}
12170 		mutex_exit(&rp->r_statelock);
12171 	}
12172 
12173 	/*
12174 	 * Set the `commit inprogress' state bit.  We must
12175 	 * first wait until any current one finishes.
12176 	 */
12177 	mutex_enter(&rp->r_statelock);
12178 	while (rp->r_flags & R4COMMIT) {
12179 		rp->r_flags |= R4COMMITWAIT;
12180 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12181 		rp->r_flags &= ~R4COMMITWAIT;
12182 	}
12183 	rp->r_flags |= R4COMMIT;
12184 	mutex_exit(&rp->r_statelock);
12185 
12186 	/*
12187 	 * Gather all of the pages which need to be
12188 	 * committed.
12189 	 */
12190 	if (plen == 0)
12191 		nfs4_get_commit(vp);
12192 	else
12193 		nfs4_get_commit_range(vp, poff, plen);
12194 
12195 	/*
12196 	 * Clear the `commit inprogress' bit and disconnect the
12197 	 * page list which was gathered by nfs4_get_commit.
12198 	 */
12199 	plist = rp->r_commit.c_pages;
12200 	rp->r_commit.c_pages = NULL;
12201 	offset = rp->r_commit.c_commbase;
12202 	len = rp->r_commit.c_commlen;
12203 	mutex_enter(&rp->r_statelock);
12204 	rp->r_flags &= ~R4COMMIT;
12205 	cv_broadcast(&rp->r_commit.c_cv);
12206 	mutex_exit(&rp->r_statelock);
12207 
12208 	/*
12209 	 * If any pages need to be committed, commit them and
12210 	 * then unlock them so that they can be freed some
12211 	 * time later.
12212 	 */
12213 	if (plist == NULL)
12214 		return (0);
12215 
12216 	/*
12217 	 * No error occurred during the flush portion
12218 	 * of this operation, so now attempt to commit
12219 	 * the data to stable storage on the server.
12220 	 *
12221 	 * This will unlock all of the pages on the list.
12222 	 */
12223 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12224 }
12225 
12226 static int
12227 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12228     cred_t *cr)
12229 {
12230 	int error;
12231 	page_t *pp;
12232 
12233 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12234 
12235 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12236 
12237 	/*
12238 	 * If we got an error, then just unlock all of the pages
12239 	 * on the list.
12240 	 */
12241 	if (error) {
12242 		while (plist != NULL) {
12243 			pp = plist;
12244 			page_sub(&plist, pp);
12245 			page_unlock(pp);
12246 		}
12247 		return (error);
12248 	}
12249 	/*
12250 	 * We've tried as hard as we can to commit the data to stable
12251 	 * storage on the server.  We just unlock the pages and clear
12252 	 * the commit required state.  They will get freed later.
12253 	 */
12254 	while (plist != NULL) {
12255 		pp = plist;
12256 		page_sub(&plist, pp);
12257 		pp->p_fsdata = C_NOCOMMIT;
12258 		page_unlock(pp);
12259 	}
12260 
12261 	return (error);
12262 }
12263 
12264 static void
12265 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12266     cred_t *cr)
12267 {
12268 
12269 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12270 }
12271 
12272 /*ARGSUSED*/
12273 static int
12274 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12275     caller_context_t *ct)
12276 {
12277 	int		error = 0;
12278 	mntinfo4_t	*mi;
12279 	vattr_t		va;
12280 	vsecattr_t	nfsace4_vsap;
12281 
12282 	mi = VTOMI4(vp);
12283 	if (nfs_zone() != mi->mi_zone)
12284 		return (EIO);
12285 	if (mi->mi_flags & MI4_ACL) {
12286 		/* if we have a delegation, return it */
12287 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12288 			(void) nfs4delegreturn(VTOR4(vp),
12289 			    NFS4_DR_REOPEN|NFS4_DR_PUSH);
12290 
12291 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12292 		    NFS4_ACL_SET);
12293 		if (error) /* EINVAL */
12294 			return (error);
12295 
12296 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12297 			/*
12298 			 * These are aclent_t type entries.
12299 			 */
12300 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12301 			    vp->v_type == VDIR, FALSE);
12302 			if (error)
12303 				return (error);
12304 		} else {
12305 			/*
12306 			 * These are ace_t type entries.
12307 			 */
12308 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12309 			    FALSE);
12310 			if (error)
12311 				return (error);
12312 		}
12313 		bzero(&va, sizeof (va));
12314 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12315 		vs_ace4_destroy(&nfsace4_vsap);
12316 		return (error);
12317 	}
12318 	return (ENOSYS);
12319 }
12320 
12321 /* ARGSUSED */
12322 int
12323 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12324     caller_context_t *ct)
12325 {
12326 	int		error;
12327 	mntinfo4_t	*mi;
12328 	nfs4_ga_res_t	gar;
12329 	rnode4_t	*rp = VTOR4(vp);
12330 
12331 	mi = VTOMI4(vp);
12332 	if (nfs_zone() != mi->mi_zone)
12333 		return (EIO);
12334 
12335 	bzero(&gar, sizeof (gar));
12336 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12337 
12338 	/*
12339 	 * vsecattr->vsa_mask holds the original acl request mask.
12340 	 * This is needed when determining what to return.
12341 	 * (See: nfs4_create_getsecattr_return())
12342 	 */
12343 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12344 	if (error) /* EINVAL */
12345 		return (error);
12346 
12347 	/*
12348 	 * If this is a referral stub, don't try to go OTW for an ACL
12349 	 */
12350 	if (RP_ISSTUB_REFERRAL(VTOR4(vp)))
12351 		return (fs_fab_acl(vp, vsecattr, flag, cr, ct));
12352 
12353 	if (mi->mi_flags & MI4_ACL) {
12354 		/*
12355 		 * Check if the data is cached and the cache is valid.  If it
12356 		 * is we don't go over the wire.
12357 		 */
12358 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12359 			mutex_enter(&rp->r_statelock);
12360 			if (rp->r_secattr != NULL) {
12361 				error = nfs4_create_getsecattr_return(
12362 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12363 				    rp->r_attr.va_gid,
12364 				    vp->v_type == VDIR);
12365 				if (!error) { /* error == 0 - Success! */
12366 					mutex_exit(&rp->r_statelock);
12367 					return (error);
12368 				}
12369 			}
12370 			mutex_exit(&rp->r_statelock);
12371 		}
12372 
12373 		/*
12374 		 * The getattr otw call will always get both the acl, in
12375 		 * the form of a list of nfsace4's, and the number of acl
12376 		 * entries; independent of the value of gar.n4g_va.va_mask.
12377 		 */
12378 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12379 		if (error) {
12380 			vs_ace4_destroy(&gar.n4g_vsa);
12381 			if (error == ENOTSUP || error == EOPNOTSUPP)
12382 				error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12383 			return (error);
12384 		}
12385 
12386 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12387 			/*
12388 			 * No error was returned, but according to the response
12389 			 * bitmap, neither was an acl.
12390 			 */
12391 			vs_ace4_destroy(&gar.n4g_vsa);
12392 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12393 			return (error);
12394 		}
12395 
12396 		/*
12397 		 * Update the cache with the ACL.
12398 		 */
12399 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12400 
12401 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12402 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12403 		    vp->v_type == VDIR);
12404 		vs_ace4_destroy(&gar.n4g_vsa);
12405 		if ((error) && (vsecattr->vsa_mask &
12406 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12407 		    (error != EACCES)) {
12408 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12409 		}
12410 		return (error);
12411 	}
12412 	error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12413 	return (error);
12414 }
12415 
12416 /*
12417  * The function returns:
12418  *	- 0 (zero) if the passed in "acl_mask" is a valid request.
12419  *	- EINVAL if the passed in "acl_mask" is an invalid request.
12420  *
12421  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12422  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12423  *
12424  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12425  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12426  * - We have a count field set without the corresponding acl field set. (e.g. -
12427  * VSA_ACECNT is set, but VSA_ACE is not)
12428  */
12429 static int
12430 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12431 {
12432 	/* Shortcut the masks that are always valid. */
12433 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12434 		return (0);
12435 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12436 		return (0);
12437 
12438 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12439 		/*
12440 		 * We can't have any VSA_ACL type stuff in the mask now.
12441 		 */
12442 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12443 		    VSA_DFACLCNT))
12444 			return (EINVAL);
12445 
12446 		if (op == NFS4_ACL_SET) {
12447 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12448 				return (EINVAL);
12449 		}
12450 	}
12451 
12452 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12453 		/*
12454 		 * We can't have any VSA_ACE type stuff in the mask now.
12455 		 */
12456 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12457 			return (EINVAL);
12458 
12459 		if (op == NFS4_ACL_SET) {
12460 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12461 				return (EINVAL);
12462 
12463 			if ((acl_mask & VSA_DFACLCNT) &&
12464 			    !(acl_mask & VSA_DFACL))
12465 				return (EINVAL);
12466 		}
12467 	}
12468 	return (0);
12469 }
12470 
12471 /*
12472  * The theory behind creating the correct getsecattr return is simply this:
12473  * "Don't return anything that the caller is not expecting to have to free."
12474  */
12475 static int
12476 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12477     uid_t uid, gid_t gid, int isdir)
12478 {
12479 	int error = 0;
12480 	/* Save the mask since the translators modify it. */
12481 	uint_t	orig_mask = vsap->vsa_mask;
12482 
12483 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12484 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid, FALSE);
12485 
12486 		if (error)
12487 			return (error);
12488 
12489 		/*
12490 		 * If the caller only asked for the ace count (VSA_ACECNT)
12491 		 * don't give them the full acl (VSA_ACE), free it.
12492 		 */
12493 		if (!orig_mask & VSA_ACE) {
12494 			if (vsap->vsa_aclentp != NULL) {
12495 				kmem_free(vsap->vsa_aclentp,
12496 				    vsap->vsa_aclcnt * sizeof (ace_t));
12497 				vsap->vsa_aclentp = NULL;
12498 			}
12499 		}
12500 		vsap->vsa_mask = orig_mask;
12501 
12502 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12503 	    VSA_DFACLCNT)) {
12504 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12505 		    isdir, FALSE);
12506 
12507 		if (error)
12508 			return (error);
12509 
12510 		/*
12511 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12512 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12513 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12514 		 */
12515 		if (!orig_mask & VSA_ACL) {
12516 			if (vsap->vsa_aclentp != NULL) {
12517 				kmem_free(vsap->vsa_aclentp,
12518 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12519 				vsap->vsa_aclentp = NULL;
12520 			}
12521 		}
12522 
12523 		if (!orig_mask & VSA_DFACL) {
12524 			if (vsap->vsa_dfaclentp != NULL) {
12525 				kmem_free(vsap->vsa_dfaclentp,
12526 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12527 				vsap->vsa_dfaclentp = NULL;
12528 			}
12529 		}
12530 		vsap->vsa_mask = orig_mask;
12531 	}
12532 	return (0);
12533 }
12534 
12535 /* ARGSUSED */
12536 int
12537 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr,
12538     caller_context_t *ct)
12539 {
12540 	int error;
12541 
12542 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12543 		return (EIO);
12544 	/*
12545 	 * check for valid cmd parameter
12546 	 */
12547 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12548 		return (EINVAL);
12549 
12550 	/*
12551 	 * Check access permissions
12552 	 */
12553 	if ((cmd & F_SHARE) &&
12554 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12555 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12556 		return (EBADF);
12557 
12558 	/*
12559 	 * If the filesystem is mounted using local locking, pass the
12560 	 * request off to the local share code.
12561 	 */
12562 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12563 		return (fs_shrlock(vp, cmd, shr, flag, cr, ct));
12564 
12565 	switch (cmd) {
12566 	case F_SHARE:
12567 	case F_UNSHARE:
12568 		/*
12569 		 * This will be properly implemented later,
12570 		 * see RFE: 4823948 .
12571 		 */
12572 		error = EAGAIN;
12573 		break;
12574 
12575 	case F_HASREMOTELOCKS:
12576 		/*
12577 		 * NFS client can't store remote locks itself
12578 		 */
12579 		shr->s_access = 0;
12580 		error = 0;
12581 		break;
12582 
12583 	default:
12584 		error = EINVAL;
12585 		break;
12586 	}
12587 
12588 	return (error);
12589 }
12590 
12591 /*
12592  * Common code called by directory ops to update the attrcache
12593  */
12594 static int
12595 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12596     hrtime_t t, vnode_t *vp, cred_t *cr)
12597 {
12598 	int error = 0;
12599 
12600 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12601 
12602 	if (status != NFS4_OK) {
12603 		/* getattr not done or failed */
12604 		PURGE_ATTRCACHE4(vp);
12605 		return (error);
12606 	}
12607 
12608 	if (garp) {
12609 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12610 	} else {
12611 		PURGE_ATTRCACHE4(vp);
12612 	}
12613 	return (error);
12614 }
12615 
12616 /*
12617  * Update directory caches for directory modification ops (link, rename, etc.)
12618  * When dinfo is NULL, manage dircaches in the old way.
12619  */
12620 static void
12621 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12622     dirattr_info_t *dinfo)
12623 {
12624 	rnode4_t	*drp = VTOR4(dvp);
12625 
12626 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12627 
12628 	/* Purge rddir cache for dir since it changed */
12629 	if (drp->r_dir != NULL)
12630 		nfs4_purge_rddir_cache(dvp);
12631 
12632 	/*
12633 	 * If caller provided dinfo, then use it to manage dir caches.
12634 	 */
12635 	if (dinfo != NULL) {
12636 		if (vp != NULL) {
12637 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12638 			if (!VTOR4(vp)->created_v4) {
12639 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12640 				dnlc_update(dvp, nm, vp);
12641 			} else {
12642 				/*
12643 				 * XXX don't update if the created_v4 flag is
12644 				 * set
12645 				 */
12646 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12647 				NFS4_DEBUG(nfs4_client_state_debug,
12648 				    (CE_NOTE, "nfs4_update_dircaches: "
12649 				    "don't update dnlc: created_v4 flag"));
12650 			}
12651 		}
12652 
12653 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12654 		    dinfo->di_cred, FALSE, cinfo);
12655 
12656 		return;
12657 	}
12658 
12659 	/*
12660 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12661 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12662 	 * attrs, the dir's attrs must be purged.
12663 	 *
12664 	 * XXX this check and dnlc update/purge should really be atomic,
12665 	 * XXX but can't use rnode statelock because it'll deadlock in
12666 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12667 	 * XXX does occur.
12668 	 *
12669 	 * XXX We also may want to check that atomic is true in the
12670 	 * XXX change_info struct. If it is not, the change_info may
12671 	 * XXX reflect changes by more than one clients which means that
12672 	 * XXX our cache may not be valid.
12673 	 */
12674 	PURGE_ATTRCACHE4(dvp);
12675 	if (drp->r_change == cinfo->before) {
12676 		/* no changes took place in the directory prior to our link */
12677 		if (vp != NULL) {
12678 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12679 			if (!VTOR4(vp)->created_v4) {
12680 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12681 				dnlc_update(dvp, nm, vp);
12682 			} else {
12683 				/*
12684 				 * XXX dont' update if the created_v4 flag
12685 				 * is set
12686 				 */
12687 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12688 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12689 				    "nfs4_update_dircaches: don't"
12690 				    " update dnlc: created_v4 flag"));
12691 			}
12692 		}
12693 	} else {
12694 		/* Another client modified directory - purge its dnlc cache */
12695 		dnlc_purge_vp(dvp);
12696 	}
12697 }
12698 
12699 /*
12700  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12701  * file.
12702  *
12703  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12704  * file (ie: client recovery) and otherwise set to FALSE.
12705  *
12706  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12707  * initiated) calling functions.
12708  *
12709  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12710  * of resending a 'lost' open request.
12711  *
12712  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12713  * server that hands out BAD_SEQID on open confirm.
12714  *
12715  * Errors are returned via the nfs4_error_t parameter.
12716  */
12717 void
12718 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12719     bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12720     bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12721 {
12722 	COMPOUND4args_clnt args;
12723 	COMPOUND4res_clnt res;
12724 	nfs_argop4 argop[2];
12725 	nfs_resop4 *resop;
12726 	int doqueue = 1;
12727 	mntinfo4_t *mi;
12728 	OPEN_CONFIRM4args *open_confirm_args;
12729 	int needrecov;
12730 
12731 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12732 #if DEBUG
12733 	mutex_enter(&oop->oo_lock);
12734 	ASSERT(oop->oo_seqid_inuse);
12735 	mutex_exit(&oop->oo_lock);
12736 #endif
12737 
12738 recov_retry_confirm:
12739 	nfs4_error_zinit(ep);
12740 	*retry_open = FALSE;
12741 
12742 	if (resend)
12743 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12744 	else
12745 		args.ctag = TAG_OPEN_CONFIRM;
12746 
12747 	args.array_len = 2;
12748 	args.array = argop;
12749 
12750 	/* putfh target fh */
12751 	argop[0].argop = OP_CPUTFH;
12752 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12753 
12754 	argop[1].argop = OP_OPEN_CONFIRM;
12755 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12756 
12757 	(*seqid) += 1;
12758 	open_confirm_args->seqid = *seqid;
12759 	open_confirm_args->open_stateid = *stateid;
12760 
12761 	mi = VTOMI4(vp);
12762 
12763 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12764 
12765 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12766 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12767 	}
12768 
12769 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12770 	if (!needrecov && ep->error)
12771 		return;
12772 
12773 	if (needrecov) {
12774 		bool_t abort = FALSE;
12775 
12776 		if (reopening_file == FALSE) {
12777 			nfs4_bseqid_entry_t *bsep = NULL;
12778 
12779 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12780 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12781 				    vp, 0, args.ctag,
12782 				    open_confirm_args->seqid);
12783 
12784 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
12785 			    NULL, NULL, OP_OPEN_CONFIRM, bsep, NULL, NULL);
12786 			if (bsep) {
12787 				kmem_free(bsep, sizeof (*bsep));
12788 				if (num_bseqid_retryp &&
12789 				    --(*num_bseqid_retryp) == 0)
12790 					abort = TRUE;
12791 			}
12792 		}
12793 		if ((ep->error == ETIMEDOUT ||
12794 		    res.status == NFS4ERR_RESOURCE) &&
12795 		    abort == FALSE && resend == FALSE) {
12796 			if (!ep->error)
12797 				xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12798 
12799 			delay(SEC_TO_TICK(confirm_retry_sec));
12800 			goto recov_retry_confirm;
12801 		}
12802 		/* State may have changed so retry the entire OPEN op */
12803 		if (abort == FALSE)
12804 			*retry_open = TRUE;
12805 		else
12806 			*retry_open = FALSE;
12807 		if (!ep->error)
12808 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12809 		return;
12810 	}
12811 
12812 	if (res.status) {
12813 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12814 		return;
12815 	}
12816 
12817 	resop = &res.array[1];  /* open confirm res */
12818 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
12819 	    stateid, sizeof (*stateid));
12820 
12821 	xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12822 }
12823 
12824 /*
12825  * Return the credentials associated with a client state object.  The
12826  * caller is responsible for freeing the credentials.
12827  */
12828 
12829 static cred_t *
12830 state_to_cred(nfs4_open_stream_t *osp)
12831 {
12832 	cred_t *cr;
12833 
12834 	/*
12835 	 * It's ok to not lock the open stream and open owner to get
12836 	 * the oo_cred since this is only written once (upon creation)
12837 	 * and will not change.
12838 	 */
12839 	cr = osp->os_open_owner->oo_cred;
12840 	crhold(cr);
12841 
12842 	return (cr);
12843 }
12844 
12845 /*
12846  * nfs4_find_sysid
12847  *
12848  * Find the sysid for the knetconfig associated with the given mi.
12849  */
12850 static struct lm_sysid *
12851 nfs4_find_sysid(mntinfo4_t *mi)
12852 {
12853 	ASSERT(nfs_zone() == mi->mi_zone);
12854 
12855 	/*
12856 	 * Switch from RDMA knconf to original mount knconf
12857 	 */
12858 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
12859 	    mi->mi_curr_serv->sv_hostname, NULL));
12860 }
12861 
12862 #ifdef DEBUG
12863 /*
12864  * Return a string version of the call type for easy reading.
12865  */
12866 static char *
12867 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
12868 {
12869 	switch (ctype) {
12870 	case NFS4_LCK_CTYPE_NORM:
12871 		return ("NORMAL");
12872 	case NFS4_LCK_CTYPE_RECLAIM:
12873 		return ("RECLAIM");
12874 	case NFS4_LCK_CTYPE_RESEND:
12875 		return ("RESEND");
12876 	case NFS4_LCK_CTYPE_REINSTATE:
12877 		return ("REINSTATE");
12878 	default:
12879 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
12880 		    "type %d", ctype);
12881 		return ("");
12882 	}
12883 }
12884 #endif
12885 
12886 /*
12887  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
12888  * Unlock requests don't have an over-the-wire locktype, so we just return
12889  * something non-threatening.
12890  */
12891 
12892 static nfs_lock_type4
12893 flk_to_locktype(int cmd, int l_type)
12894 {
12895 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
12896 
12897 	switch (l_type) {
12898 	case F_UNLCK:
12899 		return (READ_LT);
12900 	case F_RDLCK:
12901 		if (cmd == F_SETLK)
12902 			return (READ_LT);
12903 		else
12904 			return (READW_LT);
12905 	case F_WRLCK:
12906 		if (cmd == F_SETLK)
12907 			return (WRITE_LT);
12908 		else
12909 			return (WRITEW_LT);
12910 	}
12911 	panic("flk_to_locktype");
12912 	/*NOTREACHED*/
12913 }
12914 
12915 /*
12916  * Do some preliminary checks for nfs4frlock.
12917  */
12918 static int
12919 nfs4frlock_validate_args(int cmd, flock64_t *flk, int flag, vnode_t *vp,
12920     u_offset_t offset)
12921 {
12922 	int error = 0;
12923 
12924 	/*
12925 	 * If we are setting a lock, check that the file is opened
12926 	 * with the correct mode.
12927 	 */
12928 	if (cmd == F_SETLK || cmd == F_SETLKW) {
12929 		if ((flk->l_type == F_RDLCK && (flag & FREAD) == 0) ||
12930 		    (flk->l_type == F_WRLCK && (flag & FWRITE) == 0)) {
12931 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12932 			    "nfs4frlock_validate_args: file was opened with "
12933 			    "incorrect mode"));
12934 			return (EBADF);
12935 		}
12936 	}
12937 
12938 	/* Convert the offset. It may need to be restored before returning. */
12939 	if (error = convoff(vp, flk, 0, offset)) {
12940 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12941 		    "nfs4frlock_validate_args: convoff  =>  error= %d\n",
12942 		    error));
12943 		return (error);
12944 	}
12945 
12946 	return (error);
12947 }
12948 
12949 /*
12950  * Set the flock64's lm_sysid for nfs4frlock.
12951  */
12952 static int
12953 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
12954 {
12955 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12956 
12957 	/* Find the lm_sysid */
12958 	*lspp = nfs4_find_sysid(VTOMI4(vp));
12959 
12960 	if (*lspp == NULL) {
12961 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12962 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
12963 		return (ENOLCK);
12964 	}
12965 
12966 	flk->l_sysid = lm_sysidt(*lspp);
12967 
12968 	return (0);
12969 }
12970 
12971 /*
12972  * Do the remaining preliminary setup for nfs4frlock.
12973  */
12974 static void
12975 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
12976     flock64_t *flk, short *whencep, vnode_t *vp, cred_t *search_cr,
12977     cred_t **cred_otw)
12978 {
12979 	/*
12980 	 * set tick_delay to the base delay time.
12981 	 * (NFS4_BASE_WAIT_TIME is in secs)
12982 	 */
12983 
12984 	*tick_delayp = drv_usectohz(NFS4_BASE_WAIT_TIME * 1000 * 1000);
12985 
12986 	/*
12987 	 * If lock is relative to EOF, we need the newest length of the
12988 	 * file. Therefore invalidate the ATTR_CACHE.
12989 	 */
12990 
12991 	*whencep = flk->l_whence;
12992 
12993 	if (*whencep == 2)		/* SEEK_END */
12994 		PURGE_ATTRCACHE4(vp);
12995 
12996 	recov_statep->rs_flags = 0;
12997 	recov_statep->rs_num_retry_despite_err = 0;
12998 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
12999 }
13000 
13001 /*
13002  * Initialize and allocate the data structures necessary for
13003  * the nfs4frlock call.
13004  * Allocates argsp's op array.
13005  */
13006 static void
13007 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
13008     nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
13009     bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
13010     bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
13011 {
13012 	int		argoplist_size;
13013 	int		num_ops = 2;
13014 
13015 	*retry = FALSE;
13016 	*did_start_fop = FALSE;
13017 	*skip_get_err = FALSE;
13018 	lost_rqstp->lr_op = 0;
13019 	argoplist_size  = num_ops * sizeof (nfs_argop4);
13020 	/* fill array with zero */
13021 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
13022 
13023 	*argspp = argsp;
13024 	*respp = NULL;
13025 
13026 	argsp->array_len = num_ops;
13027 	argsp->array = *argopp;
13028 
13029 	/* initialize in case of error; will get real value down below */
13030 	argsp->ctag = TAG_NONE;
13031 
13032 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
13033 		*op_hintp = OH_LOCKU;
13034 	else
13035 		*op_hintp = OH_OTHER;
13036 }
13037 
13038 /*
13039  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
13040  * the proper nfs4_server_t for this instance of nfs4frlock.
13041  * Returns 0 (success) or an errno value.
13042  */
13043 static int
13044 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
13045     nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
13046     bool_t *did_start_fop, bool_t *startrecovp)
13047 {
13048 	int error = 0;
13049 	rnode4_t *rp;
13050 
13051 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13052 
13053 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13054 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
13055 		    recov_statep, startrecovp);
13056 		if (error)
13057 			return (error);
13058 		*did_start_fop = TRUE;
13059 	} else {
13060 		*did_start_fop = FALSE;
13061 		*startrecovp = FALSE;
13062 	}
13063 
13064 	if (!error) {
13065 		rp = VTOR4(vp);
13066 
13067 		/* If the file failed recovery, just quit. */
13068 		mutex_enter(&rp->r_statelock);
13069 		if (rp->r_flags & R4RECOVERR) {
13070 			error = EIO;
13071 		}
13072 		mutex_exit(&rp->r_statelock);
13073 	}
13074 
13075 	return (error);
13076 }
13077 
13078 /*
13079  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
13080  * resend nfs4frlock call is initiated by the recovery framework.
13081  * Acquires the lop and oop seqid synchronization.
13082  */
13083 static void
13084 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
13085     COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
13086     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13087     LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
13088 {
13089 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
13090 	int error;
13091 
13092 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
13093 	    (CE_NOTE,
13094 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
13095 	ASSERT(resend_rqstp != NULL);
13096 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
13097 	    resend_rqstp->lr_op == OP_LOCKU);
13098 
13099 	*oopp = resend_rqstp->lr_oop;
13100 	if (resend_rqstp->lr_oop) {
13101 		open_owner_hold(resend_rqstp->lr_oop);
13102 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
13103 		ASSERT(error == 0);	/* recov thread always succeeds */
13104 	}
13105 
13106 	/* Must resend this lost lock/locku request. */
13107 	ASSERT(resend_rqstp->lr_lop != NULL);
13108 	*lopp = resend_rqstp->lr_lop;
13109 	lock_owner_hold(resend_rqstp->lr_lop);
13110 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
13111 	ASSERT(error == 0);	/* recov thread always succeeds */
13112 
13113 	*ospp = resend_rqstp->lr_osp;
13114 	if (*ospp)
13115 		open_stream_hold(resend_rqstp->lr_osp);
13116 
13117 	if (resend_rqstp->lr_op == OP_LOCK) {
13118 		LOCK4args *lock_args;
13119 
13120 		argop->argop = OP_LOCK;
13121 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
13122 		lock_args->locktype = resend_rqstp->lr_locktype;
13123 		lock_args->reclaim =
13124 		    (resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
13125 		lock_args->offset = resend_rqstp->lr_flk->l_start;
13126 		lock_args->length = resend_rqstp->lr_flk->l_len;
13127 		if (lock_args->length == 0)
13128 			lock_args->length = ~lock_args->length;
13129 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
13130 		    mi2clientid(mi), &lock_args->locker);
13131 
13132 		switch (resend_rqstp->lr_ctype) {
13133 		case NFS4_LCK_CTYPE_RESEND:
13134 			argsp->ctag = TAG_LOCK_RESEND;
13135 			break;
13136 		case NFS4_LCK_CTYPE_REINSTATE:
13137 			argsp->ctag = TAG_LOCK_REINSTATE;
13138 			break;
13139 		case NFS4_LCK_CTYPE_RECLAIM:
13140 			argsp->ctag = TAG_LOCK_RECLAIM;
13141 			break;
13142 		default:
13143 			argsp->ctag = TAG_LOCK_UNKNOWN;
13144 			break;
13145 		}
13146 	} else {
13147 		LOCKU4args *locku_args;
13148 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
13149 
13150 		argop->argop = OP_LOCKU;
13151 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
13152 		locku_args->locktype = READ_LT;
13153 		locku_args->seqid = lop->lock_seqid + 1;
13154 		mutex_enter(&lop->lo_lock);
13155 		locku_args->lock_stateid = lop->lock_stateid;
13156 		mutex_exit(&lop->lo_lock);
13157 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13158 		locku_args->length = resend_rqstp->lr_flk->l_len;
13159 		if (locku_args->length == 0)
13160 			locku_args->length = ~locku_args->length;
13161 
13162 		switch (resend_rqstp->lr_ctype) {
13163 		case NFS4_LCK_CTYPE_RESEND:
13164 			argsp->ctag = TAG_LOCKU_RESEND;
13165 			break;
13166 		case NFS4_LCK_CTYPE_REINSTATE:
13167 			argsp->ctag = TAG_LOCKU_REINSTATE;
13168 			break;
13169 		default:
13170 			argsp->ctag = TAG_LOCK_UNKNOWN;
13171 			break;
13172 		}
13173 	}
13174 }
13175 
13176 /*
13177  * Setup the LOCKT4 arguments.
13178  */
13179 static void
13180 nfs4frlock_setup_lockt_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13181     LOCKT4args **lockt_argsp, COMPOUND4args_clnt *argsp, flock64_t *flk,
13182     rnode4_t *rp)
13183 {
13184 	LOCKT4args *lockt_args;
13185 
13186 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13187 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13188 	argop->argop = OP_LOCKT;
13189 	argsp->ctag = TAG_LOCKT;
13190 	lockt_args = &argop->nfs_argop4_u.oplockt;
13191 
13192 	/*
13193 	 * The locktype will be READ_LT unless it's
13194 	 * a write lock. We do this because the Solaris
13195 	 * system call allows the combination of
13196 	 * F_UNLCK and F_GETLK* and so in that case the
13197 	 * unlock is mapped to a read.
13198 	 */
13199 	if (flk->l_type == F_WRLCK)
13200 		lockt_args->locktype = WRITE_LT;
13201 	else
13202 		lockt_args->locktype = READ_LT;
13203 
13204 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13205 	/* set the lock owner4 args */
13206 	nfs4_setlockowner_args(&lockt_args->owner, rp,
13207 	    ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13208 	    flk->l_pid);
13209 	lockt_args->offset = flk->l_start;
13210 	lockt_args->length = flk->l_len;
13211 	if (flk->l_len == 0)
13212 		lockt_args->length = ~lockt_args->length;
13213 
13214 	*lockt_argsp = lockt_args;
13215 }
13216 
13217 /*
13218  * If the client is holding a delegation, and the open stream to be used
13219  * with this lock request is a delegation open stream, then re-open the stream.
13220  * Sets the nfs4_error_t to all zeros unless the open stream has already
13221  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13222  * means the caller should retry (like a recovery retry).
13223  */
13224 static void
13225 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13226 {
13227 	open_delegation_type4	dt;
13228 	bool_t			reopen_needed, force;
13229 	nfs4_open_stream_t	*osp;
13230 	open_claim_type4	oclaim;
13231 	rnode4_t		*rp = VTOR4(vp);
13232 	mntinfo4_t		*mi = VTOMI4(vp);
13233 
13234 	ASSERT(nfs_zone() == mi->mi_zone);
13235 
13236 	nfs4_error_zinit(ep);
13237 
13238 	mutex_enter(&rp->r_statev4_lock);
13239 	dt = rp->r_deleg_type;
13240 	mutex_exit(&rp->r_statev4_lock);
13241 
13242 	if (dt != OPEN_DELEGATE_NONE) {
13243 		nfs4_open_owner_t	*oop;
13244 
13245 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13246 		if (!oop) {
13247 			ep->stat = NFS4ERR_IO;
13248 			return;
13249 		}
13250 		/* returns with 'os_sync_lock' held */
13251 		osp = find_open_stream(oop, rp);
13252 		if (!osp) {
13253 			open_owner_rele(oop);
13254 			ep->stat = NFS4ERR_IO;
13255 			return;
13256 		}
13257 
13258 		if (osp->os_failed_reopen) {
13259 			NFS4_DEBUG((nfs4_open_stream_debug ||
13260 			    nfs4_client_lock_debug), (CE_NOTE,
13261 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13262 			    "for osp %p, cr %p, rp %s", (void *)osp,
13263 			    (void *)cr, rnode4info(rp)));
13264 			mutex_exit(&osp->os_sync_lock);
13265 			open_stream_rele(osp, rp);
13266 			open_owner_rele(oop);
13267 			ep->stat = NFS4ERR_IO;
13268 			return;
13269 		}
13270 
13271 		/*
13272 		 * Determine whether a reopen is needed.  If this
13273 		 * is a delegation open stream, then send the open
13274 		 * to the server to give visibility to the open owner.
13275 		 * Even if it isn't a delegation open stream, we need
13276 		 * to check if the previous open CLAIM_DELEGATE_CUR
13277 		 * was sufficient.
13278 		 */
13279 
13280 		reopen_needed = osp->os_delegation ||
13281 		    ((lt == F_RDLCK &&
13282 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13283 		    (lt == F_WRLCK &&
13284 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13285 
13286 		mutex_exit(&osp->os_sync_lock);
13287 		open_owner_rele(oop);
13288 
13289 		if (reopen_needed) {
13290 			/*
13291 			 * Always use CLAIM_PREVIOUS after server reboot.
13292 			 * The server will reject CLAIM_DELEGATE_CUR if
13293 			 * it is used during the grace period.
13294 			 */
13295 			mutex_enter(&mi->mi_lock);
13296 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13297 				oclaim = CLAIM_PREVIOUS;
13298 				force = TRUE;
13299 			} else {
13300 				oclaim = CLAIM_DELEGATE_CUR;
13301 				force = FALSE;
13302 			}
13303 			mutex_exit(&mi->mi_lock);
13304 
13305 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13306 			if (ep->error == EAGAIN) {
13307 				nfs4_error_zinit(ep);
13308 				ep->stat = NFS4ERR_DELAY;
13309 			}
13310 		}
13311 		open_stream_rele(osp, rp);
13312 		osp = NULL;
13313 	}
13314 }
13315 
13316 /*
13317  * Setup the LOCKU4 arguments.
13318  * Returns errors via the nfs4_error_t.
13319  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13320  *			over-the-wire.  The caller must release the
13321  *			reference on *lopp.
13322  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13323  * (other)		unrecoverable error.
13324  */
13325 static void
13326 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13327     LOCKU4args **locku_argsp, flock64_t *flk,
13328     nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13329     vnode_t *vp, int flag, u_offset_t offset, cred_t *cr,
13330     bool_t *skip_get_err, bool_t *go_otwp)
13331 {
13332 	nfs4_lock_owner_t	*lop = NULL;
13333 	LOCKU4args		*locku_args;
13334 	pid_t			pid;
13335 	bool_t			is_spec = FALSE;
13336 	rnode4_t		*rp = VTOR4(vp);
13337 
13338 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13339 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13340 
13341 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13342 	if (ep->error || ep->stat)
13343 		return;
13344 
13345 	argop->argop = OP_LOCKU;
13346 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13347 		argsp->ctag = TAG_LOCKU_REINSTATE;
13348 	else
13349 		argsp->ctag = TAG_LOCKU;
13350 	locku_args = &argop->nfs_argop4_u.oplocku;
13351 	*locku_argsp = locku_args;
13352 
13353 	/* locktype should be set to any legal value */
13354 	locku_args->locktype = READ_LT;
13355 
13356 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13357 	    flk->l_pid;
13358 
13359 	/*
13360 	 * Get the lock owner stateid.  If no lock owner
13361 	 * exists, return success.
13362 	 */
13363 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13364 	*lopp = lop;
13365 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13366 		is_spec = TRUE;
13367 	if (!lop || is_spec) {
13368 		/*
13369 		 * No lock owner so no locks to unlock.
13370 		 * Return success.  If there was a failed
13371 		 * reclaim earlier, the lock might still be
13372 		 * registered with the local locking code,
13373 		 * so notify it of the unlock.
13374 		 *
13375 		 * If the lockowner is using a special stateid,
13376 		 * then the original lock request (that created
13377 		 * this lockowner) was never successful, so we
13378 		 * have no lock to undo OTW.
13379 		 */
13380 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13381 		    "nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13382 		    "(%ld) so return success", (long)pid));
13383 
13384 		if (ctype == NFS4_LCK_CTYPE_NORM)
13385 			flk->l_pid = curproc->p_pid;
13386 		nfs4_register_lock_locally(vp, flk, flag, offset);
13387 		/*
13388 		 * Release our hold and NULL out so final_cleanup
13389 		 * doesn't try to end a lock seqid sync we
13390 		 * never started.
13391 		 */
13392 		if (is_spec) {
13393 			lock_owner_rele(lop);
13394 			*lopp = NULL;
13395 		}
13396 		*skip_get_err = TRUE;
13397 		*go_otwp = FALSE;
13398 		return;
13399 	}
13400 
13401 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13402 	if (ep->error == EAGAIN) {
13403 		lock_owner_rele(lop);
13404 		*lopp = NULL;
13405 		return;
13406 	}
13407 
13408 	mutex_enter(&lop->lo_lock);
13409 	locku_args->lock_stateid = lop->lock_stateid;
13410 	mutex_exit(&lop->lo_lock);
13411 	locku_args->seqid = lop->lock_seqid + 1;
13412 
13413 	/* leave the ref count on lop, rele after RPC call */
13414 
13415 	locku_args->offset = flk->l_start;
13416 	locku_args->length = flk->l_len;
13417 	if (flk->l_len == 0)
13418 		locku_args->length = ~locku_args->length;
13419 
13420 	*go_otwp = TRUE;
13421 }
13422 
13423 /*
13424  * Setup the LOCK4 arguments.
13425  *
13426  * Returns errors via the nfs4_error_t.
13427  * NFS4_OK		no problems
13428  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13429  * (other)		unrecoverable error
13430  */
13431 static void
13432 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13433     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13434     nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13435     flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13436 {
13437 	LOCK4args		*lock_args;
13438 	nfs4_open_owner_t	*oop = NULL;
13439 	nfs4_open_stream_t	*osp = NULL;
13440 	nfs4_lock_owner_t	*lop = NULL;
13441 	pid_t			pid;
13442 	rnode4_t		*rp = VTOR4(vp);
13443 
13444 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13445 
13446 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13447 	if (ep->error || ep->stat != NFS4_OK)
13448 		return;
13449 
13450 	argop->argop = OP_LOCK;
13451 	if (ctype == NFS4_LCK_CTYPE_NORM)
13452 		argsp->ctag = TAG_LOCK;
13453 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13454 		argsp->ctag = TAG_RELOCK;
13455 	else
13456 		argsp->ctag = TAG_LOCK_REINSTATE;
13457 	lock_args = &argop->nfs_argop4_u.oplock;
13458 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13459 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13460 	/*
13461 	 * Get the lock owner.  If no lock owner exists,
13462 	 * create a 'temporary' one and grab the open seqid
13463 	 * synchronization (which puts a hold on the open
13464 	 * owner and open stream).
13465 	 * This also grabs the lock seqid synchronization.
13466 	 */
13467 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid : flk->l_pid;
13468 	ep->stat =
13469 	    nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13470 
13471 	if (ep->stat != NFS4_OK)
13472 		goto out;
13473 
13474 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13475 	    &lock_args->locker);
13476 
13477 	lock_args->offset = flk->l_start;
13478 	lock_args->length = flk->l_len;
13479 	if (flk->l_len == 0)
13480 		lock_args->length = ~lock_args->length;
13481 	*lock_argsp = lock_args;
13482 out:
13483 	*oopp = oop;
13484 	*ospp = osp;
13485 	*lopp = lop;
13486 }
13487 
13488 /*
13489  * After we get the reply from the server, record the proper information
13490  * for possible resend lock requests.
13491  */
13492 static void
13493 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13494     nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13495     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13496     nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13497 {
13498 	bool_t unlock = (flk->l_type == F_UNLCK);
13499 
13500 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13501 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13502 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13503 
13504 	if (error != 0 && !unlock) {
13505 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13506 		    nfs4_client_lock_debug), (CE_NOTE,
13507 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13508 		    " for lop %p", (void *)lop));
13509 		ASSERT(lop != NULL);
13510 		mutex_enter(&lop->lo_lock);
13511 		lop->lo_pending_rqsts = 1;
13512 		mutex_exit(&lop->lo_lock);
13513 	}
13514 
13515 	lost_rqstp->lr_putfirst = FALSE;
13516 	lost_rqstp->lr_op = 0;
13517 
13518 	/*
13519 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13520 	 * recovery purposes so that the lock request that was sent
13521 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13522 	 * unmount.  This is done to have the client's local locking state
13523 	 * match the v4 server's state; that is, the request was
13524 	 * potentially received and accepted by the server but the client
13525 	 * thinks it was not.
13526 	 */
13527 	if (error == ETIMEDOUT || error == EINTR ||
13528 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13529 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13530 		    nfs4_client_lock_debug), (CE_NOTE,
13531 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13532 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13533 		    (void *)lop, (void *)oop, (void *)osp));
13534 		if (unlock)
13535 			lost_rqstp->lr_op = OP_LOCKU;
13536 		else {
13537 			lost_rqstp->lr_op = OP_LOCK;
13538 			lost_rqstp->lr_locktype = locktype;
13539 		}
13540 		/*
13541 		 * Objects are held and rele'd via the recovery code.
13542 		 * See nfs4_save_lost_rqst.
13543 		 */
13544 		lost_rqstp->lr_vp = vp;
13545 		lost_rqstp->lr_dvp = NULL;
13546 		lost_rqstp->lr_oop = oop;
13547 		lost_rqstp->lr_osp = osp;
13548 		lost_rqstp->lr_lop = lop;
13549 		lost_rqstp->lr_cr = cr;
13550 		switch (ctype) {
13551 		case NFS4_LCK_CTYPE_NORM:
13552 			flk->l_pid = ttoproc(curthread)->p_pid;
13553 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13554 			break;
13555 		case NFS4_LCK_CTYPE_REINSTATE:
13556 			lost_rqstp->lr_putfirst = TRUE;
13557 			lost_rqstp->lr_ctype = ctype;
13558 			break;
13559 		default:
13560 			break;
13561 		}
13562 		lost_rqstp->lr_flk = flk;
13563 	}
13564 }
13565 
13566 /*
13567  * Update lop's seqid.  Also update the seqid stored in a resend request,
13568  * if any.  (Some recovery errors increment the seqid, and we may have to
13569  * send the resend request again.)
13570  */
13571 
13572 static void
13573 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13574     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13575 {
13576 	if (lock_args) {
13577 		if (lock_args->locker.new_lock_owner == TRUE)
13578 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13579 		else {
13580 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13581 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13582 		}
13583 	} else if (locku_args) {
13584 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13585 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13586 	}
13587 }
13588 
13589 /*
13590  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13591  * COMPOUND4 args/res for calls that need to retry.
13592  * Switches the *cred_otwp to base_cr.
13593  */
13594 static void
13595 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13596     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13597     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13598     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13599     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13600 {
13601 	nfs4_open_owner_t	*oop = *oopp;
13602 	nfs4_open_stream_t	*osp = *ospp;
13603 	nfs4_lock_owner_t	*lop = *lopp;
13604 	nfs_argop4		*argop = (*argspp)->array;
13605 
13606 	if (*did_start_fop) {
13607 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13608 		    needrecov);
13609 		*did_start_fop = FALSE;
13610 	}
13611 	ASSERT((*argspp)->array_len == 2);
13612 	if (argop[1].argop == OP_LOCK)
13613 		nfs4args_lock_free(&argop[1]);
13614 	else if (argop[1].argop == OP_LOCKT)
13615 		nfs4args_lockt_free(&argop[1]);
13616 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13617 	if (!error)
13618 		xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13619 	*argspp = NULL;
13620 	*respp = NULL;
13621 
13622 	if (lop) {
13623 		nfs4_end_lock_seqid_sync(lop);
13624 		lock_owner_rele(lop);
13625 		*lopp = NULL;
13626 	}
13627 
13628 	/* need to free up the reference on osp for lock args */
13629 	if (osp != NULL) {
13630 		open_stream_rele(osp, VTOR4(vp));
13631 		*ospp = NULL;
13632 	}
13633 
13634 	/* need to free up the reference on oop for lock args */
13635 	if (oop != NULL) {
13636 		nfs4_end_open_seqid_sync(oop);
13637 		open_owner_rele(oop);
13638 		*oopp = NULL;
13639 	}
13640 
13641 	crfree(*cred_otwp);
13642 	*cred_otwp = base_cr;
13643 	crhold(*cred_otwp);
13644 }
13645 
13646 /*
13647  * Function to process the client's recovery for nfs4frlock.
13648  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13649  *
13650  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13651  * COMPOUND4 args/res for calls that need to retry.
13652  *
13653  * Note: the rp's r_lkserlock is *not* dropped during this path.
13654  */
13655 static bool_t
13656 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13657     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13658     LOCK4args *lock_args, LOCKU4args *locku_args,
13659     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13660     nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13661     nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13662     bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13663 {
13664 	nfs4_open_owner_t	*oop = *oopp;
13665 	nfs4_open_stream_t	*osp = *ospp;
13666 	nfs4_lock_owner_t	*lop = *lopp;
13667 
13668 	bool_t abort, retry;
13669 
13670 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13671 	ASSERT((*argspp) != NULL);
13672 	ASSERT((*respp) != NULL);
13673 	if (lock_args || locku_args)
13674 		ASSERT(lop != NULL);
13675 
13676 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13677 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13678 
13679 	retry = TRUE;
13680 	abort = FALSE;
13681 	if (needrecov) {
13682 		nfs4_bseqid_entry_t *bsep = NULL;
13683 		nfs_opnum4 op;
13684 
13685 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13686 
13687 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13688 			seqid4 seqid;
13689 
13690 			if (lock_args) {
13691 				if (lock_args->locker.new_lock_owner == TRUE)
13692 					seqid = lock_args->locker.locker4_u.
13693 					    open_owner.open_seqid;
13694 				else
13695 					seqid = lock_args->locker.locker4_u.
13696 					    lock_owner.lock_seqid;
13697 			} else if (locku_args) {
13698 				seqid = locku_args->seqid;
13699 			} else {
13700 				seqid = 0;
13701 			}
13702 
13703 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13704 			    flk->l_pid, (*argspp)->ctag, seqid);
13705 		}
13706 
13707 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13708 		    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13709 		    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13710 		    NULL, op, bsep, NULL, NULL);
13711 
13712 		if (bsep)
13713 			kmem_free(bsep, sizeof (*bsep));
13714 	}
13715 
13716 	/*
13717 	 * Return that we do not want to retry the request for 3 cases:
13718 	 * 1. If we received EINTR or are bailing out because of a forced
13719 	 *    unmount, we came into this code path just for the sake of
13720 	 *    initiating recovery, we now need to return the error.
13721 	 * 2. If we have aborted recovery.
13722 	 * 3. We received NFS4ERR_BAD_SEQID.
13723 	 */
13724 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13725 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13726 		retry = FALSE;
13727 
13728 	if (*did_start_fop == TRUE) {
13729 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13730 		    needrecov);
13731 		*did_start_fop = FALSE;
13732 	}
13733 
13734 	if (retry == TRUE) {
13735 		nfs_argop4	*argop;
13736 
13737 		argop = (*argspp)->array;
13738 		ASSERT((*argspp)->array_len == 2);
13739 
13740 		if (argop[1].argop == OP_LOCK)
13741 			nfs4args_lock_free(&argop[1]);
13742 		else if (argop[1].argop == OP_LOCKT)
13743 			nfs4args_lockt_free(&argop[1]);
13744 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13745 		if (!ep->error)
13746 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13747 		*respp = NULL;
13748 		*argspp = NULL;
13749 	}
13750 
13751 	if (lop != NULL) {
13752 		nfs4_end_lock_seqid_sync(lop);
13753 		lock_owner_rele(lop);
13754 	}
13755 
13756 	*lopp = NULL;
13757 
13758 	/* need to free up the reference on osp for lock args */
13759 	if (osp != NULL) {
13760 		open_stream_rele(osp, rp);
13761 		*ospp = NULL;
13762 	}
13763 
13764 	/* need to free up the reference on oop for lock args */
13765 	if (oop != NULL) {
13766 		nfs4_end_open_seqid_sync(oop);
13767 		open_owner_rele(oop);
13768 		*oopp = NULL;
13769 	}
13770 
13771 	return (retry);
13772 }
13773 
13774 /*
13775  * Handles the successful reply from the server for nfs4frlock.
13776  */
13777 static void
13778 nfs4frlock_results_ok(nfs4_lock_call_type_t ctype, int cmd, flock64_t *flk,
13779     vnode_t *vp, int flag, u_offset_t offset,
13780     nfs4_lost_rqst_t *resend_rqstp)
13781 {
13782 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13783 	if ((cmd == F_SETLK || cmd == F_SETLKW) &&
13784 	    (flk->l_type == F_RDLCK || flk->l_type == F_WRLCK)) {
13785 		if (ctype == NFS4_LCK_CTYPE_NORM) {
13786 			flk->l_pid = ttoproc(curthread)->p_pid;
13787 			/*
13788 			 * We do not register lost locks locally in
13789 			 * the 'resend' case since the user/application
13790 			 * doesn't think we have the lock.
13791 			 */
13792 			ASSERT(!resend_rqstp);
13793 			nfs4_register_lock_locally(vp, flk, flag, offset);
13794 		}
13795 	}
13796 }
13797 
13798 /*
13799  * Handle the DENIED reply from the server for nfs4frlock.
13800  * Returns TRUE if we should retry the request; FALSE otherwise.
13801  *
13802  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13803  * COMPOUND4 args/res for calls that need to retry.  Can also
13804  * drop and regrab the r_lkserlock.
13805  */
13806 static bool_t
13807 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13808     LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13809     nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13810     vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13811     nfs4_recov_state_t *recov_statep, int needrecov,
13812     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13813     clock_t *tick_delayp, short *whencep, int *errorp,
13814     nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13815     bool_t *skip_get_err)
13816 {
13817 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13818 
13819 	if (lock_args) {
13820 		nfs4_open_owner_t	*oop = *oopp;
13821 		nfs4_open_stream_t	*osp = *ospp;
13822 		nfs4_lock_owner_t	*lop = *lopp;
13823 		int			intr;
13824 
13825 		/*
13826 		 * Blocking lock needs to sleep and retry from the request.
13827 		 *
13828 		 * Do not block and wait for 'resend' or 'reinstate'
13829 		 * lock requests, just return the error.
13830 		 *
13831 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13832 		 */
13833 		if (cmd == F_SETLKW) {
13834 			rnode4_t *rp = VTOR4(vp);
13835 			nfs_argop4 *argop = (*argspp)->array;
13836 
13837 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13838 
13839 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13840 			    recov_statep, needrecov);
13841 			*did_start_fop = FALSE;
13842 			ASSERT((*argspp)->array_len == 2);
13843 			if (argop[1].argop == OP_LOCK)
13844 				nfs4args_lock_free(&argop[1]);
13845 			else if (argop[1].argop == OP_LOCKT)
13846 				nfs4args_lockt_free(&argop[1]);
13847 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13848 			if (*respp)
13849 				xdr_free(xdr_COMPOUND4res_clnt,
13850 				    (caddr_t)*respp);
13851 			*argspp = NULL;
13852 			*respp = NULL;
13853 			nfs4_end_lock_seqid_sync(lop);
13854 			lock_owner_rele(lop);
13855 			*lopp = NULL;
13856 			if (osp != NULL) {
13857 				open_stream_rele(osp, rp);
13858 				*ospp = NULL;
13859 			}
13860 			if (oop != NULL) {
13861 				nfs4_end_open_seqid_sync(oop);
13862 				open_owner_rele(oop);
13863 				*oopp = NULL;
13864 			}
13865 
13866 			nfs_rw_exit(&rp->r_lkserlock);
13867 
13868 			intr = nfs4_block_and_wait(tick_delayp, rp);
13869 
13870 			if (intr) {
13871 				(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13872 				    RW_WRITER, FALSE);
13873 				*errorp = EINTR;
13874 				return (FALSE);
13875 			}
13876 
13877 			(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13878 			    RW_WRITER, FALSE);
13879 
13880 			/*
13881 			 * Make sure we are still safe to lock with
13882 			 * regards to mmapping.
13883 			 */
13884 			if (!nfs4_safelock(vp, flk, cr)) {
13885 				*errorp = EAGAIN;
13886 				return (FALSE);
13887 			}
13888 
13889 			return (TRUE);
13890 		}
13891 		if (ctype == NFS4_LCK_CTYPE_NORM)
13892 			*errorp = EAGAIN;
13893 		*skip_get_err = TRUE;
13894 		flk->l_whence = 0;
13895 		*whencep = 0;
13896 		return (FALSE);
13897 	} else if (lockt_args) {
13898 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13899 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
13900 
13901 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
13902 		    flk, lockt_args);
13903 
13904 		/* according to NLM code */
13905 		*errorp = 0;
13906 		*whencep = 0;
13907 		*skip_get_err = TRUE;
13908 		return (FALSE);
13909 	}
13910 	return (FALSE);
13911 }
13912 
13913 /*
13914  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
13915  */
13916 static void
13917 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
13918 {
13919 	switch (resp->status) {
13920 	case NFS4ERR_ACCESS:
13921 	case NFS4ERR_ADMIN_REVOKED:
13922 	case NFS4ERR_BADHANDLE:
13923 	case NFS4ERR_BAD_RANGE:
13924 	case NFS4ERR_BAD_SEQID:
13925 	case NFS4ERR_BAD_STATEID:
13926 	case NFS4ERR_BADXDR:
13927 	case NFS4ERR_DEADLOCK:
13928 	case NFS4ERR_DELAY:
13929 	case NFS4ERR_EXPIRED:
13930 	case NFS4ERR_FHEXPIRED:
13931 	case NFS4ERR_GRACE:
13932 	case NFS4ERR_INVAL:
13933 	case NFS4ERR_ISDIR:
13934 	case NFS4ERR_LEASE_MOVED:
13935 	case NFS4ERR_LOCK_NOTSUPP:
13936 	case NFS4ERR_LOCK_RANGE:
13937 	case NFS4ERR_MOVED:
13938 	case NFS4ERR_NOFILEHANDLE:
13939 	case NFS4ERR_NO_GRACE:
13940 	case NFS4ERR_OLD_STATEID:
13941 	case NFS4ERR_OPENMODE:
13942 	case NFS4ERR_RECLAIM_BAD:
13943 	case NFS4ERR_RECLAIM_CONFLICT:
13944 	case NFS4ERR_RESOURCE:
13945 	case NFS4ERR_SERVERFAULT:
13946 	case NFS4ERR_STALE:
13947 	case NFS4ERR_STALE_CLIENTID:
13948 	case NFS4ERR_STALE_STATEID:
13949 		return;
13950 	default:
13951 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13952 		    "nfs4frlock_results_default: got unrecognizable "
13953 		    "res.status %d", resp->status));
13954 		*errorp = NFS4ERR_INVAL;
13955 	}
13956 }
13957 
13958 /*
13959  * The lock request was successful, so update the client's state.
13960  */
13961 static void
13962 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
13963     LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
13964     vnode_t *vp, flock64_t *flk, cred_t *cr,
13965     nfs4_lost_rqst_t *resend_rqstp)
13966 {
13967 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13968 
13969 	if (lock_args) {
13970 		LOCK4res *lock_res;
13971 
13972 		lock_res = &resop->nfs_resop4_u.oplock;
13973 		/* update the stateid with server's response */
13974 
13975 		if (lock_args->locker.new_lock_owner == TRUE) {
13976 			mutex_enter(&lop->lo_lock);
13977 			lop->lo_just_created = NFS4_PERM_CREATED;
13978 			mutex_exit(&lop->lo_lock);
13979 		}
13980 
13981 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
13982 
13983 		/*
13984 		 * If the lock was the result of a resending a lost
13985 		 * request, we've synched up the stateid and seqid
13986 		 * with the server, but now the server might be out of sync
13987 		 * with what the application thinks it has for locks.
13988 		 * Clean that up here.  It's unclear whether we should do
13989 		 * this even if the filesystem has been forcibly unmounted.
13990 		 * For most servers, it's probably wasted effort, but
13991 		 * RFC 7530 lets servers require that unlocks exactly match
13992 		 * the locks that are held.
13993 		 */
13994 		if (resend_rqstp != NULL &&
13995 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
13996 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
13997 		} else {
13998 			flk->l_whence = 0;
13999 		}
14000 	} else if (locku_args) {
14001 		LOCKU4res *locku_res;
14002 
14003 		locku_res = &resop->nfs_resop4_u.oplocku;
14004 
14005 		/* Update the stateid with the server's response */
14006 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
14007 	} else if (lockt_args) {
14008 		/* Switch the lock type to express success, see fcntl */
14009 		flk->l_type = F_UNLCK;
14010 		flk->l_whence = 0;
14011 	}
14012 }
14013 
14014 /*
14015  * Do final cleanup before exiting nfs4frlock.
14016  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
14017  * COMPOUND4 args/res for calls that haven't already.
14018  */
14019 static void
14020 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
14021     COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
14022     nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
14023     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
14024     short whence, u_offset_t offset, struct lm_sysid *ls,
14025     int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
14026     bool_t did_start_fop, bool_t skip_get_err,
14027     cred_t *cred_otw, cred_t *cred)
14028 {
14029 	mntinfo4_t	*mi = VTOMI4(vp);
14030 	rnode4_t	*rp = VTOR4(vp);
14031 	int		error = *errorp;
14032 	nfs_argop4	*argop;
14033 	int	do_flush_pages = 0;
14034 
14035 	ASSERT(nfs_zone() == mi->mi_zone);
14036 	/*
14037 	 * The client recovery code wants the raw status information,
14038 	 * so don't map the NFS status code to an errno value for
14039 	 * non-normal call types.
14040 	 */
14041 	if (ctype == NFS4_LCK_CTYPE_NORM) {
14042 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
14043 			*errorp = geterrno4(resp->status);
14044 		if (did_start_fop == TRUE)
14045 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
14046 			    needrecov);
14047 
14048 		/*
14049 		 * We've established a new lock on the server, so invalidate
14050 		 * the pages associated with the vnode to get the most up to
14051 		 * date pages from the server after acquiring the lock. We
14052 		 * want to be sure that the read operation gets the newest data.
14053 		 * N.B.
14054 		 * We used to do this in nfs4frlock_results_ok but that doesn't
14055 		 * work since VOP_PUTPAGE can call nfs4_commit which calls
14056 		 * nfs4_start_fop. We flush the pages below after calling
14057 		 * nfs4_end_fop above
14058 		 * The flush of the page cache must be done after
14059 		 * nfs4_end_open_seqid_sync() to avoid a 4-way hang.
14060 		 */
14061 		if (!error && resp && resp->status == NFS4_OK)
14062 			do_flush_pages = 1;
14063 	}
14064 	if (argsp) {
14065 		ASSERT(argsp->array_len == 2);
14066 		argop = argsp->array;
14067 		if (argop[1].argop == OP_LOCK)
14068 			nfs4args_lock_free(&argop[1]);
14069 		else if (argop[1].argop == OP_LOCKT)
14070 			nfs4args_lockt_free(&argop[1]);
14071 		kmem_free(argop, 2 * sizeof (nfs_argop4));
14072 		if (resp)
14073 			xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
14074 	}
14075 
14076 	/* free the reference on the lock owner */
14077 	if (lop != NULL) {
14078 		nfs4_end_lock_seqid_sync(lop);
14079 		lock_owner_rele(lop);
14080 	}
14081 
14082 	/* need to free up the reference on osp for lock args */
14083 	if (osp != NULL)
14084 		open_stream_rele(osp, rp);
14085 
14086 	/* need to free up the reference on oop for lock args */
14087 	if (oop != NULL) {
14088 		nfs4_end_open_seqid_sync(oop);
14089 		open_owner_rele(oop);
14090 	}
14091 
14092 	if (do_flush_pages)
14093 		nfs4_flush_pages(vp, cred);
14094 
14095 	(void) convoff(vp, flk, whence, offset);
14096 
14097 	lm_rel_sysid(ls);
14098 
14099 	/*
14100 	 * Record debug information in the event we get EINVAL.
14101 	 */
14102 	mutex_enter(&mi->mi_lock);
14103 	if (*errorp == EINVAL && (lock_args || locku_args) &&
14104 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
14105 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
14106 			zcmn_err(getzoneid(), CE_NOTE,
14107 			    "%s operation failed with "
14108 			    "EINVAL probably since the server, %s,"
14109 			    " doesn't support POSIX style locking",
14110 			    lock_args ? "LOCK" : "LOCKU",
14111 			    mi->mi_curr_serv->sv_hostname);
14112 			mi->mi_flags |= MI4_LOCK_DEBUG;
14113 		}
14114 	}
14115 	mutex_exit(&mi->mi_lock);
14116 
14117 	if (cred_otw)
14118 		crfree(cred_otw);
14119 }
14120 
14121 /*
14122  * This calls the server and the local locking code.
14123  *
14124  * Client locks are registerred locally by oring the sysid with
14125  * LM_SYSID_CLIENT. The server registers locks locally using just the sysid.
14126  * We need to distinguish between the two to avoid collision in case one
14127  * machine is used as both client and server.
14128  *
14129  * Blocking lock requests will continually retry to acquire the lock
14130  * forever.
14131  *
14132  * The ctype is defined as follows:
14133  * NFS4_LCK_CTYPE_NORM: normal lock request.
14134  *
14135  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
14136  * recovery, get the pid from flk instead of curproc, and don't reregister
14137  * the lock locally.
14138  *
14139  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
14140  * that we will use the information passed in via resend_rqstp to setup the
14141  * lock/locku request.  This resend is the exact same request as the 'lost
14142  * lock', and is initiated by the recovery framework. A successful resend
14143  * request can initiate one or more reinstate requests.
14144  *
14145  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14146  * does not trigger additional reinstate requests.  This lock call type is
14147  * set for setting the v4 server's locking state back to match what the
14148  * client's local locking state is in the event of a received 'lost lock'.
14149  *
14150  * Errors are returned via the nfs4_error_t parameter.
14151  */
14152 void
14153 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14154     int flag, u_offset_t offset, cred_t *cr, nfs4_error_t *ep,
14155     nfs4_lost_rqst_t *resend_rqstp, int *did_reclaimp)
14156 {
14157 	COMPOUND4args_clnt	args, *argsp = NULL;
14158 	COMPOUND4res_clnt	res, *resp = NULL;
14159 	nfs_argop4	*argop;
14160 	nfs_resop4	*resop;
14161 	rnode4_t	*rp;
14162 	int		doqueue = 1;
14163 	clock_t		tick_delay;  /* delay in clock ticks */
14164 	struct lm_sysid	*ls;
14165 	LOCK4args	*lock_args = NULL;
14166 	LOCKU4args	*locku_args = NULL;
14167 	LOCKT4args	*lockt_args = NULL;
14168 	nfs4_open_owner_t *oop = NULL;
14169 	nfs4_open_stream_t *osp = NULL;
14170 	nfs4_lock_owner_t *lop = NULL;
14171 	bool_t		needrecov = FALSE;
14172 	nfs4_recov_state_t recov_state;
14173 	short		whence;
14174 	nfs4_op_hint_t	op_hint;
14175 	nfs4_lost_rqst_t lost_rqst;
14176 	bool_t		retry = FALSE;
14177 	bool_t		did_start_fop = FALSE;
14178 	bool_t		skip_get_err = FALSE;
14179 	cred_t		*cred_otw = NULL;
14180 	bool_t		recovonly;	/* just queue request */
14181 	int		frc_no_reclaim = 0;
14182 #ifdef DEBUG
14183 	char *name;
14184 #endif
14185 
14186 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14187 
14188 #ifdef DEBUG
14189 	name = fn_name(VTOSV(vp)->sv_name);
14190 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14191 	    "%s: cmd %d, type %d, offset %llu, start %"PRIx64", "
14192 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14193 	    "resend request %s", name, cmd, flk->l_type, offset, flk->l_start,
14194 	    flk->l_len, ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid :
14195 	    flk->l_pid, flk->l_sysid, nfs4frlock_get_call_type(ctype),
14196 	    resend_rqstp ? "TRUE" : "FALSE"));
14197 	kmem_free(name, MAXNAMELEN);
14198 #endif
14199 
14200 	nfs4_error_zinit(ep);
14201 	ep->error = nfs4frlock_validate_args(cmd, flk, flag, vp, offset);
14202 	if (ep->error)
14203 		return;
14204 	ep->error = nfs4frlock_get_sysid(&ls, vp, flk);
14205 	if (ep->error)
14206 		return;
14207 	nfs4frlock_pre_setup(&tick_delay, &recov_state, flk, &whence,
14208 	    vp, cr, &cred_otw);
14209 
14210 recov_retry:
14211 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14212 	    &retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14213 	rp = VTOR4(vp);
14214 
14215 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14216 	    &did_start_fop, &recovonly);
14217 
14218 	if (ep->error)
14219 		goto out;
14220 
14221 	if (recovonly) {
14222 		/*
14223 		 * Leave the request for the recovery system to deal with.
14224 		 */
14225 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14226 		ASSERT(cmd != F_GETLK);
14227 		ASSERT(flk->l_type == F_UNLCK);
14228 
14229 		nfs4_error_init(ep, EINTR);
14230 		needrecov = TRUE;
14231 		lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14232 		if (lop != NULL) {
14233 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14234 			    NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14235 			(void) nfs4_start_recovery(ep,
14236 			    VTOMI4(vp), vp, NULL, NULL,
14237 			    (lost_rqst.lr_op == OP_LOCK ||
14238 			    lost_rqst.lr_op == OP_LOCKU) ?
14239 			    &lost_rqst : NULL, OP_LOCKU, NULL, NULL, NULL);
14240 			lock_owner_rele(lop);
14241 			lop = NULL;
14242 		}
14243 		flk->l_pid = curproc->p_pid;
14244 		nfs4_register_lock_locally(vp, flk, flag, offset);
14245 		goto out;
14246 	}
14247 
14248 	/* putfh directory fh */
14249 	argop[0].argop = OP_CPUTFH;
14250 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14251 
14252 	/*
14253 	 * Set up the over-the-wire arguments and get references to the
14254 	 * open owner, etc.
14255 	 */
14256 
14257 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14258 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14259 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14260 		    &argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14261 	} else {
14262 		bool_t go_otw = TRUE;
14263 
14264 		ASSERT(resend_rqstp == NULL);
14265 
14266 		switch (cmd) {
14267 		case F_GETLK:
14268 			nfs4frlock_setup_lockt_args(ctype, &argop[1],
14269 			    &lockt_args, argsp, flk, rp);
14270 			break;
14271 		case F_SETLKW:
14272 		case F_SETLK:
14273 			if (flk->l_type == F_UNLCK)
14274 				nfs4frlock_setup_locku_args(ctype,
14275 				    &argop[1], &locku_args, flk,
14276 				    &lop, ep, argsp,
14277 				    vp, flag, offset, cr,
14278 				    &skip_get_err, &go_otw);
14279 			else
14280 				nfs4frlock_setup_lock_args(ctype,
14281 				    &lock_args, &oop, &osp, &lop, &argop[1],
14282 				    argsp, flk, cmd, vp, cr, ep);
14283 
14284 			if (ep->error)
14285 				goto out;
14286 
14287 			switch (ep->stat) {
14288 			case NFS4_OK:
14289 				break;
14290 			case NFS4ERR_DELAY:
14291 				/* recov thread never gets this error */
14292 				ASSERT(resend_rqstp == NULL);
14293 				ASSERT(did_start_fop);
14294 
14295 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14296 				    &recov_state, TRUE);
14297 				did_start_fop = FALSE;
14298 				if (argop[1].argop == OP_LOCK)
14299 					nfs4args_lock_free(&argop[1]);
14300 				else if (argop[1].argop == OP_LOCKT)
14301 					nfs4args_lockt_free(&argop[1]);
14302 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14303 				argsp = NULL;
14304 				goto recov_retry;
14305 			default:
14306 				ep->error = EIO;
14307 				goto out;
14308 			}
14309 			break;
14310 		default:
14311 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14312 			    "nfs4_frlock: invalid cmd %d", cmd));
14313 			ep->error = EINVAL;
14314 			goto out;
14315 		}
14316 
14317 		if (!go_otw)
14318 			goto out;
14319 	}
14320 
14321 	/* XXX should we use the local reclock as a cache ? */
14322 	/*
14323 	 * Unregister the lock with the local locking code before
14324 	 * contacting the server.  This avoids a potential race where
14325 	 * another process gets notified that it has been granted a lock
14326 	 * before we can unregister ourselves locally.
14327 	 */
14328 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK) {
14329 		if (ctype == NFS4_LCK_CTYPE_NORM)
14330 			flk->l_pid = ttoproc(curthread)->p_pid;
14331 		nfs4_register_lock_locally(vp, flk, flag, offset);
14332 	}
14333 
14334 	/*
14335 	 * Send the server the lock request.  Continually loop with a delay
14336 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14337 	 */
14338 	resp = &res;
14339 
14340 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14341 	    (CE_NOTE,
14342 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14343 	    rnode4info(rp)));
14344 
14345 	if (lock_args && frc_no_reclaim) {
14346 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14347 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14348 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14349 		lock_args->reclaim = FALSE;
14350 		if (did_reclaimp)
14351 			*did_reclaimp = 0;
14352 	}
14353 
14354 	/*
14355 	 * Do the OTW call.
14356 	 */
14357 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14358 
14359 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14360 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14361 
14362 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14363 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14364 	    "nfs4frlock: needrecov %d", needrecov));
14365 
14366 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14367 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14368 		    args.ctag);
14369 
14370 	/*
14371 	 * Check if one of these mutually exclusive error cases has
14372 	 * happened:
14373 	 *   need to swap credentials due to access error
14374 	 *   recovery is needed
14375 	 *   different error (only known case is missing Kerberos ticket)
14376 	 */
14377 
14378 	if ((ep->error == EACCES ||
14379 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14380 	    cred_otw != cr) {
14381 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14382 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14383 		    cr, &cred_otw);
14384 		goto recov_retry;
14385 	}
14386 
14387 	if (needrecov) {
14388 		/*
14389 		 * LOCKT requests don't need to recover from lost
14390 		 * requests since they don't create/modify state.
14391 		 */
14392 		if ((ep->error == EINTR ||
14393 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14394 		    lockt_args)
14395 			goto out;
14396 		/*
14397 		 * Do not attempt recovery for requests initiated by
14398 		 * the recovery framework.  Let the framework redrive them.
14399 		 */
14400 		if (ctype != NFS4_LCK_CTYPE_NORM)
14401 			goto out;
14402 		else {
14403 			ASSERT(resend_rqstp == NULL);
14404 		}
14405 
14406 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14407 		    flk_to_locktype(cmd, flk->l_type),
14408 		    oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14409 
14410 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14411 		    &resp, lock_args, locku_args, &oop, &osp, &lop,
14412 		    rp, vp, &recov_state, op_hint, &did_start_fop,
14413 		    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14414 
14415 		if (retry) {
14416 			ASSERT(oop == NULL);
14417 			ASSERT(osp == NULL);
14418 			ASSERT(lop == NULL);
14419 			goto recov_retry;
14420 		}
14421 		goto out;
14422 	}
14423 
14424 	/*
14425 	 * Bail out if have reached this point with ep->error set. Can
14426 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14427 	 * This happens if Kerberos ticket has expired or has been
14428 	 * destroyed.
14429 	 */
14430 	if (ep->error != 0)
14431 		goto out;
14432 
14433 	/*
14434 	 * Process the reply.
14435 	 */
14436 	switch (resp->status) {
14437 	case NFS4_OK:
14438 		resop = &resp->array[1];
14439 		nfs4frlock_results_ok(ctype, cmd, flk, vp, flag, offset,
14440 		    resend_rqstp);
14441 		/*
14442 		 * Have a successful lock operation, now update state.
14443 		 */
14444 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14445 		    resop, lop, vp, flk, cr, resend_rqstp);
14446 		break;
14447 
14448 	case NFS4ERR_DENIED:
14449 		resop = &resp->array[1];
14450 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14451 		    &oop, &osp, &lop, cmd, vp, flk, op_hint,
14452 		    &recov_state, needrecov, &argsp, &resp,
14453 		    &tick_delay, &whence, &ep->error, resop, cr,
14454 		    &did_start_fop, &skip_get_err);
14455 
14456 		if (retry) {
14457 			ASSERT(oop == NULL);
14458 			ASSERT(osp == NULL);
14459 			ASSERT(lop == NULL);
14460 			goto recov_retry;
14461 		}
14462 		break;
14463 	/*
14464 	 * If the server won't let us reclaim, fall-back to trying to lock
14465 	 * the file from scratch. Code elsewhere will check the changeinfo
14466 	 * to ensure the file hasn't been changed.
14467 	 */
14468 	case NFS4ERR_NO_GRACE:
14469 		if (lock_args && lock_args->reclaim == TRUE) {
14470 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14471 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14472 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14473 			frc_no_reclaim = 1;
14474 			/* clean up before retrying */
14475 			needrecov = 0;
14476 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14477 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14478 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14479 			goto recov_retry;
14480 		}
14481 		/* FALLTHROUGH */
14482 
14483 	default:
14484 		nfs4frlock_results_default(resp, &ep->error);
14485 		break;
14486 	}
14487 out:
14488 	/*
14489 	 * Process and cleanup from error.  Make interrupted unlock
14490 	 * requests look successful, since they will be handled by the
14491 	 * client recovery code.
14492 	 */
14493 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14494 	    needrecov, oop, osp, lop, flk, whence, offset, ls, &ep->error,
14495 	    lock_args, locku_args, did_start_fop,
14496 	    skip_get_err, cred_otw, cr);
14497 
14498 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14499 	    (cmd == F_SETLK || cmd == F_SETLKW))
14500 		ep->error = 0;
14501 }
14502 
14503 /*
14504  * nfs4_safelock:
14505  *
14506  * Return non-zero if the given lock request can be handled without
14507  * violating the constraints on concurrent mapping and locking.
14508  */
14509 
14510 static int
14511 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14512 {
14513 	rnode4_t *rp = VTOR4(vp);
14514 	struct vattr va;
14515 	int error;
14516 
14517 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14518 	ASSERT(rp->r_mapcnt >= 0);
14519 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14520 	    "(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14521 	    "write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14522 	    bfp->l_start, bfp->l_len, rp->r_mapcnt));
14523 
14524 	if (rp->r_mapcnt == 0)
14525 		return (1);		/* always safe if not mapped */
14526 
14527 	/*
14528 	 * If the file is already mapped and there are locks, then they
14529 	 * should be all safe locks.  So adding or removing a lock is safe
14530 	 * as long as the new request is safe (i.e., whole-file, meaning
14531 	 * length and starting offset are both zero).
14532 	 */
14533 
14534 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14535 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14536 		    "cannot lock a memory mapped file unless locking the "
14537 		    "entire file: start %"PRIx64", len %"PRIx64,
14538 		    bfp->l_start, bfp->l_len));
14539 		return (0);
14540 	}
14541 
14542 	/* mandatory locking and mapping don't mix */
14543 	va.va_mask = AT_MODE;
14544 	error = VOP_GETATTR(vp, &va, 0, cr, NULL);
14545 	if (error != 0) {
14546 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14547 		    "getattr error %d", error));
14548 		return (0);		/* treat errors conservatively */
14549 	}
14550 	if (MANDLOCK(vp, va.va_mode)) {
14551 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14552 		    "cannot mandatory lock and mmap a file"));
14553 		return (0);
14554 	}
14555 
14556 	return (1);
14557 }
14558 
14559 
14560 /*
14561  * Register the lock locally within Solaris.
14562  * As the client, we "or" the sysid with LM_SYSID_CLIENT when
14563  * recording locks locally.
14564  *
14565  * This should handle conflicts/cooperation with NFS v2/v3 since all locks
14566  * are registered locally.
14567  */
14568 void
14569 nfs4_register_lock_locally(vnode_t *vp, struct flock64 *flk, int flag,
14570     u_offset_t offset)
14571 {
14572 	int oldsysid;
14573 	int error;
14574 #ifdef DEBUG
14575 	char *name;
14576 #endif
14577 
14578 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14579 
14580 #ifdef DEBUG
14581 	name = fn_name(VTOSV(vp)->sv_name);
14582 	NFS4_DEBUG(nfs4_client_lock_debug,
14583 	    (CE_NOTE, "nfs4_register_lock_locally: %s: type %d, "
14584 	    "start %"PRIx64", length %"PRIx64", pid %ld, sysid %d",
14585 	    name, flk->l_type, flk->l_start, flk->l_len, (long)flk->l_pid,
14586 	    flk->l_sysid));
14587 	kmem_free(name, MAXNAMELEN);
14588 #endif
14589 
14590 	/* register the lock with local locking */
14591 	oldsysid = flk->l_sysid;
14592 	flk->l_sysid |= LM_SYSID_CLIENT;
14593 	error = reclock(vp, flk, SETFLCK, flag, offset, NULL);
14594 #ifdef DEBUG
14595 	if (error != 0) {
14596 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14597 		    "nfs4_register_lock_locally: could not register with"
14598 		    " local locking"));
14599 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14600 		    "error %d, vp 0x%p, pid %d, sysid 0x%x",
14601 		    error, (void *)vp, flk->l_pid, flk->l_sysid));
14602 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14603 		    "type %d off 0x%" PRIx64 " len 0x%" PRIx64,
14604 		    flk->l_type, flk->l_start, flk->l_len));
14605 		(void) reclock(vp, flk, 0, flag, offset, NULL);
14606 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14607 		    "blocked by pid %d sysid 0x%x type %d "
14608 		    "off 0x%" PRIx64 " len 0x%" PRIx64,
14609 		    flk->l_pid, flk->l_sysid, flk->l_type, flk->l_start,
14610 		    flk->l_len));
14611 	}
14612 #endif
14613 	flk->l_sysid = oldsysid;
14614 }
14615 
14616 /*
14617  * nfs4_lockrelease:
14618  *
14619  * Release any locks on the given vnode that are held by the current
14620  * process.  Also removes the lock owner (if one exists) from the rnode's
14621  * list.
14622  */
14623 static int
14624 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14625 {
14626 	flock64_t ld;
14627 	int ret, error;
14628 	rnode4_t *rp;
14629 	nfs4_lock_owner_t *lop;
14630 	nfs4_recov_state_t recov_state;
14631 	mntinfo4_t *mi;
14632 	bool_t possible_orphan = FALSE;
14633 	bool_t recovonly;
14634 
14635 	ASSERT((uintptr_t)vp > KERNELBASE);
14636 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14637 
14638 	rp = VTOR4(vp);
14639 	mi = VTOMI4(vp);
14640 
14641 	/*
14642 	 * If we have not locked anything then we can
14643 	 * just return since we have no work to do.
14644 	 */
14645 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14646 		return (0);
14647 	}
14648 
14649 	/*
14650 	 * We need to comprehend that another thread may
14651 	 * kick off recovery and the lock_owner we have stashed
14652 	 * in lop might be invalid so we should NOT cache it
14653 	 * locally!
14654 	 */
14655 	recov_state.rs_flags = 0;
14656 	recov_state.rs_num_retry_despite_err = 0;
14657 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14658 	    &recovonly);
14659 	if (error) {
14660 		mutex_enter(&rp->r_statelock);
14661 		rp->r_flags |= R4LODANGLERS;
14662 		mutex_exit(&rp->r_statelock);
14663 		return (error);
14664 	}
14665 
14666 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14667 
14668 	/*
14669 	 * Check if the lock owner might have a lock (request was sent but
14670 	 * no response was received).  Also check if there are any remote
14671 	 * locks on the file.  (In theory we shouldn't have to make this
14672 	 * second check if there's no lock owner, but for now we'll be
14673 	 * conservative and do it anyway.)  If either condition is true,
14674 	 * send an unlock for the entire file to the server.
14675 	 *
14676 	 * Note that no explicit synchronization is needed here.  At worst,
14677 	 * flk_has_remote_locks() will return a false positive, in which case
14678 	 * the unlock call wastes time but doesn't harm correctness.
14679 	 */
14680 
14681 	if (lop) {
14682 		mutex_enter(&lop->lo_lock);
14683 		possible_orphan = lop->lo_pending_rqsts;
14684 		mutex_exit(&lop->lo_lock);
14685 		lock_owner_rele(lop);
14686 	}
14687 
14688 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14689 
14690 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14691 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14692 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14693 	    (void *)lop));
14694 
14695 	if (possible_orphan || flk_has_remote_locks(vp)) {
14696 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14697 		ld.l_whence = 0;	/* unlock from start of file */
14698 		ld.l_start = 0;
14699 		ld.l_len = 0;		/* do entire file */
14700 
14701 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL,
14702 		    cr, NULL);
14703 
14704 		if (ret != 0) {
14705 			/*
14706 			 * If VOP_FRLOCK fails, make sure we unregister
14707 			 * local locks before we continue.
14708 			 */
14709 			ld.l_pid = ttoproc(curthread)->p_pid;
14710 			nfs4_register_lock_locally(vp, &ld, flag, offset);
14711 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14712 			    "nfs4_lockrelease: lock release error on vp"
14713 			    " %p: error %d.\n", (void *)vp, ret));
14714 		}
14715 	}
14716 
14717 	recov_state.rs_flags = 0;
14718 	recov_state.rs_num_retry_despite_err = 0;
14719 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14720 	    &recovonly);
14721 	if (error) {
14722 		mutex_enter(&rp->r_statelock);
14723 		rp->r_flags |= R4LODANGLERS;
14724 		mutex_exit(&rp->r_statelock);
14725 		return (error);
14726 	}
14727 
14728 	/*
14729 	 * So, here we're going to need to retrieve the lock-owner
14730 	 * again (in case recovery has done a switch-a-roo) and
14731 	 * remove it because we can.
14732 	 */
14733 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14734 
14735 	if (lop) {
14736 		nfs4_rnode_remove_lock_owner(rp, lop);
14737 		lock_owner_rele(lop);
14738 	}
14739 
14740 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14741 	return (0);
14742 }
14743 
14744 /*
14745  * Wait for 'tick_delay' clock ticks.
14746  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14747  * NOTE: lock_lease_time is in seconds.
14748  *
14749  * XXX For future improvements, should implement a waiting queue scheme.
14750  */
14751 static int
14752 nfs4_block_and_wait(clock_t *tick_delay, rnode4_t *rp)
14753 {
14754 	long milliseconds_delay;
14755 	time_t lock_lease_time;
14756 
14757 	/* wait tick_delay clock ticks or siginteruptus */
14758 	if (delay_sig(*tick_delay)) {
14759 		return (EINTR);
14760 	}
14761 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14762 	    "reissue the lock request: blocked for %ld clock ticks: %ld "
14763 	    "milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14764 
14765 	/* get the lease time */
14766 	lock_lease_time = r2lease_time(rp);
14767 
14768 	/* drv_hztousec converts ticks to microseconds */
14769 	milliseconds_delay = drv_hztousec(*tick_delay) / 1000;
14770 	if (milliseconds_delay < lock_lease_time * 1000) {
14771 		*tick_delay = 2 * *tick_delay;
14772 		if (drv_hztousec(*tick_delay) > lock_lease_time * 1000 * 1000)
14773 			*tick_delay = drv_usectohz(lock_lease_time*1000*1000);
14774 	}
14775 	return (0);
14776 }
14777 
14778 
14779 void
14780 nfs4_vnops_init(void)
14781 {
14782 }
14783 
14784 void
14785 nfs4_vnops_fini(void)
14786 {
14787 }
14788 
14789 /*
14790  * Return a reference to the directory (parent) vnode for a given vnode,
14791  * using the saved pathname information and the directory file handle.  The
14792  * caller is responsible for disposing of the reference.
14793  * Returns zero or an errno value.
14794  *
14795  * Caller should set need_start_op to FALSE if it is the recovery
14796  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14797  */
14798 int
14799 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14800 {
14801 	svnode_t *svnp;
14802 	vnode_t *dvp = NULL;
14803 	servinfo4_t *svp;
14804 	nfs4_fname_t *mfname;
14805 	int error;
14806 
14807 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14808 
14809 	if (vp->v_flag & VROOT) {
14810 		nfs4_sharedfh_t *sfh;
14811 		nfs_fh4 fh;
14812 		mntinfo4_t *mi;
14813 
14814 		ASSERT(vp->v_type == VREG);
14815 
14816 		mi = VTOMI4(vp);
14817 		svp = mi->mi_curr_serv;
14818 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14819 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14820 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14821 		sfh = sfh4_get(&fh, VTOMI4(vp));
14822 		nfs_rw_exit(&svp->sv_lock);
14823 		mfname = mi->mi_fname;
14824 		fn_hold(mfname);
14825 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14826 		sfh4_rele(&sfh);
14827 
14828 		if (dvp->v_type == VNON)
14829 			dvp->v_type = VDIR;
14830 		*dvpp = dvp;
14831 		return (0);
14832 	}
14833 
14834 	svnp = VTOSV(vp);
14835 
14836 	if (svnp == NULL) {
14837 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14838 		    "shadow node is NULL"));
14839 		return (EINVAL);
14840 	}
14841 
14842 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14843 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14844 		    "shadow node name or dfh val == NULL"));
14845 		return (EINVAL);
14846 	}
14847 
14848 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14849 	    (int)need_start_op);
14850 	if (error != 0) {
14851 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14852 		    "nfs4_make_dotdot returned %d", error));
14853 		return (error);
14854 	}
14855 	if (!dvp) {
14856 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14857 		    "nfs4_make_dotdot returned a NULL dvp"));
14858 		return (EIO);
14859 	}
14860 	if (dvp->v_type == VNON)
14861 		dvp->v_type = VDIR;
14862 	ASSERT(dvp->v_type == VDIR);
14863 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14864 		mutex_enter(&dvp->v_lock);
14865 		dvp->v_flag |= V_XATTRDIR;
14866 		mutex_exit(&dvp->v_lock);
14867 	}
14868 	*dvpp = dvp;
14869 	return (0);
14870 }
14871 
14872 /*
14873  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14874  * length that fnamep can accept, including the trailing null.
14875  * Returns 0 if okay, returns an errno value if there was a problem.
14876  */
14877 
14878 int
14879 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14880 {
14881 	char *fn;
14882 	int err = 0;
14883 	servinfo4_t *svp;
14884 	svnode_t *shvp;
14885 
14886 	/*
14887 	 * If the file being opened has VROOT set, then this is
14888 	 * a "file" mount.  sv_name will not be interesting, so
14889 	 * go back to the servinfo4 to get the original mount
14890 	 * path and strip off all but the final edge.  Otherwise
14891 	 * just return the name from the shadow vnode.
14892 	 */
14893 
14894 	if (vp->v_flag & VROOT) {
14895 
14896 		svp = VTOMI4(vp)->mi_curr_serv;
14897 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14898 
14899 		fn = strrchr(svp->sv_path, '/');
14900 		if (fn == NULL)
14901 			err = EINVAL;
14902 		else
14903 			fn++;
14904 	} else {
14905 		shvp = VTOSV(vp);
14906 		fn = fn_name(shvp->sv_name);
14907 	}
14908 
14909 	if (err == 0)
14910 		if (strlen(fn) < maxlen)
14911 			(void) strcpy(fnamep, fn);
14912 		else
14913 			err = ENAMETOOLONG;
14914 
14915 	if (vp->v_flag & VROOT)
14916 		nfs_rw_exit(&svp->sv_lock);
14917 	else
14918 		kmem_free(fn, MAXNAMELEN);
14919 
14920 	return (err);
14921 }
14922 
14923 /*
14924  * Bookkeeping for a close that doesn't need to go over the wire.
14925  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14926  * it is left at 1.
14927  */
14928 void
14929 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14930 {
14931 	rnode4_t		*rp;
14932 	mntinfo4_t		*mi;
14933 
14934 	mi = VTOMI4(vp);
14935 	rp = VTOR4(vp);
14936 
14937 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14938 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14939 	ASSERT(nfs_zone() == mi->mi_zone);
14940 	ASSERT(mutex_owned(&osp->os_sync_lock));
14941 	ASSERT(*have_lockp);
14942 
14943 	if (!osp->os_valid ||
14944 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14945 		return;
14946 	}
14947 
14948 	/*
14949 	 * This removes the reference obtained at OPEN; ie,
14950 	 * when the open stream structure was created.
14951 	 *
14952 	 * We don't have to worry about calling 'open_stream_rele'
14953 	 * since we our currently holding a reference to this
14954 	 * open stream which means the count can not go to 0 with
14955 	 * this decrement.
14956 	 */
14957 	ASSERT(osp->os_ref_count >= 2);
14958 	osp->os_ref_count--;
14959 	osp->os_valid = 0;
14960 	mutex_exit(&osp->os_sync_lock);
14961 	*have_lockp = 0;
14962 
14963 	nfs4_dec_state_ref_count(mi);
14964 }
14965 
14966 /*
14967  * Close all remaining open streams on the rnode.  These open streams
14968  * could be here because:
14969  * - The close attempted at either close or delmap failed
14970  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
14971  * - Someone did mknod on a regular file but never opened it
14972  */
14973 int
14974 nfs4close_all(vnode_t *vp, cred_t *cr)
14975 {
14976 	nfs4_open_stream_t *osp;
14977 	int error;
14978 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
14979 	rnode4_t *rp;
14980 
14981 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14982 
14983 	error = 0;
14984 	rp = VTOR4(vp);
14985 
14986 	/*
14987 	 * At this point, all we know is that the last time
14988 	 * someone called vn_rele, the count was 1.  Since then,
14989 	 * the vnode could have been re-activated.  We want to
14990 	 * loop through the open streams and close each one, but
14991 	 * we have to be careful since once we release the rnode
14992 	 * hash bucket lock, someone else is free to come in and
14993 	 * re-activate the rnode and add new open streams.  The
14994 	 * strategy is take the rnode hash bucket lock, verify that
14995 	 * the count is still 1, grab the open stream off the
14996 	 * head of the list and mark it invalid, then release the
14997 	 * rnode hash bucket lock and proceed with that open stream.
14998 	 * This is ok because nfs4close_one() will acquire the proper
14999 	 * open/create to close/destroy synchronization for open
15000 	 * streams, and will ensure that if someone has reopened
15001 	 * the open stream after we've dropped the hash bucket lock
15002 	 * then we'll just simply return without destroying the
15003 	 * open stream.
15004 	 * Repeat until the list is empty.
15005 	 */
15006 
15007 	for (;;) {
15008 
15009 		/* make sure vnode hasn't been reactivated */
15010 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
15011 		mutex_enter(&vp->v_lock);
15012 		if (vp->v_count > 1) {
15013 			mutex_exit(&vp->v_lock);
15014 			rw_exit(&rp->r_hashq->r_lock);
15015 			break;
15016 		}
15017 		/*
15018 		 * Grabbing r_os_lock before releasing v_lock prevents
15019 		 * a window where the rnode/open stream could get
15020 		 * reactivated (and os_force_close set to 0) before we
15021 		 * had a chance to set os_force_close to 1.
15022 		 */
15023 		mutex_enter(&rp->r_os_lock);
15024 		mutex_exit(&vp->v_lock);
15025 
15026 		osp = list_head(&rp->r_open_streams);
15027 		if (!osp) {
15028 			/* nothing left to CLOSE OTW, so return */
15029 			mutex_exit(&rp->r_os_lock);
15030 			rw_exit(&rp->r_hashq->r_lock);
15031 			break;
15032 		}
15033 
15034 		mutex_enter(&rp->r_statev4_lock);
15035 		/* the file can't still be mem mapped */
15036 		ASSERT(rp->r_mapcnt == 0);
15037 		if (rp->created_v4)
15038 			rp->created_v4 = 0;
15039 		mutex_exit(&rp->r_statev4_lock);
15040 
15041 		/*
15042 		 * Grab a ref on this open stream; nfs4close_one
15043 		 * will mark it as invalid
15044 		 */
15045 		mutex_enter(&osp->os_sync_lock);
15046 		osp->os_ref_count++;
15047 		osp->os_force_close = 1;
15048 		mutex_exit(&osp->os_sync_lock);
15049 		mutex_exit(&rp->r_os_lock);
15050 		rw_exit(&rp->r_hashq->r_lock);
15051 
15052 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
15053 
15054 		/* Update error if it isn't already non-zero */
15055 		if (error == 0) {
15056 			if (e.error)
15057 				error = e.error;
15058 			else if (e.stat)
15059 				error = geterrno4(e.stat);
15060 		}
15061 
15062 #ifdef	DEBUG
15063 		nfs4close_all_cnt++;
15064 #endif
15065 		/* Release the ref on osp acquired above. */
15066 		open_stream_rele(osp, rp);
15067 
15068 		/* Proceed to the next open stream, if any */
15069 	}
15070 	return (error);
15071 }
15072 
15073 /*
15074  * nfs4close_one - close one open stream for a file if needed.
15075  *
15076  * "close_type" indicates which close path this is:
15077  * CLOSE_NORM: close initiated via VOP_CLOSE.
15078  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
15079  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
15080  *	the close and release of client state for this open stream
15081  *	(unless someone else has the open stream open).
15082  * CLOSE_RESEND: indicates the request is a replay of an earlier request
15083  *	(e.g., due to abort because of a signal).
15084  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
15085  *
15086  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
15087  * recovery.  Instead, the caller is expected to deal with retries.
15088  *
15089  * The caller can either pass in the osp ('provided_osp') or not.
15090  *
15091  * 'access_bits' represents the access we are closing/downgrading.
15092  *
15093  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
15094  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
15095  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
15096  *
15097  * Errors are returned via the nfs4_error_t.
15098  */
15099 void
15100 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
15101     int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
15102     nfs4_close_type_t close_type, size_t len, uint_t maxprot,
15103     uint_t mmap_flags)
15104 {
15105 	nfs4_open_owner_t *oop;
15106 	nfs4_open_stream_t *osp = NULL;
15107 	int retry = 0;
15108 	int num_retries = NFS4_NUM_RECOV_RETRIES;
15109 	rnode4_t *rp;
15110 	mntinfo4_t *mi;
15111 	nfs4_recov_state_t recov_state;
15112 	cred_t *cred_otw = NULL;
15113 	bool_t recovonly = FALSE;
15114 	int isrecov;
15115 	int force_close;
15116 	int close_failed = 0;
15117 	int did_dec_count = 0;
15118 	int did_start_op = 0;
15119 	int did_force_recovlock = 0;
15120 	int did_start_seqid_sync = 0;
15121 	int have_sync_lock = 0;
15122 
15123 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15124 
15125 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
15126 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
15127 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
15128 	    len, maxprot, mmap_flags, access_bits));
15129 
15130 	nfs4_error_zinit(ep);
15131 	rp = VTOR4(vp);
15132 	mi = VTOMI4(vp);
15133 	isrecov = (close_type == CLOSE_RESEND ||
15134 	    close_type == CLOSE_AFTER_RESEND);
15135 
15136 	/*
15137 	 * First get the open owner.
15138 	 */
15139 	if (!provided_osp) {
15140 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
15141 	} else {
15142 		oop = provided_osp->os_open_owner;
15143 		ASSERT(oop != NULL);
15144 		open_owner_hold(oop);
15145 	}
15146 
15147 	if (!oop) {
15148 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15149 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15150 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15151 		    (void *)provided_osp, close_type));
15152 		ep->error = EIO;
15153 		goto out;
15154 	}
15155 
15156 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15157 recov_retry:
15158 	osp = NULL;
15159 	close_failed = 0;
15160 	force_close = (close_type == CLOSE_FORCE);
15161 	retry = 0;
15162 	did_start_op = 0;
15163 	did_force_recovlock = 0;
15164 	did_start_seqid_sync = 0;
15165 	have_sync_lock = 0;
15166 	recovonly = FALSE;
15167 	recov_state.rs_flags = 0;
15168 	recov_state.rs_num_retry_despite_err = 0;
15169 
15170 	/*
15171 	 * Second synchronize with recovery.
15172 	 */
15173 	if (!isrecov) {
15174 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15175 		    &recov_state, &recovonly);
15176 		if (!ep->error) {
15177 			did_start_op = 1;
15178 		} else {
15179 			close_failed = 1;
15180 			/*
15181 			 * If we couldn't get start_fop, but have to
15182 			 * cleanup state, then at least acquire the
15183 			 * mi_recovlock so we can synchronize with
15184 			 * recovery.
15185 			 */
15186 			if (close_type == CLOSE_FORCE) {
15187 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15188 				    RW_READER, FALSE);
15189 				did_force_recovlock = 1;
15190 			} else
15191 				goto out;
15192 		}
15193 	}
15194 
15195 	/*
15196 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15197 	 * set 'recovonly' to TRUE since most likely this is due to
15198 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15199 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15200 	 * to retry, causing us to loop until recovery finishes.  Plus we
15201 	 * don't need protection over the open seqid since we're not going
15202 	 * OTW, hence don't need to use the seqid.
15203 	 */
15204 	if (recovonly == FALSE) {
15205 		/* need to grab the open owner sync before 'os_sync_lock' */
15206 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15207 		if (ep->error == EAGAIN) {
15208 			ASSERT(!isrecov);
15209 			if (did_start_op)
15210 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15211 				    &recov_state, TRUE);
15212 			if (did_force_recovlock)
15213 				nfs_rw_exit(&mi->mi_recovlock);
15214 			goto recov_retry;
15215 		}
15216 		did_start_seqid_sync = 1;
15217 	}
15218 
15219 	/*
15220 	 * Third get an open stream and acquire 'os_sync_lock' to
15221 	 * sychronize the opening/creating of an open stream with the
15222 	 * closing/destroying of an open stream.
15223 	 */
15224 	if (!provided_osp) {
15225 		/* returns with 'os_sync_lock' held */
15226 		osp = find_open_stream(oop, rp);
15227 		if (!osp) {
15228 			ep->error = EIO;
15229 			goto out;
15230 		}
15231 	} else {
15232 		osp = provided_osp;
15233 		open_stream_hold(osp);
15234 		mutex_enter(&osp->os_sync_lock);
15235 	}
15236 	have_sync_lock = 1;
15237 
15238 	ASSERT(oop == osp->os_open_owner);
15239 
15240 	/*
15241 	 * Fourth, do any special pre-OTW CLOSE processing
15242 	 * based on the specific close type.
15243 	 */
15244 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15245 	    !did_dec_count) {
15246 		ASSERT(osp->os_open_ref_count > 0);
15247 		osp->os_open_ref_count--;
15248 		did_dec_count = 1;
15249 		if (osp->os_open_ref_count == 0)
15250 			osp->os_final_close = 1;
15251 	}
15252 
15253 	if (close_type == CLOSE_FORCE) {
15254 		/* see if somebody reopened the open stream. */
15255 		if (!osp->os_force_close) {
15256 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15257 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15258 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15259 			ep->error = 0;
15260 			ep->stat = NFS4_OK;
15261 			goto out;
15262 		}
15263 
15264 		if (!osp->os_final_close && !did_dec_count) {
15265 			osp->os_open_ref_count--;
15266 			did_dec_count = 1;
15267 		}
15268 
15269 		/*
15270 		 * We can't depend on os_open_ref_count being 0 due to the
15271 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15272 		 */
15273 #ifdef	NOTYET
15274 		ASSERT(osp->os_open_ref_count == 0);
15275 #endif
15276 		if (osp->os_open_ref_count != 0) {
15277 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15278 			    "nfs4close_one: should panic here on an "
15279 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15280 			    "since this is probably the exec problem."));
15281 
15282 			osp->os_open_ref_count = 0;
15283 		}
15284 
15285 		/*
15286 		 * There is the possibility that nfs4close_one()
15287 		 * for close_type == CLOSE_DELMAP couldn't find the
15288 		 * open stream, thus couldn't decrement its os_mapcnt;
15289 		 * therefore we can't use this ASSERT yet.
15290 		 */
15291 #ifdef	NOTYET
15292 		ASSERT(osp->os_mapcnt == 0);
15293 #endif
15294 		osp->os_mapcnt = 0;
15295 	}
15296 
15297 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15298 		ASSERT(osp->os_mapcnt >= btopr(len));
15299 
15300 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15301 			osp->os_mmap_write -= btopr(len);
15302 		if (maxprot & PROT_READ)
15303 			osp->os_mmap_read -= btopr(len);
15304 		if (maxprot & PROT_EXEC)
15305 			osp->os_mmap_read -= btopr(len);
15306 		/* mirror the PROT_NONE check in nfs4_addmap() */
15307 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15308 		    !(maxprot & PROT_EXEC))
15309 			osp->os_mmap_read -= btopr(len);
15310 		osp->os_mapcnt -= btopr(len);
15311 		did_dec_count = 1;
15312 	}
15313 
15314 	if (recovonly) {
15315 		nfs4_lost_rqst_t lost_rqst;
15316 
15317 		/* request should not already be in recovery queue */
15318 		ASSERT(lrp == NULL);
15319 		nfs4_error_init(ep, EINTR);
15320 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15321 		    osp, cred_otw, vp);
15322 		mutex_exit(&osp->os_sync_lock);
15323 		have_sync_lock = 0;
15324 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15325 		    lost_rqst.lr_op == OP_CLOSE ?
15326 		    &lost_rqst : NULL, OP_CLOSE, NULL, NULL, NULL);
15327 		close_failed = 1;
15328 		force_close = 0;
15329 		goto close_cleanup;
15330 	}
15331 
15332 	/*
15333 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15334 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15335 	 * space, which means we stopped operating on the open stream
15336 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15337 	 * stateid could be stale, potentially triggering a false
15338 	 * setclientid), and just clean up the client's internal state.
15339 	 */
15340 	if (osp->os_orig_oo_name != oop->oo_name) {
15341 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15342 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15343 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15344 		    "oo_name %" PRIx64")",
15345 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15346 		    oop->oo_name));
15347 		close_failed = 1;
15348 	}
15349 
15350 	/* If the file failed recovery, just quit. */
15351 	mutex_enter(&rp->r_statelock);
15352 	if (rp->r_flags & R4RECOVERR) {
15353 		close_failed = 1;
15354 	}
15355 	mutex_exit(&rp->r_statelock);
15356 
15357 	/*
15358 	 * If the force close path failed to obtain start_fop
15359 	 * then skip the OTW close and just remove the state.
15360 	 */
15361 	if (close_failed)
15362 		goto close_cleanup;
15363 
15364 	/*
15365 	 * Fifth, check to see if there are still mapped pages or other
15366 	 * opens using this open stream.  If there are then we can't
15367 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15368 	 */
15369 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15370 		nfs4_lost_rqst_t	new_lost_rqst;
15371 		bool_t			needrecov = FALSE;
15372 		cred_t			*odg_cred_otw = NULL;
15373 		seqid4			open_dg_seqid = 0;
15374 
15375 		if (osp->os_delegation) {
15376 			/*
15377 			 * If this open stream was never OPENed OTW then we
15378 			 * surely can't DOWNGRADE it (especially since the
15379 			 * osp->open_stateid is really a delegation stateid
15380 			 * when os_delegation is 1).
15381 			 */
15382 			if (access_bits & FREAD)
15383 				osp->os_share_acc_read--;
15384 			if (access_bits & FWRITE)
15385 				osp->os_share_acc_write--;
15386 			osp->os_share_deny_none--;
15387 			nfs4_error_zinit(ep);
15388 			goto out;
15389 		}
15390 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15391 		    lrp, ep, &odg_cred_otw, &open_dg_seqid);
15392 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15393 		if (needrecov && !isrecov) {
15394 			bool_t abort;
15395 			nfs4_bseqid_entry_t *bsep = NULL;
15396 
15397 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15398 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15399 				    vp, 0,
15400 				    lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15401 				    open_dg_seqid);
15402 
15403 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15404 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15405 			mutex_exit(&osp->os_sync_lock);
15406 			have_sync_lock = 0;
15407 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15408 			    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15409 			    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15410 			    bsep, NULL, NULL);
15411 			if (odg_cred_otw)
15412 				crfree(odg_cred_otw);
15413 			if (bsep)
15414 				kmem_free(bsep, sizeof (*bsep));
15415 
15416 			if (abort == TRUE)
15417 				goto out;
15418 
15419 			if (did_start_seqid_sync) {
15420 				nfs4_end_open_seqid_sync(oop);
15421 				did_start_seqid_sync = 0;
15422 			}
15423 			open_stream_rele(osp, rp);
15424 
15425 			if (did_start_op)
15426 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15427 				    &recov_state, FALSE);
15428 			if (did_force_recovlock)
15429 				nfs_rw_exit(&mi->mi_recovlock);
15430 
15431 			goto recov_retry;
15432 		} else {
15433 			if (odg_cred_otw)
15434 				crfree(odg_cred_otw);
15435 		}
15436 		goto out;
15437 	}
15438 
15439 	/*
15440 	 * If this open stream was created as the results of an open
15441 	 * while holding a delegation, then just release it; no need
15442 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15443 	 */
15444 	if (osp->os_delegation) {
15445 		nfs4close_notw(vp, osp, &have_sync_lock);
15446 		nfs4_error_zinit(ep);
15447 		goto out;
15448 	}
15449 
15450 	/*
15451 	 * If this stream is not valid, we're done.
15452 	 */
15453 	if (!osp->os_valid) {
15454 		nfs4_error_zinit(ep);
15455 		goto out;
15456 	}
15457 
15458 	/*
15459 	 * Last open or mmap ref has vanished, need to do an OTW close.
15460 	 * First check to see if a close is still necessary.
15461 	 */
15462 	if (osp->os_failed_reopen) {
15463 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15464 		    "don't close OTW osp %p since reopen failed.",
15465 		    (void *)osp));
15466 		/*
15467 		 * Reopen of the open stream failed, hence the
15468 		 * stateid of the open stream is invalid/stale, and
15469 		 * sending this OTW would incorrectly cause another
15470 		 * round of recovery.  In this case, we need to set
15471 		 * the 'os_valid' bit to 0 so another thread doesn't
15472 		 * come in and re-open this open stream before
15473 		 * this "closing" thread cleans up state (decrementing
15474 		 * the nfs4_server_t's state_ref_count and decrementing
15475 		 * the os_ref_count).
15476 		 */
15477 		osp->os_valid = 0;
15478 		/*
15479 		 * This removes the reference obtained at OPEN; ie,
15480 		 * when the open stream structure was created.
15481 		 *
15482 		 * We don't have to worry about calling 'open_stream_rele'
15483 		 * since we our currently holding a reference to this
15484 		 * open stream which means the count can not go to 0 with
15485 		 * this decrement.
15486 		 */
15487 		ASSERT(osp->os_ref_count >= 2);
15488 		osp->os_ref_count--;
15489 		nfs4_error_zinit(ep);
15490 		close_failed = 0;
15491 		goto close_cleanup;
15492 	}
15493 
15494 	ASSERT(osp->os_ref_count > 1);
15495 
15496 	/*
15497 	 * Sixth, try the CLOSE OTW.
15498 	 */
15499 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15500 	    close_type, ep, &have_sync_lock);
15501 
15502 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15503 		/*
15504 		 * Let the recovery thread be responsible for
15505 		 * removing the state for CLOSE.
15506 		 */
15507 		close_failed = 1;
15508 		force_close = 0;
15509 		retry = 0;
15510 	}
15511 
15512 	/* See if we need to retry with a different cred */
15513 	if ((ep->error == EACCES ||
15514 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15515 	    cred_otw != cr) {
15516 		crfree(cred_otw);
15517 		cred_otw = cr;
15518 		crhold(cred_otw);
15519 		retry = 1;
15520 	}
15521 
15522 	if (ep->error || ep->stat)
15523 		close_failed = 1;
15524 
15525 	if (retry && !isrecov && num_retries-- > 0) {
15526 		if (have_sync_lock) {
15527 			mutex_exit(&osp->os_sync_lock);
15528 			have_sync_lock = 0;
15529 		}
15530 		if (did_start_seqid_sync) {
15531 			nfs4_end_open_seqid_sync(oop);
15532 			did_start_seqid_sync = 0;
15533 		}
15534 		open_stream_rele(osp, rp);
15535 
15536 		if (did_start_op)
15537 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15538 			    &recov_state, FALSE);
15539 		if (did_force_recovlock)
15540 			nfs_rw_exit(&mi->mi_recovlock);
15541 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15542 		    "nfs4close_one: need to retry the close "
15543 		    "operation"));
15544 		goto recov_retry;
15545 	}
15546 close_cleanup:
15547 	/*
15548 	 * Seventh and lastly, process our results.
15549 	 */
15550 	if (close_failed && force_close) {
15551 		/*
15552 		 * It's ok to drop and regrab the 'os_sync_lock' since
15553 		 * nfs4close_notw() will recheck to make sure the
15554 		 * "close"/removal of state should happen.
15555 		 */
15556 		if (!have_sync_lock) {
15557 			mutex_enter(&osp->os_sync_lock);
15558 			have_sync_lock = 1;
15559 		}
15560 		/*
15561 		 * This is last call, remove the ref on the open
15562 		 * stream created by open and clean everything up.
15563 		 */
15564 		osp->os_pending_close = 0;
15565 		nfs4close_notw(vp, osp, &have_sync_lock);
15566 		nfs4_error_zinit(ep);
15567 	}
15568 
15569 	if (!close_failed) {
15570 		if (have_sync_lock) {
15571 			osp->os_pending_close = 0;
15572 			mutex_exit(&osp->os_sync_lock);
15573 			have_sync_lock = 0;
15574 		} else {
15575 			mutex_enter(&osp->os_sync_lock);
15576 			osp->os_pending_close = 0;
15577 			mutex_exit(&osp->os_sync_lock);
15578 		}
15579 		if (did_start_op && recov_state.rs_sp != NULL) {
15580 			mutex_enter(&recov_state.rs_sp->s_lock);
15581 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15582 			mutex_exit(&recov_state.rs_sp->s_lock);
15583 		} else {
15584 			nfs4_dec_state_ref_count(mi);
15585 		}
15586 		nfs4_error_zinit(ep);
15587 	}
15588 
15589 out:
15590 	if (have_sync_lock)
15591 		mutex_exit(&osp->os_sync_lock);
15592 	if (did_start_op)
15593 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15594 		    recovonly ? TRUE : FALSE);
15595 	if (did_force_recovlock)
15596 		nfs_rw_exit(&mi->mi_recovlock);
15597 	if (cred_otw)
15598 		crfree(cred_otw);
15599 	if (osp)
15600 		open_stream_rele(osp, rp);
15601 	if (oop) {
15602 		if (did_start_seqid_sync)
15603 			nfs4_end_open_seqid_sync(oop);
15604 		open_owner_rele(oop);
15605 	}
15606 }
15607 
15608 /*
15609  * Convert information returned by the server in the LOCK4denied
15610  * structure to the form required by fcntl.
15611  */
15612 static void
15613 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15614 {
15615 	nfs4_lo_name_t *lo;
15616 
15617 #ifdef	DEBUG
15618 	if (denied_to_flk_debug) {
15619 		lockt_denied_debug = lockt_denied;
15620 		debug_enter("lockt_denied");
15621 	}
15622 #endif
15623 
15624 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15625 	flk->l_whence = 0;	/* aka SEEK_SET */
15626 	flk->l_start = lockt_denied->offset;
15627 	flk->l_len = lockt_denied->length;
15628 
15629 	/*
15630 	 * If the blocking clientid matches our client id, then we can
15631 	 * interpret the lockowner (since we built it).  If not, then
15632 	 * fabricate a sysid and pid.  Note that the l_sysid field
15633 	 * in *flk already has the local sysid.
15634 	 */
15635 
15636 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15637 
15638 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15639 			lo = (nfs4_lo_name_t *)
15640 			    lockt_denied->owner.owner_val;
15641 
15642 			flk->l_pid = lo->ln_pid;
15643 		} else {
15644 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15645 			    "denied_to_flk: bad lock owner length\n"));
15646 
15647 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15648 		}
15649 	} else {
15650 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15651 		"denied_to_flk: foreign clientid\n"));
15652 
15653 		/*
15654 		 * Construct a new sysid which should be different from
15655 		 * sysids of other systems.
15656 		 */
15657 
15658 		flk->l_sysid++;
15659 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15660 	}
15661 }
15662 
15663 static pid_t
15664 lo_to_pid(lock_owner4 *lop)
15665 {
15666 	pid_t pid = 0;
15667 	uchar_t *cp;
15668 	int i;
15669 
15670 	cp = (uchar_t *)&lop->clientid;
15671 
15672 	for (i = 0; i < sizeof (lop->clientid); i++)
15673 		pid += (pid_t)*cp++;
15674 
15675 	cp = (uchar_t *)lop->owner_val;
15676 
15677 	for (i = 0; i < lop->owner_len; i++)
15678 		pid += (pid_t)*cp++;
15679 
15680 	return (pid);
15681 }
15682 
15683 /*
15684  * Given a lock pointer, returns the length of that lock.
15685  * "end" is the last locked offset the "l_len" covers from
15686  * the start of the lock.
15687  */
15688 static off64_t
15689 lock_to_end(flock64_t *lock)
15690 {
15691 	off64_t lock_end;
15692 
15693 	if (lock->l_len == 0)
15694 		lock_end = (off64_t)MAXEND;
15695 	else
15696 		lock_end = lock->l_start + lock->l_len - 1;
15697 
15698 	return (lock_end);
15699 }
15700 
15701 /*
15702  * Given the end of a lock, it will return you the length "l_len" for that lock.
15703  */
15704 static off64_t
15705 end_to_len(off64_t start, off64_t end)
15706 {
15707 	off64_t lock_len;
15708 
15709 	ASSERT(end >= start);
15710 	if (end == MAXEND)
15711 		lock_len = 0;
15712 	else
15713 		lock_len = end - start + 1;
15714 
15715 	return (lock_len);
15716 }
15717 
15718 /*
15719  * On given end for a lock it determines if it is the last locked offset
15720  * or not, if so keeps it as is, else adds one to return the length for
15721  * valid start.
15722  */
15723 static off64_t
15724 start_check(off64_t x)
15725 {
15726 	if (x == MAXEND)
15727 		return (x);
15728 	else
15729 		return (x + 1);
15730 }
15731 
15732 /*
15733  * See if these two locks overlap, and if so return 1;
15734  * otherwise, return 0.
15735  */
15736 static int
15737 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15738 {
15739 	off64_t llfp_end, curfp_end;
15740 
15741 	llfp_end = lock_to_end(llfp);
15742 	curfp_end = lock_to_end(curfp);
15743 
15744 	if (((llfp_end >= curfp->l_start) &&
15745 	    (llfp->l_start <= curfp->l_start)) ||
15746 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15747 		return (1);
15748 	return (0);
15749 }
15750 
15751 /*
15752  * Determine what the intersecting lock region is, and add that to the
15753  * 'nl_llpp' locklist in increasing order (by l_start).
15754  */
15755 static void
15756 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15757     locklist_t **nl_llpp, vnode_t *vp)
15758 {
15759 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15760 	off64_t lost_flp_end, local_flp_end, len, start;
15761 
15762 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15763 
15764 	if (!locks_intersect(lost_flp, local_flp))
15765 		return;
15766 
15767 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15768 	    "locks intersect"));
15769 
15770 	lost_flp_end = lock_to_end(lost_flp);
15771 	local_flp_end = lock_to_end(local_flp);
15772 
15773 	/* Find the starting point of the intersecting region */
15774 	if (local_flp->l_start > lost_flp->l_start)
15775 		start = local_flp->l_start;
15776 	else
15777 		start = lost_flp->l_start;
15778 
15779 	/* Find the lenght of the intersecting region */
15780 	if (lost_flp_end < local_flp_end)
15781 		len = end_to_len(start, lost_flp_end);
15782 	else
15783 		len = end_to_len(start, local_flp_end);
15784 
15785 	/*
15786 	 * Prepare the flock structure for the intersection found and insert
15787 	 * it into the new list in increasing l_start order. This list contains
15788 	 * intersections of locks registered by the client with the local host
15789 	 * and the lost lock.
15790 	 * The lock type of this lock is the same as that of the local_flp.
15791 	 */
15792 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15793 	intersect_llp->ll_flock.l_start = start;
15794 	intersect_llp->ll_flock.l_len = len;
15795 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15796 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15797 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15798 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15799 	intersect_llp->ll_vp = vp;
15800 
15801 	tmp_fllp = *nl_llpp;
15802 	cur_fllp = NULL;
15803 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15804 	    intersect_llp->ll_flock.l_start) {
15805 			cur_fllp = tmp_fllp;
15806 			tmp_fllp = tmp_fllp->ll_next;
15807 	}
15808 	if (cur_fllp == NULL) {
15809 		/* first on the list */
15810 		intersect_llp->ll_next = *nl_llpp;
15811 		*nl_llpp = intersect_llp;
15812 	} else {
15813 		intersect_llp->ll_next = cur_fllp->ll_next;
15814 		cur_fllp->ll_next = intersect_llp;
15815 	}
15816 
15817 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15818 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15819 	    intersect_llp->ll_flock.l_start,
15820 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15821 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15822 }
15823 
15824 /*
15825  * Our local locking current state is potentially different than
15826  * what the NFSv4 server thinks we have due to a lost lock that was
15827  * resent and then received.  We need to reset our "NFSv4" locking
15828  * state to match the current local locking state for this pid since
15829  * that is what the user/application sees as what the world is.
15830  *
15831  * We cannot afford to drop the open/lock seqid sync since then we can
15832  * get confused about what the current local locking state "is" versus
15833  * "was".
15834  *
15835  * If we are unable to fix up the locks, we send SIGLOST to the affected
15836  * process.  This is not done if the filesystem has been forcibly
15837  * unmounted, in case the process has already exited and a new process
15838  * exists with the same pid.
15839  */
15840 static void
15841 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15842     nfs4_lock_owner_t *lop)
15843 {
15844 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15845 	mntinfo4_t *mi = VTOMI4(vp);
15846 	const int cmd = F_SETLK;
15847 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15848 	flock64_t ul_fl;
15849 
15850 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15851 	    "nfs4_reinstitute_local_lock_state"));
15852 
15853 	/*
15854 	 * Find active locks for this vp from the local locking code.
15855 	 * Scan through this list and find out the locks that intersect with
15856 	 * the lost lock. Once we find the lock that intersects, add the
15857 	 * intersection area as a new lock to a new list "ri_llp". The lock
15858 	 * type of the intersection region lock added to ri_llp is the same
15859 	 * as that found in the active lock list, "list". The intersecting
15860 	 * region locks are added to ri_llp in increasing l_start order.
15861 	 */
15862 	ASSERT(nfs_zone() == mi->mi_zone);
15863 
15864 	locks = flk_active_locks_for_vp(vp);
15865 	ri_llp = NULL;
15866 
15867 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15868 		ASSERT(llp->ll_vp == vp);
15869 		/*
15870 		 * Pick locks that belong to this pid/lockowner
15871 		 */
15872 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15873 			continue;
15874 
15875 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15876 	}
15877 
15878 	/*
15879 	 * Now we have the list of intersections with the lost lock. These are
15880 	 * the locks that were/are active before the server replied to the
15881 	 * last/lost lock. Issue these locks to the server here. Playing these
15882 	 * locks to the server will re-establish our current local locking state
15883 	 * with the v4 server.
15884 	 * If we get an error, send SIGLOST to the application for that lock.
15885 	 */
15886 
15887 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15888 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15889 		    "nfs4_reinstitute_local_lock_state: need to issue "
15890 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15891 		    llp->ll_flock.l_start,
15892 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15893 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15894 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15895 		/*
15896 		 * No need to relock what we already have
15897 		 */
15898 		if (llp->ll_flock.l_type == lost_flp->l_type)
15899 			continue;
15900 
15901 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15902 	}
15903 
15904 	/*
15905 	 * Now keeping the start of the lost lock as our reference parse the
15906 	 * newly created ri_llp locklist to find the ranges that we have locked
15907 	 * with the v4 server but not in the current local locking. We need
15908 	 * to unlock these ranges.
15909 	 * These ranges can also be reffered to as those ranges, where the lost
15910 	 * lock does not overlap with the locks in the ri_llp but are locked
15911 	 * since the server replied to the lost lock.
15912 	 */
15913 	cur_start = lost_flp->l_start;
15914 	lost_flp_end = lock_to_end(lost_flp);
15915 
15916 	ul_fl.l_type = F_UNLCK;
15917 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15918 	ul_fl.l_sysid = lost_flp->l_sysid;
15919 	ul_fl.l_pid = lost_flp->l_pid;
15920 
15921 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15922 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15923 
15924 		if (llp->ll_flock.l_start <= cur_start) {
15925 			cur_start = start_check(llp_ll_flock_end);
15926 			continue;
15927 		}
15928 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15929 		    "nfs4_reinstitute_local_lock_state: "
15930 		    "UNLOCK [%"PRIx64" - %"PRIx64"]",
15931 		    cur_start, llp->ll_flock.l_start));
15932 
15933 		ul_fl.l_start = cur_start;
15934 		ul_fl.l_len = end_to_len(cur_start,
15935 		    (llp->ll_flock.l_start - 1));
15936 
15937 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15938 		cur_start = start_check(llp_ll_flock_end);
15939 	}
15940 
15941 	/*
15942 	 * In the case where the lost lock ends after all intersecting locks,
15943 	 * unlock the last part of the lost lock range.
15944 	 */
15945 	if (cur_start != start_check(lost_flp_end)) {
15946 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15947 		    "nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15948 		    "lost lock region [%"PRIx64" - %"PRIx64"]",
15949 		    cur_start, lost_flp->l_start + lost_flp->l_len));
15950 
15951 		ul_fl.l_start = cur_start;
15952 		/*
15953 		 * Is it an to-EOF lock? if so unlock till the end
15954 		 */
15955 		if (lost_flp->l_len == 0)
15956 			ul_fl.l_len = 0;
15957 		else
15958 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15959 
15960 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15961 	}
15962 
15963 	if (locks != NULL)
15964 		flk_free_locklist(locks);
15965 
15966 	/* Free up our newly created locklist */
15967 	for (llp = ri_llp; llp != NULL; ) {
15968 		tmp_llp = llp->ll_next;
15969 		kmem_free(llp, sizeof (locklist_t));
15970 		llp = tmp_llp;
15971 	}
15972 
15973 	/*
15974 	 * Now return back to the original calling nfs4frlock()
15975 	 * and let us naturally drop our seqid syncs.
15976 	 */
15977 }
15978 
15979 /*
15980  * Create a lost state record for the given lock reinstantiation request
15981  * and push it onto the lost state queue.
15982  */
15983 static void
15984 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
15985     nfs4_lock_owner_t *lop)
15986 {
15987 	nfs4_lost_rqst_t req;
15988 	nfs_lock_type4 locktype;
15989 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
15990 
15991 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15992 
15993 	locktype = flk_to_locktype(cmd, flk->l_type);
15994 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
15995 	    NULL, NULL, lop, flk, &req, cr, vp);
15996 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
15997 	    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
15998 	    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
15999 	    NULL, NULL, NULL);
16000 }
16001