xref: /titanic_50/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision 00c76d6fcc0e3d5821ed5ac5165f1835f8151454)
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  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  *	Copyright 1983,1984,1985,1986,1987,1988,1989 AT&T.
28  *	All Rights Reserved
29  */
30 
31 #pragma ident	"%Z%%M%	%I%	%E% SMI"
32 
33 #include <sys/param.h>
34 #include <sys/types.h>
35 #include <sys/systm.h>
36 #include <sys/cred.h>
37 #include <sys/time.h>
38 #include <sys/vnode.h>
39 #include <sys/vfs.h>
40 #include <sys/vfs_opreg.h>
41 #include <sys/file.h>
42 #include <sys/filio.h>
43 #include <sys/uio.h>
44 #include <sys/buf.h>
45 #include <sys/mman.h>
46 #include <sys/pathname.h>
47 #include <sys/dirent.h>
48 #include <sys/debug.h>
49 #include <sys/vmsystm.h>
50 #include <sys/fcntl.h>
51 #include <sys/flock.h>
52 #include <sys/swap.h>
53 #include <sys/errno.h>
54 #include <sys/strsubr.h>
55 #include <sys/sysmacros.h>
56 #include <sys/kmem.h>
57 #include <sys/cmn_err.h>
58 #include <sys/pathconf.h>
59 #include <sys/utsname.h>
60 #include <sys/dnlc.h>
61 #include <sys/acl.h>
62 #include <sys/systeminfo.h>
63 #include <sys/policy.h>
64 #include <sys/sdt.h>
65 #include <sys/list.h>
66 #include <sys/stat.h>
67 
68 #include <rpc/types.h>
69 #include <rpc/auth.h>
70 #include <rpc/clnt.h>
71 
72 #include <nfs/nfs.h>
73 #include <nfs/nfs_clnt.h>
74 #include <nfs/nfs_acl.h>
75 #include <nfs/lm.h>
76 #include <nfs/nfs4.h>
77 #include <nfs/nfs4_kprot.h>
78 #include <nfs/rnode4.h>
79 #include <nfs/nfs4_clnt.h>
80 
81 #include <vm/hat.h>
82 #include <vm/as.h>
83 #include <vm/page.h>
84 #include <vm/pvn.h>
85 #include <vm/seg.h>
86 #include <vm/seg_map.h>
87 #include <vm/seg_kpm.h>
88 #include <vm/seg_vn.h>
89 
90 #include <fs/fs_subr.h>
91 
92 #include <sys/ddi.h>
93 #include <sys/int_fmtio.h>
94 
95 typedef struct {
96 	nfs4_ga_res_t	*di_garp;
97 	cred_t		*di_cred;
98 	hrtime_t	di_time_call;
99 } dirattr_info_t;
100 
101 typedef enum nfs4_acl_op {
102 	NFS4_ACL_GET,
103 	NFS4_ACL_SET
104 } nfs4_acl_op_t;
105 
106 static void	nfs4_update_dircaches(change_info4 *, vnode_t *, vnode_t *,
107 			char *, dirattr_info_t *);
108 
109 static void	nfs4close_otw(rnode4_t *, cred_t *, nfs4_open_owner_t *,
110 		    nfs4_open_stream_t *, int *, int *, nfs4_close_type_t,
111 		    nfs4_error_t *, int *);
112 static int	nfs4_rdwrlbn(vnode_t *, page_t *, u_offset_t, size_t, int,
113 			cred_t *);
114 static int	nfs4write(vnode_t *, caddr_t, u_offset_t, int, cred_t *,
115 			stable_how4 *);
116 static int	nfs4read(vnode_t *, caddr_t, offset_t, int, size_t *,
117 			cred_t *, bool_t, struct uio *);
118 static int	nfs4setattr(vnode_t *, struct vattr *, int, cred_t *,
119 			vsecattr_t *);
120 static int	nfs4openattr(vnode_t *, vnode_t **, int, cred_t *);
121 static int	nfs4lookup(vnode_t *, char *, vnode_t **, cred_t *, int);
122 static int	nfs4lookup_xattr(vnode_t *, char *, vnode_t **, int, cred_t *);
123 static int	nfs4lookupvalidate_otw(vnode_t *, char *, vnode_t **, cred_t *);
124 static int	nfs4lookupnew_otw(vnode_t *, char *, vnode_t **, cred_t *);
125 static int	nfs4mknod(vnode_t *, char *, struct vattr *, enum vcexcl,
126 			int, vnode_t **, cred_t *);
127 static int	nfs4open_otw(vnode_t *, char *, struct vattr *, vnode_t **,
128 			cred_t *, int, int, enum createmode4, int);
129 static int	nfs4rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
130 			caller_context_t *);
131 static int	nfs4rename_persistent_fh(vnode_t *, char *, vnode_t *,
132 			vnode_t *, char *, cred_t *, nfsstat4 *);
133 static int	nfs4rename_volatile_fh(vnode_t *, char *, vnode_t *,
134 			vnode_t *, char *, cred_t *, nfsstat4 *);
135 static int	do_nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
136 static void	nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
137 static int	nfs4_bio(struct buf *, stable_how4 *, cred_t *, bool_t);
138 static int	nfs4_getapage(vnode_t *, u_offset_t, size_t, uint_t *,
139 			page_t *[], size_t, struct seg *, caddr_t,
140 			enum seg_rw, cred_t *);
141 static void	nfs4_readahead(vnode_t *, u_offset_t, caddr_t, struct seg *,
142 			cred_t *);
143 static int	nfs4_sync_putapage(vnode_t *, page_t *, u_offset_t, size_t,
144 			int, cred_t *);
145 static int	nfs4_sync_pageio(vnode_t *, page_t *, u_offset_t, size_t,
146 			int, cred_t *);
147 static int	nfs4_commit(vnode_t *, offset4, count4, cred_t *);
148 static void	nfs4_set_mod(vnode_t *);
149 static void	nfs4_get_commit(vnode_t *);
150 static void	nfs4_get_commit_range(vnode_t *, u_offset_t, size_t);
151 static int	nfs4_putpage_commit(vnode_t *, offset_t, size_t, cred_t *);
152 static int	nfs4_commit_vp(vnode_t *, u_offset_t, size_t, cred_t *, int);
153 static int	nfs4_sync_commit(vnode_t *, page_t *, offset3, count3,
154 			cred_t *);
155 static void	do_nfs4_async_commit(vnode_t *, page_t *, offset3, count3,
156 			cred_t *);
157 static int	nfs4_update_attrcache(nfsstat4, nfs4_ga_res_t *,
158 			hrtime_t, vnode_t *, cred_t *);
159 static int	nfs4_open_non_reg_file(vnode_t **, int, cred_t *);
160 static int	nfs4_safelock(vnode_t *, const struct flock64 *, cred_t *);
161 static void	nfs4_register_lock_locally(vnode_t *, struct flock64 *, int,
162 			u_offset_t);
163 static int 	nfs4_lockrelease(vnode_t *, int, offset_t, cred_t *);
164 static int	nfs4_block_and_wait(clock_t *, rnode4_t *);
165 static cred_t  *state_to_cred(nfs4_open_stream_t *);
166 static int	vtoname(vnode_t *, char *, ssize_t);
167 static void	denied_to_flk(LOCK4denied *, flock64_t *, LOCKT4args *);
168 static pid_t	lo_to_pid(lock_owner4 *);
169 static void	nfs4_reinstitute_local_lock_state(vnode_t *, flock64_t *,
170 			cred_t *, nfs4_lock_owner_t *);
171 static void	push_reinstate(vnode_t *, int, flock64_t *, cred_t *,
172 			nfs4_lock_owner_t *);
173 static int 	open_and_get_osp(vnode_t *, cred_t *, nfs4_open_stream_t **);
174 static void	nfs4_delmap_callback(struct as *, void *, uint_t);
175 static void	nfs4_free_delmapcall(nfs4_delmapcall_t *);
176 static nfs4_delmapcall_t	*nfs4_init_delmapcall();
177 static int	nfs4_find_and_delete_delmapcall(rnode4_t *, int *);
178 static int	nfs4_is_acl_mask_valid(uint_t, nfs4_acl_op_t);
179 static int	nfs4_create_getsecattr_return(vsecattr_t *, vsecattr_t *,
180 			uid_t, gid_t, int);
181 
182 /*
183  * Routines that implement the setting of v4 args for the misc. ops
184  */
185 static void	nfs4args_lock_free(nfs_argop4 *);
186 static void	nfs4args_lockt_free(nfs_argop4 *);
187 static void	nfs4args_setattr(nfs_argop4 *, vattr_t *, vsecattr_t *,
188 			int, rnode4_t *, cred_t *, bitmap4, int *,
189 			nfs4_stateid_types_t *);
190 static void	nfs4args_setattr_free(nfs_argop4 *);
191 static int	nfs4args_verify(nfs_argop4 *, vattr_t *, enum nfs_opnum4,
192 			bitmap4);
193 static void	nfs4args_verify_free(nfs_argop4 *);
194 static void	nfs4args_write(nfs_argop4 *, stable_how4, rnode4_t *, cred_t *,
195 			WRITE4args **, nfs4_stateid_types_t *);
196 
197 /*
198  * These are the vnode ops functions that implement the vnode interface to
199  * the networked file system.  See more comments below at nfs4_vnodeops.
200  */
201 static int	nfs4_open(vnode_t **, int, cred_t *, caller_context_t *);
202 static int	nfs4_close(vnode_t *, int, int, offset_t, cred_t *,
203 			caller_context_t *);
204 static int	nfs4_read(vnode_t *, struct uio *, int, cred_t *,
205 			caller_context_t *);
206 static int	nfs4_write(vnode_t *, struct uio *, int, cred_t *,
207 			caller_context_t *);
208 static int	nfs4_ioctl(vnode_t *, int, intptr_t, int, cred_t *, int *,
209 			caller_context_t *);
210 static int	nfs4_setattr(vnode_t *, struct vattr *, int, cred_t *,
211 			caller_context_t *);
212 static int	nfs4_access(vnode_t *, int, int, cred_t *, caller_context_t *);
213 static int	nfs4_readlink(vnode_t *, struct uio *, cred_t *,
214 			caller_context_t *);
215 static int	nfs4_fsync(vnode_t *, int, cred_t *, caller_context_t *);
216 static int	nfs4_create(vnode_t *, char *, struct vattr *, enum vcexcl,
217 			int, vnode_t **, cred_t *, int, caller_context_t *,
218 			vsecattr_t *);
219 static int	nfs4_remove(vnode_t *, char *, cred_t *, caller_context_t *,
220 			int);
221 static int	nfs4_link(vnode_t *, vnode_t *, char *, cred_t *,
222 			caller_context_t *, int);
223 static int	nfs4_rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
224 			caller_context_t *, int);
225 static int	nfs4_mkdir(vnode_t *, char *, struct vattr *, vnode_t **,
226 			cred_t *, caller_context_t *, int, vsecattr_t *);
227 static int	nfs4_rmdir(vnode_t *, char *, vnode_t *, cred_t *,
228 			caller_context_t *, int);
229 static int	nfs4_symlink(vnode_t *, char *, struct vattr *, char *,
230 			cred_t *, caller_context_t *, int);
231 static int	nfs4_readdir(vnode_t *, struct uio *, cred_t *, int *,
232 			caller_context_t *, int);
233 static int	nfs4_seek(vnode_t *, offset_t, offset_t *, caller_context_t *);
234 static int	nfs4_getpage(vnode_t *, offset_t, size_t, uint_t *,
235 			page_t *[], size_t, struct seg *, caddr_t,
236 			enum seg_rw, cred_t *, caller_context_t *);
237 static int	nfs4_putpage(vnode_t *, offset_t, size_t, int, cred_t *,
238 			caller_context_t *);
239 static int	nfs4_map(vnode_t *, offset_t, struct as *, caddr_t *, size_t,
240 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
241 static int	nfs4_addmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
242 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
243 static int	nfs4_cmp(vnode_t *, vnode_t *, caller_context_t *);
244 static int	nfs4_frlock(vnode_t *, int, struct flock64 *, int, offset_t,
245 			struct flk_callback *, cred_t *, caller_context_t *);
246 static int	nfs4_space(vnode_t *, int, struct flock64 *, int, offset_t,
247 			cred_t *, caller_context_t *);
248 static int	nfs4_delmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
249 			uint_t, uint_t, uint_t, cred_t *, caller_context_t *);
250 static int	nfs4_pageio(vnode_t *, page_t *, u_offset_t, size_t, int,
251 			cred_t *, caller_context_t *);
252 static void	nfs4_dispose(vnode_t *, page_t *, int, int, cred_t *,
253 			caller_context_t *);
254 static int	nfs4_setsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
255 			caller_context_t *);
256 /*
257  * These vnode ops are required to be called from outside this source file,
258  * e.g. by ephemeral mount stub vnode ops, and so may not be declared
259  * as static.
260  */
261 int	nfs4_getattr(vnode_t *, struct vattr *, int, cred_t *,
262 	    caller_context_t *);
263 void	nfs4_inactive(vnode_t *, cred_t *, caller_context_t *);
264 int	nfs4_lookup(vnode_t *, char *, vnode_t **,
265 	    struct pathname *, int, vnode_t *, cred_t *,
266 	    caller_context_t *, int *, pathname_t *);
267 int	nfs4_fid(vnode_t *, fid_t *, caller_context_t *);
268 int	nfs4_rwlock(vnode_t *, int, caller_context_t *);
269 void	nfs4_rwunlock(vnode_t *, int, caller_context_t *);
270 int	nfs4_realvp(vnode_t *, vnode_t **, caller_context_t *);
271 int	nfs4_pathconf(vnode_t *, int, ulong_t *, cred_t *,
272 	    caller_context_t *);
273 int	nfs4_getsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
274 	    caller_context_t *);
275 int	nfs4_shrlock(vnode_t *, int, struct shrlock *, int, cred_t *,
276 	    caller_context_t *);
277 
278 /*
279  * Used for nfs4_commit_vp() to indicate if we should
280  * wait on pending writes.
281  */
282 #define	NFS4_WRITE_NOWAIT	0
283 #define	NFS4_WRITE_WAIT		1
284 
285 #define	NFS4_BASE_WAIT_TIME 1	/* 1 second */
286 
287 /*
288  * Error flags used to pass information about certain special errors
289  * which need to be handled specially.
290  */
291 #define	NFS_EOF			-98
292 #define	NFS_VERF_MISMATCH	-97
293 
294 /*
295  * Flags used to differentiate between which operation drove the
296  * potential CLOSE OTW. (see nfs4_close_otw_if_necessary)
297  */
298 #define	NFS4_CLOSE_OP		0x1
299 #define	NFS4_DELMAP_OP		0x2
300 #define	NFS4_INACTIVE_OP	0x3
301 
302 #define	ISVDEV(t) ((t == VBLK) || (t == VCHR) || (t == VFIFO))
303 
304 /* ALIGN64 aligns the given buffer and adjust buffer size to 64 bit */
305 #define	ALIGN64(x, ptr, sz)						\
306 	x = ((uintptr_t)(ptr)) & (sizeof (uint64_t) - 1);		\
307 	if (x) {							\
308 		x = sizeof (uint64_t) - (x);				\
309 		sz -= (x);						\
310 		ptr += (x);						\
311 	}
312 
313 #ifdef DEBUG
314 int nfs4_client_attr_debug = 0;
315 int nfs4_client_state_debug = 0;
316 int nfs4_client_shadow_debug = 0;
317 int nfs4_client_lock_debug = 0;
318 int nfs4_seqid_sync = 0;
319 int nfs4_client_map_debug = 0;
320 static int nfs4_pageio_debug = 0;
321 int nfs4_client_inactive_debug = 0;
322 int nfs4_client_recov_debug = 0;
323 int nfs4_client_failover_debug = 0;
324 int nfs4_client_call_debug = 0;
325 int nfs4_client_lookup_debug = 0;
326 int nfs4_client_zone_debug = 0;
327 int nfs4_lost_rqst_debug = 0;
328 int nfs4_rdattrerr_debug = 0;
329 int nfs4_open_stream_debug = 0;
330 
331 int nfs4read_error_inject;
332 
333 static int nfs4_create_misses = 0;
334 
335 static int nfs4_readdir_cache_shorts = 0;
336 static int nfs4_readdir_readahead = 0;
337 
338 static int nfs4_bio_do_stop = 0;
339 
340 static int nfs4_lostpage = 0;	/* number of times we lost original page */
341 
342 int nfs4_mmap_debug = 0;
343 
344 static int nfs4_pathconf_cache_hits = 0;
345 static int nfs4_pathconf_cache_misses = 0;
346 
347 int nfs4close_all_cnt;
348 int nfs4close_one_debug = 0;
349 int nfs4close_notw_debug = 0;
350 
351 int denied_to_flk_debug = 0;
352 void *lockt_denied_debug;
353 
354 #endif
355 
356 /*
357  * How long to wait before trying again if OPEN_CONFIRM gets ETIMEDOUT
358  * or NFS4ERR_RESOURCE.
359  */
360 static int confirm_retry_sec = 30;
361 
362 static int nfs4_lookup_neg_cache = 1;
363 
364 /*
365  * number of pages to read ahead
366  * optimized for 100 base-T.
367  */
368 static int nfs4_nra = 4;
369 
370 static int nfs4_do_symlink_cache = 1;
371 
372 static int nfs4_pathconf_disable_cache = 0;
373 
374 /*
375  * These are the vnode ops routines which implement the vnode interface to
376  * the networked file system.  These routines just take their parameters,
377  * make them look networkish by putting the right info into interface structs,
378  * and then calling the appropriate remote routine(s) to do the work.
379  *
380  * Note on directory name lookup cacheing:  If we detect a stale fhandle,
381  * we purge the directory cache relative to that vnode.  This way, the
382  * user won't get burned by the cache repeatedly.  See <nfs/rnode4.h> for
383  * more details on rnode locking.
384  */
385 
386 struct vnodeops *nfs4_vnodeops;
387 
388 const fs_operation_def_t nfs4_vnodeops_template[] = {
389 	VOPNAME_OPEN,		{ .vop_open = nfs4_open },
390 	VOPNAME_CLOSE,		{ .vop_close = nfs4_close },
391 	VOPNAME_READ,		{ .vop_read = nfs4_read },
392 	VOPNAME_WRITE,		{ .vop_write = nfs4_write },
393 	VOPNAME_IOCTL,		{ .vop_ioctl = nfs4_ioctl },
394 	VOPNAME_GETATTR,	{ .vop_getattr = nfs4_getattr },
395 	VOPNAME_SETATTR,	{ .vop_setattr = nfs4_setattr },
396 	VOPNAME_ACCESS,		{ .vop_access = nfs4_access },
397 	VOPNAME_LOOKUP,		{ .vop_lookup = nfs4_lookup },
398 	VOPNAME_CREATE,		{ .vop_create = nfs4_create },
399 	VOPNAME_REMOVE,		{ .vop_remove = nfs4_remove },
400 	VOPNAME_LINK,		{ .vop_link = nfs4_link },
401 	VOPNAME_RENAME,		{ .vop_rename = nfs4_rename },
402 	VOPNAME_MKDIR,		{ .vop_mkdir = nfs4_mkdir },
403 	VOPNAME_RMDIR,		{ .vop_rmdir = nfs4_rmdir },
404 	VOPNAME_READDIR,	{ .vop_readdir = nfs4_readdir },
405 	VOPNAME_SYMLINK,	{ .vop_symlink = nfs4_symlink },
406 	VOPNAME_READLINK,	{ .vop_readlink = nfs4_readlink },
407 	VOPNAME_FSYNC,		{ .vop_fsync = nfs4_fsync },
408 	VOPNAME_INACTIVE,	{ .vop_inactive = nfs4_inactive },
409 	VOPNAME_FID,		{ .vop_fid = nfs4_fid },
410 	VOPNAME_RWLOCK,		{ .vop_rwlock = nfs4_rwlock },
411 	VOPNAME_RWUNLOCK,	{ .vop_rwunlock = nfs4_rwunlock },
412 	VOPNAME_SEEK,		{ .vop_seek = nfs4_seek },
413 	VOPNAME_FRLOCK,		{ .vop_frlock = nfs4_frlock },
414 	VOPNAME_SPACE,		{ .vop_space = nfs4_space },
415 	VOPNAME_REALVP,		{ .vop_realvp = nfs4_realvp },
416 	VOPNAME_GETPAGE,	{ .vop_getpage = nfs4_getpage },
417 	VOPNAME_PUTPAGE,	{ .vop_putpage = nfs4_putpage },
418 	VOPNAME_MAP,		{ .vop_map = nfs4_map },
419 	VOPNAME_ADDMAP,		{ .vop_addmap = nfs4_addmap },
420 	VOPNAME_DELMAP,		{ .vop_delmap = nfs4_delmap },
421 	/* no separate nfs4_dump */
422 	VOPNAME_DUMP,		{ .vop_dump = nfs_dump },
423 	VOPNAME_PATHCONF,	{ .vop_pathconf = nfs4_pathconf },
424 	VOPNAME_PAGEIO,		{ .vop_pageio = nfs4_pageio },
425 	VOPNAME_DISPOSE,	{ .vop_dispose = nfs4_dispose },
426 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = nfs4_setsecattr },
427 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = nfs4_getsecattr },
428 	VOPNAME_SHRLOCK,	{ .vop_shrlock = nfs4_shrlock },
429 	VOPNAME_VNEVENT, 	{ .vop_vnevent = fs_vnevent_support },
430 	NULL,			NULL
431 };
432 
433 /*
434  * The following are subroutines and definitions to set args or get res
435  * for the different nfsv4 ops
436  */
437 
438 void
439 nfs4args_lookup_free(nfs_argop4 *argop, int arglen)
440 {
441 	int		i;
442 
443 	for (i = 0; i < arglen; i++) {
444 		if (argop[i].argop == OP_LOOKUP) {
445 			kmem_free(
446 			    argop[i].nfs_argop4_u.oplookup.
447 			    objname.utf8string_val,
448 			    argop[i].nfs_argop4_u.oplookup.
449 			    objname.utf8string_len);
450 		}
451 	}
452 }
453 
454 static void
455 nfs4args_lock_free(nfs_argop4 *argop)
456 {
457 	locker4 *locker = &argop->nfs_argop4_u.oplock.locker;
458 
459 	if (locker->new_lock_owner == TRUE) {
460 		open_to_lock_owner4 *open_owner;
461 
462 		open_owner = &locker->locker4_u.open_owner;
463 		if (open_owner->lock_owner.owner_val != NULL) {
464 			kmem_free(open_owner->lock_owner.owner_val,
465 			    open_owner->lock_owner.owner_len);
466 		}
467 	}
468 }
469 
470 static void
471 nfs4args_lockt_free(nfs_argop4 *argop)
472 {
473 	lock_owner4 *lowner = &argop->nfs_argop4_u.oplockt.owner;
474 
475 	if (lowner->owner_val != NULL) {
476 		kmem_free(lowner->owner_val, lowner->owner_len);
477 	}
478 }
479 
480 static void
481 nfs4args_setattr(nfs_argop4 *argop, vattr_t *vap, vsecattr_t *vsap, int flags,
482     rnode4_t *rp, cred_t *cr, bitmap4 supp, int *error,
483     nfs4_stateid_types_t *sid_types)
484 {
485 	fattr4		*attr = &argop->nfs_argop4_u.opsetattr.obj_attributes;
486 	mntinfo4_t	*mi;
487 
488 	argop->argop = OP_SETATTR;
489 	/*
490 	 * The stateid is set to 0 if client is not modifying the size
491 	 * and otherwise to whatever nfs4_get_stateid() returns.
492 	 *
493 	 * XXX Note: nfs4_get_stateid() returns 0 if no lockowner and/or no
494 	 * state struct could be found for the process/file pair.  We may
495 	 * want to change this in the future (by OPENing the file).  See
496 	 * bug # 4474852.
497 	 */
498 	if (vap->va_mask & AT_SIZE) {
499 
500 		ASSERT(rp != NULL);
501 		mi = VTOMI4(RTOV4(rp));
502 
503 		argop->nfs_argop4_u.opsetattr.stateid =
504 		    nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
505 		    OP_SETATTR, sid_types, FALSE);
506 	} else {
507 		bzero(&argop->nfs_argop4_u.opsetattr.stateid,
508 		    sizeof (stateid4));
509 	}
510 
511 	*error = vattr_to_fattr4(vap, vsap, attr, flags, OP_SETATTR, supp);
512 	if (*error)
513 		bzero(attr, sizeof (*attr));
514 }
515 
516 static void
517 nfs4args_setattr_free(nfs_argop4 *argop)
518 {
519 	nfs4_fattr4_free(&argop->nfs_argop4_u.opsetattr.obj_attributes);
520 }
521 
522 static int
523 nfs4args_verify(nfs_argop4 *argop, vattr_t *vap, enum nfs_opnum4 op,
524     bitmap4 supp)
525 {
526 	fattr4 *attr;
527 	int error = 0;
528 
529 	argop->argop = op;
530 	switch (op) {
531 	case OP_VERIFY:
532 		attr = &argop->nfs_argop4_u.opverify.obj_attributes;
533 		break;
534 	case OP_NVERIFY:
535 		attr = &argop->nfs_argop4_u.opnverify.obj_attributes;
536 		break;
537 	default:
538 		return (EINVAL);
539 	}
540 	if (!error)
541 		error = vattr_to_fattr4(vap, NULL, attr, 0, op, supp);
542 	if (error)
543 		bzero(attr, sizeof (*attr));
544 	return (error);
545 }
546 
547 static void
548 nfs4args_verify_free(nfs_argop4 *argop)
549 {
550 	switch (argop->argop) {
551 	case OP_VERIFY:
552 		nfs4_fattr4_free(&argop->nfs_argop4_u.opverify.obj_attributes);
553 		break;
554 	case OP_NVERIFY:
555 		nfs4_fattr4_free(&argop->nfs_argop4_u.opnverify.obj_attributes);
556 		break;
557 	default:
558 		break;
559 	}
560 }
561 
562 static void
563 nfs4args_write(nfs_argop4 *argop, stable_how4 stable, rnode4_t *rp, cred_t *cr,
564     WRITE4args **wargs_pp, nfs4_stateid_types_t *sid_tp)
565 {
566 	WRITE4args *wargs = &argop->nfs_argop4_u.opwrite;
567 	mntinfo4_t *mi = VTOMI4(RTOV4(rp));
568 
569 	argop->argop = OP_WRITE;
570 	wargs->stable = stable;
571 	wargs->stateid = nfs4_get_w_stateid(cr, rp, curproc->p_pidp->pid_id,
572 	    mi, OP_WRITE, sid_tp);
573 	wargs->mblk = NULL;
574 	*wargs_pp = wargs;
575 }
576 
577 void
578 nfs4args_copen_free(OPEN4cargs *open_args)
579 {
580 	if (open_args->owner.owner_val) {
581 		kmem_free(open_args->owner.owner_val,
582 		    open_args->owner.owner_len);
583 	}
584 	if ((open_args->opentype == OPEN4_CREATE) &&
585 	    (open_args->mode != EXCLUSIVE4)) {
586 		nfs4_fattr4_free(&open_args->createhow4_u.createattrs);
587 	}
588 }
589 
590 /*
591  * XXX:  This is referenced in modstubs.s
592  */
593 struct vnodeops *
594 nfs4_getvnodeops(void)
595 {
596 	return (nfs4_vnodeops);
597 }
598 
599 /*
600  * The OPEN operation opens a regular file.
601  */
602 /*ARGSUSED3*/
603 static int
604 nfs4_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
605 {
606 	vnode_t *dvp = NULL;
607 	rnode4_t *rp, *drp;
608 	int error;
609 	int just_been_created;
610 	char fn[MAXNAMELEN];
611 
612 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4_open: "));
613 	if (nfs_zone() != VTOMI4(*vpp)->mi_zone)
614 		return (EIO);
615 	rp = VTOR4(*vpp);
616 
617 	/*
618 	 * Check to see if opening something besides a regular file;
619 	 * if so skip the OTW call
620 	 */
621 	if ((*vpp)->v_type != VREG) {
622 		error = nfs4_open_non_reg_file(vpp, flag, cr);
623 		return (error);
624 	}
625 
626 	/*
627 	 * XXX - would like a check right here to know if the file is
628 	 * executable or not, so as to skip OTW
629 	 */
630 
631 	if ((error = vtodv(*vpp, &dvp, cr, TRUE)) != 0)
632 		return (error);
633 
634 	drp = VTOR4(dvp);
635 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
636 		return (EINTR);
637 
638 	if ((error = vtoname(*vpp, fn, MAXNAMELEN)) != 0) {
639 		nfs_rw_exit(&drp->r_rwlock);
640 		return (error);
641 	}
642 
643 	/*
644 	 * See if this file has just been CREATEd.
645 	 * If so, clear the flag and update the dnlc, which was previously
646 	 * skipped in nfs4_create.
647 	 * XXX need better serilization on this.
648 	 * XXX move this into the nf4open_otw call, after we have
649 	 * XXX acquired the open owner seqid sync.
650 	 */
651 	mutex_enter(&rp->r_statev4_lock);
652 	if (rp->created_v4) {
653 		rp->created_v4 = 0;
654 		mutex_exit(&rp->r_statev4_lock);
655 
656 		dnlc_update(dvp, fn, *vpp);
657 		/* This is needed so we don't bump the open ref count */
658 		just_been_created = 1;
659 	} else {
660 		mutex_exit(&rp->r_statev4_lock);
661 		just_been_created = 0;
662 	}
663 
664 	/*
665 	 * If caller specified O_TRUNC/FTRUNC, then be sure to set
666 	 * FWRITE (to drive successful setattr(size=0) after open)
667 	 */
668 	if (flag & FTRUNC)
669 		flag |= FWRITE;
670 
671 	error = nfs4open_otw(dvp, fn, NULL, vpp, cr, 0, flag, 0,
672 	    just_been_created);
673 
674 	if (!error && !((*vpp)->v_flag & VROOT))
675 		dnlc_update(dvp, fn, *vpp);
676 
677 	nfs_rw_exit(&drp->r_rwlock);
678 
679 	/* release the hold from vtodv */
680 	VN_RELE(dvp);
681 
682 	/* exchange the shadow for the master vnode, if needed */
683 
684 	if (error == 0 && IS_SHADOW(*vpp, rp))
685 		sv_exchange(vpp);
686 
687 	return (error);
688 }
689 
690 /*
691  * See if there's a "lost open" request to be saved and recovered.
692  */
693 static void
694 nfs4open_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
695     nfs4_open_owner_t *oop, cred_t *cr, vnode_t *vp,
696     vnode_t *dvp, OPEN4cargs *open_args)
697 {
698 	vfs_t *vfsp;
699 	char *srccfp;
700 
701 	vfsp = (dvp ? dvp->v_vfsp : vp->v_vfsp);
702 
703 	if (error != ETIMEDOUT && error != EINTR &&
704 	    !NFS4_FRC_UNMT_ERR(error, vfsp)) {
705 		lost_rqstp->lr_op = 0;
706 		return;
707 	}
708 
709 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
710 	    "nfs4open_save_lost_rqst: error %d", error));
711 
712 	lost_rqstp->lr_op = OP_OPEN;
713 
714 	/*
715 	 * The vp (if it is not NULL) and dvp are held and rele'd via
716 	 * the recovery code.  See nfs4_save_lost_rqst.
717 	 */
718 	lost_rqstp->lr_vp = vp;
719 	lost_rqstp->lr_dvp = dvp;
720 	lost_rqstp->lr_oop = oop;
721 	lost_rqstp->lr_osp = NULL;
722 	lost_rqstp->lr_lop = NULL;
723 	lost_rqstp->lr_cr = cr;
724 	lost_rqstp->lr_flk = NULL;
725 	lost_rqstp->lr_oacc = open_args->share_access;
726 	lost_rqstp->lr_odeny = open_args->share_deny;
727 	lost_rqstp->lr_oclaim = open_args->claim;
728 	if (open_args->claim == CLAIM_DELEGATE_CUR) {
729 		lost_rqstp->lr_ostateid =
730 		    open_args->open_claim4_u.delegate_cur_info.delegate_stateid;
731 		srccfp = open_args->open_claim4_u.delegate_cur_info.cfile;
732 	} else {
733 		srccfp = open_args->open_claim4_u.cfile;
734 	}
735 	lost_rqstp->lr_ofile.utf8string_len = 0;
736 	lost_rqstp->lr_ofile.utf8string_val = NULL;
737 	(void) str_to_utf8(srccfp, &lost_rqstp->lr_ofile);
738 	lost_rqstp->lr_putfirst = FALSE;
739 }
740 
741 struct nfs4_excl_time {
742 	uint32 seconds;
743 	uint32 nseconds;
744 };
745 
746 /*
747  * The OPEN operation creates and/or opens a regular file
748  *
749  * ARGSUSED
750  */
751 static int
752 nfs4open_otw(vnode_t *dvp, char *file_name, struct vattr *in_va,
753     vnode_t **vpp, cred_t *cr, int create_flag, int open_flag,
754     enum createmode4 createmode, int file_just_been_created)
755 {
756 	rnode4_t *rp;
757 	rnode4_t *drp = VTOR4(dvp);
758 	vnode_t *vp = NULL;
759 	vnode_t *vpi = *vpp;
760 	bool_t needrecov = FALSE;
761 
762 	int doqueue = 1;
763 
764 	COMPOUND4args_clnt args;
765 	COMPOUND4res_clnt res;
766 	nfs_argop4 *argop;
767 	nfs_resop4 *resop;
768 	int argoplist_size;
769 	int idx_open, idx_fattr;
770 
771 	GETFH4res *gf_res = NULL;
772 	OPEN4res *op_res = NULL;
773 	nfs4_ga_res_t *garp;
774 	fattr4 *attr = NULL;
775 	struct nfs4_excl_time verf;
776 	bool_t did_excl_setup = FALSE;
777 	int created_osp;
778 
779 	OPEN4cargs *open_args;
780 	nfs4_open_owner_t	*oop = NULL;
781 	nfs4_open_stream_t	*osp = NULL;
782 	seqid4 seqid = 0;
783 	bool_t retry_open = FALSE;
784 	nfs4_recov_state_t recov_state;
785 	nfs4_lost_rqst_t lost_rqst;
786 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
787 	hrtime_t t;
788 	int acc = 0;
789 	cred_t *cred_otw = NULL;	/* cred used to do the RPC call */
790 	cred_t *ncr = NULL;
791 
792 	nfs4_sharedfh_t *otw_sfh;
793 	nfs4_sharedfh_t *orig_sfh;
794 	int fh_differs = 0;
795 	int numops, setgid_flag;
796 	int num_bseqid_retry = NFS4_NUM_RETRY_BAD_SEQID + 1;
797 
798 	/*
799 	 * Make sure we properly deal with setting the right gid on
800 	 * a newly created file to reflect the parent's setgid bit
801 	 */
802 	setgid_flag = 0;
803 	if (create_flag && in_va) {
804 
805 		/*
806 		 * If the parent's directory has the setgid bit set
807 		 * _and_ the client was able to get a valid mapping
808 		 * for the parent dir's owner_group, we want to
809 		 * append NVERIFY(owner_group == dva.va_gid) and
810 		 * SETATTR to the CREATE compound.
811 		 */
812 		mutex_enter(&drp->r_statelock);
813 		if (drp->r_attr.va_mode & VSGID &&
814 		    drp->r_attr.va_gid != GID_NOBODY) {
815 			in_va->va_gid = drp->r_attr.va_gid;
816 			setgid_flag = 1;
817 		}
818 		mutex_exit(&drp->r_statelock);
819 	}
820 
821 	/*
822 	 * Normal/non-create compound:
823 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new)
824 	 *
825 	 * Open(create) compound no setgid:
826 	 * PUTFH(dfh) + SAVEFH + OPEN(create) + GETFH + GETATTR(new) +
827 	 * RESTOREFH + GETATTR
828 	 *
829 	 * Open(create) setgid:
830 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new) +
831 	 * SAVEFH + PUTFH(dfh) + GETATTR(dvp) + RESTOREFH +
832 	 * NVERIFY(grp) + SETATTR
833 	 */
834 	if (setgid_flag) {
835 		numops = 10;
836 		idx_open = 1;
837 		idx_fattr = 3;
838 	} else if (create_flag) {
839 		numops = 7;
840 		idx_open = 2;
841 		idx_fattr = 4;
842 	} else {
843 		numops = 4;
844 		idx_open = 1;
845 		idx_fattr = 3;
846 	}
847 
848 	args.array_len = numops;
849 	argoplist_size = numops * sizeof (nfs_argop4);
850 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
851 
852 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw: "
853 	    "open %s open flag 0x%x cred %p", file_name, open_flag,
854 	    (void *)cr));
855 
856 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
857 	if (create_flag) {
858 		/*
859 		 * We are to create a file.  Initialize the passed in vnode
860 		 * pointer.
861 		 */
862 		vpi = NULL;
863 	} else {
864 		/*
865 		 * Check to see if the client owns a read delegation and is
866 		 * trying to open for write.  If so, then return the delegation
867 		 * to avoid the server doing a cb_recall and returning DELAY.
868 		 * NB - we don't use the statev4_lock here because we'd have
869 		 * to drop the lock anyway and the result would be stale.
870 		 */
871 		if ((open_flag & FWRITE) &&
872 		    VTOR4(vpi)->r_deleg_type == OPEN_DELEGATE_READ)
873 			(void) nfs4delegreturn(VTOR4(vpi), NFS4_DR_REOPEN);
874 
875 		/*
876 		 * If the file has a delegation, then do an access check up
877 		 * front.  This avoids having to an access check later after
878 		 * we've already done start_op, which could deadlock.
879 		 */
880 		if (VTOR4(vpi)->r_deleg_type != OPEN_DELEGATE_NONE) {
881 			if (open_flag & FREAD &&
882 			    nfs4_access(vpi, VREAD, 0, cr, NULL) == 0)
883 				acc |= VREAD;
884 			if (open_flag & FWRITE &&
885 			    nfs4_access(vpi, VWRITE, 0, cr, NULL) == 0)
886 				acc |= VWRITE;
887 		}
888 	}
889 
890 	drp = VTOR4(dvp);
891 
892 	recov_state.rs_flags = 0;
893 	recov_state.rs_num_retry_despite_err = 0;
894 	cred_otw = cr;
895 
896 recov_retry:
897 	fh_differs = 0;
898 	nfs4_error_zinit(&e);
899 
900 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, vpi, &recov_state);
901 	if (e.error) {
902 		if (ncr != NULL)
903 			crfree(ncr);
904 		kmem_free(argop, argoplist_size);
905 		return (e.error);
906 	}
907 
908 	args.ctag = TAG_OPEN;
909 	args.array_len = numops;
910 	args.array = argop;
911 
912 	/* putfh directory fh */
913 	argop[0].argop = OP_CPUTFH;
914 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
915 
916 	/* OPEN: either op 1 or op 2 depending upon create/setgid flags */
917 	argop[idx_open].argop = OP_COPEN;
918 	open_args = &argop[idx_open].nfs_argop4_u.opcopen;
919 	open_args->claim = CLAIM_NULL;
920 
921 	/* name of file */
922 	open_args->open_claim4_u.cfile = file_name;
923 	open_args->owner.owner_len = 0;
924 	open_args->owner.owner_val = NULL;
925 
926 	if (create_flag) {
927 		/* CREATE a file */
928 		open_args->opentype = OPEN4_CREATE;
929 		open_args->mode = createmode;
930 		if (createmode == EXCLUSIVE4) {
931 			if (did_excl_setup == FALSE) {
932 				verf.seconds = nfs_atoi(hw_serial);
933 				if (verf.seconds != 0)
934 					verf.nseconds = newnum();
935 				else {
936 					timestruc_t now;
937 
938 					gethrestime(&now);
939 					verf.seconds = now.tv_sec;
940 					verf.nseconds = now.tv_nsec;
941 				}
942 				/*
943 				 * Since the server will use this value for the
944 				 * mtime, make sure that it can't overflow. Zero
945 				 * out the MSB. The actual value does not matter
946 				 * here, only its uniqeness.
947 				 */
948 				verf.seconds &= INT32_MAX;
949 				did_excl_setup = TRUE;
950 			}
951 
952 			/* Now copy over verifier to OPEN4args. */
953 			open_args->createhow4_u.createverf = *(uint64_t *)&verf;
954 		} else {
955 			int v_error;
956 			bitmap4 supp_attrs;
957 			servinfo4_t *svp;
958 
959 			attr = &open_args->createhow4_u.createattrs;
960 
961 			svp = drp->r_server;
962 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
963 			supp_attrs = svp->sv_supp_attrs;
964 			nfs_rw_exit(&svp->sv_lock);
965 
966 			/* GUARDED4 or UNCHECKED4 */
967 			v_error = vattr_to_fattr4(in_va, NULL, attr, 0, OP_OPEN,
968 			    supp_attrs);
969 			if (v_error) {
970 				bzero(attr, sizeof (*attr));
971 				nfs4args_copen_free(open_args);
972 				nfs4_end_op(VTOMI4(dvp), dvp, vpi,
973 				    &recov_state, FALSE);
974 				if (ncr != NULL)
975 					crfree(ncr);
976 				kmem_free(argop, argoplist_size);
977 				return (v_error);
978 			}
979 		}
980 	} else {
981 		/* NO CREATE */
982 		open_args->opentype = OPEN4_NOCREATE;
983 	}
984 
985 	if (recov_state.rs_sp != NULL) {
986 		mutex_enter(&recov_state.rs_sp->s_lock);
987 		open_args->owner.clientid = recov_state.rs_sp->clientid;
988 		mutex_exit(&recov_state.rs_sp->s_lock);
989 	} else {
990 		/* XXX should we just fail here? */
991 		open_args->owner.clientid = 0;
992 	}
993 
994 	/*
995 	 * This increments oop's ref count or creates a temporary 'just_created'
996 	 * open owner that will become valid when this OPEN/OPEN_CONFIRM call
997 	 * completes.
998 	 */
999 	mutex_enter(&VTOMI4(dvp)->mi_lock);
1000 
1001 	/* See if a permanent or just created open owner exists */
1002 	oop = find_open_owner_nolock(cr, NFS4_JUST_CREATED, VTOMI4(dvp));
1003 	if (!oop) {
1004 		/*
1005 		 * This open owner does not exist so create a temporary
1006 		 * just created one.
1007 		 */
1008 		oop = create_open_owner(cr, VTOMI4(dvp));
1009 		ASSERT(oop != NULL);
1010 	}
1011 	mutex_exit(&VTOMI4(dvp)->mi_lock);
1012 
1013 	/* this length never changes, do alloc before seqid sync */
1014 	open_args->owner.owner_len = sizeof (oop->oo_name);
1015 	open_args->owner.owner_val =
1016 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1017 
1018 	e.error = nfs4_start_open_seqid_sync(oop, VTOMI4(dvp));
1019 	if (e.error == EAGAIN) {
1020 		open_owner_rele(oop);
1021 		nfs4args_copen_free(open_args);
1022 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1023 		if (ncr != NULL) {
1024 			crfree(ncr);
1025 			ncr = NULL;
1026 		}
1027 		goto recov_retry;
1028 	}
1029 
1030 	/* Check to see if we need to do the OTW call */
1031 	if (!create_flag) {
1032 		if (!nfs4_is_otw_open_necessary(oop, open_flag, vpi,
1033 		    file_just_been_created, &e.error, acc, &recov_state)) {
1034 
1035 			/*
1036 			 * The OTW open is not necessary.  Either
1037 			 * the open can succeed without it (eg.
1038 			 * delegation, error == 0) or the open
1039 			 * must fail due to an access failure
1040 			 * (error != 0).  In either case, tidy
1041 			 * up and return.
1042 			 */
1043 
1044 			nfs4_end_open_seqid_sync(oop);
1045 			open_owner_rele(oop);
1046 			nfs4args_copen_free(open_args);
1047 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, FALSE);
1048 			if (ncr != NULL)
1049 				crfree(ncr);
1050 			kmem_free(argop, argoplist_size);
1051 			return (e.error);
1052 		}
1053 	}
1054 
1055 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1056 	    open_args->owner.owner_len);
1057 
1058 	seqid = nfs4_get_open_seqid(oop) + 1;
1059 	open_args->seqid = seqid;
1060 	open_args->share_access = 0;
1061 	if (open_flag & FREAD)
1062 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1063 	if (open_flag & FWRITE)
1064 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1065 	open_args->share_deny = OPEN4_SHARE_DENY_NONE;
1066 
1067 
1068 
1069 	/*
1070 	 * getfh w/sanity check for idx_open/idx_fattr
1071 	 */
1072 	ASSERT((idx_open + 1) == (idx_fattr - 1));
1073 	argop[idx_open + 1].argop = OP_GETFH;
1074 
1075 	/* getattr */
1076 	argop[idx_fattr].argop = OP_GETATTR;
1077 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1078 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1079 
1080 	if (setgid_flag) {
1081 		vattr_t	_v;
1082 		servinfo4_t *svp;
1083 		bitmap4	supp_attrs;
1084 
1085 		svp = drp->r_server;
1086 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1087 		supp_attrs = svp->sv_supp_attrs;
1088 		nfs_rw_exit(&svp->sv_lock);
1089 
1090 		/*
1091 		 * For setgid case, we need to:
1092 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1093 		 */
1094 		argop[4].argop = OP_SAVEFH;
1095 
1096 		argop[5].argop = OP_CPUTFH;
1097 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
1098 
1099 		argop[6].argop = OP_GETATTR;
1100 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1101 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1102 
1103 		argop[7].argop = OP_RESTOREFH;
1104 
1105 		/*
1106 		 * nverify
1107 		 */
1108 		_v.va_mask = AT_GID;
1109 		_v.va_gid = in_va->va_gid;
1110 		if (!(e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
1111 		    supp_attrs))) {
1112 
1113 			/*
1114 			 * setattr
1115 			 *
1116 			 * We _know_ we're not messing with AT_SIZE or
1117 			 * AT_XTIME, so no need for stateid or flags.
1118 			 * Also we specify NULL rp since we're only
1119 			 * interested in setting owner_group attributes.
1120 			 */
1121 			nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr,
1122 			    supp_attrs, &e.error, 0);
1123 			if (e.error)
1124 				nfs4args_verify_free(&argop[8]);
1125 		}
1126 
1127 		if (e.error) {
1128 			/*
1129 			 * XXX - Revisit the last argument to nfs4_end_op()
1130 			 *	 once 5020486 is fixed.
1131 			 */
1132 			nfs4_end_open_seqid_sync(oop);
1133 			open_owner_rele(oop);
1134 			nfs4args_copen_free(open_args);
1135 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1136 			if (ncr != NULL)
1137 				crfree(ncr);
1138 			kmem_free(argop, argoplist_size);
1139 			return (e.error);
1140 		}
1141 	} else if (create_flag) {
1142 		/*
1143 		 * For setgid case, we need to:
1144 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1145 		 */
1146 		argop[1].argop = OP_SAVEFH;
1147 
1148 		argop[5].argop = OP_RESTOREFH;
1149 
1150 		argop[6].argop = OP_GETATTR;
1151 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1152 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1153 	}
1154 
1155 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1156 	    "nfs4open_otw: %s call, nm %s, rp %s",
1157 	    needrecov ? "recov" : "first", file_name,
1158 	    rnode4info(VTOR4(dvp))));
1159 
1160 	t = gethrtime();
1161 
1162 	rfs4call(VTOMI4(dvp), &args, &res, cred_otw, &doqueue, 0, &e);
1163 
1164 	if (!e.error && nfs4_need_to_bump_seqid(&res))
1165 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1166 
1167 	needrecov = nfs4_needs_recovery(&e, TRUE, dvp->v_vfsp);
1168 
1169 	if (e.error || needrecov) {
1170 		bool_t abort = FALSE;
1171 
1172 		if (needrecov) {
1173 			nfs4_bseqid_entry_t *bsep = NULL;
1174 
1175 			nfs4open_save_lost_rqst(e.error, &lost_rqst, oop,
1176 			    cred_otw, vpi, dvp, open_args);
1177 
1178 			if (!e.error && res.status == NFS4ERR_BAD_SEQID) {
1179 				bsep = nfs4_create_bseqid_entry(oop, NULL,
1180 				    vpi, 0, args.ctag, open_args->seqid);
1181 				num_bseqid_retry--;
1182 			}
1183 
1184 			abort = nfs4_start_recovery(&e, VTOMI4(dvp), dvp, vpi,
1185 			    NULL, lost_rqst.lr_op == OP_OPEN ?
1186 			    &lost_rqst : NULL, OP_OPEN, bsep);
1187 
1188 			if (bsep)
1189 				kmem_free(bsep, sizeof (*bsep));
1190 			/* give up if we keep getting BAD_SEQID */
1191 			if (num_bseqid_retry == 0)
1192 				abort = TRUE;
1193 			if (abort == TRUE && e.error == 0)
1194 				e.error = geterrno4(res.status);
1195 		}
1196 		nfs4_end_open_seqid_sync(oop);
1197 		open_owner_rele(oop);
1198 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1199 		nfs4args_copen_free(open_args);
1200 		if (setgid_flag) {
1201 			nfs4args_verify_free(&argop[8]);
1202 			nfs4args_setattr_free(&argop[9]);
1203 		}
1204 		if (!e.error)
1205 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1206 		if (ncr != NULL) {
1207 			crfree(ncr);
1208 			ncr = NULL;
1209 		}
1210 		if (!needrecov || abort == TRUE || e.error == EINTR ||
1211 		    NFS4_FRC_UNMT_ERR(e.error, dvp->v_vfsp)) {
1212 			kmem_free(argop, argoplist_size);
1213 			return (e.error);
1214 		}
1215 		goto recov_retry;
1216 	}
1217 
1218 	/*
1219 	 * Will check and update lease after checking the rflag for
1220 	 * OPEN_CONFIRM in the successful OPEN call.
1221 	 */
1222 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
1223 
1224 		/*
1225 		 * XXX what if we're crossing mount points from server1:/drp
1226 		 * to server2:/drp/rp.
1227 		 */
1228 
1229 		/* Signal our end of use of the open seqid */
1230 		nfs4_end_open_seqid_sync(oop);
1231 
1232 		/*
1233 		 * This will destroy the open owner if it was just created,
1234 		 * and no one else has put a reference on it.
1235 		 */
1236 		open_owner_rele(oop);
1237 		if (create_flag && (createmode != EXCLUSIVE4) &&
1238 		    res.status == NFS4ERR_BADOWNER)
1239 			nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1240 
1241 		e.error = geterrno4(res.status);
1242 		nfs4args_copen_free(open_args);
1243 		if (setgid_flag) {
1244 			nfs4args_verify_free(&argop[8]);
1245 			nfs4args_setattr_free(&argop[9]);
1246 		}
1247 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1248 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1249 		/*
1250 		 * If the reply is NFS4ERR_ACCESS, it may be because
1251 		 * we are root (no root net access).  If the real uid
1252 		 * is not root, then retry with the real uid instead.
1253 		 */
1254 		if (ncr != NULL) {
1255 			crfree(ncr);
1256 			ncr = NULL;
1257 		}
1258 		if (res.status == NFS4ERR_ACCESS &&
1259 		    (ncr = crnetadjust(cred_otw)) != NULL) {
1260 			cred_otw = ncr;
1261 			goto recov_retry;
1262 		}
1263 		kmem_free(argop, argoplist_size);
1264 		return (e.error);
1265 	}
1266 
1267 	resop = &res.array[idx_open];  /* open res */
1268 	op_res = &resop->nfs_resop4_u.opopen;
1269 
1270 #ifdef DEBUG
1271 	/*
1272 	 * verify attrset bitmap
1273 	 */
1274 	if (create_flag &&
1275 	    (createmode == UNCHECKED4 || createmode == GUARDED4)) {
1276 		/* make sure attrset returned is what we asked for */
1277 		/* XXX Ignore this 'error' for now */
1278 		if (attr->attrmask != op_res->attrset)
1279 			/* EMPTY */;
1280 	}
1281 #endif
1282 
1283 	if (op_res->rflags & OPEN4_RESULT_LOCKTYPE_POSIX) {
1284 		mutex_enter(&VTOMI4(dvp)->mi_lock);
1285 		VTOMI4(dvp)->mi_flags |= MI4_POSIX_LOCK;
1286 		mutex_exit(&VTOMI4(dvp)->mi_lock);
1287 	}
1288 
1289 	resop = &res.array[idx_open + 1];  /* getfh res */
1290 	gf_res = &resop->nfs_resop4_u.opgetfh;
1291 
1292 	otw_sfh = sfh4_get(&gf_res->object, VTOMI4(dvp));
1293 
1294 	/*
1295 	 * The open stateid has been updated on the server but not
1296 	 * on the client yet.  There is a path: makenfs4node->nfs4_attr_cache->
1297 	 * flush_pages->VOP_PUTPAGE->...->nfs4write where we will issue an OTW
1298 	 * WRITE call.  That, however, will use the old stateid, so go ahead
1299 	 * and upate the open stateid now, before any call to makenfs4node.
1300 	 */
1301 	if (vpi) {
1302 		nfs4_open_stream_t	*tmp_osp;
1303 		rnode4_t		*tmp_rp = VTOR4(vpi);
1304 
1305 		tmp_osp = find_open_stream(oop, tmp_rp);
1306 		if (tmp_osp) {
1307 			tmp_osp->open_stateid = op_res->stateid;
1308 			mutex_exit(&tmp_osp->os_sync_lock);
1309 			open_stream_rele(tmp_osp, tmp_rp);
1310 		}
1311 
1312 		/*
1313 		 * We must determine if the file handle given by the otw open
1314 		 * is the same as the file handle which was passed in with
1315 		 * *vpp.  This case can be reached if the file we are trying
1316 		 * to open has been removed and another file has been created
1317 		 * having the same file name.  The passed in vnode is released
1318 		 * later.
1319 		 */
1320 		orig_sfh = VTOR4(vpi)->r_fh;
1321 		fh_differs = nfs4cmpfh(&orig_sfh->sfh_fh, &otw_sfh->sfh_fh);
1322 	}
1323 
1324 	garp = &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res;
1325 
1326 	if (create_flag || fh_differs) {
1327 		int rnode_err = 0;
1328 
1329 		vp = makenfs4node(otw_sfh, garp, dvp->v_vfsp, t, cr,
1330 		    dvp, fn_get(VTOSV(dvp)->sv_name, file_name));
1331 
1332 		if (e.error)
1333 			PURGE_ATTRCACHE4(vp);
1334 		/*
1335 		 * For the newly created vp case, make sure the rnode
1336 		 * isn't bad before using it.
1337 		 */
1338 		mutex_enter(&(VTOR4(vp))->r_statelock);
1339 		if (VTOR4(vp)->r_flags & R4RECOVERR)
1340 			rnode_err = EIO;
1341 		mutex_exit(&(VTOR4(vp))->r_statelock);
1342 
1343 		if (rnode_err) {
1344 			nfs4_end_open_seqid_sync(oop);
1345 			nfs4args_copen_free(open_args);
1346 			if (setgid_flag) {
1347 				nfs4args_verify_free(&argop[8]);
1348 				nfs4args_setattr_free(&argop[9]);
1349 			}
1350 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1351 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1352 			    needrecov);
1353 			open_owner_rele(oop);
1354 			VN_RELE(vp);
1355 			if (ncr != NULL)
1356 				crfree(ncr);
1357 			sfh4_rele(&otw_sfh);
1358 			kmem_free(argop, argoplist_size);
1359 			return (EIO);
1360 		}
1361 	} else {
1362 		vp = vpi;
1363 	}
1364 	sfh4_rele(&otw_sfh);
1365 
1366 	/*
1367 	 * It seems odd to get a full set of attrs and then not update
1368 	 * the object's attrcache in the non-create case.  Create case uses
1369 	 * the attrs since makenfs4node checks to see if the attrs need to
1370 	 * be updated (and then updates them).  The non-create case should
1371 	 * update attrs also.
1372 	 */
1373 	if (! create_flag && ! fh_differs && !e.error) {
1374 		nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
1375 	}
1376 
1377 	nfs4_error_zinit(&e);
1378 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
1379 		/* This does not do recovery for vp explicitly. */
1380 		nfs4open_confirm(vp, &seqid, &op_res->stateid, cred_otw, FALSE,
1381 		    &retry_open, oop, FALSE, &e, &num_bseqid_retry);
1382 
1383 		if (e.error || e.stat) {
1384 			nfs4_end_open_seqid_sync(oop);
1385 			nfs4args_copen_free(open_args);
1386 			if (setgid_flag) {
1387 				nfs4args_verify_free(&argop[8]);
1388 				nfs4args_setattr_free(&argop[9]);
1389 			}
1390 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1391 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1392 			    needrecov);
1393 			open_owner_rele(oop);
1394 			if (create_flag || fh_differs) {
1395 				/* rele the makenfs4node */
1396 				VN_RELE(vp);
1397 			}
1398 			if (ncr != NULL) {
1399 				crfree(ncr);
1400 				ncr = NULL;
1401 			}
1402 			if (retry_open == TRUE) {
1403 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1404 				    "nfs4open_otw: retry the open since OPEN "
1405 				    "CONFIRM failed with error %d stat %d",
1406 				    e.error, e.stat));
1407 				if (create_flag && createmode == GUARDED4) {
1408 					NFS4_DEBUG(nfs4_client_recov_debug,
1409 					    (CE_NOTE, "nfs4open_otw: switch "
1410 					    "createmode from GUARDED4 to "
1411 					    "UNCHECKED4"));
1412 					createmode = UNCHECKED4;
1413 				}
1414 				goto recov_retry;
1415 			}
1416 			if (!e.error) {
1417 				if (create_flag && (createmode != EXCLUSIVE4) &&
1418 				    e.stat == NFS4ERR_BADOWNER)
1419 					nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1420 
1421 				e.error = geterrno4(e.stat);
1422 			}
1423 			kmem_free(argop, argoplist_size);
1424 			return (e.error);
1425 		}
1426 	}
1427 
1428 	rp = VTOR4(vp);
1429 
1430 	mutex_enter(&rp->r_statev4_lock);
1431 	if (create_flag)
1432 		rp->created_v4 = 1;
1433 	mutex_exit(&rp->r_statev4_lock);
1434 
1435 	mutex_enter(&oop->oo_lock);
1436 	/* Doesn't matter if 'oo_just_created' already was set as this */
1437 	oop->oo_just_created = NFS4_PERM_CREATED;
1438 	if (oop->oo_cred_otw)
1439 		crfree(oop->oo_cred_otw);
1440 	oop->oo_cred_otw = cred_otw;
1441 	crhold(oop->oo_cred_otw);
1442 	mutex_exit(&oop->oo_lock);
1443 
1444 	/* returns with 'os_sync_lock' held */
1445 	osp = find_or_create_open_stream(oop, rp, &created_osp);
1446 	if (!osp) {
1447 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1448 		    "nfs4open_otw: failed to create an open stream"));
1449 		NFS4_DEBUG(nfs4_seqid_sync, (CE_NOTE, "nfs4open_otw: "
1450 		    "signal our end of use of the open seqid"));
1451 
1452 		nfs4_end_open_seqid_sync(oop);
1453 		open_owner_rele(oop);
1454 		nfs4args_copen_free(open_args);
1455 		if (setgid_flag) {
1456 			nfs4args_verify_free(&argop[8]);
1457 			nfs4args_setattr_free(&argop[9]);
1458 		}
1459 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1460 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1461 		if (create_flag || fh_differs)
1462 			VN_RELE(vp);
1463 		if (ncr != NULL)
1464 			crfree(ncr);
1465 
1466 		kmem_free(argop, argoplist_size);
1467 		return (EINVAL);
1468 
1469 	}
1470 
1471 	osp->open_stateid = op_res->stateid;
1472 
1473 	if (open_flag & FREAD)
1474 		osp->os_share_acc_read++;
1475 	if (open_flag & FWRITE)
1476 		osp->os_share_acc_write++;
1477 	osp->os_share_deny_none++;
1478 
1479 	/*
1480 	 * Need to reset this bitfield for the possible case where we were
1481 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
1482 	 * we could retry the CLOSE, OPENed the file again.
1483 	 */
1484 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
1485 	osp->os_final_close = 0;
1486 	osp->os_force_close = 0;
1487 #ifdef DEBUG
1488 	if (osp->os_failed_reopen)
1489 		NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE, "nfs4open_otw:"
1490 		    " clearing os_failed_reopen for osp %p, cr %p, rp %s",
1491 		    (void *)osp, (void *)cr, rnode4info(rp)));
1492 #endif
1493 	osp->os_failed_reopen = 0;
1494 
1495 	mutex_exit(&osp->os_sync_lock);
1496 
1497 	nfs4_end_open_seqid_sync(oop);
1498 
1499 	if (created_osp && recov_state.rs_sp != NULL) {
1500 		mutex_enter(&recov_state.rs_sp->s_lock);
1501 		nfs4_inc_state_ref_count_nolock(recov_state.rs_sp, VTOMI4(dvp));
1502 		mutex_exit(&recov_state.rs_sp->s_lock);
1503 	}
1504 
1505 	/* get rid of our reference to find oop */
1506 	open_owner_rele(oop);
1507 
1508 	open_stream_rele(osp, rp);
1509 
1510 	/* accept delegation, if any */
1511 	nfs4_delegation_accept(rp, CLAIM_NULL, op_res, garp, cred_otw);
1512 
1513 	nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1514 
1515 	if (createmode == EXCLUSIVE4 &&
1516 	    (in_va->va_mask & ~(AT_GID | AT_SIZE))) {
1517 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw:"
1518 		    " EXCLUSIVE4: sending a SETATTR"));
1519 		/*
1520 		 * If doing an exclusive create, then generate
1521 		 * a SETATTR to set the initial attributes.
1522 		 * Try to set the mtime and the atime to the
1523 		 * server's current time.  It is somewhat
1524 		 * expected that these fields will be used to
1525 		 * store the exclusive create cookie.  If not,
1526 		 * server implementors will need to know that
1527 		 * a SETATTR will follow an exclusive create
1528 		 * and the cookie should be destroyed if
1529 		 * appropriate.
1530 		 *
1531 		 * The AT_GID and AT_SIZE bits are turned off
1532 		 * so that the SETATTR request will not attempt
1533 		 * to process these.  The gid will be set
1534 		 * separately if appropriate.  The size is turned
1535 		 * off because it is assumed that a new file will
1536 		 * be created empty and if the file wasn't empty,
1537 		 * then the exclusive create will have failed
1538 		 * because the file must have existed already.
1539 		 * Therefore, no truncate operation is needed.
1540 		 */
1541 		in_va->va_mask &= ~(AT_GID | AT_SIZE);
1542 		in_va->va_mask |= (AT_MTIME | AT_ATIME);
1543 
1544 		e.error = nfs4setattr(vp, in_va, 0, cr, NULL);
1545 		if (e.error) {
1546 			/*
1547 			 * Couldn't correct the attributes of
1548 			 * the newly created file and the
1549 			 * attributes are wrong.  Remove the
1550 			 * file and return an error to the
1551 			 * application.
1552 			 */
1553 			/* XXX will this take care of client state ? */
1554 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1555 			    "nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1556 			    " remove file", e.error));
1557 			VN_RELE(vp);
1558 			(void) nfs4_remove(dvp, file_name, cr, NULL, 0);
1559 			/*
1560 			 * Since we've reled the vnode and removed
1561 			 * the file we now need to return the error.
1562 			 * At this point we don't want to update the
1563 			 * dircaches, call nfs4_waitfor_purge_complete
1564 			 * or set vpp to vp so we need to skip these
1565 			 * as well.
1566 			 */
1567 			goto skip_update_dircaches;
1568 		}
1569 	}
1570 
1571 	/*
1572 	 * If we created or found the correct vnode, due to create_flag or
1573 	 * fh_differs being set, then update directory cache attribute, readdir
1574 	 * and dnlc caches.
1575 	 */
1576 	if (create_flag || fh_differs) {
1577 		dirattr_info_t dinfo, *dinfop;
1578 
1579 		/*
1580 		 * Make sure getattr succeeded before using results.
1581 		 * note: op 7 is getattr(dir) for both flavors of
1582 		 * open(create).
1583 		 */
1584 		if (create_flag && res.status == NFS4_OK) {
1585 			dinfo.di_time_call = t;
1586 			dinfo.di_cred = cr;
1587 			dinfo.di_garp =
1588 			    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
1589 			dinfop = &dinfo;
1590 		} else {
1591 			dinfop = NULL;
1592 		}
1593 
1594 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1595 		    dinfop);
1596 	}
1597 
1598 	/*
1599 	 * If the page cache for this file was flushed from actions
1600 	 * above, it was done asynchronously and if that is true,
1601 	 * there is a need to wait here for it to complete.  This must
1602 	 * be done outside of start_fop/end_fop.
1603 	 */
1604 	(void) nfs4_waitfor_purge_complete(vp);
1605 
1606 	/*
1607 	 * It is implicit that we are in the open case (create_flag == 0) since
1608 	 * fh_differs can only be set to a non-zero value in the open case.
1609 	 */
1610 	if (fh_differs != 0 && vpi != NULL)
1611 		VN_RELE(vpi);
1612 
1613 	/*
1614 	 * Be sure to set *vpp to the correct value before returning.
1615 	 */
1616 	*vpp = vp;
1617 
1618 skip_update_dircaches:
1619 
1620 	nfs4args_copen_free(open_args);
1621 	if (setgid_flag) {
1622 		nfs4args_verify_free(&argop[8]);
1623 		nfs4args_setattr_free(&argop[9]);
1624 	}
1625 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1626 
1627 	if (ncr)
1628 		crfree(ncr);
1629 	kmem_free(argop, argoplist_size);
1630 	return (e.error);
1631 }
1632 
1633 /*
1634  * Reopen an open instance.  cf. nfs4open_otw().
1635  *
1636  * Errors are returned by the nfs4_error_t parameter.
1637  * - ep->error contains an errno value or zero.
1638  * - if it is zero, ep->stat is set to an NFS status code, if any.
1639  *   If the file could not be reopened, but the caller should continue, the
1640  *   file is marked dead and no error values are returned.  If the caller
1641  *   should stop recovering open files and start over, either the ep->error
1642  *   value or ep->stat will indicate an error (either something that requires
1643  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1644  *   filehandles) may be handled silently by this routine.
1645  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1646  *   will be started, so the caller should not do it.
1647  *
1648  * Gotos:
1649  * - kill_file : reopen failed in such a fashion to constitute marking the
1650  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1651  *   is for cases where recovery is not possible.
1652  * - failed_reopen : same as above, except that the file has already been
1653  *   marked dead, so no need to do it again.
1654  * - bailout : reopen failed but we are able to recover and retry the reopen -
1655  *   either within this function immediately or via the calling function.
1656  */
1657 
1658 void
1659 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1660     open_claim_type4 claim, bool_t frc_use_claim_previous,
1661     bool_t is_recov)
1662 {
1663 	COMPOUND4args_clnt args;
1664 	COMPOUND4res_clnt res;
1665 	nfs_argop4 argop[4];
1666 	nfs_resop4 *resop;
1667 	OPEN4res *op_res = NULL;
1668 	OPEN4cargs *open_args;
1669 	GETFH4res *gf_res;
1670 	rnode4_t *rp = VTOR4(vp);
1671 	int doqueue = 1;
1672 	cred_t *cr = NULL, *cred_otw = NULL;
1673 	nfs4_open_owner_t *oop = NULL;
1674 	seqid4 seqid;
1675 	nfs4_ga_res_t *garp;
1676 	char fn[MAXNAMELEN];
1677 	nfs4_recov_state_t recov = {NULL, 0};
1678 	nfs4_lost_rqst_t lost_rqst;
1679 	mntinfo4_t *mi = VTOMI4(vp);
1680 	bool_t abort;
1681 	char *failed_msg = "";
1682 	int fh_different;
1683 	hrtime_t t;
1684 	nfs4_bseqid_entry_t *bsep = NULL;
1685 
1686 	ASSERT(nfs4_consistent_type(vp));
1687 	ASSERT(nfs_zone() == mi->mi_zone);
1688 
1689 	nfs4_error_zinit(ep);
1690 
1691 	/* this is the cred used to find the open owner */
1692 	cr = state_to_cred(osp);
1693 	if (cr == NULL) {
1694 		failed_msg = "Couldn't reopen: no cred";
1695 		goto kill_file;
1696 	}
1697 	/* use this cred for OTW operations */
1698 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1699 
1700 top:
1701 	nfs4_error_zinit(ep);
1702 
1703 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1704 		/* File system has been unmounted, quit */
1705 		ep->error = EIO;
1706 		failed_msg = "Couldn't reopen: file system has been unmounted";
1707 		goto kill_file;
1708 	}
1709 
1710 	oop = osp->os_open_owner;
1711 
1712 	ASSERT(oop != NULL);
1713 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1714 		failed_msg = "can't reopen: no open owner";
1715 		goto kill_file;
1716 	}
1717 	open_owner_hold(oop);
1718 
1719 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1720 	if (ep->error) {
1721 		open_owner_rele(oop);
1722 		oop = NULL;
1723 		goto bailout;
1724 	}
1725 
1726 	/*
1727 	 * If the rnode has a delegation and the delegation has been
1728 	 * recovered and the server didn't request a recall and the caller
1729 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1730 	 * recovery) and the rnode hasn't been marked dead, then install
1731 	 * the delegation stateid in the open stream.  Otherwise, proceed
1732 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1733 	 */
1734 	mutex_enter(&rp->r_statev4_lock);
1735 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1736 	    !rp->r_deleg_return_pending &&
1737 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1738 	    !rp->r_deleg_needs_recall &&
1739 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1740 	    !(rp->r_flags & R4RECOVERR)) {
1741 		mutex_enter(&osp->os_sync_lock);
1742 		osp->os_delegation = 1;
1743 		osp->open_stateid = rp->r_deleg_stateid;
1744 		mutex_exit(&osp->os_sync_lock);
1745 		mutex_exit(&rp->r_statev4_lock);
1746 		goto bailout;
1747 	}
1748 	mutex_exit(&rp->r_statev4_lock);
1749 
1750 	/*
1751 	 * If the file failed recovery, just quit.  This failure need not
1752 	 * affect other reopens, so don't return an error.
1753 	 */
1754 	mutex_enter(&rp->r_statelock);
1755 	if (rp->r_flags & R4RECOVERR) {
1756 		mutex_exit(&rp->r_statelock);
1757 		ep->error = 0;
1758 		goto failed_reopen;
1759 	}
1760 	mutex_exit(&rp->r_statelock);
1761 
1762 	/*
1763 	 * argop is empty here
1764 	 *
1765 	 * PUTFH, OPEN, GETATTR
1766 	 */
1767 	args.ctag = TAG_REOPEN;
1768 	args.array_len = 4;
1769 	args.array = argop;
1770 
1771 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1772 	    "nfs4_reopen: file is type %d, id %s",
1773 	    vp->v_type, rnode4info(VTOR4(vp))));
1774 
1775 	argop[0].argop = OP_CPUTFH;
1776 
1777 	if (claim != CLAIM_PREVIOUS) {
1778 		/*
1779 		 * if this is a file mount then
1780 		 * use the mntinfo parentfh
1781 		 */
1782 		argop[0].nfs_argop4_u.opcputfh.sfh =
1783 		    (vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1784 		    VTOSV(vp)->sv_dfh;
1785 	} else {
1786 		/* putfh fh to reopen */
1787 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1788 	}
1789 
1790 	argop[1].argop = OP_COPEN;
1791 	open_args = &argop[1].nfs_argop4_u.opcopen;
1792 	open_args->claim = claim;
1793 
1794 	if (claim == CLAIM_NULL) {
1795 
1796 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1797 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1798 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1799 			    (void *)vp);
1800 			failed_msg = "Couldn't reopen: vtoname failed for "
1801 			    "CLAIM_NULL";
1802 			/* nothing allocated yet */
1803 			goto kill_file;
1804 		}
1805 
1806 		open_args->open_claim4_u.cfile = fn;
1807 	} else if (claim == CLAIM_PREVIOUS) {
1808 
1809 		/*
1810 		 * We have two cases to deal with here:
1811 		 * 1) We're being called to reopen files in order to satisfy
1812 		 *    a lock operation request which requires us to explicitly
1813 		 *    reopen files which were opened under a delegation.  If
1814 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1815 		 *    that case, frc_use_claim_previous is TRUE and we must
1816 		 *    use the rnode's current delegation type (r_deleg_type).
1817 		 * 2) We're reopening files during some form of recovery.
1818 		 *    In this case, frc_use_claim_previous is FALSE and we
1819 		 *    use the delegation type appropriate for recovery
1820 		 *    (r_deleg_needs_recovery).
1821 		 */
1822 		mutex_enter(&rp->r_statev4_lock);
1823 		open_args->open_claim4_u.delegate_type =
1824 		    frc_use_claim_previous ?
1825 		    rp->r_deleg_type :
1826 		    rp->r_deleg_needs_recovery;
1827 		mutex_exit(&rp->r_statev4_lock);
1828 
1829 	} else if (claim == CLAIM_DELEGATE_CUR) {
1830 
1831 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1832 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1833 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1834 			    "with %m", (void *)vp);
1835 			failed_msg = "Couldn't reopen: vtoname failed for "
1836 			    "CLAIM_DELEGATE_CUR";
1837 			/* nothing allocated yet */
1838 			goto kill_file;
1839 		}
1840 
1841 		mutex_enter(&rp->r_statev4_lock);
1842 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1843 		    rp->r_deleg_stateid;
1844 		mutex_exit(&rp->r_statev4_lock);
1845 
1846 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1847 	}
1848 	open_args->opentype = OPEN4_NOCREATE;
1849 	open_args->owner.clientid = mi2clientid(mi);
1850 	open_args->owner.owner_len = sizeof (oop->oo_name);
1851 	open_args->owner.owner_val =
1852 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1853 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1854 	    open_args->owner.owner_len);
1855 	open_args->share_access = 0;
1856 	open_args->share_deny = 0;
1857 
1858 	mutex_enter(&osp->os_sync_lock);
1859 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1860 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1861 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1862 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1863 	    osp->os_share_acc_write, osp->os_open_ref_count,
1864 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1865 
1866 	if (osp->os_share_acc_read || osp->os_mmap_read)
1867 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1868 	if (osp->os_share_acc_write || osp->os_mmap_write)
1869 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1870 	if (osp->os_share_deny_read)
1871 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1872 	if (osp->os_share_deny_write)
1873 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1874 	mutex_exit(&osp->os_sync_lock);
1875 
1876 	seqid = nfs4_get_open_seqid(oop) + 1;
1877 	open_args->seqid = seqid;
1878 
1879 	/* Construct the getfh part of the compound */
1880 	argop[2].argop = OP_GETFH;
1881 
1882 	/* Construct the getattr part of the compound */
1883 	argop[3].argop = OP_GETATTR;
1884 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1885 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1886 
1887 	t = gethrtime();
1888 
1889 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1890 
1891 	if (ep->error) {
1892 		if (!is_recov && !frc_use_claim_previous &&
1893 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1894 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1895 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1896 			    cred_otw, vp, NULL, open_args);
1897 			abort = nfs4_start_recovery(ep,
1898 			    VTOMI4(vp), vp, NULL, NULL,
1899 			    lost_rqst.lr_op == OP_OPEN ?
1900 			    &lost_rqst : NULL, OP_OPEN, NULL);
1901 			nfs4args_copen_free(open_args);
1902 			goto bailout;
1903 		}
1904 
1905 		nfs4args_copen_free(open_args);
1906 
1907 		if (ep->error == EACCES && cred_otw != cr) {
1908 			crfree(cred_otw);
1909 			cred_otw = cr;
1910 			crhold(cred_otw);
1911 			nfs4_end_open_seqid_sync(oop);
1912 			open_owner_rele(oop);
1913 			oop = NULL;
1914 			goto top;
1915 		}
1916 		if (ep->error == ETIMEDOUT)
1917 			goto bailout;
1918 		failed_msg = "Couldn't reopen: rpc error";
1919 		goto kill_file;
1920 	}
1921 
1922 	if (nfs4_need_to_bump_seqid(&res))
1923 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1924 
1925 	switch (res.status) {
1926 	case NFS4_OK:
1927 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1928 			mutex_enter(&rp->r_statelock);
1929 			rp->r_delay_interval = 0;
1930 			mutex_exit(&rp->r_statelock);
1931 		}
1932 		break;
1933 	case NFS4ERR_BAD_SEQID:
1934 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1935 		    args.ctag, open_args->seqid);
1936 
1937 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1938 		    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1939 		    NULL, OP_OPEN, bsep);
1940 
1941 		nfs4args_copen_free(open_args);
1942 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1943 		nfs4_end_open_seqid_sync(oop);
1944 		open_owner_rele(oop);
1945 		oop = NULL;
1946 		kmem_free(bsep, sizeof (*bsep));
1947 
1948 		goto kill_file;
1949 	case NFS4ERR_NO_GRACE:
1950 		nfs4args_copen_free(open_args);
1951 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1952 		nfs4_end_open_seqid_sync(oop);
1953 		open_owner_rele(oop);
1954 		oop = NULL;
1955 		if (claim == CLAIM_PREVIOUS) {
1956 			/*
1957 			 * Retry as a plain open. We don't need to worry about
1958 			 * checking the changeinfo: it is acceptable for a
1959 			 * client to re-open a file and continue processing
1960 			 * (in the absence of locks).
1961 			 */
1962 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1963 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1964 			    "will retry as CLAIM_NULL"));
1965 			claim = CLAIM_NULL;
1966 			nfs4_mi_kstat_inc_no_grace(mi);
1967 			goto top;
1968 		}
1969 		failed_msg =
1970 		    "Couldn't reopen: tried reclaim outside grace period. ";
1971 		goto kill_file;
1972 	case NFS4ERR_GRACE:
1973 		nfs4_set_grace_wait(mi);
1974 		nfs4args_copen_free(open_args);
1975 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1976 		nfs4_end_open_seqid_sync(oop);
1977 		open_owner_rele(oop);
1978 		oop = NULL;
1979 		ep->error = nfs4_wait_for_grace(mi, &recov);
1980 		if (ep->error != 0)
1981 			goto bailout;
1982 		goto top;
1983 	case NFS4ERR_DELAY:
1984 		nfs4_set_delay_wait(vp);
1985 		nfs4args_copen_free(open_args);
1986 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1987 		nfs4_end_open_seqid_sync(oop);
1988 		open_owner_rele(oop);
1989 		oop = NULL;
1990 		ep->error = nfs4_wait_for_delay(vp, &recov);
1991 		nfs4_mi_kstat_inc_delay(mi);
1992 		if (ep->error != 0)
1993 			goto bailout;
1994 		goto top;
1995 	case NFS4ERR_FHEXPIRED:
1996 		/* recover filehandle and retry */
1997 		abort = nfs4_start_recovery(ep,
1998 		    mi, vp, NULL, NULL, NULL, OP_OPEN, NULL);
1999 		nfs4args_copen_free(open_args);
2000 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2001 		nfs4_end_open_seqid_sync(oop);
2002 		open_owner_rele(oop);
2003 		oop = NULL;
2004 		if (abort == FALSE)
2005 			goto top;
2006 		failed_msg = "Couldn't reopen: recovery aborted";
2007 		goto kill_file;
2008 	case NFS4ERR_RESOURCE:
2009 	case NFS4ERR_STALE_CLIENTID:
2010 	case NFS4ERR_WRONGSEC:
2011 	case NFS4ERR_EXPIRED:
2012 		/*
2013 		 * Do not mark the file dead and let the calling
2014 		 * function initiate recovery.
2015 		 */
2016 		nfs4args_copen_free(open_args);
2017 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2018 		nfs4_end_open_seqid_sync(oop);
2019 		open_owner_rele(oop);
2020 		oop = NULL;
2021 		goto bailout;
2022 	case NFS4ERR_ACCESS:
2023 		if (cred_otw != cr) {
2024 			crfree(cred_otw);
2025 			cred_otw = cr;
2026 			crhold(cred_otw);
2027 			nfs4args_copen_free(open_args);
2028 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2029 			nfs4_end_open_seqid_sync(oop);
2030 			open_owner_rele(oop);
2031 			oop = NULL;
2032 			goto top;
2033 		}
2034 		/* fall through */
2035 	default:
2036 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2037 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2038 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2039 		    rnode4info(VTOR4(vp))));
2040 		failed_msg = "Couldn't reopen: NFSv4 error";
2041 		nfs4args_copen_free(open_args);
2042 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2043 		goto kill_file;
2044 	}
2045 
2046 	resop = &res.array[1];  /* open res */
2047 	op_res = &resop->nfs_resop4_u.opopen;
2048 
2049 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2050 
2051 	/*
2052 	 * Check if the path we reopened really is the same
2053 	 * file. We could end up in a situation where the file
2054 	 * was removed and a new file created with the same name.
2055 	 */
2056 	resop = &res.array[2];
2057 	gf_res = &resop->nfs_resop4_u.opgetfh;
2058 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2059 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2060 	if (fh_different) {
2061 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2062 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2063 			/* Oops, we don't have the same file */
2064 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2065 				failed_msg = "Couldn't reopen: Persistent "
2066 				    "file handle changed";
2067 			else
2068 				failed_msg = "Couldn't reopen: Volatile "
2069 				    "(no expire on open) file handle changed";
2070 
2071 			nfs4args_copen_free(open_args);
2072 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2073 			nfs_rw_exit(&mi->mi_fh_lock);
2074 			goto kill_file;
2075 
2076 		} else {
2077 			/*
2078 			 * We have volatile file handles that don't compare.
2079 			 * If the fids are the same then we assume that the
2080 			 * file handle expired but the rnode still refers to
2081 			 * the same file object.
2082 			 *
2083 			 * First check that we have fids or not.
2084 			 * If we don't we have a dumb server so we will
2085 			 * just assume every thing is ok for now.
2086 			 */
2087 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2088 			    rp->r_attr.va_mask & AT_NODEID &&
2089 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2090 				/*
2091 				 * We have fids, but they don't
2092 				 * compare. So kill the file.
2093 				 */
2094 				failed_msg =
2095 				    "Couldn't reopen: file handle changed"
2096 				    " due to mismatched fids";
2097 				nfs4args_copen_free(open_args);
2098 				(void) xdr_free(xdr_COMPOUND4res_clnt,
2099 				    (caddr_t)&res);
2100 				nfs_rw_exit(&mi->mi_fh_lock);
2101 				goto kill_file;
2102 			} else {
2103 				/*
2104 				 * We have volatile file handles that refers
2105 				 * to the same file (at least they have the
2106 				 * same fid) or we don't have fids so we
2107 				 * can't tell. :(. We'll be a kind and accepting
2108 				 * client so we'll update the rnode's file
2109 				 * handle with the otw handle.
2110 				 *
2111 				 * We need to drop mi->mi_fh_lock since
2112 				 * sh4_update acquires it. Since there is
2113 				 * only one recovery thread there is no
2114 				 * race.
2115 				 */
2116 				nfs_rw_exit(&mi->mi_fh_lock);
2117 				sfh4_update(rp->r_fh, &gf_res->object);
2118 			}
2119 		}
2120 	} else {
2121 		nfs_rw_exit(&mi->mi_fh_lock);
2122 	}
2123 
2124 	ASSERT(nfs4_consistent_type(vp));
2125 
2126 	/*
2127 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2128 	 * over.  Presumably if there is a persistent error it will show up
2129 	 * when we resend the OPEN.
2130 	 */
2131 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2132 		bool_t retry_open = FALSE;
2133 
2134 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2135 		    cred_otw, is_recov, &retry_open,
2136 		    oop, FALSE, ep, NULL);
2137 		if (ep->error || ep->stat) {
2138 			nfs4args_copen_free(open_args);
2139 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2140 			nfs4_end_open_seqid_sync(oop);
2141 			open_owner_rele(oop);
2142 			oop = NULL;
2143 			goto top;
2144 		}
2145 	}
2146 
2147 	mutex_enter(&osp->os_sync_lock);
2148 	osp->open_stateid = op_res->stateid;
2149 	osp->os_delegation = 0;
2150 	/*
2151 	 * Need to reset this bitfield for the possible case where we were
2152 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2153 	 * we could retry the CLOSE, OPENed the file again.
2154 	 */
2155 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2156 	osp->os_final_close = 0;
2157 	osp->os_force_close = 0;
2158 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2159 		osp->os_dc_openacc = open_args->share_access;
2160 	mutex_exit(&osp->os_sync_lock);
2161 
2162 	nfs4_end_open_seqid_sync(oop);
2163 
2164 	/* accept delegation, if any */
2165 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2166 
2167 	nfs4args_copen_free(open_args);
2168 
2169 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2170 
2171 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2172 
2173 	ASSERT(nfs4_consistent_type(vp));
2174 
2175 	open_owner_rele(oop);
2176 	crfree(cr);
2177 	crfree(cred_otw);
2178 	return;
2179 
2180 kill_file:
2181 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2182 failed_reopen:
2183 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2184 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2185 	    (void *)osp, (void *)cr, rnode4info(rp)));
2186 	mutex_enter(&osp->os_sync_lock);
2187 	osp->os_failed_reopen = 1;
2188 	mutex_exit(&osp->os_sync_lock);
2189 bailout:
2190 	if (oop != NULL) {
2191 		nfs4_end_open_seqid_sync(oop);
2192 		open_owner_rele(oop);
2193 	}
2194 	if (cr != NULL)
2195 		crfree(cr);
2196 	if (cred_otw != NULL)
2197 		crfree(cred_otw);
2198 }
2199 
2200 /* for . and .. OPENs */
2201 /* ARGSUSED */
2202 static int
2203 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2204 {
2205 	rnode4_t *rp;
2206 	nfs4_ga_res_t gar;
2207 
2208 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2209 
2210 	/*
2211 	 * If close-to-open consistency checking is turned off or
2212 	 * if there is no cached data, we can avoid
2213 	 * the over the wire getattr.  Otherwise, force a
2214 	 * call to the server to get fresh attributes and to
2215 	 * check caches. This is required for close-to-open
2216 	 * consistency.
2217 	 */
2218 	rp = VTOR4(*vpp);
2219 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2220 	    (rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2221 		return (0);
2222 
2223 	gar.n4g_va.va_mask = AT_ALL;
2224 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2225 }
2226 
2227 /*
2228  * CLOSE a file
2229  */
2230 /* ARGSUSED */
2231 static int
2232 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
2233 	caller_context_t *ct)
2234 {
2235 	rnode4_t	*rp;
2236 	int		 error = 0;
2237 	int		 r_error = 0;
2238 	int		 n4error = 0;
2239 	nfs4_error_t	 e = { 0, NFS4_OK, RPC_SUCCESS };
2240 
2241 	/*
2242 	 * Remove client state for this (lockowner, file) pair.
2243 	 * Issue otw v4 call to have the server do the same.
2244 	 */
2245 
2246 	rp = VTOR4(vp);
2247 
2248 	/*
2249 	 * zone_enter(2) prevents processes from changing zones with NFS files
2250 	 * open; if we happen to get here from the wrong zone we can't do
2251 	 * anything over the wire.
2252 	 */
2253 	if (VTOMI4(vp)->mi_zone != nfs_zone()) {
2254 		/*
2255 		 * We could attempt to clean up locks, except we're sure
2256 		 * that the current process didn't acquire any locks on
2257 		 * the file: any attempt to lock a file belong to another zone
2258 		 * will fail, and one can't lock an NFS file and then change
2259 		 * zones, as that fails too.
2260 		 *
2261 		 * Returning an error here is the sane thing to do.  A
2262 		 * subsequent call to VN_RELE() which translates to a
2263 		 * nfs4_inactive() will clean up state: if the zone of the
2264 		 * vnode's origin is still alive and kicking, the inactive
2265 		 * thread will handle the request (from the correct zone), and
2266 		 * everything (minus the OTW close call) should be OK.  If the
2267 		 * zone is going away nfs4_async_inactive() will throw away
2268 		 * delegations, open streams and cached pages inline.
2269 		 */
2270 		return (EIO);
2271 	}
2272 
2273 	/*
2274 	 * If we are using local locking for this filesystem, then
2275 	 * release all of the SYSV style record locks.  Otherwise,
2276 	 * we are doing network locking and we need to release all
2277 	 * of the network locks.  All of the locks held by this
2278 	 * process on this file are released no matter what the
2279 	 * incoming reference count is.
2280 	 */
2281 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK) {
2282 		cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
2283 		cleanshares(vp, ttoproc(curthread)->p_pid);
2284 	} else
2285 		e.error = nfs4_lockrelease(vp, flag, offset, cr);
2286 
2287 	if (e.error)
2288 		return (e.error);
2289 
2290 	if (count > 1)
2291 		return (0);
2292 
2293 	/*
2294 	 * If the file has been `unlinked', then purge the
2295 	 * DNLC so that this vnode will get reycled quicker
2296 	 * and the .nfs* file on the server will get removed.
2297 	 */
2298 	if (rp->r_unldvp != NULL)
2299 		dnlc_purge_vp(vp);
2300 
2301 	/*
2302 	 * If the file was open for write and there are pages,
2303 	 * do a synchronous flush and commit of all of the
2304 	 * dirty and uncommitted pages.
2305 	 */
2306 	ASSERT(!e.error);
2307 	if ((flag & FWRITE) && nfs4_has_pages(vp))
2308 		error = nfs4_putpage_commit(vp, 0, 0, cr);
2309 
2310 	mutex_enter(&rp->r_statelock);
2311 	r_error = rp->r_error;
2312 	rp->r_error = 0;
2313 	mutex_exit(&rp->r_statelock);
2314 
2315 	/*
2316 	 * If this file type is one for which no explicit 'open' was
2317 	 * done, then bail now (ie. no need for protocol 'close'). If
2318 	 * there was an error w/the vm subsystem, return _that_ error,
2319 	 * otherwise, return any errors that may've been reported via
2320 	 * the rnode.
2321 	 */
2322 	if (vp->v_type != VREG)
2323 		return (error ? error : r_error);
2324 
2325 	/*
2326 	 * The sync putpage commit may have failed above, but since
2327 	 * we're working w/a regular file, we need to do the protocol
2328 	 * 'close' (nfs4close_one will figure out if an otw close is
2329 	 * needed or not). Report any errors _after_ doing the protocol
2330 	 * 'close'.
2331 	 */
2332 	nfs4close_one(vp, NULL, cr, flag, NULL, &e, CLOSE_NORM, 0, 0, 0);
2333 	n4error = e.error ? e.error : geterrno4(e.stat);
2334 
2335 	/*
2336 	 * Error reporting prio (Hi -> Lo)
2337 	 *
2338 	 *   i) nfs4_putpage_commit (error)
2339 	 *  ii) rnode's (r_error)
2340 	 * iii) nfs4close_one (n4error)
2341 	 */
2342 	return (error ? error : (r_error ? r_error : n4error));
2343 }
2344 
2345 /*
2346  * Initialize *lost_rqstp.
2347  */
2348 
2349 static void
2350 nfs4close_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
2351     nfs4_open_owner_t *oop, nfs4_open_stream_t *osp, cred_t *cr,
2352     vnode_t *vp)
2353 {
2354 	if (error != ETIMEDOUT && error != EINTR &&
2355 	    !NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
2356 		lost_rqstp->lr_op = 0;
2357 		return;
2358 	}
2359 
2360 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
2361 	    "nfs4close_save_lost_rqst: error %d", error));
2362 
2363 	lost_rqstp->lr_op = OP_CLOSE;
2364 	/*
2365 	 * The vp is held and rele'd via the recovery code.
2366 	 * See nfs4_save_lost_rqst.
2367 	 */
2368 	lost_rqstp->lr_vp = vp;
2369 	lost_rqstp->lr_dvp = NULL;
2370 	lost_rqstp->lr_oop = oop;
2371 	lost_rqstp->lr_osp = osp;
2372 	ASSERT(osp != NULL);
2373 	ASSERT(mutex_owned(&osp->os_sync_lock));
2374 	osp->os_pending_close = 1;
2375 	lost_rqstp->lr_lop = NULL;
2376 	lost_rqstp->lr_cr = cr;
2377 	lost_rqstp->lr_flk = NULL;
2378 	lost_rqstp->lr_putfirst = FALSE;
2379 }
2380 
2381 /*
2382  * Assumes you already have the open seqid sync grabbed as well as the
2383  * 'os_sync_lock'.  Note: this will release the open seqid sync and
2384  * 'os_sync_lock' if client recovery starts.  Calling functions have to
2385  * be prepared to handle this.
2386  *
2387  * 'recov' is returned as 1 if the CLOSE operation detected client recovery
2388  * was needed and was started, and that the calling function should retry
2389  * this function; otherwise it is returned as 0.
2390  *
2391  * Errors are returned via the nfs4_error_t parameter.
2392  */
2393 static void
2394 nfs4close_otw(rnode4_t *rp, cred_t *cred_otw, nfs4_open_owner_t *oop,
2395     nfs4_open_stream_t *osp, int *recov, int *did_start_seqid_syncp,
2396     nfs4_close_type_t close_type, nfs4_error_t *ep, int *have_sync_lockp)
2397 {
2398 	COMPOUND4args_clnt args;
2399 	COMPOUND4res_clnt res;
2400 	CLOSE4args *close_args;
2401 	nfs_resop4 *resop;
2402 	nfs_argop4 argop[3];
2403 	int doqueue = 1;
2404 	mntinfo4_t *mi;
2405 	seqid4 seqid;
2406 	vnode_t *vp;
2407 	bool_t needrecov = FALSE;
2408 	nfs4_lost_rqst_t lost_rqst;
2409 	hrtime_t t;
2410 
2411 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
2412 
2413 	ASSERT(MUTEX_HELD(&osp->os_sync_lock));
2414 
2415 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw"));
2416 
2417 	/* Only set this to 1 if recovery is started */
2418 	*recov = 0;
2419 
2420 	/* do the OTW call to close the file */
2421 
2422 	if (close_type == CLOSE_RESEND)
2423 		args.ctag = TAG_CLOSE_LOST;
2424 	else if (close_type == CLOSE_AFTER_RESEND)
2425 		args.ctag = TAG_CLOSE_UNDO;
2426 	else
2427 		args.ctag = TAG_CLOSE;
2428 
2429 	args.array_len = 3;
2430 	args.array = argop;
2431 
2432 	vp = RTOV4(rp);
2433 
2434 	mi = VTOMI4(vp);
2435 
2436 	/* putfh target fh */
2437 	argop[0].argop = OP_CPUTFH;
2438 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
2439 
2440 	argop[1].argop = OP_GETATTR;
2441 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
2442 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
2443 
2444 	argop[2].argop = OP_CLOSE;
2445 	close_args = &argop[2].nfs_argop4_u.opclose;
2446 
2447 	seqid = nfs4_get_open_seqid(oop) + 1;
2448 
2449 	close_args->seqid = seqid;
2450 	close_args->open_stateid = osp->open_stateid;
2451 
2452 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
2453 	    "nfs4close_otw: %s call, rp %s", needrecov ? "recov" : "first",
2454 	    rnode4info(rp)));
2455 
2456 	t = gethrtime();
2457 
2458 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
2459 
2460 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
2461 		nfs4_set_open_seqid(seqid, oop, args.ctag);
2462 	}
2463 
2464 	needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
2465 	if (ep->error && !needrecov) {
2466 		/*
2467 		 * if there was an error and no recovery is to be done
2468 		 * then then set up the file to flush its cache if
2469 		 * needed for the next caller.
2470 		 */
2471 		mutex_enter(&rp->r_statelock);
2472 		PURGE_ATTRCACHE4_LOCKED(rp);
2473 		rp->r_flags &= ~R4WRITEMODIFIED;
2474 		mutex_exit(&rp->r_statelock);
2475 		return;
2476 	}
2477 
2478 	if (needrecov) {
2479 		bool_t abort;
2480 		nfs4_bseqid_entry_t *bsep = NULL;
2481 
2482 		if (close_type != CLOSE_RESEND)
2483 			nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
2484 			    osp, cred_otw, vp);
2485 
2486 		if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
2487 			bsep = nfs4_create_bseqid_entry(oop, NULL, vp,
2488 			    0, args.ctag, close_args->seqid);
2489 
2490 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
2491 		    "nfs4close_otw: initiating recovery. error %d "
2492 		    "res.status %d", ep->error, res.status));
2493 
2494 		/*
2495 		 * Drop the 'os_sync_lock' here so we don't hit
2496 		 * a potential recursive mutex_enter via an
2497 		 * 'open_stream_hold()'.
2498 		 */
2499 		mutex_exit(&osp->os_sync_lock);
2500 		*have_sync_lockp = 0;
2501 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
2502 		    (close_type != CLOSE_RESEND &&
2503 		    lost_rqst.lr_op == OP_CLOSE) ? &lost_rqst : NULL,
2504 		    OP_CLOSE, bsep);
2505 
2506 		/* drop open seq sync, and let the calling function regrab it */
2507 		nfs4_end_open_seqid_sync(oop);
2508 		*did_start_seqid_syncp = 0;
2509 
2510 		if (bsep)
2511 			kmem_free(bsep, sizeof (*bsep));
2512 		/*
2513 		 * For signals, the caller wants to quit, so don't say to
2514 		 * retry.  For forced unmount, if it's a user thread, it
2515 		 * wants to quit.  If it's a recovery thread, the retry
2516 		 * will happen higher-up on the call stack.  Either way,
2517 		 * don't say to retry.
2518 		 */
2519 		if (abort == FALSE && ep->error != EINTR &&
2520 		    !NFS4_FRC_UNMT_ERR(ep->error, mi->mi_vfsp) &&
2521 		    close_type != CLOSE_RESEND &&
2522 		    close_type != CLOSE_AFTER_RESEND)
2523 			*recov = 1;
2524 		else
2525 			*recov = 0;
2526 
2527 		if (!ep->error)
2528 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2529 		return;
2530 	}
2531 
2532 	if (res.status) {
2533 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2534 		return;
2535 	}
2536 
2537 	mutex_enter(&rp->r_statev4_lock);
2538 	rp->created_v4 = 0;
2539 	mutex_exit(&rp->r_statev4_lock);
2540 
2541 	resop = &res.array[2];
2542 	osp->open_stateid = resop->nfs_resop4_u.opclose.open_stateid;
2543 	osp->os_valid = 0;
2544 
2545 	/*
2546 	 * This removes the reference obtained at OPEN; ie, when the
2547 	 * open stream structure was created.
2548 	 *
2549 	 * We don't have to worry about calling 'open_stream_rele'
2550 	 * since we our currently holding a reference to the open
2551 	 * stream which means the count cannot go to 0 with this
2552 	 * decrement.
2553 	 */
2554 	ASSERT(osp->os_ref_count >= 2);
2555 	osp->os_ref_count--;
2556 
2557 	if (!ep->error)
2558 		nfs4_attr_cache(vp,
2559 		    &res.array[1].nfs_resop4_u.opgetattr.ga_res,
2560 		    t, cred_otw, TRUE, NULL);
2561 
2562 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw:"
2563 	    " returning %d", ep->error));
2564 
2565 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2566 }
2567 
2568 /* ARGSUSED */
2569 static int
2570 nfs4_read(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2571     caller_context_t *ct)
2572 {
2573 	rnode4_t *rp;
2574 	u_offset_t off;
2575 	offset_t diff;
2576 	uint_t on;
2577 	uint_t n;
2578 	caddr_t base;
2579 	uint_t flags;
2580 	int error;
2581 	mntinfo4_t *mi;
2582 
2583 	rp = VTOR4(vp);
2584 
2585 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2586 
2587 	if (IS_SHADOW(vp, rp))
2588 		vp = RTOV4(rp);
2589 
2590 	if (vp->v_type != VREG)
2591 		return (EISDIR);
2592 
2593 	mi = VTOMI4(vp);
2594 
2595 	if (nfs_zone() != mi->mi_zone)
2596 		return (EIO);
2597 
2598 	if (uiop->uio_resid == 0)
2599 		return (0);
2600 
2601 	if (uiop->uio_loffset < 0 || uiop->uio_loffset + uiop->uio_resid < 0)
2602 		return (EINVAL);
2603 
2604 	mutex_enter(&rp->r_statelock);
2605 	if (rp->r_flags & R4RECOVERRP)
2606 		error = (rp->r_error ? rp->r_error : EIO);
2607 	else
2608 		error = 0;
2609 	mutex_exit(&rp->r_statelock);
2610 	if (error)
2611 		return (error);
2612 
2613 	/*
2614 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2615 	 * using client-side direct I/O and the file is not mmap'd and
2616 	 * there are no cached pages.
2617 	 */
2618 	if ((vp->v_flag & VNOCACHE) ||
2619 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2620 	    rp->r_mapcnt == 0 && !nfs4_has_pages(vp))) {
2621 		size_t resid = 0;
2622 
2623 		return (nfs4read(vp, NULL, uiop->uio_loffset,
2624 		    uiop->uio_resid, &resid, cr, FALSE, uiop));
2625 	}
2626 
2627 	error = 0;
2628 
2629 	do {
2630 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2631 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2632 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2633 
2634 		if (error = nfs4_validate_caches(vp, cr))
2635 			break;
2636 
2637 		mutex_enter(&rp->r_statelock);
2638 		diff = rp->r_size - uiop->uio_loffset;
2639 		mutex_exit(&rp->r_statelock);
2640 		if (diff <= 0)
2641 			break;
2642 		if (diff < n)
2643 			n = (uint_t)diff;
2644 
2645 		if (vpm_enable) {
2646 			/*
2647 			 * Copy data.
2648 			 */
2649 			error = vpm_data_copy(vp, off + on, n, uiop,
2650 			    1, NULL, 0, S_READ);
2651 		} else {
2652 			base = segmap_getmapflt(segkmap, vp, off + on, n, 1,
2653 			    S_READ);
2654 
2655 			error = uiomove(base + on, n, UIO_READ, uiop);
2656 		}
2657 
2658 		if (!error) {
2659 			/*
2660 			 * If read a whole block or read to eof,
2661 			 * won't need this buffer again soon.
2662 			 */
2663 			mutex_enter(&rp->r_statelock);
2664 			if (n + on == MAXBSIZE ||
2665 			    uiop->uio_loffset == rp->r_size)
2666 				flags = SM_DONTNEED;
2667 			else
2668 				flags = 0;
2669 			mutex_exit(&rp->r_statelock);
2670 			if (vpm_enable) {
2671 				error = vpm_sync_pages(vp, off, n, flags);
2672 			} else {
2673 				error = segmap_release(segkmap, base, flags);
2674 			}
2675 		} else {
2676 			if (vpm_enable) {
2677 				(void) vpm_sync_pages(vp, off, n, 0);
2678 			} else {
2679 				(void) segmap_release(segkmap, base, 0);
2680 			}
2681 		}
2682 	} while (!error && uiop->uio_resid > 0);
2683 
2684 	return (error);
2685 }
2686 
2687 /* ARGSUSED */
2688 static int
2689 nfs4_write(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2690     caller_context_t *ct)
2691 {
2692 	rlim64_t limit = uiop->uio_llimit;
2693 	rnode4_t *rp;
2694 	u_offset_t off;
2695 	caddr_t base;
2696 	uint_t flags;
2697 	int remainder;
2698 	size_t n;
2699 	int on;
2700 	int error;
2701 	int resid;
2702 	u_offset_t offset;
2703 	mntinfo4_t *mi;
2704 	uint_t bsize;
2705 
2706 	rp = VTOR4(vp);
2707 
2708 	if (IS_SHADOW(vp, rp))
2709 		vp = RTOV4(rp);
2710 
2711 	if (vp->v_type != VREG)
2712 		return (EISDIR);
2713 
2714 	mi = VTOMI4(vp);
2715 
2716 	if (nfs_zone() != mi->mi_zone)
2717 		return (EIO);
2718 
2719 	if (uiop->uio_resid == 0)
2720 		return (0);
2721 
2722 	mutex_enter(&rp->r_statelock);
2723 	if (rp->r_flags & R4RECOVERRP)
2724 		error = (rp->r_error ? rp->r_error : EIO);
2725 	else
2726 		error = 0;
2727 	mutex_exit(&rp->r_statelock);
2728 	if (error)
2729 		return (error);
2730 
2731 	if (ioflag & FAPPEND) {
2732 		struct vattr va;
2733 
2734 		/*
2735 		 * Must serialize if appending.
2736 		 */
2737 		if (nfs_rw_lock_held(&rp->r_rwlock, RW_READER)) {
2738 			nfs_rw_exit(&rp->r_rwlock);
2739 			if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER,
2740 			    INTR(vp)))
2741 				return (EINTR);
2742 		}
2743 
2744 		va.va_mask = AT_SIZE;
2745 		error = nfs4getattr(vp, &va, cr);
2746 		if (error)
2747 			return (error);
2748 		uiop->uio_loffset = va.va_size;
2749 	}
2750 
2751 	offset = uiop->uio_loffset + uiop->uio_resid;
2752 
2753 	if (uiop->uio_loffset < (offset_t)0 || offset < 0)
2754 		return (EINVAL);
2755 
2756 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
2757 		limit = MAXOFFSET_T;
2758 
2759 	/*
2760 	 * Check to make sure that the process will not exceed
2761 	 * its limit on file size.  It is okay to write up to
2762 	 * the limit, but not beyond.  Thus, the write which
2763 	 * reaches the limit will be short and the next write
2764 	 * will return an error.
2765 	 */
2766 	remainder = 0;
2767 	if (offset > uiop->uio_llimit) {
2768 		remainder = offset - uiop->uio_llimit;
2769 		uiop->uio_resid = uiop->uio_llimit - uiop->uio_loffset;
2770 		if (uiop->uio_resid <= 0) {
2771 			proc_t *p = ttoproc(curthread);
2772 
2773 			uiop->uio_resid += remainder;
2774 			mutex_enter(&p->p_lock);
2775 			(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE],
2776 			    p->p_rctls, p, RCA_UNSAFE_SIGINFO);
2777 			mutex_exit(&p->p_lock);
2778 			return (EFBIG);
2779 		}
2780 	}
2781 
2782 	/* update the change attribute, if we have a write delegation */
2783 
2784 	mutex_enter(&rp->r_statev4_lock);
2785 	if (rp->r_deleg_type == OPEN_DELEGATE_WRITE)
2786 		rp->r_deleg_change++;
2787 
2788 	mutex_exit(&rp->r_statev4_lock);
2789 
2790 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
2791 		return (EINTR);
2792 
2793 	/*
2794 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2795 	 * using client-side direct I/O and the file is not mmap'd and
2796 	 * there are no cached pages.
2797 	 */
2798 	if ((vp->v_flag & VNOCACHE) ||
2799 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2800 	    rp->r_mapcnt == 0 && !nfs4_has_pages(vp))) {
2801 		size_t bufsize;
2802 		int count;
2803 		u_offset_t org_offset;
2804 		stable_how4 stab_comm;
2805 nfs4_fwrite:
2806 		if (rp->r_flags & R4STALE) {
2807 			resid = uiop->uio_resid;
2808 			offset = uiop->uio_loffset;
2809 			error = rp->r_error;
2810 			goto bottom;
2811 		}
2812 
2813 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2814 		base = kmem_alloc(bufsize, KM_SLEEP);
2815 		do {
2816 			if (ioflag & FDSYNC)
2817 				stab_comm = DATA_SYNC4;
2818 			else
2819 				stab_comm = FILE_SYNC4;
2820 			resid = uiop->uio_resid;
2821 			offset = uiop->uio_loffset;
2822 			count = MIN(uiop->uio_resid, bufsize);
2823 			org_offset = uiop->uio_loffset;
2824 			error = uiomove(base, count, UIO_WRITE, uiop);
2825 			if (!error) {
2826 				error = nfs4write(vp, base, org_offset,
2827 				    count, cr, &stab_comm);
2828 				if (!error) {
2829 					mutex_enter(&rp->r_statelock);
2830 					if (rp->r_size < uiop->uio_loffset)
2831 						rp->r_size = uiop->uio_loffset;
2832 					mutex_exit(&rp->r_statelock);
2833 				}
2834 			}
2835 		} while (!error && uiop->uio_resid > 0);
2836 		kmem_free(base, bufsize);
2837 		goto bottom;
2838 	}
2839 
2840 	bsize = vp->v_vfsp->vfs_bsize;
2841 
2842 	do {
2843 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2844 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2845 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2846 
2847 		resid = uiop->uio_resid;
2848 		offset = uiop->uio_loffset;
2849 
2850 		if (rp->r_flags & R4STALE) {
2851 			error = rp->r_error;
2852 			break;
2853 		}
2854 
2855 		/*
2856 		 * Don't create dirty pages faster than they
2857 		 * can be cleaned so that the system doesn't
2858 		 * get imbalanced.  If the async queue is
2859 		 * maxed out, then wait for it to drain before
2860 		 * creating more dirty pages.  Also, wait for
2861 		 * any threads doing pagewalks in the vop_getattr
2862 		 * entry points so that they don't block for
2863 		 * long periods.
2864 		 */
2865 		mutex_enter(&rp->r_statelock);
2866 		while ((mi->mi_max_threads != 0 &&
2867 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2868 		    rp->r_gcount > 0)
2869 			cv_wait(&rp->r_cv, &rp->r_statelock);
2870 		mutex_exit(&rp->r_statelock);
2871 
2872 		if (vpm_enable) {
2873 			/*
2874 			 * It will use kpm mappings, so no need to
2875 			 * pass an address.
2876 			 */
2877 			error = writerp4(rp, NULL, n, uiop, 0);
2878 		} else  {
2879 			if (segmap_kpm) {
2880 				int pon = uiop->uio_loffset & PAGEOFFSET;
2881 				size_t pn = MIN(PAGESIZE - pon,
2882 				    uiop->uio_resid);
2883 				int pagecreate;
2884 
2885 				mutex_enter(&rp->r_statelock);
2886 				pagecreate = (pon == 0) && (pn == PAGESIZE ||
2887 				    uiop->uio_loffset + pn >= rp->r_size);
2888 				mutex_exit(&rp->r_statelock);
2889 
2890 				base = segmap_getmapflt(segkmap, vp, off + on,
2891 				    pn, !pagecreate, S_WRITE);
2892 
2893 				error = writerp4(rp, base + pon, n, uiop,
2894 				    pagecreate);
2895 
2896 			} else {
2897 				base = segmap_getmapflt(segkmap, vp, off + on,
2898 				    n, 0, S_READ);
2899 				error = writerp4(rp, base + on, n, uiop, 0);
2900 			}
2901 		}
2902 
2903 		if (!error) {
2904 			if (mi->mi_flags & MI4_NOAC)
2905 				flags = SM_WRITE;
2906 			else if ((uiop->uio_loffset % bsize) == 0 ||
2907 			    IS_SWAPVP(vp)) {
2908 				/*
2909 				 * Have written a whole block.
2910 				 * Start an asynchronous write
2911 				 * and mark the buffer to
2912 				 * indicate that it won't be
2913 				 * needed again soon.
2914 				 */
2915 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
2916 			} else
2917 				flags = 0;
2918 			if ((ioflag & (FSYNC|FDSYNC)) ||
2919 			    (rp->r_flags & R4OUTOFSPACE)) {
2920 				flags &= ~SM_ASYNC;
2921 				flags |= SM_WRITE;
2922 			}
2923 			if (vpm_enable) {
2924 				error = vpm_sync_pages(vp, off, n, flags);
2925 			} else {
2926 				error = segmap_release(segkmap, base, flags);
2927 			}
2928 		} else {
2929 			if (vpm_enable) {
2930 				(void) vpm_sync_pages(vp, off, n, 0);
2931 			} else {
2932 				(void) segmap_release(segkmap, base, 0);
2933 			}
2934 			/*
2935 			 * In the event that we got an access error while
2936 			 * faulting in a page for a write-only file just
2937 			 * force a write.
2938 			 */
2939 			if (error == EACCES)
2940 				goto nfs4_fwrite;
2941 		}
2942 	} while (!error && uiop->uio_resid > 0);
2943 
2944 bottom:
2945 	if (error) {
2946 		uiop->uio_resid = resid + remainder;
2947 		uiop->uio_loffset = offset;
2948 	} else {
2949 		uiop->uio_resid += remainder;
2950 
2951 		mutex_enter(&rp->r_statev4_lock);
2952 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
2953 			gethrestime(&rp->r_attr.va_mtime);
2954 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
2955 		}
2956 		mutex_exit(&rp->r_statev4_lock);
2957 	}
2958 
2959 	nfs_rw_exit(&rp->r_lkserlock);
2960 
2961 	return (error);
2962 }
2963 
2964 /*
2965  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
2966  */
2967 static int
2968 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
2969     int flags, cred_t *cr)
2970 {
2971 	struct buf *bp;
2972 	int error;
2973 	page_t *savepp;
2974 	uchar_t fsdata;
2975 	stable_how4 stab_comm;
2976 
2977 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
2978 	bp = pageio_setup(pp, len, vp, flags);
2979 	ASSERT(bp != NULL);
2980 
2981 	/*
2982 	 * pageio_setup should have set b_addr to 0.  This
2983 	 * is correct since we want to do I/O on a page
2984 	 * boundary.  bp_mapin will use this addr to calculate
2985 	 * an offset, and then set b_addr to the kernel virtual
2986 	 * address it allocated for us.
2987 	 */
2988 	ASSERT(bp->b_un.b_addr == 0);
2989 
2990 	bp->b_edev = 0;
2991 	bp->b_dev = 0;
2992 	bp->b_lblkno = lbtodb(off);
2993 	bp->b_file = vp;
2994 	bp->b_offset = (offset_t)off;
2995 	bp_mapin(bp);
2996 
2997 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
2998 	    freemem > desfree)
2999 		stab_comm = UNSTABLE4;
3000 	else
3001 		stab_comm = FILE_SYNC4;
3002 
3003 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
3004 
3005 	bp_mapout(bp);
3006 	pageio_done(bp);
3007 
3008 	if (stab_comm == UNSTABLE4)
3009 		fsdata = C_DELAYCOMMIT;
3010 	else
3011 		fsdata = C_NOCOMMIT;
3012 
3013 	savepp = pp;
3014 	do {
3015 		pp->p_fsdata = fsdata;
3016 	} while ((pp = pp->p_next) != savepp);
3017 
3018 	return (error);
3019 }
3020 
3021 /*
3022  */
3023 static int
3024 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
3025 {
3026 	nfs4_open_owner_t	*oop;
3027 	nfs4_open_stream_t	*osp;
3028 	rnode4_t		*rp = VTOR4(vp);
3029 	mntinfo4_t 		*mi = VTOMI4(vp);
3030 	int 			reopen_needed;
3031 
3032 	ASSERT(nfs_zone() == mi->mi_zone);
3033 
3034 
3035 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
3036 	if (!oop)
3037 		return (EIO);
3038 
3039 	/* returns with 'os_sync_lock' held */
3040 	osp = find_open_stream(oop, rp);
3041 	if (!osp) {
3042 		open_owner_rele(oop);
3043 		return (EIO);
3044 	}
3045 
3046 	if (osp->os_failed_reopen) {
3047 		mutex_exit(&osp->os_sync_lock);
3048 		open_stream_rele(osp, rp);
3049 		open_owner_rele(oop);
3050 		return (EIO);
3051 	}
3052 
3053 	/*
3054 	 * Determine whether a reopen is needed.  If this
3055 	 * is a delegation open stream, then the os_delegation bit
3056 	 * should be set.
3057 	 */
3058 
3059 	reopen_needed = osp->os_delegation;
3060 
3061 	mutex_exit(&osp->os_sync_lock);
3062 	open_owner_rele(oop);
3063 
3064 	if (reopen_needed) {
3065 		nfs4_error_zinit(ep);
3066 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
3067 		mutex_enter(&osp->os_sync_lock);
3068 		if (ep->error || ep->stat || osp->os_failed_reopen) {
3069 			mutex_exit(&osp->os_sync_lock);
3070 			open_stream_rele(osp, rp);
3071 			return (EIO);
3072 		}
3073 		mutex_exit(&osp->os_sync_lock);
3074 	}
3075 	open_stream_rele(osp, rp);
3076 
3077 	return (0);
3078 }
3079 
3080 /*
3081  * Write to file.  Writes to remote server in largest size
3082  * chunks that the server can handle.  Write is synchronous.
3083  */
3084 static int
3085 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3086     stable_how4 *stab_comm)
3087 {
3088 	mntinfo4_t *mi;
3089 	COMPOUND4args_clnt args;
3090 	COMPOUND4res_clnt res;
3091 	WRITE4args *wargs;
3092 	WRITE4res *wres;
3093 	nfs_argop4 argop[2];
3094 	nfs_resop4 *resop;
3095 	int tsize;
3096 	stable_how4 stable;
3097 	rnode4_t *rp;
3098 	int doqueue = 1;
3099 	bool_t needrecov;
3100 	nfs4_recov_state_t recov_state;
3101 	nfs4_stateid_types_t sid_types;
3102 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3103 
3104 	rp = VTOR4(vp);
3105 	mi = VTOMI4(vp);
3106 
3107 	ASSERT(nfs_zone() == mi->mi_zone);
3108 
3109 	stable = *stab_comm;
3110 	*stab_comm = FILE_SYNC4;
3111 
3112 	needrecov = FALSE;
3113 	recov_state.rs_flags = 0;
3114 	recov_state.rs_num_retry_despite_err = 0;
3115 	nfs4_init_stateid_types(&sid_types);
3116 
3117 recov_retry:
3118 	args.ctag = TAG_WRITE;
3119 	args.array_len = 2;
3120 	args.array = argop;
3121 
3122 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3123 	    &recov_state, NULL);
3124 	if (e.error)
3125 		return (e.error);
3126 
3127 	/* 0. putfh target fh */
3128 	argop[0].argop = OP_CPUTFH;
3129 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3130 
3131 	/* 1. write */
3132 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3133 
3134 	do {
3135 
3136 		wargs->offset = (offset4)offset;
3137 		wargs->data_val = base;
3138 
3139 		if (mi->mi_io_kstats) {
3140 			mutex_enter(&mi->mi_lock);
3141 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3142 			mutex_exit(&mi->mi_lock);
3143 		}
3144 
3145 		if ((vp->v_flag & VNOCACHE) ||
3146 		    (rp->r_flags & R4DIRECTIO) ||
3147 		    (mi->mi_flags & MI4_DIRECTIO))
3148 			tsize = MIN(mi->mi_stsize, count);
3149 		else
3150 			tsize = MIN(mi->mi_curwrite, count);
3151 		wargs->data_len = (uint_t)tsize;
3152 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3153 
3154 		if (mi->mi_io_kstats) {
3155 			mutex_enter(&mi->mi_lock);
3156 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3157 			mutex_exit(&mi->mi_lock);
3158 		}
3159 
3160 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3161 		if (e.error && !needrecov) {
3162 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3163 			    &recov_state, needrecov);
3164 			return (e.error);
3165 		}
3166 
3167 
3168 		/*
3169 		 * Do handling of OLD_STATEID outside
3170 		 * of the normal recovery framework.
3171 		 *
3172 		 * If write receives a BAD stateid error while using a
3173 		 * delegation stateid, retry using the open stateid (if it
3174 		 * exists).  If it doesn't have an open stateid, reopen the
3175 		 * file first, then retry.
3176 		 */
3177 		if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3178 		    sid_types.cur_sid_type != SPEC_SID) {
3179 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3180 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3181 			    &recov_state, needrecov);
3182 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3183 			goto recov_retry;
3184 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3185 		    sid_types.cur_sid_type == DEL_SID) {
3186 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3187 			mutex_enter(&rp->r_statev4_lock);
3188 			rp->r_deleg_return_pending = TRUE;
3189 			mutex_exit(&rp->r_statev4_lock);
3190 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3191 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3192 				    &recov_state, needrecov);
3193 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3194 				    (caddr_t)&res);
3195 				return (EIO);
3196 			}
3197 			nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3198 			    &recov_state, needrecov);
3199 			/* hold needed for nfs4delegreturn_thread */
3200 			VN_HOLD(vp);
3201 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3202 			    NFS4_DR_DISCARD), FALSE);
3203 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3204 			goto recov_retry;
3205 		}
3206 
3207 		if (needrecov) {
3208 			bool_t abort;
3209 
3210 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3211 			    "nfs4write: client got error %d, res.status %d"
3212 			    ", so start recovery", e.error, res.status));
3213 
3214 			abort = nfs4_start_recovery(&e,
3215 			    VTOMI4(vp), vp, NULL, &wargs->stateid,
3216 			    NULL, OP_WRITE, NULL);
3217 			if (!e.error) {
3218 				e.error = geterrno4(res.status);
3219 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3220 				    (caddr_t)&res);
3221 			}
3222 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3223 			    &recov_state, needrecov);
3224 			if (abort == FALSE)
3225 				goto recov_retry;
3226 			return (e.error);
3227 		}
3228 
3229 		if (res.status) {
3230 			e.error = geterrno4(res.status);
3231 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3232 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3233 			    &recov_state, needrecov);
3234 			return (e.error);
3235 		}
3236 
3237 		resop = &res.array[1];	/* write res */
3238 		wres = &resop->nfs_resop4_u.opwrite;
3239 
3240 		if ((int)wres->count > tsize) {
3241 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3242 
3243 			zcmn_err(getzoneid(), CE_WARN,
3244 			    "nfs4write: server wrote %u, requested was %u",
3245 			    (int)wres->count, tsize);
3246 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3247 			    &recov_state, needrecov);
3248 			return (EIO);
3249 		}
3250 		if (wres->committed == UNSTABLE4) {
3251 			*stab_comm = UNSTABLE4;
3252 			if (wargs->stable == DATA_SYNC4 ||
3253 			    wargs->stable == FILE_SYNC4) {
3254 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3255 				    (caddr_t)&res);
3256 				zcmn_err(getzoneid(), CE_WARN,
3257 				    "nfs4write: server %s did not commit "
3258 				    "to stable storage",
3259 				    rp->r_server->sv_hostname);
3260 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3261 				    &recov_state, needrecov);
3262 				return (EIO);
3263 			}
3264 		}
3265 
3266 		tsize = (int)wres->count;
3267 		count -= tsize;
3268 		base += tsize;
3269 		offset += tsize;
3270 		if (mi->mi_io_kstats) {
3271 			mutex_enter(&mi->mi_lock);
3272 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3273 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3274 			    tsize;
3275 			mutex_exit(&mi->mi_lock);
3276 		}
3277 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3278 		mutex_enter(&rp->r_statelock);
3279 		if (rp->r_flags & R4HAVEVERF) {
3280 			if (rp->r_writeverf != wres->writeverf) {
3281 				nfs4_set_mod(vp);
3282 				rp->r_writeverf = wres->writeverf;
3283 			}
3284 		} else {
3285 			rp->r_writeverf = wres->writeverf;
3286 			rp->r_flags |= R4HAVEVERF;
3287 		}
3288 		PURGE_ATTRCACHE4_LOCKED(rp);
3289 		rp->r_flags |= R4WRITEMODIFIED;
3290 		gethrestime(&rp->r_attr.va_mtime);
3291 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3292 		mutex_exit(&rp->r_statelock);
3293 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3294 	} while (count);
3295 
3296 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state, needrecov);
3297 
3298 	return (e.error);
3299 }
3300 
3301 /*
3302  * Read from a file.  Reads data in largest chunks our interface can handle.
3303  */
3304 static int
3305 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3306     size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3307 {
3308 	mntinfo4_t *mi;
3309 	COMPOUND4args_clnt args;
3310 	COMPOUND4res_clnt res;
3311 	READ4args *rargs;
3312 	nfs_argop4 argop[2];
3313 	int tsize;
3314 	int doqueue;
3315 	rnode4_t *rp;
3316 	int data_len;
3317 	bool_t is_eof;
3318 	bool_t needrecov = FALSE;
3319 	nfs4_recov_state_t recov_state;
3320 	nfs4_stateid_types_t sid_types;
3321 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3322 
3323 	rp = VTOR4(vp);
3324 	mi = VTOMI4(vp);
3325 	doqueue = 1;
3326 
3327 	ASSERT(nfs_zone() == mi->mi_zone);
3328 
3329 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3330 
3331 	args.array_len = 2;
3332 	args.array = argop;
3333 
3334 	nfs4_init_stateid_types(&sid_types);
3335 
3336 	recov_state.rs_flags = 0;
3337 	recov_state.rs_num_retry_despite_err = 0;
3338 
3339 recov_retry:
3340 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3341 	    &recov_state, NULL);
3342 	if (e.error)
3343 		return (e.error);
3344 
3345 	/* putfh target fh */
3346 	argop[0].argop = OP_CPUTFH;
3347 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3348 
3349 	/* read */
3350 	argop[1].argop = OP_READ;
3351 	rargs = &argop[1].nfs_argop4_u.opread;
3352 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3353 	    OP_READ, &sid_types, async);
3354 
3355 	do {
3356 		if (mi->mi_io_kstats) {
3357 			mutex_enter(&mi->mi_lock);
3358 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3359 			mutex_exit(&mi->mi_lock);
3360 		}
3361 
3362 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3363 		    "nfs4read: %s call, rp %s",
3364 		    needrecov ? "recov" : "first",
3365 		    rnode4info(rp)));
3366 
3367 		if ((vp->v_flag & VNOCACHE) ||
3368 		    (rp->r_flags & R4DIRECTIO) ||
3369 		    (mi->mi_flags & MI4_DIRECTIO))
3370 			tsize = MIN(mi->mi_tsize, count);
3371 		else
3372 			tsize = MIN(mi->mi_curread, count);
3373 		rargs->offset = (offset4)offset;
3374 		rargs->count = (count4)tsize;
3375 		rargs->res_data_val_alt = NULL;
3376 		rargs->res_mblk = NULL;
3377 		rargs->res_uiop = NULL;
3378 		rargs->res_maxsize = 0;
3379 		if (uiop)
3380 			rargs->res_uiop = uiop;
3381 		else
3382 			rargs->res_data_val_alt = base;
3383 		rargs->res_maxsize = tsize;
3384 
3385 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3386 #ifdef	DEBUG
3387 		if (nfs4read_error_inject) {
3388 			res.status = nfs4read_error_inject;
3389 			nfs4read_error_inject = 0;
3390 		}
3391 #endif
3392 
3393 		if (mi->mi_io_kstats) {
3394 			mutex_enter(&mi->mi_lock);
3395 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3396 			mutex_exit(&mi->mi_lock);
3397 		}
3398 
3399 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3400 		if (e.error != 0 && !needrecov) {
3401 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3402 			    &recov_state, needrecov);
3403 			return (e.error);
3404 		}
3405 
3406 		/*
3407 		 * Do proper retry for OLD and BAD stateid errors outside
3408 		 * of the normal recovery framework.  There are two differences
3409 		 * between async and sync reads.  The first is that we allow
3410 		 * retry on BAD_STATEID for async reads, but not sync reads.
3411 		 * The second is that we mark the file dead for a failed
3412 		 * attempt with a special stateid for sync reads, but just
3413 		 * return EIO for async reads.
3414 		 *
3415 		 * If a sync read receives a BAD stateid error while using a
3416 		 * delegation stateid, retry using the open stateid (if it
3417 		 * exists).  If it doesn't have an open stateid, reopen the
3418 		 * file first, then retry.
3419 		 */
3420 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3421 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3422 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3423 			    &recov_state, needrecov);
3424 			if (sid_types.cur_sid_type == SPEC_SID) {
3425 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3426 				    (caddr_t)&res);
3427 				return (EIO);
3428 			}
3429 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3430 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3431 			goto recov_retry;
3432 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3433 		    !async && sid_types.cur_sid_type != SPEC_SID) {
3434 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3435 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3436 			    &recov_state, needrecov);
3437 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3438 			goto recov_retry;
3439 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3440 		    sid_types.cur_sid_type == DEL_SID) {
3441 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3442 			mutex_enter(&rp->r_statev4_lock);
3443 			rp->r_deleg_return_pending = TRUE;
3444 			mutex_exit(&rp->r_statev4_lock);
3445 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3446 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3447 				    &recov_state, needrecov);
3448 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3449 				    (caddr_t)&res);
3450 				return (EIO);
3451 			}
3452 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3453 			    &recov_state, needrecov);
3454 			/* hold needed for nfs4delegreturn_thread */
3455 			VN_HOLD(vp);
3456 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3457 			    NFS4_DR_DISCARD), FALSE);
3458 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3459 			goto recov_retry;
3460 		}
3461 		if (needrecov) {
3462 			bool_t abort;
3463 
3464 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3465 			    "nfs4read: initiating recovery\n"));
3466 
3467 			abort = nfs4_start_recovery(&e,
3468 			    mi, vp, NULL, &rargs->stateid,
3469 			    NULL, OP_READ, NULL);
3470 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3471 			    &recov_state, needrecov);
3472 			/*
3473 			 * Do not retry if we got OLD_STATEID using a special
3474 			 * stateid.  This avoids looping with a broken server.
3475 			 */
3476 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3477 			    sid_types.cur_sid_type == SPEC_SID)
3478 				abort = TRUE;
3479 
3480 			if (abort == FALSE) {
3481 				/*
3482 				 * Need to retry all possible stateids in
3483 				 * case the recovery error wasn't stateid
3484 				 * related or the stateids have become
3485 				 * stale (server reboot).
3486 				 */
3487 				nfs4_init_stateid_types(&sid_types);
3488 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3489 				    (caddr_t)&res);
3490 				goto recov_retry;
3491 			}
3492 
3493 			if (!e.error) {
3494 				e.error = geterrno4(res.status);
3495 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3496 				    (caddr_t)&res);
3497 			}
3498 			return (e.error);
3499 		}
3500 
3501 		if (res.status) {
3502 			e.error = geterrno4(res.status);
3503 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3504 			    &recov_state, needrecov);
3505 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3506 			return (e.error);
3507 		}
3508 
3509 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3510 		count -= data_len;
3511 		if (base)
3512 			base += data_len;
3513 		offset += data_len;
3514 		if (mi->mi_io_kstats) {
3515 			mutex_enter(&mi->mi_lock);
3516 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3517 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3518 			mutex_exit(&mi->mi_lock);
3519 		}
3520 		lwp_stat_update(LWP_STAT_INBLK, 1);
3521 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3522 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3523 
3524 	} while (count && !is_eof);
3525 
3526 	*residp = count;
3527 
3528 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3529 
3530 	return (e.error);
3531 }
3532 
3533 /* ARGSUSED */
3534 static int
3535 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp,
3536 	caller_context_t *ct)
3537 {
3538 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3539 		return (EIO);
3540 	switch (cmd) {
3541 		case _FIODIRECTIO:
3542 			return (nfs4_directio(vp, (int)arg, cr));
3543 		default:
3544 			return (ENOTTY);
3545 	}
3546 }
3547 
3548 /* ARGSUSED */
3549 int
3550 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3551     caller_context_t *ct)
3552 {
3553 	int error;
3554 	rnode4_t *rp = VTOR4(vp);
3555 
3556 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3557 		return (EIO);
3558 	/*
3559 	 * If it has been specified that the return value will
3560 	 * just be used as a hint, and we are only being asked
3561 	 * for size, fsid or rdevid, then return the client's
3562 	 * notion of these values without checking to make sure
3563 	 * that the attribute cache is up to date.
3564 	 * The whole point is to avoid an over the wire GETATTR
3565 	 * call.
3566 	 */
3567 	if (flags & ATTR_HINT) {
3568 		if (vap->va_mask ==
3569 		    (vap->va_mask & (AT_SIZE | AT_FSID | AT_RDEV))) {
3570 			mutex_enter(&rp->r_statelock);
3571 			if (vap->va_mask | AT_SIZE)
3572 				vap->va_size = rp->r_size;
3573 			if (vap->va_mask | AT_FSID)
3574 				vap->va_fsid = rp->r_attr.va_fsid;
3575 			if (vap->va_mask | AT_RDEV)
3576 				vap->va_rdev = rp->r_attr.va_rdev;
3577 			mutex_exit(&rp->r_statelock);
3578 			return (0);
3579 		}
3580 	}
3581 
3582 	/*
3583 	 * Only need to flush pages if asking for the mtime
3584 	 * and if there any dirty pages or any outstanding
3585 	 * asynchronous (write) requests for this file.
3586 	 */
3587 	if (vap->va_mask & AT_MTIME) {
3588 		rp = VTOR4(vp);
3589 		if (nfs4_has_pages(vp)) {
3590 			mutex_enter(&rp->r_statev4_lock);
3591 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3592 				mutex_exit(&rp->r_statev4_lock);
3593 				if (rp->r_flags & R4DIRTY ||
3594 				    rp->r_awcount > 0) {
3595 					mutex_enter(&rp->r_statelock);
3596 					rp->r_gcount++;
3597 					mutex_exit(&rp->r_statelock);
3598 					error =
3599 					    nfs4_putpage(vp, (u_offset_t)0,
3600 					    0, 0, cr, NULL);
3601 					mutex_enter(&rp->r_statelock);
3602 					if (error && (error == ENOSPC ||
3603 					    error == EDQUOT)) {
3604 						if (!rp->r_error)
3605 							rp->r_error = error;
3606 					}
3607 					if (--rp->r_gcount == 0)
3608 						cv_broadcast(&rp->r_cv);
3609 					mutex_exit(&rp->r_statelock);
3610 				}
3611 			} else {
3612 				mutex_exit(&rp->r_statev4_lock);
3613 			}
3614 		}
3615 	}
3616 	return (nfs4getattr(vp, vap, cr));
3617 }
3618 
3619 int
3620 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3621 {
3622 	/*
3623 	 * If these are the only two bits cleared
3624 	 * on the server then return 0 (OK) else
3625 	 * return 1 (BAD).
3626 	 */
3627 	on_client &= ~(S_ISUID|S_ISGID);
3628 	if (on_client == from_server)
3629 		return (0);
3630 	else
3631 		return (1);
3632 }
3633 
3634 /*ARGSUSED4*/
3635 static int
3636 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3637     caller_context_t *ct)
3638 {
3639 	if (vap->va_mask & AT_NOSET)
3640 		return (EINVAL);
3641 
3642 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3643 		return (EIO);
3644 
3645 	/*
3646 	 * Don't call secpolicy_vnode_setattr, the client cannot
3647 	 * use its cached attributes to make security decisions
3648 	 * as the server may be faking mode bits or mapping uid/gid.
3649 	 * Always just let the server to the checking.
3650 	 * If we provide the ability to remove basic priviledges
3651 	 * to setattr (e.g. basic without chmod) then we will
3652 	 * need to add a check here before calling the server.
3653 	 */
3654 
3655 	return (nfs4setattr(vp, vap, flags, cr, NULL));
3656 }
3657 
3658 /*
3659  * To replace the "guarded" version 3 setattr, we use two types of compound
3660  * setattr requests:
3661  * 1. The "normal" setattr, used when the size of the file isn't being
3662  *    changed - { Putfh <fh>; Setattr; Getattr }/
3663  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3664  *    with only ctime as the argument. If the server ctime differs from
3665  *    what is cached on the client, the verify will fail, but we would
3666  *    already have the ctime from the preceding getattr, so just set it
3667  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3668  *	Setattr; Getattr }.
3669  *
3670  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3671  * this setattr and NULL if they are not.
3672  */
3673 static int
3674 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3675     vsecattr_t *vsap)
3676 {
3677 	COMPOUND4args_clnt args;
3678 	COMPOUND4res_clnt res, *resp = NULL;
3679 	nfs4_ga_res_t *garp = NULL;
3680 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3681 	nfs_argop4 argop[5];
3682 	int verify_argop = -1;
3683 	int setattr_argop = 1;
3684 	nfs_resop4 *resop;
3685 	vattr_t va;
3686 	rnode4_t *rp;
3687 	int doqueue = 1;
3688 	uint_t mask = vap->va_mask;
3689 	mode_t omode;
3690 	vsecattr_t *vsp;
3691 	timestruc_t ctime;
3692 	bool_t needrecov = FALSE;
3693 	nfs4_recov_state_t recov_state;
3694 	nfs4_stateid_types_t sid_types;
3695 	stateid4 stateid;
3696 	hrtime_t t;
3697 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3698 	servinfo4_t *svp;
3699 	bitmap4 supp_attrs;
3700 
3701 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3702 	rp = VTOR4(vp);
3703 	nfs4_init_stateid_types(&sid_types);
3704 
3705 	/*
3706 	 * Only need to flush pages if there are any pages and
3707 	 * if the file is marked as dirty in some fashion.  The
3708 	 * file must be flushed so that we can accurately
3709 	 * determine the size of the file and the cached data
3710 	 * after the SETATTR returns.  A file is considered to
3711 	 * be dirty if it is either marked with R4DIRTY, has
3712 	 * outstanding i/o's active, or is mmap'd.  In this
3713 	 * last case, we can't tell whether there are dirty
3714 	 * pages, so we flush just to be sure.
3715 	 */
3716 	if (nfs4_has_pages(vp) &&
3717 	    ((rp->r_flags & R4DIRTY) ||
3718 	    rp->r_count > 0 ||
3719 	    rp->r_mapcnt > 0)) {
3720 		ASSERT(vp->v_type != VCHR);
3721 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr, NULL);
3722 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3723 			mutex_enter(&rp->r_statelock);
3724 			if (!rp->r_error)
3725 				rp->r_error = e.error;
3726 			mutex_exit(&rp->r_statelock);
3727 		}
3728 	}
3729 
3730 	if (mask & AT_SIZE) {
3731 		/*
3732 		 * Verification setattr compound for non-deleg AT_SIZE:
3733 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3734 		 * Set ctime local here (outside the do_again label)
3735 		 * so that subsequent retries (after failed VERIFY)
3736 		 * will use ctime from GETATTR results (from failed
3737 		 * verify compound) as VERIFY arg.
3738 		 * If file has delegation, then VERIFY(time_metadata)
3739 		 * is of little added value, so don't bother.
3740 		 */
3741 		mutex_enter(&rp->r_statev4_lock);
3742 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3743 		    rp->r_deleg_return_pending) {
3744 			numops = 5;
3745 			ctime = rp->r_attr.va_ctime;
3746 		}
3747 		mutex_exit(&rp->r_statev4_lock);
3748 	}
3749 
3750 	recov_state.rs_flags = 0;
3751 	recov_state.rs_num_retry_despite_err = 0;
3752 
3753 	args.ctag = TAG_SETATTR;
3754 do_again:
3755 recov_retry:
3756 	setattr_argop = numops - 2;
3757 
3758 	args.array = argop;
3759 	args.array_len = numops;
3760 
3761 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3762 	if (e.error)
3763 		return (e.error);
3764 
3765 
3766 	/* putfh target fh */
3767 	argop[0].argop = OP_CPUTFH;
3768 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3769 
3770 	if (numops == 5) {
3771 		/*
3772 		 * We only care about the ctime, but need to get mtime
3773 		 * and size for proper cache update.
3774 		 */
3775 		/* getattr */
3776 		argop[1].argop = OP_GETATTR;
3777 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3778 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3779 
3780 		/* verify - set later in loop */
3781 		verify_argop = 2;
3782 	}
3783 
3784 	/* setattr */
3785 	svp = rp->r_server;
3786 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3787 	supp_attrs = svp->sv_supp_attrs;
3788 	nfs_rw_exit(&svp->sv_lock);
3789 
3790 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3791 	    supp_attrs, &e.error, &sid_types);
3792 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3793 	if (e.error) {
3794 		/* req time field(s) overflow - return immediately */
3795 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3796 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3797 		    opsetattr.obj_attributes);
3798 		return (e.error);
3799 	}
3800 	omode = rp->r_attr.va_mode;
3801 
3802 	/* getattr */
3803 	argop[numops-1].argop = OP_GETATTR;
3804 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3805 	/*
3806 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3807 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3808 	 * used in updating the ACL cache.
3809 	 */
3810 	if (vsap != NULL)
3811 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3812 		    FATTR4_ACL_MASK;
3813 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3814 
3815 	/*
3816 	 * setattr iterates if the object size is set and the cached ctime
3817 	 * does not match the file ctime. In that case, verify the ctime first.
3818 	 */
3819 
3820 	do {
3821 		if (verify_argop != -1) {
3822 			/*
3823 			 * Verify that the ctime match before doing setattr.
3824 			 */
3825 			va.va_mask = AT_CTIME;
3826 			va.va_ctime = ctime;
3827 			svp = rp->r_server;
3828 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3829 			supp_attrs = svp->sv_supp_attrs;
3830 			nfs_rw_exit(&svp->sv_lock);
3831 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3832 			    OP_VERIFY, supp_attrs);
3833 			if (e.error) {
3834 				/* req time field(s) overflow - return */
3835 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3836 				    needrecov);
3837 				break;
3838 			}
3839 		}
3840 
3841 		doqueue = 1;
3842 
3843 		t = gethrtime();
3844 
3845 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3846 
3847 		/*
3848 		 * Purge the access cache and ACL cache if changing either the
3849 		 * owner of the file, the group owner, or the mode.  These may
3850 		 * change the access permissions of the file, so purge old
3851 		 * information and start over again.
3852 		 */
3853 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3854 			(void) nfs4_access_purge_rp(rp);
3855 			if (rp->r_secattr != NULL) {
3856 				mutex_enter(&rp->r_statelock);
3857 				vsp = rp->r_secattr;
3858 				rp->r_secattr = NULL;
3859 				mutex_exit(&rp->r_statelock);
3860 				if (vsp != NULL)
3861 					nfs4_acl_free_cache(vsp);
3862 			}
3863 		}
3864 
3865 		/*
3866 		 * If res.array_len == numops, then everything succeeded,
3867 		 * except for possibly the final getattr.  If only the
3868 		 * last getattr failed, give up, and don't try recovery.
3869 		 */
3870 		if (res.array_len == numops) {
3871 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3872 			    needrecov);
3873 			if (! e.error)
3874 				resp = &res;
3875 			break;
3876 		}
3877 
3878 		/*
3879 		 * if either rpc call failed or completely succeeded - done
3880 		 */
3881 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
3882 		if (e.error) {
3883 			PURGE_ATTRCACHE4(vp);
3884 			if (!needrecov) {
3885 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3886 				    needrecov);
3887 				break;
3888 			}
3889 		}
3890 
3891 		/*
3892 		 * Do proper retry for OLD_STATEID outside of the normal
3893 		 * recovery framework.
3894 		 */
3895 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3896 		    sid_types.cur_sid_type != SPEC_SID &&
3897 		    sid_types.cur_sid_type != NO_SID) {
3898 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3899 			    needrecov);
3900 			nfs4_save_stateid(&stateid, &sid_types);
3901 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3902 			    opsetattr.obj_attributes);
3903 			if (verify_argop != -1) {
3904 				nfs4args_verify_free(&argop[verify_argop]);
3905 				verify_argop = -1;
3906 			}
3907 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3908 			goto recov_retry;
3909 		}
3910 
3911 		if (needrecov) {
3912 			bool_t abort;
3913 
3914 			abort = nfs4_start_recovery(&e,
3915 			    VTOMI4(vp), vp, NULL, NULL, NULL,
3916 			    OP_SETATTR, NULL);
3917 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3918 			    needrecov);
3919 			/*
3920 			 * Do not retry if we failed with OLD_STATEID using
3921 			 * a special stateid.  This is done to avoid looping
3922 			 * with a broken server.
3923 			 */
3924 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3925 			    (sid_types.cur_sid_type == SPEC_SID ||
3926 			    sid_types.cur_sid_type == NO_SID))
3927 				abort = TRUE;
3928 			if (!e.error) {
3929 				if (res.status == NFS4ERR_BADOWNER)
3930 					nfs4_log_badowner(VTOMI4(vp),
3931 					    OP_SETATTR);
3932 
3933 				e.error = geterrno4(res.status);
3934 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3935 				    (caddr_t)&res);
3936 			}
3937 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3938 			    opsetattr.obj_attributes);
3939 			if (verify_argop != -1) {
3940 				nfs4args_verify_free(&argop[verify_argop]);
3941 				verify_argop = -1;
3942 			}
3943 			if (abort == FALSE) {
3944 				/*
3945 				 * Need to retry all possible stateids in
3946 				 * case the recovery error wasn't stateid
3947 				 * related or the stateids have become
3948 				 * stale (server reboot).
3949 				 */
3950 				nfs4_init_stateid_types(&sid_types);
3951 				goto recov_retry;
3952 			}
3953 			return (e.error);
3954 		}
3955 
3956 		/*
3957 		 * Need to call nfs4_end_op before nfs4getattr to
3958 		 * avoid potential nfs4_start_op deadlock. See RFE
3959 		 * 4777612.  Calls to nfs4_invalidate_pages() and
3960 		 * nfs4_purge_stale_fh() might also generate over the
3961 		 * wire calls which my cause nfs4_start_op() deadlock.
3962 		 */
3963 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3964 
3965 		/*
3966 		 * Check to update lease.
3967 		 */
3968 		resp = &res;
3969 		if (res.status == NFS4_OK) {
3970 			break;
3971 		}
3972 
3973 		/*
3974 		 * Check if verify failed to see if try again
3975 		 */
3976 		if ((verify_argop == -1) || (res.array_len != 3)) {
3977 			/*
3978 			 * can't continue...
3979 			 */
3980 			if (res.status == NFS4ERR_BADOWNER)
3981 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
3982 
3983 			e.error = geterrno4(res.status);
3984 		} else {
3985 			/*
3986 			 * When the verify request fails, the client ctime is
3987 			 * not in sync with the server. This is the same as
3988 			 * the version 3 "not synchronized" error, and we
3989 			 * handle it in a similar manner (XXX do we need to???).
3990 			 * Use the ctime returned in the first getattr for
3991 			 * the input to the next verify.
3992 			 * If we couldn't get the attributes, then we give up
3993 			 * because we can't complete the operation as required.
3994 			 */
3995 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
3996 		}
3997 		if (e.error) {
3998 			PURGE_ATTRCACHE4(vp);
3999 			nfs4_purge_stale_fh(e.error, vp, cr);
4000 		} else {
4001 			/*
4002 			 * retry with a new verify value
4003 			 */
4004 			ctime = garp->n4g_va.va_ctime;
4005 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4006 			resp = NULL;
4007 		}
4008 		if (!e.error) {
4009 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4010 			    opsetattr.obj_attributes);
4011 			if (verify_argop != -1) {
4012 				nfs4args_verify_free(&argop[verify_argop]);
4013 				verify_argop = -1;
4014 			}
4015 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4016 			goto do_again;
4017 		}
4018 	} while (!e.error);
4019 
4020 	if (e.error) {
4021 		/*
4022 		 * If we are here, rfs4call has an irrecoverable error - return
4023 		 */
4024 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4025 		    opsetattr.obj_attributes);
4026 		if (verify_argop != -1) {
4027 			nfs4args_verify_free(&argop[verify_argop]);
4028 			verify_argop = -1;
4029 		}
4030 		if (resp)
4031 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4032 		return (e.error);
4033 	}
4034 
4035 
4036 
4037 	/*
4038 	 * If changing the size of the file, invalidate
4039 	 * any local cached data which is no longer part
4040 	 * of the file.  We also possibly invalidate the
4041 	 * last page in the file.  We could use
4042 	 * pvn_vpzero(), but this would mark the page as
4043 	 * modified and require it to be written back to
4044 	 * the server for no particularly good reason.
4045 	 * This way, if we access it, then we bring it
4046 	 * back in.  A read should be cheaper than a
4047 	 * write.
4048 	 */
4049 	if (mask & AT_SIZE) {
4050 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
4051 	}
4052 
4053 	/* either no error or one of the postop getattr failed */
4054 
4055 	/*
4056 	 * XXX Perform a simplified version of wcc checking. Instead of
4057 	 * have another getattr to get pre-op, just purge cache if
4058 	 * any of the ops prior to and including the getattr failed.
4059 	 * If the getattr succeeded then update the attrcache accordingly.
4060 	 */
4061 
4062 	garp = NULL;
4063 	if (res.status == NFS4_OK) {
4064 		/*
4065 		 * Last getattr
4066 		 */
4067 		resop = &res.array[numops - 1];
4068 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4069 	}
4070 	/*
4071 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
4072 	 * rather than filling it.  See the function itself for details.
4073 	 */
4074 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4075 	if (garp != NULL) {
4076 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
4077 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
4078 			vs_ace4_destroy(&garp->n4g_vsa);
4079 		} else {
4080 			if (vsap != NULL) {
4081 				/*
4082 				 * The ACL was supposed to be set and to be
4083 				 * returned in the last getattr of this
4084 				 * compound, but for some reason the getattr
4085 				 * result doesn't contain the ACL.  In this
4086 				 * case, purge the ACL cache.
4087 				 */
4088 				if (rp->r_secattr != NULL) {
4089 					mutex_enter(&rp->r_statelock);
4090 					vsp = rp->r_secattr;
4091 					rp->r_secattr = NULL;
4092 					mutex_exit(&rp->r_statelock);
4093 					if (vsp != NULL)
4094 						nfs4_acl_free_cache(vsp);
4095 				}
4096 			}
4097 		}
4098 	}
4099 
4100 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4101 		/*
4102 		 * Set the size, rather than relying on getting it updated
4103 		 * via a GETATTR.  With delegations the client tries to
4104 		 * suppress GETATTR calls.
4105 		 */
4106 		mutex_enter(&rp->r_statelock);
4107 		rp->r_size = vap->va_size;
4108 		mutex_exit(&rp->r_statelock);
4109 	}
4110 
4111 	/*
4112 	 * Can free up request args and res
4113 	 */
4114 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4115 	    opsetattr.obj_attributes);
4116 	if (verify_argop != -1) {
4117 		nfs4args_verify_free(&argop[verify_argop]);
4118 		verify_argop = -1;
4119 	}
4120 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4121 
4122 	/*
4123 	 * Some servers will change the mode to clear the setuid
4124 	 * and setgid bits when changing the uid or gid.  The
4125 	 * client needs to compensate appropriately.
4126 	 */
4127 	if (mask & (AT_UID | AT_GID)) {
4128 		int terror, do_setattr;
4129 
4130 		do_setattr = 0;
4131 		va.va_mask = AT_MODE;
4132 		terror = nfs4getattr(vp, &va, cr);
4133 		if (!terror &&
4134 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4135 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4136 			va.va_mask = AT_MODE;
4137 			if (mask & AT_MODE) {
4138 				/*
4139 				 * We asked the mode to be changed and what
4140 				 * we just got from the server in getattr is
4141 				 * not what we wanted it to be, so set it now.
4142 				 */
4143 				va.va_mode = vap->va_mode;
4144 				do_setattr = 1;
4145 			} else {
4146 				/*
4147 				 * We did not ask the mode to be changed,
4148 				 * Check to see that the server just cleared
4149 				 * I_SUID and I_GUID from it. If not then
4150 				 * set mode to omode with UID/GID cleared.
4151 				 */
4152 				if (nfs4_compare_modes(va.va_mode, omode)) {
4153 					omode &= ~(S_ISUID|S_ISGID);
4154 					va.va_mode = omode;
4155 					do_setattr = 1;
4156 				}
4157 			}
4158 
4159 			if (do_setattr)
4160 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4161 		}
4162 	}
4163 
4164 	return (e.error);
4165 }
4166 
4167 /* ARGSUSED */
4168 static int
4169 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr, caller_context_t *ct)
4170 {
4171 	COMPOUND4args_clnt args;
4172 	COMPOUND4res_clnt res;
4173 	int doqueue;
4174 	uint32_t acc, resacc, argacc;
4175 	rnode4_t *rp;
4176 	cred_t *cred, *ncr, *ncrfree = NULL;
4177 	nfs4_access_type_t cacc;
4178 	int num_ops;
4179 	nfs_argop4 argop[3];
4180 	nfs_resop4 *resop;
4181 	bool_t needrecov = FALSE, do_getattr;
4182 	nfs4_recov_state_t recov_state;
4183 	int rpc_error;
4184 	hrtime_t t;
4185 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4186 	mntinfo4_t *mi = VTOMI4(vp);
4187 
4188 	if (nfs_zone() != mi->mi_zone)
4189 		return (EIO);
4190 
4191 	acc = 0;
4192 	if (mode & VREAD)
4193 		acc |= ACCESS4_READ;
4194 	if (mode & VWRITE) {
4195 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4196 			return (EROFS);
4197 		if (vp->v_type == VDIR)
4198 			acc |= ACCESS4_DELETE;
4199 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4200 	}
4201 	if (mode & VEXEC) {
4202 		if (vp->v_type == VDIR)
4203 			acc |= ACCESS4_LOOKUP;
4204 		else
4205 			acc |= ACCESS4_EXECUTE;
4206 	}
4207 
4208 	if (VTOR4(vp)->r_acache != NULL) {
4209 		e.error = nfs4_validate_caches(vp, cr);
4210 		if (e.error)
4211 			return (e.error);
4212 	}
4213 
4214 	rp = VTOR4(vp);
4215 	if (vp->v_type == VDIR)
4216 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4217 		    ACCESS4_EXTEND | ACCESS4_LOOKUP;
4218 	else
4219 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4220 		    ACCESS4_EXECUTE;
4221 	recov_state.rs_flags = 0;
4222 	recov_state.rs_num_retry_despite_err = 0;
4223 
4224 	cred = cr;
4225 	/*
4226 	 * ncr and ncrfree both initially
4227 	 * point to the memory area returned
4228 	 * by crnetadjust();
4229 	 * ncrfree not NULL when exiting means
4230 	 * that we need to release it
4231 	 */
4232 	ncr = crnetadjust(cred);
4233 	ncrfree = ncr;
4234 
4235 tryagain:
4236 	cacc = nfs4_access_check(rp, acc, cred);
4237 	if (cacc == NFS4_ACCESS_ALLOWED) {
4238 		if (ncrfree != NULL)
4239 			crfree(ncrfree);
4240 		return (0);
4241 	}
4242 	if (cacc == NFS4_ACCESS_DENIED) {
4243 		/*
4244 		 * If the cred can be adjusted, try again
4245 		 * with the new cred.
4246 		 */
4247 		if (ncr != NULL) {
4248 			cred = ncr;
4249 			ncr = NULL;
4250 			goto tryagain;
4251 		}
4252 		if (ncrfree != NULL)
4253 			crfree(ncrfree);
4254 		return (EACCES);
4255 	}
4256 
4257 recov_retry:
4258 	/*
4259 	 * Don't take with r_statev4_lock here. r_deleg_type could
4260 	 * change as soon as lock is released.  Since it is an int,
4261 	 * there is no atomicity issue.
4262 	 */
4263 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4264 	num_ops = do_getattr ? 3 : 2;
4265 
4266 	args.ctag = TAG_ACCESS;
4267 
4268 	args.array_len = num_ops;
4269 	args.array = argop;
4270 
4271 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4272 	    &recov_state, NULL)) {
4273 		if (ncrfree != NULL)
4274 			crfree(ncrfree);
4275 		return (e.error);
4276 	}
4277 
4278 	/* putfh target fh */
4279 	argop[0].argop = OP_CPUTFH;
4280 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4281 
4282 	/* access */
4283 	argop[1].argop = OP_ACCESS;
4284 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4285 
4286 	/* getattr */
4287 	if (do_getattr) {
4288 		argop[2].argop = OP_GETATTR;
4289 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4290 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4291 	}
4292 
4293 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4294 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4295 	    rnode4info(VTOR4(vp))));
4296 
4297 	doqueue = 1;
4298 	t = gethrtime();
4299 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4300 	rpc_error = e.error;
4301 
4302 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4303 	if (needrecov) {
4304 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4305 		    "nfs4_access: initiating recovery\n"));
4306 
4307 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4308 		    NULL, OP_ACCESS, NULL) == FALSE) {
4309 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4310 			    &recov_state, needrecov);
4311 			if (!e.error)
4312 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4313 				    (caddr_t)&res);
4314 			goto recov_retry;
4315 		}
4316 	}
4317 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4318 
4319 	if (e.error)
4320 		goto out;
4321 
4322 	if (res.status) {
4323 		e.error = geterrno4(res.status);
4324 		/*
4325 		 * This might generate over the wire calls throught
4326 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4327 		 * here to avoid a deadlock.
4328 		 */
4329 		nfs4_purge_stale_fh(e.error, vp, cr);
4330 		goto out;
4331 	}
4332 	resop = &res.array[1];	/* access res */
4333 
4334 	resacc = resop->nfs_resop4_u.opaccess.access;
4335 
4336 	if (do_getattr) {
4337 		resop++;	/* getattr res */
4338 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4339 		    t, cr, FALSE, NULL);
4340 	}
4341 
4342 	if (!e.error) {
4343 		nfs4_access_cache(rp, argacc, resacc, cred);
4344 		/*
4345 		 * we just cached results with cred; if cred is the
4346 		 * adjusted credentials from crnetadjust, we do not want
4347 		 * to release them before exiting: hence setting ncrfree
4348 		 * to NULL
4349 		 */
4350 		if (cred != cr)
4351 			ncrfree = NULL;
4352 		/* XXX check the supported bits too? */
4353 		if ((acc & resacc) != acc) {
4354 			/*
4355 			 * The following code implements the semantic
4356 			 * that a setuid root program has *at least* the
4357 			 * permissions of the user that is running the
4358 			 * program.  See rfs3call() for more portions
4359 			 * of the implementation of this functionality.
4360 			 */
4361 			/* XXX-LP */
4362 			if (ncr != NULL) {
4363 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4364 				    (caddr_t)&res);
4365 				cred = ncr;
4366 				ncr = NULL;
4367 				goto tryagain;
4368 			}
4369 			e.error = EACCES;
4370 		}
4371 	}
4372 
4373 out:
4374 	if (!rpc_error)
4375 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4376 
4377 	if (ncrfree != NULL)
4378 		crfree(ncrfree);
4379 
4380 	return (e.error);
4381 }
4382 
4383 /* ARGSUSED */
4384 static int
4385 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr, caller_context_t *ct)
4386 {
4387 	COMPOUND4args_clnt args;
4388 	COMPOUND4res_clnt res;
4389 	int doqueue;
4390 	rnode4_t *rp;
4391 	nfs_argop4 argop[3];
4392 	nfs_resop4 *resop;
4393 	READLINK4res *lr_res;
4394 	nfs4_ga_res_t *garp;
4395 	uint_t len;
4396 	char *linkdata;
4397 	bool_t needrecov = FALSE;
4398 	nfs4_recov_state_t recov_state;
4399 	hrtime_t t;
4400 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4401 
4402 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4403 		return (EIO);
4404 	/*
4405 	 * Can't readlink anything other than a symbolic link.
4406 	 */
4407 	if (vp->v_type != VLNK)
4408 		return (EINVAL);
4409 
4410 	rp = VTOR4(vp);
4411 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4412 		e.error = nfs4_validate_caches(vp, cr);
4413 		if (e.error)
4414 			return (e.error);
4415 		mutex_enter(&rp->r_statelock);
4416 		if (rp->r_symlink.contents != NULL) {
4417 			e.error = uiomove(rp->r_symlink.contents,
4418 			    rp->r_symlink.len, UIO_READ, uiop);
4419 			mutex_exit(&rp->r_statelock);
4420 			return (e.error);
4421 		}
4422 		mutex_exit(&rp->r_statelock);
4423 	}
4424 	recov_state.rs_flags = 0;
4425 	recov_state.rs_num_retry_despite_err = 0;
4426 
4427 recov_retry:
4428 	args.array_len = 3;
4429 	args.array = argop;
4430 	args.ctag = TAG_READLINK;
4431 
4432 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4433 	if (e.error) {
4434 		return (e.error);
4435 	}
4436 
4437 	/* 0. putfh symlink fh */
4438 	argop[0].argop = OP_CPUTFH;
4439 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4440 
4441 	/* 1. readlink */
4442 	argop[1].argop = OP_READLINK;
4443 
4444 	/* 2. getattr */
4445 	argop[2].argop = OP_GETATTR;
4446 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4447 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4448 
4449 	doqueue = 1;
4450 
4451 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4452 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4453 	    rnode4info(VTOR4(vp))));
4454 
4455 	t = gethrtime();
4456 
4457 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4458 
4459 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4460 	if (needrecov) {
4461 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4462 		    "nfs4_readlink: initiating recovery\n"));
4463 
4464 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4465 		    NULL, OP_READLINK, NULL) == FALSE) {
4466 			if (!e.error)
4467 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4468 				    (caddr_t)&res);
4469 
4470 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4471 			    needrecov);
4472 			goto recov_retry;
4473 		}
4474 	}
4475 
4476 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4477 
4478 	if (e.error)
4479 		return (e.error);
4480 
4481 	/*
4482 	 * There is an path in the code below which calls
4483 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4484 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4485 	 * here to avoid nfs4_start_op() deadlock.
4486 	 */
4487 
4488 	if (res.status && (res.array_len < args.array_len)) {
4489 		/*
4490 		 * either Putfh or Link failed
4491 		 */
4492 		e.error = geterrno4(res.status);
4493 		nfs4_purge_stale_fh(e.error, vp, cr);
4494 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4495 		return (e.error);
4496 	}
4497 
4498 	resop = &res.array[1];	/* readlink res */
4499 	lr_res = &resop->nfs_resop4_u.opreadlink;
4500 
4501 	/*
4502 	 * treat symlink names as data
4503 	 */
4504 	linkdata = utf8_to_str(&lr_res->link, &len, NULL);
4505 	if (linkdata != NULL) {
4506 		int uio_len = len - 1;
4507 		/* len includes null byte, which we won't uiomove */
4508 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4509 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4510 			mutex_enter(&rp->r_statelock);
4511 			if (rp->r_symlink.contents == NULL) {
4512 				rp->r_symlink.contents = linkdata;
4513 				rp->r_symlink.len = uio_len;
4514 				rp->r_symlink.size = len;
4515 				mutex_exit(&rp->r_statelock);
4516 			} else {
4517 				mutex_exit(&rp->r_statelock);
4518 				kmem_free(linkdata, len);
4519 			}
4520 		} else {
4521 			kmem_free(linkdata, len);
4522 		}
4523 	}
4524 	if (res.status == NFS4_OK) {
4525 		resop++;	/* getattr res */
4526 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4527 	}
4528 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4529 
4530 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4531 
4532 	/*
4533 	 * The over the wire error for attempting to readlink something
4534 	 * other than a symbolic link is ENXIO.  However, we need to
4535 	 * return EINVAL instead of ENXIO, so we map it here.
4536 	 */
4537 	return (e.error == ENXIO ? EINVAL : e.error);
4538 }
4539 
4540 /*
4541  * Flush local dirty pages to stable storage on the server.
4542  *
4543  * If FNODSYNC is specified, then there is nothing to do because
4544  * metadata changes are not cached on the client before being
4545  * sent to the server.
4546  */
4547 /* ARGSUSED */
4548 static int
4549 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
4550 {
4551 	int error;
4552 
4553 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4554 		return (0);
4555 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4556 		return (EIO);
4557 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4558 	if (!error)
4559 		error = VTOR4(vp)->r_error;
4560 	return (error);
4561 }
4562 
4563 /*
4564  * Weirdness: if the file was removed or the target of a rename
4565  * operation while it was open, it got renamed instead.  Here we
4566  * remove the renamed file.
4567  */
4568 /* ARGSUSED */
4569 void
4570 nfs4_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4571 {
4572 	rnode4_t *rp;
4573 
4574 	ASSERT(vp != DNLC_NO_VNODE);
4575 
4576 	rp = VTOR4(vp);
4577 
4578 	if (IS_SHADOW(vp, rp)) {
4579 		sv_inactive(vp);
4580 		return;
4581 	}
4582 
4583 	/*
4584 	 * If this is coming from the wrong zone, we let someone in the right
4585 	 * zone take care of it asynchronously.  We can get here due to
4586 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4587 	 * potentially turn into an expensive no-op if, for instance, v_count
4588 	 * gets incremented in the meantime, but it's still correct.
4589 	 */
4590 	if (nfs_zone() != VTOMI4(vp)->mi_zone) {
4591 		nfs4_async_inactive(vp, cr);
4592 		return;
4593 	}
4594 
4595 	/*
4596 	 * Some of the cleanup steps might require over-the-wire
4597 	 * operations.  Since VOP_INACTIVE can get called as a result of
4598 	 * other over-the-wire operations (e.g., an attribute cache update
4599 	 * can lead to a DNLC purge), doing those steps now would lead to a
4600 	 * nested call to the recovery framework, which can deadlock.  So
4601 	 * do any over-the-wire cleanups asynchronously, in a separate
4602 	 * thread.
4603 	 */
4604 
4605 	mutex_enter(&rp->r_os_lock);
4606 	mutex_enter(&rp->r_statelock);
4607 	mutex_enter(&rp->r_statev4_lock);
4608 
4609 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4610 		mutex_exit(&rp->r_statev4_lock);
4611 		mutex_exit(&rp->r_statelock);
4612 		mutex_exit(&rp->r_os_lock);
4613 		nfs4_async_inactive(vp, cr);
4614 		return;
4615 	}
4616 
4617 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4618 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4619 		mutex_exit(&rp->r_statev4_lock);
4620 		mutex_exit(&rp->r_statelock);
4621 		mutex_exit(&rp->r_os_lock);
4622 		nfs4_async_inactive(vp, cr);
4623 		return;
4624 	}
4625 
4626 	if (rp->r_unldvp != NULL) {
4627 		mutex_exit(&rp->r_statev4_lock);
4628 		mutex_exit(&rp->r_statelock);
4629 		mutex_exit(&rp->r_os_lock);
4630 		nfs4_async_inactive(vp, cr);
4631 		return;
4632 	}
4633 	mutex_exit(&rp->r_statev4_lock);
4634 	mutex_exit(&rp->r_statelock);
4635 	mutex_exit(&rp->r_os_lock);
4636 
4637 	rp4_addfree(rp, cr);
4638 }
4639 
4640 /*
4641  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4642  * various bits of state.  The caller must not refer to vp after this call.
4643  */
4644 
4645 void
4646 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4647 {
4648 	rnode4_t *rp = VTOR4(vp);
4649 	nfs4_recov_state_t recov_state;
4650 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4651 	vnode_t *unldvp;
4652 	char *unlname;
4653 	cred_t *unlcred;
4654 	COMPOUND4args_clnt args;
4655 	COMPOUND4res_clnt res, *resp;
4656 	nfs_argop4 argop[2];
4657 	int doqueue;
4658 #ifdef DEBUG
4659 	char *name;
4660 #endif
4661 
4662 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
4663 	ASSERT(!IS_SHADOW(vp, rp));
4664 
4665 #ifdef DEBUG
4666 	name = fn_name(VTOSV(vp)->sv_name);
4667 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4668 	    "release vnode %s", name));
4669 	kmem_free(name, MAXNAMELEN);
4670 #endif
4671 
4672 	if (vp->v_type == VREG) {
4673 		bool_t recov_failed = FALSE;
4674 
4675 		e.error = nfs4close_all(vp, cr);
4676 		if (e.error) {
4677 			/* Check to see if recovery failed */
4678 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4679 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4680 				recov_failed = TRUE;
4681 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4682 			if (!recov_failed) {
4683 				mutex_enter(&rp->r_statelock);
4684 				if (rp->r_flags & R4RECOVERR)
4685 					recov_failed = TRUE;
4686 				mutex_exit(&rp->r_statelock);
4687 			}
4688 			if (recov_failed) {
4689 				NFS4_DEBUG(nfs4_client_recov_debug,
4690 				    (CE_NOTE, "nfs4_inactive_otw: "
4691 				    "close failed (recovery failure)"));
4692 			}
4693 		}
4694 	}
4695 
4696 redo:
4697 	if (rp->r_unldvp == NULL) {
4698 		rp4_addfree(rp, cr);
4699 		return;
4700 	}
4701 
4702 	/*
4703 	 * Save the vnode pointer for the directory where the
4704 	 * unlinked-open file got renamed, then set it to NULL
4705 	 * to prevent another thread from getting here before
4706 	 * we're done with the remove.  While we have the
4707 	 * statelock, make local copies of the pertinent rnode
4708 	 * fields.  If we weren't to do this in an atomic way, the
4709 	 * the unl* fields could become inconsistent with respect
4710 	 * to each other due to a race condition between this
4711 	 * code and nfs_remove().  See bug report 1034328.
4712 	 */
4713 	mutex_enter(&rp->r_statelock);
4714 	if (rp->r_unldvp == NULL) {
4715 		mutex_exit(&rp->r_statelock);
4716 		rp4_addfree(rp, cr);
4717 		return;
4718 	}
4719 
4720 	unldvp = rp->r_unldvp;
4721 	rp->r_unldvp = NULL;
4722 	unlname = rp->r_unlname;
4723 	rp->r_unlname = NULL;
4724 	unlcred = rp->r_unlcred;
4725 	rp->r_unlcred = NULL;
4726 	mutex_exit(&rp->r_statelock);
4727 
4728 	/*
4729 	 * If there are any dirty pages left, then flush
4730 	 * them.  This is unfortunate because they just
4731 	 * may get thrown away during the remove operation,
4732 	 * but we have to do this for correctness.
4733 	 */
4734 	if (nfs4_has_pages(vp) &&
4735 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4736 		ASSERT(vp->v_type != VCHR);
4737 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, NULL);
4738 		if (e.error) {
4739 			mutex_enter(&rp->r_statelock);
4740 			if (!rp->r_error)
4741 				rp->r_error = e.error;
4742 			mutex_exit(&rp->r_statelock);
4743 		}
4744 	}
4745 
4746 	recov_state.rs_flags = 0;
4747 	recov_state.rs_num_retry_despite_err = 0;
4748 recov_retry_remove:
4749 	/*
4750 	 * Do the remove operation on the renamed file
4751 	 */
4752 	args.ctag = TAG_INACTIVE;
4753 
4754 	/*
4755 	 * Remove ops: putfh dir; remove
4756 	 */
4757 	args.array_len = 2;
4758 	args.array = argop;
4759 
4760 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4761 	if (e.error) {
4762 		kmem_free(unlname, MAXNAMELEN);
4763 		crfree(unlcred);
4764 		VN_RELE(unldvp);
4765 		/*
4766 		 * Try again; this time around r_unldvp will be NULL, so we'll
4767 		 * just call rp4_addfree() and return.
4768 		 */
4769 		goto redo;
4770 	}
4771 
4772 	/* putfh directory */
4773 	argop[0].argop = OP_CPUTFH;
4774 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4775 
4776 	/* remove */
4777 	argop[1].argop = OP_CREMOVE;
4778 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4779 
4780 	doqueue = 1;
4781 	resp = &res;
4782 
4783 #if 0 /* notyet */
4784 	/*
4785 	 * Can't do this yet.  We may be being called from
4786 	 * dnlc_purge_XXX while that routine is holding a
4787 	 * mutex lock to the nc_rele list.  The calls to
4788 	 * nfs3_cache_wcc_data may result in calls to
4789 	 * dnlc_purge_XXX.  This will result in a deadlock.
4790 	 */
4791 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4792 	if (e.error) {
4793 		PURGE_ATTRCACHE4(unldvp);
4794 		resp = NULL;
4795 	} else if (res.status) {
4796 		e.error = geterrno4(res.status);
4797 		PURGE_ATTRCACHE4(unldvp);
4798 		/*
4799 		 * This code is inactive right now
4800 		 * but if made active there should
4801 		 * be a nfs4_end_op() call before
4802 		 * nfs4_purge_stale_fh to avoid start_op()
4803 		 * deadlock. See BugId: 4948726
4804 		 */
4805 		nfs4_purge_stale_fh(error, unldvp, cr);
4806 	} else {
4807 		nfs_resop4 *resop;
4808 		REMOVE4res *rm_res;
4809 
4810 		resop = &res.array[1];
4811 		rm_res = &resop->nfs_resop4_u.opremove;
4812 		/*
4813 		 * Update directory cache attribute,
4814 		 * readdir and dnlc caches.
4815 		 */
4816 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4817 	}
4818 #else
4819 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4820 
4821 	PURGE_ATTRCACHE4(unldvp);
4822 #endif
4823 
4824 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4825 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4826 		    NULL, NULL, OP_REMOVE, NULL) == FALSE) {
4827 			if (!e.error)
4828 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4829 				    (caddr_t)&res);
4830 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4831 			    &recov_state, TRUE);
4832 			goto recov_retry_remove;
4833 		}
4834 	}
4835 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4836 
4837 	/*
4838 	 * Release stuff held for the remove
4839 	 */
4840 	VN_RELE(unldvp);
4841 	if (!e.error && resp)
4842 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4843 
4844 	kmem_free(unlname, MAXNAMELEN);
4845 	crfree(unlcred);
4846 	goto redo;
4847 }
4848 
4849 /*
4850  * Remote file system operations having to do with directory manipulation.
4851  */
4852 /* ARGSUSED3 */
4853 int
4854 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4855     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
4856     int *direntflags, pathname_t *realpnp)
4857 {
4858 	int error;
4859 	vnode_t *vp, *avp = NULL;
4860 	rnode4_t *drp;
4861 
4862 	*vpp = NULL;
4863 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4864 		return (EPERM);
4865 	/*
4866 	 * if LOOKUP_XATTR, must replace dvp (object) with
4867 	 * object's attrdir before continuing with lookup
4868 	 */
4869 	if (flags & LOOKUP_XATTR) {
4870 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4871 		if (error)
4872 			return (error);
4873 
4874 		dvp = avp;
4875 
4876 		/*
4877 		 * If lookup is for "", just return dvp now.  The attrdir
4878 		 * has already been activated (from nfs4lookup_xattr), and
4879 		 * the caller will RELE the original dvp -- not
4880 		 * the attrdir.  So, set vpp and return.
4881 		 * Currently, when the LOOKUP_XATTR flag is
4882 		 * passed to VOP_LOOKUP, the name is always empty, and
4883 		 * shortcircuiting here avoids 3 unneeded lock/unlock
4884 		 * pairs.
4885 		 *
4886 		 * If a non-empty name was provided, then it is the
4887 		 * attribute name, and it will be looked up below.
4888 		 */
4889 		if (*nm == '\0') {
4890 			*vpp = dvp;
4891 			return (0);
4892 		}
4893 
4894 		/*
4895 		 * The vfs layer never sends a name when asking for the
4896 		 * attrdir, so we should never get here (unless of course
4897 		 * name is passed at some time in future -- at which time
4898 		 * we'll blow up here).
4899 		 */
4900 		ASSERT(0);
4901 	}
4902 
4903 	drp = VTOR4(dvp);
4904 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4905 		return (EINTR);
4906 
4907 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
4908 	nfs_rw_exit(&drp->r_rwlock);
4909 
4910 	/*
4911 	 * If vnode is a device, create special vnode.
4912 	 */
4913 	if (!error && ISVDEV((*vpp)->v_type)) {
4914 		vp = *vpp;
4915 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
4916 		VN_RELE(vp);
4917 	}
4918 
4919 	return (error);
4920 }
4921 
4922 /* ARGSUSED */
4923 static int
4924 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
4925 {
4926 	int error;
4927 	rnode4_t *drp;
4928 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
4929 	mntinfo4_t *mi;
4930 
4931 	mi = VTOMI4(dvp);
4932 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR) &&
4933 	    !vfs_has_feature(mi->mi_vfsp, VFSFT_XVATTR))
4934 		return (EINVAL);
4935 
4936 	drp = VTOR4(dvp);
4937 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4938 		return (EINTR);
4939 
4940 	mutex_enter(&drp->r_statelock);
4941 	/*
4942 	 * If the server doesn't support xattrs just return EINVAL
4943 	 */
4944 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
4945 		mutex_exit(&drp->r_statelock);
4946 		nfs_rw_exit(&drp->r_rwlock);
4947 		return (EINVAL);
4948 	}
4949 
4950 	/*
4951 	 * If there is a cached xattr directory entry,
4952 	 * use it as long as the attributes are valid. If the
4953 	 * attributes are not valid, take the simple approach and
4954 	 * free the cached value and re-fetch a new value.
4955 	 *
4956 	 * We don't negative entry cache for now, if we did we
4957 	 * would need to check if the file has changed on every
4958 	 * lookup. But xattrs don't exist very often and failing
4959 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
4960 	 * so do an openattr over the wire for now.
4961 	 */
4962 	if (drp->r_xattr_dir != NULL) {
4963 		if (ATTRCACHE4_VALID(dvp)) {
4964 			VN_HOLD(drp->r_xattr_dir);
4965 			*vpp = drp->r_xattr_dir;
4966 			mutex_exit(&drp->r_statelock);
4967 			nfs_rw_exit(&drp->r_rwlock);
4968 			return (0);
4969 		}
4970 		VN_RELE(drp->r_xattr_dir);
4971 		drp->r_xattr_dir = NULL;
4972 	}
4973 	mutex_exit(&drp->r_statelock);
4974 
4975 	error = nfs4openattr(dvp, vpp, cflag, cr);
4976 
4977 	nfs_rw_exit(&drp->r_rwlock);
4978 
4979 	return (error);
4980 }
4981 
4982 static int
4983 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
4984 {
4985 	int error;
4986 	rnode4_t *drp;
4987 
4988 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
4989 
4990 	/*
4991 	 * If lookup is for "", just return dvp.  Don't need
4992 	 * to send it over the wire, look it up in the dnlc,
4993 	 * or perform any access checks.
4994 	 */
4995 	if (*nm == '\0') {
4996 		VN_HOLD(dvp);
4997 		*vpp = dvp;
4998 		return (0);
4999 	}
5000 
5001 	/*
5002 	 * Can't do lookups in non-directories.
5003 	 */
5004 	if (dvp->v_type != VDIR)
5005 		return (ENOTDIR);
5006 
5007 	/*
5008 	 * If lookup is for ".", just return dvp.  Don't need
5009 	 * to send it over the wire or look it up in the dnlc,
5010 	 * just need to check access.
5011 	 */
5012 	if (nm[0] == '.' && nm[1] == '\0') {
5013 		error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5014 		if (error)
5015 			return (error);
5016 		VN_HOLD(dvp);
5017 		*vpp = dvp;
5018 		return (0);
5019 	}
5020 
5021 	drp = VTOR4(dvp);
5022 	if (!(drp->r_flags & R4LOOKUP)) {
5023 		mutex_enter(&drp->r_statelock);
5024 		drp->r_flags |= R4LOOKUP;
5025 		mutex_exit(&drp->r_statelock);
5026 	}
5027 
5028 	*vpp = NULL;
5029 	/*
5030 	 * Lookup this name in the DNLC.  If there is no entry
5031 	 * lookup over the wire.
5032 	 */
5033 	if (!skipdnlc)
5034 		*vpp = dnlc_lookup(dvp, nm);
5035 	if (*vpp == NULL) {
5036 		/*
5037 		 * We need to go over the wire to lookup the name.
5038 		 */
5039 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
5040 	}
5041 
5042 	/*
5043 	 * We hit on the dnlc
5044 	 */
5045 	if (*vpp != DNLC_NO_VNODE ||
5046 	    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
5047 		/*
5048 		 * But our attrs may not be valid.
5049 		 */
5050 		if (ATTRCACHE4_VALID(dvp)) {
5051 			error = nfs4_waitfor_purge_complete(dvp);
5052 			if (error) {
5053 				VN_RELE(*vpp);
5054 				*vpp = NULL;
5055 				return (error);
5056 			}
5057 
5058 			/*
5059 			 * If after the purge completes, check to make sure
5060 			 * our attrs are still valid.
5061 			 */
5062 			if (ATTRCACHE4_VALID(dvp)) {
5063 				/*
5064 				 * If we waited for a purge we may have
5065 				 * lost our vnode so look it up again.
5066 				 */
5067 				VN_RELE(*vpp);
5068 				*vpp = dnlc_lookup(dvp, nm);
5069 				if (*vpp == NULL)
5070 					return (nfs4lookupnew_otw(dvp,
5071 					    nm, vpp, cr));
5072 
5073 				/*
5074 				 * The access cache should almost always hit
5075 				 */
5076 				error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5077 
5078 				if (error) {
5079 					VN_RELE(*vpp);
5080 					*vpp = NULL;
5081 					return (error);
5082 				}
5083 				if (*vpp == DNLC_NO_VNODE) {
5084 					VN_RELE(*vpp);
5085 					*vpp = NULL;
5086 					return (ENOENT);
5087 				}
5088 				return (0);
5089 			}
5090 		}
5091 	}
5092 
5093 	ASSERT(*vpp != NULL);
5094 
5095 	/*
5096 	 * We may have gotten here we have one of the following cases:
5097 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5098 	 *		need to validate them.
5099 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5100 	 *		must validate.
5101 	 *
5102 	 * Go to the server and check if the directory has changed, if
5103 	 * it hasn't we are done and can use the dnlc entry.
5104 	 */
5105 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5106 }
5107 
5108 /*
5109  * Go to the server and check if the directory has changed, if
5110  * it hasn't we are done and can use the dnlc entry.  If it
5111  * has changed we get a new copy of its attributes and check
5112  * the access for VEXEC, then relookup the filename and
5113  * get its filehandle and attributes.
5114  *
5115  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5116  *	if the NVERIFY failed we must
5117  *		purge the caches
5118  *		cache new attributes (will set r_time_attr_inval)
5119  *		cache new access
5120  *		recheck VEXEC access
5121  *		add name to dnlc, possibly negative
5122  *		if LOOKUP succeeded
5123  *			cache new attributes
5124  *	else
5125  *		set a new r_time_attr_inval for dvp
5126  *		check to make sure we have access
5127  *
5128  * The vpp returned is the vnode passed in if the directory is valid,
5129  * a new vnode if successful lookup, or NULL on error.
5130  */
5131 static int
5132 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5133 {
5134 	COMPOUND4args_clnt args;
5135 	COMPOUND4res_clnt res;
5136 	fattr4 *ver_fattr;
5137 	fattr4_change dchange;
5138 	int32_t *ptr;
5139 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5140 	nfs_argop4 *argop;
5141 	int doqueue;
5142 	mntinfo4_t *mi;
5143 	nfs4_recov_state_t recov_state;
5144 	hrtime_t t;
5145 	int isdotdot;
5146 	vnode_t *nvp;
5147 	nfs_fh4 *fhp;
5148 	nfs4_sharedfh_t *sfhp;
5149 	nfs4_access_type_t cacc;
5150 	rnode4_t *nrp;
5151 	rnode4_t *drp = VTOR4(dvp);
5152 	nfs4_ga_res_t *garp = NULL;
5153 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5154 
5155 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5156 	ASSERT(nm != NULL);
5157 	ASSERT(nm[0] != '\0');
5158 	ASSERT(dvp->v_type == VDIR);
5159 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5160 	ASSERT(*vpp != NULL);
5161 
5162 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5163 		isdotdot = 1;
5164 		args.ctag = TAG_LOOKUP_VPARENT;
5165 	} else {
5166 		/*
5167 		 * If dvp were a stub, it should have triggered and caused
5168 		 * a mount for us to get this far.
5169 		 */
5170 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5171 
5172 		isdotdot = 0;
5173 		args.ctag = TAG_LOOKUP_VALID;
5174 	}
5175 
5176 	mi = VTOMI4(dvp);
5177 	recov_state.rs_flags = 0;
5178 	recov_state.rs_num_retry_despite_err = 0;
5179 
5180 	nvp = NULL;
5181 
5182 	/* Save the original mount point security information */
5183 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5184 
5185 recov_retry:
5186 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5187 	    &recov_state, NULL);
5188 	if (e.error) {
5189 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5190 		VN_RELE(*vpp);
5191 		*vpp = NULL;
5192 		return (e.error);
5193 	}
5194 
5195 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5196 
5197 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5198 	args.array_len = 7;
5199 	args.array = argop;
5200 
5201 	/* 0. putfh file */
5202 	argop[0].argop = OP_CPUTFH;
5203 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5204 
5205 	/* 1. nverify the change info */
5206 	argop[1].argop = OP_NVERIFY;
5207 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5208 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5209 	ver_fattr->attrlist4 = (char *)&dchange;
5210 	ptr = (int32_t *)&dchange;
5211 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5212 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5213 
5214 	/* 2. getattr directory */
5215 	argop[2].argop = OP_GETATTR;
5216 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5217 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5218 
5219 	/* 3. access directory */
5220 	argop[3].argop = OP_ACCESS;
5221 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5222 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5223 
5224 	/* 4. lookup name */
5225 	if (isdotdot) {
5226 		argop[4].argop = OP_LOOKUPP;
5227 	} else {
5228 		argop[4].argop = OP_CLOOKUP;
5229 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5230 	}
5231 
5232 	/* 5. resulting file handle */
5233 	argop[5].argop = OP_GETFH;
5234 
5235 	/* 6. resulting file attributes */
5236 	argop[6].argop = OP_GETATTR;
5237 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5238 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5239 
5240 	doqueue = 1;
5241 	t = gethrtime();
5242 
5243 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5244 
5245 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5246 		/*
5247 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5248 		 * from this thread, do not go thru the recovery thread since
5249 		 * we need the nm information.
5250 		 *
5251 		 * Not doing dotdot case because there is no specification
5252 		 * for (PUTFH, SECINFO "..") yet.
5253 		 */
5254 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5255 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5256 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5257 				    &recov_state, FALSE);
5258 			else
5259 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5260 				    &recov_state, TRUE);
5261 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5262 			kmem_free(argop, argoplist_size);
5263 			if (!e.error)
5264 				goto recov_retry;
5265 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5266 			VN_RELE(*vpp);
5267 			*vpp = NULL;
5268 			return (e.error);
5269 		}
5270 
5271 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5272 		    OP_LOOKUP, NULL) == FALSE) {
5273 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5274 			    &recov_state, TRUE);
5275 
5276 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5277 			kmem_free(argop, argoplist_size);
5278 			goto recov_retry;
5279 		}
5280 	}
5281 
5282 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5283 
5284 	if (e.error || res.array_len == 0) {
5285 		/*
5286 		 * If e.error isn't set, then reply has no ops (or we couldn't
5287 		 * be here).  The only legal way to reply without an op array
5288 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5289 		 * be in the reply for all other status values.
5290 		 *
5291 		 * For valid replies without an ops array, return ENOTSUP
5292 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5293 		 * return EIO -- don't trust status.
5294 		 */
5295 		if (e.error == 0)
5296 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5297 			    ENOTSUP : EIO;
5298 		VN_RELE(*vpp);
5299 		*vpp = NULL;
5300 		kmem_free(argop, argoplist_size);
5301 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5302 		return (e.error);
5303 	}
5304 
5305 	if (res.status != NFS4ERR_SAME) {
5306 		e.error = geterrno4(res.status);
5307 
5308 		/*
5309 		 * The NVERIFY "failed" so the directory has changed
5310 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5311 		 * cleanly.
5312 		 */
5313 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5314 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5315 			nfs4_purge_stale_fh(e.error, dvp, cr);
5316 			VN_RELE(*vpp);
5317 			*vpp = NULL;
5318 			goto exit;
5319 		}
5320 
5321 		/*
5322 		 * We know the NVERIFY "failed" so we must:
5323 		 *	purge the caches (access and indirectly dnlc if needed)
5324 		 */
5325 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5326 
5327 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5328 			nfs4_purge_stale_fh(e.error, dvp, cr);
5329 			VN_RELE(*vpp);
5330 			*vpp = NULL;
5331 			goto exit;
5332 		}
5333 
5334 		/*
5335 		 * Install new cached attributes for the directory
5336 		 */
5337 		nfs4_attr_cache(dvp,
5338 		    &res.array[2].nfs_resop4_u.opgetattr.ga_res,
5339 		    t, cr, FALSE, NULL);
5340 
5341 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5342 			nfs4_purge_stale_fh(e.error, dvp, cr);
5343 			VN_RELE(*vpp);
5344 			*vpp = NULL;
5345 			e.error = geterrno4(res.status);
5346 			goto exit;
5347 		}
5348 
5349 		/*
5350 		 * Now we know the directory is valid,
5351 		 * cache new directory access
5352 		 */
5353 		nfs4_access_cache(drp,
5354 		    args.array[3].nfs_argop4_u.opaccess.access,
5355 		    res.array[3].nfs_resop4_u.opaccess.access, cr);
5356 
5357 		/*
5358 		 * recheck VEXEC access
5359 		 */
5360 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5361 		if (cacc != NFS4_ACCESS_ALLOWED) {
5362 			/*
5363 			 * Directory permissions might have been revoked
5364 			 */
5365 			if (cacc == NFS4_ACCESS_DENIED) {
5366 				e.error = EACCES;
5367 				VN_RELE(*vpp);
5368 				*vpp = NULL;
5369 				goto exit;
5370 			}
5371 
5372 			/*
5373 			 * Somehow we must not have asked for enough
5374 			 * so try a singleton ACCESS, should never happen.
5375 			 */
5376 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5377 			if (e.error) {
5378 				VN_RELE(*vpp);
5379 				*vpp = NULL;
5380 				goto exit;
5381 			}
5382 		}
5383 
5384 		e.error = geterrno4(res.status);
5385 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5386 			/*
5387 			 * The lookup failed, probably no entry
5388 			 */
5389 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5390 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5391 			} else {
5392 				/*
5393 				 * Might be some other error, so remove
5394 				 * the dnlc entry to make sure we start all
5395 				 * over again, next time.
5396 				 */
5397 				dnlc_remove(dvp, nm);
5398 			}
5399 			VN_RELE(*vpp);
5400 			*vpp = NULL;
5401 			goto exit;
5402 		}
5403 
5404 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5405 			/*
5406 			 * The file exists but we can't get its fh for
5407 			 * some unknown reason.  Remove it from the dnlc
5408 			 * and error out to be safe.
5409 			 */
5410 			dnlc_remove(dvp, nm);
5411 			VN_RELE(*vpp);
5412 			*vpp = NULL;
5413 			goto exit;
5414 		}
5415 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5416 		if (fhp->nfs_fh4_len == 0) {
5417 			/*
5418 			 * The file exists but a bogus fh
5419 			 * some unknown reason.  Remove it from the dnlc
5420 			 * and error out to be safe.
5421 			 */
5422 			e.error = ENOENT;
5423 			dnlc_remove(dvp, nm);
5424 			VN_RELE(*vpp);
5425 			*vpp = NULL;
5426 			goto exit;
5427 		}
5428 		sfhp = sfh4_get(fhp, mi);
5429 
5430 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5431 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5432 
5433 		/*
5434 		 * Make the new rnode
5435 		 */
5436 		if (isdotdot) {
5437 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5438 			if (e.error) {
5439 				sfh4_rele(&sfhp);
5440 				VN_RELE(*vpp);
5441 				*vpp = NULL;
5442 				goto exit;
5443 			}
5444 			/*
5445 			 * XXX if nfs4_make_dotdot uses an existing rnode
5446 			 * XXX it doesn't update the attributes.
5447 			 * XXX for now just save them again to save an OTW
5448 			 */
5449 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5450 		} else {
5451 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5452 			    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5453 			/*
5454 			 * If v_type == VNON, then garp was NULL because
5455 			 * the last op in the compound failed and makenfs4node
5456 			 * could not find the vnode for sfhp. It created
5457 			 * a new vnode, so we have nothing to purge here.
5458 			 */
5459 			if (nvp->v_type == VNON) {
5460 				vattr_t vattr;
5461 
5462 				vattr.va_mask = AT_TYPE;
5463 				/*
5464 				 * N.B. We've already called nfs4_end_fop above.
5465 				 */
5466 				e.error = nfs4getattr(nvp, &vattr, cr);
5467 				if (e.error) {
5468 					sfh4_rele(&sfhp);
5469 					VN_RELE(*vpp);
5470 					*vpp = NULL;
5471 					VN_RELE(nvp);
5472 					goto exit;
5473 				}
5474 				nvp->v_type = vattr.va_type;
5475 			}
5476 		}
5477 		sfh4_rele(&sfhp);
5478 
5479 		nrp = VTOR4(nvp);
5480 		mutex_enter(&nrp->r_statev4_lock);
5481 		if (!nrp->created_v4) {
5482 			mutex_exit(&nrp->r_statev4_lock);
5483 			dnlc_update(dvp, nm, nvp);
5484 		} else
5485 			mutex_exit(&nrp->r_statev4_lock);
5486 
5487 		VN_RELE(*vpp);
5488 		*vpp = nvp;
5489 	} else {
5490 		hrtime_t now;
5491 		hrtime_t delta = 0;
5492 
5493 		e.error = 0;
5494 
5495 		/*
5496 		 * Because the NVERIFY "succeeded" we know that the
5497 		 * directory attributes are still valid
5498 		 * so update r_time_attr_inval
5499 		 */
5500 		now = gethrtime();
5501 		mutex_enter(&drp->r_statelock);
5502 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5503 			delta = now - drp->r_time_attr_saved;
5504 			if (delta < mi->mi_acdirmin)
5505 				delta = mi->mi_acdirmin;
5506 			else if (delta > mi->mi_acdirmax)
5507 				delta = mi->mi_acdirmax;
5508 		}
5509 		drp->r_time_attr_inval = now + delta;
5510 		mutex_exit(&drp->r_statelock);
5511 		dnlc_update(dvp, nm, *vpp);
5512 
5513 		/*
5514 		 * Even though we have a valid directory attr cache
5515 		 * and dnlc entry, we may not have access.
5516 		 * This should almost always hit the cache.
5517 		 */
5518 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5519 		if (e.error) {
5520 			VN_RELE(*vpp);
5521 			*vpp = NULL;
5522 		}
5523 
5524 		if (*vpp == DNLC_NO_VNODE) {
5525 			VN_RELE(*vpp);
5526 			*vpp = NULL;
5527 			e.error = ENOENT;
5528 		}
5529 	}
5530 
5531 exit:
5532 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5533 	kmem_free(argop, argoplist_size);
5534 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5535 	return (e.error);
5536 }
5537 
5538 /*
5539  * We need to go over the wire to lookup the name, but
5540  * while we are there verify the directory has not
5541  * changed but if it has, get new attributes and check access
5542  *
5543  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5544  *					NVERIFY GETATTR ACCESS
5545  *
5546  * With the results:
5547  *	if the NVERIFY failed we must purge the caches, add new attributes,
5548  *		and cache new access.
5549  *	set a new r_time_attr_inval
5550  *	add name to dnlc, possibly negative
5551  *	if LOOKUP succeeded
5552  *		cache new attributes
5553  */
5554 static int
5555 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5556 {
5557 	COMPOUND4args_clnt args;
5558 	COMPOUND4res_clnt res;
5559 	fattr4 *ver_fattr;
5560 	fattr4_change dchange;
5561 	int32_t *ptr;
5562 	nfs4_ga_res_t *garp = NULL;
5563 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5564 	nfs_argop4 *argop;
5565 	int doqueue;
5566 	mntinfo4_t *mi;
5567 	nfs4_recov_state_t recov_state;
5568 	hrtime_t t;
5569 	int isdotdot;
5570 	vnode_t *nvp;
5571 	nfs_fh4 *fhp;
5572 	nfs4_sharedfh_t *sfhp;
5573 	nfs4_access_type_t cacc;
5574 	rnode4_t *nrp;
5575 	rnode4_t *drp = VTOR4(dvp);
5576 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5577 
5578 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5579 	ASSERT(nm != NULL);
5580 	ASSERT(nm[0] != '\0');
5581 	ASSERT(dvp->v_type == VDIR);
5582 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5583 	ASSERT(*vpp == NULL);
5584 
5585 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5586 		isdotdot = 1;
5587 		args.ctag = TAG_LOOKUP_PARENT;
5588 	} else {
5589 		/*
5590 		 * If dvp were a stub, it should have triggered and caused
5591 		 * a mount for us to get this far.
5592 		 */
5593 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5594 
5595 		isdotdot = 0;
5596 		args.ctag = TAG_LOOKUP;
5597 	}
5598 
5599 	mi = VTOMI4(dvp);
5600 	recov_state.rs_flags = 0;
5601 	recov_state.rs_num_retry_despite_err = 0;
5602 
5603 	nvp = NULL;
5604 
5605 	/* Save the original mount point security information */
5606 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5607 
5608 recov_retry:
5609 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5610 	    &recov_state, NULL);
5611 	if (e.error) {
5612 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5613 		return (e.error);
5614 	}
5615 
5616 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5617 
5618 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5619 	args.array_len = 9;
5620 	args.array = argop;
5621 
5622 	/* 0. putfh file */
5623 	argop[0].argop = OP_CPUTFH;
5624 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5625 
5626 	/* 1. savefh for the nverify */
5627 	argop[1].argop = OP_SAVEFH;
5628 
5629 	/* 2. lookup name */
5630 	if (isdotdot) {
5631 		argop[2].argop = OP_LOOKUPP;
5632 	} else {
5633 		argop[2].argop = OP_CLOOKUP;
5634 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5635 	}
5636 
5637 	/* 3. resulting file handle */
5638 	argop[3].argop = OP_GETFH;
5639 
5640 	/* 4. resulting file attributes */
5641 	argop[4].argop = OP_GETATTR;
5642 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5643 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5644 
5645 	/* 5. restorefh back the directory for the nverify */
5646 	argop[5].argop = OP_RESTOREFH;
5647 
5648 	/* 6. nverify the change info */
5649 	argop[6].argop = OP_NVERIFY;
5650 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5651 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5652 	ver_fattr->attrlist4 = (char *)&dchange;
5653 	ptr = (int32_t *)&dchange;
5654 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5655 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5656 
5657 	/* 7. getattr directory */
5658 	argop[7].argop = OP_GETATTR;
5659 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5660 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5661 
5662 	/* 8. access directory */
5663 	argop[8].argop = OP_ACCESS;
5664 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5665 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5666 
5667 	doqueue = 1;
5668 	t = gethrtime();
5669 
5670 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5671 
5672 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5673 		/*
5674 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5675 		 * from this thread, do not go thru the recovery thread since
5676 		 * we need the nm information.
5677 		 *
5678 		 * Not doing dotdot case because there is no specification
5679 		 * for (PUTFH, SECINFO "..") yet.
5680 		 */
5681 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5682 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5683 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5684 				    &recov_state, FALSE);
5685 			else
5686 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5687 				    &recov_state, TRUE);
5688 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5689 			kmem_free(argop, argoplist_size);
5690 			if (!e.error)
5691 				goto recov_retry;
5692 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5693 			return (e.error);
5694 		}
5695 
5696 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5697 		    OP_LOOKUP, NULL) == FALSE) {
5698 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5699 			    &recov_state, TRUE);
5700 
5701 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5702 			kmem_free(argop, argoplist_size);
5703 			goto recov_retry;
5704 		}
5705 	}
5706 
5707 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5708 
5709 	if (e.error || res.array_len == 0) {
5710 		/*
5711 		 * If e.error isn't set, then reply has no ops (or we couldn't
5712 		 * be here).  The only legal way to reply without an op array
5713 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5714 		 * be in the reply for all other status values.
5715 		 *
5716 		 * For valid replies without an ops array, return ENOTSUP
5717 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5718 		 * return EIO -- don't trust status.
5719 		 */
5720 		if (e.error == 0)
5721 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5722 			    ENOTSUP : EIO;
5723 
5724 		kmem_free(argop, argoplist_size);
5725 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5726 		return (e.error);
5727 	}
5728 
5729 	e.error = geterrno4(res.status);
5730 
5731 	/*
5732 	 * The PUTFH and SAVEFH may have failed.
5733 	 */
5734 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5735 	    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5736 		nfs4_purge_stale_fh(e.error, dvp, cr);
5737 		goto exit;
5738 	}
5739 
5740 	/*
5741 	 * Check if the file exists, if it does delay entering
5742 	 * into the dnlc until after we update the directory
5743 	 * attributes so we don't cause it to get purged immediately.
5744 	 */
5745 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5746 		/*
5747 		 * The lookup failed, probably no entry
5748 		 */
5749 		if (e.error == ENOENT && nfs4_lookup_neg_cache)
5750 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5751 		goto exit;
5752 	}
5753 
5754 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5755 		/*
5756 		 * The file exists but we can't get its fh for
5757 		 * some unknown reason. Error out to be safe.
5758 		 */
5759 		goto exit;
5760 	}
5761 
5762 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5763 	if (fhp->nfs_fh4_len == 0) {
5764 		/*
5765 		 * The file exists but a bogus fh
5766 		 * some unknown reason.  Error out to be safe.
5767 		 */
5768 		e.error = EIO;
5769 		goto exit;
5770 	}
5771 	sfhp = sfh4_get(fhp, mi);
5772 
5773 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5774 		sfh4_rele(&sfhp);
5775 		e.error = EIO;
5776 		goto exit;
5777 	}
5778 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5779 
5780 	/*
5781 	 * The RESTOREFH may have failed
5782 	 */
5783 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5784 		sfh4_rele(&sfhp);
5785 		e.error = EIO;
5786 		goto exit;
5787 	}
5788 
5789 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5790 		/*
5791 		 * First make sure the NVERIFY failed as we expected,
5792 		 * if it didn't then be conservative and error out
5793 		 * as we can't trust the directory.
5794 		 */
5795 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5796 			sfh4_rele(&sfhp);
5797 			e.error = EIO;
5798 			goto exit;
5799 		}
5800 
5801 		/*
5802 		 * We know the NVERIFY "failed" so the directory has changed,
5803 		 * so we must:
5804 		 *	purge the caches (access and indirectly dnlc if needed)
5805 		 */
5806 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5807 
5808 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5809 			sfh4_rele(&sfhp);
5810 			goto exit;
5811 		}
5812 		nfs4_attr_cache(dvp,
5813 		    &res.array[7].nfs_resop4_u.opgetattr.ga_res,
5814 		    t, cr, FALSE, NULL);
5815 
5816 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5817 			nfs4_purge_stale_fh(e.error, dvp, cr);
5818 			sfh4_rele(&sfhp);
5819 			e.error = geterrno4(res.status);
5820 			goto exit;
5821 		}
5822 
5823 		/*
5824 		 * Now we know the directory is valid,
5825 		 * cache new directory access
5826 		 */
5827 		nfs4_access_cache(drp,
5828 		    args.array[8].nfs_argop4_u.opaccess.access,
5829 		    res.array[8].nfs_resop4_u.opaccess.access, cr);
5830 
5831 		/*
5832 		 * recheck VEXEC access
5833 		 */
5834 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5835 		if (cacc != NFS4_ACCESS_ALLOWED) {
5836 			/*
5837 			 * Directory permissions might have been revoked
5838 			 */
5839 			if (cacc == NFS4_ACCESS_DENIED) {
5840 				sfh4_rele(&sfhp);
5841 				e.error = EACCES;
5842 				goto exit;
5843 			}
5844 
5845 			/*
5846 			 * Somehow we must not have asked for enough
5847 			 * so try a singleton ACCESS should never happen
5848 			 */
5849 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5850 			if (e.error) {
5851 				sfh4_rele(&sfhp);
5852 				goto exit;
5853 			}
5854 		}
5855 
5856 		e.error = geterrno4(res.status);
5857 	} else {
5858 		hrtime_t now;
5859 		hrtime_t delta = 0;
5860 
5861 		e.error = 0;
5862 
5863 		/*
5864 		 * Because the NVERIFY "succeeded" we know that the
5865 		 * directory attributes are still valid
5866 		 * so update r_time_attr_inval
5867 		 */
5868 		now = gethrtime();
5869 		mutex_enter(&drp->r_statelock);
5870 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5871 			delta = now - drp->r_time_attr_saved;
5872 			if (delta < mi->mi_acdirmin)
5873 				delta = mi->mi_acdirmin;
5874 			else if (delta > mi->mi_acdirmax)
5875 				delta = mi->mi_acdirmax;
5876 		}
5877 		drp->r_time_attr_inval = now + delta;
5878 		mutex_exit(&drp->r_statelock);
5879 
5880 		/*
5881 		 * Even though we have a valid directory attr cache,
5882 		 * we may not have access.
5883 		 * This should almost always hit the cache.
5884 		 */
5885 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5886 		if (e.error) {
5887 			sfh4_rele(&sfhp);
5888 			goto exit;
5889 		}
5890 	}
5891 
5892 	/*
5893 	 * Now we have successfully completed the lookup, if the
5894 	 * directory has changed we now have the valid attributes.
5895 	 * We also know we have directory access.
5896 	 * Create the new rnode and insert it in the dnlc.
5897 	 */
5898 	if (isdotdot) {
5899 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5900 		if (e.error) {
5901 			sfh4_rele(&sfhp);
5902 			goto exit;
5903 		}
5904 		/*
5905 		 * XXX if nfs4_make_dotdot uses an existing rnode
5906 		 * XXX it doesn't update the attributes.
5907 		 * XXX for now just save them again to save an OTW
5908 		 */
5909 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5910 	} else {
5911 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5912 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5913 	}
5914 	sfh4_rele(&sfhp);
5915 
5916 	nrp = VTOR4(nvp);
5917 	mutex_enter(&nrp->r_statev4_lock);
5918 	if (!nrp->created_v4) {
5919 		mutex_exit(&nrp->r_statev4_lock);
5920 		dnlc_update(dvp, nm, nvp);
5921 	} else
5922 		mutex_exit(&nrp->r_statev4_lock);
5923 
5924 	*vpp = nvp;
5925 
5926 exit:
5927 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5928 	kmem_free(argop, argoplist_size);
5929 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5930 	return (e.error);
5931 }
5932 
5933 #ifdef DEBUG
5934 void
5935 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
5936 {
5937 	uint_t i, len;
5938 	zoneid_t zoneid = getzoneid();
5939 	char *s;
5940 
5941 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
5942 	for (i = 0; i < argcnt; i++) {
5943 		nfs_argop4 *op = &argbase[i];
5944 		switch (op->argop) {
5945 		case OP_CPUTFH:
5946 		case OP_PUTFH:
5947 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
5948 			break;
5949 		case OP_PUTROOTFH:
5950 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
5951 			break;
5952 		case OP_CLOOKUP:
5953 			s = op->nfs_argop4_u.opclookup.cname;
5954 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5955 			break;
5956 		case OP_LOOKUP:
5957 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
5958 			    &len, NULL);
5959 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5960 			kmem_free(s, len);
5961 			break;
5962 		case OP_LOOKUPP:
5963 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
5964 			break;
5965 		case OP_GETFH:
5966 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
5967 			break;
5968 		case OP_GETATTR:
5969 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
5970 			break;
5971 		case OP_OPENATTR:
5972 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
5973 			break;
5974 		default:
5975 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
5976 			    op->argop);
5977 			break;
5978 		}
5979 	}
5980 }
5981 #endif
5982 
5983 /*
5984  * nfs4lookup_setup - constructs a multi-lookup compound request.
5985  *
5986  * Given the path "nm1/nm2/.../nmn", the following compound requests
5987  * may be created:
5988  *
5989  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
5990  * is faster, for now.
5991  *
5992  * l4_getattrs indicates the type of compound requested.
5993  *
5994  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
5995  *
5996  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
5997  *
5998  *   total number of ops is n + 1.
5999  *
6000  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
6001  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
6002  *      before the last component, and only get attributes
6003  *      for the last component.  Note that the second-to-last
6004  *	pathname component is XATTR_RPATH, which does NOT go
6005  *	over-the-wire as a lookup.
6006  *
6007  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
6008  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
6009  *
6010  *   and total number of ops is n + 5.
6011  *
6012  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
6013  *      attribute directory: create lookups plus an OPENATTR
6014  *	replacing the last lookup.  Note that the last pathname
6015  *	component is XATTR_RPATH, which does NOT go over-the-wire
6016  *	as a lookup.
6017  *
6018  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
6019  *		Openattr; Getfh; Getattr }
6020  *
6021  *   and total number of ops is n + 5.
6022  *
6023  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6024  *	nodes too.
6025  *
6026  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6027  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6028  *
6029  *   and total number of ops is 3*n + 1.
6030  *
6031  * All cases: returns the index in the arg array of the final LOOKUP op, or
6032  * -1 if no LOOKUPs were used.
6033  */
6034 int
6035 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6036 {
6037 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6038 	nfs_argop4 *argbase, *argop;
6039 	int arglen, argcnt;
6040 	int n = 1;	/* number of components */
6041 	int nga = 1;	/* number of Getattr's in request */
6042 	char c = '\0', *s, *p;
6043 	int lookup_idx = -1;
6044 	int argoplist_size;
6045 
6046 	/* set lookuparg response result to 0 */
6047 	lookupargp->resp->status = NFS4_OK;
6048 
6049 	/* skip leading "/" or "." e.g. ".//./" if there is */
6050 	for (; ; nm++) {
6051 		if (*nm != '/' && *nm != '.')
6052 			break;
6053 
6054 		/* ".." is counted as 1 component */
6055 		if (*nm == '.' && *(nm + 1) == '.')
6056 			break;
6057 	}
6058 
6059 	/*
6060 	 * Find n = number of components - nm must be null terminated
6061 	 * Skip "." components.
6062 	 */
6063 	if (*nm != '\0')
6064 		for (n = 1, s = nm; *s != '\0'; s++) {
6065 			if ((*s == '/') && (*(s + 1) != '/') &&
6066 			    (*(s + 1) != '\0') &&
6067 			    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6068 			    *(s + 2) == '\0')))
6069 				n++;
6070 		}
6071 	else
6072 		n = 0;
6073 
6074 	/*
6075 	 * nga is number of components that need Getfh+Getattr
6076 	 */
6077 	switch (l4_getattrs) {
6078 	case LKP4_NO_ATTRIBUTES:
6079 		nga = 0;
6080 		break;
6081 	case LKP4_ALL_ATTRIBUTES:
6082 		nga = n;
6083 		/*
6084 		 * Always have at least 1 getfh, getattr pair
6085 		 */
6086 		if (nga == 0)
6087 			nga++;
6088 		break;
6089 	case LKP4_LAST_ATTRDIR:
6090 	case LKP4_LAST_NAMED_ATTR:
6091 		nga = n+1;
6092 		break;
6093 	}
6094 
6095 	/*
6096 	 * If change to use the filehandle attr instead of getfh
6097 	 * the following line can be deleted.
6098 	 */
6099 	nga *= 2;
6100 
6101 	/*
6102 	 * calculate number of ops in request as
6103 	 * header + trailer + lookups + getattrs
6104 	 */
6105 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6106 
6107 	argoplist_size = arglen * sizeof (nfs_argop4);
6108 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6109 	lookupargp->argsp->array = argop;
6110 
6111 	argcnt = lookupargp->header_len;
6112 	argop += argcnt;
6113 
6114 	/*
6115 	 * loop and create a lookup op and possibly getattr/getfh for
6116 	 * each component. Skip "." components.
6117 	 */
6118 	for (s = nm; *s != '\0'; s = p) {
6119 		/*
6120 		 * Set up a pathname struct for each component if needed
6121 		 */
6122 		while (*s == '/')
6123 			s++;
6124 		if (*s == '\0')
6125 			break;
6126 
6127 		for (p = s; (*p != '/') && (*p != '\0'); p++)
6128 			;
6129 		c = *p;
6130 		*p = '\0';
6131 
6132 		if (s[0] == '.' && s[1] == '\0') {
6133 			*p = c;
6134 			continue;
6135 		}
6136 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6137 		    strcmp(s, XATTR_RPATH) == 0) {
6138 			/* getfh XXX may not be needed in future */
6139 			argop->argop = OP_GETFH;
6140 			argop++;
6141 			argcnt++;
6142 
6143 			/* getattr */
6144 			argop->argop = OP_GETATTR;
6145 			argop->nfs_argop4_u.opgetattr.attr_request =
6146 			    lookupargp->ga_bits;
6147 			argop->nfs_argop4_u.opgetattr.mi =
6148 			    lookupargp->mi;
6149 			argop++;
6150 			argcnt++;
6151 
6152 			/* openattr */
6153 			argop->argop = OP_OPENATTR;
6154 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6155 		    strcmp(s, XATTR_RPATH) == 0) {
6156 			/* openattr */
6157 			argop->argop = OP_OPENATTR;
6158 			argop++;
6159 			argcnt++;
6160 
6161 			/* getfh XXX may not be needed in future */
6162 			argop->argop = OP_GETFH;
6163 			argop++;
6164 			argcnt++;
6165 
6166 			/* getattr */
6167 			argop->argop = OP_GETATTR;
6168 			argop->nfs_argop4_u.opgetattr.attr_request =
6169 			    lookupargp->ga_bits;
6170 			argop->nfs_argop4_u.opgetattr.mi =
6171 			    lookupargp->mi;
6172 			argop++;
6173 			argcnt++;
6174 			*p = c;
6175 			continue;
6176 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6177 			/* lookupp */
6178 			argop->argop = OP_LOOKUPP;
6179 		} else {
6180 			/* lookup */
6181 			argop->argop = OP_LOOKUP;
6182 			(void) str_to_utf8(s,
6183 			    &argop->nfs_argop4_u.oplookup.objname);
6184 		}
6185 		lookup_idx = argcnt;
6186 		argop++;
6187 		argcnt++;
6188 
6189 		*p = c;
6190 
6191 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6192 			/* getfh XXX may not be needed in future */
6193 			argop->argop = OP_GETFH;
6194 			argop++;
6195 			argcnt++;
6196 
6197 			/* getattr */
6198 			argop->argop = OP_GETATTR;
6199 			argop->nfs_argop4_u.opgetattr.attr_request =
6200 			    lookupargp->ga_bits;
6201 			argop->nfs_argop4_u.opgetattr.mi =
6202 			    lookupargp->mi;
6203 			argop++;
6204 			argcnt++;
6205 		}
6206 	}
6207 
6208 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6209 	    ((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6210 		if (needgetfh) {
6211 			/* stick in a post-lookup getfh */
6212 			argop->argop = OP_GETFH;
6213 			argcnt++;
6214 			argop++;
6215 		}
6216 		/* post-lookup getattr */
6217 		argop->argop = OP_GETATTR;
6218 		argop->nfs_argop4_u.opgetattr.attr_request =
6219 		    lookupargp->ga_bits;
6220 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6221 		argcnt++;
6222 	}
6223 	argcnt += lookupargp->trailer_len;	/* actual op count */
6224 	lookupargp->argsp->array_len = argcnt;
6225 	lookupargp->arglen = arglen;
6226 
6227 #ifdef DEBUG
6228 	if (nfs4_client_lookup_debug)
6229 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6230 #endif
6231 
6232 	return (lookup_idx);
6233 }
6234 
6235 static int
6236 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6237 {
6238 	COMPOUND4args_clnt	args;
6239 	COMPOUND4res_clnt	res;
6240 	GETFH4res	*gf_res = NULL;
6241 	nfs_argop4	argop[4];
6242 	nfs_resop4	*resop = NULL;
6243 	nfs4_sharedfh_t *sfhp;
6244 	hrtime_t t;
6245 	nfs4_error_t	e;
6246 
6247 	rnode4_t	*drp;
6248 	int		doqueue = 1;
6249 	vnode_t		*vp;
6250 	int		needrecov = 0;
6251 	nfs4_recov_state_t recov_state;
6252 
6253 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6254 
6255 	*avp = NULL;
6256 	recov_state.rs_flags = 0;
6257 	recov_state.rs_num_retry_despite_err = 0;
6258 
6259 recov_retry:
6260 	/* COMPOUND: putfh, openattr, getfh, getattr */
6261 	args.array_len = 4;
6262 	args.array = argop;
6263 	args.ctag = TAG_OPENATTR;
6264 
6265 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6266 	if (e.error)
6267 		return (e.error);
6268 
6269 	drp = VTOR4(dvp);
6270 
6271 	/* putfh */
6272 	argop[0].argop = OP_CPUTFH;
6273 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6274 
6275 	/* openattr */
6276 	argop[1].argop = OP_OPENATTR;
6277 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6278 
6279 	/* getfh */
6280 	argop[2].argop = OP_GETFH;
6281 
6282 	/* getattr */
6283 	argop[3].argop = OP_GETATTR;
6284 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6285 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6286 
6287 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6288 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6289 	    rnode4info(drp)));
6290 
6291 	t = gethrtime();
6292 
6293 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6294 
6295 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6296 	if (needrecov) {
6297 		bool_t abort;
6298 
6299 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6300 		    "nfs4openattr: initiating recovery\n"));
6301 
6302 		abort = nfs4_start_recovery(&e,
6303 		    VTOMI4(dvp), dvp, NULL, NULL, NULL,
6304 		    OP_OPENATTR, NULL);
6305 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6306 		if (!e.error) {
6307 			e.error = geterrno4(res.status);
6308 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6309 		}
6310 		if (abort == FALSE)
6311 			goto recov_retry;
6312 		return (e.error);
6313 	}
6314 
6315 	if (e.error) {
6316 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6317 		return (e.error);
6318 	}
6319 
6320 	if (res.status) {
6321 		/*
6322 		 * If OTW errro is NOTSUPP, then it should be
6323 		 * translated to EINVAL.  All Solaris file system
6324 		 * implementations return EINVAL to the syscall layer
6325 		 * when the attrdir cannot be created due to an
6326 		 * implementation restriction or noxattr mount option.
6327 		 */
6328 		if (res.status == NFS4ERR_NOTSUPP) {
6329 			mutex_enter(&drp->r_statelock);
6330 			if (drp->r_xattr_dir)
6331 				VN_RELE(drp->r_xattr_dir);
6332 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6333 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6334 			mutex_exit(&drp->r_statelock);
6335 
6336 			e.error = EINVAL;
6337 		} else {
6338 			e.error = geterrno4(res.status);
6339 		}
6340 
6341 		if (e.error) {
6342 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6343 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6344 			    needrecov);
6345 			return (e.error);
6346 		}
6347 	}
6348 
6349 	resop = &res.array[0];  /* putfh res */
6350 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6351 
6352 	resop = &res.array[1];  /* openattr res */
6353 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6354 
6355 	resop = &res.array[2];  /* getfh res */
6356 	gf_res = &resop->nfs_resop4_u.opgetfh;
6357 	if (gf_res->object.nfs_fh4_len == 0) {
6358 		*avp = NULL;
6359 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6360 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6361 		return (ENOENT);
6362 	}
6363 
6364 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6365 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6366 	    dvp->v_vfsp, t, cr, dvp,
6367 	    fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH));
6368 	sfh4_rele(&sfhp);
6369 
6370 	if (e.error)
6371 		PURGE_ATTRCACHE4(vp);
6372 
6373 	mutex_enter(&vp->v_lock);
6374 	vp->v_flag |= V_XATTRDIR;
6375 	mutex_exit(&vp->v_lock);
6376 
6377 	*avp = vp;
6378 
6379 	mutex_enter(&drp->r_statelock);
6380 	if (drp->r_xattr_dir)
6381 		VN_RELE(drp->r_xattr_dir);
6382 	VN_HOLD(vp);
6383 	drp->r_xattr_dir = vp;
6384 
6385 	/*
6386 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6387 	 * NULL.  xattrs could be created at any time, and we have no
6388 	 * way to update pc4_xattr_exists in the base object if/when
6389 	 * it happens.
6390 	 */
6391 	drp->r_pathconf.pc4_xattr_valid = 0;
6392 
6393 	mutex_exit(&drp->r_statelock);
6394 
6395 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6396 
6397 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6398 
6399 	return (0);
6400 }
6401 
6402 /* ARGSUSED */
6403 static int
6404 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6405 	int mode, vnode_t **vpp, cred_t *cr, int flags, caller_context_t *ct,
6406 	vsecattr_t *vsecp)
6407 {
6408 	int error;
6409 	vnode_t *vp = NULL;
6410 	rnode4_t *rp;
6411 	struct vattr vattr;
6412 	rnode4_t *drp;
6413 	vnode_t *tempvp;
6414 	enum createmode4 createmode;
6415 	bool_t must_trunc = FALSE;
6416 	int	truncating = 0;
6417 
6418 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6419 		return (EPERM);
6420 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6421 		return (EINVAL);
6422 	}
6423 
6424 	/* . and .. have special meaning in the protocol, reject them. */
6425 
6426 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6427 		return (EISDIR);
6428 
6429 	drp = VTOR4(dvp);
6430 
6431 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6432 		return (EINTR);
6433 
6434 top:
6435 	/*
6436 	 * We make a copy of the attributes because the caller does not
6437 	 * expect us to change what va points to.
6438 	 */
6439 	vattr = *va;
6440 
6441 	/*
6442 	 * If the pathname is "", then dvp is the root vnode of
6443 	 * a remote file mounted over a local directory.
6444 	 * All that needs to be done is access
6445 	 * checking and truncation.  Note that we avoid doing
6446 	 * open w/ create because the parent directory might
6447 	 * be in pseudo-fs and the open would fail.
6448 	 */
6449 	if (*nm == '\0') {
6450 		error = 0;
6451 		VN_HOLD(dvp);
6452 		vp = dvp;
6453 		must_trunc = TRUE;
6454 	} else {
6455 		/*
6456 		 * We need to go over the wire, just to be sure whether the
6457 		 * file exists or not.  Using the DNLC can be dangerous in
6458 		 * this case when making a decision regarding existence.
6459 		 */
6460 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6461 	}
6462 
6463 	if (exclusive)
6464 		createmode = EXCLUSIVE4;
6465 	else
6466 		createmode = GUARDED4;
6467 
6468 	/*
6469 	 * error would be set if the file does not exist on the
6470 	 * server, so lets go create it.
6471 	 */
6472 	if (error) {
6473 		goto create_otw;
6474 	}
6475 
6476 	/*
6477 	 * File does exist on the server
6478 	 */
6479 	if (exclusive == EXCL)
6480 		error = EEXIST;
6481 	else if (vp->v_type == VDIR && (mode & VWRITE))
6482 		error = EISDIR;
6483 	else {
6484 		/*
6485 		 * If vnode is a device, create special vnode.
6486 		 */
6487 		if (ISVDEV(vp->v_type)) {
6488 			tempvp = vp;
6489 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6490 			VN_RELE(tempvp);
6491 		}
6492 		if (!(error = VOP_ACCESS(vp, mode, 0, cr, ct))) {
6493 			if ((vattr.va_mask & AT_SIZE) &&
6494 			    vp->v_type == VREG) {
6495 				rp = VTOR4(vp);
6496 				/*
6497 				 * Check here for large file handled
6498 				 * by LF-unaware process (as
6499 				 * ufs_create() does)
6500 				 */
6501 				if (!(flags & FOFFMAX)) {
6502 					mutex_enter(&rp->r_statelock);
6503 					if (rp->r_size > MAXOFF32_T)
6504 						error = EOVERFLOW;
6505 					mutex_exit(&rp->r_statelock);
6506 				}
6507 
6508 				/* if error is set then we need to return */
6509 				if (error) {
6510 					nfs_rw_exit(&drp->r_rwlock);
6511 					VN_RELE(vp);
6512 					return (error);
6513 				}
6514 
6515 				if (must_trunc) {
6516 					vattr.va_mask = AT_SIZE;
6517 					error = nfs4setattr(vp, &vattr, 0, cr,
6518 					    NULL);
6519 				} else {
6520 				/*
6521 				 * we know we have a regular file that already
6522 				 * exists and we may end up truncating the file
6523 				 * as a result of the open_otw, so flush out
6524 				 * any dirty pages for this file first.
6525 				 */
6526 					if (nfs4_has_pages(vp) &&
6527 					    ((rp->r_flags & R4DIRTY) ||
6528 					    rp->r_count > 0 ||
6529 					    rp->r_mapcnt > 0)) {
6530 						error = nfs4_putpage(vp,
6531 						    (offset_t)0, 0, 0, cr, ct);
6532 						if (error && (error == ENOSPC ||
6533 						    error == EDQUOT)) {
6534 							mutex_enter(
6535 							    &rp->r_statelock);
6536 							if (!rp->r_error)
6537 								rp->r_error =
6538 								    error;
6539 							mutex_exit(
6540 							    &rp->r_statelock);
6541 						}
6542 					}
6543 					vattr.va_mask = (AT_SIZE |
6544 					    AT_TYPE | AT_MODE);
6545 					vattr.va_type = VREG;
6546 					createmode = UNCHECKED4;
6547 					truncating = 1;
6548 					goto create_otw;
6549 				}
6550 			}
6551 		}
6552 	}
6553 	nfs_rw_exit(&drp->r_rwlock);
6554 	if (error) {
6555 		VN_RELE(vp);
6556 	} else {
6557 		vnode_t *tvp;
6558 		rnode4_t *trp;
6559 		/*
6560 		 * existing file got truncated, notify.
6561 		 */
6562 		tvp = vp;
6563 		if (vp->v_type == VREG) {
6564 			trp = VTOR4(vp);
6565 			if (IS_SHADOW(vp, trp))
6566 				tvp = RTOV4(trp);
6567 		}
6568 		vnevent_create(tvp, ct);
6569 		*vpp = vp;
6570 	}
6571 	return (error);
6572 
6573 create_otw:
6574 	dnlc_remove(dvp, nm);
6575 
6576 	ASSERT(vattr.va_mask & AT_TYPE);
6577 
6578 	/*
6579 	 * If not a regular file let nfs4mknod() handle it.
6580 	 */
6581 	if (vattr.va_type != VREG) {
6582 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6583 		nfs_rw_exit(&drp->r_rwlock);
6584 		return (error);
6585 	}
6586 
6587 	/*
6588 	 * It _is_ a regular file.
6589 	 */
6590 	ASSERT(vattr.va_mask & AT_MODE);
6591 	if (MANDMODE(vattr.va_mode)) {
6592 		nfs_rw_exit(&drp->r_rwlock);
6593 		return (EACCES);
6594 	}
6595 
6596 	/*
6597 	 * If this happens to be a mknod of a regular file, then flags will
6598 	 * have neither FREAD or FWRITE.  However, we must set at least one
6599 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6600 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6601 	 * set (based on openmode specified by app).
6602 	 */
6603 	if ((flags & (FREAD|FWRITE)) == 0)
6604 		flags |= (FREAD|FWRITE);
6605 
6606 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6607 
6608 	if (vp != NULL) {
6609 		/* if create was successful, throw away the file's pages */
6610 		if (!error && (vattr.va_mask & AT_SIZE))
6611 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6612 			    cr);
6613 		/* release the lookup hold */
6614 		VN_RELE(vp);
6615 		vp = NULL;
6616 	}
6617 
6618 	/*
6619 	 * validate that we opened a regular file. This handles a misbehaving
6620 	 * server that returns an incorrect FH.
6621 	 */
6622 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6623 		error = EISDIR;
6624 		VN_RELE(*vpp);
6625 	}
6626 
6627 	/*
6628 	 * If this is not an exclusive create, then the CREATE
6629 	 * request will be made with the GUARDED mode set.  This
6630 	 * means that the server will return EEXIST if the file
6631 	 * exists.  The file could exist because of a retransmitted
6632 	 * request.  In this case, we recover by starting over and
6633 	 * checking to see whether the file exists.  This second
6634 	 * time through it should and a CREATE request will not be
6635 	 * sent.
6636 	 *
6637 	 * This handles the problem of a dangling CREATE request
6638 	 * which contains attributes which indicate that the file
6639 	 * should be truncated.  This retransmitted request could
6640 	 * possibly truncate valid data in the file if not caught
6641 	 * by the duplicate request mechanism on the server or if
6642 	 * not caught by other means.  The scenario is:
6643 	 *
6644 	 * Client transmits CREATE request with size = 0
6645 	 * Client times out, retransmits request.
6646 	 * Response to the first request arrives from the server
6647 	 *  and the client proceeds on.
6648 	 * Client writes data to the file.
6649 	 * The server now processes retransmitted CREATE request
6650 	 *  and truncates file.
6651 	 *
6652 	 * The use of the GUARDED CREATE request prevents this from
6653 	 * happening because the retransmitted CREATE would fail
6654 	 * with EEXIST and would not truncate the file.
6655 	 */
6656 	if (error == EEXIST && exclusive == NONEXCL) {
6657 #ifdef DEBUG
6658 		nfs4_create_misses++;
6659 #endif
6660 		goto top;
6661 	}
6662 	nfs_rw_exit(&drp->r_rwlock);
6663 	if (truncating && !error && *vpp) {
6664 		vnode_t *tvp;
6665 		rnode4_t *trp;
6666 		/*
6667 		 * existing file got truncated, notify.
6668 		 */
6669 		tvp = *vpp;
6670 		trp = VTOR4(tvp);
6671 		if (IS_SHADOW(tvp, trp))
6672 			tvp = RTOV4(trp);
6673 		vnevent_create(tvp, ct);
6674 	}
6675 	return (error);
6676 }
6677 
6678 /*
6679  * Create compound (for mkdir, mknod, symlink):
6680  * { Putfh <dfh>; Create; Getfh; Getattr }
6681  * It's okay if setattr failed to set gid - this is not considered
6682  * an error, but purge attrs in that case.
6683  */
6684 static int
6685 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6686     vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6687 {
6688 	int need_end_op = FALSE;
6689 	COMPOUND4args_clnt args;
6690 	COMPOUND4res_clnt res, *resp = NULL;
6691 	nfs_argop4 *argop;
6692 	nfs_resop4 *resop;
6693 	int doqueue;
6694 	mntinfo4_t *mi;
6695 	rnode4_t *drp = VTOR4(dvp);
6696 	change_info4 *cinfo;
6697 	GETFH4res *gf_res;
6698 	struct vattr vattr;
6699 	vnode_t *vp;
6700 	fattr4 *crattr;
6701 	bool_t needrecov = FALSE;
6702 	nfs4_recov_state_t recov_state;
6703 	nfs4_sharedfh_t *sfhp = NULL;
6704 	hrtime_t t;
6705 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6706 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6707 	dirattr_info_t dinfo, *dinfop;
6708 	servinfo4_t *svp;
6709 	bitmap4 supp_attrs;
6710 
6711 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6712 	    type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6713 
6714 	mi = VTOMI4(dvp);
6715 
6716 	/*
6717 	 * Make sure we properly deal with setting the right gid
6718 	 * on a new directory to reflect the parent's setgid bit
6719 	 */
6720 	setgid_flag = 0;
6721 	if (type == NF4DIR) {
6722 		struct vattr dva;
6723 
6724 		va->va_mode &= ~VSGID;
6725 		dva.va_mask = AT_MODE | AT_GID;
6726 		if (VOP_GETATTR(dvp, &dva, 0, cr, NULL) == 0) {
6727 
6728 			/*
6729 			 * If the parent's directory has the setgid bit set
6730 			 * _and_ the client was able to get a valid mapping
6731 			 * for the parent dir's owner_group, we want to
6732 			 * append NVERIFY(owner_group == dva.va_gid) and
6733 			 * SETTATTR to the CREATE compound.
6734 			 */
6735 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6736 				setgid_flag = 1;
6737 				va->va_mode |= VSGID;
6738 				if (dva.va_gid != GID_NOBODY) {
6739 					va->va_mask |= AT_GID;
6740 					va->va_gid = dva.va_gid;
6741 				}
6742 			}
6743 		}
6744 	}
6745 
6746 	/*
6747 	 * Create ops:
6748 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6749 	 *	5:restorefh(dir) 6:getattr(dir)
6750 	 *
6751 	 * if (setgid)
6752 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6753 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6754 	 *	8:nverify 9:setattr
6755 	 */
6756 	if (setgid_flag) {
6757 		numops = 10;
6758 		idx_create = 1;
6759 		idx_fattr = 3;
6760 	} else {
6761 		numops = 7;
6762 		idx_create = 2;
6763 		idx_fattr = 4;
6764 	}
6765 
6766 	ASSERT(nfs_zone() == mi->mi_zone);
6767 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6768 		return (EINTR);
6769 	}
6770 	recov_state.rs_flags = 0;
6771 	recov_state.rs_num_retry_despite_err = 0;
6772 
6773 	argoplist_size = numops * sizeof (nfs_argop4);
6774 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6775 
6776 recov_retry:
6777 	if (type == NF4LNK)
6778 		args.ctag = TAG_SYMLINK;
6779 	else if (type == NF4DIR)
6780 		args.ctag = TAG_MKDIR;
6781 	else
6782 		args.ctag = TAG_MKNOD;
6783 
6784 	args.array_len = numops;
6785 	args.array = argop;
6786 
6787 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6788 		nfs_rw_exit(&drp->r_rwlock);
6789 		kmem_free(argop, argoplist_size);
6790 		return (e.error);
6791 	}
6792 	need_end_op = TRUE;
6793 
6794 
6795 	/* 0: putfh directory */
6796 	argop[0].argop = OP_CPUTFH;
6797 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6798 
6799 	/* 1/2: Create object */
6800 	argop[idx_create].argop = OP_CCREATE;
6801 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6802 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6803 	if (type == NF4LNK) {
6804 		/*
6805 		 * symlink, treat name as data
6806 		 */
6807 		ASSERT(data != NULL);
6808 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6809 		    (char *)data;
6810 	}
6811 	if (type == NF4BLK || type == NF4CHR) {
6812 		ASSERT(data != NULL);
6813 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6814 		    *((specdata4 *)data);
6815 	}
6816 
6817 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6818 
6819 	svp = drp->r_server;
6820 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6821 	supp_attrs = svp->sv_supp_attrs;
6822 	nfs_rw_exit(&svp->sv_lock);
6823 
6824 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6825 		nfs_rw_exit(&drp->r_rwlock);
6826 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6827 		e.error = EINVAL;
6828 		kmem_free(argop, argoplist_size);
6829 		return (e.error);
6830 	}
6831 
6832 	/* 2/3: getfh fh of created object */
6833 	ASSERT(idx_create + 1 == idx_fattr - 1);
6834 	argop[idx_create + 1].argop = OP_GETFH;
6835 
6836 	/* 3/4: getattr of new object */
6837 	argop[idx_fattr].argop = OP_GETATTR;
6838 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6839 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6840 
6841 	if (setgid_flag) {
6842 		vattr_t	_v;
6843 
6844 		argop[4].argop = OP_SAVEFH;
6845 
6846 		argop[5].argop = OP_CPUTFH;
6847 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6848 
6849 		argop[6].argop = OP_GETATTR;
6850 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6851 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6852 
6853 		argop[7].argop = OP_RESTOREFH;
6854 
6855 		/*
6856 		 * nverify
6857 		 *
6858 		 * XXX - Revisit the last argument to nfs4_end_op()
6859 		 *	 once 5020486 is fixed.
6860 		 */
6861 		_v.va_mask = AT_GID;
6862 		_v.va_gid = va->va_gid;
6863 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6864 		    supp_attrs)) {
6865 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6866 			nfs_rw_exit(&drp->r_rwlock);
6867 			nfs4_fattr4_free(crattr);
6868 			kmem_free(argop, argoplist_size);
6869 			return (e.error);
6870 		}
6871 
6872 		/*
6873 		 * setattr
6874 		 *
6875 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
6876 		 * so no need for stateid or flags. Also we specify NULL
6877 		 * rp since we're only interested in setting owner_group
6878 		 * attributes.
6879 		 */
6880 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
6881 		    &e.error, 0);
6882 
6883 		if (e.error) {
6884 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6885 			nfs_rw_exit(&drp->r_rwlock);
6886 			nfs4_fattr4_free(crattr);
6887 			nfs4args_verify_free(&argop[8]);
6888 			kmem_free(argop, argoplist_size);
6889 			return (e.error);
6890 		}
6891 	} else {
6892 		argop[1].argop = OP_SAVEFH;
6893 
6894 		argop[5].argop = OP_RESTOREFH;
6895 
6896 		argop[6].argop = OP_GETATTR;
6897 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6898 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6899 	}
6900 
6901 	dnlc_remove(dvp, nm);
6902 
6903 	doqueue = 1;
6904 	t = gethrtime();
6905 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
6906 
6907 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
6908 	if (e.error) {
6909 		PURGE_ATTRCACHE4(dvp);
6910 		if (!needrecov)
6911 			goto out;
6912 	}
6913 
6914 	if (needrecov) {
6915 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
6916 		    OP_CREATE, NULL) == FALSE) {
6917 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6918 			    needrecov);
6919 			need_end_op = FALSE;
6920 			nfs4_fattr4_free(crattr);
6921 			if (setgid_flag) {
6922 				nfs4args_verify_free(&argop[8]);
6923 				nfs4args_setattr_free(&argop[9]);
6924 			}
6925 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6926 			goto recov_retry;
6927 		}
6928 	}
6929 
6930 	resp = &res;
6931 
6932 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
6933 
6934 		if (res.status == NFS4ERR_BADOWNER)
6935 			nfs4_log_badowner(mi, OP_CREATE);
6936 
6937 		e.error = geterrno4(res.status);
6938 
6939 		/*
6940 		 * This check is left over from when create was implemented
6941 		 * using a setattr op (instead of createattrs).  If the
6942 		 * putfh/create/getfh failed, the error was returned.  If
6943 		 * setattr/getattr failed, we keep going.
6944 		 *
6945 		 * It might be better to get rid of the GETFH also, and just
6946 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
6947 		 * Then if any of the operations failed, we could return the
6948 		 * error now, and remove much of the error code below.
6949 		 */
6950 		if (res.array_len <= idx_fattr) {
6951 			/*
6952 			 * Either Putfh, Create or Getfh failed.
6953 			 */
6954 			PURGE_ATTRCACHE4(dvp);
6955 			/*
6956 			 * nfs4_purge_stale_fh() may generate otw calls through
6957 			 * nfs4_invalidate_pages. Hence the need to call
6958 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
6959 			 */
6960 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6961 			    needrecov);
6962 			need_end_op = FALSE;
6963 			nfs4_purge_stale_fh(e.error, dvp, cr);
6964 			goto out;
6965 		}
6966 	}
6967 
6968 	resop = &res.array[idx_create];	/* create res */
6969 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
6970 
6971 	resop = &res.array[idx_create + 1]; /* getfh res */
6972 	gf_res = &resop->nfs_resop4_u.opgetfh;
6973 
6974 	sfhp = sfh4_get(&gf_res->object, mi);
6975 	if (e.error) {
6976 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
6977 		    fn_get(VTOSV(dvp)->sv_name, nm));
6978 		if (vp->v_type == VNON) {
6979 			vattr.va_mask = AT_TYPE;
6980 			/*
6981 			 * Need to call nfs4_end_op before nfs4getattr to avoid
6982 			 * potential nfs4_start_op deadlock. See RFE 4777612.
6983 			 */
6984 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6985 			    needrecov);
6986 			need_end_op = FALSE;
6987 			e.error = nfs4getattr(vp, &vattr, cr);
6988 			if (e.error) {
6989 				VN_RELE(vp);
6990 				*vpp = NULL;
6991 				goto out;
6992 			}
6993 			vp->v_type = vattr.va_type;
6994 		}
6995 		e.error = 0;
6996 	} else {
6997 		*vpp = vp = makenfs4node(sfhp,
6998 		    &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
6999 		    dvp->v_vfsp, t, cr,
7000 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
7001 	}
7002 
7003 	/*
7004 	 * If compound succeeded, then update dir attrs
7005 	 */
7006 	if (res.status == NFS4_OK) {
7007 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
7008 		dinfo.di_cred = cr;
7009 		dinfo.di_time_call = t;
7010 		dinfop = &dinfo;
7011 	} else
7012 		dinfop = NULL;
7013 
7014 	/* Update directory cache attribute, readdir and dnlc caches */
7015 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
7016 
7017 out:
7018 	if (sfhp != NULL)
7019 		sfh4_rele(&sfhp);
7020 	nfs_rw_exit(&drp->r_rwlock);
7021 	nfs4_fattr4_free(crattr);
7022 	if (setgid_flag) {
7023 		nfs4args_verify_free(&argop[8]);
7024 		nfs4args_setattr_free(&argop[9]);
7025 	}
7026 	if (resp)
7027 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7028 	if (need_end_op)
7029 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7030 
7031 	kmem_free(argop, argoplist_size);
7032 	return (e.error);
7033 }
7034 
7035 /* ARGSUSED */
7036 static int
7037 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7038     int mode, vnode_t **vpp, cred_t *cr)
7039 {
7040 	int error;
7041 	vnode_t *vp;
7042 	nfs_ftype4 type;
7043 	specdata4 spec, *specp = NULL;
7044 
7045 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7046 
7047 	switch (va->va_type) {
7048 	case VCHR:
7049 	case VBLK:
7050 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7051 		spec.specdata1 = getmajor(va->va_rdev);
7052 		spec.specdata2 = getminor(va->va_rdev);
7053 		specp = &spec;
7054 		break;
7055 
7056 	case VFIFO:
7057 		type = NF4FIFO;
7058 		break;
7059 	case VSOCK:
7060 		type = NF4SOCK;
7061 		break;
7062 
7063 	default:
7064 		return (EINVAL);
7065 	}
7066 
7067 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7068 	if (error) {
7069 		return (error);
7070 	}
7071 
7072 	/*
7073 	 * This might not be needed any more; special case to deal
7074 	 * with problematic v2/v3 servers.  Since create was unable
7075 	 * to set group correctly, not sure what hope setattr has.
7076 	 */
7077 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7078 		va->va_mask = AT_GID;
7079 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7080 	}
7081 
7082 	/*
7083 	 * If vnode is a device create special vnode
7084 	 */
7085 	if (ISVDEV(vp->v_type)) {
7086 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7087 		VN_RELE(vp);
7088 	} else {
7089 		*vpp = vp;
7090 	}
7091 	return (error);
7092 }
7093 
7094 /*
7095  * Remove requires that the current fh be the target directory.
7096  * After the operation, the current fh is unchanged.
7097  * The compound op structure is:
7098  *      PUTFH(targetdir), REMOVE
7099  *
7100  * Weirdness: if the vnode to be removed is open
7101  * we rename it instead of removing it and nfs_inactive
7102  * will remove the new name.
7103  */
7104 /* ARGSUSED */
7105 static int
7106 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr, caller_context_t *ct, int flags)
7107 {
7108 	COMPOUND4args_clnt args;
7109 	COMPOUND4res_clnt res, *resp = NULL;
7110 	REMOVE4res *rm_res;
7111 	nfs_argop4 argop[3];
7112 	nfs_resop4 *resop;
7113 	vnode_t *vp;
7114 	char *tmpname;
7115 	int doqueue;
7116 	mntinfo4_t *mi;
7117 	rnode4_t *rp;
7118 	rnode4_t *drp;
7119 	int needrecov = 0;
7120 	nfs4_recov_state_t recov_state;
7121 	int isopen;
7122 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7123 	dirattr_info_t dinfo;
7124 
7125 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7126 		return (EPERM);
7127 	drp = VTOR4(dvp);
7128 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7129 		return (EINTR);
7130 
7131 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7132 	if (e.error) {
7133 		nfs_rw_exit(&drp->r_rwlock);
7134 		return (e.error);
7135 	}
7136 
7137 	if (vp->v_type == VDIR) {
7138 		VN_RELE(vp);
7139 		nfs_rw_exit(&drp->r_rwlock);
7140 		return (EISDIR);
7141 	}
7142 
7143 	/*
7144 	 * First just remove the entry from the name cache, as it
7145 	 * is most likely the only entry for this vp.
7146 	 */
7147 	dnlc_remove(dvp, nm);
7148 
7149 	rp = VTOR4(vp);
7150 
7151 	/*
7152 	 * For regular file types, check to see if the file is open by looking
7153 	 * at the open streams.
7154 	 * For all other types, check the reference count on the vnode.  Since
7155 	 * they are not opened OTW they never have an open stream.
7156 	 *
7157 	 * If the file is open, rename it to .nfsXXXX.
7158 	 */
7159 	if (vp->v_type != VREG) {
7160 		/*
7161 		 * If the file has a v_count > 1 then there may be more than one
7162 		 * entry in the name cache due multiple links or an open file,
7163 		 * but we don't have the real reference count so flush all
7164 		 * possible entries.
7165 		 */
7166 		if (vp->v_count > 1)
7167 			dnlc_purge_vp(vp);
7168 
7169 		/*
7170 		 * Now we have the real reference count.
7171 		 */
7172 		isopen = vp->v_count > 1;
7173 	} else {
7174 		mutex_enter(&rp->r_os_lock);
7175 		isopen = list_head(&rp->r_open_streams) != NULL;
7176 		mutex_exit(&rp->r_os_lock);
7177 	}
7178 
7179 	mutex_enter(&rp->r_statelock);
7180 	if (isopen &&
7181 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7182 		mutex_exit(&rp->r_statelock);
7183 		tmpname = newname();
7184 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr, ct);
7185 		if (e.error)
7186 			kmem_free(tmpname, MAXNAMELEN);
7187 		else {
7188 			mutex_enter(&rp->r_statelock);
7189 			if (rp->r_unldvp == NULL) {
7190 				VN_HOLD(dvp);
7191 				rp->r_unldvp = dvp;
7192 				if (rp->r_unlcred != NULL)
7193 					crfree(rp->r_unlcred);
7194 				crhold(cr);
7195 				rp->r_unlcred = cr;
7196 				rp->r_unlname = tmpname;
7197 			} else {
7198 				kmem_free(rp->r_unlname, MAXNAMELEN);
7199 				rp->r_unlname = tmpname;
7200 			}
7201 			mutex_exit(&rp->r_statelock);
7202 		}
7203 		VN_RELE(vp);
7204 		nfs_rw_exit(&drp->r_rwlock);
7205 		return (e.error);
7206 	}
7207 	/*
7208 	 * Actually remove the file/dir
7209 	 */
7210 	mutex_exit(&rp->r_statelock);
7211 
7212 	/*
7213 	 * We need to flush any dirty pages which happen to
7214 	 * be hanging around before removing the file.
7215 	 * This shouldn't happen very often since in NFSv4
7216 	 * we should be close to open consistent.
7217 	 */
7218 	if (nfs4_has_pages(vp) &&
7219 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7220 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, ct);
7221 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7222 			mutex_enter(&rp->r_statelock);
7223 			if (!rp->r_error)
7224 				rp->r_error = e.error;
7225 			mutex_exit(&rp->r_statelock);
7226 		}
7227 	}
7228 
7229 	mi = VTOMI4(dvp);
7230 
7231 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7232 	recov_state.rs_flags = 0;
7233 	recov_state.rs_num_retry_despite_err = 0;
7234 
7235 recov_retry:
7236 	/*
7237 	 * Remove ops: putfh dir; remove
7238 	 */
7239 	args.ctag = TAG_REMOVE;
7240 	args.array_len = 3;
7241 	args.array = argop;
7242 
7243 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7244 	if (e.error) {
7245 		nfs_rw_exit(&drp->r_rwlock);
7246 		VN_RELE(vp);
7247 		return (e.error);
7248 	}
7249 
7250 	/* putfh directory */
7251 	argop[0].argop = OP_CPUTFH;
7252 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7253 
7254 	/* remove */
7255 	argop[1].argop = OP_CREMOVE;
7256 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7257 
7258 	/* getattr dir */
7259 	argop[2].argop = OP_GETATTR;
7260 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7261 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7262 
7263 	doqueue = 1;
7264 	dinfo.di_time_call = gethrtime();
7265 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7266 
7267 	PURGE_ATTRCACHE4(vp);
7268 
7269 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7270 	if (e.error)
7271 		PURGE_ATTRCACHE4(dvp);
7272 
7273 	if (needrecov) {
7274 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7275 		    NULL, NULL, NULL, OP_REMOVE, NULL) == FALSE) {
7276 			if (!e.error)
7277 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7278 				    (caddr_t)&res);
7279 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7280 			    needrecov);
7281 			goto recov_retry;
7282 		}
7283 	}
7284 
7285 	/*
7286 	 * Matching nfs4_end_op() for start_op() above.
7287 	 * There is a path in the code below which calls
7288 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7289 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7290 	 * here to avoid nfs4_start_op() deadlock.
7291 	 */
7292 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7293 
7294 	if (!e.error) {
7295 		resp = &res;
7296 
7297 		if (res.status) {
7298 			e.error = geterrno4(res.status);
7299 			PURGE_ATTRCACHE4(dvp);
7300 			nfs4_purge_stale_fh(e.error, dvp, cr);
7301 		} else {
7302 			resop = &res.array[1];	/* remove res */
7303 			rm_res = &resop->nfs_resop4_u.opremove;
7304 
7305 			dinfo.di_garp =
7306 			    &res.array[2].nfs_resop4_u.opgetattr.ga_res;
7307 			dinfo.di_cred = cr;
7308 
7309 			/* Update directory attr, readdir and dnlc caches */
7310 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7311 			    &dinfo);
7312 		}
7313 	}
7314 	nfs_rw_exit(&drp->r_rwlock);
7315 	if (resp)
7316 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7317 
7318 	if (e.error == 0) {
7319 		vnode_t *tvp;
7320 		rnode4_t *trp;
7321 		trp = VTOR4(vp);
7322 		tvp = vp;
7323 		if (IS_SHADOW(vp, trp))
7324 			tvp = RTOV4(trp);
7325 		vnevent_remove(tvp, dvp, nm, ct);
7326 	}
7327 	VN_RELE(vp);
7328 	return (e.error);
7329 }
7330 
7331 /*
7332  * Link requires that the current fh be the target directory and the
7333  * saved fh be the source fh. After the operation, the current fh is unchanged.
7334  * Thus the compound op structure is:
7335  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7336  *	GETATTR(file)
7337  */
7338 /* ARGSUSED */
7339 static int
7340 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr,
7341     caller_context_t *ct, int flags)
7342 {
7343 	COMPOUND4args_clnt args;
7344 	COMPOUND4res_clnt res, *resp = NULL;
7345 	LINK4res *ln_res;
7346 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7347 	nfs_argop4 *argop;
7348 	nfs_resop4 *resop;
7349 	vnode_t *realvp, *nvp;
7350 	int doqueue;
7351 	mntinfo4_t *mi;
7352 	rnode4_t *tdrp;
7353 	bool_t needrecov = FALSE;
7354 	nfs4_recov_state_t recov_state;
7355 	hrtime_t t;
7356 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7357 	dirattr_info_t dinfo;
7358 
7359 	ASSERT(*tnm != '\0');
7360 	ASSERT(tdvp->v_type == VDIR);
7361 	ASSERT(nfs4_consistent_type(tdvp));
7362 	ASSERT(nfs4_consistent_type(svp));
7363 
7364 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7365 		return (EPERM);
7366 	if (VOP_REALVP(svp, &realvp, ct) == 0) {
7367 		svp = realvp;
7368 		ASSERT(nfs4_consistent_type(svp));
7369 	}
7370 
7371 	tdrp = VTOR4(tdvp);
7372 	mi = VTOMI4(svp);
7373 
7374 	if (!(mi->mi_flags & MI4_LINK)) {
7375 		return (EOPNOTSUPP);
7376 	}
7377 	recov_state.rs_flags = 0;
7378 	recov_state.rs_num_retry_despite_err = 0;
7379 
7380 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7381 		return (EINTR);
7382 
7383 recov_retry:
7384 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7385 
7386 	args.ctag = TAG_LINK;
7387 
7388 	/*
7389 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7390 	 * restorefh; getattr(fl)
7391 	 */
7392 	args.array_len = 7;
7393 	args.array = argop;
7394 
7395 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7396 	if (e.error) {
7397 		kmem_free(argop, argoplist_size);
7398 		nfs_rw_exit(&tdrp->r_rwlock);
7399 		return (e.error);
7400 	}
7401 
7402 	/* 0. putfh file */
7403 	argop[0].argop = OP_CPUTFH;
7404 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7405 
7406 	/* 1. save current fh to free up the space for the dir */
7407 	argop[1].argop = OP_SAVEFH;
7408 
7409 	/* 2. putfh targetdir */
7410 	argop[2].argop = OP_CPUTFH;
7411 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7412 
7413 	/* 3. link: current_fh is targetdir, saved_fh is source */
7414 	argop[3].argop = OP_CLINK;
7415 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7416 
7417 	/* 4. Get attributes of dir */
7418 	argop[4].argop = OP_GETATTR;
7419 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7420 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7421 
7422 	/* 5. If link was successful, restore current vp to file */
7423 	argop[5].argop = OP_RESTOREFH;
7424 
7425 	/* 6. Get attributes of linked object */
7426 	argop[6].argop = OP_GETATTR;
7427 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7428 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7429 
7430 	dnlc_remove(tdvp, tnm);
7431 
7432 	doqueue = 1;
7433 	t = gethrtime();
7434 
7435 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7436 
7437 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7438 	if (e.error != 0 && !needrecov) {
7439 		PURGE_ATTRCACHE4(tdvp);
7440 		PURGE_ATTRCACHE4(svp);
7441 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7442 		goto out;
7443 	}
7444 
7445 	if (needrecov) {
7446 		bool_t abort;
7447 
7448 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7449 		    NULL, NULL, OP_LINK, NULL);
7450 		if (abort == FALSE) {
7451 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7452 			    needrecov);
7453 			kmem_free(argop, argoplist_size);
7454 			if (!e.error)
7455 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7456 				    (caddr_t)&res);
7457 			goto recov_retry;
7458 		} else {
7459 			if (e.error != 0) {
7460 				PURGE_ATTRCACHE4(tdvp);
7461 				PURGE_ATTRCACHE4(svp);
7462 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7463 				    &recov_state, needrecov);
7464 				goto out;
7465 			}
7466 			/* fall through for res.status case */
7467 		}
7468 	}
7469 
7470 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7471 
7472 	resp = &res;
7473 	if (res.status) {
7474 		/* If link succeeded, then don't return error */
7475 		e.error = geterrno4(res.status);
7476 		if (res.array_len <= 4) {
7477 			/*
7478 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7479 			 */
7480 			PURGE_ATTRCACHE4(svp);
7481 			PURGE_ATTRCACHE4(tdvp);
7482 			if (e.error == EOPNOTSUPP) {
7483 				mutex_enter(&mi->mi_lock);
7484 				mi->mi_flags &= ~MI4_LINK;
7485 				mutex_exit(&mi->mi_lock);
7486 			}
7487 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7488 			/* XXX-LP */
7489 			if (e.error == EISDIR && crgetuid(cr) != 0)
7490 				e.error = EPERM;
7491 			goto out;
7492 		}
7493 	}
7494 
7495 	/* either no error or one of the postop getattr failed */
7496 
7497 	/*
7498 	 * XXX - if LINK succeeded, but no attrs were returned for link
7499 	 * file, purge its cache.
7500 	 *
7501 	 * XXX Perform a simplified version of wcc checking. Instead of
7502 	 * have another getattr to get pre-op, just purge cache if
7503 	 * any of the ops prior to and including the getattr failed.
7504 	 * If the getattr succeeded then update the attrcache accordingly.
7505 	 */
7506 
7507 	/*
7508 	 * update cache with link file postattrs.
7509 	 * Note: at this point resop points to link res.
7510 	 */
7511 	resop = &res.array[3];	/* link res */
7512 	ln_res = &resop->nfs_resop4_u.oplink;
7513 	if (res.status == NFS4_OK)
7514 		e.error = nfs4_update_attrcache(res.status,
7515 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res,
7516 		    t, svp, cr);
7517 
7518 	/*
7519 	 * Call makenfs4node to create the new shadow vp for tnm.
7520 	 * We pass NULL attrs because we just cached attrs for
7521 	 * the src object.  All we're trying to accomplish is to
7522 	 * to create the new shadow vnode.
7523 	 */
7524 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7525 	    tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm));
7526 
7527 	/* Update target cache attribute, readdir and dnlc caches */
7528 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7529 	dinfo.di_time_call = t;
7530 	dinfo.di_cred = cr;
7531 
7532 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7533 	ASSERT(nfs4_consistent_type(tdvp));
7534 	ASSERT(nfs4_consistent_type(svp));
7535 	ASSERT(nfs4_consistent_type(nvp));
7536 	VN_RELE(nvp);
7537 
7538 	if (!e.error) {
7539 		vnode_t *tvp;
7540 		rnode4_t *trp;
7541 		/*
7542 		 * Notify the source file of this link operation.
7543 		 */
7544 		trp = VTOR4(svp);
7545 		tvp = svp;
7546 		if (IS_SHADOW(svp, trp))
7547 			tvp = RTOV4(trp);
7548 		vnevent_link(tvp, ct);
7549 	}
7550 out:
7551 	kmem_free(argop, argoplist_size);
7552 	if (resp)
7553 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7554 
7555 	nfs_rw_exit(&tdrp->r_rwlock);
7556 
7557 	return (e.error);
7558 }
7559 
7560 /* ARGSUSED */
7561 static int
7562 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7563     caller_context_t *ct, int flags)
7564 {
7565 	vnode_t *realvp;
7566 
7567 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7568 		return (EPERM);
7569 	if (VOP_REALVP(ndvp, &realvp, ct) == 0)
7570 		ndvp = realvp;
7571 
7572 	return (nfs4rename(odvp, onm, ndvp, nnm, cr, ct));
7573 }
7574 
7575 /*
7576  * nfs4rename does the real work of renaming in NFS Version 4.
7577  *
7578  * A file handle is considered volatile for renaming purposes if either
7579  * of the volatile bits are turned on. However, the compound may differ
7580  * based on the likelihood of the filehandle to change during rename.
7581  */
7582 static int
7583 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7584     caller_context_t *ct)
7585 {
7586 	int error;
7587 	mntinfo4_t *mi;
7588 	vnode_t *nvp = NULL;
7589 	vnode_t *ovp = NULL;
7590 	char *tmpname = NULL;
7591 	rnode4_t *rp;
7592 	rnode4_t *odrp;
7593 	rnode4_t *ndrp;
7594 	int did_link = 0;
7595 	int do_link = 1;
7596 	nfsstat4 stat = NFS4_OK;
7597 
7598 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7599 	ASSERT(nfs4_consistent_type(odvp));
7600 	ASSERT(nfs4_consistent_type(ndvp));
7601 
7602 	if (onm[0] == '.' && (onm[1] == '\0' ||
7603 	    (onm[1] == '.' && onm[2] == '\0')))
7604 		return (EINVAL);
7605 
7606 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7607 	    (nnm[1] == '.' && nnm[2] == '\0')))
7608 		return (EINVAL);
7609 
7610 	odrp = VTOR4(odvp);
7611 	ndrp = VTOR4(ndvp);
7612 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7613 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7614 			return (EINTR);
7615 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7616 			nfs_rw_exit(&odrp->r_rwlock);
7617 			return (EINTR);
7618 		}
7619 	} else {
7620 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7621 			return (EINTR);
7622 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7623 			nfs_rw_exit(&ndrp->r_rwlock);
7624 			return (EINTR);
7625 		}
7626 	}
7627 
7628 	/*
7629 	 * Lookup the target file.  If it exists, it needs to be
7630 	 * checked to see whether it is a mount point and whether
7631 	 * it is active (open).
7632 	 */
7633 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7634 	if (!error) {
7635 		int	isactive;
7636 
7637 		ASSERT(nfs4_consistent_type(nvp));
7638 		/*
7639 		 * If this file has been mounted on, then just
7640 		 * return busy because renaming to it would remove
7641 		 * the mounted file system from the name space.
7642 		 */
7643 		if (vn_ismntpt(nvp)) {
7644 			VN_RELE(nvp);
7645 			nfs_rw_exit(&odrp->r_rwlock);
7646 			nfs_rw_exit(&ndrp->r_rwlock);
7647 			return (EBUSY);
7648 		}
7649 
7650 		/*
7651 		 * First just remove the entry from the name cache, as it
7652 		 * is most likely the only entry for this vp.
7653 		 */
7654 		dnlc_remove(ndvp, nnm);
7655 
7656 		rp = VTOR4(nvp);
7657 
7658 		if (nvp->v_type != VREG) {
7659 			/*
7660 			 * Purge the name cache of all references to this vnode
7661 			 * so that we can check the reference count to infer
7662 			 * whether it is active or not.
7663 			 */
7664 			if (nvp->v_count > 1)
7665 				dnlc_purge_vp(nvp);
7666 
7667 			isactive = nvp->v_count > 1;
7668 		} else {
7669 			mutex_enter(&rp->r_os_lock);
7670 			isactive = list_head(&rp->r_open_streams) != NULL;
7671 			mutex_exit(&rp->r_os_lock);
7672 		}
7673 
7674 		/*
7675 		 * If the vnode is active and is not a directory,
7676 		 * arrange to rename it to a
7677 		 * temporary file so that it will continue to be
7678 		 * accessible.  This implements the "unlink-open-file"
7679 		 * semantics for the target of a rename operation.
7680 		 * Before doing this though, make sure that the
7681 		 * source and target files are not already the same.
7682 		 */
7683 		if (isactive && nvp->v_type != VDIR) {
7684 			/*
7685 			 * Lookup the source name.
7686 			 */
7687 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7688 
7689 			/*
7690 			 * The source name *should* already exist.
7691 			 */
7692 			if (error) {
7693 				VN_RELE(nvp);
7694 				nfs_rw_exit(&odrp->r_rwlock);
7695 				nfs_rw_exit(&ndrp->r_rwlock);
7696 				return (error);
7697 			}
7698 
7699 			ASSERT(nfs4_consistent_type(ovp));
7700 
7701 			/*
7702 			 * Compare the two vnodes.  If they are the same,
7703 			 * just release all held vnodes and return success.
7704 			 */
7705 			if (VN_CMP(ovp, nvp)) {
7706 				VN_RELE(ovp);
7707 				VN_RELE(nvp);
7708 				nfs_rw_exit(&odrp->r_rwlock);
7709 				nfs_rw_exit(&ndrp->r_rwlock);
7710 				return (0);
7711 			}
7712 
7713 			/*
7714 			 * Can't mix and match directories and non-
7715 			 * directories in rename operations.  We already
7716 			 * know that the target is not a directory.  If
7717 			 * the source is a directory, return an error.
7718 			 */
7719 			if (ovp->v_type == VDIR) {
7720 				VN_RELE(ovp);
7721 				VN_RELE(nvp);
7722 				nfs_rw_exit(&odrp->r_rwlock);
7723 				nfs_rw_exit(&ndrp->r_rwlock);
7724 				return (ENOTDIR);
7725 			}
7726 link_call:
7727 			/*
7728 			 * The target file exists, is not the same as
7729 			 * the source file, and is active.  We first
7730 			 * try to Link it to a temporary filename to
7731 			 * avoid having the server removing the file
7732 			 * completely (which could cause data loss to
7733 			 * the user's POV in the event the Rename fails
7734 			 * -- see bug 1165874).
7735 			 */
7736 			/*
7737 			 * The do_link and did_link booleans are
7738 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7739 			 * returned for the Rename.  Some servers can
7740 			 * not Rename over an Open file, so they return
7741 			 * this error.  The client needs to Remove the
7742 			 * newly created Link and do two Renames, just
7743 			 * as if the server didn't support LINK.
7744 			 */
7745 			tmpname = newname();
7746 			error = 0;
7747 
7748 			if (do_link) {
7749 				error = nfs4_link(ndvp, nvp, tmpname, cr,
7750 				    NULL, 0);
7751 			}
7752 			if (error == EOPNOTSUPP || !do_link) {
7753 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7754 				    cr, NULL, 0);
7755 				did_link = 0;
7756 			} else {
7757 				did_link = 1;
7758 			}
7759 			if (error) {
7760 				kmem_free(tmpname, MAXNAMELEN);
7761 				VN_RELE(ovp);
7762 				VN_RELE(nvp);
7763 				nfs_rw_exit(&odrp->r_rwlock);
7764 				nfs_rw_exit(&ndrp->r_rwlock);
7765 				return (error);
7766 			}
7767 
7768 			mutex_enter(&rp->r_statelock);
7769 			if (rp->r_unldvp == NULL) {
7770 				VN_HOLD(ndvp);
7771 				rp->r_unldvp = ndvp;
7772 				if (rp->r_unlcred != NULL)
7773 					crfree(rp->r_unlcred);
7774 				crhold(cr);
7775 				rp->r_unlcred = cr;
7776 				rp->r_unlname = tmpname;
7777 			} else {
7778 				if (rp->r_unlname)
7779 					kmem_free(rp->r_unlname, MAXNAMELEN);
7780 				rp->r_unlname = tmpname;
7781 			}
7782 			mutex_exit(&rp->r_statelock);
7783 		}
7784 
7785 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7786 
7787 		ASSERT(nfs4_consistent_type(nvp));
7788 	}
7789 
7790 	if (ovp == NULL) {
7791 		/*
7792 		 * When renaming directories to be a subdirectory of a
7793 		 * different parent, the dnlc entry for ".." will no
7794 		 * longer be valid, so it must be removed.
7795 		 *
7796 		 * We do a lookup here to determine whether we are renaming
7797 		 * a directory and we need to check if we are renaming
7798 		 * an unlinked file.  This might have already been done
7799 		 * in previous code, so we check ovp == NULL to avoid
7800 		 * doing it twice.
7801 		 */
7802 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7803 		/*
7804 		 * The source name *should* already exist.
7805 		 */
7806 		if (error) {
7807 			nfs_rw_exit(&odrp->r_rwlock);
7808 			nfs_rw_exit(&ndrp->r_rwlock);
7809 			if (nvp) {
7810 				VN_RELE(nvp);
7811 			}
7812 			return (error);
7813 		}
7814 		ASSERT(ovp != NULL);
7815 		ASSERT(nfs4_consistent_type(ovp));
7816 	}
7817 
7818 	/*
7819 	 * Is the object being renamed a dir, and if so, is
7820 	 * it being renamed to a child of itself?  The underlying
7821 	 * fs should ultimately return EINVAL for this case;
7822 	 * however, buggy beta non-Solaris NFSv4 servers at
7823 	 * interop testing events have allowed this behavior,
7824 	 * and it caused our client to panic due to a recursive
7825 	 * mutex_enter in fn_move.
7826 	 *
7827 	 * The tedious locking in fn_move could be changed to
7828 	 * deal with this case, and the client could avoid the
7829 	 * panic; however, the client would just confuse itself
7830 	 * later and misbehave.  A better way to handle the broken
7831 	 * server is to detect this condition and return EINVAL
7832 	 * without ever sending the the bogus rename to the server.
7833 	 * We know the rename is invalid -- just fail it now.
7834 	 */
7835 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7836 		VN_RELE(ovp);
7837 		nfs_rw_exit(&odrp->r_rwlock);
7838 		nfs_rw_exit(&ndrp->r_rwlock);
7839 		if (nvp) {
7840 			VN_RELE(nvp);
7841 		}
7842 		return (EINVAL);
7843 	}
7844 
7845 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7846 
7847 	/*
7848 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7849 	 * possible for the filehandle to change due to the rename.
7850 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7851 	 * the fh will not change because of the rename, but we still need
7852 	 * to update its rnode entry with the new name for
7853 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7854 	 * has no effect on these for now, but for future improvements,
7855 	 * we might want to use it too to simplify handling of files
7856 	 * that are open with that flag on. (XXX)
7857 	 */
7858 	mi = VTOMI4(odvp);
7859 	if (NFS4_VOLATILE_FH(mi))
7860 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7861 		    &stat);
7862 	else
7863 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7864 		    &stat);
7865 
7866 	ASSERT(nfs4_consistent_type(odvp));
7867 	ASSERT(nfs4_consistent_type(ndvp));
7868 	ASSERT(nfs4_consistent_type(ovp));
7869 
7870 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
7871 		do_link = 0;
7872 		/*
7873 		 * Before the 'link_call' code, we did a nfs4_lookup
7874 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
7875 		 * call we call VN_RELE to match that hold.  We need
7876 		 * to place an additional VN_HOLD here since we will
7877 		 * be hitting that VN_RELE again.
7878 		 */
7879 		VN_HOLD(nvp);
7880 
7881 		(void) nfs4_remove(ndvp, tmpname, cr, NULL, 0);
7882 
7883 		/* Undo the unlinked file naming stuff we just did */
7884 		mutex_enter(&rp->r_statelock);
7885 		if (rp->r_unldvp) {
7886 			VN_RELE(ndvp);
7887 			rp->r_unldvp = NULL;
7888 			if (rp->r_unlcred != NULL)
7889 				crfree(rp->r_unlcred);
7890 			rp->r_unlcred = NULL;
7891 			/* rp->r_unlanme points to tmpname */
7892 			if (rp->r_unlname)
7893 				kmem_free(rp->r_unlname, MAXNAMELEN);
7894 			rp->r_unlname = NULL;
7895 		}
7896 		mutex_exit(&rp->r_statelock);
7897 
7898 		if (nvp) {
7899 			VN_RELE(nvp);
7900 		}
7901 		goto link_call;
7902 	}
7903 
7904 	if (error) {
7905 		VN_RELE(ovp);
7906 		nfs_rw_exit(&odrp->r_rwlock);
7907 		nfs_rw_exit(&ndrp->r_rwlock);
7908 		if (nvp) {
7909 			VN_RELE(nvp);
7910 		}
7911 		return (error);
7912 	}
7913 
7914 	/*
7915 	 * when renaming directories to be a subdirectory of a
7916 	 * different parent, the dnlc entry for ".." will no
7917 	 * longer be valid, so it must be removed
7918 	 */
7919 	rp = VTOR4(ovp);
7920 	if (ndvp != odvp) {
7921 		if (ovp->v_type == VDIR) {
7922 			dnlc_remove(ovp, "..");
7923 			if (rp->r_dir != NULL)
7924 				nfs4_purge_rddir_cache(ovp);
7925 		}
7926 	}
7927 
7928 	/*
7929 	 * If we are renaming the unlinked file, update the
7930 	 * r_unldvp and r_unlname as needed.
7931 	 */
7932 	mutex_enter(&rp->r_statelock);
7933 	if (rp->r_unldvp != NULL) {
7934 		if (strcmp(rp->r_unlname, onm) == 0) {
7935 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
7936 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
7937 			if (ndvp != rp->r_unldvp) {
7938 				VN_RELE(rp->r_unldvp);
7939 				rp->r_unldvp = ndvp;
7940 				VN_HOLD(ndvp);
7941 			}
7942 		}
7943 	}
7944 	mutex_exit(&rp->r_statelock);
7945 
7946 	/*
7947 	 * Notify the rename vnevents to source vnode, and to the target
7948 	 * vnode if it already existed.
7949 	 */
7950 	if (error == 0) {
7951 		vnode_t *tvp;
7952 		rnode4_t *trp;
7953 		/*
7954 		 * Notify the vnode. Each links is represented by
7955 		 * a different vnode, in nfsv4.
7956 		 */
7957 		if (nvp) {
7958 			trp = VTOR4(nvp);
7959 			tvp = nvp;
7960 			if (IS_SHADOW(nvp, trp))
7961 				tvp = RTOV4(trp);
7962 			vnevent_rename_dest(tvp, ndvp, nnm, ct);
7963 		}
7964 
7965 		/*
7966 		 * if the source and destination directory are not the
7967 		 * same notify the destination directory.
7968 		 */
7969 		if (VTOR4(odvp) != VTOR4(ndvp)) {
7970 			trp = VTOR4(ndvp);
7971 			tvp = ndvp;
7972 			if (IS_SHADOW(ndvp, trp))
7973 				tvp = RTOV4(trp);
7974 			vnevent_rename_dest_dir(tvp, ct);
7975 		}
7976 
7977 		trp = VTOR4(ovp);
7978 		tvp = ovp;
7979 		if (IS_SHADOW(ovp, trp))
7980 			tvp = RTOV4(trp);
7981 		vnevent_rename_src(tvp, odvp, onm, ct);
7982 	}
7983 
7984 	if (nvp) {
7985 		VN_RELE(nvp);
7986 	}
7987 	VN_RELE(ovp);
7988 
7989 	nfs_rw_exit(&odrp->r_rwlock);
7990 	nfs_rw_exit(&ndrp->r_rwlock);
7991 
7992 	return (error);
7993 }
7994 
7995 /*
7996  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
7997  * when it is known that the filehandle is persistent through rename.
7998  *
7999  * Rename requires that the current fh be the target directory and the
8000  * saved fh be the source directory. After the operation, the current fh
8001  * is unchanged.
8002  * The compound op structure for persistent fh rename is:
8003  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
8004  * Rather than bother with the directory postop args, we'll simply
8005  * update that a change occurred in the cache, so no post-op getattrs.
8006  */
8007 static int
8008 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
8009     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8010 {
8011 	COMPOUND4args_clnt args;
8012 	COMPOUND4res_clnt res, *resp = NULL;
8013 	nfs_argop4 *argop;
8014 	nfs_resop4 *resop;
8015 	int doqueue, argoplist_size;
8016 	mntinfo4_t *mi;
8017 	rnode4_t *odrp = VTOR4(odvp);
8018 	rnode4_t *ndrp = VTOR4(ndvp);
8019 	RENAME4res *rn_res;
8020 	bool_t needrecov;
8021 	nfs4_recov_state_t recov_state;
8022 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8023 	dirattr_info_t dinfo, *dinfop;
8024 
8025 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8026 
8027 	recov_state.rs_flags = 0;
8028 	recov_state.rs_num_retry_despite_err = 0;
8029 
8030 	/*
8031 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
8032 	 *
8033 	 * If source/target are different dirs, then append putfh(src); getattr
8034 	 */
8035 	args.array_len = (odvp == ndvp) ? 5 : 7;
8036 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8037 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8038 
8039 recov_retry:
8040 	*statp = NFS4_OK;
8041 
8042 	/* No need to Lookup the file, persistent fh */
8043 	args.ctag = TAG_RENAME;
8044 
8045 	mi = VTOMI4(odvp);
8046 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8047 	if (e.error) {
8048 		kmem_free(argop, argoplist_size);
8049 		return (e.error);
8050 	}
8051 
8052 	/* 0: putfh source directory */
8053 	argop[0].argop = OP_CPUTFH;
8054 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8055 
8056 	/* 1: Save source fh to free up current for target */
8057 	argop[1].argop = OP_SAVEFH;
8058 
8059 	/* 2: putfh targetdir */
8060 	argop[2].argop = OP_CPUTFH;
8061 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8062 
8063 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8064 	argop[3].argop = OP_CRENAME;
8065 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8066 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8067 
8068 	/* 4: getattr (targetdir) */
8069 	argop[4].argop = OP_GETATTR;
8070 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8071 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8072 
8073 	if (ndvp != odvp) {
8074 
8075 		/* 5: putfh (sourcedir) */
8076 		argop[5].argop = OP_CPUTFH;
8077 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8078 
8079 		/* 6: getattr (sourcedir) */
8080 		argop[6].argop = OP_GETATTR;
8081 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8082 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8083 	}
8084 
8085 	dnlc_remove(odvp, onm);
8086 	dnlc_remove(ndvp, nnm);
8087 
8088 	doqueue = 1;
8089 	dinfo.di_time_call = gethrtime();
8090 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8091 
8092 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8093 	if (e.error) {
8094 		PURGE_ATTRCACHE4(odvp);
8095 		PURGE_ATTRCACHE4(ndvp);
8096 	} else {
8097 		*statp = res.status;
8098 	}
8099 
8100 	if (needrecov) {
8101 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8102 		    OP_RENAME, NULL) == FALSE) {
8103 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8104 			if (!e.error)
8105 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8106 				    (caddr_t)&res);
8107 			goto recov_retry;
8108 		}
8109 	}
8110 
8111 	if (!e.error) {
8112 		resp = &res;
8113 		/*
8114 		 * as long as OP_RENAME
8115 		 */
8116 		if (res.status != NFS4_OK && res.array_len <= 4) {
8117 			e.error = geterrno4(res.status);
8118 			PURGE_ATTRCACHE4(odvp);
8119 			PURGE_ATTRCACHE4(ndvp);
8120 			/*
8121 			 * System V defines rename to return EEXIST, not
8122 			 * ENOTEMPTY if the target directory is not empty.
8123 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8124 			 * which geterrno4 maps to ENOTEMPTY.
8125 			 */
8126 			if (e.error == ENOTEMPTY)
8127 				e.error = EEXIST;
8128 		} else {
8129 
8130 			resop = &res.array[3];	/* rename res */
8131 			rn_res = &resop->nfs_resop4_u.oprename;
8132 
8133 			if (res.status == NFS4_OK) {
8134 				/*
8135 				 * Update target attribute, readdir and dnlc
8136 				 * caches.
8137 				 */
8138 				dinfo.di_garp =
8139 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8140 				dinfo.di_cred = cr;
8141 				dinfop = &dinfo;
8142 			} else
8143 				dinfop = NULL;
8144 
8145 			nfs4_update_dircaches(&rn_res->target_cinfo,
8146 			    ndvp, NULL, NULL, dinfop);
8147 
8148 			/*
8149 			 * Update source attribute, readdir and dnlc caches
8150 			 *
8151 			 */
8152 			if (ndvp != odvp) {
8153 				if (dinfop)
8154 					dinfo.di_garp =
8155 					    &(res.array[6].nfs_resop4_u.
8156 					    opgetattr.ga_res);
8157 
8158 				nfs4_update_dircaches(&rn_res->source_cinfo,
8159 				    odvp, NULL, NULL, dinfop);
8160 			}
8161 
8162 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8163 			    nnm);
8164 		}
8165 	}
8166 
8167 	if (resp)
8168 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8169 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8170 	kmem_free(argop, argoplist_size);
8171 
8172 	return (e.error);
8173 }
8174 
8175 /*
8176  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8177  * it is possible for the filehandle to change due to the rename.
8178  *
8179  * The compound req in this case includes a post-rename lookup and getattr
8180  * to ensure that we have the correct fh and attributes for the object.
8181  *
8182  * Rename requires that the current fh be the target directory and the
8183  * saved fh be the source directory. After the operation, the current fh
8184  * is unchanged.
8185  *
8186  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8187  * update the filehandle for the renamed object.  We also get the old
8188  * filehandle for historical reasons; this should be taken out sometime.
8189  * This results in a rather cumbersome compound...
8190  *
8191  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8192  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8193  *
8194  */
8195 static int
8196 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8197     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8198 {
8199 	COMPOUND4args_clnt args;
8200 	COMPOUND4res_clnt res, *resp = NULL;
8201 	int argoplist_size;
8202 	nfs_argop4 *argop;
8203 	nfs_resop4 *resop;
8204 	int doqueue;
8205 	mntinfo4_t *mi;
8206 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8207 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8208 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8209 	RENAME4res *rn_res;
8210 	GETFH4res *ngf_res;
8211 	bool_t needrecov;
8212 	nfs4_recov_state_t recov_state;
8213 	hrtime_t t;
8214 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8215 	dirattr_info_t dinfo, *dinfop = &dinfo;
8216 
8217 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8218 
8219 	recov_state.rs_flags = 0;
8220 	recov_state.rs_num_retry_despite_err = 0;
8221 
8222 recov_retry:
8223 	*statp = NFS4_OK;
8224 
8225 	/*
8226 	 * There is a window between the RPC and updating the path and
8227 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8228 	 * code, so that it doesn't try to use the old path during that
8229 	 * window.
8230 	 */
8231 	mutex_enter(&orp->r_statelock);
8232 	while (orp->r_flags & R4RECEXPFH) {
8233 		klwp_t *lwp = ttolwp(curthread);
8234 
8235 		if (lwp != NULL)
8236 			lwp->lwp_nostop++;
8237 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8238 			mutex_exit(&orp->r_statelock);
8239 			if (lwp != NULL)
8240 				lwp->lwp_nostop--;
8241 			return (EINTR);
8242 		}
8243 		if (lwp != NULL)
8244 			lwp->lwp_nostop--;
8245 	}
8246 	orp->r_flags |= R4RECEXPFH;
8247 	mutex_exit(&orp->r_statelock);
8248 
8249 	mi = VTOMI4(odvp);
8250 
8251 	args.ctag = TAG_RENAME_VFH;
8252 	args.array_len = (odvp == ndvp) ? 10 : 12;
8253 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8254 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8255 
8256 	/*
8257 	 * Rename ops:
8258 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8259 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8260 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8261 	 *
8262 	 *    if (odvp != ndvp)
8263 	 *	add putfh(sourcedir), getattr(sourcedir) }
8264 	 */
8265 	args.array = argop;
8266 
8267 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8268 	    &recov_state, NULL);
8269 	if (e.error) {
8270 		kmem_free(argop, argoplist_size);
8271 		mutex_enter(&orp->r_statelock);
8272 		orp->r_flags &= ~R4RECEXPFH;
8273 		cv_broadcast(&orp->r_cv);
8274 		mutex_exit(&orp->r_statelock);
8275 		return (e.error);
8276 	}
8277 
8278 	/* 0: putfh source directory */
8279 	argop[0].argop = OP_CPUTFH;
8280 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8281 
8282 	/* 1: Save source fh to free up current for target */
8283 	argop[1].argop = OP_SAVEFH;
8284 
8285 	/* 2: Lookup pre-rename fh of renamed object */
8286 	argop[2].argop = OP_CLOOKUP;
8287 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8288 
8289 	/* 3: getfh fh of renamed object (before rename) */
8290 	argop[3].argop = OP_GETFH;
8291 
8292 	/* 4: putfh targetdir */
8293 	argop[4].argop = OP_CPUTFH;
8294 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8295 
8296 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8297 	argop[5].argop = OP_CRENAME;
8298 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8299 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8300 
8301 	/* 6: getattr of target dir (post op attrs) */
8302 	argop[6].argop = OP_GETATTR;
8303 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8304 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8305 
8306 	/* 7: Lookup post-rename fh of renamed object */
8307 	argop[7].argop = OP_CLOOKUP;
8308 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8309 
8310 	/* 8: getfh fh of renamed object (after rename) */
8311 	argop[8].argop = OP_GETFH;
8312 
8313 	/* 9: getattr of renamed object */
8314 	argop[9].argop = OP_GETATTR;
8315 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8316 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8317 
8318 	/*
8319 	 * If source/target dirs are different, then get new post-op
8320 	 * attrs for source dir also.
8321 	 */
8322 	if (ndvp != odvp) {
8323 		/* 10: putfh (sourcedir) */
8324 		argop[10].argop = OP_CPUTFH;
8325 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8326 
8327 		/* 11: getattr (sourcedir) */
8328 		argop[11].argop = OP_GETATTR;
8329 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8330 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8331 	}
8332 
8333 	dnlc_remove(odvp, onm);
8334 	dnlc_remove(ndvp, nnm);
8335 
8336 	doqueue = 1;
8337 	t = gethrtime();
8338 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8339 
8340 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8341 	if (e.error) {
8342 		PURGE_ATTRCACHE4(odvp);
8343 		PURGE_ATTRCACHE4(ndvp);
8344 		if (!needrecov) {
8345 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8346 			    &recov_state, needrecov);
8347 			goto out;
8348 		}
8349 	} else {
8350 		*statp = res.status;
8351 	}
8352 
8353 	if (needrecov) {
8354 		bool_t abort;
8355 
8356 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8357 		    OP_RENAME, NULL);
8358 		if (abort == FALSE) {
8359 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8360 			    &recov_state, needrecov);
8361 			kmem_free(argop, argoplist_size);
8362 			if (!e.error)
8363 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8364 				    (caddr_t)&res);
8365 			mutex_enter(&orp->r_statelock);
8366 			orp->r_flags &= ~R4RECEXPFH;
8367 			cv_broadcast(&orp->r_cv);
8368 			mutex_exit(&orp->r_statelock);
8369 			goto recov_retry;
8370 		} else {
8371 			if (e.error != 0) {
8372 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8373 				    &recov_state, needrecov);
8374 				goto out;
8375 			}
8376 			/* fall through for res.status case */
8377 		}
8378 	}
8379 
8380 	resp = &res;
8381 	/*
8382 	 * If OP_RENAME (or any prev op) failed, then return an error.
8383 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8384 	 */
8385 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8386 		/*
8387 		 * Error in an op other than last Getattr
8388 		 */
8389 		e.error = geterrno4(res.status);
8390 		PURGE_ATTRCACHE4(odvp);
8391 		PURGE_ATTRCACHE4(ndvp);
8392 		/*
8393 		 * System V defines rename to return EEXIST, not
8394 		 * ENOTEMPTY if the target directory is not empty.
8395 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8396 		 * which geterrno4 maps to ENOTEMPTY.
8397 		 */
8398 		if (e.error == ENOTEMPTY)
8399 			e.error = EEXIST;
8400 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8401 		    needrecov);
8402 		goto out;
8403 	}
8404 
8405 	/* rename results */
8406 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8407 
8408 	if (res.status == NFS4_OK) {
8409 		/* Update target attribute, readdir and dnlc caches */
8410 		dinfo.di_garp =
8411 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
8412 		dinfo.di_cred = cr;
8413 		dinfo.di_time_call = t;
8414 	} else
8415 		dinfop = NULL;
8416 
8417 	/* Update source cache attribute, readdir and dnlc caches */
8418 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8419 
8420 	/* Update source cache attribute, readdir and dnlc caches */
8421 	if (ndvp != odvp) {
8422 
8423 		/*
8424 		 * If dinfop is non-NULL, then compound succeded, so
8425 		 * set di_garp to attrs for source dir.  dinfop is only
8426 		 * set to NULL when compound fails.
8427 		 */
8428 		if (dinfop)
8429 			dinfo.di_garp =
8430 			    &res.array[11].nfs_resop4_u.opgetattr.ga_res;
8431 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8432 		    dinfop);
8433 	}
8434 
8435 	/*
8436 	 * Update the rnode with the new component name and args,
8437 	 * and if the file handle changed, also update it with the new fh.
8438 	 * This is only necessary if the target object has an rnode
8439 	 * entry and there is no need to create one for it.
8440 	 */
8441 	resop = &res.array[8];	/* getfh new res */
8442 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8443 
8444 	/*
8445 	 * Update the path and filehandle for the renamed object.
8446 	 */
8447 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8448 
8449 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8450 
8451 	if (res.status == NFS4_OK) {
8452 		resop++;	/* getattr res */
8453 		e.error = nfs4_update_attrcache(res.status,
8454 		    &resop->nfs_resop4_u.opgetattr.ga_res,
8455 		    t, ovp, cr);
8456 	}
8457 
8458 out:
8459 	kmem_free(argop, argoplist_size);
8460 	if (resp)
8461 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8462 	mutex_enter(&orp->r_statelock);
8463 	orp->r_flags &= ~R4RECEXPFH;
8464 	cv_broadcast(&orp->r_cv);
8465 	mutex_exit(&orp->r_statelock);
8466 
8467 	return (e.error);
8468 }
8469 
8470 /* ARGSUSED */
8471 static int
8472 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr,
8473     caller_context_t *ct, int flags, vsecattr_t *vsecp)
8474 {
8475 	int error;
8476 	vnode_t *vp;
8477 
8478 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8479 		return (EPERM);
8480 	/*
8481 	 * As ".." has special meaning and rather than send a mkdir
8482 	 * over the wire to just let the server freak out, we just
8483 	 * short circuit it here and return EEXIST
8484 	 */
8485 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8486 		return (EEXIST);
8487 
8488 	/*
8489 	 * Decision to get the right gid and setgid bit of the
8490 	 * new directory is now made in call_nfs4_create_req.
8491 	 */
8492 	va->va_mask |= AT_MODE;
8493 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8494 	if (error)
8495 		return (error);
8496 
8497 	*vpp = vp;
8498 	return (0);
8499 }
8500 
8501 
8502 /*
8503  * rmdir is using the same remove v4 op as does remove.
8504  * Remove requires that the current fh be the target directory.
8505  * After the operation, the current fh is unchanged.
8506  * The compound op structure is:
8507  *      PUTFH(targetdir), REMOVE
8508  */
8509 /*ARGSUSED4*/
8510 static int
8511 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr,
8512     caller_context_t *ct, int flags)
8513 {
8514 	int need_end_op = FALSE;
8515 	COMPOUND4args_clnt args;
8516 	COMPOUND4res_clnt res, *resp = NULL;
8517 	REMOVE4res *rm_res;
8518 	nfs_argop4 argop[3];
8519 	nfs_resop4 *resop;
8520 	vnode_t *vp;
8521 	int doqueue;
8522 	mntinfo4_t *mi;
8523 	rnode4_t *drp;
8524 	bool_t needrecov = FALSE;
8525 	nfs4_recov_state_t recov_state;
8526 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8527 	dirattr_info_t dinfo, *dinfop;
8528 
8529 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8530 		return (EPERM);
8531 	/*
8532 	 * As ".." has special meaning and rather than send a rmdir
8533 	 * over the wire to just let the server freak out, we just
8534 	 * short circuit it here and return EEXIST
8535 	 */
8536 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8537 		return (EEXIST);
8538 
8539 	drp = VTOR4(dvp);
8540 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8541 		return (EINTR);
8542 
8543 	/*
8544 	 * Attempt to prevent a rmdir(".") from succeeding.
8545 	 */
8546 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8547 	if (e.error) {
8548 		nfs_rw_exit(&drp->r_rwlock);
8549 		return (e.error);
8550 	}
8551 	if (vp == cdir) {
8552 		VN_RELE(vp);
8553 		nfs_rw_exit(&drp->r_rwlock);
8554 		return (EINVAL);
8555 	}
8556 
8557 	/*
8558 	 * Since nfsv4 remove op works on both files and directories,
8559 	 * check that the removed object is indeed a directory.
8560 	 */
8561 	if (vp->v_type != VDIR) {
8562 		VN_RELE(vp);
8563 		nfs_rw_exit(&drp->r_rwlock);
8564 		return (ENOTDIR);
8565 	}
8566 
8567 	/*
8568 	 * First just remove the entry from the name cache, as it
8569 	 * is most likely an entry for this vp.
8570 	 */
8571 	dnlc_remove(dvp, nm);
8572 
8573 	/*
8574 	 * If there vnode reference count is greater than one, then
8575 	 * there may be additional references in the DNLC which will
8576 	 * need to be purged.  First, trying removing the entry for
8577 	 * the parent directory and see if that removes the additional
8578 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8579 	 * to completely remove any references to the directory which
8580 	 * might still exist in the DNLC.
8581 	 */
8582 	if (vp->v_count > 1) {
8583 		dnlc_remove(vp, "..");
8584 		if (vp->v_count > 1)
8585 			dnlc_purge_vp(vp);
8586 	}
8587 
8588 	mi = VTOMI4(dvp);
8589 	recov_state.rs_flags = 0;
8590 	recov_state.rs_num_retry_despite_err = 0;
8591 
8592 recov_retry:
8593 	args.ctag = TAG_RMDIR;
8594 
8595 	/*
8596 	 * Rmdir ops: putfh dir; remove
8597 	 */
8598 	args.array_len = 3;
8599 	args.array = argop;
8600 
8601 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8602 	if (e.error) {
8603 		nfs_rw_exit(&drp->r_rwlock);
8604 		return (e.error);
8605 	}
8606 	need_end_op = TRUE;
8607 
8608 	/* putfh directory */
8609 	argop[0].argop = OP_CPUTFH;
8610 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8611 
8612 	/* remove */
8613 	argop[1].argop = OP_CREMOVE;
8614 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8615 
8616 	/* getattr (postop attrs for dir that contained removed dir) */
8617 	argop[2].argop = OP_GETATTR;
8618 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8619 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8620 
8621 	dinfo.di_time_call = gethrtime();
8622 	doqueue = 1;
8623 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8624 
8625 	PURGE_ATTRCACHE4(vp);
8626 
8627 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8628 	if (e.error) {
8629 		PURGE_ATTRCACHE4(dvp);
8630 	}
8631 
8632 	if (needrecov) {
8633 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8634 		    NULL, OP_REMOVE, NULL) == FALSE) {
8635 			if (!e.error)
8636 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8637 				    (caddr_t)&res);
8638 
8639 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8640 			    needrecov);
8641 			need_end_op = FALSE;
8642 			goto recov_retry;
8643 		}
8644 	}
8645 
8646 	if (!e.error) {
8647 		resp = &res;
8648 
8649 		/*
8650 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8651 		 * failed.
8652 		 */
8653 		if (res.status != NFS4_OK && res.array_len <= 2) {
8654 			e.error = geterrno4(res.status);
8655 			PURGE_ATTRCACHE4(dvp);
8656 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8657 			    &recov_state, needrecov);
8658 			need_end_op = FALSE;
8659 			nfs4_purge_stale_fh(e.error, dvp, cr);
8660 			/*
8661 			 * System V defines rmdir to return EEXIST, not
8662 			 * ENOTEMPTY if the directory is not empty.  Over
8663 			 * the wire, the error is NFSERR_ENOTEMPTY which
8664 			 * geterrno4 maps to ENOTEMPTY.
8665 			 */
8666 			if (e.error == ENOTEMPTY)
8667 				e.error = EEXIST;
8668 		} else {
8669 			resop = &res.array[1];	/* remove res */
8670 			rm_res = &resop->nfs_resop4_u.opremove;
8671 
8672 			if (res.status == NFS4_OK) {
8673 				resop = &res.array[2];	/* dir attrs */
8674 				dinfo.di_garp =
8675 				    &resop->nfs_resop4_u.opgetattr.ga_res;
8676 				dinfo.di_cred = cr;
8677 				dinfop = &dinfo;
8678 			} else
8679 				dinfop = NULL;
8680 
8681 			/* Update dir attribute, readdir and dnlc caches */
8682 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8683 			    dinfop);
8684 
8685 			/* destroy rddir cache for dir that was removed */
8686 			if (VTOR4(vp)->r_dir != NULL)
8687 				nfs4_purge_rddir_cache(vp);
8688 		}
8689 	}
8690 
8691 	if (need_end_op)
8692 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8693 
8694 	nfs_rw_exit(&drp->r_rwlock);
8695 
8696 	if (resp)
8697 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8698 
8699 	if (e.error == 0) {
8700 		vnode_t *tvp;
8701 		rnode4_t *trp;
8702 		trp = VTOR4(vp);
8703 		tvp = vp;
8704 		if (IS_SHADOW(vp, trp))
8705 			tvp = RTOV4(trp);
8706 		vnevent_rmdir(tvp, dvp, nm, ct);
8707 	}
8708 
8709 	VN_RELE(vp);
8710 
8711 	return (e.error);
8712 }
8713 
8714 /* ARGSUSED */
8715 static int
8716 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr,
8717     caller_context_t *ct, int flags)
8718 {
8719 	int error;
8720 	vnode_t *vp;
8721 	rnode4_t *rp;
8722 	char *contents;
8723 	mntinfo4_t *mi = VTOMI4(dvp);
8724 
8725 	if (nfs_zone() != mi->mi_zone)
8726 		return (EPERM);
8727 	if (!(mi->mi_flags & MI4_SYMLINK))
8728 		return (EOPNOTSUPP);
8729 
8730 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8731 	if (error)
8732 		return (error);
8733 
8734 	ASSERT(nfs4_consistent_type(vp));
8735 	rp = VTOR4(vp);
8736 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8737 
8738 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8739 
8740 		if (contents != NULL) {
8741 			mutex_enter(&rp->r_statelock);
8742 			if (rp->r_symlink.contents == NULL) {
8743 				rp->r_symlink.len = strlen(tnm);
8744 				bcopy(tnm, contents, rp->r_symlink.len);
8745 				rp->r_symlink.contents = contents;
8746 				rp->r_symlink.size = MAXPATHLEN;
8747 				mutex_exit(&rp->r_statelock);
8748 			} else {
8749 				mutex_exit(&rp->r_statelock);
8750 				kmem_free((void *)contents, MAXPATHLEN);
8751 			}
8752 		}
8753 	}
8754 	VN_RELE(vp);
8755 
8756 	return (error);
8757 }
8758 
8759 
8760 /*
8761  * Read directory entries.
8762  * There are some weird things to look out for here.  The uio_loffset
8763  * field is either 0 or it is the offset returned from a previous
8764  * readdir.  It is an opaque value used by the server to find the
8765  * correct directory block to read. The count field is the number
8766  * of blocks to read on the server.  This is advisory only, the server
8767  * may return only one block's worth of entries.  Entries may be compressed
8768  * on the server.
8769  */
8770 /* ARGSUSED */
8771 static int
8772 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp,
8773 	caller_context_t *ct, int flags)
8774 {
8775 	int error;
8776 	uint_t count;
8777 	rnode4_t *rp;
8778 	rddir4_cache *rdc;
8779 	rddir4_cache *rrdc;
8780 
8781 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8782 		return (EIO);
8783 	rp = VTOR4(vp);
8784 
8785 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8786 
8787 	/*
8788 	 * Make sure that the directory cache is valid.
8789 	 */
8790 	if (rp->r_dir != NULL) {
8791 		if (nfs_disable_rddir_cache != 0) {
8792 			/*
8793 			 * Setting nfs_disable_rddir_cache in /etc/system
8794 			 * allows interoperability with servers that do not
8795 			 * properly update the attributes of directories.
8796 			 * Any cached information gets purged before an
8797 			 * access is made to it.
8798 			 */
8799 			nfs4_purge_rddir_cache(vp);
8800 		}
8801 
8802 		error = nfs4_validate_caches(vp, cr);
8803 		if (error)
8804 			return (error);
8805 	}
8806 
8807 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8808 
8809 	/*
8810 	 * Short circuit last readdir which always returns 0 bytes.
8811 	 * This can be done after the directory has been read through
8812 	 * completely at least once.  This will set r_direof which
8813 	 * can be used to find the value of the last cookie.
8814 	 */
8815 	mutex_enter(&rp->r_statelock);
8816 	if (rp->r_direof != NULL &&
8817 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8818 		mutex_exit(&rp->r_statelock);
8819 #ifdef DEBUG
8820 		nfs4_readdir_cache_shorts++;
8821 #endif
8822 		if (eofp)
8823 			*eofp = 1;
8824 		return (0);
8825 	}
8826 
8827 	/*
8828 	 * Look for a cache entry.  Cache entries are identified
8829 	 * by the NFS cookie value and the byte count requested.
8830 	 */
8831 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8832 
8833 	/*
8834 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8835 	 */
8836 	if (rdc == NULL) {
8837 		mutex_exit(&rp->r_statelock);
8838 		return (EINTR);
8839 	}
8840 
8841 	/*
8842 	 * Check to see if we need to fill this entry in.
8843 	 */
8844 	if (rdc->flags & RDDIRREQ) {
8845 		rdc->flags &= ~RDDIRREQ;
8846 		rdc->flags |= RDDIR;
8847 		mutex_exit(&rp->r_statelock);
8848 
8849 		/*
8850 		 * Do the readdir.
8851 		 */
8852 		nfs4readdir(vp, rdc, cr);
8853 
8854 		/*
8855 		 * Reacquire the lock, so that we can continue
8856 		 */
8857 		mutex_enter(&rp->r_statelock);
8858 		/*
8859 		 * The entry is now complete
8860 		 */
8861 		rdc->flags &= ~RDDIR;
8862 	}
8863 
8864 	ASSERT(!(rdc->flags & RDDIR));
8865 
8866 	/*
8867 	 * If an error occurred while attempting
8868 	 * to fill the cache entry, mark the entry invalid and
8869 	 * just return the error.
8870 	 */
8871 	if (rdc->error) {
8872 		error = rdc->error;
8873 		rdc->flags |= RDDIRREQ;
8874 		rddir4_cache_rele(rp, rdc);
8875 		mutex_exit(&rp->r_statelock);
8876 		return (error);
8877 	}
8878 
8879 	/*
8880 	 * The cache entry is complete and good,
8881 	 * copyout the dirent structs to the calling
8882 	 * thread.
8883 	 */
8884 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
8885 
8886 	/*
8887 	 * If no error occurred during the copyout,
8888 	 * update the offset in the uio struct to
8889 	 * contain the value of the next NFS 4 cookie
8890 	 * and set the eof value appropriately.
8891 	 */
8892 	if (!error) {
8893 		uiop->uio_loffset = rdc->nfs4_ncookie;
8894 		if (eofp)
8895 			*eofp = rdc->eof;
8896 	}
8897 
8898 	/*
8899 	 * Decide whether to do readahead.  Don't if we
8900 	 * have already read to the end of directory.
8901 	 */
8902 	if (rdc->eof) {
8903 		/*
8904 		 * Make the entry the direof only if it is cached
8905 		 */
8906 		if (rdc->flags & RDDIRCACHED)
8907 			rp->r_direof = rdc;
8908 		rddir4_cache_rele(rp, rdc);
8909 		mutex_exit(&rp->r_statelock);
8910 		return (error);
8911 	}
8912 
8913 	/* Determine if a readdir readahead should be done */
8914 	if (!(rp->r_flags & R4LOOKUP)) {
8915 		rddir4_cache_rele(rp, rdc);
8916 		mutex_exit(&rp->r_statelock);
8917 		return (error);
8918 	}
8919 
8920 	/*
8921 	 * Now look for a readahead entry.
8922 	 *
8923 	 * Check to see whether we found an entry for the readahead.
8924 	 * If so, we don't need to do anything further, so free the new
8925 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
8926 	 * it to the cache, and then initiate an asynchronous readdir
8927 	 * operation to fill it.
8928 	 */
8929 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
8930 
8931 	/*
8932 	 * A readdir cache entry could not be obtained for the readahead.  In
8933 	 * this case we skip the readahead and return.
8934 	 */
8935 	if (rrdc == NULL) {
8936 		rddir4_cache_rele(rp, rdc);
8937 		mutex_exit(&rp->r_statelock);
8938 		return (error);
8939 	}
8940 
8941 	/*
8942 	 * Check to see if we need to fill this entry in.
8943 	 */
8944 	if (rrdc->flags & RDDIRREQ) {
8945 		rrdc->flags &= ~RDDIRREQ;
8946 		rrdc->flags |= RDDIR;
8947 		rddir4_cache_rele(rp, rdc);
8948 		mutex_exit(&rp->r_statelock);
8949 #ifdef DEBUG
8950 		nfs4_readdir_readahead++;
8951 #endif
8952 		/*
8953 		 * Do the readdir.
8954 		 */
8955 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
8956 		return (error);
8957 	}
8958 
8959 	rddir4_cache_rele(rp, rrdc);
8960 	rddir4_cache_rele(rp, rdc);
8961 	mutex_exit(&rp->r_statelock);
8962 	return (error);
8963 }
8964 
8965 static int
8966 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
8967 {
8968 	int error;
8969 	rnode4_t *rp;
8970 
8971 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
8972 
8973 	rp = VTOR4(vp);
8974 
8975 	/*
8976 	 * Obtain the readdir results for the caller.
8977 	 */
8978 	nfs4readdir(vp, rdc, cr);
8979 
8980 	mutex_enter(&rp->r_statelock);
8981 	/*
8982 	 * The entry is now complete
8983 	 */
8984 	rdc->flags &= ~RDDIR;
8985 
8986 	error = rdc->error;
8987 	if (error)
8988 		rdc->flags |= RDDIRREQ;
8989 	rddir4_cache_rele(rp, rdc);
8990 	mutex_exit(&rp->r_statelock);
8991 
8992 	return (error);
8993 }
8994 
8995 /*
8996  * Read directory entries.
8997  * There are some weird things to look out for here.  The uio_loffset
8998  * field is either 0 or it is the offset returned from a previous
8999  * readdir.  It is an opaque value used by the server to find the
9000  * correct directory block to read. The count field is the number
9001  * of blocks to read on the server.  This is advisory only, the server
9002  * may return only one block's worth of entries.  Entries may be compressed
9003  * on the server.
9004  *
9005  * Generates the following compound request:
9006  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9007  *    must include a Lookupp as well. In this case, send:
9008  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9009  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9010  *
9011  * Get complete attributes and filehandles for entries if this is the
9012  * first read of the directory. Otherwise, just get fileid's.
9013  */
9014 static void
9015 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9016 {
9017 	COMPOUND4args_clnt args;
9018 	COMPOUND4res_clnt res;
9019 	READDIR4args *rargs;
9020 	READDIR4res_clnt *rd_res;
9021 	bitmap4 rd_bitsval;
9022 	nfs_argop4 argop[5];
9023 	nfs_resop4 *resop;
9024 	rnode4_t *rp = VTOR4(vp);
9025 	mntinfo4_t *mi = VTOMI4(vp);
9026 	int doqueue;
9027 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9028 	vnode_t *dvp;
9029 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9030 	int num_ops, res_opcnt;
9031 	bool_t needrecov = FALSE;
9032 	nfs4_recov_state_t recov_state;
9033 	hrtime_t t;
9034 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9035 
9036 	ASSERT(nfs_zone() == mi->mi_zone);
9037 	ASSERT(rdc->flags & RDDIR);
9038 	ASSERT(rdc->entries == NULL);
9039 
9040 	/*
9041 	 * If rp were a stub, it should have triggered and caused
9042 	 * a mount for us to get this far.
9043 	 */
9044 	ASSERT(!RP_ISSTUB(rp));
9045 
9046 	num_ops = 2;
9047 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9048 		/*
9049 		 * Since nfsv4 readdir may not return entries for "." and "..",
9050 		 * the client must recreate them:
9051 		 * To find the correct nodeid, do the following:
9052 		 * For current node, get nodeid from dnlc.
9053 		 * - if current node is rootvp, set pnodeid to nodeid.
9054 		 * - else if parent is in the dnlc, get its nodeid from there.
9055 		 * - else add LOOKUPP+GETATTR to compound.
9056 		 */
9057 		nodeid = rp->r_attr.va_nodeid;
9058 		if (vp->v_flag & VROOT) {
9059 			pnodeid = nodeid;	/* root of mount point */
9060 		} else {
9061 			dvp = dnlc_lookup(vp, "..");
9062 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9063 				/* parent in dnlc cache - no need for otw */
9064 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9065 			} else {
9066 				/*
9067 				 * parent not in dnlc cache,
9068 				 * do lookupp to get its id
9069 				 */
9070 				num_ops = 5;
9071 				pnodeid = 0; /* set later by getattr parent */
9072 			}
9073 			if (dvp)
9074 				VN_RELE(dvp);
9075 		}
9076 	}
9077 	recov_state.rs_flags = 0;
9078 	recov_state.rs_num_retry_despite_err = 0;
9079 
9080 	/* Save the original mount point security flavor */
9081 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9082 
9083 recov_retry:
9084 	args.ctag = TAG_READDIR;
9085 
9086 	args.array = argop;
9087 	args.array_len = num_ops;
9088 
9089 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9090 	    &recov_state, NULL)) {
9091 		/*
9092 		 * If readdir a node that is a stub for a crossed mount point,
9093 		 * keep the original secinfo flavor for the current file
9094 		 * system, not the crossed one.
9095 		 */
9096 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9097 		rdc->error = e.error;
9098 		return;
9099 	}
9100 
9101 	/*
9102 	 * Determine which attrs to request for dirents.  This code
9103 	 * must be protected by nfs4_start/end_fop because of r_server
9104 	 * (which will change during failover recovery).
9105 	 *
9106 	 */
9107 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9108 		/*
9109 		 * Get all vattr attrs plus filehandle and rdattr_error
9110 		 */
9111 		rd_bitsval = NFS4_VATTR_MASK |
9112 		    FATTR4_RDATTR_ERROR_MASK |
9113 		    FATTR4_FILEHANDLE_MASK;
9114 
9115 		if (rp->r_flags & R4READDIRWATTR) {
9116 			mutex_enter(&rp->r_statelock);
9117 			rp->r_flags &= ~R4READDIRWATTR;
9118 			mutex_exit(&rp->r_statelock);
9119 		}
9120 	} else {
9121 		servinfo4_t *svp = rp->r_server;
9122 
9123 		/*
9124 		 * Already read directory. Use readdir with
9125 		 * no attrs (except for mounted_on_fileid) for updates.
9126 		 */
9127 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9128 
9129 		/*
9130 		 * request mounted on fileid if supported, else request
9131 		 * fileid.  maybe we should verify that fileid is supported
9132 		 * and request something else if not.
9133 		 */
9134 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9135 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9136 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9137 		nfs_rw_exit(&svp->sv_lock);
9138 	}
9139 
9140 	/* putfh directory fh */
9141 	argop[0].argop = OP_CPUTFH;
9142 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9143 
9144 	argop[1].argop = OP_READDIR;
9145 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9146 	/*
9147 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9148 	 * cookie 0 should be used over-the-wire to start reading at
9149 	 * the beginning of the directory excluding "." and "..".
9150 	 */
9151 	if (rdc->nfs4_cookie == 0 ||
9152 	    rdc->nfs4_cookie == 1 ||
9153 	    rdc->nfs4_cookie == 2) {
9154 		rargs->cookie = (nfs_cookie4)0;
9155 		rargs->cookieverf = 0;
9156 	} else {
9157 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9158 		mutex_enter(&rp->r_statelock);
9159 		rargs->cookieverf = rp->r_cookieverf4;
9160 		mutex_exit(&rp->r_statelock);
9161 	}
9162 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9163 	rargs->maxcount = mi->mi_tsize;
9164 	rargs->attr_request = rd_bitsval;
9165 	rargs->rdc = rdc;
9166 	rargs->dvp = vp;
9167 	rargs->mi = mi;
9168 	rargs->cr = cr;
9169 
9170 
9171 	/*
9172 	 * If count < than the minimum required, we return no entries
9173 	 * and fail with EINVAL
9174 	 */
9175 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9176 		rdc->error = EINVAL;
9177 		goto out;
9178 	}
9179 
9180 	if (args.array_len == 5) {
9181 		/*
9182 		 * Add lookupp and getattr for parent nodeid.
9183 		 */
9184 		argop[2].argop = OP_LOOKUPP;
9185 
9186 		argop[3].argop = OP_GETFH;
9187 
9188 		/* getattr parent */
9189 		argop[4].argop = OP_GETATTR;
9190 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9191 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9192 	}
9193 
9194 	doqueue = 1;
9195 
9196 	if (mi->mi_io_kstats) {
9197 		mutex_enter(&mi->mi_lock);
9198 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9199 		mutex_exit(&mi->mi_lock);
9200 	}
9201 
9202 	/* capture the time of this call */
9203 	rargs->t = t = gethrtime();
9204 
9205 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9206 
9207 	if (mi->mi_io_kstats) {
9208 		mutex_enter(&mi->mi_lock);
9209 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9210 		mutex_exit(&mi->mi_lock);
9211 	}
9212 
9213 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9214 
9215 	/*
9216 	 * If RPC error occurred and it isn't an error that
9217 	 * triggers recovery, then go ahead and fail now.
9218 	 */
9219 	if (e.error != 0 && !needrecov) {
9220 		rdc->error = e.error;
9221 		goto out;
9222 	}
9223 
9224 	if (needrecov) {
9225 		bool_t abort;
9226 
9227 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9228 		    "nfs4readdir: initiating recovery.\n"));
9229 
9230 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9231 		    NULL, OP_READDIR, NULL);
9232 		if (abort == FALSE) {
9233 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9234 			    &recov_state, needrecov);
9235 			if (!e.error)
9236 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9237 				    (caddr_t)&res);
9238 			if (rdc->entries != NULL) {
9239 				kmem_free(rdc->entries, rdc->entlen);
9240 				rdc->entries = NULL;
9241 			}
9242 			goto recov_retry;
9243 		}
9244 
9245 		if (e.error != 0) {
9246 			rdc->error = e.error;
9247 			goto out;
9248 		}
9249 
9250 		/* fall through for res.status case */
9251 	}
9252 
9253 	res_opcnt = res.array_len;
9254 
9255 	/*
9256 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9257 	 * failure here.  Subsequent ops are for filling out dot-dot
9258 	 * dirent, and if they fail, we still want to give the caller
9259 	 * the dirents returned by (the successful) READDIR op, so we need
9260 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9261 	 *
9262 	 * One example where PUTFH+READDIR ops would succeed but
9263 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9264 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9265 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9266 	 * x perm.  We need to come up with a non-vendor-specific way
9267 	 * for a POSIX server to return d_ino from dotdot's dirent if
9268 	 * client only requests mounted_on_fileid, and just say the
9269 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9270 	 * client requested any mandatory attrs, server would be required
9271 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9272 	 * for dotdot.
9273 	 */
9274 
9275 	if (res.status) {
9276 		if (res_opcnt <= 2) {
9277 			e.error = geterrno4(res.status);
9278 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9279 			    &recov_state, needrecov);
9280 			nfs4_purge_stale_fh(e.error, vp, cr);
9281 			rdc->error = e.error;
9282 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9283 			if (rdc->entries != NULL) {
9284 				kmem_free(rdc->entries, rdc->entlen);
9285 				rdc->entries = NULL;
9286 			}
9287 			/*
9288 			 * If readdir a node that is a stub for a
9289 			 * crossed mount point, keep the original
9290 			 * secinfo flavor for the current file system,
9291 			 * not the crossed one.
9292 			 */
9293 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9294 			return;
9295 		}
9296 	}
9297 
9298 	resop = &res.array[1];	/* readdir res */
9299 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9300 
9301 	mutex_enter(&rp->r_statelock);
9302 	rp->r_cookieverf4 = rd_res->cookieverf;
9303 	mutex_exit(&rp->r_statelock);
9304 
9305 	/*
9306 	 * For "." and ".." entries
9307 	 * e.g.
9308 	 *	seek(cookie=0) -> "." entry with d_off = 1
9309 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9310 	 */
9311 	if (cookie == (nfs_cookie4) 0) {
9312 		if (rd_res->dotp)
9313 			rd_res->dotp->d_ino = nodeid;
9314 		if (rd_res->dotdotp)
9315 			rd_res->dotdotp->d_ino = pnodeid;
9316 	}
9317 	if (cookie == (nfs_cookie4) 1) {
9318 		if (rd_res->dotdotp)
9319 			rd_res->dotdotp->d_ino = pnodeid;
9320 	}
9321 
9322 
9323 	/* LOOKUPP+GETATTR attemped */
9324 	if (args.array_len == 5 && rd_res->dotdotp) {
9325 		if (res.status == NFS4_OK && res_opcnt == 5) {
9326 			nfs_fh4 *fhp;
9327 			nfs4_sharedfh_t *sfhp;
9328 			vnode_t *pvp;
9329 			nfs4_ga_res_t *garp;
9330 
9331 			resop++;	/* lookupp */
9332 			resop++;	/* getfh   */
9333 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9334 
9335 			resop++;	/* getattr of parent */
9336 
9337 			/*
9338 			 * First, take care of finishing the
9339 			 * readdir results.
9340 			 */
9341 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9342 			/*
9343 			 * The d_ino of .. must be the inode number
9344 			 * of the mounted filesystem.
9345 			 */
9346 			if (garp->n4g_va.va_mask & AT_NODEID)
9347 				rd_res->dotdotp->d_ino =
9348 				    garp->n4g_va.va_nodeid;
9349 
9350 
9351 			/*
9352 			 * Next, create the ".." dnlc entry
9353 			 */
9354 			sfhp = sfh4_get(fhp, mi);
9355 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9356 				dnlc_update(vp, "..", pvp);
9357 				VN_RELE(pvp);
9358 			}
9359 			sfh4_rele(&sfhp);
9360 		}
9361 	}
9362 
9363 	if (mi->mi_io_kstats) {
9364 		mutex_enter(&mi->mi_lock);
9365 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9366 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9367 		mutex_exit(&mi->mi_lock);
9368 	}
9369 
9370 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9371 
9372 out:
9373 	/*
9374 	 * If readdir a node that is a stub for a crossed mount point,
9375 	 * keep the original secinfo flavor for the current file system,
9376 	 * not the crossed one.
9377 	 */
9378 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9379 
9380 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9381 }
9382 
9383 
9384 static int
9385 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9386 {
9387 	rnode4_t *rp = VTOR4(bp->b_vp);
9388 	int count;
9389 	int error;
9390 	cred_t *cred_otw = NULL;
9391 	offset_t offset;
9392 	nfs4_open_stream_t *osp = NULL;
9393 	bool_t first_time = TRUE;	/* first time getting otw cred */
9394 	bool_t last_time = FALSE;	/* last time getting otw cred */
9395 
9396 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9397 
9398 	DTRACE_IO1(start, struct buf *, bp);
9399 	offset = ldbtob(bp->b_lblkno);
9400 
9401 	if (bp->b_flags & B_READ) {
9402 	read_again:
9403 		/*
9404 		 * Releases the osp, if it is provided.
9405 		 * Puts a hold on the cred_otw and the new osp (if found).
9406 		 */
9407 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9408 		    &first_time, &last_time);
9409 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9410 		    offset, bp->b_bcount, &bp->b_resid, cred_otw,
9411 		    readahead, NULL);
9412 		crfree(cred_otw);
9413 		if (!error) {
9414 			if (bp->b_resid) {
9415 				/*
9416 				 * Didn't get it all because we hit EOF,
9417 				 * zero all the memory beyond the EOF.
9418 				 */
9419 				/* bzero(rdaddr + */
9420 				bzero(bp->b_un.b_addr +
9421 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9422 			}
9423 			mutex_enter(&rp->r_statelock);
9424 			if (bp->b_resid == bp->b_bcount &&
9425 			    offset >= rp->r_size) {
9426 				/*
9427 				 * We didn't read anything at all as we are
9428 				 * past EOF.  Return an error indicator back
9429 				 * but don't destroy the pages (yet).
9430 				 */
9431 				error = NFS_EOF;
9432 			}
9433 			mutex_exit(&rp->r_statelock);
9434 		} else if (error == EACCES && last_time == FALSE) {
9435 				goto read_again;
9436 		}
9437 	} else {
9438 		if (!(rp->r_flags & R4STALE)) {
9439 write_again:
9440 			/*
9441 			 * Releases the osp, if it is provided.
9442 			 * Puts a hold on the cred_otw and the new
9443 			 * osp (if found).
9444 			 */
9445 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9446 			    &first_time, &last_time);
9447 			mutex_enter(&rp->r_statelock);
9448 			count = MIN(bp->b_bcount, rp->r_size - offset);
9449 			mutex_exit(&rp->r_statelock);
9450 			if (count < 0)
9451 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9452 #ifdef DEBUG
9453 			if (count == 0) {
9454 				zoneid_t zoneid = getzoneid();
9455 
9456 				zcmn_err(zoneid, CE_WARN,
9457 				    "nfs4_bio: zero length write at %lld",
9458 				    offset);
9459 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9460 				    "b_bcount=%ld, file size=%lld",
9461 				    rp->r_flags, (long)bp->b_bcount,
9462 				    rp->r_size);
9463 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9464 				if (nfs4_bio_do_stop)
9465 					debug_enter("nfs4_bio");
9466 			}
9467 #endif
9468 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9469 			    count, cred_otw, stab_comm);
9470 			if (error == EACCES && last_time == FALSE) {
9471 				crfree(cred_otw);
9472 				goto write_again;
9473 			}
9474 			bp->b_error = error;
9475 			if (error && error != EINTR &&
9476 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9477 				/*
9478 				 * Don't print EDQUOT errors on the console.
9479 				 * Don't print asynchronous EACCES errors.
9480 				 * Don't print EFBIG errors.
9481 				 * Print all other write errors.
9482 				 */
9483 				if (error != EDQUOT && error != EFBIG &&
9484 				    (error != EACCES ||
9485 				    !(bp->b_flags & B_ASYNC)))
9486 					nfs4_write_error(bp->b_vp,
9487 					    error, cred_otw);
9488 				/*
9489 				 * Update r_error and r_flags as appropriate.
9490 				 * If the error was ESTALE, then mark the
9491 				 * rnode as not being writeable and save
9492 				 * the error status.  Otherwise, save any
9493 				 * errors which occur from asynchronous
9494 				 * page invalidations.  Any errors occurring
9495 				 * from other operations should be saved
9496 				 * by the caller.
9497 				 */
9498 				mutex_enter(&rp->r_statelock);
9499 				if (error == ESTALE) {
9500 					rp->r_flags |= R4STALE;
9501 					if (!rp->r_error)
9502 						rp->r_error = error;
9503 				} else if (!rp->r_error &&
9504 				    (bp->b_flags &
9505 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9506 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9507 					rp->r_error = error;
9508 				}
9509 				mutex_exit(&rp->r_statelock);
9510 			}
9511 			crfree(cred_otw);
9512 		} else
9513 			error = rp->r_error;
9514 	}
9515 
9516 	if (error != 0 && error != NFS_EOF)
9517 		bp->b_flags |= B_ERROR;
9518 
9519 	if (osp)
9520 		open_stream_rele(osp, rp);
9521 
9522 	DTRACE_IO1(done, struct buf *, bp);
9523 
9524 	return (error);
9525 }
9526 
9527 /* ARGSUSED */
9528 int
9529 nfs4_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
9530 {
9531 	return (EREMOTE);
9532 }
9533 
9534 /* ARGSUSED2 */
9535 int
9536 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9537 {
9538 	rnode4_t *rp = VTOR4(vp);
9539 
9540 	if (!write_lock) {
9541 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9542 		return (V_WRITELOCK_FALSE);
9543 	}
9544 
9545 	if ((rp->r_flags & R4DIRECTIO) ||
9546 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9547 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9548 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9549 			return (V_WRITELOCK_FALSE);
9550 		nfs_rw_exit(&rp->r_rwlock);
9551 	}
9552 
9553 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9554 	return (V_WRITELOCK_TRUE);
9555 }
9556 
9557 /* ARGSUSED */
9558 void
9559 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9560 {
9561 	rnode4_t *rp = VTOR4(vp);
9562 
9563 	nfs_rw_exit(&rp->r_rwlock);
9564 }
9565 
9566 /* ARGSUSED */
9567 static int
9568 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp, caller_context_t *ct)
9569 {
9570 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9571 		return (EIO);
9572 
9573 	/*
9574 	 * Because we stuff the readdir cookie into the offset field
9575 	 * someone may attempt to do an lseek with the cookie which
9576 	 * we want to succeed.
9577 	 */
9578 	if (vp->v_type == VDIR)
9579 		return (0);
9580 	if (*noffp < 0)
9581 		return (EINVAL);
9582 	return (0);
9583 }
9584 
9585 
9586 /*
9587  * Return all the pages from [off..off+len) in file
9588  */
9589 /* ARGSUSED */
9590 static int
9591 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9592     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9593 	enum seg_rw rw, cred_t *cr, caller_context_t *ct)
9594 {
9595 	rnode4_t *rp;
9596 	int error;
9597 	mntinfo4_t *mi;
9598 
9599 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9600 		return (EIO);
9601 	rp = VTOR4(vp);
9602 	if (IS_SHADOW(vp, rp))
9603 		vp = RTOV4(rp);
9604 
9605 	if (vp->v_flag & VNOMAP)
9606 		return (ENOSYS);
9607 
9608 	if (protp != NULL)
9609 		*protp = PROT_ALL;
9610 
9611 	/*
9612 	 * Now validate that the caches are up to date.
9613 	 */
9614 	if (error = nfs4_validate_caches(vp, cr))
9615 		return (error);
9616 
9617 	mi = VTOMI4(vp);
9618 retry:
9619 	mutex_enter(&rp->r_statelock);
9620 
9621 	/*
9622 	 * Don't create dirty pages faster than they
9623 	 * can be cleaned so that the system doesn't
9624 	 * get imbalanced.  If the async queue is
9625 	 * maxed out, then wait for it to drain before
9626 	 * creating more dirty pages.  Also, wait for
9627 	 * any threads doing pagewalks in the vop_getattr
9628 	 * entry points so that they don't block for
9629 	 * long periods.
9630 	 */
9631 	if (rw == S_CREATE) {
9632 		while ((mi->mi_max_threads != 0 &&
9633 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
9634 		    rp->r_gcount > 0)
9635 			cv_wait(&rp->r_cv, &rp->r_statelock);
9636 	}
9637 
9638 	/*
9639 	 * If we are getting called as a side effect of an nfs_write()
9640 	 * operation the local file size might not be extended yet.
9641 	 * In this case we want to be able to return pages of zeroes.
9642 	 */
9643 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9644 		NFS4_DEBUG(nfs4_pageio_debug,
9645 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9646 		    "len=%llu, size=%llu, attrsize =%llu", off,
9647 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9648 		mutex_exit(&rp->r_statelock);
9649 		return (EFAULT);		/* beyond EOF */
9650 	}
9651 
9652 	mutex_exit(&rp->r_statelock);
9653 
9654 	if (len <= PAGESIZE) {
9655 		error = nfs4_getapage(vp, off, len, protp, pl, plsz,
9656 		    seg, addr, rw, cr);
9657 		NFS4_DEBUG(nfs4_pageio_debug && error,
9658 		    (CE_NOTE, "getpage error %d; off=%lld, "
9659 		    "len=%lld", error, off, (u_longlong_t)len));
9660 	} else {
9661 		error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9662 		    pl, plsz, seg, addr, rw, cr);
9663 		NFS4_DEBUG(nfs4_pageio_debug && error,
9664 		    (CE_NOTE, "getpages error %d; off=%lld, "
9665 		    "len=%lld", error, off, (u_longlong_t)len));
9666 	}
9667 
9668 	switch (error) {
9669 	case NFS_EOF:
9670 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9671 		goto retry;
9672 	case ESTALE:
9673 		nfs4_purge_stale_fh(error, vp, cr);
9674 	}
9675 
9676 	return (error);
9677 }
9678 
9679 /*
9680  * Called from pvn_getpages or nfs4_getpage to get a particular page.
9681  */
9682 /* ARGSUSED */
9683 static int
9684 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9685     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9686     enum seg_rw rw, cred_t *cr)
9687 {
9688 	rnode4_t *rp;
9689 	uint_t bsize;
9690 	struct buf *bp;
9691 	page_t *pp;
9692 	u_offset_t lbn;
9693 	u_offset_t io_off;
9694 	u_offset_t blkoff;
9695 	u_offset_t rablkoff;
9696 	size_t io_len;
9697 	uint_t blksize;
9698 	int error;
9699 	int readahead;
9700 	int readahead_issued = 0;
9701 	int ra_window; /* readahead window */
9702 	page_t *pagefound;
9703 	page_t *savepp;
9704 
9705 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9706 		return (EIO);
9707 
9708 	rp = VTOR4(vp);
9709 	ASSERT(!IS_SHADOW(vp, rp));
9710 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9711 
9712 reread:
9713 	bp = NULL;
9714 	pp = NULL;
9715 	pagefound = NULL;
9716 
9717 	if (pl != NULL)
9718 		pl[0] = NULL;
9719 
9720 	error = 0;
9721 	lbn = off / bsize;
9722 	blkoff = lbn * bsize;
9723 
9724 	/*
9725 	 * Queueing up the readahead before doing the synchronous read
9726 	 * results in a significant increase in read throughput because
9727 	 * of the increased parallelism between the async threads and
9728 	 * the process context.
9729 	 */
9730 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9731 	    rw != S_CREATE &&
9732 	    !(vp->v_flag & VNOCACHE)) {
9733 		mutex_enter(&rp->r_statelock);
9734 
9735 		/*
9736 		 * Calculate the number of readaheads to do.
9737 		 * a) No readaheads at offset = 0.
9738 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9739 		 *    window is closed.
9740 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9741 		 *    upon how far the readahead window is open or close.
9742 		 * d) No readaheads if rp->r_nextr is not within the scope
9743 		 *    of the readahead window (random i/o).
9744 		 */
9745 
9746 		if (off == 0)
9747 			readahead = 0;
9748 		else if (blkoff == rp->r_nextr)
9749 			readahead = nfs4_nra;
9750 		else if (rp->r_nextr > blkoff &&
9751 		    ((ra_window = (rp->r_nextr - blkoff) / bsize)
9752 		    <= (nfs4_nra - 1)))
9753 			readahead = nfs4_nra - ra_window;
9754 		else
9755 			readahead = 0;
9756 
9757 		rablkoff = rp->r_nextr;
9758 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9759 			mutex_exit(&rp->r_statelock);
9760 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9761 			    addr + (rablkoff + bsize - off),
9762 			    seg, cr, nfs4_readahead) < 0) {
9763 				mutex_enter(&rp->r_statelock);
9764 				break;
9765 			}
9766 			readahead--;
9767 			rablkoff += bsize;
9768 			/*
9769 			 * Indicate that we did a readahead so
9770 			 * readahead offset is not updated
9771 			 * by the synchronous read below.
9772 			 */
9773 			readahead_issued = 1;
9774 			mutex_enter(&rp->r_statelock);
9775 			/*
9776 			 * set readahead offset to
9777 			 * offset of last async readahead
9778 			 * request.
9779 			 */
9780 			rp->r_nextr = rablkoff;
9781 		}
9782 		mutex_exit(&rp->r_statelock);
9783 	}
9784 
9785 again:
9786 	if ((pagefound = page_exists(vp, off)) == NULL) {
9787 		if (pl == NULL) {
9788 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9789 			    nfs4_readahead);
9790 		} else if (rw == S_CREATE) {
9791 			/*
9792 			 * Block for this page is not allocated, or the offset
9793 			 * is beyond the current allocation size, or we're
9794 			 * allocating a swap slot and the page was not found,
9795 			 * so allocate it and return a zero page.
9796 			 */
9797 			if ((pp = page_create_va(vp, off,
9798 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9799 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9800 			io_len = PAGESIZE;
9801 			mutex_enter(&rp->r_statelock);
9802 			rp->r_nextr = off + PAGESIZE;
9803 			mutex_exit(&rp->r_statelock);
9804 		} else {
9805 			/*
9806 			 * Need to go to server to get a block
9807 			 */
9808 			mutex_enter(&rp->r_statelock);
9809 			if (blkoff < rp->r_size &&
9810 			    blkoff + bsize > rp->r_size) {
9811 				/*
9812 				 * If less than a block left in
9813 				 * file read less than a block.
9814 				 */
9815 				if (rp->r_size <= off) {
9816 					/*
9817 					 * Trying to access beyond EOF,
9818 					 * set up to get at least one page.
9819 					 */
9820 					blksize = off + PAGESIZE - blkoff;
9821 				} else
9822 					blksize = rp->r_size - blkoff;
9823 			} else if ((off == 0) ||
9824 			    (off != rp->r_nextr && !readahead_issued)) {
9825 				blksize = PAGESIZE;
9826 				blkoff = off; /* block = page here */
9827 			} else
9828 				blksize = bsize;
9829 			mutex_exit(&rp->r_statelock);
9830 
9831 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9832 			    &io_len, blkoff, blksize, 0);
9833 
9834 			/*
9835 			 * Some other thread has entered the page,
9836 			 * so just use it.
9837 			 */
9838 			if (pp == NULL)
9839 				goto again;
9840 
9841 			/*
9842 			 * Now round the request size up to page boundaries.
9843 			 * This ensures that the entire page will be
9844 			 * initialized to zeroes if EOF is encountered.
9845 			 */
9846 			io_len = ptob(btopr(io_len));
9847 
9848 			bp = pageio_setup(pp, io_len, vp, B_READ);
9849 			ASSERT(bp != NULL);
9850 
9851 			/*
9852 			 * pageio_setup should have set b_addr to 0.  This
9853 			 * is correct since we want to do I/O on a page
9854 			 * boundary.  bp_mapin will use this addr to calculate
9855 			 * an offset, and then set b_addr to the kernel virtual
9856 			 * address it allocated for us.
9857 			 */
9858 			ASSERT(bp->b_un.b_addr == 0);
9859 
9860 			bp->b_edev = 0;
9861 			bp->b_dev = 0;
9862 			bp->b_lblkno = lbtodb(io_off);
9863 			bp->b_file = vp;
9864 			bp->b_offset = (offset_t)off;
9865 			bp_mapin(bp);
9866 
9867 			/*
9868 			 * If doing a write beyond what we believe is EOF,
9869 			 * don't bother trying to read the pages from the
9870 			 * server, we'll just zero the pages here.  We
9871 			 * don't check that the rw flag is S_WRITE here
9872 			 * because some implementations may attempt a
9873 			 * read access to the buffer before copying data.
9874 			 */
9875 			mutex_enter(&rp->r_statelock);
9876 			if (io_off >= rp->r_size && seg == segkmap) {
9877 				mutex_exit(&rp->r_statelock);
9878 				bzero(bp->b_un.b_addr, io_len);
9879 			} else {
9880 				mutex_exit(&rp->r_statelock);
9881 				error = nfs4_bio(bp, NULL, cr, FALSE);
9882 			}
9883 
9884 			/*
9885 			 * Unmap the buffer before freeing it.
9886 			 */
9887 			bp_mapout(bp);
9888 			pageio_done(bp);
9889 
9890 			savepp = pp;
9891 			do {
9892 				pp->p_fsdata = C_NOCOMMIT;
9893 			} while ((pp = pp->p_next) != savepp);
9894 
9895 			if (error == NFS_EOF) {
9896 				/*
9897 				 * If doing a write system call just return
9898 				 * zeroed pages, else user tried to get pages
9899 				 * beyond EOF, return error.  We don't check
9900 				 * that the rw flag is S_WRITE here because
9901 				 * some implementations may attempt a read
9902 				 * access to the buffer before copying data.
9903 				 */
9904 				if (seg == segkmap)
9905 					error = 0;
9906 				else
9907 					error = EFAULT;
9908 			}
9909 
9910 			if (!readahead_issued && !error) {
9911 				mutex_enter(&rp->r_statelock);
9912 				rp->r_nextr = io_off + io_len;
9913 				mutex_exit(&rp->r_statelock);
9914 			}
9915 		}
9916 	}
9917 
9918 out:
9919 	if (pl == NULL)
9920 		return (error);
9921 
9922 	if (error) {
9923 		if (pp != NULL)
9924 			pvn_read_done(pp, B_ERROR);
9925 		return (error);
9926 	}
9927 
9928 	if (pagefound) {
9929 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
9930 
9931 		/*
9932 		 * Page exists in the cache, acquire the appropriate lock.
9933 		 * If this fails, start all over again.
9934 		 */
9935 		if ((pp = page_lookup(vp, off, se)) == NULL) {
9936 #ifdef DEBUG
9937 			nfs4_lostpage++;
9938 #endif
9939 			goto reread;
9940 		}
9941 		pl[0] = pp;
9942 		pl[1] = NULL;
9943 		return (0);
9944 	}
9945 
9946 	if (pp != NULL)
9947 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
9948 
9949 	return (error);
9950 }
9951 
9952 static void
9953 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
9954     cred_t *cr)
9955 {
9956 	int error;
9957 	page_t *pp;
9958 	u_offset_t io_off;
9959 	size_t io_len;
9960 	struct buf *bp;
9961 	uint_t bsize, blksize;
9962 	rnode4_t *rp = VTOR4(vp);
9963 	page_t *savepp;
9964 
9965 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9966 
9967 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9968 
9969 	mutex_enter(&rp->r_statelock);
9970 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
9971 		/*
9972 		 * If less than a block left in file read less
9973 		 * than a block.
9974 		 */
9975 		blksize = rp->r_size - blkoff;
9976 	} else
9977 		blksize = bsize;
9978 	mutex_exit(&rp->r_statelock);
9979 
9980 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
9981 	    &io_off, &io_len, blkoff, blksize, 1);
9982 	/*
9983 	 * The isra flag passed to the kluster function is 1, we may have
9984 	 * gotten a return value of NULL for a variety of reasons (# of free
9985 	 * pages < minfree, someone entered the page on the vnode etc). In all
9986 	 * cases, we want to punt on the readahead.
9987 	 */
9988 	if (pp == NULL)
9989 		return;
9990 
9991 	/*
9992 	 * Now round the request size up to page boundaries.
9993 	 * This ensures that the entire page will be
9994 	 * initialized to zeroes if EOF is encountered.
9995 	 */
9996 	io_len = ptob(btopr(io_len));
9997 
9998 	bp = pageio_setup(pp, io_len, vp, B_READ);
9999 	ASSERT(bp != NULL);
10000 
10001 	/*
10002 	 * pageio_setup should have set b_addr to 0.  This is correct since
10003 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10004 	 * to calculate an offset, and then set b_addr to the kernel virtual
10005 	 * address it allocated for us.
10006 	 */
10007 	ASSERT(bp->b_un.b_addr == 0);
10008 
10009 	bp->b_edev = 0;
10010 	bp->b_dev = 0;
10011 	bp->b_lblkno = lbtodb(io_off);
10012 	bp->b_file = vp;
10013 	bp->b_offset = (offset_t)blkoff;
10014 	bp_mapin(bp);
10015 
10016 	/*
10017 	 * If doing a write beyond what we believe is EOF, don't bother trying
10018 	 * to read the pages from the server, we'll just zero the pages here.
10019 	 * We don't check that the rw flag is S_WRITE here because some
10020 	 * implementations may attempt a read access to the buffer before
10021 	 * copying data.
10022 	 */
10023 	mutex_enter(&rp->r_statelock);
10024 	if (io_off >= rp->r_size && seg == segkmap) {
10025 		mutex_exit(&rp->r_statelock);
10026 		bzero(bp->b_un.b_addr, io_len);
10027 		error = 0;
10028 	} else {
10029 		mutex_exit(&rp->r_statelock);
10030 		error = nfs4_bio(bp, NULL, cr, TRUE);
10031 		if (error == NFS_EOF)
10032 			error = 0;
10033 	}
10034 
10035 	/*
10036 	 * Unmap the buffer before freeing it.
10037 	 */
10038 	bp_mapout(bp);
10039 	pageio_done(bp);
10040 
10041 	savepp = pp;
10042 	do {
10043 		pp->p_fsdata = C_NOCOMMIT;
10044 	} while ((pp = pp->p_next) != savepp);
10045 
10046 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10047 
10048 	/*
10049 	 * In case of error set readahead offset
10050 	 * to the lowest offset.
10051 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10052 	 */
10053 	if (error && rp->r_nextr > io_off) {
10054 		mutex_enter(&rp->r_statelock);
10055 		if (rp->r_nextr > io_off)
10056 			rp->r_nextr = io_off;
10057 		mutex_exit(&rp->r_statelock);
10058 	}
10059 }
10060 
10061 /*
10062  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10063  * If len == 0, do from off to EOF.
10064  *
10065  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10066  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10067  * (from pageout).
10068  */
10069 /* ARGSUSED */
10070 static int
10071 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
10072 	caller_context_t *ct)
10073 {
10074 	int error;
10075 	rnode4_t *rp;
10076 
10077 	ASSERT(cr != NULL);
10078 
10079 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10080 		return (EIO);
10081 
10082 	rp = VTOR4(vp);
10083 	if (IS_SHADOW(vp, rp))
10084 		vp = RTOV4(rp);
10085 
10086 	/*
10087 	 * XXX - Why should this check be made here?
10088 	 */
10089 	if (vp->v_flag & VNOMAP)
10090 		return (ENOSYS);
10091 
10092 	if (len == 0 && !(flags & B_INVAL) &&
10093 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10094 		return (0);
10095 
10096 	mutex_enter(&rp->r_statelock);
10097 	rp->r_count++;
10098 	mutex_exit(&rp->r_statelock);
10099 	error = nfs4_putpages(vp, off, len, flags, cr);
10100 	mutex_enter(&rp->r_statelock);
10101 	rp->r_count--;
10102 	cv_broadcast(&rp->r_cv);
10103 	mutex_exit(&rp->r_statelock);
10104 
10105 	return (error);
10106 }
10107 
10108 /*
10109  * Write out a single page, possibly klustering adjacent dirty pages.
10110  */
10111 int
10112 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10113     int flags, cred_t *cr)
10114 {
10115 	u_offset_t io_off;
10116 	u_offset_t lbn_off;
10117 	u_offset_t lbn;
10118 	size_t io_len;
10119 	uint_t bsize;
10120 	int error;
10121 	rnode4_t *rp;
10122 
10123 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10124 	ASSERT(pp != NULL);
10125 	ASSERT(cr != NULL);
10126 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10127 
10128 	rp = VTOR4(vp);
10129 	ASSERT(rp->r_count > 0);
10130 	ASSERT(!IS_SHADOW(vp, rp));
10131 
10132 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10133 	lbn = pp->p_offset / bsize;
10134 	lbn_off = lbn * bsize;
10135 
10136 	/*
10137 	 * Find a kluster that fits in one block, or in
10138 	 * one page if pages are bigger than blocks.  If
10139 	 * there is less file space allocated than a whole
10140 	 * page, we'll shorten the i/o request below.
10141 	 */
10142 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10143 	    roundup(bsize, PAGESIZE), flags);
10144 
10145 	/*
10146 	 * pvn_write_kluster shouldn't have returned a page with offset
10147 	 * behind the original page we were given.  Verify that.
10148 	 */
10149 	ASSERT((pp->p_offset / bsize) >= lbn);
10150 
10151 	/*
10152 	 * Now pp will have the list of kept dirty pages marked for
10153 	 * write back.  It will also handle invalidation and freeing
10154 	 * of pages that are not dirty.  Check for page length rounding
10155 	 * problems.
10156 	 */
10157 	if (io_off + io_len > lbn_off + bsize) {
10158 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10159 		io_len = lbn_off + bsize - io_off;
10160 	}
10161 	/*
10162 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10163 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10164 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10165 	 * progress and the r_size has not been made consistent with the
10166 	 * new size of the file. When the uiomove() completes the r_size is
10167 	 * updated and the R4MODINPROGRESS flag is cleared.
10168 	 *
10169 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10170 	 * consistent value of r_size. Without this handshaking, it is
10171 	 * possible that nfs4_bio() picks  up the old value of r_size
10172 	 * before the uiomove() in writerp4() completes. This will result
10173 	 * in the write through nfs4_bio() being dropped.
10174 	 *
10175 	 * More precisely, there is a window between the time the uiomove()
10176 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10177 	 * operation intervenes in this window, the page will be picked up,
10178 	 * because it is dirty (it will be unlocked, unless it was
10179 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10180 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10181 	 * checked. This will still be the old size. Therefore the page will
10182 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10183 	 * the page will be found to be clean and the write will be dropped.
10184 	 */
10185 	if (rp->r_flags & R4MODINPROGRESS) {
10186 		mutex_enter(&rp->r_statelock);
10187 		if ((rp->r_flags & R4MODINPROGRESS) &&
10188 		    rp->r_modaddr + MAXBSIZE > io_off &&
10189 		    rp->r_modaddr < io_off + io_len) {
10190 			page_t *plist;
10191 			/*
10192 			 * A write is in progress for this region of the file.
10193 			 * If we did not detect R4MODINPROGRESS here then this
10194 			 * path through nfs_putapage() would eventually go to
10195 			 * nfs4_bio() and may not write out all of the data
10196 			 * in the pages. We end up losing data. So we decide
10197 			 * to set the modified bit on each page in the page
10198 			 * list and mark the rnode with R4DIRTY. This write
10199 			 * will be restarted at some later time.
10200 			 */
10201 			plist = pp;
10202 			while (plist != NULL) {
10203 				pp = plist;
10204 				page_sub(&plist, pp);
10205 				hat_setmod(pp);
10206 				page_io_unlock(pp);
10207 				page_unlock(pp);
10208 			}
10209 			rp->r_flags |= R4DIRTY;
10210 			mutex_exit(&rp->r_statelock);
10211 			if (offp)
10212 				*offp = io_off;
10213 			if (lenp)
10214 				*lenp = io_len;
10215 			return (0);
10216 		}
10217 		mutex_exit(&rp->r_statelock);
10218 	}
10219 
10220 	if (flags & B_ASYNC) {
10221 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10222 		    nfs4_sync_putapage);
10223 	} else
10224 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10225 
10226 	if (offp)
10227 		*offp = io_off;
10228 	if (lenp)
10229 		*lenp = io_len;
10230 	return (error);
10231 }
10232 
10233 static int
10234 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10235     int flags, cred_t *cr)
10236 {
10237 	int error;
10238 	rnode4_t *rp;
10239 
10240 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10241 
10242 	flags |= B_WRITE;
10243 
10244 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10245 
10246 	rp = VTOR4(vp);
10247 
10248 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10249 	    error == EACCES) &&
10250 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10251 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10252 			mutex_enter(&rp->r_statelock);
10253 			rp->r_flags |= R4OUTOFSPACE;
10254 			mutex_exit(&rp->r_statelock);
10255 		}
10256 		flags |= B_ERROR;
10257 		pvn_write_done(pp, flags);
10258 		/*
10259 		 * If this was not an async thread, then try again to
10260 		 * write out the pages, but this time, also destroy
10261 		 * them whether or not the write is successful.  This
10262 		 * will prevent memory from filling up with these
10263 		 * pages and destroying them is the only alternative
10264 		 * if they can't be written out.
10265 		 *
10266 		 * Don't do this if this is an async thread because
10267 		 * when the pages are unlocked in pvn_write_done,
10268 		 * some other thread could have come along, locked
10269 		 * them, and queued for an async thread.  It would be
10270 		 * possible for all of the async threads to be tied
10271 		 * up waiting to lock the pages again and they would
10272 		 * all already be locked and waiting for an async
10273 		 * thread to handle them.  Deadlock.
10274 		 */
10275 		if (!(flags & B_ASYNC)) {
10276 			error = nfs4_putpage(vp, io_off, io_len,
10277 			    B_INVAL | B_FORCE, cr, NULL);
10278 		}
10279 	} else {
10280 		if (error)
10281 			flags |= B_ERROR;
10282 		else if (rp->r_flags & R4OUTOFSPACE) {
10283 			mutex_enter(&rp->r_statelock);
10284 			rp->r_flags &= ~R4OUTOFSPACE;
10285 			mutex_exit(&rp->r_statelock);
10286 		}
10287 		pvn_write_done(pp, flags);
10288 		if (freemem < desfree)
10289 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10290 			    NFS4_WRITE_NOWAIT);
10291 	}
10292 
10293 	return (error);
10294 }
10295 
10296 #ifdef DEBUG
10297 int nfs4_force_open_before_mmap = 0;
10298 #endif
10299 
10300 /* ARGSUSED */
10301 static int
10302 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10303     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10304     caller_context_t *ct)
10305 {
10306 	struct segvn_crargs vn_a;
10307 	int error = 0;
10308 	rnode4_t *rp = VTOR4(vp);
10309 	mntinfo4_t *mi = VTOMI4(vp);
10310 
10311 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10312 		return (EIO);
10313 
10314 	if (vp->v_flag & VNOMAP)
10315 		return (ENOSYS);
10316 
10317 	if (off < 0 || (off + len) < 0)
10318 		return (ENXIO);
10319 
10320 	if (vp->v_type != VREG)
10321 		return (ENODEV);
10322 
10323 	/*
10324 	 * If the file is delegated to the client don't do anything.
10325 	 * If the file is not delegated, then validate the data cache.
10326 	 */
10327 	mutex_enter(&rp->r_statev4_lock);
10328 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10329 		mutex_exit(&rp->r_statev4_lock);
10330 		error = nfs4_validate_caches(vp, cr);
10331 		if (error)
10332 			return (error);
10333 	} else {
10334 		mutex_exit(&rp->r_statev4_lock);
10335 	}
10336 
10337 	/*
10338 	 * Check to see if the vnode is currently marked as not cachable.
10339 	 * This means portions of the file are locked (through VOP_FRLOCK).
10340 	 * In this case the map request must be refused.  We use
10341 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10342 	 */
10343 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
10344 		return (EINTR);
10345 
10346 	if (vp->v_flag & VNOCACHE) {
10347 		error = EAGAIN;
10348 		goto done;
10349 	}
10350 
10351 	/*
10352 	 * Don't allow concurrent locks and mapping if mandatory locking is
10353 	 * enabled.
10354 	 */
10355 	if (flk_has_remote_locks(vp)) {
10356 		struct vattr va;
10357 		va.va_mask = AT_MODE;
10358 		error = nfs4getattr(vp, &va, cr);
10359 		if (error != 0)
10360 			goto done;
10361 		if (MANDLOCK(vp, va.va_mode)) {
10362 			error = EAGAIN;
10363 			goto done;
10364 		}
10365 	}
10366 
10367 	/*
10368 	 * It is possible that the rnode has a lost lock request that we
10369 	 * are still trying to recover, and that the request conflicts with
10370 	 * this map request.
10371 	 *
10372 	 * An alternative approach would be for nfs4_safemap() to consider
10373 	 * queued lock requests when deciding whether to set or clear
10374 	 * VNOCACHE.  This would require the frlock code path to call
10375 	 * nfs4_safemap() after enqueing a lost request.
10376 	 */
10377 	if (nfs4_map_lost_lock_conflict(vp)) {
10378 		error = EAGAIN;
10379 		goto done;
10380 	}
10381 
10382 	as_rangelock(as);
10383 	if (!(flags & MAP_FIXED)) {
10384 		map_addr(addrp, len, off, 1, flags);
10385 		if (*addrp == NULL) {
10386 			as_rangeunlock(as);
10387 			error = ENOMEM;
10388 			goto done;
10389 		}
10390 	} else {
10391 		/*
10392 		 * User specified address - blow away any previous mappings
10393 		 */
10394 		(void) as_unmap(as, *addrp, len);
10395 	}
10396 
10397 	if (vp->v_type == VREG) {
10398 		/*
10399 		 * We need to retrieve the open stream
10400 		 */
10401 		nfs4_open_stream_t	*osp = NULL;
10402 		nfs4_open_owner_t	*oop = NULL;
10403 
10404 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10405 		if (oop != NULL) {
10406 			/* returns with 'os_sync_lock' held */
10407 			osp = find_open_stream(oop, rp);
10408 			open_owner_rele(oop);
10409 		}
10410 		if (osp == NULL) {
10411 #ifdef DEBUG
10412 			if (nfs4_force_open_before_mmap) {
10413 				error = EIO;
10414 				goto done;
10415 			}
10416 #endif
10417 			/* returns with 'os_sync_lock' held */
10418 			error = open_and_get_osp(vp, cr, &osp);
10419 			if (osp == NULL) {
10420 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10421 				    "nfs4_map: we tried to OPEN the file "
10422 				    "but again no osp, so fail with EIO"));
10423 				goto done;
10424 			}
10425 		}
10426 
10427 		if (osp->os_failed_reopen) {
10428 			mutex_exit(&osp->os_sync_lock);
10429 			open_stream_rele(osp, rp);
10430 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10431 			    "nfs4_map: os_failed_reopen set on "
10432 			    "osp %p, cr %p, rp %s", (void *)osp,
10433 			    (void *)cr, rnode4info(rp)));
10434 			error = EIO;
10435 			goto done;
10436 		}
10437 		mutex_exit(&osp->os_sync_lock);
10438 		open_stream_rele(osp, rp);
10439 	}
10440 
10441 	vn_a.vp = vp;
10442 	vn_a.offset = off;
10443 	vn_a.type = (flags & MAP_TYPE);
10444 	vn_a.prot = (uchar_t)prot;
10445 	vn_a.maxprot = (uchar_t)maxprot;
10446 	vn_a.flags = (flags & ~MAP_TYPE);
10447 	vn_a.cred = cr;
10448 	vn_a.amp = NULL;
10449 	vn_a.szc = 0;
10450 	vn_a.lgrp_mem_policy_flags = 0;
10451 
10452 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10453 	as_rangeunlock(as);
10454 
10455 done:
10456 	nfs_rw_exit(&rp->r_lkserlock);
10457 	return (error);
10458 }
10459 
10460 /*
10461  * We're most likely dealing with a kernel module that likes to READ
10462  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10463  * officially OPEN the file to create the necessary client state
10464  * for bookkeeping of os_mmap_read/write counts.
10465  *
10466  * Since VOP_MAP only passes in a pointer to the vnode rather than
10467  * a double pointer, we can't handle the case where nfs4open_otw()
10468  * returns a different vnode than the one passed into VOP_MAP (since
10469  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10470  * we return NULL and let nfs4_map() fail.  Note: the only case where
10471  * this should happen is if the file got removed and replaced with the
10472  * same name on the server (in addition to the fact that we're trying
10473  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10474  */
10475 static int
10476 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10477 {
10478 	rnode4_t		*rp, *drp;
10479 	vnode_t			*dvp, *open_vp;
10480 	char			file_name[MAXNAMELEN];
10481 	int			just_created;
10482 	nfs4_open_stream_t	*osp;
10483 	nfs4_open_owner_t	*oop;
10484 	int			error;
10485 
10486 	*ospp = NULL;
10487 	open_vp = map_vp;
10488 
10489 	rp = VTOR4(open_vp);
10490 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10491 		return (error);
10492 	drp = VTOR4(dvp);
10493 
10494 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10495 		VN_RELE(dvp);
10496 		return (EINTR);
10497 	}
10498 
10499 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10500 		nfs_rw_exit(&drp->r_rwlock);
10501 		VN_RELE(dvp);
10502 		return (error);
10503 	}
10504 
10505 	mutex_enter(&rp->r_statev4_lock);
10506 	if (rp->created_v4) {
10507 		rp->created_v4 = 0;
10508 		mutex_exit(&rp->r_statev4_lock);
10509 
10510 		dnlc_update(dvp, file_name, open_vp);
10511 		/* This is needed so we don't bump the open ref count */
10512 		just_created = 1;
10513 	} else {
10514 		mutex_exit(&rp->r_statev4_lock);
10515 		just_created = 0;
10516 	}
10517 
10518 	VN_HOLD(map_vp);
10519 
10520 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10521 	    just_created);
10522 	if (error) {
10523 		nfs_rw_exit(&drp->r_rwlock);
10524 		VN_RELE(dvp);
10525 		VN_RELE(map_vp);
10526 		return (error);
10527 	}
10528 
10529 	nfs_rw_exit(&drp->r_rwlock);
10530 	VN_RELE(dvp);
10531 
10532 	/*
10533 	 * If nfs4open_otw() returned a different vnode then "undo"
10534 	 * the open and return failure to the caller.
10535 	 */
10536 	if (!VN_CMP(open_vp, map_vp)) {
10537 		nfs4_error_t e;
10538 
10539 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10540 		    "open returned a different vnode"));
10541 		/*
10542 		 * If there's an error, ignore it,
10543 		 * and let VOP_INACTIVE handle it.
10544 		 */
10545 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10546 		    CLOSE_NORM, 0, 0, 0);
10547 		VN_RELE(map_vp);
10548 		return (EIO);
10549 	}
10550 
10551 	VN_RELE(map_vp);
10552 
10553 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10554 	if (!oop) {
10555 		nfs4_error_t e;
10556 
10557 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10558 		    "no open owner"));
10559 		/*
10560 		 * If there's an error, ignore it,
10561 		 * and let VOP_INACTIVE handle it.
10562 		 */
10563 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10564 		    CLOSE_NORM, 0, 0, 0);
10565 		return (EIO);
10566 	}
10567 	osp = find_open_stream(oop, rp);
10568 	open_owner_rele(oop);
10569 	*ospp = osp;
10570 	return (0);
10571 }
10572 
10573 /*
10574  * Please be aware that when this function is called, the address space write
10575  * a_lock is held.  Do not put over the wire calls in this function.
10576  */
10577 /* ARGSUSED */
10578 static int
10579 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10580     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10581     caller_context_t *ct)
10582 {
10583 	rnode4_t		*rp;
10584 	int			error = 0;
10585 	mntinfo4_t		*mi;
10586 
10587 	mi = VTOMI4(vp);
10588 	rp = VTOR4(vp);
10589 
10590 	if (nfs_zone() != mi->mi_zone)
10591 		return (EIO);
10592 	if (vp->v_flag & VNOMAP)
10593 		return (ENOSYS);
10594 
10595 	/*
10596 	 * Need to hold rwlock while incrementing the mapcnt so that
10597 	 * mmap'ing can be serialized with writes so that the caching
10598 	 * can be handled correctly.
10599 	 *
10600 	 * Don't need to update the open stream first, since this
10601 	 * mmap can't add any additional share access that isn't
10602 	 * already contained in the open stream (for the case where we
10603 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10604 	 * take into account os_mmap_read[write] counts).
10605 	 */
10606 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR(vp)))
10607 		return (EINTR);
10608 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10609 	nfs_rw_exit(&rp->r_rwlock);
10610 
10611 	if (vp->v_type == VREG) {
10612 		/*
10613 		 * We need to retrieve the open stream and update the counts.
10614 		 * If there is no open stream here, something is wrong.
10615 		 */
10616 		nfs4_open_stream_t	*osp = NULL;
10617 		nfs4_open_owner_t	*oop = NULL;
10618 
10619 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10620 		if (oop != NULL) {
10621 			/* returns with 'os_sync_lock' held */
10622 			osp = find_open_stream(oop, rp);
10623 			open_owner_rele(oop);
10624 		}
10625 		if (osp == NULL) {
10626 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10627 			    "nfs4_addmap: we should have an osp"
10628 			    "but we don't, so fail with EIO"));
10629 			error = EIO;
10630 			goto out;
10631 		}
10632 
10633 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10634 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10635 
10636 		/*
10637 		 * Update the map count in the open stream.
10638 		 * This is necessary in the case where we
10639 		 * open/mmap/close/, then the server reboots, and we
10640 		 * attempt to reopen.  If the mmap doesn't add share
10641 		 * access then we send an invalid reopen with
10642 		 * access = NONE.
10643 		 *
10644 		 * We need to specifically check each PROT_* so a mmap
10645 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10646 		 * read and write access.  A simple comparison of prot
10647 		 * to ~PROT_WRITE to determine read access is insufficient
10648 		 * since prot can be |= with PROT_USER, etc.
10649 		 */
10650 
10651 		/*
10652 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10653 		 */
10654 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10655 			osp->os_mmap_write += btopr(len);
10656 		if (maxprot & PROT_READ)
10657 			osp->os_mmap_read += btopr(len);
10658 		if (maxprot & PROT_EXEC)
10659 			osp->os_mmap_read += btopr(len);
10660 		/*
10661 		 * Ensure that os_mmap_read gets incremented, even if
10662 		 * maxprot were to look like PROT_NONE.
10663 		 */
10664 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10665 		    !(maxprot & PROT_EXEC))
10666 			osp->os_mmap_read += btopr(len);
10667 		osp->os_mapcnt += btopr(len);
10668 		mutex_exit(&osp->os_sync_lock);
10669 		open_stream_rele(osp, rp);
10670 	}
10671 
10672 out:
10673 	/*
10674 	 * If we got an error, then undo our
10675 	 * incrementing of 'r_mapcnt'.
10676 	 */
10677 
10678 	if (error) {
10679 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10680 		ASSERT(rp->r_mapcnt >= 0);
10681 	}
10682 	return (error);
10683 }
10684 
10685 /* ARGSUSED */
10686 static int
10687 nfs4_cmp(vnode_t *vp1, vnode_t *vp2, caller_context_t *ct)
10688 {
10689 
10690 	return (VTOR4(vp1) == VTOR4(vp2));
10691 }
10692 
10693 /* ARGSUSED */
10694 static int
10695 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10696     offset_t offset, struct flk_callback *flk_cbp, cred_t *cr,
10697     caller_context_t *ct)
10698 {
10699 	int rc;
10700 	u_offset_t start, end;
10701 	rnode4_t *rp;
10702 	int error = 0, intr = INTR4(vp);
10703 	nfs4_error_t e;
10704 
10705 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10706 		return (EIO);
10707 
10708 	/* check for valid cmd parameter */
10709 	if (cmd != F_GETLK && cmd != F_SETLK && cmd != F_SETLKW)
10710 		return (EINVAL);
10711 
10712 	/* Verify l_type. */
10713 	switch (bfp->l_type) {
10714 	case F_RDLCK:
10715 		if (cmd != F_GETLK && !(flag & FREAD))
10716 			return (EBADF);
10717 		break;
10718 	case F_WRLCK:
10719 		if (cmd != F_GETLK && !(flag & FWRITE))
10720 			return (EBADF);
10721 		break;
10722 	case F_UNLCK:
10723 		intr = 0;
10724 		break;
10725 
10726 	default:
10727 		return (EINVAL);
10728 	}
10729 
10730 	/* check the validity of the lock range */
10731 	if (rc = flk_convert_lock_data(vp, bfp, &start, &end, offset))
10732 		return (rc);
10733 	if (rc = flk_check_lock_data(start, end, MAXEND))
10734 		return (rc);
10735 
10736 	/*
10737 	 * If the filesystem is mounted using local locking, pass the
10738 	 * request off to the local locking code.
10739 	 */
10740 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10741 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10742 			/*
10743 			 * For complete safety, we should be holding
10744 			 * r_lkserlock.  However, we can't call
10745 			 * nfs4_safelock and then fs_frlock while
10746 			 * holding r_lkserlock, so just invoke
10747 			 * nfs4_safelock and expect that this will
10748 			 * catch enough of the cases.
10749 			 */
10750 			if (!nfs4_safelock(vp, bfp, cr))
10751 				return (EAGAIN);
10752 		}
10753 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
10754 	}
10755 
10756 	rp = VTOR4(vp);
10757 
10758 	/*
10759 	 * Check whether the given lock request can proceed, given the
10760 	 * current file mappings.
10761 	 */
10762 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr))
10763 		return (EINTR);
10764 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10765 		if (!nfs4_safelock(vp, bfp, cr)) {
10766 			rc = EAGAIN;
10767 			goto done;
10768 		}
10769 	}
10770 
10771 	/*
10772 	 * Flush the cache after waiting for async I/O to finish.  For new
10773 	 * locks, this is so that the process gets the latest bits from the
10774 	 * server.  For unlocks, this is so that other clients see the
10775 	 * latest bits once the file has been unlocked.  If currently dirty
10776 	 * pages can't be flushed, then don't allow a lock to be set.  But
10777 	 * allow unlocks to succeed, to avoid having orphan locks on the
10778 	 * server.
10779 	 */
10780 	if (cmd != F_GETLK) {
10781 		mutex_enter(&rp->r_statelock);
10782 		while (rp->r_count > 0) {
10783 			if (intr) {
10784 				klwp_t *lwp = ttolwp(curthread);
10785 
10786 				if (lwp != NULL)
10787 					lwp->lwp_nostop++;
10788 				if (cv_wait_sig(&rp->r_cv,
10789 				    &rp->r_statelock) == 0) {
10790 					if (lwp != NULL)
10791 						lwp->lwp_nostop--;
10792 					rc = EINTR;
10793 					break;
10794 				}
10795 				if (lwp != NULL)
10796 					lwp->lwp_nostop--;
10797 				} else
10798 					cv_wait(&rp->r_cv, &rp->r_statelock);
10799 		}
10800 		mutex_exit(&rp->r_statelock);
10801 		if (rc != 0)
10802 			goto done;
10803 		error = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr, ct);
10804 		if (error) {
10805 			if (error == ENOSPC || error == EDQUOT) {
10806 				mutex_enter(&rp->r_statelock);
10807 				if (!rp->r_error)
10808 					rp->r_error = error;
10809 				mutex_exit(&rp->r_statelock);
10810 			}
10811 			if (bfp->l_type != F_UNLCK) {
10812 				rc = ENOLCK;
10813 				goto done;
10814 			}
10815 		}
10816 	}
10817 
10818 	/*
10819 	 * Call the lock manager to do the real work of contacting
10820 	 * the server and obtaining the lock.
10821 	 */
10822 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, flag, offset,
10823 	    cr, &e, NULL, NULL);
10824 	rc = e.error;
10825 
10826 	if (rc == 0)
10827 		nfs4_lockcompletion(vp, cmd);
10828 
10829 done:
10830 	nfs_rw_exit(&rp->r_lkserlock);
10831 
10832 	return (rc);
10833 }
10834 
10835 /*
10836  * Free storage space associated with the specified vnode.  The portion
10837  * to be freed is specified by bfp->l_start and bfp->l_len (already
10838  * normalized to a "whence" of 0).
10839  *
10840  * This is an experimental facility whose continued existence is not
10841  * guaranteed.  Currently, we only support the special case
10842  * of l_len == 0, meaning free to end of file.
10843  */
10844 /* ARGSUSED */
10845 static int
10846 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10847     offset_t offset, cred_t *cr, caller_context_t *ct)
10848 {
10849 	int error;
10850 
10851 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10852 		return (EIO);
10853 	ASSERT(vp->v_type == VREG);
10854 	if (cmd != F_FREESP)
10855 		return (EINVAL);
10856 
10857 	error = convoff(vp, bfp, 0, offset);
10858 	if (!error) {
10859 		ASSERT(bfp->l_start >= 0);
10860 		if (bfp->l_len == 0) {
10861 			struct vattr va;
10862 
10863 			va.va_mask = AT_SIZE;
10864 			va.va_size = bfp->l_start;
10865 			error = nfs4setattr(vp, &va, 0, cr, NULL);
10866 		} else
10867 			error = EINVAL;
10868 	}
10869 
10870 	return (error);
10871 }
10872 
10873 /* ARGSUSED */
10874 int
10875 nfs4_realvp(vnode_t *vp, vnode_t **vpp, caller_context_t *ct)
10876 {
10877 	rnode4_t *rp;
10878 	rp = VTOR4(vp);
10879 
10880 	if (vp->v_type == VREG && IS_SHADOW(vp, rp)) {
10881 		vp = RTOV4(rp);
10882 	}
10883 	*vpp = vp;
10884 	return (0);
10885 }
10886 
10887 /*
10888  * Setup and add an address space callback to do the work of the delmap call.
10889  * The callback will (and must be) deleted in the actual callback function.
10890  *
10891  * This is done in order to take care of the problem that we have with holding
10892  * the address space's a_lock for a long period of time (e.g. if the NFS server
10893  * is down).  Callbacks will be executed in the address space code while the
10894  * a_lock is not held.  Holding the address space's a_lock causes things such
10895  * as ps and fork to hang because they are trying to acquire this lock as well.
10896  */
10897 /* ARGSUSED */
10898 static int
10899 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10900     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
10901     caller_context_t *ct)
10902 {
10903 	int			caller_found;
10904 	int			error;
10905 	rnode4_t		*rp;
10906 	nfs4_delmap_args_t	*dmapp;
10907 	nfs4_delmapcall_t	*delmap_call;
10908 
10909 	if (vp->v_flag & VNOMAP)
10910 		return (ENOSYS);
10911 
10912 	/*
10913 	 * A process may not change zones if it has NFS pages mmap'ed
10914 	 * in, so we can't legitimately get here from the wrong zone.
10915 	 */
10916 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10917 
10918 	rp = VTOR4(vp);
10919 
10920 	/*
10921 	 * The way that the address space of this process deletes its mapping
10922 	 * of this file is via the following call chains:
10923 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10924 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10925 	 *
10926 	 * With the use of address space callbacks we are allowed to drop the
10927 	 * address space lock, a_lock, while executing the NFS operations that
10928 	 * need to go over the wire.  Returning EAGAIN to the caller of this
10929 	 * function is what drives the execution of the callback that we add
10930 	 * below.  The callback will be executed by the address space code
10931 	 * after dropping the a_lock.  When the callback is finished, since
10932 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
10933 	 * is called again on the same segment to finish the rest of the work
10934 	 * that needs to happen during unmapping.
10935 	 *
10936 	 * This action of calling back into the segment driver causes
10937 	 * nfs4_delmap() to get called again, but since the callback was
10938 	 * already executed at this point, it already did the work and there
10939 	 * is nothing left for us to do.
10940 	 *
10941 	 * To Summarize:
10942 	 * - The first time nfs4_delmap is called by the current thread is when
10943 	 * we add the caller associated with this delmap to the delmap caller
10944 	 * list, add the callback, and return EAGAIN.
10945 	 * - The second time in this call chain when nfs4_delmap is called we
10946 	 * will find this caller in the delmap caller list and realize there
10947 	 * is no more work to do thus removing this caller from the list and
10948 	 * returning the error that was set in the callback execution.
10949 	 */
10950 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
10951 	if (caller_found) {
10952 		/*
10953 		 * 'error' is from the actual delmap operations.  To avoid
10954 		 * hangs, we need to handle the return of EAGAIN differently
10955 		 * since this is what drives the callback execution.
10956 		 * In this case, we don't want to return EAGAIN and do the
10957 		 * callback execution because there are none to execute.
10958 		 */
10959 		if (error == EAGAIN)
10960 			return (0);
10961 		else
10962 			return (error);
10963 	}
10964 
10965 	/* current caller was not in the list */
10966 	delmap_call = nfs4_init_delmapcall();
10967 
10968 	mutex_enter(&rp->r_statelock);
10969 	list_insert_tail(&rp->r_indelmap, delmap_call);
10970 	mutex_exit(&rp->r_statelock);
10971 
10972 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
10973 
10974 	dmapp->vp = vp;
10975 	dmapp->off = off;
10976 	dmapp->addr = addr;
10977 	dmapp->len = len;
10978 	dmapp->prot = prot;
10979 	dmapp->maxprot = maxprot;
10980 	dmapp->flags = flags;
10981 	dmapp->cr = cr;
10982 	dmapp->caller = delmap_call;
10983 
10984 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
10985 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
10986 
10987 	return (error ? error : EAGAIN);
10988 }
10989 
10990 static nfs4_delmapcall_t *
10991 nfs4_init_delmapcall()
10992 {
10993 	nfs4_delmapcall_t	*delmap_call;
10994 
10995 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
10996 	delmap_call->call_id = curthread;
10997 	delmap_call->error = 0;
10998 
10999 	return (delmap_call);
11000 }
11001 
11002 static void
11003 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11004 {
11005 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11006 }
11007 
11008 /*
11009  * Searches for the current delmap caller (based on curthread) in the list of
11010  * callers.  If it is found, we remove it and free the delmap caller.
11011  * Returns:
11012  *      0 if the caller wasn't found
11013  *      1 if the caller was found, removed and freed.  *errp will be set
11014  *	to what the result of the delmap was.
11015  */
11016 static int
11017 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11018 {
11019 	nfs4_delmapcall_t	*delmap_call;
11020 
11021 	/*
11022 	 * If the list doesn't exist yet, we create it and return
11023 	 * that the caller wasn't found.  No list = no callers.
11024 	 */
11025 	mutex_enter(&rp->r_statelock);
11026 	if (!(rp->r_flags & R4DELMAPLIST)) {
11027 		/* The list does not exist */
11028 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11029 		    offsetof(nfs4_delmapcall_t, call_node));
11030 		rp->r_flags |= R4DELMAPLIST;
11031 		mutex_exit(&rp->r_statelock);
11032 		return (0);
11033 	} else {
11034 		/* The list exists so search it */
11035 		for (delmap_call = list_head(&rp->r_indelmap);
11036 		    delmap_call != NULL;
11037 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11038 			if (delmap_call->call_id == curthread) {
11039 				/* current caller is in the list */
11040 				*errp = delmap_call->error;
11041 				list_remove(&rp->r_indelmap, delmap_call);
11042 				mutex_exit(&rp->r_statelock);
11043 				nfs4_free_delmapcall(delmap_call);
11044 				return (1);
11045 			}
11046 		}
11047 	}
11048 	mutex_exit(&rp->r_statelock);
11049 	return (0);
11050 }
11051 
11052 /*
11053  * Remove some pages from an mmap'd vnode.  Just update the
11054  * count of pages.  If doing close-to-open, then flush and
11055  * commit all of the pages associated with this file.
11056  * Otherwise, start an asynchronous page flush to write out
11057  * any dirty pages.  This will also associate a credential
11058  * with the rnode which can be used to write the pages.
11059  */
11060 /* ARGSUSED */
11061 static void
11062 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11063 {
11064 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11065 	rnode4_t		*rp;
11066 	mntinfo4_t		*mi;
11067 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11068 
11069 	rp = VTOR4(dmapp->vp);
11070 	mi = VTOMI4(dmapp->vp);
11071 
11072 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11073 	ASSERT(rp->r_mapcnt >= 0);
11074 
11075 	/*
11076 	 * Initiate a page flush and potential commit if there are
11077 	 * pages, the file system was not mounted readonly, the segment
11078 	 * was mapped shared, and the pages themselves were writeable.
11079 	 */
11080 	if (nfs4_has_pages(dmapp->vp) &&
11081 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11082 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11083 		mutex_enter(&rp->r_statelock);
11084 		rp->r_flags |= R4DIRTY;
11085 		mutex_exit(&rp->r_statelock);
11086 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11087 		    dmapp->len, dmapp->cr);
11088 		if (!e.error) {
11089 			mutex_enter(&rp->r_statelock);
11090 			e.error = rp->r_error;
11091 			rp->r_error = 0;
11092 			mutex_exit(&rp->r_statelock);
11093 		}
11094 	} else
11095 		e.error = 0;
11096 
11097 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11098 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11099 		    B_INVAL, dmapp->cr, NULL);
11100 
11101 	if (e.error) {
11102 		e.stat = puterrno4(e.error);
11103 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11104 		    OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11105 		dmapp->caller->error = e.error;
11106 	}
11107 
11108 	/* Check to see if we need to close the file */
11109 
11110 	if (dmapp->vp->v_type == VREG) {
11111 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11112 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11113 
11114 		if (e.error != 0 || e.stat != NFS4_OK) {
11115 			/*
11116 			 * Since it is possible that e.error == 0 and
11117 			 * e.stat != NFS4_OK (and vice versa),
11118 			 * we do the proper checking in order to get both
11119 			 * e.error and e.stat reporting the correct info.
11120 			 */
11121 			if (e.stat == NFS4_OK)
11122 				e.stat = puterrno4(e.error);
11123 			if (e.error == 0)
11124 				e.error = geterrno4(e.stat);
11125 
11126 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11127 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11128 			dmapp->caller->error = e.error;
11129 		}
11130 	}
11131 
11132 	(void) as_delete_callback(as, arg);
11133 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11134 }
11135 
11136 
11137 static uint_t
11138 fattr4_maxfilesize_to_bits(uint64_t ll)
11139 {
11140 	uint_t l = 1;
11141 
11142 	if (ll == 0) {
11143 		return (0);
11144 	}
11145 
11146 	if (ll & 0xffffffff00000000) {
11147 		l += 32; ll >>= 32;
11148 	}
11149 	if (ll & 0xffff0000) {
11150 		l += 16; ll >>= 16;
11151 	}
11152 	if (ll & 0xff00) {
11153 		l += 8; ll >>= 8;
11154 	}
11155 	if (ll & 0xf0) {
11156 		l += 4; ll >>= 4;
11157 	}
11158 	if (ll & 0xc) {
11159 		l += 2; ll >>= 2;
11160 	}
11161 	if (ll & 0x2) {
11162 		l += 1;
11163 	}
11164 	return (l);
11165 }
11166 
11167 /* ARGSUSED */
11168 int
11169 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
11170 	caller_context_t *ct)
11171 {
11172 	int error;
11173 	hrtime_t t;
11174 	rnode4_t *rp;
11175 	nfs4_ga_res_t gar;
11176 	nfs4_ga_ext_res_t ger;
11177 
11178 	gar.n4g_ext_res = &ger;
11179 
11180 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11181 		return (EIO);
11182 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11183 		*valp = MAXPATHLEN;
11184 		return (0);
11185 	}
11186 	if (cmd == _PC_ACL_ENABLED) {
11187 		*valp = _ACL_ACE_ENABLED;
11188 		return (0);
11189 	}
11190 
11191 	rp = VTOR4(vp);
11192 	if (cmd == _PC_XATTR_EXISTS) {
11193 		/*
11194 		 * Eventually should attempt small client readdir before
11195 		 * going otw with GETATTR(FATTR4_NAMED_ATTR).  For now
11196 		 * just drive the OTW getattr.  This is required because
11197 		 * _PC_XATTR_EXISTS can only return true if attributes
11198 		 * exist -- simply checking for existence of the attrdir
11199 		 * is not sufficient.
11200 		 *
11201 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11202 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11203 		 * and we don't have any way to update the "base" object's
11204 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11205 		 * could help out.
11206 		 */
11207 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11208 		    rp->r_xattr_dir == NULL) {
11209 			*valp = rp->r_pathconf.pc4_xattr_exists;
11210 			return (0);
11211 		}
11212 	} else {  /* OLD CODE */
11213 		if (ATTRCACHE4_VALID(vp)) {
11214 			mutex_enter(&rp->r_statelock);
11215 			if (rp->r_pathconf.pc4_cache_valid) {
11216 				error = 0;
11217 				switch (cmd) {
11218 				case _PC_FILESIZEBITS:
11219 					*valp =
11220 					    rp->r_pathconf.pc4_filesizebits;
11221 					break;
11222 				case _PC_LINK_MAX:
11223 					*valp =
11224 					    rp->r_pathconf.pc4_link_max;
11225 					break;
11226 				case _PC_NAME_MAX:
11227 					*valp =
11228 					    rp->r_pathconf.pc4_name_max;
11229 					break;
11230 				case _PC_CHOWN_RESTRICTED:
11231 					*valp =
11232 					    rp->r_pathconf.pc4_chown_restricted;
11233 					break;
11234 				case _PC_NO_TRUNC:
11235 					*valp =
11236 					    rp->r_pathconf.pc4_no_trunc;
11237 					break;
11238 				default:
11239 					error = EINVAL;
11240 					break;
11241 				}
11242 				mutex_exit(&rp->r_statelock);
11243 #ifdef DEBUG
11244 				nfs4_pathconf_cache_hits++;
11245 #endif
11246 				return (error);
11247 			}
11248 			mutex_exit(&rp->r_statelock);
11249 		}
11250 	}
11251 #ifdef DEBUG
11252 	nfs4_pathconf_cache_misses++;
11253 #endif
11254 
11255 	t = gethrtime();
11256 
11257 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11258 
11259 	if (error) {
11260 		mutex_enter(&rp->r_statelock);
11261 		rp->r_pathconf.pc4_cache_valid = FALSE;
11262 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11263 		mutex_exit(&rp->r_statelock);
11264 		return (error);
11265 	}
11266 
11267 	/* interpret the max filesize */
11268 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11269 	    fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11270 
11271 	/* Store the attributes we just received */
11272 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11273 
11274 	switch (cmd) {
11275 	case _PC_FILESIZEBITS:
11276 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11277 		break;
11278 	case _PC_LINK_MAX:
11279 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11280 		break;
11281 	case _PC_NAME_MAX:
11282 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11283 		break;
11284 	case _PC_CHOWN_RESTRICTED:
11285 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11286 		break;
11287 	case _PC_NO_TRUNC:
11288 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11289 		break;
11290 	case _PC_XATTR_EXISTS:
11291 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists;
11292 		break;
11293 	default:
11294 		return (EINVAL);
11295 	}
11296 
11297 	return (0);
11298 }
11299 
11300 /*
11301  * Called by async thread to do synchronous pageio. Do the i/o, wait
11302  * for it to complete, and cleanup the page list when done.
11303  */
11304 static int
11305 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11306     int flags, cred_t *cr)
11307 {
11308 	int error;
11309 
11310 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11311 
11312 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11313 	if (flags & B_READ)
11314 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11315 	else
11316 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11317 	return (error);
11318 }
11319 
11320 /* ARGSUSED */
11321 static int
11322 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11323 	int flags, cred_t *cr, caller_context_t *ct)
11324 {
11325 	int error;
11326 	rnode4_t *rp;
11327 
11328 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11329 		return (EIO);
11330 
11331 	if (pp == NULL)
11332 		return (EINVAL);
11333 
11334 	rp = VTOR4(vp);
11335 	mutex_enter(&rp->r_statelock);
11336 	rp->r_count++;
11337 	mutex_exit(&rp->r_statelock);
11338 
11339 	if (flags & B_ASYNC) {
11340 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11341 		    nfs4_sync_pageio);
11342 	} else
11343 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11344 	mutex_enter(&rp->r_statelock);
11345 	rp->r_count--;
11346 	cv_broadcast(&rp->r_cv);
11347 	mutex_exit(&rp->r_statelock);
11348 	return (error);
11349 }
11350 
11351 /* ARGSUSED */
11352 static void
11353 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr,
11354 	caller_context_t *ct)
11355 {
11356 	int error;
11357 	rnode4_t *rp;
11358 	page_t *plist;
11359 	page_t *pptr;
11360 	offset3 offset;
11361 	count3 len;
11362 	k_sigset_t smask;
11363 
11364 	/*
11365 	 * We should get called with fl equal to either B_FREE or
11366 	 * B_INVAL.  Any other value is illegal.
11367 	 *
11368 	 * The page that we are either supposed to free or destroy
11369 	 * should be exclusive locked and its io lock should not
11370 	 * be held.
11371 	 */
11372 	ASSERT(fl == B_FREE || fl == B_INVAL);
11373 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11374 
11375 	rp = VTOR4(vp);
11376 
11377 	/*
11378 	 * If the page doesn't need to be committed or we shouldn't
11379 	 * even bother attempting to commit it, then just make sure
11380 	 * that the p_fsdata byte is clear and then either free or
11381 	 * destroy the page as appropriate.
11382 	 */
11383 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11384 		pp->p_fsdata = C_NOCOMMIT;
11385 		if (fl == B_FREE)
11386 			page_free(pp, dn);
11387 		else
11388 			page_destroy(pp, dn);
11389 		return;
11390 	}
11391 
11392 	/*
11393 	 * If there is a page invalidation operation going on, then
11394 	 * if this is one of the pages being destroyed, then just
11395 	 * clear the p_fsdata byte and then either free or destroy
11396 	 * the page as appropriate.
11397 	 */
11398 	mutex_enter(&rp->r_statelock);
11399 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11400 		mutex_exit(&rp->r_statelock);
11401 		pp->p_fsdata = C_NOCOMMIT;
11402 		if (fl == B_FREE)
11403 			page_free(pp, dn);
11404 		else
11405 			page_destroy(pp, dn);
11406 		return;
11407 	}
11408 
11409 	/*
11410 	 * If we are freeing this page and someone else is already
11411 	 * waiting to do a commit, then just unlock the page and
11412 	 * return.  That other thread will take care of commiting
11413 	 * this page.  The page can be freed sometime after the
11414 	 * commit has finished.  Otherwise, if the page is marked
11415 	 * as delay commit, then we may be getting called from
11416 	 * pvn_write_done, one page at a time.   This could result
11417 	 * in one commit per page, so we end up doing lots of small
11418 	 * commits instead of fewer larger commits.  This is bad,
11419 	 * we want do as few commits as possible.
11420 	 */
11421 	if (fl == B_FREE) {
11422 		if (rp->r_flags & R4COMMITWAIT) {
11423 			page_unlock(pp);
11424 			mutex_exit(&rp->r_statelock);
11425 			return;
11426 		}
11427 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11428 			pp->p_fsdata = C_COMMIT;
11429 			page_unlock(pp);
11430 			mutex_exit(&rp->r_statelock);
11431 			return;
11432 		}
11433 	}
11434 
11435 	/*
11436 	 * Check to see if there is a signal which would prevent an
11437 	 * attempt to commit the pages from being successful.  If so,
11438 	 * then don't bother with all of the work to gather pages and
11439 	 * generate the unsuccessful RPC.  Just return from here and
11440 	 * let the page be committed at some later time.
11441 	 */
11442 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11443 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11444 		sigunintr(&smask);
11445 		page_unlock(pp);
11446 		mutex_exit(&rp->r_statelock);
11447 		return;
11448 	}
11449 	sigunintr(&smask);
11450 
11451 	/*
11452 	 * We are starting to need to commit pages, so let's try
11453 	 * to commit as many as possible at once to reduce the
11454 	 * overhead.
11455 	 *
11456 	 * Set the `commit inprogress' state bit.  We must
11457 	 * first wait until any current one finishes.  Then
11458 	 * we initialize the c_pages list with this page.
11459 	 */
11460 	while (rp->r_flags & R4COMMIT) {
11461 		rp->r_flags |= R4COMMITWAIT;
11462 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11463 		rp->r_flags &= ~R4COMMITWAIT;
11464 	}
11465 	rp->r_flags |= R4COMMIT;
11466 	mutex_exit(&rp->r_statelock);
11467 	ASSERT(rp->r_commit.c_pages == NULL);
11468 	rp->r_commit.c_pages = pp;
11469 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11470 	rp->r_commit.c_commlen = PAGESIZE;
11471 
11472 	/*
11473 	 * Gather together all other pages which can be committed.
11474 	 * They will all be chained off r_commit.c_pages.
11475 	 */
11476 	nfs4_get_commit(vp);
11477 
11478 	/*
11479 	 * Clear the `commit inprogress' status and disconnect
11480 	 * the list of pages to be committed from the rnode.
11481 	 * At this same time, we also save the starting offset
11482 	 * and length of data to be committed on the server.
11483 	 */
11484 	plist = rp->r_commit.c_pages;
11485 	rp->r_commit.c_pages = NULL;
11486 	offset = rp->r_commit.c_commbase;
11487 	len = rp->r_commit.c_commlen;
11488 	mutex_enter(&rp->r_statelock);
11489 	rp->r_flags &= ~R4COMMIT;
11490 	cv_broadcast(&rp->r_commit.c_cv);
11491 	mutex_exit(&rp->r_statelock);
11492 
11493 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11494 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11495 		nfs4_async_commit(vp, plist, offset, len,
11496 		    cr, do_nfs4_async_commit);
11497 		return;
11498 	}
11499 
11500 	/*
11501 	 * Actually generate the COMMIT op over the wire operation.
11502 	 */
11503 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11504 
11505 	/*
11506 	 * If we got an error during the commit, just unlock all
11507 	 * of the pages.  The pages will get retransmitted to the
11508 	 * server during a putpage operation.
11509 	 */
11510 	if (error) {
11511 		while (plist != NULL) {
11512 			pptr = plist;
11513 			page_sub(&plist, pptr);
11514 			page_unlock(pptr);
11515 		}
11516 		return;
11517 	}
11518 
11519 	/*
11520 	 * We've tried as hard as we can to commit the data to stable
11521 	 * storage on the server.  We just unlock the rest of the pages
11522 	 * and clear the commit required state.  They will be put
11523 	 * onto the tail of the cachelist if they are nolonger
11524 	 * mapped.
11525 	 */
11526 	while (plist != pp) {
11527 		pptr = plist;
11528 		page_sub(&plist, pptr);
11529 		pptr->p_fsdata = C_NOCOMMIT;
11530 		page_unlock(pptr);
11531 	}
11532 
11533 	/*
11534 	 * It is possible that nfs4_commit didn't return error but
11535 	 * some other thread has modified the page we are going
11536 	 * to free/destroy.
11537 	 *    In this case we need to rewrite the page. Do an explicit check
11538 	 * before attempting to free/destroy the page. If modified, needs to
11539 	 * be rewritten so unlock the page and return.
11540 	 */
11541 	if (hat_ismod(pp)) {
11542 		pp->p_fsdata = C_NOCOMMIT;
11543 		page_unlock(pp);
11544 		return;
11545 	}
11546 
11547 	/*
11548 	 * Now, as appropriate, either free or destroy the page
11549 	 * that we were called with.
11550 	 */
11551 	pp->p_fsdata = C_NOCOMMIT;
11552 	if (fl == B_FREE)
11553 		page_free(pp, dn);
11554 	else
11555 		page_destroy(pp, dn);
11556 }
11557 
11558 /*
11559  * Commit requires that the current fh be the file written to.
11560  * The compound op structure is:
11561  *      PUTFH(file), COMMIT
11562  */
11563 static int
11564 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11565 {
11566 	COMPOUND4args_clnt args;
11567 	COMPOUND4res_clnt res;
11568 	COMMIT4res *cm_res;
11569 	nfs_argop4 argop[2];
11570 	nfs_resop4 *resop;
11571 	int doqueue;
11572 	mntinfo4_t *mi;
11573 	rnode4_t *rp;
11574 	cred_t *cred_otw = NULL;
11575 	bool_t needrecov = FALSE;
11576 	nfs4_recov_state_t recov_state;
11577 	nfs4_open_stream_t *osp = NULL;
11578 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11579 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11580 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11581 
11582 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11583 
11584 	rp = VTOR4(vp);
11585 
11586 	mi = VTOMI4(vp);
11587 	recov_state.rs_flags = 0;
11588 	recov_state.rs_num_retry_despite_err = 0;
11589 get_commit_cred:
11590 	/*
11591 	 * Releases the osp, if a valid open stream is provided.
11592 	 * Puts a hold on the cred_otw and the new osp (if found).
11593 	 */
11594 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11595 	    &first_time, &last_time);
11596 	args.ctag = TAG_COMMIT;
11597 recov_retry:
11598 	/*
11599 	 * Commit ops: putfh file; commit
11600 	 */
11601 	args.array_len = 2;
11602 	args.array = argop;
11603 
11604 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11605 	    &recov_state, NULL);
11606 	if (e.error) {
11607 		crfree(cred_otw);
11608 		if (osp != NULL)
11609 			open_stream_rele(osp, rp);
11610 		return (e.error);
11611 	}
11612 
11613 	/* putfh directory */
11614 	argop[0].argop = OP_CPUTFH;
11615 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11616 
11617 	/* commit */
11618 	argop[1].argop = OP_COMMIT;
11619 	argop[1].nfs_argop4_u.opcommit.offset = offset;
11620 	argop[1].nfs_argop4_u.opcommit.count = count;
11621 
11622 	doqueue = 1;
11623 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
11624 
11625 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
11626 	if (!needrecov && e.error) {
11627 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
11628 		    needrecov);
11629 		crfree(cred_otw);
11630 		if (e.error == EACCES && last_time == FALSE)
11631 			goto get_commit_cred;
11632 		if (osp != NULL)
11633 			open_stream_rele(osp, rp);
11634 		return (e.error);
11635 	}
11636 
11637 	if (needrecov) {
11638 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
11639 		    NULL, OP_COMMIT, NULL) == FALSE) {
11640 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11641 			    &recov_state, needrecov);
11642 			if (!e.error)
11643 				(void) xdr_free(xdr_COMPOUND4res_clnt,
11644 				    (caddr_t)&res);
11645 			goto recov_retry;
11646 		}
11647 		if (e.error) {
11648 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11649 			    &recov_state, needrecov);
11650 			crfree(cred_otw);
11651 			if (osp != NULL)
11652 				open_stream_rele(osp, rp);
11653 			return (e.error);
11654 		}
11655 		/* fall through for res.status case */
11656 	}
11657 
11658 	if (res.status) {
11659 		e.error = geterrno4(res.status);
11660 		if (e.error == EACCES && last_time == FALSE) {
11661 			crfree(cred_otw);
11662 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11663 			    &recov_state, needrecov);
11664 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11665 			goto get_commit_cred;
11666 		}
11667 		/*
11668 		 * Can't do a nfs4_purge_stale_fh here because this
11669 		 * can cause a deadlock.  nfs4_commit can
11670 		 * be called from nfs4_dispose which can be called
11671 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
11672 		 * can call back to pvn_vplist_dirty.
11673 		 */
11674 		if (e.error == ESTALE) {
11675 			mutex_enter(&rp->r_statelock);
11676 			rp->r_flags |= R4STALE;
11677 			if (!rp->r_error)
11678 				rp->r_error = e.error;
11679 			mutex_exit(&rp->r_statelock);
11680 			PURGE_ATTRCACHE4(vp);
11681 		} else {
11682 			mutex_enter(&rp->r_statelock);
11683 			if (!rp->r_error)
11684 				rp->r_error = e.error;
11685 			mutex_exit(&rp->r_statelock);
11686 		}
11687 	} else {
11688 		ASSERT(rp->r_flags & R4HAVEVERF);
11689 		resop = &res.array[1];	/* commit res */
11690 		cm_res = &resop->nfs_resop4_u.opcommit;
11691 		mutex_enter(&rp->r_statelock);
11692 		if (cm_res->writeverf == rp->r_writeverf) {
11693 			mutex_exit(&rp->r_statelock);
11694 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11695 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11696 			    &recov_state, needrecov);
11697 			crfree(cred_otw);
11698 			if (osp != NULL)
11699 				open_stream_rele(osp, rp);
11700 			return (0);
11701 		}
11702 		nfs4_set_mod(vp);
11703 		rp->r_writeverf = cm_res->writeverf;
11704 		mutex_exit(&rp->r_statelock);
11705 		e.error = NFS_VERF_MISMATCH;
11706 	}
11707 
11708 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11709 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
11710 	crfree(cred_otw);
11711 	if (osp != NULL)
11712 		open_stream_rele(osp, rp);
11713 
11714 	return (e.error);
11715 }
11716 
11717 static void
11718 nfs4_set_mod(vnode_t *vp)
11719 {
11720 	page_t *pp;
11721 	kmutex_t *vphm;
11722 	rnode4_t *rp;
11723 
11724 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11725 
11726 	/* make sure we're looking at the master vnode, not a shadow */
11727 
11728 	rp = VTOR4(vp);
11729 	if (IS_SHADOW(vp, rp))
11730 		vp = RTOV4(rp);
11731 
11732 	vphm = page_vnode_mutex(vp);
11733 	mutex_enter(vphm);
11734 	/*
11735 	 * If there are no pages associated with this vnode, then
11736 	 * just return.
11737 	 */
11738 	if ((pp = vp->v_pages) == NULL) {
11739 		mutex_exit(vphm);
11740 		return;
11741 	}
11742 
11743 	do {
11744 		if (pp->p_fsdata != C_NOCOMMIT) {
11745 			hat_setmod(pp);
11746 			pp->p_fsdata = C_NOCOMMIT;
11747 		}
11748 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11749 	mutex_exit(vphm);
11750 }
11751 
11752 /*
11753  * This function is used to gather a page list of the pages which
11754  * can be committed on the server.
11755  *
11756  * The calling thread must have set R4COMMIT.  This bit is used to
11757  * serialize access to the commit structure in the rnode.  As long
11758  * as the thread has set R4COMMIT, then it can manipulate the commit
11759  * structure without requiring any other locks.
11760  *
11761  * When this function is called from nfs4_dispose() the page passed
11762  * into nfs4_dispose() will be SE_EXCL locked, and so this function
11763  * will skip it. This is not a problem since we initially add the
11764  * page to the r_commit page list.
11765  *
11766  */
11767 static void
11768 nfs4_get_commit(vnode_t *vp)
11769 {
11770 	rnode4_t *rp;
11771 	page_t *pp;
11772 	kmutex_t *vphm;
11773 
11774 	rp = VTOR4(vp);
11775 
11776 	ASSERT(rp->r_flags & R4COMMIT);
11777 
11778 	/* make sure we're looking at the master vnode, not a shadow */
11779 
11780 	if (IS_SHADOW(vp, rp))
11781 		vp = RTOV4(rp);
11782 
11783 	vphm = page_vnode_mutex(vp);
11784 	mutex_enter(vphm);
11785 
11786 	/*
11787 	 * If there are no pages associated with this vnode, then
11788 	 * just return.
11789 	 */
11790 	if ((pp = vp->v_pages) == NULL) {
11791 		mutex_exit(vphm);
11792 		return;
11793 	}
11794 
11795 	/*
11796 	 * Step through all of the pages associated with this vnode
11797 	 * looking for pages which need to be committed.
11798 	 */
11799 	do {
11800 		/*
11801 		 * First short-cut everything (without the page_lock)
11802 		 * and see if this page does not need to be committed
11803 		 * or is modified if so then we'll just skip it.
11804 		 */
11805 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
11806 			continue;
11807 
11808 		/*
11809 		 * Attempt to lock the page.  If we can't, then
11810 		 * someone else is messing with it or we have been
11811 		 * called from nfs4_dispose and this is the page that
11812 		 * nfs4_dispose was called with.. anyway just skip it.
11813 		 */
11814 		if (!page_trylock(pp, SE_EXCL))
11815 			continue;
11816 
11817 		/*
11818 		 * Lets check again now that we have the page lock.
11819 		 */
11820 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11821 			page_unlock(pp);
11822 			continue;
11823 		}
11824 
11825 		/* this had better not be a free page */
11826 		ASSERT(PP_ISFREE(pp) == 0);
11827 
11828 		/*
11829 		 * The page needs to be committed and we locked it.
11830 		 * Update the base and length parameters and add it
11831 		 * to r_pages.
11832 		 */
11833 		if (rp->r_commit.c_pages == NULL) {
11834 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11835 			rp->r_commit.c_commlen = PAGESIZE;
11836 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
11837 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
11838 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
11839 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11840 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
11841 		    <= pp->p_offset) {
11842 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11843 			    rp->r_commit.c_commbase + PAGESIZE;
11844 		}
11845 		page_add(&rp->r_commit.c_pages, pp);
11846 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11847 
11848 	mutex_exit(vphm);
11849 }
11850 
11851 /*
11852  * This routine is used to gather together a page list of the pages
11853  * which are to be committed on the server.  This routine must not
11854  * be called if the calling thread holds any locked pages.
11855  *
11856  * The calling thread must have set R4COMMIT.  This bit is used to
11857  * serialize access to the commit structure in the rnode.  As long
11858  * as the thread has set R4COMMIT, then it can manipulate the commit
11859  * structure without requiring any other locks.
11860  */
11861 static void
11862 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
11863 {
11864 
11865 	rnode4_t *rp;
11866 	page_t *pp;
11867 	u_offset_t end;
11868 	u_offset_t off;
11869 	ASSERT(len != 0);
11870 	rp = VTOR4(vp);
11871 	ASSERT(rp->r_flags & R4COMMIT);
11872 
11873 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11874 
11875 	/* make sure we're looking at the master vnode, not a shadow */
11876 
11877 	if (IS_SHADOW(vp, rp))
11878 		vp = RTOV4(rp);
11879 
11880 	/*
11881 	 * If there are no pages associated with this vnode, then
11882 	 * just return.
11883 	 */
11884 	if ((pp = vp->v_pages) == NULL)
11885 		return;
11886 	/*
11887 	 * Calculate the ending offset.
11888 	 */
11889 	end = soff + len;
11890 	for (off = soff; off < end; off += PAGESIZE) {
11891 		/*
11892 		 * Lookup each page by vp, offset.
11893 		 */
11894 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
11895 			continue;
11896 		/*
11897 		 * If this page does not need to be committed or is
11898 		 * modified, then just skip it.
11899 		 */
11900 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11901 			page_unlock(pp);
11902 			continue;
11903 		}
11904 
11905 		ASSERT(PP_ISFREE(pp) == 0);
11906 		/*
11907 		 * The page needs to be committed and we locked it.
11908 		 * Update the base and length parameters and add it
11909 		 * to r_pages.
11910 		 */
11911 		if (rp->r_commit.c_pages == NULL) {
11912 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11913 			rp->r_commit.c_commlen = PAGESIZE;
11914 		} else {
11915 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11916 			    rp->r_commit.c_commbase + PAGESIZE;
11917 		}
11918 		page_add(&rp->r_commit.c_pages, pp);
11919 	}
11920 }
11921 
11922 /*
11923  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
11924  * Flushes and commits data to the server.
11925  */
11926 static int
11927 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
11928 {
11929 	int error;
11930 	verifier4 write_verf;
11931 	rnode4_t *rp = VTOR4(vp);
11932 
11933 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11934 
11935 	/*
11936 	 * Flush the data portion of the file and then commit any
11937 	 * portions which need to be committed.  This may need to
11938 	 * be done twice if the server has changed state since
11939 	 * data was last written.  The data will need to be
11940 	 * rewritten to the server and then a new commit done.
11941 	 *
11942 	 * In fact, this may need to be done several times if the
11943 	 * server is having problems and crashing while we are
11944 	 * attempting to do this.
11945 	 */
11946 
11947 top:
11948 	/*
11949 	 * Do a flush based on the poff and plen arguments.  This
11950 	 * will synchronously write out any modified pages in the
11951 	 * range specified by (poff, plen). This starts all of the
11952 	 * i/o operations which will be waited for in the next
11953 	 * call to nfs4_putpage
11954 	 */
11955 
11956 	mutex_enter(&rp->r_statelock);
11957 	write_verf = rp->r_writeverf;
11958 	mutex_exit(&rp->r_statelock);
11959 
11960 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr, NULL);
11961 	if (error == EAGAIN)
11962 		error = 0;
11963 
11964 	/*
11965 	 * Do a flush based on the poff and plen arguments.  This
11966 	 * will synchronously write out any modified pages in the
11967 	 * range specified by (poff, plen) and wait until all of
11968 	 * the asynchronous i/o's in that range are done as well.
11969 	 */
11970 	if (!error)
11971 		error = nfs4_putpage(vp, poff, plen, 0, cr, NULL);
11972 
11973 	if (error)
11974 		return (error);
11975 
11976 	mutex_enter(&rp->r_statelock);
11977 	if (rp->r_writeverf != write_verf) {
11978 		mutex_exit(&rp->r_statelock);
11979 		goto top;
11980 	}
11981 	mutex_exit(&rp->r_statelock);
11982 
11983 	/*
11984 	 * Now commit any pages which might need to be committed.
11985 	 * If the error, NFS_VERF_MISMATCH, is returned, then
11986 	 * start over with the flush operation.
11987 	 */
11988 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
11989 
11990 	if (error == NFS_VERF_MISMATCH)
11991 		goto top;
11992 
11993 	return (error);
11994 }
11995 
11996 /*
11997  * nfs4_commit_vp()  will wait for other pending commits and
11998  * will either commit the whole file or a range, plen dictates
11999  * if we commit whole file. a value of zero indicates the whole
12000  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
12001  */
12002 static int
12003 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12004     cred_t *cr, int wait_on_writes)
12005 {
12006 	rnode4_t *rp;
12007 	page_t *plist;
12008 	offset3 offset;
12009 	count3 len;
12010 
12011 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12012 
12013 	rp = VTOR4(vp);
12014 
12015 	/*
12016 	 *  before we gather commitable pages make
12017 	 *  sure there are no outstanding async writes
12018 	 */
12019 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12020 		mutex_enter(&rp->r_statelock);
12021 		while (rp->r_count > 0) {
12022 			cv_wait(&rp->r_cv, &rp->r_statelock);
12023 		}
12024 		mutex_exit(&rp->r_statelock);
12025 	}
12026 
12027 	/*
12028 	 * Set the `commit inprogress' state bit.  We must
12029 	 * first wait until any current one finishes.
12030 	 */
12031 	mutex_enter(&rp->r_statelock);
12032 	while (rp->r_flags & R4COMMIT) {
12033 		rp->r_flags |= R4COMMITWAIT;
12034 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12035 		rp->r_flags &= ~R4COMMITWAIT;
12036 	}
12037 	rp->r_flags |= R4COMMIT;
12038 	mutex_exit(&rp->r_statelock);
12039 
12040 	/*
12041 	 * Gather all of the pages which need to be
12042 	 * committed.
12043 	 */
12044 	if (plen == 0)
12045 		nfs4_get_commit(vp);
12046 	else
12047 		nfs4_get_commit_range(vp, poff, plen);
12048 
12049 	/*
12050 	 * Clear the `commit inprogress' bit and disconnect the
12051 	 * page list which was gathered by nfs4_get_commit.
12052 	 */
12053 	plist = rp->r_commit.c_pages;
12054 	rp->r_commit.c_pages = NULL;
12055 	offset = rp->r_commit.c_commbase;
12056 	len = rp->r_commit.c_commlen;
12057 	mutex_enter(&rp->r_statelock);
12058 	rp->r_flags &= ~R4COMMIT;
12059 	cv_broadcast(&rp->r_commit.c_cv);
12060 	mutex_exit(&rp->r_statelock);
12061 
12062 	/*
12063 	 * If any pages need to be committed, commit them and
12064 	 * then unlock them so that they can be freed some
12065 	 * time later.
12066 	 */
12067 	if (plist == NULL)
12068 		return (0);
12069 
12070 	/*
12071 	 * No error occurred during the flush portion
12072 	 * of this operation, so now attempt to commit
12073 	 * the data to stable storage on the server.
12074 	 *
12075 	 * This will unlock all of the pages on the list.
12076 	 */
12077 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12078 }
12079 
12080 static int
12081 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12082     cred_t *cr)
12083 {
12084 	int error;
12085 	page_t *pp;
12086 
12087 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12088 
12089 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12090 
12091 	/*
12092 	 * If we got an error, then just unlock all of the pages
12093 	 * on the list.
12094 	 */
12095 	if (error) {
12096 		while (plist != NULL) {
12097 			pp = plist;
12098 			page_sub(&plist, pp);
12099 			page_unlock(pp);
12100 		}
12101 		return (error);
12102 	}
12103 	/*
12104 	 * We've tried as hard as we can to commit the data to stable
12105 	 * storage on the server.  We just unlock the pages and clear
12106 	 * the commit required state.  They will get freed later.
12107 	 */
12108 	while (plist != NULL) {
12109 		pp = plist;
12110 		page_sub(&plist, pp);
12111 		pp->p_fsdata = C_NOCOMMIT;
12112 		page_unlock(pp);
12113 	}
12114 
12115 	return (error);
12116 }
12117 
12118 static void
12119 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12120     cred_t *cr)
12121 {
12122 
12123 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12124 }
12125 
12126 /*ARGSUSED*/
12127 static int
12128 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12129 	caller_context_t *ct)
12130 {
12131 	int		error = 0;
12132 	mntinfo4_t	*mi;
12133 	vattr_t		va;
12134 	vsecattr_t	nfsace4_vsap;
12135 
12136 	mi = VTOMI4(vp);
12137 	if (nfs_zone() != mi->mi_zone)
12138 		return (EIO);
12139 	if (mi->mi_flags & MI4_ACL) {
12140 		/* if we have a delegation, return it */
12141 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12142 			(void) nfs4delegreturn(VTOR4(vp),
12143 			    NFS4_DR_REOPEN|NFS4_DR_PUSH);
12144 
12145 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12146 		    NFS4_ACL_SET);
12147 		if (error) /* EINVAL */
12148 			return (error);
12149 
12150 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12151 			/*
12152 			 * These are aclent_t type entries.
12153 			 */
12154 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12155 			    vp->v_type == VDIR, FALSE);
12156 			if (error)
12157 				return (error);
12158 		} else {
12159 			/*
12160 			 * These are ace_t type entries.
12161 			 */
12162 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12163 			    FALSE);
12164 			if (error)
12165 				return (error);
12166 		}
12167 		bzero(&va, sizeof (va));
12168 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12169 		vs_ace4_destroy(&nfsace4_vsap);
12170 		return (error);
12171 	}
12172 	return (ENOSYS);
12173 }
12174 
12175 /* ARGSUSED */
12176 int
12177 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12178 	caller_context_t *ct)
12179 {
12180 	int		error;
12181 	mntinfo4_t	*mi;
12182 	nfs4_ga_res_t	gar;
12183 	rnode4_t	*rp = VTOR4(vp);
12184 
12185 	mi = VTOMI4(vp);
12186 	if (nfs_zone() != mi->mi_zone)
12187 		return (EIO);
12188 
12189 	bzero(&gar, sizeof (gar));
12190 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12191 
12192 	/*
12193 	 * vsecattr->vsa_mask holds the original acl request mask.
12194 	 * This is needed when determining what to return.
12195 	 * (See: nfs4_create_getsecattr_return())
12196 	 */
12197 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12198 	if (error) /* EINVAL */
12199 		return (error);
12200 
12201 	if (mi->mi_flags & MI4_ACL) {
12202 		/*
12203 		 * Check if the data is cached and the cache is valid.  If it
12204 		 * is we don't go over the wire.
12205 		 */
12206 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12207 			mutex_enter(&rp->r_statelock);
12208 			if (rp->r_secattr != NULL) {
12209 				error = nfs4_create_getsecattr_return(
12210 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12211 				    rp->r_attr.va_gid,
12212 				    vp->v_type == VDIR);
12213 				if (!error) { /* error == 0 - Success! */
12214 					mutex_exit(&rp->r_statelock);
12215 					return (error);
12216 				}
12217 			}
12218 			mutex_exit(&rp->r_statelock);
12219 		}
12220 
12221 		/*
12222 		 * The getattr otw call will always get both the acl, in
12223 		 * the form of a list of nfsace4's, and the number of acl
12224 		 * entries; independent of the value of gar.n4g_vsa.vsa_mask.
12225 		 */
12226 		gar.n4g_va.va_mask = AT_ALL;
12227 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12228 		if (error) {
12229 			vs_ace4_destroy(&gar.n4g_vsa);
12230 			if (error == ENOTSUP || error == EOPNOTSUPP)
12231 				error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12232 			return (error);
12233 		}
12234 
12235 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12236 			/*
12237 			 * No error was returned, but according to the response
12238 			 * bitmap, neither was an acl.
12239 			 */
12240 			vs_ace4_destroy(&gar.n4g_vsa);
12241 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12242 			return (error);
12243 		}
12244 
12245 		/*
12246 		 * Update the cache with the ACL.
12247 		 */
12248 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12249 
12250 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12251 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12252 		    vp->v_type == VDIR);
12253 		vs_ace4_destroy(&gar.n4g_vsa);
12254 		if ((error) && (vsecattr->vsa_mask &
12255 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12256 		    (error != EACCES)) {
12257 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12258 		}
12259 		return (error);
12260 	}
12261 	error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12262 	return (error);
12263 }
12264 
12265 /*
12266  * The function returns:
12267  * 	- 0 (zero) if the passed in "acl_mask" is a valid request.
12268  * 	- EINVAL if the passed in "acl_mask" is an invalid request.
12269  *
12270  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12271  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12272  *
12273  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12274  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12275  * - We have a count field set without the corresponding acl field set. (e.g. -
12276  * VSA_ACECNT is set, but VSA_ACE is not)
12277  */
12278 static int
12279 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12280 {
12281 	/* Shortcut the masks that are always valid. */
12282 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12283 		return (0);
12284 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12285 		return (0);
12286 
12287 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12288 		/*
12289 		 * We can't have any VSA_ACL type stuff in the mask now.
12290 		 */
12291 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12292 		    VSA_DFACLCNT))
12293 			return (EINVAL);
12294 
12295 		if (op == NFS4_ACL_SET) {
12296 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12297 				return (EINVAL);
12298 		}
12299 	}
12300 
12301 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12302 		/*
12303 		 * We can't have any VSA_ACE type stuff in the mask now.
12304 		 */
12305 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12306 			return (EINVAL);
12307 
12308 		if (op == NFS4_ACL_SET) {
12309 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12310 				return (EINVAL);
12311 
12312 			if ((acl_mask & VSA_DFACLCNT) &&
12313 			    !(acl_mask & VSA_DFACL))
12314 				return (EINVAL);
12315 		}
12316 	}
12317 	return (0);
12318 }
12319 
12320 /*
12321  * The theory behind creating the correct getsecattr return is simply this:
12322  * "Don't return anything that the caller is not expecting to have to free."
12323  */
12324 static int
12325 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12326     uid_t uid, gid_t gid, int isdir)
12327 {
12328 	int error = 0;
12329 	/* Save the mask since the translators modify it. */
12330 	uint_t	orig_mask = vsap->vsa_mask;
12331 
12332 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12333 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid,
12334 		    FALSE, ((orig_mask & VSA_ACE) ? FALSE : TRUE));
12335 
12336 		if (error)
12337 			return (error);
12338 
12339 		/*
12340 		 * If the caller only asked for the ace count (VSA_ACECNT)
12341 		 * don't give them the full acl (VSA_ACE), free it.
12342 		 */
12343 		if (!orig_mask & VSA_ACE) {
12344 			if (vsap->vsa_aclentp != NULL) {
12345 				kmem_free(vsap->vsa_aclentp,
12346 				    vsap->vsa_aclcnt * sizeof (ace_t));
12347 				vsap->vsa_aclentp = NULL;
12348 			}
12349 		}
12350 		vsap->vsa_mask = orig_mask;
12351 
12352 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12353 	    VSA_DFACLCNT)) {
12354 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12355 		    isdir, FALSE,
12356 		    ((orig_mask & (VSA_ACL | VSA_DFACL)) ? FALSE : TRUE));
12357 
12358 		if (error)
12359 			return (error);
12360 
12361 		/*
12362 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12363 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12364 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12365 		 */
12366 		if (!orig_mask & VSA_ACL) {
12367 			if (vsap->vsa_aclentp != NULL) {
12368 				kmem_free(vsap->vsa_aclentp,
12369 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12370 				vsap->vsa_aclentp = NULL;
12371 			}
12372 		}
12373 
12374 		if (!orig_mask & VSA_DFACL) {
12375 			if (vsap->vsa_dfaclentp != NULL) {
12376 				kmem_free(vsap->vsa_dfaclentp,
12377 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12378 				vsap->vsa_dfaclentp = NULL;
12379 			}
12380 		}
12381 		vsap->vsa_mask = orig_mask;
12382 	}
12383 	return (0);
12384 }
12385 
12386 /* ARGSUSED */
12387 int
12388 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr,
12389     caller_context_t *ct)
12390 {
12391 	int error;
12392 
12393 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12394 		return (EIO);
12395 	/*
12396 	 * check for valid cmd parameter
12397 	 */
12398 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12399 		return (EINVAL);
12400 
12401 	/*
12402 	 * Check access permissions
12403 	 */
12404 	if ((cmd & F_SHARE) &&
12405 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12406 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12407 		return (EBADF);
12408 
12409 	/*
12410 	 * If the filesystem is mounted using local locking, pass the
12411 	 * request off to the local share code.
12412 	 */
12413 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12414 		return (fs_shrlock(vp, cmd, shr, flag, cr, ct));
12415 
12416 	switch (cmd) {
12417 	case F_SHARE:
12418 	case F_UNSHARE:
12419 		/*
12420 		 * This will be properly implemented later,
12421 		 * see RFE: 4823948 .
12422 		 */
12423 		error = EAGAIN;
12424 		break;
12425 
12426 	case F_HASREMOTELOCKS:
12427 		/*
12428 		 * NFS client can't store remote locks itself
12429 		 */
12430 		shr->s_access = 0;
12431 		error = 0;
12432 		break;
12433 
12434 	default:
12435 		error = EINVAL;
12436 		break;
12437 	}
12438 
12439 	return (error);
12440 }
12441 
12442 /*
12443  * Common code called by directory ops to update the attrcache
12444  */
12445 static int
12446 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12447     hrtime_t t, vnode_t *vp, cred_t *cr)
12448 {
12449 	int error = 0;
12450 
12451 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12452 
12453 	if (status != NFS4_OK) {
12454 		/* getattr not done or failed */
12455 		PURGE_ATTRCACHE4(vp);
12456 		return (error);
12457 	}
12458 
12459 	if (garp) {
12460 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12461 	} else {
12462 		PURGE_ATTRCACHE4(vp);
12463 	}
12464 	return (error);
12465 }
12466 
12467 /*
12468  * Update directory caches for directory modification ops (link, rename, etc.)
12469  * When dinfo is NULL, manage dircaches in the old way.
12470  */
12471 static void
12472 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12473     dirattr_info_t *dinfo)
12474 {
12475 	rnode4_t	*drp = VTOR4(dvp);
12476 
12477 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12478 
12479 	/* Purge rddir cache for dir since it changed */
12480 	if (drp->r_dir != NULL)
12481 		nfs4_purge_rddir_cache(dvp);
12482 
12483 	/*
12484 	 * If caller provided dinfo, then use it to manage dir caches.
12485 	 */
12486 	if (dinfo != NULL) {
12487 		if (vp != NULL) {
12488 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12489 			if (!VTOR4(vp)->created_v4) {
12490 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12491 				dnlc_update(dvp, nm, vp);
12492 			} else {
12493 				/*
12494 				 * XXX don't update if the created_v4 flag is
12495 				 * set
12496 				 */
12497 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12498 				NFS4_DEBUG(nfs4_client_state_debug,
12499 				    (CE_NOTE, "nfs4_update_dircaches: "
12500 				    "don't update dnlc: created_v4 flag"));
12501 			}
12502 		}
12503 
12504 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12505 		    dinfo->di_cred, FALSE, cinfo);
12506 
12507 		return;
12508 	}
12509 
12510 	/*
12511 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12512 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12513 	 * attrs, the dir's attrs must be purged.
12514 	 *
12515 	 * XXX this check and dnlc update/purge should really be atomic,
12516 	 * XXX but can't use rnode statelock because it'll deadlock in
12517 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12518 	 * XXX does occur.
12519 	 *
12520 	 * XXX We also may want to check that atomic is true in the
12521 	 * XXX change_info struct. If it is not, the change_info may
12522 	 * XXX reflect changes by more than one clients which means that
12523 	 * XXX our cache may not be valid.
12524 	 */
12525 	PURGE_ATTRCACHE4(dvp);
12526 	if (drp->r_change == cinfo->before) {
12527 		/* no changes took place in the directory prior to our link */
12528 		if (vp != NULL) {
12529 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12530 			if (!VTOR4(vp)->created_v4) {
12531 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12532 				dnlc_update(dvp, nm, vp);
12533 			} else {
12534 				/*
12535 				 * XXX dont' update if the created_v4 flag
12536 				 * is set
12537 				 */
12538 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12539 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12540 				    "nfs4_update_dircaches: don't"
12541 				    " update dnlc: created_v4 flag"));
12542 			}
12543 		}
12544 	} else {
12545 		/* Another client modified directory - purge its dnlc cache */
12546 		dnlc_purge_vp(dvp);
12547 	}
12548 }
12549 
12550 /*
12551  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12552  * file.
12553  *
12554  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12555  * file (ie: client recovery) and otherwise set to FALSE.
12556  *
12557  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12558  * initiated) calling functions.
12559  *
12560  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12561  * of resending a 'lost' open request.
12562  *
12563  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12564  * server that hands out BAD_SEQID on open confirm.
12565  *
12566  * Errors are returned via the nfs4_error_t parameter.
12567  */
12568 void
12569 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12570     bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12571     bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12572 {
12573 	COMPOUND4args_clnt args;
12574 	COMPOUND4res_clnt res;
12575 	nfs_argop4 argop[2];
12576 	nfs_resop4 *resop;
12577 	int doqueue = 1;
12578 	mntinfo4_t *mi;
12579 	OPEN_CONFIRM4args *open_confirm_args;
12580 	int needrecov;
12581 
12582 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12583 #if DEBUG
12584 	mutex_enter(&oop->oo_lock);
12585 	ASSERT(oop->oo_seqid_inuse);
12586 	mutex_exit(&oop->oo_lock);
12587 #endif
12588 
12589 recov_retry_confirm:
12590 	nfs4_error_zinit(ep);
12591 	*retry_open = FALSE;
12592 
12593 	if (resend)
12594 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12595 	else
12596 		args.ctag = TAG_OPEN_CONFIRM;
12597 
12598 	args.array_len = 2;
12599 	args.array = argop;
12600 
12601 	/* putfh target fh */
12602 	argop[0].argop = OP_CPUTFH;
12603 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12604 
12605 	argop[1].argop = OP_OPEN_CONFIRM;
12606 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12607 
12608 	(*seqid) += 1;
12609 	open_confirm_args->seqid = *seqid;
12610 	open_confirm_args->open_stateid = *stateid;
12611 
12612 	mi = VTOMI4(vp);
12613 
12614 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12615 
12616 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12617 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12618 	}
12619 
12620 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12621 	if (!needrecov && ep->error)
12622 		return;
12623 
12624 	if (needrecov) {
12625 		bool_t abort = FALSE;
12626 
12627 		if (reopening_file == FALSE) {
12628 			nfs4_bseqid_entry_t *bsep = NULL;
12629 
12630 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12631 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12632 				    vp, 0, args.ctag,
12633 				    open_confirm_args->seqid);
12634 
12635 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp,
12636 			    NULL, NULL, NULL, OP_OPEN_CONFIRM, bsep);
12637 			if (bsep) {
12638 				kmem_free(bsep, sizeof (*bsep));
12639 				if (num_bseqid_retryp &&
12640 				    --(*num_bseqid_retryp) == 0)
12641 					abort = TRUE;
12642 			}
12643 		}
12644 		if ((ep->error == ETIMEDOUT ||
12645 		    res.status == NFS4ERR_RESOURCE) &&
12646 		    abort == FALSE && resend == FALSE) {
12647 			if (!ep->error)
12648 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12649 				    (caddr_t)&res);
12650 
12651 			delay(SEC_TO_TICK(confirm_retry_sec));
12652 			goto recov_retry_confirm;
12653 		}
12654 		/* State may have changed so retry the entire OPEN op */
12655 		if (abort == FALSE)
12656 			*retry_open = TRUE;
12657 		else
12658 			*retry_open = FALSE;
12659 		if (!ep->error)
12660 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12661 		return;
12662 	}
12663 
12664 	if (res.status) {
12665 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12666 		return;
12667 	}
12668 
12669 	resop = &res.array[1];  /* open confirm res */
12670 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
12671 	    stateid, sizeof (*stateid));
12672 
12673 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12674 }
12675 
12676 /*
12677  * Return the credentials associated with a client state object.  The
12678  * caller is responsible for freeing the credentials.
12679  */
12680 
12681 static cred_t *
12682 state_to_cred(nfs4_open_stream_t *osp)
12683 {
12684 	cred_t *cr;
12685 
12686 	/*
12687 	 * It's ok to not lock the open stream and open owner to get
12688 	 * the oo_cred since this is only written once (upon creation)
12689 	 * and will not change.
12690 	 */
12691 	cr = osp->os_open_owner->oo_cred;
12692 	crhold(cr);
12693 
12694 	return (cr);
12695 }
12696 
12697 /*
12698  * nfs4_find_sysid
12699  *
12700  * Find the sysid for the knetconfig associated with the given mi.
12701  */
12702 static struct lm_sysid *
12703 nfs4_find_sysid(mntinfo4_t *mi)
12704 {
12705 	ASSERT(nfs_zone() == mi->mi_zone);
12706 
12707 	/*
12708 	 * Switch from RDMA knconf to original mount knconf
12709 	 */
12710 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
12711 	    mi->mi_curr_serv->sv_hostname, NULL));
12712 }
12713 
12714 #ifdef DEBUG
12715 /*
12716  * Return a string version of the call type for easy reading.
12717  */
12718 static char *
12719 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
12720 {
12721 	switch (ctype) {
12722 	case NFS4_LCK_CTYPE_NORM:
12723 		return ("NORMAL");
12724 	case NFS4_LCK_CTYPE_RECLAIM:
12725 		return ("RECLAIM");
12726 	case NFS4_LCK_CTYPE_RESEND:
12727 		return ("RESEND");
12728 	case NFS4_LCK_CTYPE_REINSTATE:
12729 		return ("REINSTATE");
12730 	default:
12731 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
12732 		    "type %d", ctype);
12733 		return ("");
12734 	}
12735 }
12736 #endif
12737 
12738 /*
12739  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
12740  * Unlock requests don't have an over-the-wire locktype, so we just return
12741  * something non-threatening.
12742  */
12743 
12744 static nfs_lock_type4
12745 flk_to_locktype(int cmd, int l_type)
12746 {
12747 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
12748 
12749 	switch (l_type) {
12750 	case F_UNLCK:
12751 		return (READ_LT);
12752 	case F_RDLCK:
12753 		if (cmd == F_SETLK)
12754 			return (READ_LT);
12755 		else
12756 			return (READW_LT);
12757 	case F_WRLCK:
12758 		if (cmd == F_SETLK)
12759 			return (WRITE_LT);
12760 		else
12761 			return (WRITEW_LT);
12762 	}
12763 	panic("flk_to_locktype");
12764 	/*NOTREACHED*/
12765 }
12766 
12767 /*
12768  * Do some preliminary checks for nfs4frlock.
12769  */
12770 static int
12771 nfs4frlock_validate_args(int cmd, flock64_t *flk, int flag, vnode_t *vp,
12772     u_offset_t offset)
12773 {
12774 	int error = 0;
12775 
12776 	/*
12777 	 * If we are setting a lock, check that the file is opened
12778 	 * with the correct mode.
12779 	 */
12780 	if (cmd == F_SETLK || cmd == F_SETLKW) {
12781 		if ((flk->l_type == F_RDLCK && (flag & FREAD) == 0) ||
12782 		    (flk->l_type == F_WRLCK && (flag & FWRITE) == 0)) {
12783 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12784 			    "nfs4frlock_validate_args: file was opened with "
12785 			    "incorrect mode"));
12786 			return (EBADF);
12787 		}
12788 	}
12789 
12790 	/* Convert the offset. It may need to be restored before returning. */
12791 	if (error = convoff(vp, flk, 0, offset)) {
12792 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12793 		    "nfs4frlock_validate_args: convoff  =>  error= %d\n",
12794 		    error));
12795 		return (error);
12796 	}
12797 
12798 	return (error);
12799 }
12800 
12801 /*
12802  * Set the flock64's lm_sysid for nfs4frlock.
12803  */
12804 static int
12805 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
12806 {
12807 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12808 
12809 	/* Find the lm_sysid */
12810 	*lspp = nfs4_find_sysid(VTOMI4(vp));
12811 
12812 	if (*lspp == NULL) {
12813 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12814 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
12815 		return (ENOLCK);
12816 	}
12817 
12818 	flk->l_sysid = lm_sysidt(*lspp);
12819 
12820 	return (0);
12821 }
12822 
12823 /*
12824  * Do the remaining preliminary setup for nfs4frlock.
12825  */
12826 static void
12827 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
12828     flock64_t *flk, short *whencep, vnode_t *vp, cred_t *search_cr,
12829     cred_t **cred_otw)
12830 {
12831 	/*
12832 	 * set tick_delay to the base delay time.
12833 	 * (NFS4_BASE_WAIT_TIME is in secs)
12834 	 */
12835 
12836 	*tick_delayp = drv_usectohz(NFS4_BASE_WAIT_TIME * 1000 * 1000);
12837 
12838 	/*
12839 	 * If lock is relative to EOF, we need the newest length of the
12840 	 * file. Therefore invalidate the ATTR_CACHE.
12841 	 */
12842 
12843 	*whencep = flk->l_whence;
12844 
12845 	if (*whencep == 2)		/* SEEK_END */
12846 		PURGE_ATTRCACHE4(vp);
12847 
12848 	recov_statep->rs_flags = 0;
12849 	recov_statep->rs_num_retry_despite_err = 0;
12850 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
12851 }
12852 
12853 /*
12854  * Initialize and allocate the data structures necessary for
12855  * the nfs4frlock call.
12856  * Allocates argsp's op array, frees up the saved_rqstpp if there is one.
12857  */
12858 static void
12859 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
12860     nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
12861     bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
12862     bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
12863 {
12864 	int		argoplist_size;
12865 	int		num_ops = 2;
12866 
12867 	*retry = FALSE;
12868 	*did_start_fop = FALSE;
12869 	*skip_get_err = FALSE;
12870 	lost_rqstp->lr_op = 0;
12871 	argoplist_size  = num_ops * sizeof (nfs_argop4);
12872 	/* fill array with zero */
12873 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
12874 
12875 	*argspp = argsp;
12876 	*respp = NULL;
12877 
12878 	argsp->array_len = num_ops;
12879 	argsp->array = *argopp;
12880 
12881 	/* initialize in case of error; will get real value down below */
12882 	argsp->ctag = TAG_NONE;
12883 
12884 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
12885 		*op_hintp = OH_LOCKU;
12886 	else
12887 		*op_hintp = OH_OTHER;
12888 }
12889 
12890 /*
12891  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
12892  * the proper nfs4_server_t for this instance of nfs4frlock.
12893  * Returns 0 (success) or an errno value.
12894  */
12895 static int
12896 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
12897     nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
12898     bool_t *did_start_fop, bool_t *startrecovp)
12899 {
12900 	int error = 0;
12901 	rnode4_t *rp;
12902 
12903 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12904 
12905 	if (ctype == NFS4_LCK_CTYPE_NORM) {
12906 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
12907 		    recov_statep, startrecovp);
12908 		if (error)
12909 			return (error);
12910 		*did_start_fop = TRUE;
12911 	} else {
12912 		*did_start_fop = FALSE;
12913 		*startrecovp = FALSE;
12914 	}
12915 
12916 	if (!error) {
12917 		rp = VTOR4(vp);
12918 
12919 		/* If the file failed recovery, just quit. */
12920 		mutex_enter(&rp->r_statelock);
12921 		if (rp->r_flags & R4RECOVERR) {
12922 			error = EIO;
12923 		}
12924 		mutex_exit(&rp->r_statelock);
12925 	}
12926 
12927 	return (error);
12928 }
12929 
12930 /*
12931  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
12932  * resend nfs4frlock call is initiated by the recovery framework.
12933  * Acquires the lop and oop seqid synchronization.
12934  */
12935 static void
12936 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
12937     COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
12938     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
12939     LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
12940 {
12941 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
12942 	int error;
12943 
12944 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
12945 	    (CE_NOTE,
12946 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
12947 	ASSERT(resend_rqstp != NULL);
12948 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
12949 	    resend_rqstp->lr_op == OP_LOCKU);
12950 
12951 	*oopp = resend_rqstp->lr_oop;
12952 	if (resend_rqstp->lr_oop) {
12953 		open_owner_hold(resend_rqstp->lr_oop);
12954 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
12955 		ASSERT(error == 0);	/* recov thread always succeeds */
12956 	}
12957 
12958 	/* Must resend this lost lock/locku request. */
12959 	ASSERT(resend_rqstp->lr_lop != NULL);
12960 	*lopp = resend_rqstp->lr_lop;
12961 	lock_owner_hold(resend_rqstp->lr_lop);
12962 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
12963 	ASSERT(error == 0);	/* recov thread always succeeds */
12964 
12965 	*ospp = resend_rqstp->lr_osp;
12966 	if (*ospp)
12967 		open_stream_hold(resend_rqstp->lr_osp);
12968 
12969 	if (resend_rqstp->lr_op == OP_LOCK) {
12970 		LOCK4args *lock_args;
12971 
12972 		argop->argop = OP_LOCK;
12973 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
12974 		lock_args->locktype = resend_rqstp->lr_locktype;
12975 		lock_args->reclaim =
12976 		    (resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
12977 		lock_args->offset = resend_rqstp->lr_flk->l_start;
12978 		lock_args->length = resend_rqstp->lr_flk->l_len;
12979 		if (lock_args->length == 0)
12980 			lock_args->length = ~lock_args->length;
12981 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
12982 		    mi2clientid(mi), &lock_args->locker);
12983 
12984 		switch (resend_rqstp->lr_ctype) {
12985 		case NFS4_LCK_CTYPE_RESEND:
12986 			argsp->ctag = TAG_LOCK_RESEND;
12987 			break;
12988 		case NFS4_LCK_CTYPE_REINSTATE:
12989 			argsp->ctag = TAG_LOCK_REINSTATE;
12990 			break;
12991 		case NFS4_LCK_CTYPE_RECLAIM:
12992 			argsp->ctag = TAG_LOCK_RECLAIM;
12993 			break;
12994 		default:
12995 			argsp->ctag = TAG_LOCK_UNKNOWN;
12996 			break;
12997 		}
12998 	} else {
12999 		LOCKU4args *locku_args;
13000 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
13001 
13002 		argop->argop = OP_LOCKU;
13003 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
13004 		locku_args->locktype = READ_LT;
13005 		locku_args->seqid = lop->lock_seqid + 1;
13006 		mutex_enter(&lop->lo_lock);
13007 		locku_args->lock_stateid = lop->lock_stateid;
13008 		mutex_exit(&lop->lo_lock);
13009 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13010 		locku_args->length = resend_rqstp->lr_flk->l_len;
13011 		if (locku_args->length == 0)
13012 			locku_args->length = ~locku_args->length;
13013 
13014 		switch (resend_rqstp->lr_ctype) {
13015 		case NFS4_LCK_CTYPE_RESEND:
13016 			argsp->ctag = TAG_LOCKU_RESEND;
13017 			break;
13018 		case NFS4_LCK_CTYPE_REINSTATE:
13019 			argsp->ctag = TAG_LOCKU_REINSTATE;
13020 			break;
13021 		default:
13022 			argsp->ctag = TAG_LOCK_UNKNOWN;
13023 			break;
13024 		}
13025 	}
13026 }
13027 
13028 /*
13029  * Setup the LOCKT4 arguments.
13030  */
13031 static void
13032 nfs4frlock_setup_lockt_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13033     LOCKT4args **lockt_argsp, COMPOUND4args_clnt *argsp, flock64_t *flk,
13034     rnode4_t *rp)
13035 {
13036 	LOCKT4args *lockt_args;
13037 
13038 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13039 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13040 	argop->argop = OP_LOCKT;
13041 	argsp->ctag = TAG_LOCKT;
13042 	lockt_args = &argop->nfs_argop4_u.oplockt;
13043 
13044 	/*
13045 	 * The locktype will be READ_LT unless it's
13046 	 * a write lock. We do this because the Solaris
13047 	 * system call allows the combination of
13048 	 * F_UNLCK and F_GETLK* and so in that case the
13049 	 * unlock is mapped to a read.
13050 	 */
13051 	if (flk->l_type == F_WRLCK)
13052 		lockt_args->locktype = WRITE_LT;
13053 	else
13054 		lockt_args->locktype = READ_LT;
13055 
13056 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13057 	/* set the lock owner4 args */
13058 	nfs4_setlockowner_args(&lockt_args->owner, rp,
13059 	    ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13060 	    flk->l_pid);
13061 	lockt_args->offset = flk->l_start;
13062 	lockt_args->length = flk->l_len;
13063 	if (flk->l_len == 0)
13064 		lockt_args->length = ~lockt_args->length;
13065 
13066 	*lockt_argsp = lockt_args;
13067 }
13068 
13069 /*
13070  * If the client is holding a delegation, and the open stream to be used
13071  * with this lock request is a delegation open stream, then re-open the stream.
13072  * Sets the nfs4_error_t to all zeros unless the open stream has already
13073  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13074  * means the caller should retry (like a recovery retry).
13075  */
13076 static void
13077 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13078 {
13079 	open_delegation_type4	dt;
13080 	bool_t			reopen_needed, force;
13081 	nfs4_open_stream_t	*osp;
13082 	open_claim_type4 	oclaim;
13083 	rnode4_t		*rp = VTOR4(vp);
13084 	mntinfo4_t		*mi = VTOMI4(vp);
13085 
13086 	ASSERT(nfs_zone() == mi->mi_zone);
13087 
13088 	nfs4_error_zinit(ep);
13089 
13090 	mutex_enter(&rp->r_statev4_lock);
13091 	dt = rp->r_deleg_type;
13092 	mutex_exit(&rp->r_statev4_lock);
13093 
13094 	if (dt != OPEN_DELEGATE_NONE) {
13095 		nfs4_open_owner_t	*oop;
13096 
13097 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13098 		if (!oop) {
13099 			ep->stat = NFS4ERR_IO;
13100 			return;
13101 		}
13102 		/* returns with 'os_sync_lock' held */
13103 		osp = find_open_stream(oop, rp);
13104 		if (!osp) {
13105 			open_owner_rele(oop);
13106 			ep->stat = NFS4ERR_IO;
13107 			return;
13108 		}
13109 
13110 		if (osp->os_failed_reopen) {
13111 			NFS4_DEBUG((nfs4_open_stream_debug ||
13112 			    nfs4_client_lock_debug), (CE_NOTE,
13113 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13114 			    "for osp %p, cr %p, rp %s", (void *)osp,
13115 			    (void *)cr, rnode4info(rp)));
13116 			mutex_exit(&osp->os_sync_lock);
13117 			open_stream_rele(osp, rp);
13118 			open_owner_rele(oop);
13119 			ep->stat = NFS4ERR_IO;
13120 			return;
13121 		}
13122 
13123 		/*
13124 		 * Determine whether a reopen is needed.  If this
13125 		 * is a delegation open stream, then send the open
13126 		 * to the server to give visibility to the open owner.
13127 		 * Even if it isn't a delegation open stream, we need
13128 		 * to check if the previous open CLAIM_DELEGATE_CUR
13129 		 * was sufficient.
13130 		 */
13131 
13132 		reopen_needed = osp->os_delegation ||
13133 		    ((lt == F_RDLCK &&
13134 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13135 		    (lt == F_WRLCK &&
13136 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13137 
13138 		mutex_exit(&osp->os_sync_lock);
13139 		open_owner_rele(oop);
13140 
13141 		if (reopen_needed) {
13142 			/*
13143 			 * Always use CLAIM_PREVIOUS after server reboot.
13144 			 * The server will reject CLAIM_DELEGATE_CUR if
13145 			 * it is used during the grace period.
13146 			 */
13147 			mutex_enter(&mi->mi_lock);
13148 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13149 				oclaim = CLAIM_PREVIOUS;
13150 				force = TRUE;
13151 			} else {
13152 				oclaim = CLAIM_DELEGATE_CUR;
13153 				force = FALSE;
13154 			}
13155 			mutex_exit(&mi->mi_lock);
13156 
13157 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13158 			if (ep->error == EAGAIN) {
13159 				nfs4_error_zinit(ep);
13160 				ep->stat = NFS4ERR_DELAY;
13161 			}
13162 		}
13163 		open_stream_rele(osp, rp);
13164 		osp = NULL;
13165 	}
13166 }
13167 
13168 /*
13169  * Setup the LOCKU4 arguments.
13170  * Returns errors via the nfs4_error_t.
13171  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13172  *			over-the-wire.  The caller must release the
13173  *			reference on *lopp.
13174  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13175  * (other)		unrecoverable error.
13176  */
13177 static void
13178 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13179     LOCKU4args **locku_argsp, flock64_t *flk,
13180     nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13181     vnode_t *vp, int flag, u_offset_t offset, cred_t *cr,
13182     bool_t *skip_get_err, bool_t *go_otwp)
13183 {
13184 	nfs4_lock_owner_t	*lop = NULL;
13185 	LOCKU4args		*locku_args;
13186 	pid_t			pid;
13187 	bool_t			is_spec = FALSE;
13188 	rnode4_t		*rp = VTOR4(vp);
13189 
13190 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13191 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13192 
13193 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13194 	if (ep->error || ep->stat)
13195 		return;
13196 
13197 	argop->argop = OP_LOCKU;
13198 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13199 		argsp->ctag = TAG_LOCKU_REINSTATE;
13200 	else
13201 		argsp->ctag = TAG_LOCKU;
13202 	locku_args = &argop->nfs_argop4_u.oplocku;
13203 	*locku_argsp = locku_args;
13204 
13205 	/*
13206 	 * XXX what should locku_args->locktype be?
13207 	 * setting to ALWAYS be READ_LT so at least
13208 	 * it is a valid locktype.
13209 	 */
13210 
13211 	locku_args->locktype = READ_LT;
13212 
13213 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13214 	    flk->l_pid;
13215 
13216 	/*
13217 	 * Get the lock owner stateid.  If no lock owner
13218 	 * exists, return success.
13219 	 */
13220 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13221 	*lopp = lop;
13222 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13223 		is_spec = TRUE;
13224 	if (!lop || is_spec) {
13225 		/*
13226 		 * No lock owner so no locks to unlock.
13227 		 * Return success.  If there was a failed
13228 		 * reclaim earlier, the lock might still be
13229 		 * registered with the local locking code,
13230 		 * so notify it of the unlock.
13231 		 *
13232 		 * If the lockowner is using a special stateid,
13233 		 * then the original lock request (that created
13234 		 * this lockowner) was never successful, so we
13235 		 * have no lock to undo OTW.
13236 		 */
13237 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13238 		    "nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13239 		    "(%ld) so return success", (long)pid));
13240 
13241 		if (ctype == NFS4_LCK_CTYPE_NORM)
13242 			flk->l_pid = curproc->p_pid;
13243 		nfs4_register_lock_locally(vp, flk, flag, offset);
13244 		/*
13245 		 * Release our hold and NULL out so final_cleanup
13246 		 * doesn't try to end a lock seqid sync we
13247 		 * never started.
13248 		 */
13249 		if (is_spec) {
13250 			lock_owner_rele(lop);
13251 			*lopp = NULL;
13252 		}
13253 		*skip_get_err = TRUE;
13254 		*go_otwp = FALSE;
13255 		return;
13256 	}
13257 
13258 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13259 	if (ep->error == EAGAIN) {
13260 		lock_owner_rele(lop);
13261 		*lopp = NULL;
13262 		return;
13263 	}
13264 
13265 	mutex_enter(&lop->lo_lock);
13266 	locku_args->lock_stateid = lop->lock_stateid;
13267 	mutex_exit(&lop->lo_lock);
13268 	locku_args->seqid = lop->lock_seqid + 1;
13269 
13270 	/* leave the ref count on lop, rele after RPC call */
13271 
13272 	locku_args->offset = flk->l_start;
13273 	locku_args->length = flk->l_len;
13274 	if (flk->l_len == 0)
13275 		locku_args->length = ~locku_args->length;
13276 
13277 	*go_otwp = TRUE;
13278 }
13279 
13280 /*
13281  * Setup the LOCK4 arguments.
13282  *
13283  * Returns errors via the nfs4_error_t.
13284  * NFS4_OK		no problems
13285  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13286  * (other)		unrecoverable error
13287  */
13288 static void
13289 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13290     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13291     nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13292     flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13293 {
13294 	LOCK4args		*lock_args;
13295 	nfs4_open_owner_t	*oop = NULL;
13296 	nfs4_open_stream_t	*osp = NULL;
13297 	nfs4_lock_owner_t	*lop = NULL;
13298 	pid_t			pid;
13299 	rnode4_t		*rp = VTOR4(vp);
13300 
13301 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13302 
13303 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13304 	if (ep->error || ep->stat != NFS4_OK)
13305 		return;
13306 
13307 	argop->argop = OP_LOCK;
13308 	if (ctype == NFS4_LCK_CTYPE_NORM)
13309 		argsp->ctag = TAG_LOCK;
13310 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13311 		argsp->ctag = TAG_RELOCK;
13312 	else
13313 		argsp->ctag = TAG_LOCK_REINSTATE;
13314 	lock_args = &argop->nfs_argop4_u.oplock;
13315 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13316 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13317 	/*
13318 	 * Get the lock owner.  If no lock owner exists,
13319 	 * create a 'temporary' one and grab the open seqid
13320 	 * synchronization (which puts a hold on the open
13321 	 * owner and open stream).
13322 	 * This also grabs the lock seqid synchronization.
13323 	 */
13324 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid : flk->l_pid;
13325 	ep->stat =
13326 	    nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13327 
13328 	if (ep->stat != NFS4_OK)
13329 		goto out;
13330 
13331 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13332 	    &lock_args->locker);
13333 
13334 	lock_args->offset = flk->l_start;
13335 	lock_args->length = flk->l_len;
13336 	if (flk->l_len == 0)
13337 		lock_args->length = ~lock_args->length;
13338 	*lock_argsp = lock_args;
13339 out:
13340 	*oopp = oop;
13341 	*ospp = osp;
13342 	*lopp = lop;
13343 }
13344 
13345 /*
13346  * After we get the reply from the server, record the proper information
13347  * for possible resend lock requests.
13348  *
13349  * Allocates memory for the saved_rqstp if we have a lost lock to save.
13350  */
13351 static void
13352 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13353     nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13354     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13355     nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13356 {
13357 	bool_t unlock = (flk->l_type == F_UNLCK);
13358 
13359 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13360 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13361 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13362 
13363 	if (error != 0 && !unlock) {
13364 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13365 		    nfs4_client_lock_debug), (CE_NOTE,
13366 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13367 		    " for lop %p", (void *)lop));
13368 		ASSERT(lop != NULL);
13369 		mutex_enter(&lop->lo_lock);
13370 		lop->lo_pending_rqsts = 1;
13371 		mutex_exit(&lop->lo_lock);
13372 	}
13373 
13374 	lost_rqstp->lr_putfirst = FALSE;
13375 	lost_rqstp->lr_op = 0;
13376 
13377 	/*
13378 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13379 	 * recovery purposes so that the lock request that was sent
13380 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13381 	 * unmount.  This is done to have the client's local locking state
13382 	 * match the v4 server's state; that is, the request was
13383 	 * potentially received and accepted by the server but the client
13384 	 * thinks it was not.
13385 	 */
13386 	if (error == ETIMEDOUT || error == EINTR ||
13387 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13388 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13389 		    nfs4_client_lock_debug), (CE_NOTE,
13390 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13391 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13392 		    (void *)lop, (void *)oop, (void *)osp));
13393 		if (unlock)
13394 			lost_rqstp->lr_op = OP_LOCKU;
13395 		else {
13396 			lost_rqstp->lr_op = OP_LOCK;
13397 			lost_rqstp->lr_locktype = locktype;
13398 		}
13399 		/*
13400 		 * Objects are held and rele'd via the recovery code.
13401 		 * See nfs4_save_lost_rqst.
13402 		 */
13403 		lost_rqstp->lr_vp = vp;
13404 		lost_rqstp->lr_dvp = NULL;
13405 		lost_rqstp->lr_oop = oop;
13406 		lost_rqstp->lr_osp = osp;
13407 		lost_rqstp->lr_lop = lop;
13408 		lost_rqstp->lr_cr = cr;
13409 		switch (ctype) {
13410 		case NFS4_LCK_CTYPE_NORM:
13411 			flk->l_pid = ttoproc(curthread)->p_pid;
13412 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13413 			break;
13414 		case NFS4_LCK_CTYPE_REINSTATE:
13415 			lost_rqstp->lr_putfirst = TRUE;
13416 			lost_rqstp->lr_ctype = ctype;
13417 			break;
13418 		default:
13419 			break;
13420 		}
13421 		lost_rqstp->lr_flk = flk;
13422 	}
13423 }
13424 
13425 /*
13426  * Update lop's seqid.  Also update the seqid stored in a resend request,
13427  * if any.  (Some recovery errors increment the seqid, and we may have to
13428  * send the resend request again.)
13429  */
13430 
13431 static void
13432 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13433     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13434 {
13435 	if (lock_args) {
13436 		if (lock_args->locker.new_lock_owner == TRUE)
13437 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13438 		else {
13439 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13440 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13441 		}
13442 	} else if (locku_args) {
13443 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13444 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13445 	}
13446 }
13447 
13448 /*
13449  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13450  * COMPOUND4 args/res for calls that need to retry.
13451  * Switches the *cred_otwp to base_cr.
13452  */
13453 static void
13454 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13455     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13456     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13457     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13458     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13459 {
13460 	nfs4_open_owner_t	*oop = *oopp;
13461 	nfs4_open_stream_t	*osp = *ospp;
13462 	nfs4_lock_owner_t	*lop = *lopp;
13463 	nfs_argop4		*argop = (*argspp)->array;
13464 
13465 	if (*did_start_fop) {
13466 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13467 		    needrecov);
13468 		*did_start_fop = FALSE;
13469 	}
13470 	ASSERT((*argspp)->array_len == 2);
13471 	if (argop[1].argop == OP_LOCK)
13472 		nfs4args_lock_free(&argop[1]);
13473 	else if (argop[1].argop == OP_LOCKT)
13474 		nfs4args_lockt_free(&argop[1]);
13475 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13476 	if (!error)
13477 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13478 	*argspp = NULL;
13479 	*respp = NULL;
13480 
13481 	if (lop) {
13482 		nfs4_end_lock_seqid_sync(lop);
13483 		lock_owner_rele(lop);
13484 		*lopp = NULL;
13485 	}
13486 
13487 	/* need to free up the reference on osp for lock args */
13488 	if (osp != NULL) {
13489 		open_stream_rele(osp, VTOR4(vp));
13490 		*ospp = NULL;
13491 	}
13492 
13493 	/* need to free up the reference on oop for lock args */
13494 	if (oop != NULL) {
13495 		nfs4_end_open_seqid_sync(oop);
13496 		open_owner_rele(oop);
13497 		*oopp = NULL;
13498 	}
13499 
13500 	crfree(*cred_otwp);
13501 	*cred_otwp = base_cr;
13502 	crhold(*cred_otwp);
13503 }
13504 
13505 /*
13506  * Function to process the client's recovery for nfs4frlock.
13507  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13508  *
13509  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13510  * COMPOUND4 args/res for calls that need to retry.
13511  *
13512  * Note: the rp's r_lkserlock is *not* dropped during this path.
13513  */
13514 static bool_t
13515 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13516     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13517     LOCK4args *lock_args, LOCKU4args *locku_args,
13518     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13519     nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13520     nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13521     bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13522 {
13523 	nfs4_open_owner_t	*oop = *oopp;
13524 	nfs4_open_stream_t	*osp = *ospp;
13525 	nfs4_lock_owner_t	*lop = *lopp;
13526 
13527 	bool_t abort, retry;
13528 
13529 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13530 	ASSERT((*argspp) != NULL);
13531 	ASSERT((*respp) != NULL);
13532 	if (lock_args || locku_args)
13533 		ASSERT(lop != NULL);
13534 
13535 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13536 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13537 
13538 	retry = TRUE;
13539 	abort = FALSE;
13540 	if (needrecov) {
13541 		nfs4_bseqid_entry_t *bsep = NULL;
13542 		nfs_opnum4 op;
13543 
13544 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13545 
13546 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13547 			seqid4 seqid;
13548 
13549 			if (lock_args) {
13550 				if (lock_args->locker.new_lock_owner == TRUE)
13551 					seqid = lock_args->locker.locker4_u.
13552 					    open_owner.open_seqid;
13553 				else
13554 					seqid = lock_args->locker.locker4_u.
13555 					    lock_owner.lock_seqid;
13556 			} else if (locku_args) {
13557 				seqid = locku_args->seqid;
13558 			} else {
13559 				seqid = 0;
13560 			}
13561 
13562 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13563 			    flk->l_pid, (*argspp)->ctag, seqid);
13564 		}
13565 
13566 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13567 		    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13568 		    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13569 		    NULL, op, bsep);
13570 
13571 		if (bsep)
13572 			kmem_free(bsep, sizeof (*bsep));
13573 	}
13574 
13575 	/*
13576 	 * Return that we do not want to retry the request for 3 cases:
13577 	 * 1. If we received EINTR or are bailing out because of a forced
13578 	 *    unmount, we came into this code path just for the sake of
13579 	 *    initiating recovery, we now need to return the error.
13580 	 * 2. If we have aborted recovery.
13581 	 * 3. We received NFS4ERR_BAD_SEQID.
13582 	 */
13583 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13584 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13585 		retry = FALSE;
13586 
13587 	if (*did_start_fop == TRUE) {
13588 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13589 		    needrecov);
13590 		*did_start_fop = FALSE;
13591 	}
13592 
13593 	if (retry == TRUE) {
13594 		nfs_argop4	*argop;
13595 
13596 		argop = (*argspp)->array;
13597 		ASSERT((*argspp)->array_len == 2);
13598 
13599 		if (argop[1].argop == OP_LOCK)
13600 			nfs4args_lock_free(&argop[1]);
13601 		else if (argop[1].argop == OP_LOCKT)
13602 			nfs4args_lockt_free(&argop[1]);
13603 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13604 		if (!ep->error)
13605 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13606 		*respp = NULL;
13607 		*argspp = NULL;
13608 	}
13609 
13610 	if (lop != NULL) {
13611 		nfs4_end_lock_seqid_sync(lop);
13612 		lock_owner_rele(lop);
13613 	}
13614 
13615 	*lopp = NULL;
13616 
13617 	/* need to free up the reference on osp for lock args */
13618 	if (osp != NULL) {
13619 		open_stream_rele(osp, rp);
13620 		*ospp = NULL;
13621 	}
13622 
13623 	/* need to free up the reference on oop for lock args */
13624 	if (oop != NULL) {
13625 		nfs4_end_open_seqid_sync(oop);
13626 		open_owner_rele(oop);
13627 		*oopp = NULL;
13628 	}
13629 
13630 	return (retry);
13631 }
13632 
13633 /*
13634  * Handles the successful reply from the server for nfs4frlock.
13635  */
13636 static void
13637 nfs4frlock_results_ok(nfs4_lock_call_type_t ctype, int cmd, flock64_t *flk,
13638     vnode_t *vp, int flag, u_offset_t offset,
13639     nfs4_lost_rqst_t *resend_rqstp)
13640 {
13641 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13642 	if ((cmd == F_SETLK || cmd == F_SETLKW) &&
13643 	    (flk->l_type == F_RDLCK || flk->l_type == F_WRLCK)) {
13644 		if (ctype == NFS4_LCK_CTYPE_NORM) {
13645 			flk->l_pid = ttoproc(curthread)->p_pid;
13646 			/*
13647 			 * We do not register lost locks locally in
13648 			 * the 'resend' case since the user/application
13649 			 * doesn't think we have the lock.
13650 			 */
13651 			ASSERT(!resend_rqstp);
13652 			nfs4_register_lock_locally(vp, flk, flag, offset);
13653 		}
13654 	}
13655 }
13656 
13657 /*
13658  * Handle the DENIED reply from the server for nfs4frlock.
13659  * Returns TRUE if we should retry the request; FALSE otherwise.
13660  *
13661  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13662  * COMPOUND4 args/res for calls that need to retry.  Can also
13663  * drop and regrab the r_lkserlock.
13664  */
13665 static bool_t
13666 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13667     LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13668     nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13669     vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13670     nfs4_recov_state_t *recov_statep, int needrecov,
13671     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13672     clock_t *tick_delayp, short *whencep, int *errorp,
13673     nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13674     bool_t *skip_get_err)
13675 {
13676 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13677 
13678 	if (lock_args) {
13679 		nfs4_open_owner_t	*oop = *oopp;
13680 		nfs4_open_stream_t	*osp = *ospp;
13681 		nfs4_lock_owner_t	*lop = *lopp;
13682 		int			intr;
13683 
13684 		/*
13685 		 * Blocking lock needs to sleep and retry from the request.
13686 		 *
13687 		 * Do not block and wait for 'resend' or 'reinstate'
13688 		 * lock requests, just return the error.
13689 		 *
13690 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13691 		 */
13692 		if (cmd == F_SETLKW) {
13693 			rnode4_t *rp = VTOR4(vp);
13694 			nfs_argop4 *argop = (*argspp)->array;
13695 
13696 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13697 
13698 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13699 			    recov_statep, needrecov);
13700 			*did_start_fop = FALSE;
13701 			ASSERT((*argspp)->array_len == 2);
13702 			if (argop[1].argop == OP_LOCK)
13703 				nfs4args_lock_free(&argop[1]);
13704 			else if (argop[1].argop == OP_LOCKT)
13705 				nfs4args_lockt_free(&argop[1]);
13706 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13707 			if (*respp)
13708 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13709 				    (caddr_t)*respp);
13710 			*argspp = NULL;
13711 			*respp = NULL;
13712 			nfs4_end_lock_seqid_sync(lop);
13713 			lock_owner_rele(lop);
13714 			*lopp = NULL;
13715 			if (osp != NULL) {
13716 				open_stream_rele(osp, rp);
13717 				*ospp = NULL;
13718 			}
13719 			if (oop != NULL) {
13720 				nfs4_end_open_seqid_sync(oop);
13721 				open_owner_rele(oop);
13722 				*oopp = NULL;
13723 			}
13724 
13725 			nfs_rw_exit(&rp->r_lkserlock);
13726 
13727 			intr = nfs4_block_and_wait(tick_delayp, rp);
13728 
13729 			if (intr) {
13730 				(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13731 				    RW_WRITER, FALSE);
13732 				*errorp = EINTR;
13733 				return (FALSE);
13734 			}
13735 
13736 			(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13737 			    RW_WRITER, FALSE);
13738 
13739 			/*
13740 			 * Make sure we are still safe to lock with
13741 			 * regards to mmapping.
13742 			 */
13743 			if (!nfs4_safelock(vp, flk, cr)) {
13744 				*errorp = EAGAIN;
13745 				return (FALSE);
13746 			}
13747 
13748 			return (TRUE);
13749 		}
13750 		if (ctype == NFS4_LCK_CTYPE_NORM)
13751 			*errorp = EAGAIN;
13752 		*skip_get_err = TRUE;
13753 		flk->l_whence = 0;
13754 		*whencep = 0;
13755 		return (FALSE);
13756 	} else if (lockt_args) {
13757 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13758 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
13759 
13760 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
13761 		    flk, lockt_args);
13762 
13763 		/* according to NLM code */
13764 		*errorp = 0;
13765 		*whencep = 0;
13766 		*skip_get_err = TRUE;
13767 		return (FALSE);
13768 	}
13769 	return (FALSE);
13770 }
13771 
13772 /*
13773  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
13774  */
13775 static void
13776 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
13777 {
13778 	switch (resp->status) {
13779 	case NFS4ERR_ACCESS:
13780 	case NFS4ERR_ADMIN_REVOKED:
13781 	case NFS4ERR_BADHANDLE:
13782 	case NFS4ERR_BAD_RANGE:
13783 	case NFS4ERR_BAD_SEQID:
13784 	case NFS4ERR_BAD_STATEID:
13785 	case NFS4ERR_BADXDR:
13786 	case NFS4ERR_DEADLOCK:
13787 	case NFS4ERR_DELAY:
13788 	case NFS4ERR_EXPIRED:
13789 	case NFS4ERR_FHEXPIRED:
13790 	case NFS4ERR_GRACE:
13791 	case NFS4ERR_INVAL:
13792 	case NFS4ERR_ISDIR:
13793 	case NFS4ERR_LEASE_MOVED:
13794 	case NFS4ERR_LOCK_NOTSUPP:
13795 	case NFS4ERR_LOCK_RANGE:
13796 	case NFS4ERR_MOVED:
13797 	case NFS4ERR_NOFILEHANDLE:
13798 	case NFS4ERR_NO_GRACE:
13799 	case NFS4ERR_OLD_STATEID:
13800 	case NFS4ERR_OPENMODE:
13801 	case NFS4ERR_RECLAIM_BAD:
13802 	case NFS4ERR_RECLAIM_CONFLICT:
13803 	case NFS4ERR_RESOURCE:
13804 	case NFS4ERR_SERVERFAULT:
13805 	case NFS4ERR_STALE:
13806 	case NFS4ERR_STALE_CLIENTID:
13807 	case NFS4ERR_STALE_STATEID:
13808 		return;
13809 	default:
13810 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13811 		    "nfs4frlock_results_default: got unrecognizable "
13812 		    "res.status %d", resp->status));
13813 		*errorp = NFS4ERR_INVAL;
13814 	}
13815 }
13816 
13817 /*
13818  * The lock request was successful, so update the client's state.
13819  */
13820 static void
13821 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
13822     LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
13823     vnode_t *vp, flock64_t *flk, cred_t *cr,
13824     nfs4_lost_rqst_t *resend_rqstp)
13825 {
13826 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13827 
13828 	if (lock_args) {
13829 		LOCK4res *lock_res;
13830 
13831 		lock_res = &resop->nfs_resop4_u.oplock;
13832 		/* update the stateid with server's response */
13833 
13834 		if (lock_args->locker.new_lock_owner == TRUE) {
13835 			mutex_enter(&lop->lo_lock);
13836 			lop->lo_just_created = NFS4_PERM_CREATED;
13837 			mutex_exit(&lop->lo_lock);
13838 		}
13839 
13840 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
13841 
13842 		/*
13843 		 * If the lock was the result of a resending a lost
13844 		 * request, we've synched up the stateid and seqid
13845 		 * with the server, but now the server might be out of sync
13846 		 * with what the application thinks it has for locks.
13847 		 * Clean that up here.  It's unclear whether we should do
13848 		 * this even if the filesystem has been forcibly unmounted.
13849 		 * For most servers, it's probably wasted effort, but
13850 		 * RFC3530 lets servers require that unlocks exactly match
13851 		 * the locks that are held.
13852 		 */
13853 		if (resend_rqstp != NULL &&
13854 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
13855 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
13856 		} else {
13857 			flk->l_whence = 0;
13858 		}
13859 	} else if (locku_args) {
13860 		LOCKU4res *locku_res;
13861 
13862 		locku_res = &resop->nfs_resop4_u.oplocku;
13863 
13864 		/* Update the stateid with the server's response */
13865 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
13866 	} else if (lockt_args) {
13867 		/* Switch the lock type to express success, see fcntl */
13868 		flk->l_type = F_UNLCK;
13869 		flk->l_whence = 0;
13870 	}
13871 }
13872 
13873 /*
13874  * Do final cleanup before exiting nfs4frlock.
13875  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13876  * COMPOUND4 args/res for calls that haven't already.
13877  */
13878 static void
13879 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
13880     COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
13881     nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
13882     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13883     short whence, u_offset_t offset, struct lm_sysid *ls,
13884     int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
13885     bool_t did_start_fop, bool_t skip_get_err,
13886     cred_t *cred_otw, cred_t *cred)
13887 {
13888 	mntinfo4_t	*mi = VTOMI4(vp);
13889 	rnode4_t	*rp = VTOR4(vp);
13890 	int		error = *errorp;
13891 	nfs_argop4	*argop;
13892 
13893 	ASSERT(nfs_zone() == mi->mi_zone);
13894 	/*
13895 	 * The client recovery code wants the raw status information,
13896 	 * so don't map the NFS status code to an errno value for
13897 	 * non-normal call types.
13898 	 */
13899 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13900 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
13901 			*errorp = geterrno4(resp->status);
13902 		if (did_start_fop == TRUE)
13903 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
13904 			    needrecov);
13905 
13906 		/*
13907 		 * We've established a new lock on the server, so invalidate
13908 		 * the pages associated with the vnode to get the most up to
13909 		 * date pages from the server after acquiring the lock. We
13910 		 * want to be sure that the read operation gets the newest data.
13911 		 * N.B.
13912 		 * We used to do this in nfs4frlock_results_ok but that doesn't
13913 		 * work since VOP_PUTPAGE can call nfs4_commit which calls
13914 		 * nfs4_start_fop. We flush the pages below after calling
13915 		 * nfs4_end_fop above
13916 		 */
13917 		if (!error && resp && resp->status == NFS4_OK) {
13918 			int error;
13919 
13920 			error = VOP_PUTPAGE(vp, (u_offset_t)0,
13921 			    0, B_INVAL, cred, NULL);
13922 
13923 			if (error && (error == ENOSPC || error == EDQUOT)) {
13924 				rnode4_t *rp = VTOR4(vp);
13925 
13926 				mutex_enter(&rp->r_statelock);
13927 				if (!rp->r_error)
13928 					rp->r_error = error;
13929 				mutex_exit(&rp->r_statelock);
13930 			}
13931 		}
13932 	}
13933 	if (argsp) {
13934 		ASSERT(argsp->array_len == 2);
13935 		argop = argsp->array;
13936 		if (argop[1].argop == OP_LOCK)
13937 			nfs4args_lock_free(&argop[1]);
13938 		else if (argop[1].argop == OP_LOCKT)
13939 			nfs4args_lockt_free(&argop[1]);
13940 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13941 		if (resp)
13942 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
13943 	}
13944 
13945 	/* free the reference on the lock owner */
13946 	if (lop != NULL) {
13947 		nfs4_end_lock_seqid_sync(lop);
13948 		lock_owner_rele(lop);
13949 	}
13950 
13951 	/* need to free up the reference on osp for lock args */
13952 	if (osp != NULL)
13953 		open_stream_rele(osp, rp);
13954 
13955 	/* need to free up the reference on oop for lock args */
13956 	if (oop != NULL) {
13957 		nfs4_end_open_seqid_sync(oop);
13958 		open_owner_rele(oop);
13959 	}
13960 
13961 	(void) convoff(vp, flk, whence, offset);
13962 
13963 	lm_rel_sysid(ls);
13964 
13965 	/*
13966 	 * Record debug information in the event we get EINVAL.
13967 	 */
13968 	mutex_enter(&mi->mi_lock);
13969 	if (*errorp == EINVAL && (lock_args || locku_args) &&
13970 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
13971 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
13972 			zcmn_err(getzoneid(), CE_NOTE,
13973 			    "%s operation failed with "
13974 			    "EINVAL probably since the server, %s,"
13975 			    " doesn't support POSIX style locking",
13976 			    lock_args ? "LOCK" : "LOCKU",
13977 			    mi->mi_curr_serv->sv_hostname);
13978 			mi->mi_flags |= MI4_LOCK_DEBUG;
13979 		}
13980 	}
13981 	mutex_exit(&mi->mi_lock);
13982 
13983 	if (cred_otw)
13984 		crfree(cred_otw);
13985 }
13986 
13987 /*
13988  * This calls the server and the local locking code.
13989  *
13990  * Client locks are registerred locally by oring the sysid with
13991  * LM_SYSID_CLIENT. The server registers locks locally using just the sysid.
13992  * We need to distinguish between the two to avoid collision in case one
13993  * machine is used as both client and server.
13994  *
13995  * Blocking lock requests will continually retry to acquire the lock
13996  * forever.
13997  *
13998  * The ctype is defined as follows:
13999  * NFS4_LCK_CTYPE_NORM: normal lock request.
14000  *
14001  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
14002  * recovery, get the pid from flk instead of curproc, and don't reregister
14003  * the lock locally.
14004  *
14005  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
14006  * that we will use the information passed in via resend_rqstp to setup the
14007  * lock/locku request.  This resend is the exact same request as the 'lost
14008  * lock', and is initiated by the recovery framework. A successful resend
14009  * request can initiate one or more reinstate requests.
14010  *
14011  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14012  * does not trigger additional reinstate requests.  This lock call type is
14013  * set for setting the v4 server's locking state back to match what the
14014  * client's local locking state is in the event of a received 'lost lock'.
14015  *
14016  * Errors are returned via the nfs4_error_t parameter.
14017  */
14018 void
14019 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14020     int flag, u_offset_t offset, cred_t *cr, nfs4_error_t *ep,
14021     nfs4_lost_rqst_t *resend_rqstp, int *did_reclaimp)
14022 {
14023 	COMPOUND4args_clnt	args, *argsp = NULL;
14024 	COMPOUND4res_clnt	res, *resp = NULL;
14025 	nfs_argop4	*argop;
14026 	nfs_resop4	*resop;
14027 	rnode4_t	*rp;
14028 	int		doqueue = 1;
14029 	clock_t		tick_delay;  /* delay in clock ticks */
14030 	struct lm_sysid	*ls;
14031 	LOCK4args	*lock_args = NULL;
14032 	LOCKU4args	*locku_args = NULL;
14033 	LOCKT4args	*lockt_args = NULL;
14034 	nfs4_open_owner_t *oop = NULL;
14035 	nfs4_open_stream_t *osp = NULL;
14036 	nfs4_lock_owner_t *lop = NULL;
14037 	bool_t		needrecov = FALSE;
14038 	nfs4_recov_state_t recov_state;
14039 	short		whence;
14040 	nfs4_op_hint_t	op_hint;
14041 	nfs4_lost_rqst_t lost_rqst;
14042 	bool_t		retry = FALSE;
14043 	bool_t		did_start_fop = FALSE;
14044 	bool_t		skip_get_err = FALSE;
14045 	cred_t		*cred_otw = NULL;
14046 	bool_t		recovonly;	/* just queue request */
14047 	int		frc_no_reclaim = 0;
14048 #ifdef DEBUG
14049 	char *name;
14050 #endif
14051 
14052 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14053 
14054 #ifdef DEBUG
14055 	name = fn_name(VTOSV(vp)->sv_name);
14056 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14057 	    "%s: cmd %d, type %d, offset %llu, start %"PRIx64", "
14058 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14059 	    "resend request %s", name, cmd, flk->l_type, offset, flk->l_start,
14060 	    flk->l_len, ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid :
14061 	    flk->l_pid, flk->l_sysid, nfs4frlock_get_call_type(ctype),
14062 	    resend_rqstp ? "TRUE" : "FALSE"));
14063 	kmem_free(name, MAXNAMELEN);
14064 #endif
14065 
14066 	nfs4_error_zinit(ep);
14067 	ep->error = nfs4frlock_validate_args(cmd, flk, flag, vp, offset);
14068 	if (ep->error)
14069 		return;
14070 	ep->error = nfs4frlock_get_sysid(&ls, vp, flk);
14071 	if (ep->error)
14072 		return;
14073 	nfs4frlock_pre_setup(&tick_delay, &recov_state, flk, &whence,
14074 	    vp, cr, &cred_otw);
14075 
14076 recov_retry:
14077 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14078 	    &retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14079 	rp = VTOR4(vp);
14080 
14081 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14082 	    &did_start_fop, &recovonly);
14083 
14084 	if (ep->error)
14085 		goto out;
14086 
14087 	if (recovonly) {
14088 		/*
14089 		 * Leave the request for the recovery system to deal with.
14090 		 */
14091 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14092 		ASSERT(cmd != F_GETLK);
14093 		ASSERT(flk->l_type == F_UNLCK);
14094 
14095 		nfs4_error_init(ep, EINTR);
14096 		needrecov = TRUE;
14097 		lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14098 		if (lop != NULL) {
14099 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14100 			    NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14101 			(void) nfs4_start_recovery(ep,
14102 			    VTOMI4(vp), vp, NULL, NULL,
14103 			    (lost_rqst.lr_op == OP_LOCK ||
14104 			    lost_rqst.lr_op == OP_LOCKU) ?
14105 			    &lost_rqst : NULL, OP_LOCKU, NULL);
14106 			lock_owner_rele(lop);
14107 			lop = NULL;
14108 		}
14109 		flk->l_pid = curproc->p_pid;
14110 		nfs4_register_lock_locally(vp, flk, flag, offset);
14111 		goto out;
14112 	}
14113 
14114 	/* putfh directory fh */
14115 	argop[0].argop = OP_CPUTFH;
14116 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14117 
14118 	/*
14119 	 * Set up the over-the-wire arguments and get references to the
14120 	 * open owner, etc.
14121 	 */
14122 
14123 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14124 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14125 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14126 		    &argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14127 	} else {
14128 		bool_t go_otw = TRUE;
14129 
14130 		ASSERT(resend_rqstp == NULL);
14131 
14132 		switch (cmd) {
14133 		case F_GETLK:
14134 		case F_O_GETLK:
14135 			nfs4frlock_setup_lockt_args(ctype, &argop[1],
14136 			    &lockt_args, argsp, flk, rp);
14137 			break;
14138 		case F_SETLKW:
14139 		case F_SETLK:
14140 			if (flk->l_type == F_UNLCK)
14141 				nfs4frlock_setup_locku_args(ctype,
14142 				    &argop[1], &locku_args, flk,
14143 				    &lop, ep, argsp,
14144 				    vp, flag, offset, cr,
14145 				    &skip_get_err, &go_otw);
14146 			else
14147 				nfs4frlock_setup_lock_args(ctype,
14148 				    &lock_args, &oop, &osp, &lop, &argop[1],
14149 				    argsp, flk, cmd, vp, cr, ep);
14150 
14151 			if (ep->error)
14152 				goto out;
14153 
14154 			switch (ep->stat) {
14155 			case NFS4_OK:
14156 				break;
14157 			case NFS4ERR_DELAY:
14158 				/* recov thread never gets this error */
14159 				ASSERT(resend_rqstp == NULL);
14160 				ASSERT(did_start_fop);
14161 
14162 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14163 				    &recov_state, TRUE);
14164 				did_start_fop = FALSE;
14165 				if (argop[1].argop == OP_LOCK)
14166 					nfs4args_lock_free(&argop[1]);
14167 				else if (argop[1].argop == OP_LOCKT)
14168 					nfs4args_lockt_free(&argop[1]);
14169 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14170 				argsp = NULL;
14171 				goto recov_retry;
14172 			default:
14173 				ep->error = EIO;
14174 				goto out;
14175 			}
14176 			break;
14177 		default:
14178 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14179 			    "nfs4_frlock: invalid cmd %d", cmd));
14180 			ep->error = EINVAL;
14181 			goto out;
14182 		}
14183 
14184 		if (!go_otw)
14185 			goto out;
14186 	}
14187 
14188 	/* XXX should we use the local reclock as a cache ? */
14189 	/*
14190 	 * Unregister the lock with the local locking code before
14191 	 * contacting the server.  This avoids a potential race where
14192 	 * another process gets notified that it has been granted a lock
14193 	 * before we can unregister ourselves locally.
14194 	 */
14195 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK) {
14196 		if (ctype == NFS4_LCK_CTYPE_NORM)
14197 			flk->l_pid = ttoproc(curthread)->p_pid;
14198 		nfs4_register_lock_locally(vp, flk, flag, offset);
14199 	}
14200 
14201 	/*
14202 	 * Send the server the lock request.  Continually loop with a delay
14203 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14204 	 */
14205 	resp = &res;
14206 
14207 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14208 	    (CE_NOTE,
14209 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14210 	    rnode4info(rp)));
14211 
14212 	if (lock_args && frc_no_reclaim) {
14213 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14214 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14215 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14216 		lock_args->reclaim = FALSE;
14217 		if (did_reclaimp)
14218 			*did_reclaimp = 0;
14219 	}
14220 
14221 	/*
14222 	 * Do the OTW call.
14223 	 */
14224 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14225 
14226 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14227 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14228 
14229 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14230 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14231 	    "nfs4frlock: needrecov %d", needrecov));
14232 
14233 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14234 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14235 		    args.ctag);
14236 
14237 	/*
14238 	 * Check if one of these mutually exclusive error cases has
14239 	 * happened:
14240 	 *   need to swap credentials due to access error
14241 	 *   recovery is needed
14242 	 *   different error (only known case is missing Kerberos ticket)
14243 	 */
14244 
14245 	if ((ep->error == EACCES ||
14246 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14247 	    cred_otw != cr) {
14248 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14249 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14250 		    cr, &cred_otw);
14251 		goto recov_retry;
14252 	}
14253 
14254 	if (needrecov) {
14255 		/*
14256 		 * LOCKT requests don't need to recover from lost
14257 		 * requests since they don't create/modify state.
14258 		 */
14259 		if ((ep->error == EINTR ||
14260 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14261 		    lockt_args)
14262 			goto out;
14263 		/*
14264 		 * Do not attempt recovery for requests initiated by
14265 		 * the recovery framework.  Let the framework redrive them.
14266 		 */
14267 		if (ctype != NFS4_LCK_CTYPE_NORM)
14268 			goto out;
14269 		else {
14270 			ASSERT(resend_rqstp == NULL);
14271 		}
14272 
14273 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14274 		    flk_to_locktype(cmd, flk->l_type),
14275 		    oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14276 
14277 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14278 		    &resp, lock_args, locku_args, &oop, &osp, &lop,
14279 		    rp, vp, &recov_state, op_hint, &did_start_fop,
14280 		    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14281 
14282 		if (retry) {
14283 			ASSERT(oop == NULL);
14284 			ASSERT(osp == NULL);
14285 			ASSERT(lop == NULL);
14286 			goto recov_retry;
14287 		}
14288 		goto out;
14289 	}
14290 
14291 	/*
14292 	 * Bail out if have reached this point with ep->error set. Can
14293 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14294 	 * This happens if Kerberos ticket has expired or has been
14295 	 * destroyed.
14296 	 */
14297 	if (ep->error != 0)
14298 		goto out;
14299 
14300 	/*
14301 	 * Process the reply.
14302 	 */
14303 	switch (resp->status) {
14304 	case NFS4_OK:
14305 		resop = &resp->array[1];
14306 		nfs4frlock_results_ok(ctype, cmd, flk, vp, flag, offset,
14307 		    resend_rqstp);
14308 		/*
14309 		 * Have a successful lock operation, now update state.
14310 		 */
14311 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14312 		    resop, lop, vp, flk, cr, resend_rqstp);
14313 		break;
14314 
14315 	case NFS4ERR_DENIED:
14316 		resop = &resp->array[1];
14317 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14318 		    &oop, &osp, &lop, cmd, vp, flk, op_hint,
14319 		    &recov_state, needrecov, &argsp, &resp,
14320 		    &tick_delay, &whence, &ep->error, resop, cr,
14321 		    &did_start_fop, &skip_get_err);
14322 
14323 		if (retry) {
14324 			ASSERT(oop == NULL);
14325 			ASSERT(osp == NULL);
14326 			ASSERT(lop == NULL);
14327 			goto recov_retry;
14328 		}
14329 		break;
14330 	/*
14331 	 * If the server won't let us reclaim, fall-back to trying to lock
14332 	 * the file from scratch. Code elsewhere will check the changeinfo
14333 	 * to ensure the file hasn't been changed.
14334 	 */
14335 	case NFS4ERR_NO_GRACE:
14336 		if (lock_args && lock_args->reclaim == TRUE) {
14337 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14338 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14339 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14340 			frc_no_reclaim = 1;
14341 			/* clean up before retrying */
14342 			needrecov = 0;
14343 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14344 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14345 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14346 			goto recov_retry;
14347 		}
14348 		/* FALLTHROUGH */
14349 
14350 	default:
14351 		nfs4frlock_results_default(resp, &ep->error);
14352 		break;
14353 	}
14354 out:
14355 	/*
14356 	 * Process and cleanup from error.  Make interrupted unlock
14357 	 * requests look successful, since they will be handled by the
14358 	 * client recovery code.
14359 	 */
14360 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14361 	    needrecov, oop, osp, lop, flk, whence, offset, ls, &ep->error,
14362 	    lock_args, locku_args, did_start_fop,
14363 	    skip_get_err, cred_otw, cr);
14364 
14365 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14366 	    (cmd == F_SETLK || cmd == F_SETLKW))
14367 		ep->error = 0;
14368 }
14369 
14370 /*
14371  * nfs4_safelock:
14372  *
14373  * Return non-zero if the given lock request can be handled without
14374  * violating the constraints on concurrent mapping and locking.
14375  */
14376 
14377 static int
14378 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14379 {
14380 	rnode4_t *rp = VTOR4(vp);
14381 	struct vattr va;
14382 	int error;
14383 
14384 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14385 	ASSERT(rp->r_mapcnt >= 0);
14386 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14387 	    "(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14388 	    "write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14389 	    bfp->l_start, bfp->l_len, rp->r_mapcnt));
14390 
14391 	if (rp->r_mapcnt == 0)
14392 		return (1);		/* always safe if not mapped */
14393 
14394 	/*
14395 	 * If the file is already mapped and there are locks, then they
14396 	 * should be all safe locks.  So adding or removing a lock is safe
14397 	 * as long as the new request is safe (i.e., whole-file, meaning
14398 	 * length and starting offset are both zero).
14399 	 */
14400 
14401 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14402 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14403 		    "cannot lock a memory mapped file unless locking the "
14404 		    "entire file: start %"PRIx64", len %"PRIx64,
14405 		    bfp->l_start, bfp->l_len));
14406 		return (0);
14407 	}
14408 
14409 	/* mandatory locking and mapping don't mix */
14410 	va.va_mask = AT_MODE;
14411 	error = VOP_GETATTR(vp, &va, 0, cr, NULL);
14412 	if (error != 0) {
14413 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14414 		    "getattr error %d", error));
14415 		return (0);		/* treat errors conservatively */
14416 	}
14417 	if (MANDLOCK(vp, va.va_mode)) {
14418 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14419 		    "cannot mandatory lock and mmap a file"));
14420 		return (0);
14421 	}
14422 
14423 	return (1);
14424 }
14425 
14426 
14427 /*
14428  * Register the lock locally within Solaris.
14429  * As the client, we "or" the sysid with LM_SYSID_CLIENT when
14430  * recording locks locally.
14431  *
14432  * This should handle conflicts/cooperation with NFS v2/v3 since all locks
14433  * are registered locally.
14434  */
14435 void
14436 nfs4_register_lock_locally(vnode_t *vp, struct flock64 *flk, int flag,
14437     u_offset_t offset)
14438 {
14439 	int oldsysid;
14440 	int error;
14441 #ifdef DEBUG
14442 	char *name;
14443 #endif
14444 
14445 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14446 
14447 #ifdef DEBUG
14448 	name = fn_name(VTOSV(vp)->sv_name);
14449 	NFS4_DEBUG(nfs4_client_lock_debug,
14450 	    (CE_NOTE, "nfs4_register_lock_locally: %s: type %d, "
14451 	    "start %"PRIx64", length %"PRIx64", pid %ld, sysid %d",
14452 	    name, flk->l_type, flk->l_start, flk->l_len, (long)flk->l_pid,
14453 	    flk->l_sysid));
14454 	kmem_free(name, MAXNAMELEN);
14455 #endif
14456 
14457 	/* register the lock with local locking */
14458 	oldsysid = flk->l_sysid;
14459 	flk->l_sysid |= LM_SYSID_CLIENT;
14460 	error = reclock(vp, flk, SETFLCK, flag, offset, NULL);
14461 #ifdef DEBUG
14462 	if (error != 0) {
14463 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14464 		    "nfs4_register_lock_locally: could not register with"
14465 		    " local locking"));
14466 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14467 		    "error %d, vp 0x%p, pid %d, sysid 0x%x",
14468 		    error, (void *)vp, flk->l_pid, flk->l_sysid));
14469 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14470 		    "type %d off 0x%" PRIx64 " len 0x%" PRIx64,
14471 		    flk->l_type, flk->l_start, flk->l_len));
14472 		(void) reclock(vp, flk, 0, flag, offset, NULL);
14473 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14474 		    "blocked by pid %d sysid 0x%x type %d "
14475 		    "off 0x%" PRIx64 " len 0x%" PRIx64,
14476 		    flk->l_pid, flk->l_sysid, flk->l_type, flk->l_start,
14477 		    flk->l_len));
14478 	}
14479 #endif
14480 	flk->l_sysid = oldsysid;
14481 }
14482 
14483 /*
14484  * nfs4_lockrelease:
14485  *
14486  * Release any locks on the given vnode that are held by the current
14487  * process.  Also removes the lock owner (if one exists) from the rnode's
14488  * list.
14489  */
14490 static int
14491 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14492 {
14493 	flock64_t ld;
14494 	int ret, error;
14495 	rnode4_t *rp;
14496 	nfs4_lock_owner_t *lop;
14497 	nfs4_recov_state_t recov_state;
14498 	mntinfo4_t *mi;
14499 	bool_t possible_orphan = FALSE;
14500 	bool_t recovonly;
14501 
14502 	ASSERT((uintptr_t)vp > KERNELBASE);
14503 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14504 
14505 	rp = VTOR4(vp);
14506 	mi = VTOMI4(vp);
14507 
14508 	/*
14509 	 * If we have not locked anything then we can
14510 	 * just return since we have no work to do.
14511 	 */
14512 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14513 		return (0);
14514 	}
14515 
14516 	/*
14517 	 * We need to comprehend that another thread may
14518 	 * kick off recovery and the lock_owner we have stashed
14519 	 * in lop might be invalid so we should NOT cache it
14520 	 * locally!
14521 	 */
14522 	recov_state.rs_flags = 0;
14523 	recov_state.rs_num_retry_despite_err = 0;
14524 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14525 	    &recovonly);
14526 	if (error) {
14527 		mutex_enter(&rp->r_statelock);
14528 		rp->r_flags |= R4LODANGLERS;
14529 		mutex_exit(&rp->r_statelock);
14530 		return (error);
14531 	}
14532 
14533 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14534 
14535 	/*
14536 	 * Check if the lock owner might have a lock (request was sent but
14537 	 * no response was received).  Also check if there are any remote
14538 	 * locks on the file.  (In theory we shouldn't have to make this
14539 	 * second check if there's no lock owner, but for now we'll be
14540 	 * conservative and do it anyway.)  If either condition is true,
14541 	 * send an unlock for the entire file to the server.
14542 	 *
14543 	 * Note that no explicit synchronization is needed here.  At worst,
14544 	 * flk_has_remote_locks() will return a false positive, in which case
14545 	 * the unlock call wastes time but doesn't harm correctness.
14546 	 */
14547 
14548 	if (lop) {
14549 		mutex_enter(&lop->lo_lock);
14550 		possible_orphan = lop->lo_pending_rqsts;
14551 		mutex_exit(&lop->lo_lock);
14552 		lock_owner_rele(lop);
14553 	}
14554 
14555 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14556 
14557 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14558 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14559 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14560 	    (void *)lop));
14561 
14562 	if (possible_orphan || flk_has_remote_locks(vp)) {
14563 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14564 		ld.l_whence = 0;	/* unlock from start of file */
14565 		ld.l_start = 0;
14566 		ld.l_len = 0;		/* do entire file */
14567 
14568 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL,
14569 		    cr, NULL);
14570 
14571 		if (ret != 0) {
14572 			/*
14573 			 * If VOP_FRLOCK fails, make sure we unregister
14574 			 * local locks before we continue.
14575 			 */
14576 			ld.l_pid = ttoproc(curthread)->p_pid;
14577 			nfs4_register_lock_locally(vp, &ld, flag, offset);
14578 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14579 			    "nfs4_lockrelease: lock release error on vp"
14580 			    " %p: error %d.\n", (void *)vp, ret));
14581 		}
14582 	}
14583 
14584 	recov_state.rs_flags = 0;
14585 	recov_state.rs_num_retry_despite_err = 0;
14586 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14587 	    &recovonly);
14588 	if (error) {
14589 		mutex_enter(&rp->r_statelock);
14590 		rp->r_flags |= R4LODANGLERS;
14591 		mutex_exit(&rp->r_statelock);
14592 		return (error);
14593 	}
14594 
14595 	/*
14596 	 * So, here we're going to need to retrieve the lock-owner
14597 	 * again (in case recovery has done a switch-a-roo) and
14598 	 * remove it because we can.
14599 	 */
14600 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14601 
14602 	if (lop) {
14603 		nfs4_rnode_remove_lock_owner(rp, lop);
14604 		lock_owner_rele(lop);
14605 	}
14606 
14607 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14608 	return (0);
14609 }
14610 
14611 /*
14612  * Wait for 'tick_delay' clock ticks.
14613  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14614  * NOTE: lock_lease_time is in seconds.
14615  *
14616  * XXX For future improvements, should implement a waiting queue scheme.
14617  */
14618 static int
14619 nfs4_block_and_wait(clock_t *tick_delay, rnode4_t *rp)
14620 {
14621 	long milliseconds_delay;
14622 	time_t lock_lease_time;
14623 
14624 	/* wait tick_delay clock ticks or siginteruptus */
14625 	if (delay_sig(*tick_delay)) {
14626 		return (EINTR);
14627 	}
14628 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14629 	    "reissue the lock request: blocked for %ld clock ticks: %ld "
14630 	    "milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14631 
14632 	/* get the lease time */
14633 	lock_lease_time = r2lease_time(rp);
14634 
14635 	/* drv_hztousec converts ticks to microseconds */
14636 	milliseconds_delay = drv_hztousec(*tick_delay) / 1000;
14637 	if (milliseconds_delay < lock_lease_time * 1000) {
14638 		*tick_delay = 2 * *tick_delay;
14639 		if (drv_hztousec(*tick_delay) > lock_lease_time * 1000 * 1000)
14640 			*tick_delay = drv_usectohz(lock_lease_time*1000*1000);
14641 	}
14642 	return (0);
14643 }
14644 
14645 
14646 void
14647 nfs4_vnops_init(void)
14648 {
14649 }
14650 
14651 void
14652 nfs4_vnops_fini(void)
14653 {
14654 }
14655 
14656 /*
14657  * Return a reference to the directory (parent) vnode for a given vnode,
14658  * using the saved pathname information and the directory file handle.  The
14659  * caller is responsible for disposing of the reference.
14660  * Returns zero or an errno value.
14661  *
14662  * Caller should set need_start_op to FALSE if it is the recovery
14663  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14664  */
14665 int
14666 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14667 {
14668 	svnode_t *svnp;
14669 	vnode_t *dvp = NULL;
14670 	servinfo4_t *svp;
14671 	nfs4_fname_t *mfname;
14672 	int error;
14673 
14674 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14675 
14676 	if (vp->v_flag & VROOT) {
14677 		nfs4_sharedfh_t *sfh;
14678 		nfs_fh4 fh;
14679 		mntinfo4_t *mi;
14680 
14681 		ASSERT(vp->v_type == VREG);
14682 
14683 		mi = VTOMI4(vp);
14684 		svp = mi->mi_curr_serv;
14685 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14686 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14687 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14688 		sfh = sfh4_get(&fh, VTOMI4(vp));
14689 		nfs_rw_exit(&svp->sv_lock);
14690 		mfname = mi->mi_fname;
14691 		fn_hold(mfname);
14692 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14693 		sfh4_rele(&sfh);
14694 
14695 		if (dvp->v_type == VNON)
14696 			dvp->v_type = VDIR;
14697 		*dvpp = dvp;
14698 		return (0);
14699 	}
14700 
14701 	svnp = VTOSV(vp);
14702 
14703 	if (svnp == NULL) {
14704 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14705 		    "shadow node is NULL"));
14706 		return (EINVAL);
14707 	}
14708 
14709 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14710 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14711 		    "shadow node name or dfh val == NULL"));
14712 		return (EINVAL);
14713 	}
14714 
14715 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14716 	    (int)need_start_op);
14717 	if (error != 0) {
14718 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14719 		    "nfs4_make_dotdot returned %d", error));
14720 		return (error);
14721 	}
14722 	if (!dvp) {
14723 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14724 		    "nfs4_make_dotdot returned a NULL dvp"));
14725 		return (EIO);
14726 	}
14727 	if (dvp->v_type == VNON)
14728 		dvp->v_type = VDIR;
14729 	ASSERT(dvp->v_type == VDIR);
14730 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14731 		mutex_enter(&dvp->v_lock);
14732 		dvp->v_flag |= V_XATTRDIR;
14733 		mutex_exit(&dvp->v_lock);
14734 	}
14735 	*dvpp = dvp;
14736 	return (0);
14737 }
14738 
14739 /*
14740  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14741  * length that fnamep can accept, including the trailing null.
14742  * Returns 0 if okay, returns an errno value if there was a problem.
14743  */
14744 
14745 int
14746 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14747 {
14748 	char *fn;
14749 	int err = 0;
14750 	servinfo4_t *svp;
14751 	svnode_t *shvp;
14752 
14753 	/*
14754 	 * If the file being opened has VROOT set, then this is
14755 	 * a "file" mount.  sv_name will not be interesting, so
14756 	 * go back to the servinfo4 to get the original mount
14757 	 * path and strip off all but the final edge.  Otherwise
14758 	 * just return the name from the shadow vnode.
14759 	 */
14760 
14761 	if (vp->v_flag & VROOT) {
14762 
14763 		svp = VTOMI4(vp)->mi_curr_serv;
14764 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14765 
14766 		fn = strrchr(svp->sv_path, '/');
14767 		if (fn == NULL)
14768 			err = EINVAL;
14769 		else
14770 			fn++;
14771 	} else {
14772 		shvp = VTOSV(vp);
14773 		fn = fn_name(shvp->sv_name);
14774 	}
14775 
14776 	if (err == 0)
14777 		if (strlen(fn) < maxlen)
14778 			(void) strcpy(fnamep, fn);
14779 		else
14780 			err = ENAMETOOLONG;
14781 
14782 	if (vp->v_flag & VROOT)
14783 		nfs_rw_exit(&svp->sv_lock);
14784 	else
14785 		kmem_free(fn, MAXNAMELEN);
14786 
14787 	return (err);
14788 }
14789 
14790 /*
14791  * Bookkeeping for a close that doesn't need to go over the wire.
14792  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14793  * it is left at 1.
14794  */
14795 void
14796 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14797 {
14798 	rnode4_t		*rp;
14799 	mntinfo4_t		*mi;
14800 
14801 	mi = VTOMI4(vp);
14802 	rp = VTOR4(vp);
14803 
14804 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14805 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14806 	ASSERT(nfs_zone() == mi->mi_zone);
14807 	ASSERT(mutex_owned(&osp->os_sync_lock));
14808 	ASSERT(*have_lockp);
14809 
14810 	if (!osp->os_valid ||
14811 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14812 		return;
14813 	}
14814 
14815 	/*
14816 	 * This removes the reference obtained at OPEN; ie,
14817 	 * when the open stream structure was created.
14818 	 *
14819 	 * We don't have to worry about calling 'open_stream_rele'
14820 	 * since we our currently holding a reference to this
14821 	 * open stream which means the count can not go to 0 with
14822 	 * this decrement.
14823 	 */
14824 	ASSERT(osp->os_ref_count >= 2);
14825 	osp->os_ref_count--;
14826 	osp->os_valid = 0;
14827 	mutex_exit(&osp->os_sync_lock);
14828 	*have_lockp = 0;
14829 
14830 	nfs4_dec_state_ref_count(mi);
14831 }
14832 
14833 /*
14834  * Close all remaining open streams on the rnode.  These open streams
14835  * could be here because:
14836  * - The close attempted at either close or delmap failed
14837  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
14838  * - Someone did mknod on a regular file but never opened it
14839  */
14840 int
14841 nfs4close_all(vnode_t *vp, cred_t *cr)
14842 {
14843 	nfs4_open_stream_t *osp;
14844 	int error;
14845 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
14846 	rnode4_t *rp;
14847 
14848 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14849 
14850 	error = 0;
14851 	rp = VTOR4(vp);
14852 
14853 	/*
14854 	 * At this point, all we know is that the last time
14855 	 * someone called vn_rele, the count was 1.  Since then,
14856 	 * the vnode could have been re-activated.  We want to
14857 	 * loop through the open streams and close each one, but
14858 	 * we have to be careful since once we release the rnode
14859 	 * hash bucket lock, someone else is free to come in and
14860 	 * re-activate the rnode and add new open streams.  The
14861 	 * strategy is take the rnode hash bucket lock, verify that
14862 	 * the count is still 1, grab the open stream off the
14863 	 * head of the list and mark it invalid, then release the
14864 	 * rnode hash bucket lock and proceed with that open stream.
14865 	 * This is ok because nfs4close_one() will acquire the proper
14866 	 * open/create to close/destroy synchronization for open
14867 	 * streams, and will ensure that if someone has reopened
14868 	 * the open stream after we've dropped the hash bucket lock
14869 	 * then we'll just simply return without destroying the
14870 	 * open stream.
14871 	 * Repeat until the list is empty.
14872 	 */
14873 
14874 	for (;;) {
14875 
14876 		/* make sure vnode hasn't been reactivated */
14877 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
14878 		mutex_enter(&vp->v_lock);
14879 		if (vp->v_count > 1) {
14880 			mutex_exit(&vp->v_lock);
14881 			rw_exit(&rp->r_hashq->r_lock);
14882 			break;
14883 		}
14884 		/*
14885 		 * Grabbing r_os_lock before releasing v_lock prevents
14886 		 * a window where the rnode/open stream could get
14887 		 * reactivated (and os_force_close set to 0) before we
14888 		 * had a chance to set os_force_close to 1.
14889 		 */
14890 		mutex_enter(&rp->r_os_lock);
14891 		mutex_exit(&vp->v_lock);
14892 
14893 		osp = list_head(&rp->r_open_streams);
14894 		if (!osp) {
14895 			/* nothing left to CLOSE OTW, so return */
14896 			mutex_exit(&rp->r_os_lock);
14897 			rw_exit(&rp->r_hashq->r_lock);
14898 			break;
14899 		}
14900 
14901 		mutex_enter(&rp->r_statev4_lock);
14902 		/* the file can't still be mem mapped */
14903 		ASSERT(rp->r_mapcnt == 0);
14904 		if (rp->created_v4)
14905 			rp->created_v4 = 0;
14906 		mutex_exit(&rp->r_statev4_lock);
14907 
14908 		/*
14909 		 * Grab a ref on this open stream; nfs4close_one
14910 		 * will mark it as invalid
14911 		 */
14912 		mutex_enter(&osp->os_sync_lock);
14913 		osp->os_ref_count++;
14914 		osp->os_force_close = 1;
14915 		mutex_exit(&osp->os_sync_lock);
14916 		mutex_exit(&rp->r_os_lock);
14917 		rw_exit(&rp->r_hashq->r_lock);
14918 
14919 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
14920 
14921 		/* Update error if it isn't already non-zero */
14922 		if (error == 0) {
14923 			if (e.error)
14924 				error = e.error;
14925 			else if (e.stat)
14926 				error = geterrno4(e.stat);
14927 		}
14928 
14929 #ifdef	DEBUG
14930 		nfs4close_all_cnt++;
14931 #endif
14932 		/* Release the ref on osp acquired above. */
14933 		open_stream_rele(osp, rp);
14934 
14935 		/* Proceed to the next open stream, if any */
14936 	}
14937 	return (error);
14938 }
14939 
14940 /*
14941  * nfs4close_one - close one open stream for a file if needed.
14942  *
14943  * "close_type" indicates which close path this is:
14944  * CLOSE_NORM: close initiated via VOP_CLOSE.
14945  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
14946  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
14947  *	the close and release of client state for this open stream
14948  *	(unless someone else has the open stream open).
14949  * CLOSE_RESEND: indicates the request is a replay of an earlier request
14950  *	(e.g., due to abort because of a signal).
14951  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
14952  *
14953  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
14954  * recovery.  Instead, the caller is expected to deal with retries.
14955  *
14956  * The caller can either pass in the osp ('provided_osp') or not.
14957  *
14958  * 'access_bits' represents the access we are closing/downgrading.
14959  *
14960  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
14961  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
14962  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
14963  *
14964  * Errors are returned via the nfs4_error_t.
14965  */
14966 void
14967 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
14968     int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
14969     nfs4_close_type_t close_type, size_t len, uint_t maxprot,
14970     uint_t mmap_flags)
14971 {
14972 	nfs4_open_owner_t *oop;
14973 	nfs4_open_stream_t *osp = NULL;
14974 	int retry = 0;
14975 	int num_retries = NFS4_NUM_RECOV_RETRIES;
14976 	rnode4_t *rp;
14977 	mntinfo4_t *mi;
14978 	nfs4_recov_state_t recov_state;
14979 	cred_t *cred_otw = NULL;
14980 	bool_t recovonly = FALSE;
14981 	int isrecov;
14982 	int force_close;
14983 	int close_failed = 0;
14984 	int did_dec_count = 0;
14985 	int did_start_op = 0;
14986 	int did_force_recovlock = 0;
14987 	int did_start_seqid_sync = 0;
14988 	int have_sync_lock = 0;
14989 
14990 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14991 
14992 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
14993 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
14994 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
14995 	    len, maxprot, mmap_flags, access_bits));
14996 
14997 	nfs4_error_zinit(ep);
14998 	rp = VTOR4(vp);
14999 	mi = VTOMI4(vp);
15000 	isrecov = (close_type == CLOSE_RESEND ||
15001 	    close_type == CLOSE_AFTER_RESEND);
15002 
15003 	/*
15004 	 * First get the open owner.
15005 	 */
15006 	if (!provided_osp) {
15007 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
15008 	} else {
15009 		oop = provided_osp->os_open_owner;
15010 		ASSERT(oop != NULL);
15011 		open_owner_hold(oop);
15012 	}
15013 
15014 	if (!oop) {
15015 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15016 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15017 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15018 		    (void *)provided_osp, close_type));
15019 		ep->error = EIO;
15020 		goto out;
15021 	}
15022 
15023 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15024 recov_retry:
15025 	osp = NULL;
15026 	close_failed = 0;
15027 	force_close = (close_type == CLOSE_FORCE);
15028 	retry = 0;
15029 	did_start_op = 0;
15030 	did_force_recovlock = 0;
15031 	did_start_seqid_sync = 0;
15032 	have_sync_lock = 0;
15033 	recovonly = FALSE;
15034 	recov_state.rs_flags = 0;
15035 	recov_state.rs_num_retry_despite_err = 0;
15036 
15037 	/*
15038 	 * Second synchronize with recovery.
15039 	 */
15040 	if (!isrecov) {
15041 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15042 		    &recov_state, &recovonly);
15043 		if (!ep->error) {
15044 			did_start_op = 1;
15045 		} else {
15046 			close_failed = 1;
15047 			/*
15048 			 * If we couldn't get start_fop, but have to
15049 			 * cleanup state, then at least acquire the
15050 			 * mi_recovlock so we can synchronize with
15051 			 * recovery.
15052 			 */
15053 			if (close_type == CLOSE_FORCE) {
15054 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15055 				    RW_READER, FALSE);
15056 				did_force_recovlock = 1;
15057 			} else
15058 				goto out;
15059 		}
15060 	}
15061 
15062 	/*
15063 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15064 	 * set 'recovonly' to TRUE since most likely this is due to
15065 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15066 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15067 	 * to retry, causing us to loop until recovery finishes.  Plus we
15068 	 * don't need protection over the open seqid since we're not going
15069 	 * OTW, hence don't need to use the seqid.
15070 	 */
15071 	if (recovonly == FALSE) {
15072 		/* need to grab the open owner sync before 'os_sync_lock' */
15073 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15074 		if (ep->error == EAGAIN) {
15075 			ASSERT(!isrecov);
15076 			if (did_start_op)
15077 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15078 				    &recov_state, TRUE);
15079 			if (did_force_recovlock)
15080 				nfs_rw_exit(&mi->mi_recovlock);
15081 			goto recov_retry;
15082 		}
15083 		did_start_seqid_sync = 1;
15084 	}
15085 
15086 	/*
15087 	 * Third get an open stream and acquire 'os_sync_lock' to
15088 	 * sychronize the opening/creating of an open stream with the
15089 	 * closing/destroying of an open stream.
15090 	 */
15091 	if (!provided_osp) {
15092 		/* returns with 'os_sync_lock' held */
15093 		osp = find_open_stream(oop, rp);
15094 		if (!osp) {
15095 			ep->error = EIO;
15096 			goto out;
15097 		}
15098 	} else {
15099 		osp = provided_osp;
15100 		open_stream_hold(osp);
15101 		mutex_enter(&osp->os_sync_lock);
15102 	}
15103 	have_sync_lock = 1;
15104 
15105 	ASSERT(oop == osp->os_open_owner);
15106 
15107 	/*
15108 	 * Fourth, do any special pre-OTW CLOSE processing
15109 	 * based on the specific close type.
15110 	 */
15111 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15112 	    !did_dec_count) {
15113 		ASSERT(osp->os_open_ref_count > 0);
15114 		osp->os_open_ref_count--;
15115 		did_dec_count = 1;
15116 		if (osp->os_open_ref_count == 0)
15117 			osp->os_final_close = 1;
15118 	}
15119 
15120 	if (close_type == CLOSE_FORCE) {
15121 		/* see if somebody reopened the open stream. */
15122 		if (!osp->os_force_close) {
15123 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15124 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15125 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15126 			ep->error = 0;
15127 			ep->stat = NFS4_OK;
15128 			goto out;
15129 		}
15130 
15131 		if (!osp->os_final_close && !did_dec_count) {
15132 			osp->os_open_ref_count--;
15133 			did_dec_count = 1;
15134 		}
15135 
15136 		/*
15137 		 * We can't depend on os_open_ref_count being 0 due to the
15138 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15139 		 */
15140 #ifdef	NOTYET
15141 		ASSERT(osp->os_open_ref_count == 0);
15142 #endif
15143 		if (osp->os_open_ref_count != 0) {
15144 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15145 			    "nfs4close_one: should panic here on an "
15146 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15147 			    "since this is probably the exec problem."));
15148 
15149 			osp->os_open_ref_count = 0;
15150 		}
15151 
15152 		/*
15153 		 * There is the possibility that nfs4close_one()
15154 		 * for close_type == CLOSE_DELMAP couldn't find the
15155 		 * open stream, thus couldn't decrement its os_mapcnt;
15156 		 * therefore we can't use this ASSERT yet.
15157 		 */
15158 #ifdef	NOTYET
15159 		ASSERT(osp->os_mapcnt == 0);
15160 #endif
15161 		osp->os_mapcnt = 0;
15162 	}
15163 
15164 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15165 		ASSERT(osp->os_mapcnt >= btopr(len));
15166 
15167 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15168 			osp->os_mmap_write -= btopr(len);
15169 		if (maxprot & PROT_READ)
15170 			osp->os_mmap_read -= btopr(len);
15171 		if (maxprot & PROT_EXEC)
15172 			osp->os_mmap_read -= btopr(len);
15173 		/* mirror the PROT_NONE check in nfs4_addmap() */
15174 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15175 		    !(maxprot & PROT_EXEC))
15176 			osp->os_mmap_read -= btopr(len);
15177 		osp->os_mapcnt -= btopr(len);
15178 		did_dec_count = 1;
15179 	}
15180 
15181 	if (recovonly) {
15182 		nfs4_lost_rqst_t lost_rqst;
15183 
15184 		/* request should not already be in recovery queue */
15185 		ASSERT(lrp == NULL);
15186 		nfs4_error_init(ep, EINTR);
15187 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15188 		    osp, cred_otw, vp);
15189 		mutex_exit(&osp->os_sync_lock);
15190 		have_sync_lock = 0;
15191 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15192 		    lost_rqst.lr_op == OP_CLOSE ?
15193 		    &lost_rqst : NULL, OP_CLOSE, NULL);
15194 		close_failed = 1;
15195 		force_close = 0;
15196 		goto close_cleanup;
15197 	}
15198 
15199 	/*
15200 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15201 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15202 	 * space, which means we stopped operating on the open stream
15203 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15204 	 * stateid could be stale, potentially triggering a false
15205 	 * setclientid), and just clean up the client's internal state.
15206 	 */
15207 	if (osp->os_orig_oo_name != oop->oo_name) {
15208 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15209 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15210 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15211 		    "oo_name %" PRIx64")",
15212 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15213 		    oop->oo_name));
15214 		close_failed = 1;
15215 	}
15216 
15217 	/* If the file failed recovery, just quit. */
15218 	mutex_enter(&rp->r_statelock);
15219 	if (rp->r_flags & R4RECOVERR) {
15220 		close_failed = 1;
15221 	}
15222 	mutex_exit(&rp->r_statelock);
15223 
15224 	/*
15225 	 * If the force close path failed to obtain start_fop
15226 	 * then skip the OTW close and just remove the state.
15227 	 */
15228 	if (close_failed)
15229 		goto close_cleanup;
15230 
15231 	/*
15232 	 * Fifth, check to see if there are still mapped pages or other
15233 	 * opens using this open stream.  If there are then we can't
15234 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15235 	 */
15236 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15237 		nfs4_lost_rqst_t	new_lost_rqst;
15238 		bool_t			needrecov = FALSE;
15239 		cred_t			*odg_cred_otw = NULL;
15240 		seqid4			open_dg_seqid = 0;
15241 
15242 		if (osp->os_delegation) {
15243 			/*
15244 			 * If this open stream was never OPENed OTW then we
15245 			 * surely can't DOWNGRADE it (especially since the
15246 			 * osp->open_stateid is really a delegation stateid
15247 			 * when os_delegation is 1).
15248 			 */
15249 			if (access_bits & FREAD)
15250 				osp->os_share_acc_read--;
15251 			if (access_bits & FWRITE)
15252 				osp->os_share_acc_write--;
15253 			osp->os_share_deny_none--;
15254 			nfs4_error_zinit(ep);
15255 			goto out;
15256 		}
15257 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15258 		    lrp, ep, &odg_cred_otw, &open_dg_seqid);
15259 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15260 		if (needrecov && !isrecov) {
15261 			bool_t abort;
15262 			nfs4_bseqid_entry_t *bsep = NULL;
15263 
15264 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15265 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15266 				    vp, 0,
15267 				    lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15268 				    open_dg_seqid);
15269 
15270 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15271 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15272 			mutex_exit(&osp->os_sync_lock);
15273 			have_sync_lock = 0;
15274 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15275 			    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15276 			    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15277 			    bsep);
15278 			if (odg_cred_otw)
15279 				crfree(odg_cred_otw);
15280 			if (bsep)
15281 				kmem_free(bsep, sizeof (*bsep));
15282 
15283 			if (abort == TRUE)
15284 				goto out;
15285 
15286 			if (did_start_seqid_sync) {
15287 				nfs4_end_open_seqid_sync(oop);
15288 				did_start_seqid_sync = 0;
15289 			}
15290 			open_stream_rele(osp, rp);
15291 
15292 			if (did_start_op)
15293 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15294 				    &recov_state, FALSE);
15295 			if (did_force_recovlock)
15296 				nfs_rw_exit(&mi->mi_recovlock);
15297 
15298 			goto recov_retry;
15299 		} else {
15300 			if (odg_cred_otw)
15301 				crfree(odg_cred_otw);
15302 		}
15303 		goto out;
15304 	}
15305 
15306 	/*
15307 	 * If this open stream was created as the results of an open
15308 	 * while holding a delegation, then just release it; no need
15309 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15310 	 */
15311 	if (osp->os_delegation) {
15312 		nfs4close_notw(vp, osp, &have_sync_lock);
15313 		nfs4_error_zinit(ep);
15314 		goto out;
15315 	}
15316 
15317 	/*
15318 	 * If this stream is not valid, we're done.
15319 	 */
15320 	if (!osp->os_valid) {
15321 		nfs4_error_zinit(ep);
15322 		goto out;
15323 	}
15324 
15325 	/*
15326 	 * Last open or mmap ref has vanished, need to do an OTW close.
15327 	 * First check to see if a close is still necessary.
15328 	 */
15329 	if (osp->os_failed_reopen) {
15330 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15331 		    "don't close OTW osp %p since reopen failed.",
15332 		    (void *)osp));
15333 		/*
15334 		 * Reopen of the open stream failed, hence the
15335 		 * stateid of the open stream is invalid/stale, and
15336 		 * sending this OTW would incorrectly cause another
15337 		 * round of recovery.  In this case, we need to set
15338 		 * the 'os_valid' bit to 0 so another thread doesn't
15339 		 * come in and re-open this open stream before
15340 		 * this "closing" thread cleans up state (decrementing
15341 		 * the nfs4_server_t's state_ref_count and decrementing
15342 		 * the os_ref_count).
15343 		 */
15344 		osp->os_valid = 0;
15345 		/*
15346 		 * This removes the reference obtained at OPEN; ie,
15347 		 * when the open stream structure was created.
15348 		 *
15349 		 * We don't have to worry about calling 'open_stream_rele'
15350 		 * since we our currently holding a reference to this
15351 		 * open stream which means the count can not go to 0 with
15352 		 * this decrement.
15353 		 */
15354 		ASSERT(osp->os_ref_count >= 2);
15355 		osp->os_ref_count--;
15356 		nfs4_error_zinit(ep);
15357 		close_failed = 0;
15358 		goto close_cleanup;
15359 	}
15360 
15361 	ASSERT(osp->os_ref_count > 1);
15362 
15363 	/*
15364 	 * Sixth, try the CLOSE OTW.
15365 	 */
15366 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15367 	    close_type, ep, &have_sync_lock);
15368 
15369 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15370 		/*
15371 		 * Let the recovery thread be responsible for
15372 		 * removing the state for CLOSE.
15373 		 */
15374 		close_failed = 1;
15375 		force_close = 0;
15376 		retry = 0;
15377 	}
15378 
15379 	/* See if we need to retry with a different cred */
15380 	if ((ep->error == EACCES ||
15381 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15382 	    cred_otw != cr) {
15383 		crfree(cred_otw);
15384 		cred_otw = cr;
15385 		crhold(cred_otw);
15386 		retry = 1;
15387 	}
15388 
15389 	if (ep->error || ep->stat)
15390 		close_failed = 1;
15391 
15392 	if (retry && !isrecov && num_retries-- > 0) {
15393 		if (have_sync_lock) {
15394 			mutex_exit(&osp->os_sync_lock);
15395 			have_sync_lock = 0;
15396 		}
15397 		if (did_start_seqid_sync) {
15398 			nfs4_end_open_seqid_sync(oop);
15399 			did_start_seqid_sync = 0;
15400 		}
15401 		open_stream_rele(osp, rp);
15402 
15403 		if (did_start_op)
15404 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15405 			    &recov_state, FALSE);
15406 		if (did_force_recovlock)
15407 			nfs_rw_exit(&mi->mi_recovlock);
15408 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15409 		    "nfs4close_one: need to retry the close "
15410 		    "operation"));
15411 		goto recov_retry;
15412 	}
15413 close_cleanup:
15414 	/*
15415 	 * Seventh and lastly, process our results.
15416 	 */
15417 	if (close_failed && force_close) {
15418 		/*
15419 		 * It's ok to drop and regrab the 'os_sync_lock' since
15420 		 * nfs4close_notw() will recheck to make sure the
15421 		 * "close"/removal of state should happen.
15422 		 */
15423 		if (!have_sync_lock) {
15424 			mutex_enter(&osp->os_sync_lock);
15425 			have_sync_lock = 1;
15426 		}
15427 		/*
15428 		 * This is last call, remove the ref on the open
15429 		 * stream created by open and clean everything up.
15430 		 */
15431 		osp->os_pending_close = 0;
15432 		nfs4close_notw(vp, osp, &have_sync_lock);
15433 		nfs4_error_zinit(ep);
15434 	}
15435 
15436 	if (!close_failed) {
15437 		if (have_sync_lock) {
15438 			osp->os_pending_close = 0;
15439 			mutex_exit(&osp->os_sync_lock);
15440 			have_sync_lock = 0;
15441 		} else {
15442 			mutex_enter(&osp->os_sync_lock);
15443 			osp->os_pending_close = 0;
15444 			mutex_exit(&osp->os_sync_lock);
15445 		}
15446 		if (did_start_op && recov_state.rs_sp != NULL) {
15447 			mutex_enter(&recov_state.rs_sp->s_lock);
15448 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15449 			mutex_exit(&recov_state.rs_sp->s_lock);
15450 		} else {
15451 			nfs4_dec_state_ref_count(mi);
15452 		}
15453 		nfs4_error_zinit(ep);
15454 	}
15455 
15456 out:
15457 	if (have_sync_lock)
15458 		mutex_exit(&osp->os_sync_lock);
15459 	if (did_start_op)
15460 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15461 		    recovonly ? TRUE : FALSE);
15462 	if (did_force_recovlock)
15463 		nfs_rw_exit(&mi->mi_recovlock);
15464 	if (cred_otw)
15465 		crfree(cred_otw);
15466 	if (osp)
15467 		open_stream_rele(osp, rp);
15468 	if (oop) {
15469 		if (did_start_seqid_sync)
15470 			nfs4_end_open_seqid_sync(oop);
15471 		open_owner_rele(oop);
15472 	}
15473 }
15474 
15475 /*
15476  * Convert information returned by the server in the LOCK4denied
15477  * structure to the form required by fcntl.
15478  */
15479 static void
15480 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15481 {
15482 	nfs4_lo_name_t *lo;
15483 
15484 #ifdef	DEBUG
15485 	if (denied_to_flk_debug) {
15486 		lockt_denied_debug = lockt_denied;
15487 		debug_enter("lockt_denied");
15488 	}
15489 #endif
15490 
15491 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15492 	flk->l_whence = 0;	/* aka SEEK_SET */
15493 	flk->l_start = lockt_denied->offset;
15494 	flk->l_len = lockt_denied->length;
15495 
15496 	/*
15497 	 * If the blocking clientid matches our client id, then we can
15498 	 * interpret the lockowner (since we built it).  If not, then
15499 	 * fabricate a sysid and pid.  Note that the l_sysid field
15500 	 * in *flk already has the local sysid.
15501 	 */
15502 
15503 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15504 
15505 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15506 			lo = (nfs4_lo_name_t *)
15507 			    lockt_denied->owner.owner_val;
15508 
15509 			flk->l_pid = lo->ln_pid;
15510 		} else {
15511 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15512 			    "denied_to_flk: bad lock owner length\n"));
15513 
15514 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15515 		}
15516 	} else {
15517 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15518 		"denied_to_flk: foreign clientid\n"));
15519 
15520 		/*
15521 		 * Construct a new sysid which should be different from
15522 		 * sysids of other systems.
15523 		 */
15524 
15525 		flk->l_sysid++;
15526 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15527 	}
15528 }
15529 
15530 static pid_t
15531 lo_to_pid(lock_owner4 *lop)
15532 {
15533 	pid_t pid = 0;
15534 	uchar_t *cp;
15535 	int i;
15536 
15537 	cp = (uchar_t *)&lop->clientid;
15538 
15539 	for (i = 0; i < sizeof (lop->clientid); i++)
15540 		pid += (pid_t)*cp++;
15541 
15542 	cp = (uchar_t *)lop->owner_val;
15543 
15544 	for (i = 0; i < lop->owner_len; i++)
15545 		pid += (pid_t)*cp++;
15546 
15547 	return (pid);
15548 }
15549 
15550 /*
15551  * Given a lock pointer, returns the length of that lock.
15552  * "end" is the last locked offset the "l_len" covers from
15553  * the start of the lock.
15554  */
15555 static off64_t
15556 lock_to_end(flock64_t *lock)
15557 {
15558 	off64_t lock_end;
15559 
15560 	if (lock->l_len == 0)
15561 		lock_end = (off64_t)MAXEND;
15562 	else
15563 		lock_end = lock->l_start + lock->l_len - 1;
15564 
15565 	return (lock_end);
15566 }
15567 
15568 /*
15569  * Given the end of a lock, it will return you the length "l_len" for that lock.
15570  */
15571 static off64_t
15572 end_to_len(off64_t start, off64_t end)
15573 {
15574 	off64_t lock_len;
15575 
15576 	ASSERT(end >= start);
15577 	if (end == MAXEND)
15578 		lock_len = 0;
15579 	else
15580 		lock_len = end - start + 1;
15581 
15582 	return (lock_len);
15583 }
15584 
15585 /*
15586  * On given end for a lock it determines if it is the last locked offset
15587  * or not, if so keeps it as is, else adds one to return the length for
15588  * valid start.
15589  */
15590 static off64_t
15591 start_check(off64_t x)
15592 {
15593 	if (x == MAXEND)
15594 		return (x);
15595 	else
15596 		return (x + 1);
15597 }
15598 
15599 /*
15600  * See if these two locks overlap, and if so return 1;
15601  * otherwise, return 0.
15602  */
15603 static int
15604 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15605 {
15606 	off64_t llfp_end, curfp_end;
15607 
15608 	llfp_end = lock_to_end(llfp);
15609 	curfp_end = lock_to_end(curfp);
15610 
15611 	if (((llfp_end >= curfp->l_start) &&
15612 	    (llfp->l_start <= curfp->l_start)) ||
15613 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15614 		return (1);
15615 	return (0);
15616 }
15617 
15618 /*
15619  * Determine what the intersecting lock region is, and add that to the
15620  * 'nl_llpp' locklist in increasing order (by l_start).
15621  */
15622 static void
15623 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15624     locklist_t **nl_llpp, vnode_t *vp)
15625 {
15626 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15627 	off64_t lost_flp_end, local_flp_end, len, start;
15628 
15629 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15630 
15631 	if (!locks_intersect(lost_flp, local_flp))
15632 		return;
15633 
15634 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15635 	    "locks intersect"));
15636 
15637 	lost_flp_end = lock_to_end(lost_flp);
15638 	local_flp_end = lock_to_end(local_flp);
15639 
15640 	/* Find the starting point of the intersecting region */
15641 	if (local_flp->l_start > lost_flp->l_start)
15642 		start = local_flp->l_start;
15643 	else
15644 		start = lost_flp->l_start;
15645 
15646 	/* Find the lenght of the intersecting region */
15647 	if (lost_flp_end < local_flp_end)
15648 		len = end_to_len(start, lost_flp_end);
15649 	else
15650 		len = end_to_len(start, local_flp_end);
15651 
15652 	/*
15653 	 * Prepare the flock structure for the intersection found and insert
15654 	 * it into the new list in increasing l_start order. This list contains
15655 	 * intersections of locks registered by the client with the local host
15656 	 * and the lost lock.
15657 	 * The lock type of this lock is the same as that of the local_flp.
15658 	 */
15659 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15660 	intersect_llp->ll_flock.l_start = start;
15661 	intersect_llp->ll_flock.l_len = len;
15662 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15663 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15664 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15665 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15666 	intersect_llp->ll_vp = vp;
15667 
15668 	tmp_fllp = *nl_llpp;
15669 	cur_fllp = NULL;
15670 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15671 	    intersect_llp->ll_flock.l_start) {
15672 			cur_fllp = tmp_fllp;
15673 			tmp_fllp = tmp_fllp->ll_next;
15674 	}
15675 	if (cur_fllp == NULL) {
15676 		/* first on the list */
15677 		intersect_llp->ll_next = *nl_llpp;
15678 		*nl_llpp = intersect_llp;
15679 	} else {
15680 		intersect_llp->ll_next = cur_fllp->ll_next;
15681 		cur_fllp->ll_next = intersect_llp;
15682 	}
15683 
15684 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15685 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15686 	    intersect_llp->ll_flock.l_start,
15687 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15688 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15689 }
15690 
15691 /*
15692  * Our local locking current state is potentially different than
15693  * what the NFSv4 server thinks we have due to a lost lock that was
15694  * resent and then received.  We need to reset our "NFSv4" locking
15695  * state to match the current local locking state for this pid since
15696  * that is what the user/application sees as what the world is.
15697  *
15698  * We cannot afford to drop the open/lock seqid sync since then we can
15699  * get confused about what the current local locking state "is" versus
15700  * "was".
15701  *
15702  * If we are unable to fix up the locks, we send SIGLOST to the affected
15703  * process.  This is not done if the filesystem has been forcibly
15704  * unmounted, in case the process has already exited and a new process
15705  * exists with the same pid.
15706  */
15707 static void
15708 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15709     nfs4_lock_owner_t *lop)
15710 {
15711 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15712 	mntinfo4_t *mi = VTOMI4(vp);
15713 	const int cmd = F_SETLK;
15714 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15715 	flock64_t ul_fl;
15716 
15717 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15718 	    "nfs4_reinstitute_local_lock_state"));
15719 
15720 	/*
15721 	 * Find active locks for this vp from the local locking code.
15722 	 * Scan through this list and find out the locks that intersect with
15723 	 * the lost lock. Once we find the lock that intersects, add the
15724 	 * intersection area as a new lock to a new list "ri_llp". The lock
15725 	 * type of the intersection region lock added to ri_llp is the same
15726 	 * as that found in the active lock list, "list". The intersecting
15727 	 * region locks are added to ri_llp in increasing l_start order.
15728 	 */
15729 	ASSERT(nfs_zone() == mi->mi_zone);
15730 
15731 	locks = flk_active_locks_for_vp(vp);
15732 	ri_llp = NULL;
15733 
15734 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15735 		ASSERT(llp->ll_vp == vp);
15736 		/*
15737 		 * Pick locks that belong to this pid/lockowner
15738 		 */
15739 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15740 			continue;
15741 
15742 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15743 	}
15744 
15745 	/*
15746 	 * Now we have the list of intersections with the lost lock. These are
15747 	 * the locks that were/are active before the server replied to the
15748 	 * last/lost lock. Issue these locks to the server here. Playing these
15749 	 * locks to the server will re-establish aur current local locking state
15750 	 * with the v4 server.
15751 	 * If we get an error, send SIGLOST to the application for that lock.
15752 	 */
15753 
15754 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15755 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15756 		    "nfs4_reinstitute_local_lock_state: need to issue "
15757 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15758 		    llp->ll_flock.l_start,
15759 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15760 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15761 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15762 		/*
15763 		 * No need to relock what we already have
15764 		 */
15765 		if (llp->ll_flock.l_type == lost_flp->l_type)
15766 			continue;
15767 
15768 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15769 	}
15770 
15771 	/*
15772 	 * Now keeping the start of the lost lock as our reference parse the
15773 	 * newly created ri_llp locklist to find the ranges that we have locked
15774 	 * with the v4 server but not in the current local locking. We need
15775 	 * to unlock these ranges.
15776 	 * These ranges can also be reffered to as those ranges, where the lost
15777 	 * lock does not overlap with the locks in the ri_llp but are locked
15778 	 * since the server replied to the lost lock.
15779 	 */
15780 	cur_start = lost_flp->l_start;
15781 	lost_flp_end = lock_to_end(lost_flp);
15782 
15783 	ul_fl.l_type = F_UNLCK;
15784 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15785 	ul_fl.l_sysid = lost_flp->l_sysid;
15786 	ul_fl.l_pid = lost_flp->l_pid;
15787 
15788 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15789 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15790 
15791 		if (llp->ll_flock.l_start <= cur_start) {
15792 			cur_start = start_check(llp_ll_flock_end);
15793 			continue;
15794 		}
15795 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15796 		    "nfs4_reinstitute_local_lock_state: "
15797 		    "UNLOCK [%"PRIx64" - %"PRIx64"]",
15798 		    cur_start, llp->ll_flock.l_start));
15799 
15800 		ul_fl.l_start = cur_start;
15801 		ul_fl.l_len = end_to_len(cur_start,
15802 		    (llp->ll_flock.l_start - 1));
15803 
15804 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15805 		cur_start = start_check(llp_ll_flock_end);
15806 	}
15807 
15808 	/*
15809 	 * In the case where the lost lock ends after all intersecting locks,
15810 	 * unlock the last part of the lost lock range.
15811 	 */
15812 	if (cur_start != start_check(lost_flp_end)) {
15813 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15814 		    "nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15815 		    "lost lock region [%"PRIx64" - %"PRIx64"]",
15816 		    cur_start, lost_flp->l_start + lost_flp->l_len));
15817 
15818 		ul_fl.l_start = cur_start;
15819 		/*
15820 		 * Is it an to-EOF lock? if so unlock till the end
15821 		 */
15822 		if (lost_flp->l_len == 0)
15823 			ul_fl.l_len = 0;
15824 		else
15825 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15826 
15827 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15828 	}
15829 
15830 	if (locks != NULL)
15831 		flk_free_locklist(locks);
15832 
15833 	/* Free up our newly created locklist */
15834 	for (llp = ri_llp; llp != NULL; ) {
15835 		tmp_llp = llp->ll_next;
15836 		kmem_free(llp, sizeof (locklist_t));
15837 		llp = tmp_llp;
15838 	}
15839 
15840 	/*
15841 	 * Now return back to the original calling nfs4frlock()
15842 	 * and let us naturally drop our seqid syncs.
15843 	 */
15844 }
15845 
15846 /*
15847  * Create a lost state record for the given lock reinstantiation request
15848  * and push it onto the lost state queue.
15849  */
15850 static void
15851 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
15852     nfs4_lock_owner_t *lop)
15853 {
15854 	nfs4_lost_rqst_t req;
15855 	nfs_lock_type4 locktype;
15856 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
15857 
15858 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15859 
15860 	locktype = flk_to_locktype(cmd, flk->l_type);
15861 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
15862 	    NULL, NULL, lop, flk, &req, cr, vp);
15863 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
15864 	    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
15865 	    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
15866 	    NULL);
15867 }
15868