xref: /titanic_51/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision 821da340f9590922ba8761a64fadda18843a0e88)
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 static int	nfs4rename_persistent_fh(vnode_t *, char *, vnode_t *,
131 			vnode_t *, char *, cred_t *, nfsstat4 *);
132 static int	nfs4rename_volatile_fh(vnode_t *, char *, vnode_t *,
133 			vnode_t *, char *, cred_t *, nfsstat4 *);
134 static int	do_nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
135 static void	nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
136 static int	nfs4_bio(struct buf *, stable_how4 *, cred_t *, bool_t);
137 static int	nfs4_getapage(vnode_t *, u_offset_t, size_t, uint_t *,
138 			page_t *[], size_t, struct seg *, caddr_t,
139 			enum seg_rw, cred_t *);
140 static void	nfs4_readahead(vnode_t *, u_offset_t, caddr_t, struct seg *,
141 			cred_t *);
142 static int	nfs4_sync_putapage(vnode_t *, page_t *, u_offset_t, size_t,
143 			int, cred_t *);
144 static int	nfs4_sync_pageio(vnode_t *, page_t *, u_offset_t, size_t,
145 			int, cred_t *);
146 static int	nfs4_commit(vnode_t *, offset4, count4, cred_t *);
147 static void	nfs4_set_mod(vnode_t *);
148 static void	nfs4_get_commit(vnode_t *);
149 static void	nfs4_get_commit_range(vnode_t *, u_offset_t, size_t);
150 static int	nfs4_putpage_commit(vnode_t *, offset_t, size_t, cred_t *);
151 static int	nfs4_commit_vp(vnode_t *, u_offset_t, size_t, cred_t *, int);
152 static int	nfs4_sync_commit(vnode_t *, page_t *, offset3, count3,
153 			cred_t *);
154 static void	do_nfs4_async_commit(vnode_t *, page_t *, offset3, count3,
155 			cred_t *);
156 static int	nfs4_update_attrcache(nfsstat4, nfs4_ga_res_t *,
157 			hrtime_t, vnode_t *, cred_t *);
158 static int	nfs4_open_non_reg_file(vnode_t **, int, cred_t *);
159 static int	nfs4_safelock(vnode_t *, const struct flock64 *, cred_t *);
160 static void	nfs4_register_lock_locally(vnode_t *, struct flock64 *, int,
161 			u_offset_t);
162 static int 	nfs4_lockrelease(vnode_t *, int, offset_t, cred_t *);
163 static int	nfs4_block_and_wait(clock_t *, rnode4_t *);
164 static cred_t  *state_to_cred(nfs4_open_stream_t *);
165 static int	vtoname(vnode_t *, char *, ssize_t);
166 static void	denied_to_flk(LOCK4denied *, flock64_t *, LOCKT4args *);
167 static pid_t	lo_to_pid(lock_owner4 *);
168 static void	nfs4_reinstitute_local_lock_state(vnode_t *, flock64_t *,
169 			cred_t *, nfs4_lock_owner_t *);
170 static void	push_reinstate(vnode_t *, int, flock64_t *, cred_t *,
171 			nfs4_lock_owner_t *);
172 static int 	open_and_get_osp(vnode_t *, cred_t *, nfs4_open_stream_t **);
173 static void	nfs4_delmap_callback(struct as *, void *, uint_t);
174 static void	nfs4_free_delmapcall(nfs4_delmapcall_t *);
175 static nfs4_delmapcall_t	*nfs4_init_delmapcall();
176 static int	nfs4_find_and_delete_delmapcall(rnode4_t *, int *);
177 static int	nfs4_is_acl_mask_valid(uint_t, nfs4_acl_op_t);
178 static int	nfs4_create_getsecattr_return(vsecattr_t *, vsecattr_t *,
179 			uid_t, gid_t, int);
180 
181 /*
182  * Routines that implement the setting of v4 args for the misc. ops
183  */
184 static void	nfs4args_lock_free(nfs_argop4 *);
185 static void	nfs4args_lockt_free(nfs_argop4 *);
186 static void	nfs4args_setattr(nfs_argop4 *, vattr_t *, vsecattr_t *,
187 			int, rnode4_t *, cred_t *, bitmap4, int *,
188 			nfs4_stateid_types_t *);
189 static void	nfs4args_setattr_free(nfs_argop4 *);
190 static int	nfs4args_verify(nfs_argop4 *, vattr_t *, enum nfs_opnum4,
191 			bitmap4);
192 static void	nfs4args_verify_free(nfs_argop4 *);
193 static void	nfs4args_write(nfs_argop4 *, stable_how4, rnode4_t *, cred_t *,
194 			WRITE4args **, nfs4_stateid_types_t *);
195 
196 /*
197  * These are the vnode ops functions that implement the vnode interface to
198  * the networked file system.  See more comments below at nfs4_vnodeops.
199  */
200 static int	nfs4_open(vnode_t **, int, cred_t *);
201 static int	nfs4_close(vnode_t *, int, int, offset_t, cred_t *);
202 static int	nfs4_read(vnode_t *, struct uio *, int, cred_t *,
203 			caller_context_t *);
204 static int	nfs4_write(vnode_t *, struct uio *, int, cred_t *,
205 			caller_context_t *);
206 static int	nfs4_ioctl(vnode_t *, int, intptr_t, int, cred_t *, int *);
207 static int	nfs4_getattr(vnode_t *, struct vattr *, int, cred_t *);
208 static int	nfs4_setattr(vnode_t *, struct vattr *, int, cred_t *,
209 			caller_context_t *);
210 static int	nfs4_access(vnode_t *, int, int, cred_t *);
211 static int	nfs4_readlink(vnode_t *, struct uio *, cred_t *);
212 static int	nfs4_fsync(vnode_t *, int, cred_t *);
213 static void	nfs4_inactive(vnode_t *, cred_t *);
214 static int	nfs4_lookup(vnode_t *, char *, vnode_t **,
215 			struct pathname *, int, vnode_t *, cred_t *);
216 static int	nfs4_create(vnode_t *, char *, struct vattr *, enum vcexcl,
217 			int, vnode_t **, cred_t *, int);
218 static int	nfs4_remove(vnode_t *, char *, cred_t *);
219 static int	nfs4_link(vnode_t *, vnode_t *, char *, cred_t *);
220 static int	nfs4_rename(vnode_t *, char *, vnode_t *, char *, cred_t *);
221 static int	nfs4_mkdir(vnode_t *, char *, struct vattr *,
222 			vnode_t **, cred_t *);
223 static int	nfs4_rmdir(vnode_t *, char *, vnode_t *, cred_t *);
224 static int	nfs4_symlink(vnode_t *, char *, struct vattr *, char *,
225 			cred_t *);
226 static int	nfs4_readdir(vnode_t *, struct uio *, cred_t *, int *);
227 static int	nfs4_fid(vnode_t *, fid_t *);
228 static int	nfs4_rwlock(vnode_t *, int, caller_context_t *);
229 static void	nfs4_rwunlock(vnode_t *, int, caller_context_t *);
230 static int	nfs4_seek(vnode_t *, offset_t, offset_t *);
231 static int	nfs4_getpage(vnode_t *, offset_t, size_t, uint_t *,
232 			page_t *[], size_t, struct seg *, caddr_t,
233 			enum seg_rw, cred_t *);
234 static int	nfs4_putpage(vnode_t *, offset_t, size_t, int, cred_t *);
235 static int	nfs4_map(vnode_t *, offset_t, struct as *, caddr_t *,
236 			size_t, uchar_t, uchar_t, uint_t, cred_t *);
237 static int	nfs4_addmap(vnode_t *, offset_t, struct as *, caddr_t,
238 			size_t, uchar_t, uchar_t, uint_t, cred_t *);
239 static int	nfs4_cmp(vnode_t *, vnode_t *);
240 static int	nfs4_frlock(vnode_t *, int, struct flock64 *, int, offset_t,
241 			struct flk_callback *, cred_t *);
242 static int	nfs4_space(vnode_t *, int, struct flock64 *, int, offset_t,
243 			cred_t *, caller_context_t *);
244 static int	nfs4_realvp(vnode_t *, vnode_t **);
245 static int	nfs4_delmap(vnode_t *, offset_t, struct as *, caddr_t,
246 			size_t, uint_t, uint_t, uint_t, cred_t *);
247 static int	nfs4_pathconf(vnode_t *, int, ulong_t *, cred_t *);
248 static int	nfs4_pageio(vnode_t *, page_t *, u_offset_t, size_t, int,
249 			cred_t *);
250 static void	nfs4_dispose(vnode_t *, page_t *, int, int, cred_t *);
251 static int	nfs4_setsecattr(vnode_t *, vsecattr_t *, int, cred_t *);
252 static int	nfs4_getsecattr(vnode_t *, vsecattr_t *, int, cred_t *);
253 static int	nfs4_shrlock(vnode_t *, int, struct shrlock *, int, cred_t *);
254 
255 /*
256  * Used for nfs4_commit_vp() to indicate if we should
257  * wait on pending writes.
258  */
259 #define	NFS4_WRITE_NOWAIT	0
260 #define	NFS4_WRITE_WAIT		1
261 
262 #define	NFS4_BASE_WAIT_TIME 1	/* 1 second */
263 
264 /*
265  * Error flags used to pass information about certain special errors
266  * which need to be handled specially.
267  */
268 #define	NFS_EOF			-98
269 #define	NFS_VERF_MISMATCH	-97
270 
271 /*
272  * Flags used to differentiate between which operation drove the
273  * potential CLOSE OTW. (see nfs4_close_otw_if_necessary)
274  */
275 #define	NFS4_CLOSE_OP		0x1
276 #define	NFS4_DELMAP_OP		0x2
277 #define	NFS4_INACTIVE_OP	0x3
278 
279 #define	ISVDEV(t) ((t == VBLK) || (t == VCHR) || (t == VFIFO))
280 
281 /* ALIGN64 aligns the given buffer and adjust buffer size to 64 bit */
282 #define	ALIGN64(x, ptr, sz)						\
283 	x = ((uintptr_t)(ptr)) & (sizeof (uint64_t) - 1);		\
284 	if (x) {							\
285 		x = sizeof (uint64_t) - (x);				\
286 		sz -= (x);						\
287 		ptr += (x);						\
288 	}
289 
290 #ifdef DEBUG
291 int nfs4_client_attr_debug = 0;
292 int nfs4_client_state_debug = 0;
293 int nfs4_client_shadow_debug = 0;
294 int nfs4_client_lock_debug = 0;
295 int nfs4_seqid_sync = 0;
296 int nfs4_client_map_debug = 0;
297 static int nfs4_pageio_debug = 0;
298 int nfs4_client_inactive_debug = 0;
299 int nfs4_client_recov_debug = 0;
300 int nfs4_client_recov_stub_debug = 0;
301 int nfs4_client_failover_debug = 0;
302 int nfs4_client_call_debug = 0;
303 int nfs4_client_lookup_debug = 0;
304 int nfs4_client_zone_debug = 0;
305 int nfs4_lost_rqst_debug = 0;
306 int nfs4_rdattrerr_debug = 0;
307 int nfs4_open_stream_debug = 0;
308 
309 int nfs4read_error_inject;
310 
311 static int nfs4_create_misses = 0;
312 
313 static int nfs4_readdir_cache_shorts = 0;
314 static int nfs4_readdir_readahead = 0;
315 
316 static int nfs4_bio_do_stop = 0;
317 
318 static int nfs4_lostpage = 0;	/* number of times we lost original page */
319 
320 int nfs4_mmap_debug = 0;
321 
322 static int nfs4_pathconf_cache_hits = 0;
323 static int nfs4_pathconf_cache_misses = 0;
324 
325 int nfs4close_all_cnt;
326 int nfs4close_one_debug = 0;
327 int nfs4close_notw_debug = 0;
328 
329 int denied_to_flk_debug = 0;
330 void *lockt_denied_debug;
331 
332 #endif
333 
334 /*
335  * How long to wait before trying again if OPEN_CONFIRM gets ETIMEDOUT
336  * or NFS4ERR_RESOURCE.
337  */
338 static int confirm_retry_sec = 30;
339 
340 static int nfs4_lookup_neg_cache = 1;
341 
342 /*
343  * number of pages to read ahead
344  * optimized for 100 base-T.
345  */
346 static int nfs4_nra = 4;
347 
348 static int nfs4_do_symlink_cache = 1;
349 
350 static int nfs4_pathconf_disable_cache = 0;
351 
352 /*
353  * These are the vnode ops routines which implement the vnode interface to
354  * the networked file system.  These routines just take their parameters,
355  * make them look networkish by putting the right info into interface structs,
356  * and then calling the appropriate remote routine(s) to do the work.
357  *
358  * Note on directory name lookup cacheing:  If we detect a stale fhandle,
359  * we purge the directory cache relative to that vnode.  This way, the
360  * user won't get burned by the cache repeatedly.  See <nfs/rnode4.h> for
361  * more details on rnode locking.
362  */
363 
364 struct vnodeops *nfs4_vnodeops;
365 
366 const fs_operation_def_t nfs4_vnodeops_template[] = {
367 	VOPNAME_OPEN,		{ .vop_open = nfs4_open },
368 	VOPNAME_CLOSE,		{ .vop_close = nfs4_close },
369 	VOPNAME_READ,		{ .vop_read = nfs4_read },
370 	VOPNAME_WRITE,		{ .vop_write = nfs4_write },
371 	VOPNAME_IOCTL,		{ .vop_ioctl = nfs4_ioctl },
372 	VOPNAME_GETATTR,	{ .vop_getattr = nfs4_getattr },
373 	VOPNAME_SETATTR,	{ .vop_setattr = nfs4_setattr },
374 	VOPNAME_ACCESS,		{ .vop_access = nfs4_access },
375 	VOPNAME_LOOKUP,		{ .vop_lookup = nfs4_lookup },
376 	VOPNAME_CREATE,		{ .vop_create = nfs4_create },
377 	VOPNAME_REMOVE,		{ .vop_remove = nfs4_remove },
378 	VOPNAME_LINK,		{ .vop_link = nfs4_link },
379 	VOPNAME_RENAME,		{ .vop_rename = nfs4_rename },
380 	VOPNAME_MKDIR,		{ .vop_mkdir = nfs4_mkdir },
381 	VOPNAME_RMDIR,		{ .vop_rmdir = nfs4_rmdir },
382 	VOPNAME_READDIR,	{ .vop_readdir = nfs4_readdir },
383 	VOPNAME_SYMLINK,	{ .vop_symlink = nfs4_symlink },
384 	VOPNAME_READLINK,	{ .vop_readlink = nfs4_readlink },
385 	VOPNAME_FSYNC,		{ .vop_fsync = nfs4_fsync },
386 	VOPNAME_INACTIVE,	{ .vop_inactive = nfs4_inactive },
387 	VOPNAME_FID,		{ .vop_fid = nfs4_fid },
388 	VOPNAME_RWLOCK,		{ .vop_rwlock = nfs4_rwlock },
389 	VOPNAME_RWUNLOCK,	{ .vop_rwunlock = nfs4_rwunlock },
390 	VOPNAME_SEEK,		{ .vop_seek = nfs4_seek },
391 	VOPNAME_FRLOCK,		{ .vop_frlock = nfs4_frlock },
392 	VOPNAME_SPACE,		{ .vop_space = nfs4_space },
393 	VOPNAME_REALVP,		{ .vop_realvp = nfs4_realvp },
394 	VOPNAME_GETPAGE,	{ .vop_getpage = nfs4_getpage },
395 	VOPNAME_PUTPAGE,	{ .vop_putpage = nfs4_putpage },
396 	VOPNAME_MAP,		{ .vop_map = nfs4_map },
397 	VOPNAME_ADDMAP,		{ .vop_addmap = nfs4_addmap },
398 	VOPNAME_DELMAP,		{ .vop_delmap = nfs4_delmap },
399 	/* no separate nfs4_dump */
400 	VOPNAME_DUMP,		{ .vop_dump = nfs_dump },
401 	VOPNAME_PATHCONF,	{ .vop_pathconf = nfs4_pathconf },
402 	VOPNAME_PAGEIO,		{ .vop_pageio = nfs4_pageio },
403 	VOPNAME_DISPOSE,	{ .vop_dispose = nfs4_dispose },
404 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = nfs4_setsecattr },
405 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = nfs4_getsecattr },
406 	VOPNAME_SHRLOCK,	{ .vop_shrlock = nfs4_shrlock },
407 	VOPNAME_VNEVENT, 	{ .vop_vnevent = fs_vnevent_support },
408 	NULL,			NULL
409 };
410 
411 /*
412  * The following are subroutines and definitions to set args or get res
413  * for the different nfsv4 ops
414  */
415 
416 void
417 nfs4args_lookup_free(nfs_argop4 *argop, int arglen)
418 {
419 	int i;
420 
421 	for (i = 0; i < arglen; i++) {
422 	    if (argop[i].argop == OP_LOOKUP)
423 		kmem_free(
424 			argop[i].nfs_argop4_u.oplookup.objname.utf8string_val,
425 			argop[i].nfs_argop4_u.oplookup.objname.utf8string_len);
426 	}
427 }
428 
429 static void
430 nfs4args_lock_free(nfs_argop4 *argop)
431 {
432 	locker4 *locker = &argop->nfs_argop4_u.oplock.locker;
433 
434 	if (locker->new_lock_owner == TRUE) {
435 		open_to_lock_owner4 *open_owner;
436 
437 		open_owner = &locker->locker4_u.open_owner;
438 		if (open_owner->lock_owner.owner_val != NULL) {
439 			kmem_free(open_owner->lock_owner.owner_val,
440 				open_owner->lock_owner.owner_len);
441 		}
442 	}
443 }
444 
445 static void
446 nfs4args_lockt_free(nfs_argop4 *argop)
447 {
448 	lock_owner4 *lowner = &argop->nfs_argop4_u.oplockt.owner;
449 
450 	if (lowner->owner_val != NULL) {
451 		kmem_free(lowner->owner_val, lowner->owner_len);
452 	}
453 }
454 
455 static void
456 nfs4args_setattr(nfs_argop4 *argop, vattr_t *vap, vsecattr_t *vsap, int flags,
457 		rnode4_t *rp, cred_t *cr, bitmap4 supp, int *error,
458 		nfs4_stateid_types_t *sid_types)
459 {
460 	fattr4		*attr = &argop->nfs_argop4_u.opsetattr.obj_attributes;
461 	mntinfo4_t	*mi;
462 
463 	argop->argop = OP_SETATTR;
464 	/*
465 	 * The stateid is set to 0 if client is not modifying the size
466 	 * and otherwise to whatever nfs4_get_stateid() returns.
467 	 *
468 	 * XXX Note: nfs4_get_stateid() returns 0 if no lockowner and/or no
469 	 * state struct could be found for the process/file pair.  We may
470 	 * want to change this in the future (by OPENing the file).  See
471 	 * bug # 4474852.
472 	 */
473 	if (vap->va_mask & AT_SIZE) {
474 
475 		ASSERT(rp != NULL);
476 		mi = VTOMI4(RTOV4(rp));
477 
478 		argop->nfs_argop4_u.opsetattr.stateid =
479 			nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
480 				OP_SETATTR, sid_types, FALSE);
481 	} else {
482 		bzero(&argop->nfs_argop4_u.opsetattr.stateid,
483 		    sizeof (stateid4));
484 	}
485 
486 	*error = vattr_to_fattr4(vap, vsap, attr, flags, OP_SETATTR, supp);
487 	if (*error)
488 		bzero(attr, sizeof (*attr));
489 }
490 
491 static void
492 nfs4args_setattr_free(nfs_argop4 *argop)
493 {
494 	nfs4_fattr4_free(&argop->nfs_argop4_u.opsetattr.obj_attributes);
495 }
496 
497 static int
498 nfs4args_verify(nfs_argop4 *argop, vattr_t *vap, enum nfs_opnum4 op,
499 		bitmap4 supp)
500 {
501 	fattr4 *attr;
502 	int error = 0;
503 
504 	argop->argop = op;
505 	switch (op) {
506 	case OP_VERIFY:
507 		attr = &argop->nfs_argop4_u.opverify.obj_attributes;
508 		break;
509 	case OP_NVERIFY:
510 		attr = &argop->nfs_argop4_u.opnverify.obj_attributes;
511 		break;
512 	default:
513 		return (EINVAL);
514 	}
515 	if (!error)
516 		error = vattr_to_fattr4(vap, NULL, attr, 0, op, supp);
517 	if (error)
518 		bzero(attr, sizeof (*attr));
519 	return (error);
520 }
521 
522 static void
523 nfs4args_verify_free(nfs_argop4 *argop)
524 {
525 	switch (argop->argop) {
526 	case OP_VERIFY:
527 		nfs4_fattr4_free(&argop->nfs_argop4_u.opverify.obj_attributes);
528 		break;
529 	case OP_NVERIFY:
530 		nfs4_fattr4_free(&argop->nfs_argop4_u.opnverify.obj_attributes);
531 		break;
532 	default:
533 		break;
534 	}
535 }
536 
537 static void
538 nfs4args_write(nfs_argop4 *argop, stable_how4 stable, rnode4_t *rp, cred_t *cr,
539 	WRITE4args **wargs_pp, nfs4_stateid_types_t *sid_tp)
540 {
541 	WRITE4args *wargs = &argop->nfs_argop4_u.opwrite;
542 	mntinfo4_t *mi = VTOMI4(RTOV4(rp));
543 
544 	argop->argop = OP_WRITE;
545 	wargs->stable = stable;
546 	wargs->stateid = nfs4_get_w_stateid(cr, rp, curproc->p_pidp->pid_id,
547 				mi, OP_WRITE, sid_tp);
548 	wargs->mblk = NULL;
549 	*wargs_pp = wargs;
550 }
551 
552 void
553 nfs4args_copen_free(OPEN4cargs *open_args)
554 {
555 	if (open_args->owner.owner_val) {
556 		kmem_free(open_args->owner.owner_val,
557 					open_args->owner.owner_len);
558 	}
559 	if ((open_args->opentype == OPEN4_CREATE) &&
560 	    (open_args->mode != EXCLUSIVE4)) {
561 		nfs4_fattr4_free(&open_args->createhow4_u.createattrs);
562 	}
563 }
564 
565 /*
566  * XXX:  This is referenced in modstubs.s
567  */
568 struct vnodeops *
569 nfs4_getvnodeops(void)
570 {
571 	return (nfs4_vnodeops);
572 }
573 
574 /*
575  * The OPEN operation opens a regular file.
576  *
577  * ARGSUSED
578  */
579 static int
580 nfs4_open(vnode_t **vpp, int flag, cred_t *cr)
581 {
582 	vnode_t *dvp = NULL;
583 	rnode4_t *rp, *drp;
584 	int error;
585 	int just_been_created;
586 	char fn[MAXNAMELEN];
587 
588 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4_open: "));
589 	if (nfs_zone() != VTOMI4(*vpp)->mi_zone)
590 		return (EIO);
591 	rp = VTOR4(*vpp);
592 
593 	/*
594 	 * Check to see if opening something besides a regular file;
595 	 * if so skip the OTW call
596 	 */
597 	if ((*vpp)->v_type != VREG) {
598 		error = nfs4_open_non_reg_file(vpp, flag, cr);
599 		return (error);
600 	}
601 
602 	/*
603 	 * XXX - would like a check right here to know if the file is
604 	 * executable or not, so as to skip OTW
605 	 */
606 
607 	if ((error = vtodv(*vpp, &dvp, cr, TRUE)) != 0)
608 		return (error);
609 
610 	drp = VTOR4(dvp);
611 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
612 		return (EINTR);
613 
614 	if ((error = vtoname(*vpp, fn, MAXNAMELEN)) != 0) {
615 		nfs_rw_exit(&drp->r_rwlock);
616 		return (error);
617 	}
618 
619 	/*
620 	 * See if this file has just been CREATEd.
621 	 * If so, clear the flag and update the dnlc, which was previously
622 	 * skipped in nfs4_create.
623 	 * XXX need better serilization on this.
624 	 * XXX move this into the nf4open_otw call, after we have
625 	 * XXX acquired the open owner seqid sync.
626 	 */
627 	mutex_enter(&rp->r_statev4_lock);
628 	if (rp->created_v4) {
629 		rp->created_v4 = 0;
630 		mutex_exit(&rp->r_statev4_lock);
631 
632 		dnlc_update(dvp, fn, *vpp);
633 		/* This is needed so we don't bump the open ref count */
634 		just_been_created = 1;
635 	} else {
636 		mutex_exit(&rp->r_statev4_lock);
637 		just_been_created = 0;
638 	}
639 
640 	/*
641 	 * If caller specified O_TRUNC/FTRUNC, then be sure to set
642 	 * FWRITE (to drive successful setattr(size=0) after open)
643 	 */
644 	if (flag & FTRUNC)
645 		flag |= FWRITE;
646 
647 	error = nfs4open_otw(dvp, fn, NULL, vpp, cr, 0, flag, 0,
648 			just_been_created);
649 
650 	if (!error && !((*vpp)->v_flag & VROOT))
651 		dnlc_update(dvp, fn, *vpp);
652 
653 	nfs_rw_exit(&drp->r_rwlock);
654 
655 	/* release the hold from vtodv */
656 	VN_RELE(dvp);
657 
658 	/* exchange the shadow for the master vnode, if needed */
659 
660 	if (error == 0 && IS_SHADOW(*vpp, rp))
661 		sv_exchange(vpp);
662 
663 	return (error);
664 }
665 
666 /*
667  * See if there's a "lost open" request to be saved and recovered.
668  */
669 static void
670 nfs4open_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
671 	nfs4_open_owner_t *oop, cred_t *cr, vnode_t *vp,
672 	vnode_t *dvp, OPEN4cargs *open_args)
673 {
674 	vfs_t *vfsp;
675 	char *srccfp;
676 
677 	vfsp = (dvp ? dvp->v_vfsp : vp->v_vfsp);
678 
679 	if (error != ETIMEDOUT && error != EINTR &&
680 			!NFS4_FRC_UNMT_ERR(error, vfsp)) {
681 		lost_rqstp->lr_op = 0;
682 		return;
683 	}
684 
685 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
686 		    "nfs4open_save_lost_rqst: error %d", error));
687 
688 	lost_rqstp->lr_op = OP_OPEN;
689 	/*
690 	 * The vp (if it is not NULL) and dvp are held and rele'd via
691 	 * the recovery code.  See nfs4_save_lost_rqst.
692 	 */
693 	lost_rqstp->lr_vp = vp;
694 	lost_rqstp->lr_dvp = dvp;
695 	lost_rqstp->lr_oop = oop;
696 	lost_rqstp->lr_osp = NULL;
697 	lost_rqstp->lr_lop = NULL;
698 	lost_rqstp->lr_cr = cr;
699 	lost_rqstp->lr_flk = NULL;
700 	lost_rqstp->lr_oacc = open_args->share_access;
701 	lost_rqstp->lr_odeny = open_args->share_deny;
702 	lost_rqstp->lr_oclaim = open_args->claim;
703 	if (open_args->claim == CLAIM_DELEGATE_CUR) {
704 		lost_rqstp->lr_ostateid =
705 		    open_args->open_claim4_u.delegate_cur_info.delegate_stateid;
706 		srccfp = open_args->open_claim4_u.delegate_cur_info.cfile;
707 	} else {
708 		srccfp = open_args->open_claim4_u.cfile;
709 	}
710 	lost_rqstp->lr_ofile.utf8string_len = 0;
711 	lost_rqstp->lr_ofile.utf8string_val = NULL;
712 	(void) str_to_utf8(srccfp, &lost_rqstp->lr_ofile);
713 	lost_rqstp->lr_putfirst = FALSE;
714 }
715 
716 struct nfs4_excl_time {
717 	uint32 seconds;
718 	uint32 nseconds;
719 };
720 
721 /*
722  * The OPEN operation creates and/or opens a regular file
723  *
724  * ARGSUSED
725  */
726 static int
727 nfs4open_otw(vnode_t *dvp, char *file_name, struct vattr *in_va,
728 	vnode_t **vpp, cred_t *cr, int create_flag, int open_flag,
729 	enum createmode4 createmode, int file_just_been_created)
730 {
731 	rnode4_t *rp;
732 	rnode4_t *drp = VTOR4(dvp);
733 	vnode_t *vp = NULL;
734 	vnode_t *vpi = *vpp;
735 	bool_t needrecov = FALSE;
736 
737 	int doqueue = 1;
738 
739 	COMPOUND4args_clnt args;
740 	COMPOUND4res_clnt res;
741 	nfs_argop4 *argop;
742 	nfs_resop4 *resop;
743 	int argoplist_size;
744 	int idx_open, idx_fattr;
745 
746 	GETFH4res *gf_res = NULL;
747 	OPEN4res *op_res = NULL;
748 	nfs4_ga_res_t *garp;
749 	fattr4 *attr = NULL;
750 	struct nfs4_excl_time verf;
751 	bool_t did_excl_setup = FALSE;
752 	int created_osp;
753 
754 	OPEN4cargs *open_args;
755 	nfs4_open_owner_t	*oop = NULL;
756 	nfs4_open_stream_t	*osp = NULL;
757 	seqid4 seqid = 0;
758 	bool_t retry_open = FALSE;
759 	nfs4_recov_state_t recov_state;
760 	nfs4_lost_rqst_t lost_rqst;
761 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
762 	hrtime_t t;
763 	int acc = 0;
764 	cred_t *cred_otw = NULL;	/* cred used to do the RPC call */
765 	cred_t *ncr = NULL;
766 
767 	nfs4_sharedfh_t *otw_sfh;
768 	nfs4_sharedfh_t *orig_sfh;
769 	int fh_differs = 0;
770 	int numops, setgid_flag;
771 	int num_bseqid_retry = NFS4_NUM_RETRY_BAD_SEQID + 1;
772 
773 	/*
774 	 * Make sure we properly deal with setting the right gid on
775 	 * a newly created file to reflect the parent's setgid bit
776 	 */
777 	setgid_flag = 0;
778 	if (create_flag && in_va) {
779 
780 		/*
781 		 * If the parent's directory has the setgid bit set
782 		 * _and_ the client was able to get a valid mapping
783 		 * for the parent dir's owner_group, we want to
784 		 * append NVERIFY(owner_group == dva.va_gid) and
785 		 * SETATTR to the CREATE compound.
786 		 */
787 		mutex_enter(&drp->r_statelock);
788 		if (drp->r_attr.va_mode & VSGID &&
789 		    drp->r_attr.va_gid != GID_NOBODY) {
790 			in_va->va_gid = drp->r_attr.va_gid;
791 			setgid_flag = 1;
792 		}
793 		mutex_exit(&drp->r_statelock);
794 	}
795 
796 	/*
797 	 * Normal/non-create compound:
798 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new)
799 	 *
800 	 * Open(create) compound no setgid:
801 	 * PUTFH(dfh) + SAVEFH + OPEN(create) + GETFH + GETATTR(new) +
802 	 * RESTOREFH + GETATTR
803 	 *
804 	 * Open(create) setgid:
805 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new) +
806 	 * SAVEFH + PUTFH(dfh) + GETATTR(dvp) + RESTOREFH +
807 	 * NVERIFY(grp) + SETATTR
808 	 */
809 	if (setgid_flag) {
810 		numops = 10;
811 		idx_open = 1;
812 		idx_fattr = 3;
813 	} else if (create_flag) {
814 		numops = 7;
815 		idx_open = 2;
816 		idx_fattr = 4;
817 	} else {
818 		numops = 4;
819 		idx_open = 1;
820 		idx_fattr = 3;
821 	}
822 
823 	args.array_len = numops;
824 	argoplist_size = numops * sizeof (nfs_argop4);
825 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
826 
827 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw: "
828 		"open %s open flag 0x%x cred %p", file_name, open_flag,
829 		(void *)cr));
830 
831 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
832 	if (create_flag) {
833 		/*
834 		 * We are to create a file.  Initialize the passed in vnode
835 		 * pointer.
836 		 */
837 		vpi = NULL;
838 	} else {
839 		/*
840 		 * Check to see if the client owns a read delegation and is
841 		 * trying to open for write.  If so, then return the delegation
842 		 * to avoid the server doing a cb_recall and returning DELAY.
843 		 * NB - we don't use the statev4_lock here because we'd have
844 		 * to drop the lock anyway and the result would be stale.
845 		 */
846 		if ((open_flag & FWRITE) &&
847 		    VTOR4(vpi)->r_deleg_type == OPEN_DELEGATE_READ)
848 			(void) nfs4delegreturn(VTOR4(vpi), NFS4_DR_REOPEN);
849 
850 		/*
851 		 * If the file has a delegation, then do an access check up
852 		 * front.  This avoids having to an access check later after
853 		 * we've already done start_op, which could deadlock.
854 		 */
855 		if (VTOR4(vpi)->r_deleg_type != OPEN_DELEGATE_NONE) {
856 			if (open_flag & FREAD &&
857 			    nfs4_access(vpi, VREAD, 0, cr) == 0)
858 				acc |= VREAD;
859 			if (open_flag & FWRITE &&
860 			    nfs4_access(vpi, VWRITE, 0, cr) == 0)
861 				acc |= VWRITE;
862 		}
863 	}
864 
865 	drp = VTOR4(dvp);
866 
867 	recov_state.rs_flags = 0;
868 	recov_state.rs_num_retry_despite_err = 0;
869 	cred_otw = cr;
870 
871 recov_retry:
872 	fh_differs = 0;
873 	nfs4_error_zinit(&e);
874 
875 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, vpi, &recov_state);
876 	if (e.error) {
877 		if (ncr != NULL)
878 			crfree(ncr);
879 		kmem_free(argop, argoplist_size);
880 		return (e.error);
881 	}
882 
883 	args.ctag = TAG_OPEN;
884 	args.array_len = numops;
885 	args.array = argop;
886 
887 	/* putfh directory fh */
888 	argop[0].argop = OP_CPUTFH;
889 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
890 
891 	/* OPEN: either op 1 or op 2 depending upon create/setgid flags */
892 	argop[idx_open].argop = OP_COPEN;
893 	open_args = &argop[idx_open].nfs_argop4_u.opcopen;
894 	open_args->claim = CLAIM_NULL;
895 
896 	/* name of file */
897 	open_args->open_claim4_u.cfile = file_name;
898 	open_args->owner.owner_len = 0;
899 	open_args->owner.owner_val = NULL;
900 
901 	if (create_flag) {
902 		/* CREATE a file */
903 		open_args->opentype = OPEN4_CREATE;
904 		open_args->mode = createmode;
905 		if (createmode == EXCLUSIVE4) {
906 			if (did_excl_setup == FALSE) {
907 				verf.seconds = nfs_atoi(hw_serial);
908 				if (verf.seconds != 0)
909 					verf.nseconds = newnum();
910 				else {
911 					timestruc_t now;
912 
913 					gethrestime(&now);
914 					verf.seconds = now.tv_sec;
915 					verf.nseconds = now.tv_nsec;
916 				}
917 				/*
918 				 * Since the server will use this value for the
919 				 * mtime, make sure that it can't overflow. Zero
920 				 * out the MSB. The actual value does not matter
921 				 * here, only its uniqeness.
922 				 */
923 				verf.seconds &= INT32_MAX;
924 				did_excl_setup = TRUE;
925 			}
926 
927 			/* Now copy over verifier to OPEN4args. */
928 			open_args->createhow4_u.createverf = *(uint64_t *)&verf;
929 		} else {
930 			int v_error;
931 			bitmap4 supp_attrs;
932 			servinfo4_t *svp;
933 
934 			attr = &open_args->createhow4_u.createattrs;
935 
936 			svp = drp->r_server;
937 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
938 			supp_attrs = svp->sv_supp_attrs;
939 			nfs_rw_exit(&svp->sv_lock);
940 
941 			/* GUARDED4 or UNCHECKED4 */
942 			v_error = vattr_to_fattr4(in_va, NULL, attr, 0, OP_OPEN,
943 					supp_attrs);
944 			if (v_error) {
945 				bzero(attr, sizeof (*attr));
946 				nfs4args_copen_free(open_args);
947 				nfs4_end_op(VTOMI4(dvp), dvp, vpi,
948 					&recov_state, FALSE);
949 				if (ncr != NULL)
950 					crfree(ncr);
951 				kmem_free(argop, argoplist_size);
952 				return (v_error);
953 			}
954 		}
955 	} else {
956 		/* NO CREATE */
957 		open_args->opentype = OPEN4_NOCREATE;
958 	}
959 
960 	if (recov_state.rs_sp != NULL) {
961 		mutex_enter(&recov_state.rs_sp->s_lock);
962 		open_args->owner.clientid = recov_state.rs_sp->clientid;
963 		mutex_exit(&recov_state.rs_sp->s_lock);
964 	} else {
965 		/* XXX should we just fail here? */
966 		open_args->owner.clientid = 0;
967 	}
968 
969 	/*
970 	 * This increments oop's ref count or creates a temporary 'just_created'
971 	 * open owner that will become valid when this OPEN/OPEN_CONFIRM call
972 	 * completes.
973 	 */
974 	mutex_enter(&VTOMI4(dvp)->mi_lock);
975 
976 	/* See if a permanent or just created open owner exists */
977 	oop = find_open_owner_nolock(cr, NFS4_JUST_CREATED, VTOMI4(dvp));
978 	if (!oop) {
979 		/*
980 		 * This open owner does not exist so create a temporary
981 		 * just created one.
982 		 */
983 		oop = create_open_owner(cr, VTOMI4(dvp));
984 		ASSERT(oop != NULL);
985 	}
986 	mutex_exit(&VTOMI4(dvp)->mi_lock);
987 
988 	/* this length never changes, do alloc before seqid sync */
989 	open_args->owner.owner_len = sizeof (oop->oo_name);
990 	open_args->owner.owner_val =
991 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
992 
993 	e.error = nfs4_start_open_seqid_sync(oop, VTOMI4(dvp));
994 	if (e.error == EAGAIN) {
995 		open_owner_rele(oop);
996 		nfs4args_copen_free(open_args);
997 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
998 		if (ncr != NULL) {
999 			crfree(ncr);
1000 			ncr = NULL;
1001 		}
1002 		goto recov_retry;
1003 	}
1004 
1005 	/* Check to see if we need to do the OTW call */
1006 	if (!create_flag) {
1007 		if (!nfs4_is_otw_open_necessary(oop, open_flag, vpi,
1008 			file_just_been_created, &e.error, acc, &recov_state)) {
1009 
1010 			/*
1011 			 * The OTW open is not necessary.  Either
1012 			 * the open can succeed without it (eg.
1013 			 * delegation, error == 0) or the open
1014 			 * must fail due to an access failure
1015 			 * (error != 0).  In either case, tidy
1016 			 * up and return.
1017 			 */
1018 
1019 			nfs4_end_open_seqid_sync(oop);
1020 			open_owner_rele(oop);
1021 			nfs4args_copen_free(open_args);
1022 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, FALSE);
1023 			if (ncr != NULL)
1024 				crfree(ncr);
1025 			kmem_free(argop, argoplist_size);
1026 			return (e.error);
1027 		}
1028 	}
1029 
1030 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1031 	    open_args->owner.owner_len);
1032 
1033 	seqid = nfs4_get_open_seqid(oop) + 1;
1034 	open_args->seqid = seqid;
1035 	open_args->share_access = 0;
1036 	if (open_flag & FREAD)
1037 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1038 	if (open_flag & FWRITE)
1039 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1040 	open_args->share_deny = OPEN4_SHARE_DENY_NONE;
1041 
1042 
1043 
1044 	/*
1045 	 * getfh w/sanity check for idx_open/idx_fattr
1046 	 */
1047 	ASSERT((idx_open + 1) == (idx_fattr - 1));
1048 	argop[idx_open + 1].argop = OP_GETFH;
1049 
1050 	/* getattr */
1051 	argop[idx_fattr].argop = OP_GETATTR;
1052 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1053 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1054 
1055 	if (setgid_flag) {
1056 		vattr_t	_v;
1057 		servinfo4_t *svp;
1058 		bitmap4	supp_attrs;
1059 
1060 		svp = drp->r_server;
1061 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1062 		supp_attrs = svp->sv_supp_attrs;
1063 		nfs_rw_exit(&svp->sv_lock);
1064 
1065 		/*
1066 		 * For setgid case, we need to:
1067 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1068 		 */
1069 		argop[4].argop = OP_SAVEFH;
1070 
1071 		argop[5].argop = OP_CPUTFH;
1072 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
1073 
1074 		argop[6].argop = OP_GETATTR;
1075 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1076 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1077 
1078 		argop[7].argop = OP_RESTOREFH;
1079 
1080 		/*
1081 		 * nverify
1082 		 */
1083 		_v.va_mask = AT_GID;
1084 		_v.va_gid = in_va->va_gid;
1085 		if (!(e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
1086 		    supp_attrs))) {
1087 
1088 			/*
1089 			 * setattr
1090 			 *
1091 			 * We _know_ we're not messing with AT_SIZE or
1092 			 * AT_XTIME, so no need for stateid or flags.
1093 			 * Also we specify NULL rp since we're only
1094 			 * interested in setting owner_group attributes.
1095 			 */
1096 			nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr,
1097 			    supp_attrs, &e.error, 0);
1098 			if (e.error)
1099 				nfs4args_verify_free(&argop[8]);
1100 		}
1101 
1102 		if (e.error) {
1103 			/*
1104 			 * XXX - Revisit the last argument to nfs4_end_op()
1105 			 *	 once 5020486 is fixed.
1106 			 */
1107 			nfs4_end_open_seqid_sync(oop);
1108 			open_owner_rele(oop);
1109 			nfs4args_copen_free(open_args);
1110 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1111 			if (ncr != NULL)
1112 				crfree(ncr);
1113 			kmem_free(argop, argoplist_size);
1114 			return (e.error);
1115 		}
1116 	} else if (create_flag) {
1117 		/*
1118 		 * For setgid case, we need to:
1119 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1120 		 */
1121 		argop[1].argop = OP_SAVEFH;
1122 
1123 		argop[5].argop = OP_RESTOREFH;
1124 
1125 		argop[6].argop = OP_GETATTR;
1126 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1127 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1128 	}
1129 
1130 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1131 	    "nfs4open_otw: %s call, nm %s, rp %s",
1132 	    needrecov ? "recov" : "first", file_name,
1133 	    rnode4info(VTOR4(dvp))));
1134 
1135 	t = gethrtime();
1136 
1137 	rfs4call(VTOMI4(dvp), &args, &res, cred_otw, &doqueue, 0, &e);
1138 
1139 	if (!e.error && nfs4_need_to_bump_seqid(&res))
1140 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1141 
1142 	needrecov = nfs4_needs_recovery(&e, TRUE, dvp->v_vfsp);
1143 
1144 	if (e.error || needrecov) {
1145 		bool_t abort = FALSE;
1146 
1147 		if (needrecov) {
1148 			nfs4_bseqid_entry_t *bsep = NULL;
1149 
1150 			nfs4open_save_lost_rqst(e.error, &lost_rqst, oop,
1151 			    cred_otw, vpi, dvp, open_args);
1152 
1153 			if (!e.error && res.status == NFS4ERR_BAD_SEQID) {
1154 				bsep = nfs4_create_bseqid_entry(oop, NULL,
1155 					vpi, 0, args.ctag, open_args->seqid);
1156 				num_bseqid_retry--;
1157 			}
1158 
1159 			abort = nfs4_start_recovery(&e, VTOMI4(dvp), dvp, vpi,
1160 				    NULL, lost_rqst.lr_op == OP_OPEN ?
1161 				    &lost_rqst : NULL, OP_OPEN, bsep);
1162 
1163 			if (bsep)
1164 				kmem_free(bsep, sizeof (*bsep));
1165 			/* give up if we keep getting BAD_SEQID */
1166 			if (num_bseqid_retry == 0)
1167 				abort = TRUE;
1168 			if (abort == TRUE && e.error == 0)
1169 				e.error = geterrno4(res.status);
1170 		}
1171 		nfs4_end_open_seqid_sync(oop);
1172 		open_owner_rele(oop);
1173 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1174 		nfs4args_copen_free(open_args);
1175 		if (setgid_flag) {
1176 			nfs4args_verify_free(&argop[8]);
1177 			nfs4args_setattr_free(&argop[9]);
1178 		}
1179 		if (!e.error)
1180 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1181 		if (ncr != NULL) {
1182 			crfree(ncr);
1183 			ncr = NULL;
1184 		}
1185 		if (!needrecov || abort == TRUE || e.error == EINTR ||
1186 		    NFS4_FRC_UNMT_ERR(e.error, dvp->v_vfsp)) {
1187 			kmem_free(argop, argoplist_size);
1188 			return (e.error);
1189 		}
1190 		goto recov_retry;
1191 	}
1192 
1193 	/*
1194 	 * Will check and update lease after checking the rflag for
1195 	 * OPEN_CONFIRM in the successful OPEN call.
1196 	 */
1197 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
1198 
1199 		/*
1200 		 * XXX what if we're crossing mount points from server1:/drp
1201 		 * to server2:/drp/rp.
1202 		 */
1203 
1204 		/* Signal our end of use of the open seqid */
1205 		nfs4_end_open_seqid_sync(oop);
1206 
1207 		/*
1208 		 * This will destroy the open owner if it was just created,
1209 		 * and no one else has put a reference on it.
1210 		 */
1211 		open_owner_rele(oop);
1212 		if (create_flag && (createmode != EXCLUSIVE4) &&
1213 		    res.status == NFS4ERR_BADOWNER)
1214 			nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1215 
1216 		e.error = geterrno4(res.status);
1217 		nfs4args_copen_free(open_args);
1218 		if (setgid_flag) {
1219 			nfs4args_verify_free(&argop[8]);
1220 			nfs4args_setattr_free(&argop[9]);
1221 		}
1222 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1223 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1224 		/*
1225 		 * If the reply is NFS4ERR_ACCESS, it may be because
1226 		 * we are root (no root net access).  If the real uid
1227 		 * is not root, then retry with the real uid instead.
1228 		 */
1229 		if (ncr != NULL) {
1230 			crfree(ncr);
1231 			ncr = NULL;
1232 		}
1233 		if (res.status == NFS4ERR_ACCESS &&
1234 		    (ncr = crnetadjust(cred_otw)) != NULL) {
1235 			cred_otw = ncr;
1236 			goto recov_retry;
1237 		}
1238 		kmem_free(argop, argoplist_size);
1239 		return (e.error);
1240 	}
1241 
1242 	resop = &res.array[idx_open];  /* open res */
1243 	op_res = &resop->nfs_resop4_u.opopen;
1244 
1245 #ifdef DEBUG
1246 	/*
1247 	 * verify attrset bitmap
1248 	 */
1249 	if (create_flag &&
1250 	    (createmode == UNCHECKED4 || createmode == GUARDED4)) {
1251 		/* make sure attrset returned is what we asked for */
1252 		/* XXX Ignore this 'error' for now */
1253 		if (attr->attrmask != op_res->attrset)
1254 			/* EMPTY */;
1255 	}
1256 #endif
1257 
1258 	if (op_res->rflags & OPEN4_RESULT_LOCKTYPE_POSIX) {
1259 		mutex_enter(&VTOMI4(dvp)->mi_lock);
1260 		VTOMI4(dvp)->mi_flags |= MI4_POSIX_LOCK;
1261 		mutex_exit(&VTOMI4(dvp)->mi_lock);
1262 	}
1263 
1264 	resop = &res.array[idx_open + 1];  /* getfh res */
1265 	gf_res = &resop->nfs_resop4_u.opgetfh;
1266 
1267 	otw_sfh = sfh4_get(&gf_res->object, VTOMI4(dvp));
1268 
1269 	/*
1270 	 * The open stateid has been updated on the server but not
1271 	 * on the client yet.  There is a path: makenfs4node->nfs4_attr_cache->
1272 	 * flush_pages->VOP_PUTPAGE->...->nfs4write where we will issue an OTW
1273 	 * WRITE call.  That, however, will use the old stateid, so go ahead
1274 	 * and upate the open stateid now, before any call to makenfs4node.
1275 	 */
1276 	if (vpi) {
1277 		nfs4_open_stream_t	*tmp_osp;
1278 		rnode4_t		*tmp_rp = VTOR4(vpi);
1279 
1280 		tmp_osp = find_open_stream(oop, tmp_rp);
1281 		if (tmp_osp) {
1282 			tmp_osp->open_stateid = op_res->stateid;
1283 			mutex_exit(&tmp_osp->os_sync_lock);
1284 			open_stream_rele(tmp_osp, tmp_rp);
1285 		}
1286 
1287 		/*
1288 		 * We must determine if the file handle given by the otw open
1289 		 * is the same as the file handle which was passed in with
1290 		 * *vpp.  This case can be reached if the file we are trying
1291 		 * to open has been removed and another file has been created
1292 		 * having the same file name.  The passed in vnode is released
1293 		 * later.
1294 		 */
1295 		orig_sfh = VTOR4(vpi)->r_fh;
1296 		fh_differs = nfs4cmpfh(&orig_sfh->sfh_fh, &otw_sfh->sfh_fh);
1297 	}
1298 
1299 	garp = &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res;
1300 
1301 	if (create_flag || fh_differs) {
1302 		int rnode_err = 0;
1303 
1304 		vp = makenfs4node(otw_sfh, garp, dvp->v_vfsp, t, cr,
1305 		    dvp, fn_get(VTOSV(dvp)->sv_name, file_name));
1306 
1307 		if (e.error)
1308 			PURGE_ATTRCACHE4(vp);
1309 		/*
1310 		 * For the newly created vp case, make sure the rnode
1311 		 * isn't bad before using it.
1312 		 */
1313 		mutex_enter(&(VTOR4(vp))->r_statelock);
1314 		if (VTOR4(vp)->r_flags & R4RECOVERR)
1315 			rnode_err = EIO;
1316 		mutex_exit(&(VTOR4(vp))->r_statelock);
1317 
1318 		if (rnode_err) {
1319 			nfs4_end_open_seqid_sync(oop);
1320 			nfs4args_copen_free(open_args);
1321 			if (setgid_flag) {
1322 				nfs4args_verify_free(&argop[8]);
1323 				nfs4args_setattr_free(&argop[9]);
1324 			}
1325 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1326 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1327 				    needrecov);
1328 			open_owner_rele(oop);
1329 			VN_RELE(vp);
1330 			if (ncr != NULL)
1331 				crfree(ncr);
1332 			sfh4_rele(&otw_sfh);
1333 			kmem_free(argop, argoplist_size);
1334 			return (EIO);
1335 		}
1336 	} else {
1337 		vp = vpi;
1338 	}
1339 	sfh4_rele(&otw_sfh);
1340 
1341 	/*
1342 	 * It seems odd to get a full set of attrs and then not update
1343 	 * the object's attrcache in the non-create case.  Create case uses
1344 	 * the attrs since makenfs4node checks to see if the attrs need to
1345 	 * be updated (and then updates them).  The non-create case should
1346 	 * update attrs also.
1347 	 */
1348 	if (! create_flag && ! fh_differs && !e.error) {
1349 		nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
1350 	}
1351 
1352 	nfs4_error_zinit(&e);
1353 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
1354 		/* This does not do recovery for vp explicitly. */
1355 		nfs4open_confirm(vp, &seqid, &op_res->stateid, cred_otw, FALSE,
1356 		    &retry_open, oop, FALSE, &e, &num_bseqid_retry);
1357 
1358 		if (e.error || e.stat) {
1359 			nfs4_end_open_seqid_sync(oop);
1360 			nfs4args_copen_free(open_args);
1361 			if (setgid_flag) {
1362 				nfs4args_verify_free(&argop[8]);
1363 				nfs4args_setattr_free(&argop[9]);
1364 			}
1365 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1366 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1367 				needrecov);
1368 			open_owner_rele(oop);
1369 			if (create_flag || fh_differs) {
1370 				/* rele the makenfs4node */
1371 				VN_RELE(vp);
1372 			}
1373 			if (ncr != NULL) {
1374 				crfree(ncr);
1375 				ncr = NULL;
1376 			}
1377 			if (retry_open == TRUE) {
1378 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1379 				    "nfs4open_otw: retry the open since OPEN "
1380 				    "CONFIRM failed with error %d stat %d",
1381 				    e.error, e.stat));
1382 				if (create_flag && createmode == GUARDED4) {
1383 					NFS4_DEBUG(nfs4_client_recov_debug,
1384 					    (CE_NOTE, "nfs4open_otw: switch "
1385 					    "createmode from GUARDED4 to "
1386 					    "UNCHECKED4"));
1387 					createmode = UNCHECKED4;
1388 				}
1389 				goto recov_retry;
1390 			}
1391 			if (!e.error) {
1392 				if (create_flag && (createmode != EXCLUSIVE4) &&
1393 				    e.stat == NFS4ERR_BADOWNER)
1394 					nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1395 
1396 				e.error = geterrno4(e.stat);
1397 			}
1398 			kmem_free(argop, argoplist_size);
1399 			return (e.error);
1400 		}
1401 	}
1402 
1403 	rp = VTOR4(vp);
1404 
1405 	mutex_enter(&rp->r_statev4_lock);
1406 	if (create_flag)
1407 		rp->created_v4 = 1;
1408 	mutex_exit(&rp->r_statev4_lock);
1409 
1410 	mutex_enter(&oop->oo_lock);
1411 	/* Doesn't matter if 'oo_just_created' already was set as this */
1412 	oop->oo_just_created = NFS4_PERM_CREATED;
1413 	if (oop->oo_cred_otw)
1414 		crfree(oop->oo_cred_otw);
1415 	oop->oo_cred_otw = cred_otw;
1416 	crhold(oop->oo_cred_otw);
1417 	mutex_exit(&oop->oo_lock);
1418 
1419 	/* returns with 'os_sync_lock' held */
1420 	osp = find_or_create_open_stream(oop, rp, &created_osp);
1421 	if (!osp) {
1422 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1423 		    "nfs4open_otw: failed to create an open stream"));
1424 		NFS4_DEBUG(nfs4_seqid_sync, (CE_NOTE, "nfs4open_otw: "
1425 		    "signal our end of use of the open seqid"));
1426 
1427 		nfs4_end_open_seqid_sync(oop);
1428 		open_owner_rele(oop);
1429 		nfs4args_copen_free(open_args);
1430 		if (setgid_flag) {
1431 			nfs4args_verify_free(&argop[8]);
1432 			nfs4args_setattr_free(&argop[9]);
1433 		}
1434 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1435 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1436 		if (create_flag || fh_differs)
1437 			VN_RELE(vp);
1438 		if (ncr != NULL)
1439 			crfree(ncr);
1440 
1441 		kmem_free(argop, argoplist_size);
1442 		return (EINVAL);
1443 
1444 	}
1445 
1446 	osp->open_stateid = op_res->stateid;
1447 
1448 	if (open_flag & FREAD)
1449 		osp->os_share_acc_read++;
1450 	if (open_flag & FWRITE)
1451 		osp->os_share_acc_write++;
1452 	osp->os_share_deny_none++;
1453 
1454 	/*
1455 	 * Need to reset this bitfield for the possible case where we were
1456 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
1457 	 * we could retry the CLOSE, OPENed the file again.
1458 	 */
1459 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
1460 	osp->os_final_close = 0;
1461 	osp->os_force_close = 0;
1462 #ifdef DEBUG
1463 	if (osp->os_failed_reopen)
1464 		NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE, "nfs4open_otw:"
1465 		    " clearing os_failed_reopen for osp %p, cr %p, rp %s",
1466 		    (void *)osp, (void *)cr, rnode4info(rp)));
1467 #endif
1468 	osp->os_failed_reopen = 0;
1469 
1470 	mutex_exit(&osp->os_sync_lock);
1471 
1472 	nfs4_end_open_seqid_sync(oop);
1473 
1474 	if (created_osp && recov_state.rs_sp != NULL) {
1475 		mutex_enter(&recov_state.rs_sp->s_lock);
1476 		nfs4_inc_state_ref_count_nolock(recov_state.rs_sp, VTOMI4(dvp));
1477 		mutex_exit(&recov_state.rs_sp->s_lock);
1478 	}
1479 
1480 	/* get rid of our reference to find oop */
1481 	open_owner_rele(oop);
1482 
1483 	open_stream_rele(osp, rp);
1484 
1485 	/* accept delegation, if any */
1486 	nfs4_delegation_accept(rp, CLAIM_NULL, op_res, garp, cred_otw);
1487 
1488 	nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1489 
1490 	if (createmode == EXCLUSIVE4 &&
1491 		(in_va->va_mask & ~(AT_GID | AT_SIZE))) {
1492 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw:"
1493 			" EXCLUSIVE4: sending a SETATTR"));
1494 		/*
1495 		 * If doing an exclusive create, then generate
1496 		 * a SETATTR to set the initial attributes.
1497 		 * Try to set the mtime and the atime to the
1498 		 * server's current time.  It is somewhat
1499 		 * expected that these fields will be used to
1500 		 * store the exclusive create cookie.  If not,
1501 		 * server implementors will need to know that
1502 		 * a SETATTR will follow an exclusive create
1503 		 * and the cookie should be destroyed if
1504 		 * appropriate.
1505 		 *
1506 		 * The AT_GID and AT_SIZE bits are turned off
1507 		 * so that the SETATTR request will not attempt
1508 		 * to process these.  The gid will be set
1509 		 * separately if appropriate.  The size is turned
1510 		 * off because it is assumed that a new file will
1511 		 * be created empty and if the file wasn't empty,
1512 		 * then the exclusive create will have failed
1513 		 * because the file must have existed already.
1514 		 * Therefore, no truncate operation is needed.
1515 		 */
1516 		in_va->va_mask &= ~(AT_GID | AT_SIZE);
1517 		in_va->va_mask |= (AT_MTIME | AT_ATIME);
1518 
1519 		e.error = nfs4setattr(vp, in_va, 0, cr, NULL);
1520 		if (e.error) {
1521 			/*
1522 			 * Couldn't correct the attributes of
1523 			 * the newly created file and the
1524 			 * attributes are wrong.  Remove the
1525 			 * file and return an error to the
1526 			 * application.
1527 			 */
1528 			/* XXX will this take care of client state ? */
1529 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1530 				"nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1531 				" remove file", e.error));
1532 			VN_RELE(vp);
1533 			(void) nfs4_remove(dvp, file_name, cr);
1534 			/*
1535 			 * Since we've reled the vnode and removed
1536 			 * the file we now need to return the error.
1537 			 * At this point we don't want to update the
1538 			 * dircaches, call nfs4_waitfor_purge_complete
1539 			 * or set vpp to vp so we need to skip these
1540 			 * as well.
1541 			 */
1542 			goto skip_update_dircaches;
1543 		}
1544 	}
1545 
1546 	/*
1547 	 * If we created or found the correct vnode, due to create_flag or
1548 	 * fh_differs being set, then update directory cache attribute, readdir
1549 	 * and dnlc caches.
1550 	 */
1551 	if (create_flag || fh_differs) {
1552 		dirattr_info_t dinfo, *dinfop;
1553 
1554 		/*
1555 		 * Make sure getattr succeeded before using results.
1556 		 * note: op 7 is getattr(dir) for both flavors of
1557 		 * open(create).
1558 		 */
1559 		if (create_flag && res.status == NFS4_OK) {
1560 			dinfo.di_time_call = t;
1561 			dinfo.di_cred = cr;
1562 			dinfo.di_garp =
1563 				&res.array[6].nfs_resop4_u.opgetattr.ga_res;
1564 			dinfop = &dinfo;
1565 		} else {
1566 			dinfop = NULL;
1567 		}
1568 
1569 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1570 					dinfop);
1571 	}
1572 
1573 	/*
1574 	 * If the page cache for this file was flushed from actions
1575 	 * above, it was done asynchronously and if that is true,
1576 	 * there is a need to wait here for it to complete.  This must
1577 	 * be done outside of start_fop/end_fop.
1578 	 */
1579 	(void) nfs4_waitfor_purge_complete(vp);
1580 
1581 	/*
1582 	 * It is implicit that we are in the open case (create_flag == 0) since
1583 	 * fh_differs can only be set to a non-zero value in the open case.
1584 	 */
1585 	if (fh_differs != 0 && vpi != NULL)
1586 		VN_RELE(vpi);
1587 
1588 	/*
1589 	 * Be sure to set *vpp to the correct value before returning.
1590 	 */
1591 	*vpp = vp;
1592 
1593 skip_update_dircaches:
1594 
1595 	nfs4args_copen_free(open_args);
1596 	if (setgid_flag) {
1597 		nfs4args_verify_free(&argop[8]);
1598 		nfs4args_setattr_free(&argop[9]);
1599 	}
1600 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1601 
1602 	if (ncr)
1603 		crfree(ncr);
1604 	kmem_free(argop, argoplist_size);
1605 	return (e.error);
1606 }
1607 
1608 /*
1609  * Reopen an open instance.  cf. nfs4open_otw().
1610  *
1611  * Errors are returned by the nfs4_error_t parameter.
1612  * - ep->error contains an errno value or zero.
1613  * - if it is zero, ep->stat is set to an NFS status code, if any.
1614  *   If the file could not be reopened, but the caller should continue, the
1615  *   file is marked dead and no error values are returned.  If the caller
1616  *   should stop recovering open files and start over, either the ep->error
1617  *   value or ep->stat will indicate an error (either something that requires
1618  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1619  *   filehandles) may be handled silently by this routine.
1620  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1621  *   will be started, so the caller should not do it.
1622  *
1623  * Gotos:
1624  * - kill_file : reopen failed in such a fashion to constitute marking the
1625  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1626  *   is for cases where recovery is not possible.
1627  * - failed_reopen : same as above, except that the file has already been
1628  *   marked dead, so no need to do it again.
1629  * - bailout : reopen failed but we are able to recover and retry the reopen -
1630  *   either within this function immediatley or via the calling function.
1631  */
1632 
1633 void
1634 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1635 	    open_claim_type4 claim, bool_t frc_use_claim_previous,
1636 	    bool_t is_recov)
1637 {
1638 	COMPOUND4args_clnt args;
1639 	COMPOUND4res_clnt res;
1640 	nfs_argop4 argop[4];
1641 	nfs_resop4 *resop;
1642 	OPEN4res *op_res = NULL;
1643 	OPEN4cargs *open_args;
1644 	GETFH4res *gf_res;
1645 	rnode4_t *rp = VTOR4(vp);
1646 	int doqueue = 1;
1647 	cred_t *cr = NULL, *cred_otw = NULL;
1648 	nfs4_open_owner_t *oop = NULL;
1649 	seqid4 seqid;
1650 	nfs4_ga_res_t *garp;
1651 	char fn[MAXNAMELEN];
1652 	nfs4_recov_state_t recov = {NULL, 0};
1653 	nfs4_lost_rqst_t lost_rqst;
1654 	mntinfo4_t *mi = VTOMI4(vp);
1655 	bool_t abort;
1656 	char *failed_msg = "";
1657 	int fh_different;
1658 	hrtime_t t;
1659 	nfs4_bseqid_entry_t *bsep = NULL;
1660 
1661 	ASSERT(nfs4_consistent_type(vp));
1662 	ASSERT(nfs_zone() == mi->mi_zone);
1663 
1664 	nfs4_error_zinit(ep);
1665 
1666 	/* this is the cred used to find the open owner */
1667 	cr = state_to_cred(osp);
1668 	if (cr == NULL) {
1669 		failed_msg = "Couldn't reopen: no cred";
1670 		goto kill_file;
1671 	}
1672 	/* use this cred for OTW operations */
1673 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1674 
1675 top:
1676 	nfs4_error_zinit(ep);
1677 
1678 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1679 		/* File system has been unmounted, quit */
1680 		ep->error = EIO;
1681 		failed_msg = "Couldn't reopen: file system has been unmounted";
1682 		goto kill_file;
1683 	}
1684 
1685 	oop = osp->os_open_owner;
1686 
1687 	ASSERT(oop != NULL);
1688 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1689 		failed_msg = "can't reopen: no open owner";
1690 		goto kill_file;
1691 	}
1692 	open_owner_hold(oop);
1693 
1694 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1695 	if (ep->error) {
1696 		open_owner_rele(oop);
1697 		oop = NULL;
1698 		goto bailout;
1699 	}
1700 
1701 	/*
1702 	 * If the rnode has a delegation and the delegation has been
1703 	 * recovered and the server didn't request a recall and the caller
1704 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1705 	 * recovery) and the rnode hasn't been marked dead, then install
1706 	 * the delegation stateid in the open stream.  Otherwise, proceed
1707 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1708 	 */
1709 	mutex_enter(&rp->r_statev4_lock);
1710 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1711 	    !rp->r_deleg_return_pending &&
1712 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1713 	    !rp->r_deleg_needs_recall &&
1714 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1715 	    !(rp->r_flags & R4RECOVERR)) {
1716 		mutex_enter(&osp->os_sync_lock);
1717 		osp->os_delegation = 1;
1718 		osp->open_stateid = rp->r_deleg_stateid;
1719 		mutex_exit(&osp->os_sync_lock);
1720 		mutex_exit(&rp->r_statev4_lock);
1721 		goto bailout;
1722 	}
1723 	mutex_exit(&rp->r_statev4_lock);
1724 
1725 	/*
1726 	 * If the file failed recovery, just quit.  This failure need not
1727 	 * affect other reopens, so don't return an error.
1728 	 */
1729 	mutex_enter(&rp->r_statelock);
1730 	if (rp->r_flags & R4RECOVERR) {
1731 		mutex_exit(&rp->r_statelock);
1732 		ep->error = 0;
1733 		goto failed_reopen;
1734 	}
1735 	mutex_exit(&rp->r_statelock);
1736 
1737 	/*
1738 	 * argop is empty here
1739 	 *
1740 	 * PUTFH, OPEN, GETATTR
1741 	 */
1742 	args.ctag = TAG_REOPEN;
1743 	args.array_len = 4;
1744 	args.array = argop;
1745 
1746 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1747 	    "nfs4_reopen: file is type %d, id %s",
1748 	    vp->v_type, rnode4info(VTOR4(vp))));
1749 
1750 	argop[0].argop = OP_CPUTFH;
1751 
1752 	if (claim != CLAIM_PREVIOUS) {
1753 		/*
1754 		 * if this is a file mount then
1755 		 * use the mntinfo parentfh
1756 		 */
1757 		argop[0].nfs_argop4_u.opcputfh.sfh =
1758 			(vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1759 						VTOSV(vp)->sv_dfh;
1760 	} else {
1761 		/* putfh fh to reopen */
1762 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1763 	}
1764 
1765 	argop[1].argop = OP_COPEN;
1766 	open_args = &argop[1].nfs_argop4_u.opcopen;
1767 	open_args->claim = claim;
1768 
1769 	if (claim == CLAIM_NULL) {
1770 
1771 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1772 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1773 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1774 			    (void *)vp);
1775 			failed_msg = "Couldn't reopen: vtoname failed for "
1776 			    "CLAIM_NULL";
1777 			/* nothing allocated yet */
1778 			goto kill_file;
1779 		}
1780 
1781 		open_args->open_claim4_u.cfile = fn;
1782 	} else if (claim == CLAIM_PREVIOUS) {
1783 
1784 		/*
1785 		 * We have two cases to deal with here:
1786 		 * 1) We're being called to reopen files in order to satisfy
1787 		 *    a lock operation request which requires us to explicitly
1788 		 *    reopen files which were opened under a delegation.  If
1789 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1790 		 *    that case, frc_use_claim_previous is TRUE and we must
1791 		 *    use the rnode's current delegation type (r_deleg_type).
1792 		 * 2) We're reopening files during some form of recovery.
1793 		 *    In this case, frc_use_claim_previous is FALSE and we
1794 		 *    use the delegation type appropriate for recovery
1795 		 *    (r_deleg_needs_recovery).
1796 		 */
1797 		mutex_enter(&rp->r_statev4_lock);
1798 		open_args->open_claim4_u.delegate_type =
1799 			frc_use_claim_previous ?
1800 				rp->r_deleg_type :
1801 				rp->r_deleg_needs_recovery;
1802 		mutex_exit(&rp->r_statev4_lock);
1803 
1804 	} else if (claim == CLAIM_DELEGATE_CUR) {
1805 
1806 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1807 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1808 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1809 			    "with %m", (void *)vp);
1810 			failed_msg = "Couldn't reopen: vtoname failed for "
1811 			    "CLAIM_DELEGATE_CUR";
1812 			/* nothing allocated yet */
1813 			goto kill_file;
1814 		}
1815 
1816 		mutex_enter(&rp->r_statev4_lock);
1817 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1818 							rp->r_deleg_stateid;
1819 		mutex_exit(&rp->r_statev4_lock);
1820 
1821 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1822 	}
1823 	open_args->opentype = OPEN4_NOCREATE;
1824 	open_args->owner.clientid = mi2clientid(mi);
1825 	open_args->owner.owner_len = sizeof (oop->oo_name);
1826 	open_args->owner.owner_val =
1827 			kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1828 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1829 			open_args->owner.owner_len);
1830 	open_args->share_access = 0;
1831 	open_args->share_deny = 0;
1832 
1833 	mutex_enter(&osp->os_sync_lock);
1834 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1835 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1836 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1837 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1838 	    osp->os_share_acc_write, osp->os_open_ref_count,
1839 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1840 
1841 	if (osp->os_share_acc_read || osp->os_mmap_read)
1842 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1843 	if (osp->os_share_acc_write || osp->os_mmap_write)
1844 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1845 	if (osp->os_share_deny_read)
1846 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1847 	if (osp->os_share_deny_write)
1848 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1849 	mutex_exit(&osp->os_sync_lock);
1850 
1851 	seqid = nfs4_get_open_seqid(oop) + 1;
1852 	open_args->seqid = seqid;
1853 
1854 	/* Construct the getfh part of the compound */
1855 	argop[2].argop = OP_GETFH;
1856 
1857 	/* Construct the getattr part of the compound */
1858 	argop[3].argop = OP_GETATTR;
1859 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1860 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1861 
1862 	t = gethrtime();
1863 
1864 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1865 
1866 	if (ep->error) {
1867 		if (!is_recov && !frc_use_claim_previous &&
1868 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1869 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1870 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1871 				cred_otw, vp, NULL, open_args);
1872 			abort = nfs4_start_recovery(ep,
1873 				    VTOMI4(vp), vp, NULL, NULL,
1874 				    lost_rqst.lr_op == OP_OPEN ?
1875 				    &lost_rqst : NULL, OP_OPEN, NULL);
1876 			nfs4args_copen_free(open_args);
1877 			goto bailout;
1878 		}
1879 
1880 		nfs4args_copen_free(open_args);
1881 
1882 		if (ep->error == EACCES && cred_otw != cr) {
1883 			crfree(cred_otw);
1884 			cred_otw = cr;
1885 			crhold(cred_otw);
1886 			nfs4_end_open_seqid_sync(oop);
1887 			open_owner_rele(oop);
1888 			oop = NULL;
1889 			goto top;
1890 		}
1891 		if (ep->error == ETIMEDOUT)
1892 			goto bailout;
1893 		failed_msg = "Couldn't reopen: rpc error";
1894 		goto kill_file;
1895 	}
1896 
1897 	if (nfs4_need_to_bump_seqid(&res))
1898 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1899 
1900 	switch (res.status) {
1901 	case NFS4_OK:
1902 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1903 			mutex_enter(&rp->r_statelock);
1904 			rp->r_delay_interval = 0;
1905 			mutex_exit(&rp->r_statelock);
1906 		}
1907 		break;
1908 	case NFS4ERR_BAD_SEQID:
1909 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1910 			args.ctag, open_args->seqid);
1911 
1912 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1913 			    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1914 			    NULL, OP_OPEN, bsep);
1915 
1916 		nfs4args_copen_free(open_args);
1917 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1918 		nfs4_end_open_seqid_sync(oop);
1919 		open_owner_rele(oop);
1920 		oop = NULL;
1921 		kmem_free(bsep, sizeof (*bsep));
1922 
1923 		goto kill_file;
1924 	case NFS4ERR_NO_GRACE:
1925 		nfs4args_copen_free(open_args);
1926 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1927 		nfs4_end_open_seqid_sync(oop);
1928 		open_owner_rele(oop);
1929 		oop = NULL;
1930 		if (claim == CLAIM_PREVIOUS) {
1931 			/*
1932 			 * Retry as a plain open. We don't need to worry about
1933 			 * checking the changeinfo: it is acceptable for a
1934 			 * client to re-open a file and continue processing
1935 			 * (in the absence of locks).
1936 			 */
1937 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1938 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1939 			    "will retry as CLAIM_NULL"));
1940 			claim = CLAIM_NULL;
1941 			nfs4_mi_kstat_inc_no_grace(mi);
1942 			goto top;
1943 		}
1944 		failed_msg =
1945 		    "Couldn't reopen: tried reclaim outside grace period. ";
1946 		goto kill_file;
1947 	case NFS4ERR_GRACE:
1948 		nfs4_set_grace_wait(mi);
1949 		nfs4args_copen_free(open_args);
1950 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1951 		nfs4_end_open_seqid_sync(oop);
1952 		open_owner_rele(oop);
1953 		oop = NULL;
1954 		ep->error = nfs4_wait_for_grace(mi, &recov);
1955 		if (ep->error != 0)
1956 			goto bailout;
1957 		goto top;
1958 	case NFS4ERR_DELAY:
1959 		nfs4_set_delay_wait(vp);
1960 		nfs4args_copen_free(open_args);
1961 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1962 		nfs4_end_open_seqid_sync(oop);
1963 		open_owner_rele(oop);
1964 		oop = NULL;
1965 		ep->error = nfs4_wait_for_delay(vp, &recov);
1966 		nfs4_mi_kstat_inc_delay(mi);
1967 		if (ep->error != 0)
1968 			goto bailout;
1969 		goto top;
1970 	case NFS4ERR_FHEXPIRED:
1971 		/* recover filehandle and retry */
1972 		abort = nfs4_start_recovery(ep,
1973 				mi, vp, NULL, NULL, NULL, OP_OPEN, NULL);
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 		if (abort == FALSE)
1980 			goto top;
1981 		failed_msg = "Couldn't reopen: recovery aborted";
1982 		goto kill_file;
1983 	case NFS4ERR_RESOURCE:
1984 	case NFS4ERR_STALE_CLIENTID:
1985 	case NFS4ERR_WRONGSEC:
1986 	case NFS4ERR_EXPIRED:
1987 		/*
1988 		 * Do not mark the file dead and let the calling
1989 		 * function initiate recovery.
1990 		 */
1991 		nfs4args_copen_free(open_args);
1992 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1993 		nfs4_end_open_seqid_sync(oop);
1994 		open_owner_rele(oop);
1995 		oop = NULL;
1996 		goto bailout;
1997 	case NFS4ERR_ACCESS:
1998 		if (cred_otw != cr) {
1999 			crfree(cred_otw);
2000 			cred_otw = cr;
2001 			crhold(cred_otw);
2002 			nfs4args_copen_free(open_args);
2003 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2004 			nfs4_end_open_seqid_sync(oop);
2005 			open_owner_rele(oop);
2006 			oop = NULL;
2007 			goto top;
2008 		}
2009 		/* fall through */
2010 	default:
2011 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2012 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2013 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2014 		    rnode4info(VTOR4(vp))));
2015 		failed_msg = "Couldn't reopen: NFSv4 error";
2016 		nfs4args_copen_free(open_args);
2017 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2018 		goto kill_file;
2019 	}
2020 
2021 	resop = &res.array[1];  /* open res */
2022 	op_res = &resop->nfs_resop4_u.opopen;
2023 
2024 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2025 
2026 	/*
2027 	 * Check if the path we reopened really is the same
2028 	 * file. We could end up in a situation where the file
2029 	 * was removed and a new file created with the same name.
2030 	 */
2031 	resop = &res.array[2];
2032 	gf_res = &resop->nfs_resop4_u.opgetfh;
2033 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2034 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2035 	if (fh_different) {
2036 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2037 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2038 			/* Oops, we don't have the same file */
2039 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2040 				failed_msg = "Couldn't reopen: Persistent "
2041 				    "file handle changed";
2042 			else
2043 				failed_msg = "Couldn't reopen: Volatile "
2044 				    "(no expire on open) file handle changed";
2045 
2046 			nfs4args_copen_free(open_args);
2047 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2048 			nfs_rw_exit(&mi->mi_fh_lock);
2049 			goto kill_file;
2050 
2051 		} else {
2052 			/*
2053 			 * We have volatile file handles that don't compare.
2054 			 * If the fids are the same then we assume that the
2055 			 * file handle expired but the rnode still refers to
2056 			 * the same file object.
2057 			 *
2058 			 * First check that we have fids or not.
2059 			 * If we don't we have a dumb server so we will
2060 			 * just assume every thing is ok for now.
2061 			 */
2062 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2063 			    rp->r_attr.va_mask & AT_NODEID &&
2064 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2065 				/*
2066 				 * We have fids, but they don't
2067 				 * compare. So kill the file.
2068 				 */
2069 				failed_msg =
2070 					"Couldn't reopen: file handle changed"
2071 				    " due to mismatched fids";
2072 				nfs4args_copen_free(open_args);
2073 				(void) xdr_free(xdr_COMPOUND4res_clnt,
2074 						(caddr_t)&res);
2075 				nfs_rw_exit(&mi->mi_fh_lock);
2076 				goto kill_file;
2077 			} else {
2078 				/*
2079 				 * We have volatile file handles that refers
2080 				 * to the same file (at least they have the
2081 				 * same fid) or we don't have fids so we
2082 				 * can't tell. :(. We'll be a kind and accepting
2083 				 * client so we'll update the rnode's file
2084 				 * handle with the otw handle.
2085 				 *
2086 				 * We need to drop mi->mi_fh_lock since
2087 				 * sh4_update acquires it. Since there is
2088 				 * only one recovery thread there is no
2089 				 * race.
2090 				 */
2091 				nfs_rw_exit(&mi->mi_fh_lock);
2092 				sfh4_update(rp->r_fh, &gf_res->object);
2093 			}
2094 		}
2095 	} else {
2096 		nfs_rw_exit(&mi->mi_fh_lock);
2097 	}
2098 
2099 	ASSERT(nfs4_consistent_type(vp));
2100 
2101 	/*
2102 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2103 	 * over.  Presumably if there is a persistent error it will show up
2104 	 * when we resend the OPEN.
2105 	 */
2106 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2107 		bool_t retry_open = FALSE;
2108 
2109 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2110 					cred_otw, is_recov, &retry_open,
2111 					oop, FALSE, ep, NULL);
2112 		if (ep->error || ep->stat) {
2113 			nfs4args_copen_free(open_args);
2114 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2115 			nfs4_end_open_seqid_sync(oop);
2116 			open_owner_rele(oop);
2117 			oop = NULL;
2118 			goto top;
2119 		}
2120 	}
2121 
2122 	mutex_enter(&osp->os_sync_lock);
2123 	osp->open_stateid = op_res->stateid;
2124 	osp->os_delegation = 0;
2125 	/*
2126 	 * Need to reset this bitfield for the possible case where we were
2127 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2128 	 * we could retry the CLOSE, OPENed the file again.
2129 	 */
2130 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2131 	osp->os_final_close = 0;
2132 	osp->os_force_close = 0;
2133 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2134 		osp->os_dc_openacc = open_args->share_access;
2135 	mutex_exit(&osp->os_sync_lock);
2136 
2137 	nfs4_end_open_seqid_sync(oop);
2138 
2139 	/* accept delegation, if any */
2140 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2141 
2142 	nfs4args_copen_free(open_args);
2143 
2144 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2145 
2146 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2147 
2148 	ASSERT(nfs4_consistent_type(vp));
2149 
2150 	open_owner_rele(oop);
2151 	crfree(cr);
2152 	crfree(cred_otw);
2153 	return;
2154 
2155 kill_file:
2156 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2157 failed_reopen:
2158 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2159 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2160 	    (void *)osp, (void *)cr, rnode4info(rp)));
2161 	mutex_enter(&osp->os_sync_lock);
2162 	osp->os_failed_reopen = 1;
2163 	mutex_exit(&osp->os_sync_lock);
2164 bailout:
2165 	if (oop != NULL) {
2166 		nfs4_end_open_seqid_sync(oop);
2167 		open_owner_rele(oop);
2168 	}
2169 	if (cr != NULL)
2170 		crfree(cr);
2171 	if (cred_otw != NULL)
2172 		crfree(cred_otw);
2173 }
2174 
2175 /* for . and .. OPENs */
2176 /* ARGSUSED */
2177 static int
2178 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2179 {
2180 	rnode4_t *rp;
2181 	nfs4_ga_res_t gar;
2182 
2183 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2184 
2185 	/*
2186 	 * If close-to-open consistency checking is turned off or
2187 	 * if there is no cached data, we can avoid
2188 	 * the over the wire getattr.  Otherwise, force a
2189 	 * call to the server to get fresh attributes and to
2190 	 * check caches. This is required for close-to-open
2191 	 * consistency.
2192 	 */
2193 	rp = VTOR4(*vpp);
2194 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2195 			(rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2196 		return (0);
2197 
2198 	gar.n4g_va.va_mask = AT_ALL;
2199 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2200 }
2201 
2202 /*
2203  * CLOSE a file
2204  */
2205 static int
2206 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr)
2207 {
2208 	rnode4_t	*rp;
2209 	int		 error = 0;
2210 	int		 r_error = 0;
2211 	int		 n4error = 0;
2212 	nfs4_error_t	 e = { 0, NFS4_OK, RPC_SUCCESS };
2213 
2214 	/*
2215 	 * Remove client state for this (lockowner, file) pair.
2216 	 * Issue otw v4 call to have the server do the same.
2217 	 */
2218 
2219 	rp = VTOR4(vp);
2220 
2221 	/*
2222 	 * zone_enter(2) prevents processes from changing zones with NFS files
2223 	 * open; if we happen to get here from the wrong zone we can't do
2224 	 * anything over the wire.
2225 	 */
2226 	if (VTOMI4(vp)->mi_zone != nfs_zone()) {
2227 		/*
2228 		 * We could attempt to clean up locks, except we're sure
2229 		 * that the current process didn't acquire any locks on
2230 		 * the file: any attempt to lock a file belong to another zone
2231 		 * will fail, and one can't lock an NFS file and then change
2232 		 * zones, as that fails too.
2233 		 *
2234 		 * Returning an error here is the sane thing to do.  A
2235 		 * subsequent call to VN_RELE() which translates to a
2236 		 * nfs4_inactive() will clean up state: if the zone of the
2237 		 * vnode's origin is still alive and kicking, the inactive
2238 		 * thread will handle the request (from the correct zone), and
2239 		 * everything (minus the OTW close call) should be OK.  If the
2240 		 * zone is going away nfs4_async_inactive() will throw away
2241 		 * delegations, open streams and cached pages inline.
2242 		 */
2243 		return (EIO);
2244 	}
2245 
2246 	/*
2247 	 * If we are using local locking for this filesystem, then
2248 	 * release all of the SYSV style record locks.  Otherwise,
2249 	 * we are doing network locking and we need to release all
2250 	 * of the network locks.  All of the locks held by this
2251 	 * process on this file are released no matter what the
2252 	 * incoming reference count is.
2253 	 */
2254 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK) {
2255 		cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
2256 		cleanshares(vp, ttoproc(curthread)->p_pid);
2257 	} else
2258 		e.error = nfs4_lockrelease(vp, flag, offset, cr);
2259 
2260 	if (e.error)
2261 		return (e.error);
2262 
2263 	if (count > 1)
2264 		return (0);
2265 
2266 	/*
2267 	 * If the file has been `unlinked', then purge the
2268 	 * DNLC so that this vnode will get reycled quicker
2269 	 * and the .nfs* file on the server will get removed.
2270 	 */
2271 	if (rp->r_unldvp != NULL)
2272 		dnlc_purge_vp(vp);
2273 
2274 	/*
2275 	 * If the file was open for write and there are pages,
2276 	 * do a synchronous flush and commit of all of the
2277 	 * dirty and uncommitted pages.
2278 	 */
2279 	ASSERT(!e.error);
2280 	if ((flag & FWRITE) && nfs4_has_pages(vp))
2281 		error = nfs4_putpage_commit(vp, 0, 0, cr);
2282 
2283 	mutex_enter(&rp->r_statelock);
2284 	r_error = rp->r_error;
2285 	rp->r_error = 0;
2286 	mutex_exit(&rp->r_statelock);
2287 
2288 	/*
2289 	 * If this file type is one for which no explicit 'open' was
2290 	 * done, then bail now (ie. no need for protocol 'close'). If
2291 	 * there was an error w/the vm subsystem, return _that_ error,
2292 	 * otherwise, return any errors that may've been reported via
2293 	 * the rnode.
2294 	 */
2295 	if (vp->v_type != VREG)
2296 		return (error ? error : r_error);
2297 
2298 	/*
2299 	 * The sync putpage commit may have failed above, but since
2300 	 * we're working w/a regular file, we need to do the protocol
2301 	 * 'close' (nfs4close_one will figure out if an otw close is
2302 	 * needed or not). Report any errors _after_ doing the protocol
2303 	 * 'close'.
2304 	 */
2305 	nfs4close_one(vp, NULL, cr, flag, NULL, &e, CLOSE_NORM, 0, 0, 0);
2306 	n4error = e.error ? e.error : geterrno4(e.stat);
2307 
2308 	/*
2309 	 * Error reporting prio (Hi -> Lo)
2310 	 *
2311 	 *   i) nfs4_putpage_commit (error)
2312 	 *  ii) rnode's (r_error)
2313 	 * iii) nfs4close_one (n4error)
2314 	 */
2315 	return (error ? error : (r_error ? r_error : n4error));
2316 }
2317 
2318 /*
2319  * Initialize *lost_rqstp.
2320  */
2321 
2322 static void
2323 nfs4close_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
2324 	nfs4_open_owner_t *oop, nfs4_open_stream_t *osp, cred_t *cr,
2325 	vnode_t *vp)
2326 {
2327 	if (error != ETIMEDOUT && error != EINTR &&
2328 	    !NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
2329 		lost_rqstp->lr_op = 0;
2330 		return;
2331 	}
2332 
2333 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
2334 			"nfs4close_save_lost_rqst: error %d", error));
2335 
2336 	lost_rqstp->lr_op = OP_CLOSE;
2337 	/*
2338 	 * The vp is held and rele'd via the recovery code.
2339 	 * See nfs4_save_lost_rqst.
2340 	 */
2341 	lost_rqstp->lr_vp = vp;
2342 	lost_rqstp->lr_dvp = NULL;
2343 	lost_rqstp->lr_oop = oop;
2344 	lost_rqstp->lr_osp = osp;
2345 	ASSERT(osp != NULL);
2346 	ASSERT(mutex_owned(&osp->os_sync_lock));
2347 	osp->os_pending_close = 1;
2348 	lost_rqstp->lr_lop = NULL;
2349 	lost_rqstp->lr_cr = cr;
2350 	lost_rqstp->lr_flk = NULL;
2351 	lost_rqstp->lr_putfirst = FALSE;
2352 }
2353 
2354 /*
2355  * Assumes you already have the open seqid sync grabbed as well as the
2356  * 'os_sync_lock'.  Note: this will release the open seqid sync and
2357  * 'os_sync_lock' if client recovery starts.  Calling functions have to
2358  * be prepared to handle this.
2359  *
2360  * 'recov' is returned as 1 if the CLOSE operation detected client recovery
2361  * was needed and was started, and that the calling function should retry
2362  * this function; otherwise it is returned as 0.
2363  *
2364  * Errors are returned via the nfs4_error_t parameter.
2365  */
2366 static void
2367 nfs4close_otw(rnode4_t *rp, cred_t *cred_otw, nfs4_open_owner_t *oop,
2368 	nfs4_open_stream_t *osp, int *recov, int *did_start_seqid_syncp,
2369 	nfs4_close_type_t close_type, nfs4_error_t *ep, int *have_sync_lockp)
2370 {
2371 	COMPOUND4args_clnt args;
2372 	COMPOUND4res_clnt res;
2373 	CLOSE4args *close_args;
2374 	nfs_resop4 *resop;
2375 	nfs_argop4 argop[3];
2376 	int doqueue = 1;
2377 	mntinfo4_t *mi;
2378 	seqid4 seqid;
2379 	vnode_t *vp;
2380 	bool_t needrecov = FALSE;
2381 	nfs4_lost_rqst_t lost_rqst;
2382 	hrtime_t t;
2383 
2384 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
2385 
2386 	ASSERT(MUTEX_HELD(&osp->os_sync_lock));
2387 
2388 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw"));
2389 
2390 	/* Only set this to 1 if recovery is started */
2391 	*recov = 0;
2392 
2393 	/* do the OTW call to close the file */
2394 
2395 	if (close_type == CLOSE_RESEND)
2396 		args.ctag = TAG_CLOSE_LOST;
2397 	else if (close_type == CLOSE_AFTER_RESEND)
2398 		args.ctag = TAG_CLOSE_UNDO;
2399 	else
2400 		args.ctag = TAG_CLOSE;
2401 
2402 	args.array_len = 3;
2403 	args.array = argop;
2404 
2405 	vp = RTOV4(rp);
2406 
2407 	mi = VTOMI4(vp);
2408 
2409 	/* putfh target fh */
2410 	argop[0].argop = OP_CPUTFH;
2411 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
2412 
2413 	argop[1].argop = OP_GETATTR;
2414 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
2415 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
2416 
2417 	argop[2].argop = OP_CLOSE;
2418 	close_args = &argop[2].nfs_argop4_u.opclose;
2419 
2420 	seqid = nfs4_get_open_seqid(oop) + 1;
2421 
2422 	close_args->seqid = seqid;
2423 	close_args->open_stateid = osp->open_stateid;
2424 
2425 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
2426 	    "nfs4close_otw: %s call, rp %s", needrecov ? "recov" : "first",
2427 	    rnode4info(rp)));
2428 
2429 	t = gethrtime();
2430 
2431 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
2432 
2433 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
2434 		nfs4_set_open_seqid(seqid, oop, args.ctag);
2435 	}
2436 
2437 	needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
2438 	if (ep->error && !needrecov) {
2439 		/*
2440 		 * if there was an error and no recovery is to be done
2441 		 * then then set up the file to flush its cache if
2442 		 * needed for the next caller.
2443 		 */
2444 		mutex_enter(&rp->r_statelock);
2445 		PURGE_ATTRCACHE4_LOCKED(rp);
2446 		rp->r_flags &= ~R4WRITEMODIFIED;
2447 		mutex_exit(&rp->r_statelock);
2448 		return;
2449 	}
2450 
2451 	if (needrecov) {
2452 		bool_t abort;
2453 		nfs4_bseqid_entry_t *bsep = NULL;
2454 
2455 		if (close_type != CLOSE_RESEND)
2456 			nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
2457 				osp, cred_otw, vp);
2458 
2459 		if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
2460 			bsep = nfs4_create_bseqid_entry(oop, NULL, vp,
2461 				0, args.ctag, close_args->seqid);
2462 
2463 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
2464 			"nfs4close_otw: initiating recovery. error %d "
2465 			"res.status %d", ep->error, res.status));
2466 
2467 		/*
2468 		 * Drop the 'os_sync_lock' here so we don't hit
2469 		 * a potential recursive mutex_enter via an
2470 		 * 'open_stream_hold()'.
2471 		 */
2472 		mutex_exit(&osp->os_sync_lock);
2473 		*have_sync_lockp = 0;
2474 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
2475 			    (close_type != CLOSE_RESEND &&
2476 			    lost_rqst.lr_op == OP_CLOSE) ? &lost_rqst : NULL,
2477 			    OP_CLOSE, bsep);
2478 
2479 		/* drop open seq sync, and let the calling function regrab it */
2480 		nfs4_end_open_seqid_sync(oop);
2481 		*did_start_seqid_syncp = 0;
2482 
2483 		if (bsep)
2484 			kmem_free(bsep, sizeof (*bsep));
2485 		/*
2486 		 * For signals, the caller wants to quit, so don't say to
2487 		 * retry.  For forced unmount, if it's a user thread, it
2488 		 * wants to quit.  If it's a recovery thread, the retry
2489 		 * will happen higher-up on the call stack.  Either way,
2490 		 * don't say to retry.
2491 		 */
2492 		if (abort == FALSE && ep->error != EINTR &&
2493 		    !NFS4_FRC_UNMT_ERR(ep->error, mi->mi_vfsp) &&
2494 		    close_type != CLOSE_RESEND &&
2495 		    close_type != CLOSE_AFTER_RESEND)
2496 			*recov = 1;
2497 		else
2498 			*recov = 0;
2499 
2500 		if (!ep->error)
2501 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2502 		return;
2503 	}
2504 
2505 	if (res.status) {
2506 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2507 		return;
2508 	}
2509 
2510 	mutex_enter(&rp->r_statev4_lock);
2511 	rp->created_v4 = 0;
2512 	mutex_exit(&rp->r_statev4_lock);
2513 
2514 	resop = &res.array[2];
2515 	osp->open_stateid = resop->nfs_resop4_u.opclose.open_stateid;
2516 	osp->os_valid = 0;
2517 
2518 	/*
2519 	 * This removes the reference obtained at OPEN; ie, when the
2520 	 * open stream structure was created.
2521 	 *
2522 	 * We don't have to worry about calling 'open_stream_rele'
2523 	 * since we our currently holding a reference to the open
2524 	 * stream which means the count cannot go to 0 with this
2525 	 * decrement.
2526 	 */
2527 	ASSERT(osp->os_ref_count >= 2);
2528 	osp->os_ref_count--;
2529 
2530 	if (!ep->error)
2531 		nfs4_attr_cache(vp,
2532 				&res.array[1].nfs_resop4_u.opgetattr.ga_res,
2533 				t, cred_otw, TRUE, NULL);
2534 
2535 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw:"
2536 		" returning %d", ep->error));
2537 
2538 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2539 }
2540 
2541 /* ARGSUSED */
2542 static int
2543 nfs4_read(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2544 	caller_context_t *ct)
2545 {
2546 	rnode4_t *rp;
2547 	u_offset_t off;
2548 	offset_t diff;
2549 	uint_t on;
2550 	uint_t n;
2551 	caddr_t base;
2552 	uint_t flags;
2553 	int error;
2554 	mntinfo4_t *mi;
2555 
2556 	rp = VTOR4(vp);
2557 
2558 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2559 
2560 	if (IS_SHADOW(vp, rp))
2561 		vp = RTOV4(rp);
2562 
2563 	if (vp->v_type != VREG)
2564 		return (EISDIR);
2565 
2566 	mi = VTOMI4(vp);
2567 
2568 	if (nfs_zone() != mi->mi_zone)
2569 		return (EIO);
2570 
2571 	if (uiop->uio_resid == 0)
2572 		return (0);
2573 
2574 	if (uiop->uio_loffset < 0 || uiop->uio_loffset + uiop->uio_resid < 0)
2575 		return (EINVAL);
2576 
2577 	mutex_enter(&rp->r_statelock);
2578 	if (rp->r_flags & R4RECOVERRP)
2579 		error = (rp->r_error ? rp->r_error : EIO);
2580 	else
2581 		error = 0;
2582 	mutex_exit(&rp->r_statelock);
2583 	if (error)
2584 		return (error);
2585 
2586 	/*
2587 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2588 	 * using client-side direct I/O and the file is not mmap'd and
2589 	 * there are no cached pages.
2590 	 */
2591 	if ((vp->v_flag & VNOCACHE) ||
2592 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2593 	    rp->r_mapcnt == 0 && !nfs4_has_pages(vp))) {
2594 		size_t resid = 0;
2595 
2596 		return (nfs4read(vp, NULL, uiop->uio_loffset,
2597 				uiop->uio_resid, &resid, cr, FALSE, uiop));
2598 	}
2599 
2600 	error = 0;
2601 
2602 	do {
2603 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2604 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2605 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2606 
2607 		if (error = nfs4_validate_caches(vp, cr))
2608 			break;
2609 
2610 		mutex_enter(&rp->r_statelock);
2611 		diff = rp->r_size - uiop->uio_loffset;
2612 		mutex_exit(&rp->r_statelock);
2613 		if (diff <= 0)
2614 			break;
2615 		if (diff < n)
2616 			n = (uint_t)diff;
2617 
2618 		if (vpm_enable) {
2619 			/*
2620 			 * Copy data.
2621 			 */
2622 			error = vpm_data_copy(vp, off + on, n, uiop,
2623 						1, NULL, 0, S_READ);
2624 
2625 		} else {
2626 			base = segmap_getmapflt(segkmap, vp, off + on, n, 1,
2627 							S_READ);
2628 
2629 			error = uiomove(base + on, n, UIO_READ, uiop);
2630 		}
2631 
2632 		if (!error) {
2633 			/*
2634 			 * If read a whole block or read to eof,
2635 			 * won't need this buffer again soon.
2636 			 */
2637 			mutex_enter(&rp->r_statelock);
2638 			if (n + on == MAXBSIZE ||
2639 			    uiop->uio_loffset == rp->r_size)
2640 				flags = SM_DONTNEED;
2641 			else
2642 				flags = 0;
2643 			mutex_exit(&rp->r_statelock);
2644 			if (vpm_enable) {
2645 				error = vpm_sync_pages(vp, off, n, flags);
2646 			} else {
2647 				error = segmap_release(segkmap, base, flags);
2648 			}
2649 		} else {
2650 			if (vpm_enable) {
2651 				(void) vpm_sync_pages(vp, off, n, 0);
2652 			} else {
2653 				(void) segmap_release(segkmap, base, 0);
2654 			}
2655 		}
2656 	} while (!error && uiop->uio_resid > 0);
2657 
2658 	return (error);
2659 }
2660 
2661 /* ARGSUSED */
2662 static int
2663 nfs4_write(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2664 		caller_context_t *ct)
2665 {
2666 	rlim64_t limit = uiop->uio_llimit;
2667 	rnode4_t *rp;
2668 	u_offset_t off;
2669 	caddr_t base;
2670 	uint_t flags;
2671 	int remainder;
2672 	size_t n;
2673 	int on;
2674 	int error;
2675 	int resid;
2676 	u_offset_t offset;
2677 	mntinfo4_t *mi;
2678 	uint_t bsize;
2679 
2680 	rp = VTOR4(vp);
2681 
2682 	if (IS_SHADOW(vp, rp))
2683 		vp = RTOV4(rp);
2684 
2685 	if (vp->v_type != VREG)
2686 		return (EISDIR);
2687 
2688 	mi = VTOMI4(vp);
2689 
2690 	if (nfs_zone() != mi->mi_zone)
2691 		return (EIO);
2692 
2693 	if (uiop->uio_resid == 0)
2694 		return (0);
2695 
2696 	mutex_enter(&rp->r_statelock);
2697 	if (rp->r_flags & R4RECOVERRP)
2698 		error = (rp->r_error ? rp->r_error : EIO);
2699 	else
2700 		error = 0;
2701 	mutex_exit(&rp->r_statelock);
2702 	if (error)
2703 		return (error);
2704 
2705 	if (ioflag & FAPPEND) {
2706 		struct vattr va;
2707 
2708 		/*
2709 		 * Must serialize if appending.
2710 		 */
2711 		if (nfs_rw_lock_held(&rp->r_rwlock, RW_READER)) {
2712 			nfs_rw_exit(&rp->r_rwlock);
2713 			if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER,
2714 			    INTR(vp)))
2715 				return (EINTR);
2716 		}
2717 
2718 		va.va_mask = AT_SIZE;
2719 		error = nfs4getattr(vp, &va, cr);
2720 		if (error)
2721 			return (error);
2722 		uiop->uio_loffset = va.va_size;
2723 	}
2724 
2725 	offset = uiop->uio_loffset + uiop->uio_resid;
2726 
2727 	if (uiop->uio_loffset < (offset_t)0 || offset < 0)
2728 		return (EINVAL);
2729 
2730 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
2731 		limit = MAXOFFSET_T;
2732 
2733 	/*
2734 	 * Check to make sure that the process will not exceed
2735 	 * its limit on file size.  It is okay to write up to
2736 	 * the limit, but not beyond.  Thus, the write which
2737 	 * reaches the limit will be short and the next write
2738 	 * will return an error.
2739 	 */
2740 	remainder = 0;
2741 	if (offset > uiop->uio_llimit) {
2742 		remainder = offset - uiop->uio_llimit;
2743 		uiop->uio_resid = uiop->uio_llimit - uiop->uio_loffset;
2744 		if (uiop->uio_resid <= 0) {
2745 			proc_t *p = ttoproc(curthread);
2746 
2747 			uiop->uio_resid += remainder;
2748 			mutex_enter(&p->p_lock);
2749 			(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE],
2750 			    p->p_rctls, p, RCA_UNSAFE_SIGINFO);
2751 			mutex_exit(&p->p_lock);
2752 			return (EFBIG);
2753 		}
2754 	}
2755 
2756 	/* update the change attribute, if we have a write delegation */
2757 
2758 	mutex_enter(&rp->r_statev4_lock);
2759 	if (rp->r_deleg_type == OPEN_DELEGATE_WRITE)
2760 		rp->r_deleg_change++;
2761 
2762 	mutex_exit(&rp->r_statev4_lock);
2763 
2764 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
2765 		return (EINTR);
2766 
2767 	/*
2768 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2769 	 * using client-side direct I/O and the file is not mmap'd and
2770 	 * there are no cached pages.
2771 	 */
2772 	if ((vp->v_flag & VNOCACHE) ||
2773 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2774 	    rp->r_mapcnt == 0 && !nfs4_has_pages(vp))) {
2775 		size_t bufsize;
2776 		int count;
2777 		u_offset_t org_offset;
2778 		stable_how4 stab_comm;
2779 nfs4_fwrite:
2780 		if (rp->r_flags & R4STALE) {
2781 			resid = uiop->uio_resid;
2782 			offset = uiop->uio_loffset;
2783 			error = rp->r_error;
2784 			goto bottom;
2785 		}
2786 
2787 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2788 		base = kmem_alloc(bufsize, KM_SLEEP);
2789 		do {
2790 			if (ioflag & FDSYNC)
2791 				stab_comm = DATA_SYNC4;
2792 			else
2793 				stab_comm = FILE_SYNC4;
2794 			resid = uiop->uio_resid;
2795 			offset = uiop->uio_loffset;
2796 			count = MIN(uiop->uio_resid, bufsize);
2797 			org_offset = uiop->uio_loffset;
2798 			error = uiomove(base, count, UIO_WRITE, uiop);
2799 			if (!error) {
2800 				error = nfs4write(vp, base, org_offset,
2801 						count, cr, &stab_comm);
2802 				if (!error) {
2803 					mutex_enter(&rp->r_statelock);
2804 					if (rp->r_size < uiop->uio_loffset)
2805 						rp->r_size = uiop->uio_loffset;
2806 					mutex_exit(&rp->r_statelock);
2807 				}
2808 			}
2809 		} while (!error && uiop->uio_resid > 0);
2810 		kmem_free(base, bufsize);
2811 		goto bottom;
2812 	}
2813 
2814 	bsize = vp->v_vfsp->vfs_bsize;
2815 
2816 	do {
2817 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2818 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2819 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2820 
2821 		resid = uiop->uio_resid;
2822 		offset = uiop->uio_loffset;
2823 
2824 		if (rp->r_flags & R4STALE) {
2825 			error = rp->r_error;
2826 			break;
2827 		}
2828 
2829 		/*
2830 		 * Don't create dirty pages faster than they
2831 		 * can be cleaned so that the system doesn't
2832 		 * get imbalanced.  If the async queue is
2833 		 * maxed out, then wait for it to drain before
2834 		 * creating more dirty pages.  Also, wait for
2835 		 * any threads doing pagewalks in the vop_getattr
2836 		 * entry points so that they don't block for
2837 		 * long periods.
2838 		 */
2839 		mutex_enter(&rp->r_statelock);
2840 		while ((mi->mi_max_threads != 0 &&
2841 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2842 		    rp->r_gcount > 0)
2843 			cv_wait(&rp->r_cv, &rp->r_statelock);
2844 		mutex_exit(&rp->r_statelock);
2845 
2846 		if (vpm_enable) {
2847 			/*
2848 			 * It will use kpm mappings, so no need to
2849 			 * pass an address.
2850 			 */
2851 			error = writerp4(rp, NULL, n, uiop, 0);
2852 		} else  {
2853 			if (segmap_kpm) {
2854 				int pon = uiop->uio_loffset & PAGEOFFSET;
2855 				size_t pn = MIN(PAGESIZE - pon,
2856 							uiop->uio_resid);
2857 				int pagecreate;
2858 
2859 				mutex_enter(&rp->r_statelock);
2860 				pagecreate = (pon == 0) && (pn == PAGESIZE ||
2861 					uiop->uio_loffset + pn >= rp->r_size);
2862 				mutex_exit(&rp->r_statelock);
2863 
2864 				base = segmap_getmapflt(segkmap, vp, off + on,
2865 						pn, !pagecreate, S_WRITE);
2866 
2867 				error = writerp4(rp, base + pon, n, uiop,
2868 								pagecreate);
2869 
2870 			} else {
2871 				base = segmap_getmapflt(segkmap, vp, off + on,
2872 							n, 0, S_READ);
2873 				error = writerp4(rp, base + on, n, uiop, 0);
2874 			}
2875 		}
2876 
2877 		if (!error) {
2878 			if (mi->mi_flags & MI4_NOAC)
2879 				flags = SM_WRITE;
2880 			else if ((uiop->uio_loffset % bsize) == 0 ||
2881 			    IS_SWAPVP(vp)) {
2882 				/*
2883 				 * Have written a whole block.
2884 				 * Start an asynchronous write
2885 				 * and mark the buffer to
2886 				 * indicate that it won't be
2887 				 * needed again soon.
2888 				 */
2889 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
2890 			} else
2891 				flags = 0;
2892 			if ((ioflag & (FSYNC|FDSYNC)) ||
2893 			    (rp->r_flags & R4OUTOFSPACE)) {
2894 				flags &= ~SM_ASYNC;
2895 				flags |= SM_WRITE;
2896 			}
2897 			if (vpm_enable) {
2898 				error = vpm_sync_pages(vp, off, n, flags);
2899 			} else {
2900 				error = segmap_release(segkmap, base, flags);
2901 			}
2902 		} else {
2903 			if (vpm_enable) {
2904 				(void) vpm_sync_pages(vp, off, n, 0);
2905 			} else {
2906 				(void) segmap_release(segkmap, base, 0);
2907 			}
2908 			/*
2909 			 * In the event that we got an access error while
2910 			 * faulting in a page for a write-only file just
2911 			 * force a write.
2912 			 */
2913 			if (error == EACCES)
2914 				goto nfs4_fwrite;
2915 		}
2916 	} while (!error && uiop->uio_resid > 0);
2917 
2918 bottom:
2919 	if (error) {
2920 		uiop->uio_resid = resid + remainder;
2921 		uiop->uio_loffset = offset;
2922 	} else {
2923 		uiop->uio_resid += remainder;
2924 
2925 		mutex_enter(&rp->r_statev4_lock);
2926 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
2927 			gethrestime(&rp->r_attr.va_mtime);
2928 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
2929 		}
2930 		mutex_exit(&rp->r_statev4_lock);
2931 	}
2932 
2933 	nfs_rw_exit(&rp->r_lkserlock);
2934 
2935 	return (error);
2936 }
2937 
2938 /*
2939  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
2940  */
2941 static int
2942 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
2943 	int flags, cred_t *cr)
2944 {
2945 	struct buf *bp;
2946 	int error;
2947 	page_t *savepp;
2948 	uchar_t fsdata;
2949 	stable_how4 stab_comm;
2950 
2951 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
2952 	bp = pageio_setup(pp, len, vp, flags);
2953 	ASSERT(bp != NULL);
2954 
2955 	/*
2956 	 * pageio_setup should have set b_addr to 0.  This
2957 	 * is correct since we want to do I/O on a page
2958 	 * boundary.  bp_mapin will use this addr to calculate
2959 	 * an offset, and then set b_addr to the kernel virtual
2960 	 * address it allocated for us.
2961 	 */
2962 	ASSERT(bp->b_un.b_addr == 0);
2963 
2964 	bp->b_edev = 0;
2965 	bp->b_dev = 0;
2966 	bp->b_lblkno = lbtodb(off);
2967 	bp->b_file = vp;
2968 	bp->b_offset = (offset_t)off;
2969 	bp_mapin(bp);
2970 
2971 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
2972 	    freemem > desfree)
2973 		stab_comm = UNSTABLE4;
2974 	else
2975 		stab_comm = FILE_SYNC4;
2976 
2977 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
2978 
2979 	bp_mapout(bp);
2980 	pageio_done(bp);
2981 
2982 	if (stab_comm == UNSTABLE4)
2983 		fsdata = C_DELAYCOMMIT;
2984 	else
2985 		fsdata = C_NOCOMMIT;
2986 
2987 	savepp = pp;
2988 	do {
2989 		pp->p_fsdata = fsdata;
2990 	} while ((pp = pp->p_next) != savepp);
2991 
2992 	return (error);
2993 }
2994 
2995 /*
2996  */
2997 static int
2998 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
2999 {
3000 	nfs4_open_owner_t	*oop;
3001 	nfs4_open_stream_t	*osp;
3002 	rnode4_t		*rp = VTOR4(vp);
3003 	mntinfo4_t 		*mi = VTOMI4(vp);
3004 	int 			reopen_needed;
3005 
3006 	ASSERT(nfs_zone() == mi->mi_zone);
3007 
3008 
3009 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
3010 	if (!oop)
3011 		return (EIO);
3012 
3013 	/* returns with 'os_sync_lock' held */
3014 	osp = find_open_stream(oop, rp);
3015 	if (!osp) {
3016 		open_owner_rele(oop);
3017 		return (EIO);
3018 	}
3019 
3020 	if (osp->os_failed_reopen) {
3021 		mutex_exit(&osp->os_sync_lock);
3022 		open_stream_rele(osp, rp);
3023 		open_owner_rele(oop);
3024 		return (EIO);
3025 	}
3026 
3027 	/*
3028 	 * Determine whether a reopen is needed.  If this
3029 	 * is a delegation open stream, then the os_delegation bit
3030 	 * should be set.
3031 	 */
3032 
3033 	reopen_needed = osp->os_delegation;
3034 
3035 	mutex_exit(&osp->os_sync_lock);
3036 	open_owner_rele(oop);
3037 
3038 	if (reopen_needed) {
3039 		nfs4_error_zinit(ep);
3040 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
3041 		mutex_enter(&osp->os_sync_lock);
3042 		if (ep->error || ep->stat || osp->os_failed_reopen) {
3043 			mutex_exit(&osp->os_sync_lock);
3044 			open_stream_rele(osp, rp);
3045 			return (EIO);
3046 		}
3047 		mutex_exit(&osp->os_sync_lock);
3048 	}
3049 	open_stream_rele(osp, rp);
3050 
3051 	return (0);
3052 }
3053 
3054 /*
3055  * Write to file.  Writes to remote server in largest size
3056  * chunks that the server can handle.  Write is synchronous.
3057  */
3058 static int
3059 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3060 	stable_how4 *stab_comm)
3061 {
3062 	mntinfo4_t *mi;
3063 	COMPOUND4args_clnt args;
3064 	COMPOUND4res_clnt res;
3065 	WRITE4args *wargs;
3066 	WRITE4res *wres;
3067 	nfs_argop4 argop[2];
3068 	nfs_resop4 *resop;
3069 	int tsize;
3070 	stable_how4 stable;
3071 	rnode4_t *rp;
3072 	int doqueue = 1;
3073 	bool_t needrecov;
3074 	nfs4_recov_state_t recov_state;
3075 	nfs4_stateid_types_t sid_types;
3076 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3077 
3078 	rp = VTOR4(vp);
3079 	mi = VTOMI4(vp);
3080 
3081 	ASSERT(nfs_zone() == mi->mi_zone);
3082 
3083 	stable = *stab_comm;
3084 	*stab_comm = FILE_SYNC4;
3085 
3086 	needrecov = FALSE;
3087 	recov_state.rs_flags = 0;
3088 	recov_state.rs_num_retry_despite_err = 0;
3089 	nfs4_init_stateid_types(&sid_types);
3090 
3091 recov_retry:
3092 	args.ctag = TAG_WRITE;
3093 	args.array_len = 2;
3094 	args.array = argop;
3095 
3096 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3097 			    &recov_state, NULL);
3098 	if (e.error)
3099 		return (e.error);
3100 
3101 	/* 0. putfh target fh */
3102 	argop[0].argop = OP_CPUTFH;
3103 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3104 
3105 	/* 1. write */
3106 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3107 
3108 	do {
3109 
3110 		wargs->offset = (offset4)offset;
3111 		wargs->data_val = base;
3112 
3113 		if (mi->mi_io_kstats) {
3114 			mutex_enter(&mi->mi_lock);
3115 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3116 			mutex_exit(&mi->mi_lock);
3117 		}
3118 
3119 		if ((vp->v_flag & VNOCACHE) ||
3120 		    (rp->r_flags & R4DIRECTIO) ||
3121 		    (mi->mi_flags & MI4_DIRECTIO))
3122 			tsize = MIN(mi->mi_stsize, count);
3123 		else
3124 			tsize = MIN(mi->mi_curwrite, count);
3125 		wargs->data_len = (uint_t)tsize;
3126 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3127 
3128 		if (mi->mi_io_kstats) {
3129 			mutex_enter(&mi->mi_lock);
3130 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3131 			mutex_exit(&mi->mi_lock);
3132 		}
3133 
3134 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3135 		if (e.error && !needrecov) {
3136 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3137 				&recov_state, needrecov);
3138 			return (e.error);
3139 		}
3140 
3141 
3142 		/*
3143 		 * Do handling of OLD_STATEID outside
3144 		 * of the normal recovery framework.
3145 		 *
3146 		 * If write receives a BAD stateid error while using a
3147 		 * delegation stateid, retry using the open stateid (if it
3148 		 * exists).  If it doesn't have an open stateid, reopen the
3149 		 * file first, then retry.
3150 		 */
3151 		if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3152 		    sid_types.cur_sid_type != SPEC_SID) {
3153 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3154 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3155 				&recov_state, needrecov);
3156 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3157 			goto recov_retry;
3158 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3159 			    sid_types.cur_sid_type == DEL_SID) {
3160 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3161 			mutex_enter(&rp->r_statev4_lock);
3162 			rp->r_deleg_return_pending = TRUE;
3163 			mutex_exit(&rp->r_statev4_lock);
3164 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3165 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3166 					&recov_state, needrecov);
3167 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3168 								(caddr_t)&res);
3169 				return (EIO);
3170 			}
3171 			nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3172 				&recov_state, needrecov);
3173 			/* hold needed for nfs4delegreturn_thread */
3174 			VN_HOLD(vp);
3175 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3176 				NFS4_DR_DISCARD), FALSE);
3177 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3178 			goto recov_retry;
3179 		}
3180 
3181 		if (needrecov) {
3182 			bool_t abort;
3183 
3184 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3185 				"nfs4write: client got error %d, res.status %d"
3186 				", so start recovery", e.error, res.status));
3187 
3188 			abort = nfs4_start_recovery(&e,
3189 				    VTOMI4(vp), vp, NULL, &wargs->stateid,
3190 				    NULL, OP_WRITE, NULL);
3191 			if (!e.error) {
3192 				e.error = geterrno4(res.status);
3193 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3194 								(caddr_t)&res);
3195 			}
3196 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3197 				&recov_state, needrecov);
3198 			if (abort == FALSE)
3199 				goto recov_retry;
3200 			return (e.error);
3201 		}
3202 
3203 		if (res.status) {
3204 			e.error = geterrno4(res.status);
3205 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3206 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3207 				&recov_state, needrecov);
3208 			return (e.error);
3209 		}
3210 
3211 		resop = &res.array[1];	/* write res */
3212 		wres = &resop->nfs_resop4_u.opwrite;
3213 
3214 		if ((int)wres->count > tsize) {
3215 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3216 
3217 			zcmn_err(getzoneid(), CE_WARN,
3218 			"nfs4write: server wrote %u, requested was %u",
3219 			    (int)wres->count, tsize);
3220 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3221 				&recov_state, needrecov);
3222 			return (EIO);
3223 		}
3224 		if (wres->committed == UNSTABLE4) {
3225 			*stab_comm = UNSTABLE4;
3226 			if (wargs->stable == DATA_SYNC4 ||
3227 			    wargs->stable == FILE_SYNC4) {
3228 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3229 								(caddr_t)&res);
3230 				zcmn_err(getzoneid(), CE_WARN,
3231 					"nfs4write: server %s did not commit "
3232 					"to stable storage",
3233 					rp->r_server->sv_hostname);
3234 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3235 						&recov_state, needrecov);
3236 				return (EIO);
3237 			}
3238 		}
3239 
3240 		tsize = (int)wres->count;
3241 		count -= tsize;
3242 		base += tsize;
3243 		offset += tsize;
3244 		if (mi->mi_io_kstats) {
3245 			mutex_enter(&mi->mi_lock);
3246 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3247 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3248 			    tsize;
3249 			mutex_exit(&mi->mi_lock);
3250 		}
3251 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3252 		mutex_enter(&rp->r_statelock);
3253 		if (rp->r_flags & R4HAVEVERF) {
3254 			if (rp->r_writeverf != wres->writeverf) {
3255 				nfs4_set_mod(vp);
3256 				rp->r_writeverf = wres->writeverf;
3257 			}
3258 		} else {
3259 			rp->r_writeverf = wres->writeverf;
3260 			rp->r_flags |= R4HAVEVERF;
3261 		}
3262 		PURGE_ATTRCACHE4_LOCKED(rp);
3263 		rp->r_flags |= R4WRITEMODIFIED;
3264 		gethrestime(&rp->r_attr.va_mtime);
3265 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3266 		mutex_exit(&rp->r_statelock);
3267 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3268 	} while (count);
3269 
3270 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state, needrecov);
3271 
3272 	return (e.error);
3273 }
3274 
3275 /*
3276  * Read from a file.  Reads data in largest chunks our interface can handle.
3277  */
3278 static int
3279 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3280 	size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3281 {
3282 	mntinfo4_t *mi;
3283 	COMPOUND4args_clnt args;
3284 	COMPOUND4res_clnt res;
3285 	READ4args *rargs;
3286 	nfs_argop4 argop[2];
3287 	int tsize;
3288 	int doqueue;
3289 	rnode4_t *rp;
3290 	int data_len;
3291 	bool_t is_eof;
3292 	bool_t needrecov = FALSE;
3293 	nfs4_recov_state_t recov_state;
3294 	nfs4_stateid_types_t sid_types;
3295 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3296 
3297 	rp = VTOR4(vp);
3298 	mi = VTOMI4(vp);
3299 	doqueue = 1;
3300 
3301 	ASSERT(nfs_zone() == mi->mi_zone);
3302 
3303 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3304 
3305 	args.array_len = 2;
3306 	args.array = argop;
3307 
3308 	nfs4_init_stateid_types(&sid_types);
3309 
3310 	recov_state.rs_flags = 0;
3311 	recov_state.rs_num_retry_despite_err = 0;
3312 
3313 recov_retry:
3314 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3315 			    &recov_state, NULL);
3316 	if (e.error)
3317 		return (e.error);
3318 
3319 	/* putfh target fh */
3320 	argop[0].argop = OP_CPUTFH;
3321 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3322 
3323 	/* read */
3324 	argop[1].argop = OP_READ;
3325 	rargs = &argop[1].nfs_argop4_u.opread;
3326 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3327 				OP_READ, &sid_types, async);
3328 
3329 	do {
3330 		if (mi->mi_io_kstats) {
3331 			mutex_enter(&mi->mi_lock);
3332 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3333 			mutex_exit(&mi->mi_lock);
3334 		}
3335 
3336 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3337 		    "nfs4read: %s call, rp %s",
3338 		    needrecov ? "recov" : "first",
3339 		    rnode4info(rp)));
3340 
3341 		if ((vp->v_flag & VNOCACHE) ||
3342 		    (rp->r_flags & R4DIRECTIO) ||
3343 		    (mi->mi_flags & MI4_DIRECTIO))
3344 			tsize = MIN(mi->mi_tsize, count);
3345 		else
3346 			tsize = MIN(mi->mi_curread, count);
3347 		rargs->offset = (offset4)offset;
3348 		rargs->count = (count4)tsize;
3349 		rargs->res_data_val_alt = NULL;
3350 		rargs->res_mblk = NULL;
3351 		rargs->res_uiop = NULL;
3352 		rargs->res_maxsize = 0;
3353 		if (uiop)
3354 			rargs->res_uiop = uiop;
3355 		else
3356 			rargs->res_data_val_alt = base;
3357 		rargs->res_maxsize = tsize;
3358 
3359 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3360 #ifdef	DEBUG
3361 		if (nfs4read_error_inject) {
3362 			res.status = nfs4read_error_inject;
3363 			nfs4read_error_inject = 0;
3364 		}
3365 #endif
3366 
3367 		if (mi->mi_io_kstats) {
3368 			mutex_enter(&mi->mi_lock);
3369 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3370 			mutex_exit(&mi->mi_lock);
3371 		}
3372 
3373 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3374 		if (e.error != 0 && !needrecov) {
3375 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3376 				&recov_state, needrecov);
3377 			return (e.error);
3378 		}
3379 
3380 		/*
3381 		 * Do proper retry for OLD and BAD stateid errors outside
3382 		 * of the normal recovery framework.  There are two differences
3383 		 * between async and sync reads.  The first is that we allow
3384 		 * retry on BAD_STATEID for async reads, but not sync reads.
3385 		 * The second is that we mark the file dead for a failed
3386 		 * attempt with a special stateid for sync reads, but just
3387 		 * return EIO for async reads.
3388 		 *
3389 		 * If a sync read receives a BAD stateid error while using a
3390 		 * delegation stateid, retry using the open stateid (if it
3391 		 * exists).  If it doesn't have an open stateid, reopen the
3392 		 * file first, then retry.
3393 		 */
3394 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3395 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3396 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3397 				&recov_state, needrecov);
3398 			if (sid_types.cur_sid_type == SPEC_SID) {
3399 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3400 						(caddr_t)&res);
3401 				return (EIO);
3402 			}
3403 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3404 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3405 			goto recov_retry;
3406 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3407 			    !async && sid_types.cur_sid_type != SPEC_SID) {
3408 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3409 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3410 				&recov_state, needrecov);
3411 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3412 			goto recov_retry;
3413 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3414 			    sid_types.cur_sid_type == DEL_SID) {
3415 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3416 			mutex_enter(&rp->r_statev4_lock);
3417 			rp->r_deleg_return_pending = TRUE;
3418 			mutex_exit(&rp->r_statev4_lock);
3419 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3420 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3421 					&recov_state, needrecov);
3422 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3423 				    (caddr_t)&res);
3424 				return (EIO);
3425 			}
3426 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3427 				&recov_state, needrecov);
3428 			/* hold needed for nfs4delegreturn_thread */
3429 			VN_HOLD(vp);
3430 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3431 				NFS4_DR_DISCARD), FALSE);
3432 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3433 			goto recov_retry;
3434 		}
3435 		if (needrecov) {
3436 			bool_t abort;
3437 
3438 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3439 			    "nfs4read: initiating recovery\n"));
3440 
3441 			abort = nfs4_start_recovery(&e,
3442 				    mi, vp, NULL, &rargs->stateid,
3443 				    NULL, OP_READ, NULL);
3444 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3445 				&recov_state, needrecov);
3446 			/*
3447 			 * Do not retry if we got OLD_STATEID using a special
3448 			 * stateid.  This avoids looping with a broken server.
3449 			 */
3450 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3451 			    sid_types.cur_sid_type == SPEC_SID)
3452 				abort = TRUE;
3453 
3454 			if (abort == FALSE) {
3455 				/*
3456 				 * Need to retry all possible stateids in
3457 				 * case the recovery error wasn't stateid
3458 				 * related or the stateids have become
3459 				 * stale (server reboot).
3460 				 */
3461 				nfs4_init_stateid_types(&sid_types);
3462 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3463 						(caddr_t)&res);
3464 				goto recov_retry;
3465 			}
3466 
3467 			if (!e.error) {
3468 				e.error = geterrno4(res.status);
3469 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3470 						(caddr_t)&res);
3471 			}
3472 			return (e.error);
3473 		}
3474 
3475 		if (res.status) {
3476 			e.error = geterrno4(res.status);
3477 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3478 				&recov_state, needrecov);
3479 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3480 			return (e.error);
3481 		}
3482 
3483 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3484 		count -= data_len;
3485 		if (base)
3486 			base += data_len;
3487 		offset += data_len;
3488 		if (mi->mi_io_kstats) {
3489 			mutex_enter(&mi->mi_lock);
3490 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3491 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3492 			mutex_exit(&mi->mi_lock);
3493 		}
3494 		lwp_stat_update(LWP_STAT_INBLK, 1);
3495 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3496 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3497 
3498 	} while (count && !is_eof);
3499 
3500 	*residp = count;
3501 
3502 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3503 
3504 	return (e.error);
3505 }
3506 
3507 /* ARGSUSED */
3508 static int
3509 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp)
3510 {
3511 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3512 		return (EIO);
3513 	switch (cmd) {
3514 		case _FIODIRECTIO:
3515 			return (nfs4_directio(vp, (int)arg, cr));
3516 		default:
3517 			return (ENOTTY);
3518 	}
3519 }
3520 
3521 static int
3522 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr)
3523 {
3524 	int error;
3525 	rnode4_t *rp = VTOR4(vp);
3526 
3527 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3528 		return (EIO);
3529 	/*
3530 	 * If it has been specified that the return value will
3531 	 * just be used as a hint, and we are only being asked
3532 	 * for size, fsid or rdevid, then return the client's
3533 	 * notion of these values without checking to make sure
3534 	 * that the attribute cache is up to date.
3535 	 * The whole point is to avoid an over the wire GETATTR
3536 	 * call.
3537 	 */
3538 	if (flags & ATTR_HINT) {
3539 		if (vap->va_mask ==
3540 		    (vap->va_mask & (AT_SIZE | AT_FSID | AT_RDEV))) {
3541 			mutex_enter(&rp->r_statelock);
3542 			if (vap->va_mask | AT_SIZE)
3543 				vap->va_size = rp->r_size;
3544 			if (vap->va_mask | AT_FSID)
3545 				vap->va_fsid = rp->r_attr.va_fsid;
3546 			if (vap->va_mask | AT_RDEV)
3547 				vap->va_rdev = rp->r_attr.va_rdev;
3548 			mutex_exit(&rp->r_statelock);
3549 			return (0);
3550 		}
3551 	}
3552 
3553 	/*
3554 	 * Only need to flush pages if asking for the mtime
3555 	 * and if there any dirty pages or any outstanding
3556 	 * asynchronous (write) requests for this file.
3557 	 */
3558 	if (vap->va_mask & AT_MTIME) {
3559 		rp = VTOR4(vp);
3560 		if (nfs4_has_pages(vp)) {
3561 			mutex_enter(&rp->r_statev4_lock);
3562 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3563 				mutex_exit(&rp->r_statev4_lock);
3564 				if (rp->r_flags & R4DIRTY ||
3565 				    rp->r_awcount > 0) {
3566 					mutex_enter(&rp->r_statelock);
3567 					rp->r_gcount++;
3568 					mutex_exit(&rp->r_statelock);
3569 					error =
3570 						nfs4_putpage(vp, (u_offset_t)0,
3571 								0, 0, cr);
3572 					mutex_enter(&rp->r_statelock);
3573 					if (error && (error == ENOSPC ||
3574 							error == EDQUOT)) {
3575 						if (!rp->r_error)
3576 							rp->r_error = error;
3577 					}
3578 					if (--rp->r_gcount == 0)
3579 						cv_broadcast(&rp->r_cv);
3580 					mutex_exit(&rp->r_statelock);
3581 				}
3582 			} else {
3583 				mutex_exit(&rp->r_statev4_lock);
3584 			}
3585 		}
3586 	}
3587 	return (nfs4getattr(vp, vap, cr));
3588 }
3589 
3590 int
3591 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3592 {
3593 	/*
3594 	 * If these are the only two bits cleared
3595 	 * on the server then return 0 (OK) else
3596 	 * return 1 (BAD).
3597 	 */
3598 	on_client &= ~(S_ISUID|S_ISGID);
3599 	if (on_client == from_server)
3600 		return (0);
3601 	else
3602 		return (1);
3603 }
3604 
3605 /*ARGSUSED4*/
3606 static int
3607 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3608 		caller_context_t *ct)
3609 {
3610 	if (vap->va_mask & AT_NOSET)
3611 		return (EINVAL);
3612 
3613 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3614 		return (EIO);
3615 
3616 	/*
3617 	 * Don't call secpolicy_vnode_setattr, the client cannot
3618 	 * use its cached attributes to make security decisions
3619 	 * as the server may be faking mode bits or mapping uid/gid.
3620 	 * Always just let the server to the checking.
3621 	 * If we provide the ability to remove basic priviledges
3622 	 * to setattr (e.g. basic without chmod) then we will
3623 	 * need to add a check here before calling the server.
3624 	 */
3625 
3626 	return (nfs4setattr(vp, vap, flags, cr, NULL));
3627 }
3628 
3629 /*
3630  * To replace the "guarded" version 3 setattr, we use two types of compound
3631  * setattr requests:
3632  * 1. The "normal" setattr, used when the size of the file isn't being
3633  *    changed - { Putfh <fh>; Setattr; Getattr }/
3634  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3635  *    with only ctime as the argument. If the server ctime differs from
3636  *    what is cached on the client, the verify will fail, but we would
3637  *    already have the ctime from the preceding getattr, so just set it
3638  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3639  *	Setattr; Getattr }.
3640  *
3641  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3642  * this setattr and NULL if they are not.
3643  */
3644 static int
3645 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3646 		vsecattr_t *vsap)
3647 {
3648 	COMPOUND4args_clnt args;
3649 	COMPOUND4res_clnt res, *resp = NULL;
3650 	nfs4_ga_res_t *garp = NULL;
3651 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3652 	nfs_argop4 argop[5];
3653 	int verify_argop = -1;
3654 	int setattr_argop = 1;
3655 	nfs_resop4 *resop;
3656 	vattr_t va;
3657 	rnode4_t *rp;
3658 	int doqueue = 1;
3659 	uint_t mask = vap->va_mask;
3660 	mode_t omode;
3661 	vsecattr_t *vsp;
3662 	timestruc_t ctime;
3663 	bool_t needrecov = FALSE;
3664 	nfs4_recov_state_t recov_state;
3665 	nfs4_stateid_types_t sid_types;
3666 	stateid4 stateid;
3667 	hrtime_t t;
3668 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3669 	servinfo4_t *svp;
3670 	bitmap4 supp_attrs;
3671 
3672 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3673 	rp = VTOR4(vp);
3674 	nfs4_init_stateid_types(&sid_types);
3675 
3676 	/*
3677 	 * Only need to flush pages if there are any pages and
3678 	 * if the file is marked as dirty in some fashion.  The
3679 	 * file must be flushed so that we can accurately
3680 	 * determine the size of the file and the cached data
3681 	 * after the SETATTR returns.  A file is considered to
3682 	 * be dirty if it is either marked with R4DIRTY, has
3683 	 * outstanding i/o's active, or is mmap'd.  In this
3684 	 * last case, we can't tell whether there are dirty
3685 	 * pages, so we flush just to be sure.
3686 	 */
3687 	if (nfs4_has_pages(vp) &&
3688 	    ((rp->r_flags & R4DIRTY) ||
3689 	    rp->r_count > 0 ||
3690 	    rp->r_mapcnt > 0)) {
3691 		ASSERT(vp->v_type != VCHR);
3692 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr);
3693 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3694 			mutex_enter(&rp->r_statelock);
3695 			if (!rp->r_error)
3696 				rp->r_error = e.error;
3697 			mutex_exit(&rp->r_statelock);
3698 		}
3699 	}
3700 
3701 	if (mask & AT_SIZE) {
3702 		/*
3703 		 * Verification setattr compound for non-deleg AT_SIZE:
3704 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3705 		 * Set ctime local here (outside the do_again label)
3706 		 * so that subsequent retries (after failed VERIFY)
3707 		 * will use ctime from GETATTR results (from failed
3708 		 * verify compound) as VERIFY arg.
3709 		 * If file has delegation, then VERIFY(time_metadata)
3710 		 * is of little added value, so don't bother.
3711 		 */
3712 		mutex_enter(&rp->r_statev4_lock);
3713 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3714 						rp->r_deleg_return_pending) {
3715 			numops = 5;
3716 			ctime = rp->r_attr.va_ctime;
3717 		}
3718 		mutex_exit(&rp->r_statev4_lock);
3719 	}
3720 
3721 	recov_state.rs_flags = 0;
3722 	recov_state.rs_num_retry_despite_err = 0;
3723 
3724 	args.ctag = TAG_SETATTR;
3725 do_again:
3726 recov_retry:
3727 	setattr_argop = numops - 2;
3728 
3729 	args.array = argop;
3730 	args.array_len = numops;
3731 
3732 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3733 	if (e.error)
3734 		return (e.error);
3735 
3736 
3737 	/* putfh target fh */
3738 	argop[0].argop = OP_CPUTFH;
3739 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3740 
3741 	if (numops == 5) {
3742 		/*
3743 		 * We only care about the ctime, but need to get mtime
3744 		 * and size for proper cache update.
3745 		 */
3746 		/* getattr */
3747 		argop[1].argop = OP_GETATTR;
3748 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3749 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3750 
3751 		/* verify - set later in loop */
3752 		verify_argop = 2;
3753 	}
3754 
3755 	/* setattr */
3756 	svp = rp->r_server;
3757 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3758 	supp_attrs = svp->sv_supp_attrs;
3759 	nfs_rw_exit(&svp->sv_lock);
3760 
3761 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3762 		supp_attrs, &e.error, &sid_types);
3763 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3764 	if (e.error) {
3765 		/* req time field(s) overflow - return immediately */
3766 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3767 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3768 						opsetattr.obj_attributes);
3769 		return (e.error);
3770 	}
3771 	omode = rp->r_attr.va_mode;
3772 
3773 	/* getattr */
3774 	argop[numops-1].argop = OP_GETATTR;
3775 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3776 	/*
3777 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3778 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3779 	 * used in updating the ACL cache.
3780 	 */
3781 	if (vsap != NULL)
3782 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3783 		    FATTR4_ACL_MASK;
3784 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3785 
3786 	/*
3787 	 * setattr iterates if the object size is set and the cached ctime
3788 	 * does not match the file ctime. In that case, verify the ctime first.
3789 	 */
3790 
3791 	do {
3792 		if (verify_argop != -1) {
3793 			/*
3794 			 * Verify that the ctime match before doing setattr.
3795 			 */
3796 			va.va_mask = AT_CTIME;
3797 			va.va_ctime = ctime;
3798 			svp = rp->r_server;
3799 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3800 			supp_attrs = svp->sv_supp_attrs;
3801 			nfs_rw_exit(&svp->sv_lock);
3802 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3803 					OP_VERIFY, supp_attrs);
3804 			if (e.error) {
3805 				/* req time field(s) overflow - return */
3806 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3807 					needrecov);
3808 				break;
3809 			}
3810 		}
3811 
3812 		doqueue = 1;
3813 
3814 		t = gethrtime();
3815 
3816 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3817 
3818 		/*
3819 		 * Purge the access cache and ACL cache if changing either the
3820 		 * owner of the file, the group owner, or the mode.  These may
3821 		 * change the access permissions of the file, so purge old
3822 		 * information and start over again.
3823 		 */
3824 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3825 			(void) nfs4_access_purge_rp(rp);
3826 			if (rp->r_secattr != NULL) {
3827 				mutex_enter(&rp->r_statelock);
3828 				vsp = rp->r_secattr;
3829 				rp->r_secattr = NULL;
3830 				mutex_exit(&rp->r_statelock);
3831 				if (vsp != NULL)
3832 					nfs4_acl_free_cache(vsp);
3833 			}
3834 		}
3835 
3836 		/*
3837 		 * If res.array_len == numops, then everything succeeded,
3838 		 * except for possibly the final getattr.  If only the
3839 		 * last getattr failed, give up, and don't try recovery.
3840 		 */
3841 		if (res.array_len == numops) {
3842 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3843 			    needrecov);
3844 			if (! e.error)
3845 				resp = &res;
3846 			break;
3847 		}
3848 
3849 		/*
3850 		 * if either rpc call failed or completely succeeded - done
3851 		 */
3852 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
3853 		if (e.error) {
3854 			PURGE_ATTRCACHE4(vp);
3855 			if (!needrecov) {
3856 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3857 				    needrecov);
3858 				break;
3859 			}
3860 		}
3861 
3862 		/*
3863 		 * Do proper retry for OLD_STATEID outside of the normal
3864 		 * recovery framework.
3865 		 */
3866 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3867 		    sid_types.cur_sid_type != SPEC_SID &&
3868 		    sid_types.cur_sid_type != NO_SID) {
3869 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3870 				    needrecov);
3871 			nfs4_save_stateid(&stateid, &sid_types);
3872 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3873 						opsetattr.obj_attributes);
3874 			if (verify_argop != -1) {
3875 				nfs4args_verify_free(&argop[verify_argop]);
3876 				verify_argop = -1;
3877 			}
3878 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3879 			goto recov_retry;
3880 		}
3881 
3882 		if (needrecov) {
3883 			bool_t abort;
3884 
3885 			abort = nfs4_start_recovery(&e,
3886 				    VTOMI4(vp), vp, NULL, NULL, NULL,
3887 				    OP_SETATTR, NULL);
3888 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3889 				    needrecov);
3890 			/*
3891 			 * Do not retry if we failed with OLD_STATEID using
3892 			 * a special stateid.  This is done to avoid looping
3893 			 * with a broken server.
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 				abort = TRUE;
3899 			if (!e.error) {
3900 				if (res.status == NFS4ERR_BADOWNER)
3901 					nfs4_log_badowner(VTOMI4(vp),
3902 					    OP_SETATTR);
3903 
3904 				e.error = geterrno4(res.status);
3905 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3906 								(caddr_t)&res);
3907 			}
3908 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3909 						opsetattr.obj_attributes);
3910 			if (verify_argop != -1) {
3911 				nfs4args_verify_free(&argop[verify_argop]);
3912 				verify_argop = -1;
3913 			}
3914 			if (abort == FALSE) {
3915 				/*
3916 				 * Need to retry all possible stateids in
3917 				 * case the recovery error wasn't stateid
3918 				 * related or the stateids have become
3919 				 * stale (server reboot).
3920 				 */
3921 				nfs4_init_stateid_types(&sid_types);
3922 				goto recov_retry;
3923 			}
3924 			return (e.error);
3925 		}
3926 
3927 		/*
3928 		 * Need to call nfs4_end_op before nfs4getattr to
3929 		 * avoid potential nfs4_start_op deadlock. See RFE
3930 		 * 4777612.  Calls to nfs4_invalidate_pages() and
3931 		 * nfs4_purge_stale_fh() might also generate over the
3932 		 * wire calls which my cause nfs4_start_op() deadlock.
3933 		 */
3934 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3935 
3936 		/*
3937 		 * Check to update lease.
3938 		 */
3939 		resp = &res;
3940 		if (res.status == NFS4_OK) {
3941 			break;
3942 		}
3943 
3944 		/*
3945 		 * Check if verify failed to see if try again
3946 		 */
3947 		if ((verify_argop == -1) || (res.array_len != 3)) {
3948 			/*
3949 			 * can't continue...
3950 			 */
3951 			if (res.status == NFS4ERR_BADOWNER)
3952 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
3953 
3954 			e.error = geterrno4(res.status);
3955 		} else {
3956 			/*
3957 			 * When the verify request fails, the client ctime is
3958 			 * not in sync with the server. This is the same as
3959 			 * the version 3 "not synchronized" error, and we
3960 			 * handle it in a similar manner (XXX do we need to???).
3961 			 * Use the ctime returned in the first getattr for
3962 			 * the input to the next verify.
3963 			 * If we couldn't get the attributes, then we give up
3964 			 * because we can't complete the operation as required.
3965 			 */
3966 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
3967 		}
3968 		if (e.error) {
3969 			PURGE_ATTRCACHE4(vp);
3970 			nfs4_purge_stale_fh(e.error, vp, cr);
3971 		} else {
3972 			/*
3973 			 * retry with a new verify value
3974 			 */
3975 			ctime = garp->n4g_va.va_ctime;
3976 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3977 			resp = NULL;
3978 		}
3979 		if (!e.error) {
3980 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3981 						opsetattr.obj_attributes);
3982 			if (verify_argop != -1) {
3983 				nfs4args_verify_free(&argop[verify_argop]);
3984 				verify_argop = -1;
3985 			}
3986 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3987 			goto do_again;
3988 		}
3989 	} while (!e.error);
3990 
3991 	if (e.error) {
3992 		/*
3993 		 * If we are here, rfs4call has an irrecoverable error - return
3994 		 */
3995 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3996 						opsetattr.obj_attributes);
3997 		if (verify_argop != -1) {
3998 			nfs4args_verify_free(&argop[verify_argop]);
3999 			verify_argop = -1;
4000 		}
4001 		if (resp)
4002 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4003 		return (e.error);
4004 	}
4005 
4006 
4007 
4008 	/*
4009 	 * If changing the size of the file, invalidate
4010 	 * any local cached data which is no longer part
4011 	 * of the file.  We also possibly invalidate the
4012 	 * last page in the file.  We could use
4013 	 * pvn_vpzero(), but this would mark the page as
4014 	 * modified and require it to be written back to
4015 	 * the server for no particularly good reason.
4016 	 * This way, if we access it, then we bring it
4017 	 * back in.  A read should be cheaper than a
4018 	 * write.
4019 	 */
4020 	if (mask & AT_SIZE) {
4021 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
4022 	}
4023 
4024 	/* either no error or one of the postop getattr failed */
4025 
4026 	/*
4027 	 * XXX Perform a simplified version of wcc checking. Instead of
4028 	 * have another getattr to get pre-op, just purge cache if
4029 	 * any of the ops prior to and including the getattr failed.
4030 	 * If the getattr succeeded then update the attrcache accordingly.
4031 	 */
4032 
4033 	garp = NULL;
4034 	if (res.status == NFS4_OK) {
4035 		/*
4036 		 * Last getattr
4037 		 */
4038 		resop = &res.array[numops - 1];
4039 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4040 	}
4041 	/*
4042 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
4043 	 * rather than filling it.  See the function itself for details.
4044 	 */
4045 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4046 	if (garp != NULL) {
4047 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
4048 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
4049 			vs_ace4_destroy(&garp->n4g_vsa);
4050 		} else {
4051 			if (vsap != NULL) {
4052 				/*
4053 				 * The ACL was supposed to be set and to be
4054 				 * returned in the last getattr of this
4055 				 * compound, but for some reason the getattr
4056 				 * result doesn't contain the ACL.  In this
4057 				 * case, purge the ACL cache.
4058 				 */
4059 				if (rp->r_secattr != NULL) {
4060 					mutex_enter(&rp->r_statelock);
4061 					vsp = rp->r_secattr;
4062 					rp->r_secattr = NULL;
4063 					mutex_exit(&rp->r_statelock);
4064 					if (vsp != NULL)
4065 						nfs4_acl_free_cache(vsp);
4066 				}
4067 			}
4068 		}
4069 	}
4070 
4071 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4072 		/*
4073 		 * Set the size, rather than relying on getting it updated
4074 		 * via a GETATTR.  With delegations the client tries to
4075 		 * suppress GETATTR calls.
4076 		 */
4077 		mutex_enter(&rp->r_statelock);
4078 		rp->r_size = vap->va_size;
4079 		mutex_exit(&rp->r_statelock);
4080 	}
4081 
4082 	/*
4083 	 * Can free up request args and res
4084 	 */
4085 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4086 						opsetattr.obj_attributes);
4087 	if (verify_argop != -1) {
4088 		nfs4args_verify_free(&argop[verify_argop]);
4089 		verify_argop = -1;
4090 	}
4091 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4092 
4093 	/*
4094 	 * Some servers will change the mode to clear the setuid
4095 	 * and setgid bits when changing the uid or gid.  The
4096 	 * client needs to compensate appropriately.
4097 	 */
4098 	if (mask & (AT_UID | AT_GID)) {
4099 		int terror, do_setattr;
4100 
4101 		do_setattr = 0;
4102 		va.va_mask = AT_MODE;
4103 		terror = nfs4getattr(vp, &va, cr);
4104 		if (!terror &&
4105 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4106 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4107 			va.va_mask = AT_MODE;
4108 			if (mask & AT_MODE) {
4109 				/*
4110 				 * We asked the mode to be changed and what
4111 				 * we just got from the server in getattr is
4112 				 * not what we wanted it to be, so set it now.
4113 				 */
4114 				va.va_mode = vap->va_mode;
4115 				do_setattr = 1;
4116 			} else {
4117 				/*
4118 				 * We did not ask the mode to be changed,
4119 				 * Check to see that the server just cleared
4120 				 * I_SUID and I_GUID from it. If not then
4121 				 * set mode to omode with UID/GID cleared.
4122 				 */
4123 				if (nfs4_compare_modes(va.va_mode, omode)) {
4124 					omode &= ~(S_ISUID|S_ISGID);
4125 					va.va_mode = omode;
4126 					do_setattr = 1;
4127 				}
4128 			}
4129 
4130 			if (do_setattr)
4131 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4132 		}
4133 	}
4134 
4135 	return (e.error);
4136 }
4137 
4138 /* ARGSUSED */
4139 static int
4140 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr)
4141 {
4142 	COMPOUND4args_clnt args;
4143 	COMPOUND4res_clnt res;
4144 	int doqueue;
4145 	uint32_t acc, resacc, argacc;
4146 	rnode4_t *rp;
4147 	cred_t *cred, *ncr, *ncrfree = NULL;
4148 	nfs4_access_type_t cacc;
4149 	int num_ops;
4150 	nfs_argop4 argop[3];
4151 	nfs_resop4 *resop;
4152 	bool_t needrecov = FALSE, do_getattr;
4153 	nfs4_recov_state_t recov_state;
4154 	int rpc_error;
4155 	hrtime_t t;
4156 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4157 	mntinfo4_t *mi = VTOMI4(vp);
4158 
4159 	if (nfs_zone() != mi->mi_zone)
4160 		return (EIO);
4161 
4162 	acc = 0;
4163 	if (mode & VREAD)
4164 		acc |= ACCESS4_READ;
4165 	if (mode & VWRITE) {
4166 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4167 			return (EROFS);
4168 		if (vp->v_type == VDIR)
4169 			acc |= ACCESS4_DELETE;
4170 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4171 	}
4172 	if (mode & VEXEC) {
4173 		if (vp->v_type == VDIR)
4174 			acc |= ACCESS4_LOOKUP;
4175 		else
4176 			acc |= ACCESS4_EXECUTE;
4177 	}
4178 
4179 	if (VTOR4(vp)->r_acache != NULL) {
4180 		e.error = nfs4_validate_caches(vp, cr);
4181 		if (e.error)
4182 			return (e.error);
4183 	}
4184 
4185 	rp = VTOR4(vp);
4186 	if (vp->v_type == VDIR) {
4187 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4188 			ACCESS4_EXTEND | ACCESS4_LOOKUP;
4189 	} else {
4190 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4191 			ACCESS4_EXECUTE;
4192 	}
4193 	recov_state.rs_flags = 0;
4194 	recov_state.rs_num_retry_despite_err = 0;
4195 
4196 	cred = cr;
4197 	/*
4198 	 * ncr and ncrfree both initially
4199 	 * point to the memory area returned
4200 	 * by crnetadjust();
4201 	 * ncrfree not NULL when exiting means
4202 	 * that we need to release it
4203 	 */
4204 	ncr = crnetadjust(cred);
4205 	ncrfree = ncr;
4206 
4207 tryagain:
4208 	cacc = nfs4_access_check(rp, acc, cred);
4209 	if (cacc == NFS4_ACCESS_ALLOWED) {
4210 		if (ncrfree != NULL)
4211 			crfree(ncrfree);
4212 		return (0);
4213 	}
4214 	if (cacc == NFS4_ACCESS_DENIED) {
4215 		/*
4216 		 * If the cred can be adjusted, try again
4217 		 * with the new cred.
4218 		 */
4219 		if (ncr != NULL) {
4220 			cred = ncr;
4221 			ncr = NULL;
4222 			goto tryagain;
4223 		}
4224 		if (ncrfree != NULL)
4225 			crfree(ncrfree);
4226 		return (EACCES);
4227 	}
4228 
4229 recov_retry:
4230 	/*
4231 	 * Don't take with r_statev4_lock here. r_deleg_type could
4232 	 * change as soon as lock is released.  Since it is an int,
4233 	 * there is no atomicity issue.
4234 	 */
4235 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4236 	num_ops = do_getattr ? 3 : 2;
4237 
4238 	args.ctag = TAG_ACCESS;
4239 
4240 	args.array_len = num_ops;
4241 	args.array = argop;
4242 
4243 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4244 					&recov_state, NULL)) {
4245 		if (ncrfree != NULL)
4246 			crfree(ncrfree);
4247 		return (e.error);
4248 	}
4249 
4250 	/* putfh target fh */
4251 	argop[0].argop = OP_CPUTFH;
4252 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4253 
4254 	/* access */
4255 	argop[1].argop = OP_ACCESS;
4256 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4257 
4258 	/* getattr */
4259 	if (do_getattr) {
4260 		argop[2].argop = OP_GETATTR;
4261 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4262 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4263 	}
4264 
4265 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4266 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4267 	    rnode4info(VTOR4(vp))));
4268 
4269 	doqueue = 1;
4270 	t = gethrtime();
4271 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4272 	rpc_error = e.error;
4273 
4274 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4275 	if (needrecov) {
4276 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4277 		    "nfs4_access: initiating recovery\n"));
4278 
4279 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4280 		    NULL, OP_ACCESS, NULL) == FALSE) {
4281 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4282 			    &recov_state, needrecov);
4283 			if (!e.error)
4284 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4285 						(caddr_t)&res);
4286 			goto recov_retry;
4287 		}
4288 	}
4289 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4290 
4291 	if (e.error)
4292 		goto out;
4293 
4294 	if (res.status) {
4295 		e.error = geterrno4(res.status);
4296 		/*
4297 		 * This might generate over the wire calls throught
4298 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4299 		 * here to avoid a deadlock.
4300 		 */
4301 		nfs4_purge_stale_fh(e.error, vp, cr);
4302 		goto out;
4303 	}
4304 	resop = &res.array[1];	/* access res */
4305 
4306 	resacc = resop->nfs_resop4_u.opaccess.access;
4307 
4308 	if (do_getattr) {
4309 		resop++;	/* getattr res */
4310 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4311 				t, cr, FALSE, NULL);
4312 	}
4313 
4314 	if (!e.error) {
4315 		nfs4_access_cache(rp, argacc, resacc, cred);
4316 		/*
4317 		 * we just cached results with cred; if cred is the
4318 		 * adjusted credentials from crnetadjust, we do not want
4319 		 * to release them before exiting: hence setting ncrfree
4320 		 * to NULL
4321 		 */
4322 		if (cred != cr)
4323 			ncrfree = NULL;
4324 		/* XXX check the supported bits too? */
4325 		if ((acc & resacc) != acc) {
4326 			/*
4327 			 * The following code implements the semantic
4328 			 * that a setuid root program has *at least* the
4329 			 * permissions of the user that is running the
4330 			 * program.  See rfs3call() for more portions
4331 			 * of the implementation of this functionality.
4332 			 */
4333 			/* XXX-LP */
4334 			if (ncr != NULL) {
4335 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4336 						(caddr_t)&res);
4337 				cred = ncr;
4338 				ncr = NULL;
4339 				goto tryagain;
4340 			}
4341 			e.error = EACCES;
4342 		}
4343 	}
4344 
4345 out:
4346 	if (!rpc_error)
4347 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4348 
4349 	if (ncrfree != NULL)
4350 		crfree(ncrfree);
4351 
4352 	return (e.error);
4353 }
4354 
4355 static int
4356 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr)
4357 {
4358 	COMPOUND4args_clnt args;
4359 	COMPOUND4res_clnt res;
4360 	int doqueue;
4361 	rnode4_t *rp;
4362 	nfs_argop4 argop[3];
4363 	nfs_resop4 *resop;
4364 	READLINK4res *lr_res;
4365 	nfs4_ga_res_t *garp;
4366 	uint_t len;
4367 	char *linkdata;
4368 	bool_t needrecov = FALSE;
4369 	nfs4_recov_state_t recov_state;
4370 	hrtime_t t;
4371 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4372 
4373 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4374 		return (EIO);
4375 	/*
4376 	 * Can't readlink anything other than a symbolic link.
4377 	 */
4378 	if (vp->v_type != VLNK)
4379 		return (EINVAL);
4380 
4381 	rp = VTOR4(vp);
4382 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4383 		e.error = nfs4_validate_caches(vp, cr);
4384 		if (e.error)
4385 			return (e.error);
4386 		mutex_enter(&rp->r_statelock);
4387 		if (rp->r_symlink.contents != NULL) {
4388 			e.error = uiomove(rp->r_symlink.contents,
4389 			    rp->r_symlink.len, UIO_READ, uiop);
4390 			mutex_exit(&rp->r_statelock);
4391 			return (e.error);
4392 		}
4393 		mutex_exit(&rp->r_statelock);
4394 	}
4395 	recov_state.rs_flags = 0;
4396 	recov_state.rs_num_retry_despite_err = 0;
4397 
4398 recov_retry:
4399 	args.array_len = 3;
4400 	args.array = argop;
4401 	args.ctag = TAG_READLINK;
4402 
4403 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4404 	if (e.error) {
4405 		return (e.error);
4406 	}
4407 
4408 	/* 0. putfh symlink fh */
4409 	argop[0].argop = OP_CPUTFH;
4410 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4411 
4412 	/* 1. readlink */
4413 	argop[1].argop = OP_READLINK;
4414 
4415 	/* 2. getattr */
4416 	argop[2].argop = OP_GETATTR;
4417 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4418 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4419 
4420 	doqueue = 1;
4421 
4422 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4423 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4424 	    rnode4info(VTOR4(vp))));
4425 
4426 	t = gethrtime();
4427 
4428 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4429 
4430 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4431 	if (needrecov) {
4432 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4433 		    "nfs4_readlink: initiating recovery\n"));
4434 
4435 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4436 		    NULL, OP_READLINK, NULL) == FALSE) {
4437 			if (!e.error)
4438 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4439 								(caddr_t)&res);
4440 
4441 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4442 			    needrecov);
4443 			goto recov_retry;
4444 		}
4445 	}
4446 
4447 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4448 
4449 	if (e.error)
4450 		return (e.error);
4451 
4452 	/*
4453 	 * There is an path in the code below which calls
4454 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4455 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4456 	 * here to avoid nfs4_start_op() deadlock.
4457 	 */
4458 
4459 	if (res.status && (res.array_len < args.array_len)) {
4460 		/*
4461 		 * either Putfh or Link failed
4462 		 */
4463 		e.error = geterrno4(res.status);
4464 		nfs4_purge_stale_fh(e.error, vp, cr);
4465 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4466 		return (e.error);
4467 	}
4468 
4469 	resop = &res.array[1];	/* readlink res */
4470 	lr_res = &resop->nfs_resop4_u.opreadlink;
4471 
4472 	/*
4473 	 * treat symlink names as data
4474 	 */
4475 	linkdata = utf8_to_str(&lr_res->link, &len, NULL);
4476 	if (linkdata != NULL) {
4477 		int uio_len = len - 1;
4478 		/* len includes null byte, which we won't uiomove */
4479 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4480 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4481 			mutex_enter(&rp->r_statelock);
4482 			if (rp->r_symlink.contents == NULL) {
4483 				rp->r_symlink.contents = linkdata;
4484 				rp->r_symlink.len = uio_len;
4485 				rp->r_symlink.size = len;
4486 				mutex_exit(&rp->r_statelock);
4487 			} else {
4488 				mutex_exit(&rp->r_statelock);
4489 				kmem_free(linkdata, len);
4490 			}
4491 		} else {
4492 			kmem_free(linkdata, len);
4493 		}
4494 	}
4495 	if (res.status == NFS4_OK) {
4496 		resop++;	/* getattr res */
4497 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4498 	}
4499 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4500 
4501 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4502 
4503 	/*
4504 	 * The over the wire error for attempting to readlink something
4505 	 * other than a symbolic link is ENXIO.  However, we need to
4506 	 * return EINVAL instead of ENXIO, so we map it here.
4507 	 */
4508 	return (e.error == ENXIO ? EINVAL : e.error);
4509 }
4510 
4511 /*
4512  * Flush local dirty pages to stable storage on the server.
4513  *
4514  * If FNODSYNC is specified, then there is nothing to do because
4515  * metadata changes are not cached on the client before being
4516  * sent to the server.
4517  */
4518 static int
4519 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr)
4520 {
4521 	int error;
4522 
4523 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4524 		return (0);
4525 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4526 		return (EIO);
4527 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4528 	if (!error)
4529 		error = VTOR4(vp)->r_error;
4530 	return (error);
4531 }
4532 
4533 /*
4534  * Weirdness: if the file was removed or the target of a rename
4535  * operation while it was open, it got renamed instead.  Here we
4536  * remove the renamed file.
4537  */
4538 static void
4539 nfs4_inactive(vnode_t *vp, cred_t *cr)
4540 {
4541 	rnode4_t *rp;
4542 
4543 	ASSERT(vp != DNLC_NO_VNODE);
4544 
4545 	rp = VTOR4(vp);
4546 
4547 	if (IS_SHADOW(vp, rp)) {
4548 		sv_inactive(vp);
4549 		return;
4550 	}
4551 
4552 	/*
4553 	 * If this is coming from the wrong zone, we let someone in the right
4554 	 * zone take care of it asynchronously.  We can get here due to
4555 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4556 	 * potentially turn into an expensive no-op if, for instance, v_count
4557 	 * gets incremented in the meantime, but it's still correct.
4558 	 */
4559 	if (nfs_zone() != VTOMI4(vp)->mi_zone) {
4560 		nfs4_async_inactive(vp, cr);
4561 		return;
4562 	}
4563 
4564 	/*
4565 	 * Some of the cleanup steps might require over-the-wire
4566 	 * operations.  Since VOP_INACTIVE can get called as a result of
4567 	 * other over-the-wire operations (e.g., an attribute cache update
4568 	 * can lead to a DNLC purge), doing those steps now would lead to a
4569 	 * nested call to the recovery framework, which can deadlock.  So
4570 	 * do any over-the-wire cleanups asynchronously, in a separate
4571 	 * thread.
4572 	 */
4573 
4574 	mutex_enter(&rp->r_os_lock);
4575 	mutex_enter(&rp->r_statelock);
4576 	mutex_enter(&rp->r_statev4_lock);
4577 
4578 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4579 		mutex_exit(&rp->r_statev4_lock);
4580 		mutex_exit(&rp->r_statelock);
4581 		mutex_exit(&rp->r_os_lock);
4582 		nfs4_async_inactive(vp, cr);
4583 		return;
4584 	}
4585 
4586 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4587 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4588 		mutex_exit(&rp->r_statev4_lock);
4589 		mutex_exit(&rp->r_statelock);
4590 		mutex_exit(&rp->r_os_lock);
4591 		nfs4_async_inactive(vp, cr);
4592 		return;
4593 	}
4594 
4595 	if (rp->r_unldvp != NULL) {
4596 		mutex_exit(&rp->r_statev4_lock);
4597 		mutex_exit(&rp->r_statelock);
4598 		mutex_exit(&rp->r_os_lock);
4599 		nfs4_async_inactive(vp, cr);
4600 		return;
4601 	}
4602 	mutex_exit(&rp->r_statev4_lock);
4603 	mutex_exit(&rp->r_statelock);
4604 	mutex_exit(&rp->r_os_lock);
4605 
4606 	rp4_addfree(rp, cr);
4607 }
4608 
4609 /*
4610  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4611  * various bits of state.  The caller must not refer to vp after this call.
4612  */
4613 
4614 void
4615 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4616 {
4617 	rnode4_t *rp = VTOR4(vp);
4618 	nfs4_recov_state_t recov_state;
4619 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4620 	vnode_t *unldvp;
4621 	char *unlname;
4622 	cred_t *unlcred;
4623 	COMPOUND4args_clnt args;
4624 	COMPOUND4res_clnt res, *resp;
4625 	nfs_argop4 argop[2];
4626 	int doqueue;
4627 #ifdef DEBUG
4628 	char *name;
4629 #endif
4630 
4631 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
4632 	ASSERT(!IS_SHADOW(vp, rp));
4633 
4634 #ifdef DEBUG
4635 	name = fn_name(VTOSV(vp)->sv_name);
4636 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4637 		"release vnode %s", name));
4638 	kmem_free(name, MAXNAMELEN);
4639 #endif
4640 
4641 	if (vp->v_type == VREG) {
4642 		bool_t recov_failed = FALSE;
4643 
4644 		e.error = nfs4close_all(vp, cr);
4645 		if (e.error) {
4646 			/* Check to see if recovery failed */
4647 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4648 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4649 				recov_failed = TRUE;
4650 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4651 			if (!recov_failed) {
4652 				mutex_enter(&rp->r_statelock);
4653 				if (rp->r_flags & R4RECOVERR)
4654 					recov_failed = TRUE;
4655 				mutex_exit(&rp->r_statelock);
4656 			}
4657 			if (recov_failed) {
4658 				NFS4_DEBUG(nfs4_client_recov_debug,
4659 					    (CE_NOTE, "nfs4_inactive_otw: "
4660 					    "close failed (recovery failure)"));
4661 			}
4662 		}
4663 	}
4664 
4665 redo:
4666 	if (rp->r_unldvp == NULL) {
4667 		rp4_addfree(rp, cr);
4668 		return;
4669 	}
4670 
4671 	/*
4672 	 * Save the vnode pointer for the directory where the
4673 	 * unlinked-open file got renamed, then set it to NULL
4674 	 * to prevent another thread from getting here before
4675 	 * we're done with the remove.  While we have the
4676 	 * statelock, make local copies of the pertinent rnode
4677 	 * fields.  If we weren't to do this in an atomic way, the
4678 	 * the unl* fields could become inconsistent with respect
4679 	 * to each other due to a race condition between this
4680 	 * code and nfs_remove().  See bug report 1034328.
4681 	 */
4682 	mutex_enter(&rp->r_statelock);
4683 	if (rp->r_unldvp == NULL) {
4684 		mutex_exit(&rp->r_statelock);
4685 		rp4_addfree(rp, cr);
4686 		return;
4687 	}
4688 
4689 	unldvp = rp->r_unldvp;
4690 	rp->r_unldvp = NULL;
4691 	unlname = rp->r_unlname;
4692 	rp->r_unlname = NULL;
4693 	unlcred = rp->r_unlcred;
4694 	rp->r_unlcred = NULL;
4695 	mutex_exit(&rp->r_statelock);
4696 
4697 	/*
4698 	 * If there are any dirty pages left, then flush
4699 	 * them.  This is unfortunate because they just
4700 	 * may get thrown away during the remove operation,
4701 	 * but we have to do this for correctness.
4702 	 */
4703 	if (nfs4_has_pages(vp) &&
4704 			    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4705 		ASSERT(vp->v_type != VCHR);
4706 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr);
4707 		if (e.error) {
4708 			mutex_enter(&rp->r_statelock);
4709 			if (!rp->r_error)
4710 				rp->r_error = e.error;
4711 			mutex_exit(&rp->r_statelock);
4712 		}
4713 	}
4714 
4715 	recov_state.rs_flags = 0;
4716 	recov_state.rs_num_retry_despite_err = 0;
4717 recov_retry_remove:
4718 	/*
4719 	 * Do the remove operation on the renamed file
4720 	 */
4721 	args.ctag = TAG_INACTIVE;
4722 
4723 	/*
4724 	 * Remove ops: putfh dir; remove
4725 	 */
4726 	args.array_len = 2;
4727 	args.array = argop;
4728 
4729 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4730 	if (e.error) {
4731 		kmem_free(unlname, MAXNAMELEN);
4732 		crfree(unlcred);
4733 		VN_RELE(unldvp);
4734 		/*
4735 		 * Try again; this time around r_unldvp will be NULL, so we'll
4736 		 * just call rp4_addfree() and return.
4737 		 */
4738 		goto redo;
4739 	}
4740 
4741 	/* putfh directory */
4742 	argop[0].argop = OP_CPUTFH;
4743 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4744 
4745 	/* remove */
4746 	argop[1].argop = OP_CREMOVE;
4747 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4748 
4749 	doqueue = 1;
4750 	resp = &res;
4751 
4752 #if 0 /* notyet */
4753 	/*
4754 	 * Can't do this yet.  We may be being called from
4755 	 * dnlc_purge_XXX while that routine is holding a
4756 	 * mutex lock to the nc_rele list.  The calls to
4757 	 * nfs3_cache_wcc_data may result in calls to
4758 	 * dnlc_purge_XXX.  This will result in a deadlock.
4759 	 */
4760 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4761 	if (e.error) {
4762 		PURGE_ATTRCACHE4(unldvp);
4763 		resp = NULL;
4764 	} else if (res.status) {
4765 		e.error = geterrno4(res.status);
4766 		PURGE_ATTRCACHE4(unldvp);
4767 		/*
4768 		 * This code is inactive right now
4769 		 * but if made active there should
4770 		 * be a nfs4_end_op() call before
4771 		 * nfs4_purge_stale_fh to avoid start_op()
4772 		 * deadlock. See BugId: 4948726
4773 		 */
4774 		nfs4_purge_stale_fh(error, unldvp, cr);
4775 	} else {
4776 		nfs_resop4 *resop;
4777 		REMOVE4res *rm_res;
4778 
4779 		resop = &res.array[1];
4780 		rm_res = &resop->nfs_resop4_u.opremove;
4781 		/*
4782 		 * Update directory cache attribute,
4783 		 * readdir and dnlc caches.
4784 		 */
4785 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4786 	}
4787 #else
4788 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4789 
4790 	PURGE_ATTRCACHE4(unldvp);
4791 #endif
4792 
4793 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4794 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4795 		    NULL, NULL, OP_REMOVE, NULL) == FALSE) {
4796 			if (!e.error)
4797 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4798 								(caddr_t)&res);
4799 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4800 							&recov_state, TRUE);
4801 			goto recov_retry_remove;
4802 		}
4803 	}
4804 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4805 
4806 	/*
4807 	 * Release stuff held for the remove
4808 	 */
4809 	VN_RELE(unldvp);
4810 	if (!e.error && resp)
4811 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4812 
4813 	kmem_free(unlname, MAXNAMELEN);
4814 	crfree(unlcred);
4815 	goto redo;
4816 }
4817 
4818 /*
4819  * Remote file system operations having to do with directory manipulation.
4820  */
4821 /* ARGSUSED3 */
4822 static int
4823 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4824 	int flags, vnode_t *rdir, cred_t *cr)
4825 {
4826 	int error;
4827 	vnode_t *vp, *avp = NULL;
4828 	rnode4_t *drp;
4829 
4830 	*vpp = NULL;
4831 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4832 		return (EPERM);
4833 	/*
4834 	 * if LOOKUP_XATTR, must replace dvp (object) with
4835 	 * object's attrdir before continuing with lookup
4836 	 */
4837 	if (flags & LOOKUP_XATTR) {
4838 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4839 		if (error)
4840 			return (error);
4841 
4842 		dvp = avp;
4843 
4844 		/*
4845 		 * If lookup is for "", just return dvp now.  The attrdir
4846 		 * has already been activated (from nfs4lookup_xattr), and
4847 		 * the caller will RELE the original dvp -- not
4848 		 * the attrdir.  So, set vpp and return.
4849 		 * Currently, when the LOOKUP_XATTR flag is
4850 		 * passed to VOP_LOOKUP, the name is always empty, and
4851 		 * shortcircuiting here avoids 3 unneeded lock/unlock
4852 		 * pairs.
4853 		 *
4854 		 * If a non-empty name was provided, then it is the
4855 		 * attribute name, and it will be looked up below.
4856 		 */
4857 		if (*nm == '\0') {
4858 			*vpp = dvp;
4859 			return (0);
4860 		}
4861 
4862 		/*
4863 		 * The vfs layer never sends a name when asking for the
4864 		 * attrdir, so we should never get here (unless of course
4865 		 * name is passed at some time in future -- at which time
4866 		 * we'll blow up here).
4867 		 */
4868 		ASSERT(0);
4869 	}
4870 
4871 	drp = VTOR4(dvp);
4872 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4873 		return (EINTR);
4874 
4875 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
4876 	nfs_rw_exit(&drp->r_rwlock);
4877 
4878 	/*
4879 	 * If vnode is a device, create special vnode.
4880 	 */
4881 	if (!error && ISVDEV((*vpp)->v_type)) {
4882 		vp = *vpp;
4883 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
4884 		VN_RELE(vp);
4885 	}
4886 
4887 	return (error);
4888 }
4889 
4890 /* ARGSUSED */
4891 static int
4892 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
4893 {
4894 	int error;
4895 	rnode4_t *drp;
4896 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
4897 	mntinfo4_t *mi;
4898 
4899 	mi = VTOMI4(dvp);
4900 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR))
4901 		return (EINVAL);
4902 
4903 	drp = VTOR4(dvp);
4904 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4905 		return (EINTR);
4906 
4907 	mutex_enter(&drp->r_statelock);
4908 	/*
4909 	 * If the server doesn't support xattrs just return EINVAL
4910 	 */
4911 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
4912 		mutex_exit(&drp->r_statelock);
4913 		nfs_rw_exit(&drp->r_rwlock);
4914 		return (EINVAL);
4915 	}
4916 
4917 	/*
4918 	 * If there is a cached xattr directory entry,
4919 	 * use it as long as the attributes are valid. If the
4920 	 * attributes are not valid, take the simple approach and
4921 	 * free the cached value and re-fetch a new value.
4922 	 *
4923 	 * We don't negative entry cache for now, if we did we
4924 	 * would need to check if the file has changed on every
4925 	 * lookup. But xattrs don't exist very often and failing
4926 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
4927 	 * so do an openattr over the wire for now.
4928 	 */
4929 	if (drp->r_xattr_dir != NULL) {
4930 		if (ATTRCACHE4_VALID(dvp)) {
4931 			VN_HOLD(drp->r_xattr_dir);
4932 			*vpp = drp->r_xattr_dir;
4933 			mutex_exit(&drp->r_statelock);
4934 			nfs_rw_exit(&drp->r_rwlock);
4935 			return (0);
4936 		}
4937 		VN_RELE(drp->r_xattr_dir);
4938 		drp->r_xattr_dir = NULL;
4939 	}
4940 	mutex_exit(&drp->r_statelock);
4941 
4942 	error = nfs4openattr(dvp, vpp, cflag, cr);
4943 
4944 	nfs_rw_exit(&drp->r_rwlock);
4945 
4946 	return (error);
4947 }
4948 
4949 static int
4950 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
4951 {
4952 	int error;
4953 	rnode4_t *drp;
4954 
4955 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
4956 
4957 	/*
4958 	 * If lookup is for "", just return dvp.  Don't need
4959 	 * to send it over the wire, look it up in the dnlc,
4960 	 * or perform any access checks.
4961 	 */
4962 	if (*nm == '\0') {
4963 		VN_HOLD(dvp);
4964 		*vpp = dvp;
4965 		return (0);
4966 	}
4967 
4968 	/*
4969 	 * Can't do lookups in non-directories.
4970 	 */
4971 	if (dvp->v_type != VDIR)
4972 		return (ENOTDIR);
4973 
4974 	/*
4975 	 * If lookup is for ".", just return dvp.  Don't need
4976 	 * to send it over the wire or look it up in the dnlc,
4977 	 * just need to check access.
4978 	 */
4979 	if (nm[0] == '.' && nm[1] == '\0') {
4980 		error = nfs4_access(dvp, VEXEC, 0, cr);
4981 		if (error)
4982 			return (error);
4983 		VN_HOLD(dvp);
4984 		*vpp = dvp;
4985 		return (0);
4986 	}
4987 
4988 	drp = VTOR4(dvp);
4989 	if (!(drp->r_flags & R4LOOKUP)) {
4990 		mutex_enter(&drp->r_statelock);
4991 		drp->r_flags |= R4LOOKUP;
4992 		mutex_exit(&drp->r_statelock);
4993 	}
4994 
4995 	*vpp = NULL;
4996 	/*
4997 	 * Lookup this name in the DNLC.  If there is no entry
4998 	 * lookup over the wire.
4999 	 */
5000 	if (!skipdnlc)
5001 		*vpp = dnlc_lookup(dvp, nm);
5002 	if (*vpp == NULL) {
5003 		/*
5004 		 * We need to go over the wire to lookup the name.
5005 		 */
5006 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
5007 	}
5008 
5009 	/*
5010 	 * We hit on the dnlc
5011 	 */
5012 	if (*vpp != DNLC_NO_VNODE ||
5013 			    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
5014 		/*
5015 		 * But our attrs may not be valid.
5016 		 */
5017 		if (ATTRCACHE4_VALID(dvp)) {
5018 			error = nfs4_waitfor_purge_complete(dvp);
5019 			if (error) {
5020 				VN_RELE(*vpp);
5021 				*vpp = NULL;
5022 				return (error);
5023 			}
5024 
5025 			/*
5026 			 * If after the purge completes, check to make sure
5027 			 * our attrs are still valid.
5028 			 */
5029 			if (ATTRCACHE4_VALID(dvp)) {
5030 				/*
5031 				 * If we waited for a purge we may have
5032 				 * lost our vnode so look it up again.
5033 				 */
5034 				VN_RELE(*vpp);
5035 				*vpp = dnlc_lookup(dvp, nm);
5036 				if (*vpp == NULL)
5037 					return (nfs4lookupnew_otw(dvp,
5038 						nm, vpp, cr));
5039 
5040 				/*
5041 				 * The access cache should almost always hit
5042 				 */
5043 				error = nfs4_access(dvp, VEXEC, 0, cr);
5044 
5045 				if (error) {
5046 					VN_RELE(*vpp);
5047 					*vpp = NULL;
5048 					return (error);
5049 				}
5050 				if (*vpp == DNLC_NO_VNODE) {
5051 					VN_RELE(*vpp);
5052 					*vpp = NULL;
5053 					return (ENOENT);
5054 				}
5055 				return (0);
5056 			}
5057 		}
5058 	}
5059 
5060 	ASSERT(*vpp != NULL);
5061 
5062 	/*
5063 	 * We may have gotten here we have one of the following cases:
5064 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5065 	 *		need to validate them.
5066 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5067 	 *		must validate.
5068 	 *
5069 	 * Go to the server and check if the directory has changed, if
5070 	 * it hasn't we are done and can use the dnlc entry.
5071 	 */
5072 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5073 }
5074 
5075 /*
5076  * Go to the server and check if the directory has changed, if
5077  * it hasn't we are done and can use the dnlc entry.  If it
5078  * has changed we get a new copy of its attributes and check
5079  * the access for VEXEC, then relookup the filename and
5080  * get its filehandle and attributes.
5081  *
5082  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5083  *	if the NVERIFY failed we must
5084  *		purge the caches
5085  *		cache new attributes (will set r_time_attr_inval)
5086  *		cache new access
5087  *		recheck VEXEC access
5088  *		add name to dnlc, possibly negative
5089  *		if LOOKUP succeeded
5090  *			cache new attributes
5091  *	else
5092  *		set a new r_time_attr_inval for dvp
5093  *		check to make sure we have access
5094  *
5095  * The vpp returned is the vnode passed in if the directory is valid,
5096  * a new vnode if successful lookup, or NULL on error.
5097  */
5098 static int
5099 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5100 {
5101 	COMPOUND4args_clnt args;
5102 	COMPOUND4res_clnt res;
5103 	fattr4 *ver_fattr;
5104 	fattr4_change dchange;
5105 	int32_t *ptr;
5106 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5107 	nfs_argop4 *argop;
5108 	int doqueue;
5109 	mntinfo4_t *mi;
5110 	nfs4_recov_state_t recov_state;
5111 	hrtime_t t;
5112 	int isdotdot;
5113 	vnode_t *nvp;
5114 	nfs_fh4 *fhp;
5115 	nfs4_sharedfh_t *sfhp;
5116 	nfs4_access_type_t cacc;
5117 	rnode4_t *nrp;
5118 	rnode4_t *drp = VTOR4(dvp);
5119 	nfs4_ga_res_t *garp = NULL;
5120 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5121 
5122 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5123 	ASSERT(nm != NULL);
5124 	ASSERT(nm[0] != '\0');
5125 	ASSERT(dvp->v_type == VDIR);
5126 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5127 	ASSERT(*vpp != NULL);
5128 
5129 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5130 		isdotdot = 1;
5131 		args.ctag = TAG_LOOKUP_VPARENT;
5132 	} else {
5133 		/*
5134 		 * Do not allow crossing of server mount points.  The
5135 		 * only visible entries in a SRVSTUB dir are . and ..
5136 		 * This code handles the non-.. case.  We can't even get
5137 		 * this far if looking up ".".
5138 		 */
5139 		if (VTOR4(dvp)->r_flags & R4SRVSTUB) {
5140 			VN_RELE(*vpp);
5141 			*vpp = NULL;
5142 			return (ENOENT);
5143 		}
5144 		isdotdot = 0;
5145 		args.ctag = TAG_LOOKUP_VALID;
5146 	}
5147 
5148 	mi = VTOMI4(dvp);
5149 	recov_state.rs_flags = 0;
5150 	recov_state.rs_num_retry_despite_err = 0;
5151 
5152 	nvp = NULL;
5153 
5154 	/* Save the original mount point security information */
5155 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5156 
5157 recov_retry:
5158 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5159 			    &recov_state, NULL);
5160 	if (e.error) {
5161 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5162 		VN_RELE(*vpp);
5163 		*vpp = NULL;
5164 		return (e.error);
5165 	}
5166 
5167 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5168 
5169 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5170 	args.array_len = 7;
5171 	args.array = argop;
5172 
5173 	/* 0. putfh file */
5174 	argop[0].argop = OP_CPUTFH;
5175 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5176 
5177 	/* 1. nverify the change info */
5178 	argop[1].argop = OP_NVERIFY;
5179 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5180 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5181 	ver_fattr->attrlist4 = (char *)&dchange;
5182 	ptr = (int32_t *)&dchange;
5183 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5184 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5185 
5186 	/* 2. getattr directory */
5187 	argop[2].argop = OP_GETATTR;
5188 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5189 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5190 
5191 	/* 3. access directory */
5192 	argop[3].argop = OP_ACCESS;
5193 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5194 			ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5195 
5196 	/* 4. lookup name */
5197 	if (isdotdot) {
5198 		argop[4].argop = OP_LOOKUPP;
5199 	} else {
5200 		argop[4].argop = OP_CLOOKUP;
5201 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5202 	}
5203 
5204 	/* 5. resulting file handle */
5205 	argop[5].argop = OP_GETFH;
5206 
5207 	/* 6. resulting file attributes */
5208 	argop[6].argop = OP_GETATTR;
5209 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5210 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5211 
5212 	doqueue = 1;
5213 	t = gethrtime();
5214 
5215 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5216 
5217 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5218 		/*
5219 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5220 		 * from this thread, do not go thru the recovery thread since
5221 		 * we need the nm information.
5222 		 *
5223 		 * Not doing dotdot case because there is no specification
5224 		 * for (PUTFH, SECINFO "..") yet.
5225 		 */
5226 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5227 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr))) {
5228 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5229 					&recov_state, FALSE);
5230 			} else {
5231 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5232 					&recov_state, TRUE);
5233 			}
5234 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5235 			kmem_free(argop, argoplist_size);
5236 			if (!e.error)
5237 				goto recov_retry;
5238 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5239 			VN_RELE(*vpp);
5240 			*vpp = NULL;
5241 			return (e.error);
5242 		}
5243 
5244 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5245 		    OP_LOOKUP, NULL) == FALSE) {
5246 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5247 				&recov_state, TRUE);
5248 
5249 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5250 			kmem_free(argop, argoplist_size);
5251 			goto recov_retry;
5252 		}
5253 	}
5254 
5255 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5256 
5257 	if (e.error || res.array_len == 0) {
5258 		/*
5259 		 * If e.error isn't set, then reply has no ops (or we couldn't
5260 		 * be here).  The only legal way to reply without an op array
5261 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5262 		 * be in the reply for all other status values.
5263 		 *
5264 		 * For valid replies without an ops array, return ENOTSUP
5265 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5266 		 * return EIO -- don't trust status.
5267 		 */
5268 		if (e.error == 0)
5269 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5270 				ENOTSUP : EIO;
5271 		VN_RELE(*vpp);
5272 		*vpp = NULL;
5273 		kmem_free(argop, argoplist_size);
5274 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5275 		return (e.error);
5276 	}
5277 
5278 	if (res.status != NFS4ERR_SAME) {
5279 		e.error = geterrno4(res.status);
5280 
5281 		/*
5282 		 * The NVERIFY "failed" so the directory has changed
5283 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5284 		 * cleanly.
5285 		 */
5286 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5287 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5288 			nfs4_purge_stale_fh(e.error, dvp, cr);
5289 			VN_RELE(*vpp);
5290 			*vpp = NULL;
5291 			goto exit;
5292 		}
5293 
5294 		/*
5295 		 * We know the NVERIFY "failed" so we must:
5296 		 *	purge the caches (access and indirectly dnlc if needed)
5297 		 */
5298 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5299 
5300 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5301 			nfs4_purge_stale_fh(e.error, dvp, cr);
5302 			VN_RELE(*vpp);
5303 			*vpp = NULL;
5304 			goto exit;
5305 		}
5306 
5307 		/*
5308 		 * Install new cached attributes for the directory
5309 		 */
5310 		nfs4_attr_cache(dvp,
5311 				&res.array[2].nfs_resop4_u.opgetattr.ga_res,
5312 				t, cr, FALSE, NULL);
5313 
5314 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5315 			nfs4_purge_stale_fh(e.error, dvp, cr);
5316 			VN_RELE(*vpp);
5317 			*vpp = NULL;
5318 			e.error = geterrno4(res.status);
5319 			goto exit;
5320 		}
5321 
5322 		/*
5323 		 * Now we know the directory is valid,
5324 		 * cache new directory access
5325 		 */
5326 		nfs4_access_cache(drp,
5327 			args.array[3].nfs_argop4_u.opaccess.access,
5328 			res.array[3].nfs_resop4_u.opaccess.access, cr);
5329 
5330 		/*
5331 		 * recheck VEXEC access
5332 		 */
5333 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5334 		if (cacc != NFS4_ACCESS_ALLOWED) {
5335 			/*
5336 			 * Directory permissions might have been revoked
5337 			 */
5338 			if (cacc == NFS4_ACCESS_DENIED) {
5339 				e.error = EACCES;
5340 				VN_RELE(*vpp);
5341 				*vpp = NULL;
5342 				goto exit;
5343 			}
5344 
5345 			/*
5346 			 * Somehow we must not have asked for enough
5347 			 * so try a singleton ACCESS, should never happen.
5348 			 */
5349 			e.error = nfs4_access(dvp, VEXEC, 0, cr);
5350 			if (e.error) {
5351 				VN_RELE(*vpp);
5352 				*vpp = NULL;
5353 				goto exit;
5354 			}
5355 		}
5356 
5357 		e.error = geterrno4(res.status);
5358 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5359 			/*
5360 			 * The lookup failed, probably no entry
5361 			 */
5362 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5363 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5364 			} else {
5365 				/*
5366 				 * Might be some other error, so remove
5367 				 * the dnlc entry to make sure we start all
5368 				 * over again, next time.
5369 				 */
5370 				dnlc_remove(dvp, nm);
5371 			}
5372 			VN_RELE(*vpp);
5373 			*vpp = NULL;
5374 			goto exit;
5375 		}
5376 
5377 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5378 			/*
5379 			 * The file exists but we can't get its fh for
5380 			 * some unknown reason.  Remove it from the dnlc
5381 			 * and error out to be safe.
5382 			 */
5383 			dnlc_remove(dvp, nm);
5384 			VN_RELE(*vpp);
5385 			*vpp = NULL;
5386 			goto exit;
5387 		}
5388 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5389 		if (fhp->nfs_fh4_len == 0) {
5390 			/*
5391 			 * The file exists but a bogus fh
5392 			 * some unknown reason.  Remove it from the dnlc
5393 			 * and error out to be safe.
5394 			 */
5395 			e.error = ENOENT;
5396 			dnlc_remove(dvp, nm);
5397 			VN_RELE(*vpp);
5398 			*vpp = NULL;
5399 			goto exit;
5400 		}
5401 		sfhp = sfh4_get(fhp, mi);
5402 
5403 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5404 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5405 
5406 		/*
5407 		 * Make the new rnode
5408 		 */
5409 		if (isdotdot) {
5410 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5411 			if (e.error) {
5412 				sfh4_rele(&sfhp);
5413 				VN_RELE(*vpp);
5414 				*vpp = NULL;
5415 				goto exit;
5416 			}
5417 			/*
5418 			 * XXX if nfs4_make_dotdot uses an existing rnode
5419 			 * XXX it doesn't update the attributes.
5420 			 * XXX for now just save them again to save an OTW
5421 			 */
5422 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5423 		} else {
5424 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5425 				dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5426 			/*
5427 			 * If v_type == VNON, then garp was NULL because
5428 			 * the last op in the compound failed and makenfs4node
5429 			 * could not find the vnode for sfhp. It created
5430 			 * a new vnode, so we have nothing to purge here.
5431 			 */
5432 			if (nvp->v_type == VNON) {
5433 				vattr_t vattr;
5434 
5435 				vattr.va_mask = AT_TYPE;
5436 				/*
5437 				 * N.B. We've already called nfs4_end_fop above.
5438 				 */
5439 				e.error = nfs4getattr(nvp, &vattr, cr);
5440 				if (e.error) {
5441 					sfh4_rele(&sfhp);
5442 					VN_RELE(*vpp);
5443 					*vpp = NULL;
5444 					VN_RELE(nvp);
5445 					goto exit;
5446 				}
5447 				nvp->v_type = vattr.va_type;
5448 			}
5449 		}
5450 		sfh4_rele(&sfhp);
5451 
5452 		nrp = VTOR4(nvp);
5453 		mutex_enter(&nrp->r_statev4_lock);
5454 		if (!nrp->created_v4) {
5455 			mutex_exit(&nrp->r_statev4_lock);
5456 			dnlc_update(dvp, nm, nvp);
5457 		} else
5458 			mutex_exit(&nrp->r_statev4_lock);
5459 
5460 		VN_RELE(*vpp);
5461 		*vpp = nvp;
5462 	} else {
5463 		hrtime_t now;
5464 		hrtime_t delta = 0;
5465 
5466 		e.error = 0;
5467 
5468 		/*
5469 		 * Because the NVERIFY "succeeded" we know that the
5470 		 * directory attributes are still valid
5471 		 * so update r_time_attr_inval
5472 		 */
5473 		now = gethrtime();
5474 		mutex_enter(&drp->r_statelock);
5475 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5476 			delta = now - drp->r_time_attr_saved;
5477 			if (delta < mi->mi_acdirmin)
5478 				delta = mi->mi_acdirmin;
5479 			else if (delta > mi->mi_acdirmax)
5480 				delta = mi->mi_acdirmax;
5481 		}
5482 		drp->r_time_attr_inval = now + delta;
5483 		mutex_exit(&drp->r_statelock);
5484 		dnlc_update(dvp, nm, *vpp);
5485 
5486 		/*
5487 		 * Even though we have a valid directory attr cache
5488 		 * and dnlc entry, we may not have access.
5489 		 * This should almost always hit the cache.
5490 		 */
5491 		e.error = nfs4_access(dvp, VEXEC, 0, cr);
5492 		if (e.error) {
5493 			VN_RELE(*vpp);
5494 			*vpp = NULL;
5495 		}
5496 
5497 		if (*vpp == DNLC_NO_VNODE) {
5498 			VN_RELE(*vpp);
5499 			*vpp = NULL;
5500 			e.error = ENOENT;
5501 		}
5502 	}
5503 
5504 exit:
5505 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5506 	kmem_free(argop, argoplist_size);
5507 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5508 	return (e.error);
5509 }
5510 
5511 /*
5512  * We need to go over the wire to lookup the name, but
5513  * while we are there verify the directory has not
5514  * changed but if it has, get new attributes and check access
5515  *
5516  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5517  *					NVERIFY GETATTR ACCESS
5518  *
5519  * With the results:
5520  *	if the NVERIFY failed we must purge the caches, add new attributes,
5521  *		and cache new access.
5522  *	set a new r_time_attr_inval
5523  *	add name to dnlc, possibly negative
5524  *	if LOOKUP succeeded
5525  *		cache new attributes
5526  */
5527 static int
5528 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5529 {
5530 	COMPOUND4args_clnt args;
5531 	COMPOUND4res_clnt res;
5532 	fattr4 *ver_fattr;
5533 	fattr4_change dchange;
5534 	int32_t *ptr;
5535 	nfs4_ga_res_t *garp = NULL;
5536 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5537 	nfs_argop4 *argop;
5538 	int doqueue;
5539 	mntinfo4_t *mi;
5540 	nfs4_recov_state_t recov_state;
5541 	hrtime_t t;
5542 	int isdotdot;
5543 	vnode_t *nvp;
5544 	nfs_fh4 *fhp;
5545 	nfs4_sharedfh_t *sfhp;
5546 	nfs4_access_type_t cacc;
5547 	rnode4_t *nrp;
5548 	rnode4_t *drp = VTOR4(dvp);
5549 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5550 
5551 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5552 	ASSERT(nm != NULL);
5553 	ASSERT(nm[0] != '\0');
5554 	ASSERT(dvp->v_type == VDIR);
5555 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5556 	ASSERT(*vpp == NULL);
5557 
5558 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5559 		isdotdot = 1;
5560 		args.ctag = TAG_LOOKUP_PARENT;
5561 	} else {
5562 		/*
5563 		 * Do not allow crossing of server mount points.  The
5564 		 * only visible entries in a SRVSTUB dir are . and ..
5565 		 * This code handles the non-.. case.  We can't even get
5566 		 * this far if looking up ".".
5567 		 */
5568 		if (VTOR4(dvp)->r_flags & R4SRVSTUB)
5569 			return (ENOENT);
5570 
5571 		isdotdot = 0;
5572 		args.ctag = TAG_LOOKUP;
5573 	}
5574 
5575 	mi = VTOMI4(dvp);
5576 	recov_state.rs_flags = 0;
5577 	recov_state.rs_num_retry_despite_err = 0;
5578 
5579 	nvp = NULL;
5580 
5581 	/* Save the original mount point security information */
5582 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5583 
5584 recov_retry:
5585 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5586 			    &recov_state, NULL);
5587 	if (e.error) {
5588 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5589 		return (e.error);
5590 	}
5591 
5592 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5593 
5594 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5595 	args.array_len = 9;
5596 	args.array = argop;
5597 
5598 	/* 0. putfh file */
5599 	argop[0].argop = OP_CPUTFH;
5600 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5601 
5602 	/* 1. savefh for the nverify */
5603 	argop[1].argop = OP_SAVEFH;
5604 
5605 	/* 2. lookup name */
5606 	if (isdotdot) {
5607 		argop[2].argop = OP_LOOKUPP;
5608 	} else {
5609 		argop[2].argop = OP_CLOOKUP;
5610 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5611 	}
5612 
5613 	/* 3. resulting file handle */
5614 	argop[3].argop = OP_GETFH;
5615 
5616 	/* 4. resulting file attributes */
5617 	argop[4].argop = OP_GETATTR;
5618 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5619 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5620 
5621 	/* 5. restorefh back the directory for the nverify */
5622 	argop[5].argop = OP_RESTOREFH;
5623 
5624 	/* 6. nverify the change info */
5625 	argop[6].argop = OP_NVERIFY;
5626 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5627 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5628 	ver_fattr->attrlist4 = (char *)&dchange;
5629 	ptr = (int32_t *)&dchange;
5630 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5631 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5632 
5633 	/* 7. getattr directory */
5634 	argop[7].argop = OP_GETATTR;
5635 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5636 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5637 
5638 	/* 8. access directory */
5639 	argop[8].argop = OP_ACCESS;
5640 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5641 			ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5642 
5643 	doqueue = 1;
5644 	t = gethrtime();
5645 
5646 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5647 
5648 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5649 		/*
5650 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5651 		 * from this thread, do not go thru the recovery thread since
5652 		 * we need the nm information.
5653 		 *
5654 		 * Not doing dotdot case because there is no specification
5655 		 * for (PUTFH, SECINFO "..") yet.
5656 		 */
5657 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5658 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr))) {
5659 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5660 					&recov_state, FALSE);
5661 			} else {
5662 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5663 					&recov_state, TRUE);
5664 			}
5665 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5666 			kmem_free(argop, argoplist_size);
5667 			if (!e.error)
5668 				goto recov_retry;
5669 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5670 			return (e.error);
5671 		}
5672 
5673 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5674 		    OP_LOOKUP, NULL) == FALSE) {
5675 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5676 				&recov_state, TRUE);
5677 
5678 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5679 			kmem_free(argop, argoplist_size);
5680 			goto recov_retry;
5681 		}
5682 	}
5683 
5684 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5685 
5686 	if (e.error || res.array_len == 0) {
5687 		/*
5688 		 * If e.error isn't set, then reply has no ops (or we couldn't
5689 		 * be here).  The only legal way to reply without an op array
5690 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5691 		 * be in the reply for all other status values.
5692 		 *
5693 		 * For valid replies without an ops array, return ENOTSUP
5694 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5695 		 * return EIO -- don't trust status.
5696 		 */
5697 		if (e.error == 0)
5698 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5699 				ENOTSUP : EIO;
5700 
5701 		kmem_free(argop, argoplist_size);
5702 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5703 		return (e.error);
5704 	}
5705 
5706 	e.error = geterrno4(res.status);
5707 
5708 	/*
5709 	 * The PUTFH and SAVEFH may have failed.
5710 	 */
5711 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5712 		    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5713 		nfs4_purge_stale_fh(e.error, dvp, cr);
5714 		goto exit;
5715 	}
5716 
5717 	/*
5718 	 * Check if the file exists, if it does delay entering
5719 	 * into the dnlc until after we update the directory
5720 	 * attributes so we don't cause it to get purged immediately.
5721 	 */
5722 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5723 		/*
5724 		 * The lookup failed, probably no entry
5725 		 */
5726 		if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5727 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5728 		}
5729 		goto exit;
5730 	}
5731 
5732 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5733 		/*
5734 		 * The file exists but we can't get its fh for
5735 		 * some unknown reason. Error out to be safe.
5736 		 */
5737 		goto exit;
5738 	}
5739 
5740 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5741 	if (fhp->nfs_fh4_len == 0) {
5742 		/*
5743 		 * The file exists but a bogus fh
5744 		 * some unknown reason.  Error out to be safe.
5745 		 */
5746 		e.error = EIO;
5747 		goto exit;
5748 	}
5749 	sfhp = sfh4_get(fhp, mi);
5750 
5751 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5752 		sfh4_rele(&sfhp);
5753 		e.error = EIO;
5754 		goto exit;
5755 	}
5756 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5757 
5758 	/*
5759 	 * The RESTOREFH may have failed
5760 	 */
5761 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5762 		sfh4_rele(&sfhp);
5763 		e.error = EIO;
5764 		goto exit;
5765 	}
5766 
5767 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5768 		/*
5769 		 * First make sure the NVERIFY failed as we expected,
5770 		 * if it didn't then be conservative and error out
5771 		 * as we can't trust the directory.
5772 		 */
5773 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5774 			sfh4_rele(&sfhp);
5775 			e.error = EIO;
5776 			goto exit;
5777 		}
5778 
5779 		/*
5780 		 * We know the NVERIFY "failed" so the directory has changed,
5781 		 * so we must:
5782 		 *	purge the caches (access and indirectly dnlc if needed)
5783 		 */
5784 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5785 
5786 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5787 			sfh4_rele(&sfhp);
5788 			goto exit;
5789 		}
5790 		nfs4_attr_cache(dvp,
5791 				&res.array[7].nfs_resop4_u.opgetattr.ga_res,
5792 				t, cr, FALSE, NULL);
5793 
5794 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5795 			nfs4_purge_stale_fh(e.error, dvp, cr);
5796 			sfh4_rele(&sfhp);
5797 			e.error = geterrno4(res.status);
5798 			goto exit;
5799 		}
5800 
5801 		/*
5802 		 * Now we know the directory is valid,
5803 		 * cache new directory access
5804 		 */
5805 		nfs4_access_cache(drp,
5806 			args.array[8].nfs_argop4_u.opaccess.access,
5807 			res.array[8].nfs_resop4_u.opaccess.access, cr);
5808 
5809 		/*
5810 		 * recheck VEXEC access
5811 		 */
5812 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5813 		if (cacc != NFS4_ACCESS_ALLOWED) {
5814 			/*
5815 			 * Directory permissions might have been revoked
5816 			 */
5817 			if (cacc == NFS4_ACCESS_DENIED) {
5818 				sfh4_rele(&sfhp);
5819 				e.error = EACCES;
5820 				goto exit;
5821 			}
5822 
5823 			/*
5824 			 * Somehow we must not have asked for enough
5825 			 * so try a singleton ACCESS should never happen
5826 			 */
5827 			e.error = nfs4_access(dvp, VEXEC, 0, cr);
5828 			if (e.error) {
5829 				sfh4_rele(&sfhp);
5830 				goto exit;
5831 			}
5832 		}
5833 
5834 		e.error = geterrno4(res.status);
5835 	} else {
5836 		hrtime_t now;
5837 		hrtime_t delta = 0;
5838 
5839 		e.error = 0;
5840 
5841 		/*
5842 		 * Because the NVERIFY "succeeded" we know that the
5843 		 * directory attributes are still valid
5844 		 * so update r_time_attr_inval
5845 		 */
5846 		now = gethrtime();
5847 		mutex_enter(&drp->r_statelock);
5848 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5849 			delta = now - drp->r_time_attr_saved;
5850 			if (delta < mi->mi_acdirmin)
5851 				delta = mi->mi_acdirmin;
5852 			else if (delta > mi->mi_acdirmax)
5853 				delta = mi->mi_acdirmax;
5854 		}
5855 		drp->r_time_attr_inval = now + delta;
5856 		mutex_exit(&drp->r_statelock);
5857 
5858 		/*
5859 		 * Even though we have a valid directory attr cache,
5860 		 * we may not have access.
5861 		 * This should almost always hit the cache.
5862 		 */
5863 		e.error = nfs4_access(dvp, VEXEC, 0, cr);
5864 		if (e.error) {
5865 			sfh4_rele(&sfhp);
5866 			goto exit;
5867 		}
5868 	}
5869 
5870 	/*
5871 	 * Now we have successfully completed the lookup, if the
5872 	 * directory has changed we now have the valid attributes.
5873 	 * We also know we have directory access.
5874 	 * Create the new rnode and insert it in the dnlc.
5875 	 */
5876 	if (isdotdot) {
5877 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5878 		if (e.error) {
5879 			sfh4_rele(&sfhp);
5880 			goto exit;
5881 		}
5882 		/*
5883 		 * XXX if nfs4_make_dotdot uses an existing rnode
5884 		 * XXX it doesn't update the attributes.
5885 		 * XXX for now just save them again to save an OTW
5886 		 */
5887 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5888 	} else {
5889 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5890 			dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5891 	}
5892 	sfh4_rele(&sfhp);
5893 
5894 	nrp = VTOR4(nvp);
5895 	mutex_enter(&nrp->r_statev4_lock);
5896 	if (!nrp->created_v4) {
5897 		mutex_exit(&nrp->r_statev4_lock);
5898 		dnlc_update(dvp, nm, nvp);
5899 	} else
5900 		mutex_exit(&nrp->r_statev4_lock);
5901 
5902 	*vpp = nvp;
5903 
5904 exit:
5905 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5906 	kmem_free(argop, argoplist_size);
5907 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5908 	return (e.error);
5909 }
5910 
5911 #ifdef DEBUG
5912 void
5913 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
5914 {
5915 	uint_t i, len;
5916 	zoneid_t zoneid = getzoneid();
5917 	char *s;
5918 
5919 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
5920 	for (i = 0; i < argcnt; i++) {
5921 		nfs_argop4 *op = &argbase[i];
5922 		switch (op->argop) {
5923 		case OP_CPUTFH:
5924 		case OP_PUTFH:
5925 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
5926 			break;
5927 		case OP_PUTROOTFH:
5928 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
5929 			break;
5930 		case OP_CLOOKUP:
5931 			s = op->nfs_argop4_u.opclookup.cname;
5932 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5933 			break;
5934 		case OP_LOOKUP:
5935 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
5936 			    &len, NULL);
5937 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5938 			kmem_free(s, len);
5939 			break;
5940 		case OP_LOOKUPP:
5941 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
5942 			break;
5943 		case OP_GETFH:
5944 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
5945 			break;
5946 		case OP_GETATTR:
5947 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
5948 			break;
5949 		case OP_OPENATTR:
5950 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
5951 			break;
5952 		default:
5953 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
5954 			    op->argop);
5955 			break;
5956 		}
5957 	}
5958 }
5959 #endif
5960 
5961 /*
5962  * nfs4lookup_setup - constructs a multi-lookup compound request.
5963  *
5964  * Given the path "nm1/nm2/.../nmn", the following compound requests
5965  * may be created:
5966  *
5967  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
5968  * is faster, for now.
5969  *
5970  * l4_getattrs indicates the type of compound requested.
5971  *
5972  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
5973  *
5974  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
5975  *
5976  *   total number of ops is n + 1.
5977  *
5978  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
5979  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
5980  *      before the last component, and only get attributes
5981  *      for the last component.  Note that the second-to-last
5982  *	pathname component is XATTR_RPATH, which does NOT go
5983  *	over-the-wire as a lookup.
5984  *
5985  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
5986  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
5987  *
5988  *   and total number of ops is n + 5.
5989  *
5990  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
5991  *      attribute directory: create lookups plus an OPENATTR
5992  *	replacing the last lookup.  Note that the last pathname
5993  *	component is XATTR_RPATH, which does NOT go over-the-wire
5994  *	as a lookup.
5995  *
5996  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
5997  *		Openattr; Getfh; Getattr }
5998  *
5999  *   and total number of ops is n + 5.
6000  *
6001  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6002  *	nodes too.
6003  *
6004  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6005  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6006  *
6007  *   and total number of ops is 3*n + 1.
6008  *
6009  * All cases: returns the index in the arg array of the final LOOKUP op, or
6010  * -1 if no LOOKUPs were used.
6011  */
6012 int
6013 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6014 {
6015 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6016 	nfs_argop4 *argbase, *argop;
6017 	int arglen, argcnt;
6018 	int n = 1;	/* number of components */
6019 	int nga = 1;	/* number of Getattr's in request */
6020 	char c = '\0', *s, *p;
6021 	int lookup_idx = -1;
6022 	int argoplist_size;
6023 
6024 	/* set lookuparg response result to 0 */
6025 	lookupargp->resp->status = NFS4_OK;
6026 
6027 	/* skip leading "/" or "." e.g. ".//./" if there is */
6028 	for (; ; nm++) {
6029 		if (*nm != '/' && *nm != '.')
6030 			break;
6031 
6032 		/* ".." is counted as 1 component */
6033 		if (*nm == '.' && *(nm + 1) == '.')
6034 			break;
6035 	}
6036 
6037 	/*
6038 	 * Find n = number of components - nm must be null terminated
6039 	 * Skip "." components.
6040 	 */
6041 	if (*nm != '\0') {
6042 		for (n = 1, s = nm; *s != '\0'; s++) {
6043 			if ((*s == '/') && (*(s + 1) != '/') &&
6044 				    (*(s + 1) != '\0') &&
6045 				    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6046 					*(s + 2) == '\0')))
6047 				n++;
6048 		}
6049 	} else
6050 		n = 0;
6051 
6052 	/*
6053 	 * nga is number of components that need Getfh+Getattr
6054 	 */
6055 	switch (l4_getattrs) {
6056 	case LKP4_NO_ATTRIBUTES:
6057 		nga = 0;
6058 		break;
6059 	case LKP4_ALL_ATTRIBUTES:
6060 		nga = n;
6061 		/*
6062 		 * Always have at least 1 getfh, getattr pair
6063 		 */
6064 		if (nga == 0)
6065 			nga++;
6066 		break;
6067 	case LKP4_LAST_ATTRDIR:
6068 	case LKP4_LAST_NAMED_ATTR:
6069 		nga = n+1;
6070 		break;
6071 	}
6072 
6073 	/*
6074 	 * If change to use the filehandle attr instead of getfh
6075 	 * the following line can be deleted.
6076 	 */
6077 	nga *= 2;
6078 
6079 	/*
6080 	 * calculate number of ops in request as
6081 	 * header + trailer + lookups + getattrs
6082 	 */
6083 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6084 
6085 	argoplist_size = arglen * sizeof (nfs_argop4);
6086 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6087 	lookupargp->argsp->array = argop;
6088 
6089 	argcnt = lookupargp->header_len;
6090 	argop += argcnt;
6091 
6092 	/*
6093 	 * loop and create a lookup op and possibly getattr/getfh for
6094 	 * each component. Skip "." components.
6095 	 */
6096 	for (s = nm; *s != '\0'; s = p) {
6097 		/*
6098 		 * Set up a pathname struct for each component if needed
6099 		 */
6100 		while (*s == '/')
6101 			s++;
6102 		if (*s == '\0')
6103 			break;
6104 		for (p = s; (*p != '/') && (*p != '\0'); p++);
6105 		c = *p;
6106 		*p = '\0';
6107 
6108 		if (s[0] == '.' && s[1] == '\0') {
6109 			*p = c;
6110 			continue;
6111 		}
6112 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6113 		    strcmp(s, XATTR_RPATH) == 0) {
6114 			/* getfh XXX may not be needed in future */
6115 			argop->argop = OP_GETFH;
6116 			argop++;
6117 			argcnt++;
6118 
6119 			/* getattr */
6120 			argop->argop = OP_GETATTR;
6121 			argop->nfs_argop4_u.opgetattr.attr_request =
6122 							lookupargp->ga_bits;
6123 			argop->nfs_argop4_u.opgetattr.mi =
6124 				lookupargp->mi;
6125 			argop++;
6126 			argcnt++;
6127 
6128 			/* openattr */
6129 			argop->argop = OP_OPENATTR;
6130 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6131 		    strcmp(s, XATTR_RPATH) == 0) {
6132 			/* openattr */
6133 			argop->argop = OP_OPENATTR;
6134 			argop++;
6135 			argcnt++;
6136 
6137 			/* getfh XXX may not be needed in future */
6138 			argop->argop = OP_GETFH;
6139 			argop++;
6140 			argcnt++;
6141 
6142 			/* getattr */
6143 			argop->argop = OP_GETATTR;
6144 			argop->nfs_argop4_u.opgetattr.attr_request =
6145 							lookupargp->ga_bits;
6146 			argop->nfs_argop4_u.opgetattr.mi =
6147 							lookupargp->mi;
6148 			argop++;
6149 			argcnt++;
6150 			*p = c;
6151 			continue;
6152 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6153 			/* lookupp */
6154 			argop->argop = OP_LOOKUPP;
6155 		} else {
6156 			/* lookup */
6157 			argop->argop = OP_LOOKUP;
6158 			(void) str_to_utf8(s,
6159 				&argop->nfs_argop4_u.oplookup.objname);
6160 		}
6161 		lookup_idx = argcnt;
6162 		argop++;
6163 		argcnt++;
6164 
6165 		*p = c;
6166 
6167 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6168 			/* getfh XXX may not be needed in future */
6169 			argop->argop = OP_GETFH;
6170 			argop++;
6171 			argcnt++;
6172 
6173 			/* getattr */
6174 			argop->argop = OP_GETATTR;
6175 			argop->nfs_argop4_u.opgetattr.attr_request =
6176 							lookupargp->ga_bits;
6177 			argop->nfs_argop4_u.opgetattr.mi =
6178 							lookupargp->mi;
6179 			argop++;
6180 			argcnt++;
6181 		}
6182 	}
6183 
6184 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6185 		((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6186 		if (needgetfh) {
6187 			/* stick in a post-lookup getfh */
6188 			argop->argop = OP_GETFH;
6189 			argcnt++;
6190 			argop++;
6191 		}
6192 		/* post-lookup getattr */
6193 		argop->argop = OP_GETATTR;
6194 		argop->nfs_argop4_u.opgetattr.attr_request =
6195 						lookupargp->ga_bits;
6196 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6197 		argcnt++;
6198 	}
6199 	argcnt += lookupargp->trailer_len;	/* actual op count */
6200 	lookupargp->argsp->array_len = argcnt;
6201 	lookupargp->arglen = arglen;
6202 
6203 #ifdef DEBUG
6204 	if (nfs4_client_lookup_debug)
6205 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6206 #endif
6207 
6208 	return (lookup_idx);
6209 }
6210 
6211 static int
6212 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6213 {
6214 	COMPOUND4args_clnt	args;
6215 	COMPOUND4res_clnt	res;
6216 	GETFH4res	*gf_res = NULL;
6217 	nfs_argop4	argop[4];
6218 	nfs_resop4	*resop = NULL;
6219 	nfs4_sharedfh_t *sfhp;
6220 	hrtime_t t;
6221 	nfs4_error_t	e;
6222 
6223 	rnode4_t	*drp;
6224 	int		doqueue = 1;
6225 	vnode_t		*vp;
6226 	int		needrecov = 0;
6227 	nfs4_recov_state_t recov_state;
6228 
6229 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6230 
6231 	*avp = NULL;
6232 	recov_state.rs_flags = 0;
6233 	recov_state.rs_num_retry_despite_err = 0;
6234 
6235 recov_retry:
6236 	/* COMPOUND: putfh, openattr, getfh, getattr */
6237 	args.array_len = 4;
6238 	args.array = argop;
6239 	args.ctag = TAG_OPENATTR;
6240 
6241 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6242 	if (e.error)
6243 		return (e.error);
6244 
6245 	drp = VTOR4(dvp);
6246 
6247 	/* putfh */
6248 	argop[0].argop = OP_CPUTFH;
6249 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6250 
6251 	/* openattr */
6252 	argop[1].argop = OP_OPENATTR;
6253 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6254 
6255 	/* getfh */
6256 	argop[2].argop = OP_GETFH;
6257 
6258 	/* getattr */
6259 	argop[3].argop = OP_GETATTR;
6260 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6261 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6262 
6263 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6264 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6265 	    rnode4info(drp)));
6266 
6267 	t = gethrtime();
6268 
6269 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6270 
6271 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6272 	if (needrecov) {
6273 		bool_t abort;
6274 
6275 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6276 		    "nfs4openattr: initiating recovery\n"));
6277 
6278 		abort = nfs4_start_recovery(&e,
6279 				VTOMI4(dvp), dvp, NULL, NULL, NULL,
6280 				OP_OPENATTR, NULL);
6281 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6282 		if (!e.error) {
6283 			e.error = geterrno4(res.status);
6284 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6285 		}
6286 		if (abort == FALSE)
6287 			goto recov_retry;
6288 		return (e.error);
6289 	}
6290 
6291 	if (e.error) {
6292 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6293 		return (e.error);
6294 	}
6295 
6296 	if (res.status) {
6297 		/*
6298 		 * If OTW errro is NOTSUPP, then it should be
6299 		 * translated to EINVAL.  All Solaris file system
6300 		 * implementations return EINVAL to the syscall layer
6301 		 * when the attrdir cannot be created due to an
6302 		 * implementation restriction or noxattr mount option.
6303 		 */
6304 		if (res.status == NFS4ERR_NOTSUPP) {
6305 			mutex_enter(&drp->r_statelock);
6306 			if (drp->r_xattr_dir)
6307 				VN_RELE(drp->r_xattr_dir);
6308 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6309 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6310 			mutex_exit(&drp->r_statelock);
6311 
6312 			e.error = EINVAL;
6313 		} else {
6314 			e.error = geterrno4(res.status);
6315 		}
6316 
6317 		if (e.error) {
6318 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6319 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6320 				    needrecov);
6321 			return (e.error);
6322 		}
6323 	}
6324 
6325 	resop = &res.array[0];  /* putfh res */
6326 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6327 
6328 	resop = &res.array[1];  /* openattr res */
6329 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6330 
6331 	resop = &res.array[2];  /* getfh res */
6332 	gf_res = &resop->nfs_resop4_u.opgetfh;
6333 	if (gf_res->object.nfs_fh4_len == 0) {
6334 		*avp = NULL;
6335 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6336 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6337 		return (ENOENT);
6338 	}
6339 
6340 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6341 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6342 				dvp->v_vfsp, t, cr, dvp,
6343 				fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH));
6344 	sfh4_rele(&sfhp);
6345 
6346 	if (e.error)
6347 		PURGE_ATTRCACHE4(vp);
6348 
6349 	mutex_enter(&vp->v_lock);
6350 	vp->v_flag |= V_XATTRDIR;
6351 	mutex_exit(&vp->v_lock);
6352 
6353 	*avp = vp;
6354 
6355 	mutex_enter(&drp->r_statelock);
6356 	if (drp->r_xattr_dir)
6357 		VN_RELE(drp->r_xattr_dir);
6358 	VN_HOLD(vp);
6359 	drp->r_xattr_dir = vp;
6360 
6361 	/*
6362 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6363 	 * NULL.  xattrs could be created at any time, and we have no
6364 	 * way to update pc4_xattr_exists in the base object if/when
6365 	 * it happens.
6366 	 */
6367 	drp->r_pathconf.pc4_xattr_valid = 0;
6368 
6369 	mutex_exit(&drp->r_statelock);
6370 
6371 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6372 
6373 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6374 
6375 	return (0);
6376 }
6377 
6378 /* ARGSUSED */
6379 static int
6380 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6381 	int mode, vnode_t **vpp, cred_t *cr, int flags)
6382 {
6383 	int error;
6384 	vnode_t *vp = NULL;
6385 	rnode4_t *rp;
6386 	struct vattr vattr;
6387 	rnode4_t *drp;
6388 	vnode_t *tempvp;
6389 	enum createmode4 createmode;
6390 	bool_t must_trunc = FALSE;
6391 	int	truncating = 0;
6392 
6393 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6394 		return (EPERM);
6395 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6396 		return (EINVAL);
6397 	}
6398 
6399 	/* . and .. have special meaning in the protocol, reject them. */
6400 
6401 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6402 		return (EISDIR);
6403 
6404 	drp = VTOR4(dvp);
6405 
6406 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6407 		return (EINTR);
6408 
6409 top:
6410 	/*
6411 	 * We make a copy of the attributes because the caller does not
6412 	 * expect us to change what va points to.
6413 	 */
6414 	vattr = *va;
6415 
6416 	/*
6417 	 * If the pathname is "", then dvp is the root vnode of
6418 	 * a remote file mounted over a local directory.
6419 	 * All that needs to be done is access
6420 	 * checking and truncation.  Note that we avoid doing
6421 	 * open w/ create because the parent directory might
6422 	 * be in pseudo-fs and the open would fail.
6423 	 */
6424 	if (*nm == '\0') {
6425 		error = 0;
6426 		VN_HOLD(dvp);
6427 		vp = dvp;
6428 		must_trunc = TRUE;
6429 	} else {
6430 		/*
6431 		 * We need to go over the wire, just to be sure whether the
6432 		 * file exists or not.  Using the DNLC can be dangerous in
6433 		 * this case when making a decision regarding existence.
6434 		 */
6435 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6436 	}
6437 
6438 	if (exclusive)
6439 		createmode = EXCLUSIVE4;
6440 	else
6441 		createmode = GUARDED4;
6442 
6443 	/*
6444 	 * error would be set if the file does not exist on the
6445 	 * server, so lets go create it.
6446 	 */
6447 	if (error) {
6448 		goto create_otw;
6449 	}
6450 
6451 	/*
6452 	 * File does exist on the server
6453 	 */
6454 	if (exclusive == EXCL)
6455 		error = EEXIST;
6456 	else if (vp->v_type == VDIR && (mode & VWRITE))
6457 		error = EISDIR;
6458 	else {
6459 		/*
6460 		 * If vnode is a device, create special vnode.
6461 		 */
6462 		if (ISVDEV(vp->v_type)) {
6463 			tempvp = vp;
6464 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6465 			VN_RELE(tempvp);
6466 		}
6467 		if (!(error = VOP_ACCESS(vp, mode, 0, cr))) {
6468 			if ((vattr.va_mask & AT_SIZE) &&
6469 			    vp->v_type == VREG) {
6470 				rp = VTOR4(vp);
6471 				/*
6472 				 * Check here for large file handled
6473 				 * by LF-unaware process (as
6474 				 * ufs_create() does)
6475 				 */
6476 				if (!(flags & FOFFMAX)) {
6477 					mutex_enter(&rp->r_statelock);
6478 					if (rp->r_size > MAXOFF32_T)
6479 						error = EOVERFLOW;
6480 					mutex_exit(&rp->r_statelock);
6481 				}
6482 
6483 				/* if error is set then we need to return */
6484 				if (error) {
6485 					nfs_rw_exit(&drp->r_rwlock);
6486 					VN_RELE(vp);
6487 					return (error);
6488 				}
6489 
6490 				if (must_trunc) {
6491 					vattr.va_mask = AT_SIZE;
6492 					error = nfs4setattr(vp, &vattr, 0, cr,
6493 						NULL);
6494 				} else {
6495 				/*
6496 				 * we know we have a regular file that already
6497 				 * exists and we may end up truncating the file
6498 				 * as a result of the open_otw, so flush out
6499 				 * any dirty pages for this file first.
6500 				 */
6501 					if (nfs4_has_pages(vp) &&
6502 					    ((rp->r_flags & R4DIRTY) ||
6503 					    rp->r_count > 0 ||
6504 					    rp->r_mapcnt > 0)) {
6505 						error = nfs4_putpage(vp,
6506 							(offset_t)0, 0, 0, cr);
6507 						if (error && (error == ENOSPC ||
6508 						    error == EDQUOT)) {
6509 							mutex_enter(
6510 							    &rp->r_statelock);
6511 							if (!rp->r_error)
6512 								rp->r_error =
6513 								    error;
6514 							mutex_exit(
6515 							    &rp->r_statelock);
6516 						}
6517 					}
6518 					vattr.va_mask = (AT_SIZE |
6519 							AT_TYPE | AT_MODE);
6520 					vattr.va_type = VREG;
6521 					createmode = UNCHECKED4;
6522 					truncating = 1;
6523 					goto create_otw;
6524 				}
6525 			}
6526 		}
6527 	}
6528 	nfs_rw_exit(&drp->r_rwlock);
6529 	if (error) {
6530 		VN_RELE(vp);
6531 	} else {
6532 		vnode_t *tvp;
6533 		rnode4_t *trp;
6534 		/*
6535 		 * existing file got truncated, notify.
6536 		 */
6537 		trp = VTOR4(vp);
6538 		tvp = vp;
6539 		if (IS_SHADOW(vp, trp))
6540 			tvp = RTOV4(trp);
6541 		vnevent_create(tvp);
6542 		*vpp = vp;
6543 	}
6544 	return (error);
6545 
6546 create_otw:
6547 	dnlc_remove(dvp, nm);
6548 
6549 	ASSERT(vattr.va_mask & AT_TYPE);
6550 
6551 	/*
6552 	 * If not a regular file let nfs4mknod() handle it.
6553 	 */
6554 	if (vattr.va_type != VREG) {
6555 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6556 		nfs_rw_exit(&drp->r_rwlock);
6557 		return (error);
6558 	}
6559 
6560 	/*
6561 	 * It _is_ a regular file.
6562 	 */
6563 	ASSERT(vattr.va_mask & AT_MODE);
6564 	if (MANDMODE(vattr.va_mode)) {
6565 		nfs_rw_exit(&drp->r_rwlock);
6566 		return (EACCES);
6567 	}
6568 
6569 	/*
6570 	 * If this happens to be a mknod of a regular file, then flags will
6571 	 * have neither FREAD or FWRITE.  However, we must set at least one
6572 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6573 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6574 	 * set (based on openmode specified by app).
6575 	 */
6576 	if ((flags & (FREAD|FWRITE)) == 0)
6577 		flags |= (FREAD|FWRITE);
6578 
6579 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6580 
6581 	if (vp != NULL) {
6582 		/* if create was successful, throw away the file's pages */
6583 		if (!error && (vattr.va_mask & AT_SIZE))
6584 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6585 				cr);
6586 		/* release the lookup hold */
6587 		VN_RELE(vp);
6588 		vp = NULL;
6589 	}
6590 
6591 	/*
6592 	 * validate that we opened a regular file. This handles a misbehaving
6593 	 * server that returns an incorrect FH.
6594 	 */
6595 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6596 		error = EISDIR;
6597 		VN_RELE(*vpp);
6598 	}
6599 
6600 	/*
6601 	 * If this is not an exclusive create, then the CREATE
6602 	 * request will be made with the GUARDED mode set.  This
6603 	 * means that the server will return EEXIST if the file
6604 	 * exists.  The file could exist because of a retransmitted
6605 	 * request.  In this case, we recover by starting over and
6606 	 * checking to see whether the file exists.  This second
6607 	 * time through it should and a CREATE request will not be
6608 	 * sent.
6609 	 *
6610 	 * This handles the problem of a dangling CREATE request
6611 	 * which contains attributes which indicate that the file
6612 	 * should be truncated.  This retransmitted request could
6613 	 * possibly truncate valid data in the file if not caught
6614 	 * by the duplicate request mechanism on the server or if
6615 	 * not caught by other means.  The scenario is:
6616 	 *
6617 	 * Client transmits CREATE request with size = 0
6618 	 * Client times out, retransmits request.
6619 	 * Response to the first request arrives from the server
6620 	 *  and the client proceeds on.
6621 	 * Client writes data to the file.
6622 	 * The server now processes retransmitted CREATE request
6623 	 *  and truncates file.
6624 	 *
6625 	 * The use of the GUARDED CREATE request prevents this from
6626 	 * happening because the retransmitted CREATE would fail
6627 	 * with EEXIST and would not truncate the file.
6628 	 */
6629 	if (error == EEXIST && exclusive == NONEXCL) {
6630 #ifdef DEBUG
6631 		nfs4_create_misses++;
6632 #endif
6633 		goto top;
6634 	}
6635 	nfs_rw_exit(&drp->r_rwlock);
6636 	if (truncating && !error && *vpp) {
6637 		vnode_t *tvp;
6638 		rnode4_t *trp;
6639 		/*
6640 		 * existing file got truncated, notify.
6641 		 */
6642 		tvp = *vpp;
6643 		trp = VTOR4(tvp);
6644 		if (IS_SHADOW(vp, trp))
6645 			tvp = RTOV4(trp);
6646 		vnevent_create(tvp);
6647 	}
6648 	return (error);
6649 }
6650 
6651 /*
6652  * Create compound (for mkdir, mknod, symlink):
6653  * { Putfh <dfh>; Create; Getfh; Getattr }
6654  * It's okay if setattr failed to set gid - this is not considered
6655  * an error, but purge attrs in that case.
6656  */
6657 static int
6658 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6659 	vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6660 {
6661 	int need_end_op = FALSE;
6662 	COMPOUND4args_clnt args;
6663 	COMPOUND4res_clnt res, *resp = NULL;
6664 	nfs_argop4 *argop;
6665 	nfs_resop4 *resop;
6666 	int doqueue;
6667 	mntinfo4_t *mi;
6668 	rnode4_t *drp = VTOR4(dvp);
6669 	change_info4 *cinfo;
6670 	GETFH4res *gf_res;
6671 	struct vattr vattr;
6672 	vnode_t *vp;
6673 	fattr4 *crattr;
6674 	bool_t needrecov = FALSE;
6675 	nfs4_recov_state_t recov_state;
6676 	nfs4_sharedfh_t *sfhp = NULL;
6677 	hrtime_t t;
6678 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6679 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6680 	dirattr_info_t dinfo, *dinfop;
6681 	servinfo4_t *svp;
6682 	bitmap4 supp_attrs;
6683 
6684 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6685 		type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6686 
6687 	mi = VTOMI4(dvp);
6688 
6689 	/*
6690 	 * Make sure we properly deal with setting the right gid
6691 	 * on a new directory to reflect the parent's setgid bit
6692 	 */
6693 	setgid_flag = 0;
6694 	if (type == NF4DIR) {
6695 		struct vattr dva;
6696 
6697 		va->va_mode &= ~VSGID;
6698 		dva.va_mask = AT_MODE | AT_GID;
6699 		if (VOP_GETATTR(dvp, &dva, 0, cr) == 0) {
6700 
6701 			/*
6702 			 * If the parent's directory has the setgid bit set
6703 			 * _and_ the client was able to get a valid mapping
6704 			 * for the parent dir's owner_group, we want to
6705 			 * append NVERIFY(owner_group == dva.va_gid) and
6706 			 * SETTATTR to the CREATE compound.
6707 			 */
6708 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6709 				setgid_flag = 1;
6710 				va->va_mode |= VSGID;
6711 				if (dva.va_gid != GID_NOBODY) {
6712 					va->va_mask |= AT_GID;
6713 					va->va_gid = dva.va_gid;
6714 				}
6715 			}
6716 		}
6717 	}
6718 
6719 	/*
6720 	 * Create ops:
6721 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6722 	 *	5:restorefh(dir) 6:getattr(dir)
6723 	 *
6724 	 * if (setgid)
6725 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6726 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6727 	 *	8:nverify 9:setattr
6728 	 */
6729 	if (setgid_flag) {
6730 		numops = 10;
6731 		idx_create = 1;
6732 		idx_fattr = 3;
6733 	} else {
6734 		numops = 7;
6735 		idx_create = 2;
6736 		idx_fattr = 4;
6737 	}
6738 
6739 	ASSERT(nfs_zone() == mi->mi_zone);
6740 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6741 		return (EINTR);
6742 	}
6743 	recov_state.rs_flags = 0;
6744 	recov_state.rs_num_retry_despite_err = 0;
6745 
6746 	argoplist_size = numops * sizeof (nfs_argop4);
6747 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6748 
6749 recov_retry:
6750 	if (type == NF4LNK)
6751 		args.ctag = TAG_SYMLINK;
6752 	else if (type == NF4DIR)
6753 		args.ctag = TAG_MKDIR;
6754 	else
6755 		args.ctag = TAG_MKNOD;
6756 
6757 	args.array_len = numops;
6758 	args.array = argop;
6759 
6760 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6761 		nfs_rw_exit(&drp->r_rwlock);
6762 		kmem_free(argop, argoplist_size);
6763 		return (e.error);
6764 	}
6765 	need_end_op = TRUE;
6766 
6767 
6768 	/* 0: putfh directory */
6769 	argop[0].argop = OP_CPUTFH;
6770 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6771 
6772 	/* 1/2: Create object */
6773 	argop[idx_create].argop = OP_CCREATE;
6774 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6775 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6776 	if (type == NF4LNK) {
6777 		/*
6778 		 * symlink, treat name as data
6779 		 */
6780 		ASSERT(data != NULL);
6781 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6782 							(char *)data;
6783 	}
6784 	if (type == NF4BLK || type == NF4CHR) {
6785 		ASSERT(data != NULL);
6786 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6787 							*((specdata4 *)data);
6788 	}
6789 
6790 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6791 
6792 	svp = drp->r_server;
6793 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6794 	supp_attrs = svp->sv_supp_attrs;
6795 	nfs_rw_exit(&svp->sv_lock);
6796 
6797 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6798 		nfs_rw_exit(&drp->r_rwlock);
6799 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6800 		e.error = EINVAL;
6801 		kmem_free(argop, argoplist_size);
6802 		return (e.error);
6803 	}
6804 
6805 	/* 2/3: getfh fh of created object */
6806 	ASSERT(idx_create + 1 == idx_fattr - 1);
6807 	argop[idx_create + 1].argop = OP_GETFH;
6808 
6809 	/* 3/4: getattr of new object */
6810 	argop[idx_fattr].argop = OP_GETATTR;
6811 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6812 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6813 
6814 	if (setgid_flag) {
6815 		vattr_t	_v;
6816 
6817 		argop[4].argop = OP_SAVEFH;
6818 
6819 		argop[5].argop = OP_CPUTFH;
6820 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6821 
6822 		argop[6].argop = OP_GETATTR;
6823 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6824 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6825 
6826 		argop[7].argop = OP_RESTOREFH;
6827 
6828 		/*
6829 		 * nverify
6830 		 *
6831 		 * XXX - Revisit the last argument to nfs4_end_op()
6832 		 *	 once 5020486 is fixed.
6833 		 */
6834 		_v.va_mask = AT_GID;
6835 		_v.va_gid = va->va_gid;
6836 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6837 		    supp_attrs)) {
6838 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6839 			nfs_rw_exit(&drp->r_rwlock);
6840 			nfs4_fattr4_free(crattr);
6841 			kmem_free(argop, argoplist_size);
6842 			return (e.error);
6843 		}
6844 
6845 		/*
6846 		 * setattr
6847 		 *
6848 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
6849 		 * so no need for stateid or flags. Also we specify NULL
6850 		 * rp since we're only interested in setting owner_group
6851 		 * attributes.
6852 		 */
6853 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
6854 		    &e.error, 0);
6855 
6856 		if (e.error) {
6857 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6858 			nfs_rw_exit(&drp->r_rwlock);
6859 			nfs4_fattr4_free(crattr);
6860 			nfs4args_verify_free(&argop[8]);
6861 			kmem_free(argop, argoplist_size);
6862 			return (e.error);
6863 		}
6864 	} else {
6865 		argop[1].argop = OP_SAVEFH;
6866 
6867 		argop[5].argop = OP_RESTOREFH;
6868 
6869 		argop[6].argop = OP_GETATTR;
6870 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6871 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6872 	}
6873 
6874 	dnlc_remove(dvp, nm);
6875 
6876 	doqueue = 1;
6877 	t = gethrtime();
6878 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
6879 
6880 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
6881 	if (e.error) {
6882 		PURGE_ATTRCACHE4(dvp);
6883 		if (!needrecov)
6884 			goto out;
6885 	}
6886 
6887 	if (needrecov) {
6888 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
6889 		    OP_CREATE, NULL) == FALSE) {
6890 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6891 				    needrecov);
6892 			need_end_op = FALSE;
6893 			nfs4_fattr4_free(crattr);
6894 			if (setgid_flag) {
6895 				nfs4args_verify_free(&argop[8]);
6896 				nfs4args_setattr_free(&argop[9]);
6897 			}
6898 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6899 			goto recov_retry;
6900 		}
6901 	}
6902 
6903 	resp = &res;
6904 
6905 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
6906 
6907 		if (res.status == NFS4ERR_BADOWNER)
6908 			nfs4_log_badowner(mi, OP_CREATE);
6909 
6910 		e.error = geterrno4(res.status);
6911 
6912 		/*
6913 		 * This check is left over from when create was implemented
6914 		 * using a setattr op (instead of createattrs).  If the
6915 		 * putfh/create/getfh failed, the error was returned.  If
6916 		 * setattr/getattr failed, we keep going.
6917 		 *
6918 		 * It might be better to get rid of the GETFH also, and just
6919 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
6920 		 * Then if any of the operations failed, we could return the
6921 		 * error now, and remove much of the error code below.
6922 		 */
6923 		if (res.array_len <= idx_fattr) {
6924 			/*
6925 			 * Either Putfh, Create or Getfh failed.
6926 			 */
6927 			PURGE_ATTRCACHE4(dvp);
6928 			/*
6929 			 * nfs4_purge_stale_fh() may generate otw calls through
6930 			 * nfs4_invalidate_pages. Hence the need to call
6931 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
6932 			 */
6933 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6934 			    needrecov);
6935 			need_end_op = FALSE;
6936 			nfs4_purge_stale_fh(e.error, dvp, cr);
6937 			goto out;
6938 		}
6939 	}
6940 
6941 	resop = &res.array[idx_create];	/* create res */
6942 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
6943 
6944 	resop = &res.array[idx_create + 1]; /* getfh res */
6945 	gf_res = &resop->nfs_resop4_u.opgetfh;
6946 
6947 	sfhp = sfh4_get(&gf_res->object, mi);
6948 	if (e.error) {
6949 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
6950 		    fn_get(VTOSV(dvp)->sv_name, nm));
6951 		if (vp->v_type == VNON) {
6952 			vattr.va_mask = AT_TYPE;
6953 			/*
6954 			 * Need to call nfs4_end_op before nfs4getattr to avoid
6955 			 * potential nfs4_start_op deadlock. See RFE 4777612.
6956 			 */
6957 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6958 				needrecov);
6959 			need_end_op = FALSE;
6960 			e.error = nfs4getattr(vp, &vattr, cr);
6961 			if (e.error) {
6962 				VN_RELE(vp);
6963 				*vpp = NULL;
6964 				goto out;
6965 			}
6966 			vp->v_type = vattr.va_type;
6967 		}
6968 		e.error = 0;
6969 	} else {
6970 		*vpp = vp = makenfs4node(sfhp,
6971 			&res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
6972 			dvp->v_vfsp, t, cr,
6973 			dvp, fn_get(VTOSV(dvp)->sv_name, nm));
6974 	}
6975 
6976 	/*
6977 	 * If compound succeeded, then update dir attrs
6978 	 */
6979 	if (res.status == NFS4_OK) {
6980 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
6981 		dinfo.di_cred = cr;
6982 		dinfo.di_time_call = t;
6983 		dinfop = &dinfo;
6984 	} else
6985 		dinfop = NULL;
6986 
6987 	/* Update directory cache attribute, readdir and dnlc caches */
6988 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
6989 
6990 out:
6991 	if (sfhp != NULL)
6992 		sfh4_rele(&sfhp);
6993 	nfs_rw_exit(&drp->r_rwlock);
6994 	nfs4_fattr4_free(crattr);
6995 	if (setgid_flag) {
6996 		nfs4args_verify_free(&argop[8]);
6997 		nfs4args_setattr_free(&argop[9]);
6998 	}
6999 	if (resp)
7000 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7001 	if (need_end_op)
7002 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7003 
7004 	kmem_free(argop, argoplist_size);
7005 	return (e.error);
7006 }
7007 
7008 /* ARGSUSED */
7009 static int
7010 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7011 	int mode, vnode_t **vpp, cred_t *cr)
7012 {
7013 	int error;
7014 	vnode_t *vp;
7015 	nfs_ftype4 type;
7016 	specdata4 spec, *specp = NULL;
7017 
7018 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7019 
7020 	switch (va->va_type) {
7021 	case VCHR:
7022 	case VBLK:
7023 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7024 		spec.specdata1 = getmajor(va->va_rdev);
7025 		spec.specdata2 = getminor(va->va_rdev);
7026 		specp = &spec;
7027 		break;
7028 
7029 	case VFIFO:
7030 		type = NF4FIFO;
7031 		break;
7032 	case VSOCK:
7033 		type = NF4SOCK;
7034 		break;
7035 
7036 	default:
7037 		return (EINVAL);
7038 	}
7039 
7040 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7041 	if (error) {
7042 		return (error);
7043 	}
7044 
7045 	/*
7046 	 * This might not be needed any more; special case to deal
7047 	 * with problematic v2/v3 servers.  Since create was unable
7048 	 * to set group correctly, not sure what hope setattr has.
7049 	 */
7050 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7051 		va->va_mask = AT_GID;
7052 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7053 	}
7054 
7055 	/*
7056 	 * If vnode is a device create special vnode
7057 	 */
7058 	if (ISVDEV(vp->v_type)) {
7059 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7060 		VN_RELE(vp);
7061 	} else {
7062 		*vpp = vp;
7063 	}
7064 	return (error);
7065 }
7066 
7067 /*
7068  * Remove requires that the current fh be the target directory.
7069  * After the operation, the current fh is unchanged.
7070  * The compound op structure is:
7071  *      PUTFH(targetdir), REMOVE
7072  *
7073  * Weirdness: if the vnode to be removed is open
7074  * we rename it instead of removing it and nfs_inactive
7075  * will remove the new name.
7076  */
7077 static int
7078 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr)
7079 {
7080 	COMPOUND4args_clnt args;
7081 	COMPOUND4res_clnt res, *resp = NULL;
7082 	REMOVE4res *rm_res;
7083 	nfs_argop4 argop[3];
7084 	nfs_resop4 *resop;
7085 	vnode_t *vp;
7086 	char *tmpname;
7087 	int doqueue;
7088 	mntinfo4_t *mi;
7089 	rnode4_t *rp;
7090 	rnode4_t *drp;
7091 	int needrecov = 0;
7092 	nfs4_recov_state_t recov_state;
7093 	int isopen;
7094 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7095 	dirattr_info_t dinfo;
7096 
7097 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7098 		return (EPERM);
7099 	drp = VTOR4(dvp);
7100 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7101 		return (EINTR);
7102 
7103 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7104 	if (e.error) {
7105 		nfs_rw_exit(&drp->r_rwlock);
7106 		return (e.error);
7107 	}
7108 
7109 	if (vp->v_type == VDIR) {
7110 		VN_RELE(vp);
7111 		nfs_rw_exit(&drp->r_rwlock);
7112 		return (EISDIR);
7113 	}
7114 
7115 	/*
7116 	 * First just remove the entry from the name cache, as it
7117 	 * is most likely the only entry for this vp.
7118 	 */
7119 	dnlc_remove(dvp, nm);
7120 
7121 	rp = VTOR4(vp);
7122 
7123 	/*
7124 	 * For regular file types, check to see if the file is open by looking
7125 	 * at the open streams.
7126 	 * For all other types, check the reference count on the vnode.  Since
7127 	 * they are not opened OTW they never have an open stream.
7128 	 *
7129 	 * If the file is open, rename it to .nfsXXXX.
7130 	 */
7131 	if (vp->v_type != VREG) {
7132 		/*
7133 		 * If the file has a v_count > 1 then there may be more than one
7134 		 * entry in the name cache due multiple links or an open file,
7135 		 * but we don't have the real reference count so flush all
7136 		 * possible entries.
7137 		 */
7138 		if (vp->v_count > 1)
7139 			dnlc_purge_vp(vp);
7140 
7141 		/*
7142 		 * Now we have the real reference count.
7143 		 */
7144 		isopen = vp->v_count > 1;
7145 	} else {
7146 		mutex_enter(&rp->r_os_lock);
7147 		isopen = list_head(&rp->r_open_streams) != NULL;
7148 		mutex_exit(&rp->r_os_lock);
7149 	}
7150 
7151 	mutex_enter(&rp->r_statelock);
7152 	if (isopen &&
7153 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7154 		mutex_exit(&rp->r_statelock);
7155 		tmpname = newname();
7156 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr);
7157 		if (e.error)
7158 			kmem_free(tmpname, MAXNAMELEN);
7159 		else {
7160 			mutex_enter(&rp->r_statelock);
7161 			if (rp->r_unldvp == NULL) {
7162 				VN_HOLD(dvp);
7163 				rp->r_unldvp = dvp;
7164 				if (rp->r_unlcred != NULL)
7165 					crfree(rp->r_unlcred);
7166 				crhold(cr);
7167 				rp->r_unlcred = cr;
7168 				rp->r_unlname = tmpname;
7169 			} else {
7170 				kmem_free(rp->r_unlname, MAXNAMELEN);
7171 				rp->r_unlname = tmpname;
7172 			}
7173 			mutex_exit(&rp->r_statelock);
7174 		}
7175 		VN_RELE(vp);
7176 		nfs_rw_exit(&drp->r_rwlock);
7177 		return (e.error);
7178 	}
7179 	/*
7180 	 * Actually remove the file/dir
7181 	 */
7182 	mutex_exit(&rp->r_statelock);
7183 
7184 	/*
7185 	 * We need to flush any dirty pages which happen to
7186 	 * be hanging around before removing the file.
7187 	 * This shouldn't happen very often since in NFSv4
7188 	 * we should be close to open consistent.
7189 	 */
7190 	if (nfs4_has_pages(vp) &&
7191 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7192 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr);
7193 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7194 			mutex_enter(&rp->r_statelock);
7195 			if (!rp->r_error)
7196 				rp->r_error = e.error;
7197 			mutex_exit(&rp->r_statelock);
7198 		}
7199 	}
7200 
7201 	mi = VTOMI4(dvp);
7202 
7203 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7204 	recov_state.rs_flags = 0;
7205 	recov_state.rs_num_retry_despite_err = 0;
7206 
7207 recov_retry:
7208 	/*
7209 	 * Remove ops: putfh dir; remove
7210 	 */
7211 	args.ctag = TAG_REMOVE;
7212 	args.array_len = 3;
7213 	args.array = argop;
7214 
7215 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7216 	if (e.error) {
7217 		nfs_rw_exit(&drp->r_rwlock);
7218 		VN_RELE(vp);
7219 		return (e.error);
7220 	}
7221 
7222 	/* putfh directory */
7223 	argop[0].argop = OP_CPUTFH;
7224 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7225 
7226 	/* remove */
7227 	argop[1].argop = OP_CREMOVE;
7228 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7229 
7230 	/* getattr dir */
7231 	argop[2].argop = OP_GETATTR;
7232 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7233 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7234 
7235 	doqueue = 1;
7236 	dinfo.di_time_call = gethrtime();
7237 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7238 
7239 	PURGE_ATTRCACHE4(vp);
7240 
7241 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7242 	if (e.error)
7243 		PURGE_ATTRCACHE4(dvp);
7244 
7245 	if (needrecov) {
7246 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7247 		    NULL, NULL, NULL, OP_REMOVE, NULL) == FALSE) {
7248 			if (!e.error)
7249 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7250 								(caddr_t)&res);
7251 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7252 					needrecov);
7253 			goto recov_retry;
7254 		}
7255 	}
7256 
7257 	/*
7258 	 * Matching nfs4_end_op() for start_op() above.
7259 	 * There is a path in the code below which calls
7260 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7261 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7262 	 * here to avoid nfs4_start_op() deadlock.
7263 	 */
7264 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7265 
7266 	if (!e.error) {
7267 		resp = &res;
7268 
7269 		if (res.status) {
7270 			e.error = geterrno4(res.status);
7271 			PURGE_ATTRCACHE4(dvp);
7272 			nfs4_purge_stale_fh(e.error, dvp, cr);
7273 		} else {
7274 			resop = &res.array[1];	/* remove res */
7275 			rm_res = &resop->nfs_resop4_u.opremove;
7276 
7277 			dinfo.di_garp =
7278 				&res.array[2].nfs_resop4_u.opgetattr.ga_res;
7279 			dinfo.di_cred = cr;
7280 
7281 			/* Update directory attr, readdir and dnlc caches */
7282 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7283 				&dinfo);
7284 		}
7285 	}
7286 	nfs_rw_exit(&drp->r_rwlock);
7287 	if (resp)
7288 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7289 
7290 	if (e.error == 0) {
7291 		vnode_t *tvp;
7292 		rnode4_t *trp;
7293 		trp = VTOR4(vp);
7294 		tvp = vp;
7295 		if (IS_SHADOW(vp, trp))
7296 			tvp = RTOV4(trp);
7297 		vnevent_remove(tvp, dvp, nm);
7298 	}
7299 	VN_RELE(vp);
7300 	return (e.error);
7301 }
7302 
7303 /*
7304  * Link requires that the current fh be the target directory and the
7305  * saved fh be the source fh. After the operation, the current fh is unchanged.
7306  * Thus the compound op structure is:
7307  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7308  *	GETATTR(file)
7309  */
7310 static int
7311 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr)
7312 {
7313 	COMPOUND4args_clnt args;
7314 	COMPOUND4res_clnt res, *resp = NULL;
7315 	LINK4res *ln_res;
7316 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7317 	nfs_argop4 *argop;
7318 	nfs_resop4 *resop;
7319 	vnode_t *realvp, *nvp;
7320 	int doqueue;
7321 	mntinfo4_t *mi;
7322 	rnode4_t *tdrp;
7323 	bool_t needrecov = FALSE;
7324 	nfs4_recov_state_t recov_state;
7325 	hrtime_t t;
7326 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7327 	dirattr_info_t dinfo;
7328 
7329 	ASSERT(*tnm != '\0');
7330 	ASSERT(tdvp->v_type == VDIR);
7331 	ASSERT(nfs4_consistent_type(tdvp));
7332 	ASSERT(nfs4_consistent_type(svp));
7333 
7334 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7335 		return (EPERM);
7336 	if (VOP_REALVP(svp, &realvp) == 0) {
7337 		svp = realvp;
7338 		ASSERT(nfs4_consistent_type(svp));
7339 	}
7340 
7341 	tdrp = VTOR4(tdvp);
7342 	mi = VTOMI4(svp);
7343 
7344 	if (!(mi->mi_flags & MI4_LINK)) {
7345 		return (EOPNOTSUPP);
7346 	}
7347 	recov_state.rs_flags = 0;
7348 	recov_state.rs_num_retry_despite_err = 0;
7349 
7350 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7351 		return (EINTR);
7352 
7353 recov_retry:
7354 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7355 
7356 	args.ctag = TAG_LINK;
7357 
7358 	/*
7359 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7360 	 * restorefh; getattr(fl)
7361 	 */
7362 	args.array_len = 7;
7363 	args.array = argop;
7364 
7365 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7366 	if (e.error) {
7367 		kmem_free(argop, argoplist_size);
7368 		nfs_rw_exit(&tdrp->r_rwlock);
7369 		return (e.error);
7370 	}
7371 
7372 	/* 0. putfh file */
7373 	argop[0].argop = OP_CPUTFH;
7374 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7375 
7376 	/* 1. save current fh to free up the space for the dir */
7377 	argop[1].argop = OP_SAVEFH;
7378 
7379 	/* 2. putfh targetdir */
7380 	argop[2].argop = OP_CPUTFH;
7381 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7382 
7383 	/* 3. link: current_fh is targetdir, saved_fh is source */
7384 	argop[3].argop = OP_CLINK;
7385 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7386 
7387 	/* 4. Get attributes of dir */
7388 	argop[4].argop = OP_GETATTR;
7389 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7390 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7391 
7392 	/* 5. If link was successful, restore current vp to file */
7393 	argop[5].argop = OP_RESTOREFH;
7394 
7395 	/* 6. Get attributes of linked object */
7396 	argop[6].argop = OP_GETATTR;
7397 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7398 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7399 
7400 	dnlc_remove(tdvp, tnm);
7401 
7402 	doqueue = 1;
7403 	t = gethrtime();
7404 
7405 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7406 
7407 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7408 	if (e.error != 0 && !needrecov) {
7409 		PURGE_ATTRCACHE4(tdvp);
7410 		PURGE_ATTRCACHE4(svp);
7411 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7412 		goto out;
7413 	}
7414 
7415 	if (needrecov) {
7416 		bool_t abort;
7417 
7418 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7419 			    NULL, NULL, OP_LINK, NULL);
7420 		if (abort == FALSE) {
7421 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7422 				    needrecov);
7423 			kmem_free(argop, argoplist_size);
7424 			if (!e.error)
7425 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7426 								(caddr_t)&res);
7427 			goto recov_retry;
7428 		} else {
7429 			if (e.error != 0) {
7430 				PURGE_ATTRCACHE4(tdvp);
7431 				PURGE_ATTRCACHE4(svp);
7432 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7433 					    &recov_state, needrecov);
7434 				goto out;
7435 			}
7436 			/* fall through for res.status case */
7437 		}
7438 	}
7439 
7440 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7441 
7442 	resp = &res;
7443 	if (res.status) {
7444 		/* If link succeeded, then don't return error */
7445 		e.error = geterrno4(res.status);
7446 		if (res.array_len <= 4) {
7447 			/*
7448 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7449 			 */
7450 			PURGE_ATTRCACHE4(svp);
7451 			PURGE_ATTRCACHE4(tdvp);
7452 			if (e.error == EOPNOTSUPP) {
7453 				mutex_enter(&mi->mi_lock);
7454 				mi->mi_flags &= ~MI4_LINK;
7455 				mutex_exit(&mi->mi_lock);
7456 			}
7457 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7458 			/* XXX-LP */
7459 			if (e.error == EISDIR && crgetuid(cr) != 0)
7460 				e.error = EPERM;
7461 			goto out;
7462 		}
7463 	}
7464 
7465 	/* either no error or one of the postop getattr failed */
7466 
7467 	/*
7468 	 * XXX - if LINK succeeded, but no attrs were returned for link
7469 	 * file, purge its cache.
7470 	 *
7471 	 * XXX Perform a simplified version of wcc checking. Instead of
7472 	 * have another getattr to get pre-op, just purge cache if
7473 	 * any of the ops prior to and including the getattr failed.
7474 	 * If the getattr succeeded then update the attrcache accordingly.
7475 	 */
7476 
7477 	/*
7478 	 * update cache with link file postattrs.
7479 	 * Note: at this point resop points to link res.
7480 	 */
7481 	resop = &res.array[3];	/* link res */
7482 	ln_res = &resop->nfs_resop4_u.oplink;
7483 	if (res.status == NFS4_OK) {
7484 		e.error = nfs4_update_attrcache(res.status,
7485 				&res.array[6].nfs_resop4_u.opgetattr.ga_res,
7486 				t, svp, cr);
7487 	}
7488 
7489 	/*
7490 	 * Call makenfs4node to create the new shadow vp for tnm.
7491 	 * We pass NULL attrs because we just cached attrs for
7492 	 * the src object.  All we're trying to accomplish is to
7493 	 * to create the new shadow vnode.
7494 	 */
7495 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7496 			tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm));
7497 
7498 	/* Update target cache attribute, readdir and dnlc caches */
7499 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7500 	dinfo.di_time_call = t;
7501 	dinfo.di_cred = cr;
7502 
7503 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7504 	ASSERT(nfs4_consistent_type(tdvp));
7505 	ASSERT(nfs4_consistent_type(svp));
7506 	ASSERT(nfs4_consistent_type(nvp));
7507 	VN_RELE(nvp);
7508 
7509 	if (!e.error) {
7510 		vnode_t *tvp;
7511 		rnode4_t *trp;
7512 		/*
7513 		 * Notify the source file of this link operation.
7514 		 */
7515 		trp = VTOR4(svp);
7516 		tvp = svp;
7517 		if (IS_SHADOW(svp, trp))
7518 			tvp = RTOV4(trp);
7519 		vnevent_link(tvp);
7520 	}
7521 out:
7522 	kmem_free(argop, argoplist_size);
7523 	if (resp)
7524 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7525 
7526 	nfs_rw_exit(&tdrp->r_rwlock);
7527 
7528 	return (e.error);
7529 }
7530 
7531 static int
7532 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr)
7533 {
7534 	vnode_t *realvp;
7535 
7536 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7537 		return (EPERM);
7538 	if (VOP_REALVP(ndvp, &realvp) == 0)
7539 		ndvp = realvp;
7540 
7541 	return (nfs4rename(odvp, onm, ndvp, nnm, cr));
7542 }
7543 
7544 /*
7545  * nfs4rename does the real work of renaming in NFS Version 4.
7546  *
7547  * A file handle is considered volatile for renaming purposes if either
7548  * of the volatile bits are turned on. However, the compound may differ
7549  * based on the likelihood of the filehandle to change during rename.
7550  */
7551 static int
7552 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr)
7553 {
7554 	int error;
7555 	mntinfo4_t *mi;
7556 	vnode_t *nvp = NULL;
7557 	vnode_t *ovp = NULL;
7558 	char *tmpname = NULL;
7559 	rnode4_t *rp;
7560 	rnode4_t *odrp;
7561 	rnode4_t *ndrp;
7562 	int did_link = 0;
7563 	int do_link = 1;
7564 	nfsstat4 stat = NFS4_OK;
7565 
7566 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7567 	ASSERT(nfs4_consistent_type(odvp));
7568 	ASSERT(nfs4_consistent_type(ndvp));
7569 
7570 	if (onm[0] == '.' && (onm[1] == '\0' ||
7571 			(onm[1] == '.' && onm[2] == '\0')))
7572 		return (EINVAL);
7573 
7574 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7575 			(nnm[1] == '.' && nnm[2] == '\0')))
7576 		return (EINVAL);
7577 
7578 	odrp = VTOR4(odvp);
7579 	ndrp = VTOR4(ndvp);
7580 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7581 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7582 			return (EINTR);
7583 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7584 			nfs_rw_exit(&odrp->r_rwlock);
7585 			return (EINTR);
7586 		}
7587 	} else {
7588 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7589 			return (EINTR);
7590 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7591 			nfs_rw_exit(&ndrp->r_rwlock);
7592 			return (EINTR);
7593 		}
7594 	}
7595 
7596 	/*
7597 	 * Lookup the target file.  If it exists, it needs to be
7598 	 * checked to see whether it is a mount point and whether
7599 	 * it is active (open).
7600 	 */
7601 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7602 	if (!error) {
7603 		int	isactive;
7604 
7605 		ASSERT(nfs4_consistent_type(nvp));
7606 		/*
7607 		 * If this file has been mounted on, then just
7608 		 * return busy because renaming to it would remove
7609 		 * the mounted file system from the name space.
7610 		 */
7611 		if (vn_ismntpt(nvp)) {
7612 			VN_RELE(nvp);
7613 			nfs_rw_exit(&odrp->r_rwlock);
7614 			nfs_rw_exit(&ndrp->r_rwlock);
7615 			return (EBUSY);
7616 		}
7617 
7618 		/*
7619 		 * First just remove the entry from the name cache, as it
7620 		 * is most likely the only entry for this vp.
7621 		 */
7622 		dnlc_remove(ndvp, nnm);
7623 
7624 		rp = VTOR4(nvp);
7625 
7626 		if (nvp->v_type != VREG) {
7627 			/*
7628 			 * Purge the name cache of all references to this vnode
7629 			 * so that we can check the reference count to infer
7630 			 * whether it is active or not.
7631 			 */
7632 			if (nvp->v_count > 1)
7633 				dnlc_purge_vp(nvp);
7634 
7635 			isactive = nvp->v_count > 1;
7636 		} else {
7637 			mutex_enter(&rp->r_os_lock);
7638 			isactive = list_head(&rp->r_open_streams) != NULL;
7639 			mutex_exit(&rp->r_os_lock);
7640 		}
7641 
7642 		/*
7643 		 * If the vnode is active and is not a directory,
7644 		 * arrange to rename it to a
7645 		 * temporary file so that it will continue to be
7646 		 * accessible.  This implements the "unlink-open-file"
7647 		 * semantics for the target of a rename operation.
7648 		 * Before doing this though, make sure that the
7649 		 * source and target files are not already the same.
7650 		 */
7651 		if (isactive && nvp->v_type != VDIR) {
7652 			/*
7653 			 * Lookup the source name.
7654 			 */
7655 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7656 
7657 			/*
7658 			 * The source name *should* already exist.
7659 			 */
7660 			if (error) {
7661 				VN_RELE(nvp);
7662 				nfs_rw_exit(&odrp->r_rwlock);
7663 				nfs_rw_exit(&ndrp->r_rwlock);
7664 				return (error);
7665 			}
7666 
7667 			ASSERT(nfs4_consistent_type(ovp));
7668 
7669 			/*
7670 			 * Compare the two vnodes.  If they are the same,
7671 			 * just release all held vnodes and return success.
7672 			 */
7673 			if (VN_CMP(ovp, nvp)) {
7674 				VN_RELE(ovp);
7675 				VN_RELE(nvp);
7676 				nfs_rw_exit(&odrp->r_rwlock);
7677 				nfs_rw_exit(&ndrp->r_rwlock);
7678 				return (0);
7679 			}
7680 
7681 			/*
7682 			 * Can't mix and match directories and non-
7683 			 * directories in rename operations.  We already
7684 			 * know that the target is not a directory.  If
7685 			 * the source is a directory, return an error.
7686 			 */
7687 			if (ovp->v_type == VDIR) {
7688 				VN_RELE(ovp);
7689 				VN_RELE(nvp);
7690 				nfs_rw_exit(&odrp->r_rwlock);
7691 				nfs_rw_exit(&ndrp->r_rwlock);
7692 				return (ENOTDIR);
7693 			}
7694 link_call:
7695 			/*
7696 			 * The target file exists, is not the same as
7697 			 * the source file, and is active.  We first
7698 			 * try to Link it to a temporary filename to
7699 			 * avoid having the server removing the file
7700 			 * completely (which could cause data loss to
7701 			 * the user's POV in the event the Rename fails
7702 			 * -- see bug 1165874).
7703 			 */
7704 			/*
7705 			 * The do_link and did_link booleans are
7706 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7707 			 * returned for the Rename.  Some servers can
7708 			 * not Rename over an Open file, so they return
7709 			 * this error.  The client needs to Remove the
7710 			 * newly created Link and do two Renames, just
7711 			 * as if the server didn't support LINK.
7712 			 */
7713 			tmpname = newname();
7714 			error = 0;
7715 
7716 			if (do_link) {
7717 				error = nfs4_link(ndvp, nvp, tmpname, cr);
7718 			}
7719 			if (error == EOPNOTSUPP || !do_link) {
7720 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7721 				    cr);
7722 				did_link = 0;
7723 			} else {
7724 				did_link = 1;
7725 			}
7726 			if (error) {
7727 				kmem_free(tmpname, MAXNAMELEN);
7728 				VN_RELE(ovp);
7729 				VN_RELE(nvp);
7730 				nfs_rw_exit(&odrp->r_rwlock);
7731 				nfs_rw_exit(&ndrp->r_rwlock);
7732 				return (error);
7733 			}
7734 
7735 			mutex_enter(&rp->r_statelock);
7736 			if (rp->r_unldvp == NULL) {
7737 				VN_HOLD(ndvp);
7738 				rp->r_unldvp = ndvp;
7739 				if (rp->r_unlcred != NULL)
7740 					crfree(rp->r_unlcred);
7741 				crhold(cr);
7742 				rp->r_unlcred = cr;
7743 				rp->r_unlname = tmpname;
7744 			} else {
7745 				if (rp->r_unlname)
7746 					kmem_free(rp->r_unlname, MAXNAMELEN);
7747 				rp->r_unlname = tmpname;
7748 			}
7749 			mutex_exit(&rp->r_statelock);
7750 		}
7751 
7752 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7753 
7754 		ASSERT(nfs4_consistent_type(nvp));
7755 	}
7756 
7757 	if (ovp == NULL) {
7758 		/*
7759 		 * When renaming directories to be a subdirectory of a
7760 		 * different parent, the dnlc entry for ".." will no
7761 		 * longer be valid, so it must be removed.
7762 		 *
7763 		 * We do a lookup here to determine whether we are renaming
7764 		 * a directory and we need to check if we are renaming
7765 		 * an unlinked file.  This might have already been done
7766 		 * in previous code, so we check ovp == NULL to avoid
7767 		 * doing it twice.
7768 		 */
7769 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7770 		/*
7771 		 * The source name *should* already exist.
7772 		 */
7773 		if (error) {
7774 			nfs_rw_exit(&odrp->r_rwlock);
7775 			nfs_rw_exit(&ndrp->r_rwlock);
7776 			if (nvp) {
7777 				VN_RELE(nvp);
7778 			}
7779 			return (error);
7780 		}
7781 		ASSERT(ovp != NULL);
7782 		ASSERT(nfs4_consistent_type(ovp));
7783 	}
7784 
7785 	/*
7786 	 * Is the object being renamed a dir, and if so, is
7787 	 * it being renamed to a child of itself?  The underlying
7788 	 * fs should ultimately return EINVAL for this case;
7789 	 * however, buggy beta non-Solaris NFSv4 servers at
7790 	 * interop testing events have allowed this behavior,
7791 	 * and it caused our client to panic due to a recursive
7792 	 * mutex_enter in fn_move.
7793 	 *
7794 	 * The tedious locking in fn_move could be changed to
7795 	 * deal with this case, and the client could avoid the
7796 	 * panic; however, the client would just confuse itself
7797 	 * later and misbehave.  A better way to handle the broken
7798 	 * server is to detect this condition and return EINVAL
7799 	 * without ever sending the the bogus rename to the server.
7800 	 * We know the rename is invalid -- just fail it now.
7801 	 */
7802 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7803 		VN_RELE(ovp);
7804 		nfs_rw_exit(&odrp->r_rwlock);
7805 		nfs_rw_exit(&ndrp->r_rwlock);
7806 		if (nvp) {
7807 			VN_RELE(nvp);
7808 		}
7809 		return (EINVAL);
7810 	}
7811 
7812 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7813 
7814 	/*
7815 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7816 	 * possible for the filehandle to change due to the rename.
7817 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7818 	 * the fh will not change because of the rename, but we still need
7819 	 * to update its rnode entry with the new name for
7820 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7821 	 * has no effect on these for now, but for future improvements,
7822 	 * we might want to use it too to simplify handling of files
7823 	 * that are open with that flag on. (XXX)
7824 	 */
7825 	mi = VTOMI4(odvp);
7826 	if (NFS4_VOLATILE_FH(mi)) {
7827 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7828 				&stat);
7829 	} else {
7830 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7831 				&stat);
7832 	}
7833 	ASSERT(nfs4_consistent_type(odvp));
7834 	ASSERT(nfs4_consistent_type(ndvp));
7835 	ASSERT(nfs4_consistent_type(ovp));
7836 
7837 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
7838 		do_link = 0;
7839 		/*
7840 		 * Before the 'link_call' code, we did a nfs4_lookup
7841 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
7842 		 * call we call VN_RELE to match that hold.  We need
7843 		 * to place an additional VN_HOLD here since we will
7844 		 * be hitting that VN_RELE again.
7845 		 */
7846 		VN_HOLD(nvp);
7847 
7848 		(void) nfs4_remove(ndvp, tmpname, cr);
7849 
7850 		/* Undo the unlinked file naming stuff we just did */
7851 		mutex_enter(&rp->r_statelock);
7852 		if (rp->r_unldvp) {
7853 			VN_RELE(ndvp);
7854 			rp->r_unldvp = NULL;
7855 			if (rp->r_unlcred != NULL)
7856 				crfree(rp->r_unlcred);
7857 			rp->r_unlcred = NULL;
7858 			/* rp->r_unlanme points to tmpname */
7859 			if (rp->r_unlname)
7860 				kmem_free(rp->r_unlname, MAXNAMELEN);
7861 			rp->r_unlname = NULL;
7862 		}
7863 		mutex_exit(&rp->r_statelock);
7864 
7865 		if (nvp) {
7866 			VN_RELE(nvp);
7867 		}
7868 		goto link_call;
7869 	}
7870 
7871 	if (error) {
7872 		VN_RELE(ovp);
7873 		nfs_rw_exit(&odrp->r_rwlock);
7874 		nfs_rw_exit(&ndrp->r_rwlock);
7875 		if (nvp) {
7876 			VN_RELE(nvp);
7877 		}
7878 		return (error);
7879 	}
7880 
7881 	/*
7882 	 * when renaming directories to be a subdirectory of a
7883 	 * different parent, the dnlc entry for ".." will no
7884 	 * longer be valid, so it must be removed
7885 	 */
7886 	rp = VTOR4(ovp);
7887 	if (ndvp != odvp) {
7888 		if (ovp->v_type == VDIR) {
7889 			dnlc_remove(ovp, "..");
7890 			if (rp->r_dir != NULL)
7891 				nfs4_purge_rddir_cache(ovp);
7892 		}
7893 	}
7894 
7895 	/*
7896 	 * If we are renaming the unlinked file, update the
7897 	 * r_unldvp and r_unlname as needed.
7898 	 */
7899 	mutex_enter(&rp->r_statelock);
7900 	if (rp->r_unldvp != NULL) {
7901 		if (strcmp(rp->r_unlname, onm) == 0) {
7902 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
7903 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
7904 			if (ndvp != rp->r_unldvp) {
7905 				VN_RELE(rp->r_unldvp);
7906 				rp->r_unldvp = ndvp;
7907 				VN_HOLD(ndvp);
7908 			}
7909 		}
7910 	}
7911 	mutex_exit(&rp->r_statelock);
7912 
7913 	/*
7914 	 * Notify the rename vnevents to source vnode, and to the target
7915 	 * vnode if it already existed.
7916 	 */
7917 	if (error == 0) {
7918 		vnode_t *tvp;
7919 		rnode4_t *trp;
7920 		/*
7921 		 * Notify the vnode. Each links is represented by
7922 		 * a different vnode, in nfsv4.
7923 		 */
7924 		if (nvp) {
7925 			trp = VTOR4(nvp);
7926 			tvp = nvp;
7927 			if (IS_SHADOW(nvp, trp))
7928 				tvp = RTOV4(trp);
7929 			vnevent_rename_dest(tvp, ndvp, nnm);
7930 		}
7931 
7932 		/*
7933 		 * if the source and destination directory are not the
7934 		 * same notify the destination directory.
7935 		 */
7936 		if (VTOR4(odvp) != VTOR4(ndvp)) {
7937 			trp = VTOR4(ndvp);
7938 			tvp = ndvp;
7939 			if (IS_SHADOW(ndvp, trp))
7940 				tvp = RTOV4(trp);
7941 			vnevent_rename_dest_dir(tvp);
7942 		}
7943 
7944 		trp = VTOR4(ovp);
7945 		tvp = ovp;
7946 		if (IS_SHADOW(ovp, trp))
7947 			tvp = RTOV4(trp);
7948 		vnevent_rename_src(tvp, odvp, onm);
7949 	}
7950 
7951 	if (nvp) {
7952 		VN_RELE(nvp);
7953 	}
7954 	VN_RELE(ovp);
7955 
7956 	nfs_rw_exit(&odrp->r_rwlock);
7957 	nfs_rw_exit(&ndrp->r_rwlock);
7958 
7959 	return (error);
7960 }
7961 
7962 /*
7963  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
7964  * when it is known that the filehandle is persistent through rename.
7965  *
7966  * Rename requires that the current fh be the target directory and the
7967  * saved fh be the source directory. After the operation, the current fh
7968  * is unchanged.
7969  * The compound op structure for persistent fh rename is:
7970  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
7971  * Rather than bother with the directory postop args, we'll simply
7972  * update that a change occured in the cache, so no post-op getattrs.
7973  */
7974 static int
7975 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
7976 	vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
7977 {
7978 	COMPOUND4args_clnt args;
7979 	COMPOUND4res_clnt res, *resp = NULL;
7980 	nfs_argop4 *argop;
7981 	nfs_resop4 *resop;
7982 	int doqueue, argoplist_size;
7983 	mntinfo4_t *mi;
7984 	rnode4_t *odrp = VTOR4(odvp);
7985 	rnode4_t *ndrp = VTOR4(ndvp);
7986 	RENAME4res *rn_res;
7987 	bool_t needrecov;
7988 	nfs4_recov_state_t recov_state;
7989 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7990 	dirattr_info_t dinfo, *dinfop;
7991 
7992 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7993 
7994 	recov_state.rs_flags = 0;
7995 	recov_state.rs_num_retry_despite_err = 0;
7996 
7997 	/*
7998 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
7999 	 *
8000 	 * If source/target are different dirs, then append putfh(src); getattr
8001 	 */
8002 	args.array_len = (odvp == ndvp) ? 5 : 7;
8003 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8004 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8005 
8006 recov_retry:
8007 	*statp = NFS4_OK;
8008 
8009 	/* No need to Lookup the file, persistent fh */
8010 	args.ctag = TAG_RENAME;
8011 
8012 	mi = VTOMI4(odvp);
8013 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8014 	if (e.error) {
8015 		kmem_free(argop, argoplist_size);
8016 		return (e.error);
8017 	}
8018 
8019 	/* 0: putfh source directory */
8020 	argop[0].argop = OP_CPUTFH;
8021 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8022 
8023 	/* 1: Save source fh to free up current for target */
8024 	argop[1].argop = OP_SAVEFH;
8025 
8026 	/* 2: putfh targetdir */
8027 	argop[2].argop = OP_CPUTFH;
8028 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8029 
8030 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8031 	argop[3].argop = OP_CRENAME;
8032 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8033 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8034 
8035 	/* 4: getattr (targetdir) */
8036 	argop[4].argop = OP_GETATTR;
8037 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8038 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8039 
8040 	if (ndvp != odvp) {
8041 
8042 		/* 5: putfh (sourcedir) */
8043 		argop[5].argop = OP_CPUTFH;
8044 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8045 
8046 		/* 6: getattr (sourcedir) */
8047 		argop[6].argop = OP_GETATTR;
8048 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8049 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8050 	}
8051 
8052 	dnlc_remove(odvp, onm);
8053 	dnlc_remove(ndvp, nnm);
8054 
8055 	doqueue = 1;
8056 	dinfo.di_time_call = gethrtime();
8057 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8058 
8059 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8060 	if (e.error) {
8061 		PURGE_ATTRCACHE4(odvp);
8062 		PURGE_ATTRCACHE4(ndvp);
8063 	} else {
8064 		*statp = res.status;
8065 	}
8066 
8067 	if (needrecov) {
8068 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8069 		    OP_RENAME, NULL) == FALSE) {
8070 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8071 			if (!e.error)
8072 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8073 								(caddr_t)&res);
8074 			goto recov_retry;
8075 		}
8076 	}
8077 
8078 	if (!e.error) {
8079 		resp = &res;
8080 		/*
8081 		 * as long as OP_RENAME
8082 		 */
8083 		if (res.status != NFS4_OK && res.array_len <= 4) {
8084 			e.error = geterrno4(res.status);
8085 			PURGE_ATTRCACHE4(odvp);
8086 			PURGE_ATTRCACHE4(ndvp);
8087 			/*
8088 			 * System V defines rename to return EEXIST, not
8089 			 * ENOTEMPTY if the target directory is not empty.
8090 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8091 			 * which geterrno4 maps to ENOTEMPTY.
8092 			 */
8093 			if (e.error == ENOTEMPTY)
8094 				e.error = EEXIST;
8095 		} else {
8096 
8097 			resop = &res.array[3];	/* rename res */
8098 			rn_res = &resop->nfs_resop4_u.oprename;
8099 
8100 			if (res.status == NFS4_OK) {
8101 				/*
8102 				 * Update target attribute, readdir and dnlc
8103 				 * caches.
8104 				 */
8105 				dinfo.di_garp =
8106 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8107 				dinfo.di_cred = cr;
8108 				dinfop = &dinfo;
8109 			} else
8110 				dinfop = NULL;
8111 
8112 			nfs4_update_dircaches(&rn_res->target_cinfo,
8113 						ndvp, NULL, NULL, dinfop);
8114 
8115 			/*
8116 			 * Update source attribute, readdir and dnlc caches
8117 			 *
8118 			 */
8119 			if (ndvp != odvp) {
8120 				if (dinfop)
8121 					dinfo.di_garp =
8122 					    &(res.array[6].nfs_resop4_u.
8123 					    opgetattr.ga_res);
8124 
8125 				nfs4_update_dircaches(&rn_res->source_cinfo,
8126 						odvp, NULL, NULL, dinfop);
8127 			}
8128 
8129 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8130 									nnm);
8131 		}
8132 	}
8133 
8134 	if (resp)
8135 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8136 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8137 	kmem_free(argop, argoplist_size);
8138 
8139 	return (e.error);
8140 }
8141 
8142 /*
8143  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8144  * it is possible for the filehandle to change due to the rename.
8145  *
8146  * The compound req in this case includes a post-rename lookup and getattr
8147  * to ensure that we have the correct fh and attributes for the object.
8148  *
8149  * Rename requires that the current fh be the target directory and the
8150  * saved fh be the source directory. After the operation, the current fh
8151  * is unchanged.
8152  *
8153  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8154  * update the filehandle for the renamed object.  We also get the old
8155  * filehandle for historical reasons; this should be taken out sometime.
8156  * This results in a rather cumbersome compound...
8157  *
8158  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8159  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8160  *
8161  */
8162 static int
8163 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8164 	vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8165 {
8166 	COMPOUND4args_clnt args;
8167 	COMPOUND4res_clnt res, *resp = NULL;
8168 	int argoplist_size;
8169 	nfs_argop4 *argop;
8170 	nfs_resop4 *resop;
8171 	int doqueue;
8172 	mntinfo4_t *mi;
8173 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8174 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8175 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8176 	RENAME4res *rn_res;
8177 	GETFH4res *ngf_res;
8178 	bool_t needrecov;
8179 	nfs4_recov_state_t recov_state;
8180 	hrtime_t t;
8181 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8182 	dirattr_info_t dinfo, *dinfop = &dinfo;
8183 
8184 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8185 
8186 	recov_state.rs_flags = 0;
8187 	recov_state.rs_num_retry_despite_err = 0;
8188 
8189 recov_retry:
8190 	*statp = NFS4_OK;
8191 
8192 	/*
8193 	 * There is a window between the RPC and updating the path and
8194 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8195 	 * code, so that it doesn't try to use the old path during that
8196 	 * window.
8197 	 */
8198 	mutex_enter(&orp->r_statelock);
8199 	while (orp->r_flags & R4RECEXPFH) {
8200 		klwp_t *lwp = ttolwp(curthread);
8201 
8202 		if (lwp != NULL)
8203 			lwp->lwp_nostop++;
8204 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8205 			mutex_exit(&orp->r_statelock);
8206 			if (lwp != NULL)
8207 				lwp->lwp_nostop--;
8208 			return (EINTR);
8209 		}
8210 		if (lwp != NULL)
8211 			lwp->lwp_nostop--;
8212 	}
8213 	orp->r_flags |= R4RECEXPFH;
8214 	mutex_exit(&orp->r_statelock);
8215 
8216 	mi = VTOMI4(odvp);
8217 
8218 	args.ctag = TAG_RENAME_VFH;
8219 	args.array_len = (odvp == ndvp) ? 10 : 12;
8220 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8221 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8222 
8223 	/*
8224 	 * Rename ops:
8225 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8226 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8227 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8228 	 *
8229 	 *    if (odvp != ndvp)
8230 	 *	add putfh(sourcedir), getattr(sourcedir) }
8231 	 */
8232 	args.array = argop;
8233 
8234 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8235 			    &recov_state, NULL);
8236 	if (e.error) {
8237 		kmem_free(argop, argoplist_size);
8238 		mutex_enter(&orp->r_statelock);
8239 		orp->r_flags &= ~R4RECEXPFH;
8240 		cv_broadcast(&orp->r_cv);
8241 		mutex_exit(&orp->r_statelock);
8242 		return (e.error);
8243 	}
8244 
8245 	/* 0: putfh source directory */
8246 	argop[0].argop = OP_CPUTFH;
8247 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8248 
8249 	/* 1: Save source fh to free up current for target */
8250 	argop[1].argop = OP_SAVEFH;
8251 
8252 	/* 2: Lookup pre-rename fh of renamed object */
8253 	argop[2].argop = OP_CLOOKUP;
8254 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8255 
8256 	/* 3: getfh fh of renamed object (before rename) */
8257 	argop[3].argop = OP_GETFH;
8258 
8259 	/* 4: putfh targetdir */
8260 	argop[4].argop = OP_CPUTFH;
8261 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8262 
8263 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8264 	argop[5].argop = OP_CRENAME;
8265 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8266 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8267 
8268 	/* 6: getattr of target dir (post op attrs) */
8269 	argop[6].argop = OP_GETATTR;
8270 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8271 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8272 
8273 	/* 7: Lookup post-rename fh of renamed object */
8274 	argop[7].argop = OP_CLOOKUP;
8275 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8276 
8277 	/* 8: getfh fh of renamed object (after rename) */
8278 	argop[8].argop = OP_GETFH;
8279 
8280 	/* 9: getattr of renamed object */
8281 	argop[9].argop = OP_GETATTR;
8282 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8283 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8284 
8285 	/*
8286 	 * If source/target dirs are different, then get new post-op
8287 	 * attrs for source dir also.
8288 	 */
8289 	if (ndvp != odvp) {
8290 		/* 10: putfh (sourcedir) */
8291 		argop[10].argop = OP_CPUTFH;
8292 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8293 
8294 		/* 11: getattr (sourcedir) */
8295 		argop[11].argop = OP_GETATTR;
8296 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8297 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8298 	}
8299 
8300 	dnlc_remove(odvp, onm);
8301 	dnlc_remove(ndvp, nnm);
8302 
8303 	doqueue = 1;
8304 	t = gethrtime();
8305 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8306 
8307 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8308 	if (e.error) {
8309 		PURGE_ATTRCACHE4(odvp);
8310 		PURGE_ATTRCACHE4(ndvp);
8311 		if (!needrecov) {
8312 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8313 					&recov_state, needrecov);
8314 			goto out;
8315 		}
8316 	} else {
8317 		*statp = res.status;
8318 	}
8319 
8320 	if (needrecov) {
8321 		bool_t abort;
8322 
8323 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8324 			    OP_RENAME, NULL);
8325 		if (abort == FALSE) {
8326 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8327 					&recov_state, needrecov);
8328 			kmem_free(argop, argoplist_size);
8329 			if (!e.error)
8330 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8331 								(caddr_t)&res);
8332 			mutex_enter(&orp->r_statelock);
8333 			orp->r_flags &= ~R4RECEXPFH;
8334 			cv_broadcast(&orp->r_cv);
8335 			mutex_exit(&orp->r_statelock);
8336 			goto recov_retry;
8337 		} else {
8338 			if (e.error != 0) {
8339 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8340 						&recov_state, needrecov);
8341 				goto out;
8342 			}
8343 			/* fall through for res.status case */
8344 		}
8345 	}
8346 
8347 	resp = &res;
8348 	/*
8349 	 * If OP_RENAME (or any prev op) failed, then return an error.
8350 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8351 	 */
8352 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8353 		/*
8354 		 * Error in an op other than last Getattr
8355 		 */
8356 		e.error = geterrno4(res.status);
8357 		PURGE_ATTRCACHE4(odvp);
8358 		PURGE_ATTRCACHE4(ndvp);
8359 		/*
8360 		 * System V defines rename to return EEXIST, not
8361 		 * ENOTEMPTY if the target directory is not empty.
8362 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8363 		 * which geterrno4 maps to ENOTEMPTY.
8364 		 */
8365 		if (e.error == ENOTEMPTY)
8366 			e.error = EEXIST;
8367 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8368 				needrecov);
8369 		goto out;
8370 	}
8371 
8372 	/* rename results */
8373 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8374 
8375 	if (res.status == NFS4_OK) {
8376 		/* Update target attribute, readdir and dnlc caches */
8377 		dinfo.di_garp =
8378 			&res.array[6].nfs_resop4_u.opgetattr.ga_res;
8379 		dinfo.di_cred = cr;
8380 		dinfo.di_time_call = t;
8381 	} else
8382 		dinfop = NULL;
8383 
8384 	/* Update source cache attribute, readdir and dnlc caches */
8385 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8386 
8387 	/* Update source cache attribute, readdir and dnlc caches */
8388 	if (ndvp != odvp) {
8389 
8390 		/*
8391 		 * If dinfop is non-NULL, then compound succeded, so
8392 		 * set di_garp to attrs for source dir.  dinfop is only
8393 		 * set to NULL when compound fails.
8394 		 */
8395 		if (dinfop)
8396 			dinfo.di_garp =
8397 				&res.array[11].nfs_resop4_u.opgetattr.ga_res;
8398 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8399 				dinfop);
8400 	}
8401 
8402 	/*
8403 	 * Update the rnode with the new component name and args,
8404 	 * and if the file handle changed, also update it with the new fh.
8405 	 * This is only necessary if the target object has an rnode
8406 	 * entry and there is no need to create one for it.
8407 	 */
8408 	resop = &res.array[8];	/* getfh new res */
8409 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8410 
8411 	/*
8412 	 * Update the path and filehandle for the renamed object.
8413 	 */
8414 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8415 
8416 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8417 
8418 	if (res.status == NFS4_OK) {
8419 		resop++;	/* getattr res */
8420 		e.error = nfs4_update_attrcache(res.status,
8421 				&resop->nfs_resop4_u.opgetattr.ga_res,
8422 				t, ovp, cr);
8423 	}
8424 
8425 out:
8426 	kmem_free(argop, argoplist_size);
8427 	if (resp)
8428 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8429 	mutex_enter(&orp->r_statelock);
8430 	orp->r_flags &= ~R4RECEXPFH;
8431 	cv_broadcast(&orp->r_cv);
8432 	mutex_exit(&orp->r_statelock);
8433 
8434 	return (e.error);
8435 }
8436 
8437 static int
8438 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr)
8439 {
8440 	int error;
8441 	vnode_t *vp;
8442 
8443 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8444 		return (EPERM);
8445 	/*
8446 	 * As ".." has special meaning and rather than send a mkdir
8447 	 * over the wire to just let the server freak out, we just
8448 	 * short circuit it here and return EEXIST
8449 	 */
8450 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8451 		return (EEXIST);
8452 
8453 	/*
8454 	 * Decision to get the right gid and setgid bit of the
8455 	 * new directory is now made in call_nfs4_create_req.
8456 	 */
8457 	va->va_mask |= AT_MODE;
8458 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8459 	if (error)
8460 		return (error);
8461 
8462 	*vpp = vp;
8463 	return (0);
8464 }
8465 
8466 
8467 /*
8468  * rmdir is using the same remove v4 op as does remove.
8469  * Remove requires that the current fh be the target directory.
8470  * After the operation, the current fh is unchanged.
8471  * The compound op structure is:
8472  *      PUTFH(targetdir), REMOVE
8473  */
8474 static int
8475 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr)
8476 {
8477 	int need_end_op = FALSE;
8478 	COMPOUND4args_clnt args;
8479 	COMPOUND4res_clnt res, *resp = NULL;
8480 	REMOVE4res *rm_res;
8481 	nfs_argop4 argop[3];
8482 	nfs_resop4 *resop;
8483 	vnode_t *vp;
8484 	int doqueue;
8485 	mntinfo4_t *mi;
8486 	rnode4_t *drp;
8487 	bool_t needrecov = FALSE;
8488 	nfs4_recov_state_t recov_state;
8489 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8490 	dirattr_info_t dinfo, *dinfop;
8491 
8492 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8493 		return (EPERM);
8494 	/*
8495 	 * As ".." has special meaning and rather than send a rmdir
8496 	 * over the wire to just let the server freak out, we just
8497 	 * short circuit it here and return EEXIST
8498 	 */
8499 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8500 		return (EEXIST);
8501 
8502 	drp = VTOR4(dvp);
8503 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8504 		return (EINTR);
8505 
8506 	/*
8507 	 * Attempt to prevent a rmdir(".") from succeeding.
8508 	 */
8509 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8510 	if (e.error) {
8511 		nfs_rw_exit(&drp->r_rwlock);
8512 		return (e.error);
8513 	}
8514 	if (vp == cdir) {
8515 		VN_RELE(vp);
8516 		nfs_rw_exit(&drp->r_rwlock);
8517 		return (EINVAL);
8518 	}
8519 
8520 	/*
8521 	 * Since nfsv4 remove op works on both files and directories,
8522 	 * check that the removed object is indeed a directory.
8523 	 */
8524 	if (vp->v_type != VDIR) {
8525 		VN_RELE(vp);
8526 		nfs_rw_exit(&drp->r_rwlock);
8527 		return (ENOTDIR);
8528 	}
8529 
8530 	/*
8531 	 * First just remove the entry from the name cache, as it
8532 	 * is most likely an entry for this vp.
8533 	 */
8534 	dnlc_remove(dvp, nm);
8535 
8536 	/*
8537 	 * If there vnode reference count is greater than one, then
8538 	 * there may be additional references in the DNLC which will
8539 	 * need to be purged.  First, trying removing the entry for
8540 	 * the parent directory and see if that removes the additional
8541 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8542 	 * to completely remove any references to the directory which
8543 	 * might still exist in the DNLC.
8544 	 */
8545 	if (vp->v_count > 1) {
8546 		dnlc_remove(vp, "..");
8547 		if (vp->v_count > 1)
8548 			dnlc_purge_vp(vp);
8549 	}
8550 
8551 	mi = VTOMI4(dvp);
8552 	recov_state.rs_flags = 0;
8553 	recov_state.rs_num_retry_despite_err = 0;
8554 
8555 recov_retry:
8556 	args.ctag = TAG_RMDIR;
8557 
8558 	/*
8559 	 * Rmdir ops: putfh dir; remove
8560 	 */
8561 	args.array_len = 3;
8562 	args.array = argop;
8563 
8564 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8565 	if (e.error) {
8566 		nfs_rw_exit(&drp->r_rwlock);
8567 		return (e.error);
8568 	}
8569 	need_end_op = TRUE;
8570 
8571 	/* putfh directory */
8572 	argop[0].argop = OP_CPUTFH;
8573 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8574 
8575 	/* remove */
8576 	argop[1].argop = OP_CREMOVE;
8577 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8578 
8579 	/* getattr (postop attrs for dir that contained removed dir) */
8580 	argop[2].argop = OP_GETATTR;
8581 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8582 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8583 
8584 	dinfo.di_time_call = gethrtime();
8585 	doqueue = 1;
8586 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8587 
8588 	PURGE_ATTRCACHE4(vp);
8589 
8590 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8591 	if (e.error) {
8592 		PURGE_ATTRCACHE4(dvp);
8593 	}
8594 
8595 	if (needrecov) {
8596 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8597 		    NULL, OP_REMOVE, NULL) == FALSE) {
8598 			if (!e.error)
8599 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8600 								(caddr_t)&res);
8601 
8602 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8603 			    needrecov);
8604 			need_end_op = FALSE;
8605 			goto recov_retry;
8606 		}
8607 	}
8608 
8609 	if (!e.error) {
8610 		resp = &res;
8611 
8612 		/*
8613 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8614 		 * failed.
8615 		 */
8616 		if (res.status != NFS4_OK && res.array_len <= 2) {
8617 			e.error = geterrno4(res.status);
8618 			PURGE_ATTRCACHE4(dvp);
8619 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8620 						&recov_state, needrecov);
8621 			need_end_op = FALSE;
8622 			nfs4_purge_stale_fh(e.error, dvp, cr);
8623 			/*
8624 			 * System V defines rmdir to return EEXIST, not
8625 			 * ENOTEMPTY if the directory is not empty.  Over
8626 			 * the wire, the error is NFSERR_ENOTEMPTY which
8627 			 * geterrno4 maps to ENOTEMPTY.
8628 			 */
8629 			if (e.error == ENOTEMPTY)
8630 				e.error = EEXIST;
8631 		} else {
8632 			resop = &res.array[1];	/* remove res */
8633 			rm_res = &resop->nfs_resop4_u.opremove;
8634 
8635 			if (res.status == NFS4_OK) {
8636 				resop = &res.array[2];	/* dir attrs */
8637 				dinfo.di_garp =
8638 					&resop->nfs_resop4_u.opgetattr.ga_res;
8639 				dinfo.di_cred = cr;
8640 				dinfop = &dinfo;
8641 			} else
8642 				dinfop = NULL;
8643 
8644 			/* Update dir attribute, readdir and dnlc caches */
8645 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8646 				dinfop);
8647 
8648 			/* destroy rddir cache for dir that was removed */
8649 			if (VTOR4(vp)->r_dir != NULL)
8650 				nfs4_purge_rddir_cache(vp);
8651 		}
8652 	}
8653 
8654 	if (need_end_op)
8655 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8656 
8657 	nfs_rw_exit(&drp->r_rwlock);
8658 
8659 	if (resp)
8660 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8661 
8662 	if (e.error == 0) {
8663 		vnode_t *tvp;
8664 		rnode4_t *trp;
8665 		trp = VTOR4(vp);
8666 		tvp = vp;
8667 		if (IS_SHADOW(vp, trp))
8668 			tvp = RTOV4(trp);
8669 		vnevent_rmdir(tvp, dvp, nm);
8670 	}
8671 
8672 	VN_RELE(vp);
8673 
8674 	return (e.error);
8675 }
8676 
8677 static int
8678 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr)
8679 {
8680 	int error;
8681 	vnode_t *vp;
8682 	rnode4_t *rp;
8683 	char *contents;
8684 	mntinfo4_t *mi = VTOMI4(dvp);
8685 
8686 	if (nfs_zone() != mi->mi_zone)
8687 		return (EPERM);
8688 	if (!(mi->mi_flags & MI4_SYMLINK))
8689 		return (EOPNOTSUPP);
8690 
8691 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8692 	if (error) {
8693 		return (error);
8694 	}
8695 
8696 	ASSERT(nfs4_consistent_type(vp));
8697 	rp = VTOR4(vp);
8698 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8699 
8700 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8701 
8702 		if (contents != NULL) {
8703 			mutex_enter(&rp->r_statelock);
8704 			if (rp->r_symlink.contents == NULL) {
8705 				rp->r_symlink.len = strlen(tnm);
8706 				bcopy(tnm, contents, rp->r_symlink.len);
8707 				rp->r_symlink.contents = contents;
8708 				rp->r_symlink.size = MAXPATHLEN;
8709 				mutex_exit(&rp->r_statelock);
8710 			} else {
8711 				mutex_exit(&rp->r_statelock);
8712 				kmem_free((void *)contents, MAXPATHLEN);
8713 			}
8714 		}
8715 	}
8716 	VN_RELE(vp);
8717 
8718 	return (error);
8719 }
8720 
8721 
8722 /*
8723  * Read directory entries.
8724  * There are some weird things to look out for here.  The uio_loffset
8725  * field is either 0 or it is the offset returned from a previous
8726  * readdir.  It is an opaque value used by the server to find the
8727  * correct directory block to read. The count field is the number
8728  * of blocks to read on the server.  This is advisory only, the server
8729  * may return only one block's worth of entries.  Entries may be compressed
8730  * on the server.
8731  */
8732 static int
8733 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp)
8734 {
8735 	int error;
8736 	uint_t count;
8737 	rnode4_t *rp;
8738 	rddir4_cache *rdc;
8739 	rddir4_cache *rrdc;
8740 
8741 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8742 		return (EIO);
8743 	rp = VTOR4(vp);
8744 
8745 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8746 
8747 	/*
8748 	 * Make sure that the directory cache is valid.
8749 	 */
8750 	if (rp->r_dir != NULL) {
8751 		if (nfs_disable_rddir_cache != 0) {
8752 			/*
8753 			 * Setting nfs_disable_rddir_cache in /etc/system
8754 			 * allows interoperability with servers that do not
8755 			 * properly update the attributes of directories.
8756 			 * Any cached information gets purged before an
8757 			 * access is made to it.
8758 			 */
8759 			nfs4_purge_rddir_cache(vp);
8760 		}
8761 
8762 		error = nfs4_validate_caches(vp, cr);
8763 		if (error)
8764 			return (error);
8765 	}
8766 
8767 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8768 
8769 	/*
8770 	 * Short circuit last readdir which always returns 0 bytes.
8771 	 * This can be done after the directory has been read through
8772 	 * completely at least once.  This will set r_direof which
8773 	 * can be used to find the value of the last cookie.
8774 	 */
8775 	mutex_enter(&rp->r_statelock);
8776 	if (rp->r_direof != NULL &&
8777 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8778 		mutex_exit(&rp->r_statelock);
8779 #ifdef DEBUG
8780 		nfs4_readdir_cache_shorts++;
8781 #endif
8782 		if (eofp)
8783 			*eofp = 1;
8784 		return (0);
8785 	}
8786 
8787 	/*
8788 	 * Look for a cache entry.  Cache entries are identified
8789 	 * by the NFS cookie value and the byte count requested.
8790 	 */
8791 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8792 
8793 	/*
8794 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8795 	 */
8796 	if (rdc == NULL) {
8797 		mutex_exit(&rp->r_statelock);
8798 		return (EINTR);
8799 	}
8800 
8801 	/*
8802 	 * Check to see if we need to fill this entry in.
8803 	 */
8804 	if (rdc->flags & RDDIRREQ) {
8805 		rdc->flags &= ~RDDIRREQ;
8806 		rdc->flags |= RDDIR;
8807 		mutex_exit(&rp->r_statelock);
8808 
8809 		/*
8810 		 * Do the readdir.
8811 		 */
8812 		nfs4readdir(vp, rdc, cr);
8813 
8814 		/*
8815 		 * Reaquire the lock, so that we can continue
8816 		 */
8817 		mutex_enter(&rp->r_statelock);
8818 		/*
8819 		 * The entry is now complete
8820 		 */
8821 		rdc->flags &= ~RDDIR;
8822 	}
8823 
8824 	ASSERT(!(rdc->flags & RDDIR));
8825 
8826 	/*
8827 	 * If an error occurred while attempting
8828 	 * to fill the cache entry, mark the entry invalid and
8829 	 * just return the error.
8830 	 */
8831 	if (rdc->error) {
8832 		error = rdc->error;
8833 		rdc->flags |= RDDIRREQ;
8834 		rddir4_cache_rele(rp, rdc);
8835 		mutex_exit(&rp->r_statelock);
8836 		return (error);
8837 	}
8838 
8839 	/*
8840 	 * The cache entry is complete and good,
8841 	 * copyout the dirent structs to the calling
8842 	 * thread.
8843 	 */
8844 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
8845 
8846 	/*
8847 	 * If no error occurred during the copyout,
8848 	 * update the offset in the uio struct to
8849 	 * contain the value of the next NFS 4 cookie
8850 	 * and set the eof value appropriately.
8851 	 */
8852 	if (!error) {
8853 		uiop->uio_loffset = rdc->nfs4_ncookie;
8854 		if (eofp)
8855 			*eofp = rdc->eof;
8856 	}
8857 
8858 	/*
8859 	 * Decide whether to do readahead.  Don't if we
8860 	 * have already read to the end of directory.
8861 	 */
8862 	if (rdc->eof) {
8863 		/*
8864 		 * Make the entry the direof only if it is cached
8865 		 */
8866 		if (rdc->flags & RDDIRCACHED)
8867 			rp->r_direof = rdc;
8868 		rddir4_cache_rele(rp, rdc);
8869 		mutex_exit(&rp->r_statelock);
8870 		return (error);
8871 	}
8872 
8873 	/* Determine if a readdir readahead should be done */
8874 	if (!(rp->r_flags & R4LOOKUP)) {
8875 		rddir4_cache_rele(rp, rdc);
8876 		mutex_exit(&rp->r_statelock);
8877 		return (error);
8878 	}
8879 
8880 	/*
8881 	 * Now look for a readahead entry.
8882 	 *
8883 	 * Check to see whether we found an entry for the readahead.
8884 	 * If so, we don't need to do anything further, so free the new
8885 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
8886 	 * it to the cache, and then initiate an asynchronous readdir
8887 	 * operation to fill it.
8888 	 */
8889 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
8890 
8891 	/*
8892 	 * A readdir cache entry could not be obtained for the readahead.  In
8893 	 * this case we skip the readahead and return.
8894 	 */
8895 	if (rrdc == NULL) {
8896 		rddir4_cache_rele(rp, rdc);
8897 		mutex_exit(&rp->r_statelock);
8898 		return (error);
8899 	}
8900 
8901 	/*
8902 	 * Check to see if we need to fill this entry in.
8903 	 */
8904 	if (rrdc->flags & RDDIRREQ) {
8905 		rrdc->flags &= ~RDDIRREQ;
8906 		rrdc->flags |= RDDIR;
8907 		rddir4_cache_rele(rp, rdc);
8908 		mutex_exit(&rp->r_statelock);
8909 #ifdef DEBUG
8910 		nfs4_readdir_readahead++;
8911 #endif
8912 		/*
8913 		 * Do the readdir.
8914 		 */
8915 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
8916 		return (error);
8917 	}
8918 
8919 	rddir4_cache_rele(rp, rrdc);
8920 	rddir4_cache_rele(rp, rdc);
8921 	mutex_exit(&rp->r_statelock);
8922 	return (error);
8923 }
8924 
8925 static int
8926 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
8927 {
8928 	int error;
8929 	rnode4_t *rp;
8930 
8931 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
8932 
8933 	rp = VTOR4(vp);
8934 
8935 	/*
8936 	 * Obtain the readdir results for the caller.
8937 	 */
8938 	nfs4readdir(vp, rdc, cr);
8939 
8940 	mutex_enter(&rp->r_statelock);
8941 	/*
8942 	 * The entry is now complete
8943 	 */
8944 	rdc->flags &= ~RDDIR;
8945 
8946 	error = rdc->error;
8947 	if (error)
8948 		rdc->flags |= RDDIRREQ;
8949 	rddir4_cache_rele(rp, rdc);
8950 	mutex_exit(&rp->r_statelock);
8951 
8952 	return (error);
8953 }
8954 
8955 static void
8956 nfs4readdir_stub(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
8957 {
8958 	int stublength;
8959 	dirent64_t *dp;
8960 	u_longlong_t nodeid, pnodeid;
8961 	vnode_t *dotdotvp = NULL;
8962 	rnode4_t *rp = VTOR4(vp);
8963 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
8964 
8965 	rdc->error = 0;
8966 	rdc->entries = 0;
8967 	rdc->actlen = rdc->entlen = 0;
8968 	rdc->eof = TRUE;
8969 
8970 	/* Check for EOF case for readdir of stub */
8971 	if (cookie != 0 && cookie != 1)
8972 		return;
8973 
8974 	nodeid = rp->r_attr.va_nodeid;
8975 	if (vp->v_flag & VROOT) {
8976 		pnodeid = nodeid;	/* root of mount point */
8977 	} else {
8978 		if (rdc->error = nfs4_lookup(vp, "..", &dotdotvp, 0, 0, 0, cr))
8979 			return;
8980 		pnodeid = VTOR4(dotdotvp)->r_attr.va_nodeid;
8981 		VN_RELE(dotdotvp);
8982 	}
8983 
8984 	stublength = DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2);
8985 	rdc->entries = kmem_alloc(stublength, KM_SLEEP);
8986 	rdc->entlen = rdc->buflen = stublength;
8987 	rdc->eof = TRUE;
8988 
8989 	dp = (dirent64_t *)rdc->entries;
8990 
8991 	if (rdc->nfs4_cookie == (nfs_cookie4)0) {
8992 		bcopy(nfs4_dot_entries, rdc->entries,
8993 			DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2));
8994 		dp->d_ino = nodeid;
8995 		dp = (struct dirent64 *)(((char *)dp) + DIRENT64_RECLEN(1));
8996 		dp->d_ino = pnodeid;
8997 		rdc->actlen = DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2);
8998 	} else	{	/* for ".." entry */
8999 		bcopy(nfs4_dot_dot_entry, rdc->entries, DIRENT64_RECLEN(2));
9000 		dp->d_ino = pnodeid;
9001 		rdc->actlen = DIRENT64_RECLEN(2);
9002 	}
9003 	rdc->nfs4_ncookie = rdc->actlen;
9004 }
9005 
9006 /*
9007  * Read directory entries.
9008  * There are some weird things to look out for here.  The uio_loffset
9009  * field is either 0 or it is the offset returned from a previous
9010  * readdir.  It is an opaque value used by the server to find the
9011  * correct directory block to read. The count field is the number
9012  * of blocks to read on the server.  This is advisory only, the server
9013  * may return only one block's worth of entries.  Entries may be compressed
9014  * on the server.
9015  *
9016  * Generates the following compound request:
9017  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9018  *    must include a Lookupp as well. In this case, send:
9019  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9020  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9021  *
9022  * Get complete attributes and filehandles for entries if this is the
9023  * first read of the directory. Otherwise, just get fileid's.
9024  */
9025 static void
9026 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9027 {
9028 	COMPOUND4args_clnt args;
9029 	COMPOUND4res_clnt res;
9030 	READDIR4args *rargs;
9031 	READDIR4res_clnt *rd_res;
9032 	bitmap4 rd_bitsval;
9033 	nfs_argop4 argop[5];
9034 	nfs_resop4 *resop;
9035 	rnode4_t *rp = VTOR4(vp);
9036 	mntinfo4_t *mi = VTOMI4(vp);
9037 	int doqueue;
9038 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9039 	vnode_t *dvp;
9040 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9041 	int num_ops, res_opcnt;
9042 	bool_t needrecov = FALSE;
9043 	nfs4_recov_state_t recov_state;
9044 	hrtime_t t;
9045 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9046 
9047 	ASSERT(nfs_zone() == mi->mi_zone);
9048 	ASSERT(rdc->flags & RDDIR);
9049 	ASSERT(rdc->entries == NULL);
9050 
9051 	if (rp->r_flags & R4SRVSTUB) {
9052 		nfs4readdir_stub(vp, rdc, cr);
9053 		return;
9054 	}
9055 
9056 	num_ops = 2;
9057 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9058 		/*
9059 		 * Since nfsv4 readdir may not return entries for "." and "..",
9060 		 * the client must recreate them:
9061 		 * To find the correct nodeid, do the following:
9062 		 * For current node, get nodeid from dnlc.
9063 		 * - if current node is rootvp, set pnodeid to nodeid.
9064 		 * - else if parent is in the dnlc, get its nodeid from there.
9065 		 * - else add LOOKUPP+GETATTR to compound.
9066 		 */
9067 		nodeid = rp->r_attr.va_nodeid;
9068 		if (vp->v_flag & VROOT) {
9069 			pnodeid = nodeid;	/* root of mount point */
9070 		} else {
9071 			dvp = dnlc_lookup(vp, "..");
9072 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9073 				/* parent in dnlc cache - no need for otw */
9074 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9075 			} else {
9076 				/*
9077 				 * parent not in dnlc cache,
9078 				 * do lookupp to get its id
9079 				 */
9080 				num_ops = 5;
9081 				pnodeid = 0; /* set later by getattr parent */
9082 			}
9083 			if (dvp)
9084 				VN_RELE(dvp);
9085 		}
9086 	}
9087 	recov_state.rs_flags = 0;
9088 	recov_state.rs_num_retry_despite_err = 0;
9089 
9090 	/* Save the original mount point security flavor */
9091 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9092 
9093 recov_retry:
9094 	args.ctag = TAG_READDIR;
9095 
9096 	args.array = argop;
9097 	args.array_len = num_ops;
9098 
9099 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9100 					&recov_state, NULL)) {
9101 		/*
9102 		 * If readdir a node that is a stub for a crossed mount point,
9103 		 * keep the original secinfo flavor for the current file
9104 		 * system, not the crossed one.
9105 		 */
9106 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9107 		rdc->error = e.error;
9108 		return;
9109 	}
9110 
9111 	/*
9112 	 * Determine which attrs to request for dirents.  This code
9113 	 * must be protected by nfs4_start/end_fop because of r_server
9114 	 * (which will change during failover recovery).
9115 	 *
9116 	 */
9117 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9118 		/*
9119 		 * Get all vattr attrs plus filehandle and rdattr_error
9120 		 */
9121 		rd_bitsval = NFS4_VATTR_MASK |
9122 			FATTR4_RDATTR_ERROR_MASK |
9123 			FATTR4_FILEHANDLE_MASK;
9124 
9125 		if (rp->r_flags & R4READDIRWATTR) {
9126 			mutex_enter(&rp->r_statelock);
9127 			rp->r_flags &= ~R4READDIRWATTR;
9128 			mutex_exit(&rp->r_statelock);
9129 		}
9130 	} else {
9131 		servinfo4_t *svp = rp->r_server;
9132 
9133 		/*
9134 		 * Already read directory. Use readdir with
9135 		 * no attrs (except for mounted_on_fileid) for updates.
9136 		 */
9137 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9138 
9139 		/*
9140 		 * request mounted on fileid if supported, else request
9141 		 * fileid.  maybe we should verify that fileid is supported
9142 		 * and request something else if not.
9143 		 */
9144 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9145 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9146 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9147 		nfs_rw_exit(&svp->sv_lock);
9148 	}
9149 
9150 	/* putfh directory fh */
9151 	argop[0].argop = OP_CPUTFH;
9152 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9153 
9154 	argop[1].argop = OP_READDIR;
9155 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9156 	/*
9157 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9158 	 * cookie 0 should be used over-the-wire to start reading at
9159 	 * the beginning of the directory excluding "." and "..".
9160 	 */
9161 	if (rdc->nfs4_cookie == 0 ||
9162 	    rdc->nfs4_cookie == 1 ||
9163 	    rdc->nfs4_cookie == 2) {
9164 		rargs->cookie = (nfs_cookie4)0;
9165 		rargs->cookieverf = 0;
9166 	} else {
9167 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9168 		mutex_enter(&rp->r_statelock);
9169 		rargs->cookieverf = rp->r_cookieverf4;
9170 		mutex_exit(&rp->r_statelock);
9171 	}
9172 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9173 	rargs->maxcount = mi->mi_tsize;
9174 	rargs->attr_request = rd_bitsval;
9175 	rargs->rdc = rdc;
9176 	rargs->dvp = vp;
9177 	rargs->mi = mi;
9178 	rargs->cr = cr;
9179 
9180 
9181 	/*
9182 	 * If count < than the minimum required, we return no entries
9183 	 * and fail with EINVAL
9184 	 */
9185 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9186 		rdc->error = EINVAL;
9187 		goto out;
9188 	}
9189 
9190 	if (args.array_len == 5) {
9191 		/*
9192 		 * Add lookupp and getattr for parent nodeid.
9193 		 */
9194 		argop[2].argop = OP_LOOKUPP;
9195 
9196 		argop[3].argop = OP_GETFH;
9197 
9198 		/* getattr parent */
9199 		argop[4].argop = OP_GETATTR;
9200 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9201 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9202 	}
9203 
9204 	doqueue = 1;
9205 
9206 	if (mi->mi_io_kstats) {
9207 		mutex_enter(&mi->mi_lock);
9208 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9209 		mutex_exit(&mi->mi_lock);
9210 	}
9211 
9212 	/* capture the time of this call */
9213 	rargs->t = t = gethrtime();
9214 
9215 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9216 
9217 	if (mi->mi_io_kstats) {
9218 		mutex_enter(&mi->mi_lock);
9219 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9220 		mutex_exit(&mi->mi_lock);
9221 	}
9222 
9223 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9224 
9225 	/*
9226 	 * If RPC error occurred and it isn't an error that
9227 	 * triggers recovery, then go ahead and fail now.
9228 	 */
9229 	if (e.error != 0 && !needrecov) {
9230 		rdc->error = e.error;
9231 		goto out;
9232 	}
9233 
9234 	if (needrecov) {
9235 		bool_t abort;
9236 
9237 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9238 		    "nfs4readdir: initiating recovery.\n"));
9239 
9240 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9241 			    NULL, OP_READDIR, NULL);
9242 		if (abort == FALSE) {
9243 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9244 				    &recov_state, needrecov);
9245 			if (!e.error)
9246 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9247 						(caddr_t)&res);
9248 			if (rdc->entries != NULL) {
9249 				kmem_free(rdc->entries, rdc->entlen);
9250 				rdc->entries = NULL;
9251 			}
9252 			goto recov_retry;
9253 		}
9254 
9255 		if (e.error != 0) {
9256 			rdc->error = e.error;
9257 			goto out;
9258 		}
9259 
9260 		/* fall through for res.status case */
9261 	}
9262 
9263 	res_opcnt = res.array_len;
9264 
9265 	/*
9266 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9267 	 * failure here.  Subsequent ops are for filling out dot-dot
9268 	 * dirent, and if they fail, we still want to give the caller
9269 	 * the dirents returned by (the successful) READDIR op, so we need
9270 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9271 	 *
9272 	 * One example where PUTFH+READDIR ops would succeed but
9273 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9274 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9275 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9276 	 * x perm.  We need to come up with a non-vendor-specific way
9277 	 * for a POSIX server to return d_ino from dotdot's dirent if
9278 	 * client only requests mounted_on_fileid, and just say the
9279 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9280 	 * client requested any mandatory attrs, server would be required
9281 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9282 	 * for dotdot.
9283 	 */
9284 
9285 	if (res.status) {
9286 		if (res_opcnt <= 2) {
9287 			e.error = geterrno4(res.status);
9288 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9289 			    &recov_state, needrecov);
9290 			nfs4_purge_stale_fh(e.error, vp, cr);
9291 			rdc->error = e.error;
9292 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9293 			if (rdc->entries != NULL) {
9294 				kmem_free(rdc->entries, rdc->entlen);
9295 				rdc->entries = NULL;
9296 			}
9297 			/*
9298 			 * If readdir a node that is a stub for a
9299 			 * crossed mount point, keep the original
9300 			 * secinfo flavor for the current file system,
9301 			 * not the crossed one.
9302 			 */
9303 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9304 			return;
9305 		}
9306 	}
9307 
9308 	resop = &res.array[1];	/* readdir res */
9309 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9310 
9311 	mutex_enter(&rp->r_statelock);
9312 	rp->r_cookieverf4 = rd_res->cookieverf;
9313 	mutex_exit(&rp->r_statelock);
9314 
9315 	/*
9316 	 * For "." and ".." entries
9317 	 * e.g.
9318 	 *	seek(cookie=0) -> "." entry with d_off = 1
9319 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9320 	 */
9321 	if (cookie == (nfs_cookie4) 0) {
9322 		if (rd_res->dotp)
9323 			rd_res->dotp->d_ino = nodeid;
9324 		if (rd_res->dotdotp)
9325 			rd_res->dotdotp->d_ino = pnodeid;
9326 	}
9327 	if (cookie == (nfs_cookie4) 1) {
9328 		if (rd_res->dotdotp)
9329 			rd_res->dotdotp->d_ino = pnodeid;
9330 	}
9331 
9332 
9333 	/* LOOKUPP+GETATTR attemped */
9334 	if (args.array_len == 5 && rd_res->dotdotp) {
9335 		if (res.status == NFS4_OK && res_opcnt == 5) {
9336 			nfs_fh4 *fhp;
9337 			nfs4_sharedfh_t *sfhp;
9338 			vnode_t *pvp;
9339 			nfs4_ga_res_t *garp;
9340 
9341 			resop++;	/* lookupp */
9342 			resop++;	/* getfh   */
9343 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9344 
9345 			resop++;	/* getattr of parent */
9346 
9347 			/*
9348 			 * First, take care of finishing the
9349 			 * readdir results.
9350 			 */
9351 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9352 			/*
9353 			 * The d_ino of .. must be the inode number
9354 			 * of the mounted filesystem.
9355 			 */
9356 			if (garp->n4g_va.va_mask & AT_NODEID)
9357 				rd_res->dotdotp->d_ino =
9358 					garp->n4g_va.va_nodeid;
9359 
9360 
9361 			/*
9362 			 * Next, create the ".." dnlc entry
9363 			 */
9364 			sfhp = sfh4_get(fhp, mi);
9365 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9366 				dnlc_update(vp, "..", pvp);
9367 				VN_RELE(pvp);
9368 			}
9369 			sfh4_rele(&sfhp);
9370 		}
9371 	}
9372 
9373 	if (mi->mi_io_kstats) {
9374 		mutex_enter(&mi->mi_lock);
9375 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9376 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9377 		mutex_exit(&mi->mi_lock);
9378 	}
9379 
9380 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9381 
9382 out:
9383 	/*
9384 	 * If readdir a node that is a stub for a crossed mount point,
9385 	 * keep the original secinfo flavor for the current file system,
9386 	 * not the crossed one.
9387 	 */
9388 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9389 
9390 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9391 }
9392 
9393 
9394 static int
9395 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9396 {
9397 	rnode4_t *rp = VTOR4(bp->b_vp);
9398 	int count;
9399 	int error;
9400 	cred_t *cred_otw = NULL;
9401 	offset_t offset;
9402 	nfs4_open_stream_t *osp = NULL;
9403 	bool_t first_time = TRUE;	/* first time getting otw cred */
9404 	bool_t last_time = FALSE;	/* last time getting otw cred */
9405 
9406 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9407 
9408 	DTRACE_IO1(start, struct buf *, bp);
9409 	offset = ldbtob(bp->b_lblkno);
9410 
9411 	if (bp->b_flags & B_READ) {
9412 	read_again:
9413 		/*
9414 		 * Releases the osp, if it is provided.
9415 		 * Puts a hold on the cred_otw and the new osp (if found).
9416 		 */
9417 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9418 			&first_time, &last_time);
9419 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9420 						offset, bp->b_bcount,
9421 						&bp->b_resid, cred_otw,
9422 						readahead, NULL);
9423 		crfree(cred_otw);
9424 		if (!error) {
9425 			if (bp->b_resid) {
9426 				/*
9427 				 * Didn't get it all because we hit EOF,
9428 				 * zero all the memory beyond the EOF.
9429 				 */
9430 				/* bzero(rdaddr + */
9431 				bzero(bp->b_un.b_addr +
9432 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9433 			}
9434 			mutex_enter(&rp->r_statelock);
9435 			if (bp->b_resid == bp->b_bcount &&
9436 			    offset >= rp->r_size) {
9437 				/*
9438 				 * We didn't read anything at all as we are
9439 				 * past EOF.  Return an error indicator back
9440 				 * but don't destroy the pages (yet).
9441 				 */
9442 				error = NFS_EOF;
9443 			}
9444 			mutex_exit(&rp->r_statelock);
9445 		} else if (error == EACCES && last_time == FALSE) {
9446 				goto read_again;
9447 		}
9448 	} else {
9449 		if (!(rp->r_flags & R4STALE)) {
9450 		write_again:
9451 			/*
9452 			 * Releases the osp, if it is provided.
9453 			 * Puts a hold on the cred_otw and the new
9454 			 * osp (if found).
9455 			 */
9456 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9457 				&first_time, &last_time);
9458 			mutex_enter(&rp->r_statelock);
9459 			count = MIN(bp->b_bcount, rp->r_size - offset);
9460 			mutex_exit(&rp->r_statelock);
9461 			if (count < 0)
9462 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9463 #ifdef DEBUG
9464 			if (count == 0) {
9465 				zoneid_t zoneid = getzoneid();
9466 
9467 				zcmn_err(zoneid, CE_WARN,
9468 				    "nfs4_bio: zero length write at %lld",
9469 				    offset);
9470 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9471 				    "b_bcount=%ld, file size=%lld",
9472 				    rp->r_flags, (long)bp->b_bcount,
9473 				    rp->r_size);
9474 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9475 				if (nfs4_bio_do_stop)
9476 					debug_enter("nfs4_bio");
9477 			}
9478 #endif
9479 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9480 			    count, cred_otw, stab_comm);
9481 			if (error == EACCES && last_time == FALSE) {
9482 				crfree(cred_otw);
9483 				goto write_again;
9484 			}
9485 			bp->b_error = error;
9486 			if (error && error != EINTR &&
9487 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9488 				/*
9489 				 * Don't print EDQUOT errors on the console.
9490 				 * Don't print asynchronous EACCES errors.
9491 				 * Don't print EFBIG errors.
9492 				 * Print all other write errors.
9493 				 */
9494 				if (error != EDQUOT && error != EFBIG &&
9495 				    (error != EACCES ||
9496 				    !(bp->b_flags & B_ASYNC)))
9497 					nfs4_write_error(bp->b_vp,
9498 					    error, cred_otw);
9499 				/*
9500 				 * Update r_error and r_flags as appropriate.
9501 				 * If the error was ESTALE, then mark the
9502 				 * rnode as not being writeable and save
9503 				 * the error status.  Otherwise, save any
9504 				 * errors which occur from asynchronous
9505 				 * page invalidations.  Any errors occurring
9506 				 * from other operations should be saved
9507 				 * by the caller.
9508 				 */
9509 				mutex_enter(&rp->r_statelock);
9510 				if (error == ESTALE) {
9511 					rp->r_flags |= R4STALE;
9512 					if (!rp->r_error)
9513 						rp->r_error = error;
9514 				} else if (!rp->r_error &&
9515 				    (bp->b_flags &
9516 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9517 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9518 					rp->r_error = error;
9519 				}
9520 				mutex_exit(&rp->r_statelock);
9521 			}
9522 			crfree(cred_otw);
9523 		} else
9524 			error = rp->r_error;
9525 	}
9526 
9527 	if (error != 0 && error != NFS_EOF)
9528 		bp->b_flags |= B_ERROR;
9529 
9530 	if (osp)
9531 		open_stream_rele(osp, rp);
9532 
9533 	DTRACE_IO1(done, struct buf *, bp);
9534 
9535 	return (error);
9536 }
9537 
9538 /* ARGSUSED */
9539 static int
9540 nfs4_fid(vnode_t *vp, fid_t *fidp)
9541 {
9542 	return (EREMOTE);
9543 }
9544 
9545 /* ARGSUSED2 */
9546 static int
9547 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9548 {
9549 	rnode4_t *rp = VTOR4(vp);
9550 
9551 	if (!write_lock) {
9552 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9553 		return (V_WRITELOCK_FALSE);
9554 	}
9555 
9556 	if ((rp->r_flags & R4DIRECTIO) ||
9557 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9558 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9559 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9560 			return (V_WRITELOCK_FALSE);
9561 		nfs_rw_exit(&rp->r_rwlock);
9562 	}
9563 
9564 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9565 	return (V_WRITELOCK_TRUE);
9566 }
9567 
9568 /* ARGSUSED */
9569 static void
9570 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9571 {
9572 	rnode4_t *rp = VTOR4(vp);
9573 
9574 	nfs_rw_exit(&rp->r_rwlock);
9575 }
9576 
9577 /* ARGSUSED */
9578 static int
9579 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp)
9580 {
9581 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9582 		return (EIO);
9583 
9584 	/*
9585 	 * Because we stuff the readdir cookie into the offset field
9586 	 * someone may attempt to do an lseek with the cookie which
9587 	 * we want to succeed.
9588 	 */
9589 	if (vp->v_type == VDIR)
9590 		return (0);
9591 	if (*noffp < 0)
9592 		return (EINVAL);
9593 	return (0);
9594 }
9595 
9596 
9597 /*
9598  * Return all the pages from [off..off+len) in file
9599  */
9600 static int
9601 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9602 	page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9603 	enum seg_rw rw, cred_t *cr)
9604 {
9605 	rnode4_t *rp;
9606 	int error;
9607 	mntinfo4_t *mi;
9608 
9609 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9610 		return (EIO);
9611 	rp = VTOR4(vp);
9612 	if (IS_SHADOW(vp, rp))
9613 		vp = RTOV4(rp);
9614 
9615 	if (vp->v_flag & VNOMAP)
9616 		return (ENOSYS);
9617 
9618 	if (protp != NULL)
9619 		*protp = PROT_ALL;
9620 
9621 	/*
9622 	 * Now validate that the caches are up to date.
9623 	 */
9624 	if (error = nfs4_validate_caches(vp, cr))
9625 		return (error);
9626 
9627 	mi = VTOMI4(vp);
9628 retry:
9629 	mutex_enter(&rp->r_statelock);
9630 
9631 	/*
9632 	 * Don't create dirty pages faster than they
9633 	 * can be cleaned so that the system doesn't
9634 	 * get imbalanced.  If the async queue is
9635 	 * maxed out, then wait for it to drain before
9636 	 * creating more dirty pages.  Also, wait for
9637 	 * any threads doing pagewalks in the vop_getattr
9638 	 * entry points so that they don't block for
9639 	 * long periods.
9640 	 */
9641 	if (rw == S_CREATE) {
9642 		while ((mi->mi_max_threads != 0 &&
9643 			rp->r_awcount > 2 * mi->mi_max_threads) ||
9644 			rp->r_gcount > 0)
9645 			cv_wait(&rp->r_cv, &rp->r_statelock);
9646 	}
9647 
9648 	/*
9649 	 * If we are getting called as a side effect of an nfs_write()
9650 	 * operation the local file size might not be extended yet.
9651 	 * In this case we want to be able to return pages of zeroes.
9652 	 */
9653 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9654 		NFS4_DEBUG(nfs4_pageio_debug,
9655 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9656 		    "len=%llu, size=%llu, attrsize =%llu", off,
9657 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9658 		mutex_exit(&rp->r_statelock);
9659 		return (EFAULT);		/* beyond EOF */
9660 	}
9661 
9662 	mutex_exit(&rp->r_statelock);
9663 
9664 	if (len <= PAGESIZE) {
9665 		error = nfs4_getapage(vp, off, len, protp, pl, plsz,
9666 		    seg, addr, rw, cr);
9667 		NFS4_DEBUG(nfs4_pageio_debug && error,
9668 			(CE_NOTE, "getpage error %d; off=%lld, "
9669 			"len=%lld", error, off, (u_longlong_t)len));
9670 	} else {
9671 		error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9672 		    pl, plsz, seg, addr, rw, cr);
9673 		NFS4_DEBUG(nfs4_pageio_debug && error,
9674 			(CE_NOTE, "getpages error %d; off=%lld, "
9675 			"len=%lld", error, off, (u_longlong_t)len));
9676 	}
9677 
9678 	switch (error) {
9679 	case NFS_EOF:
9680 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9681 		goto retry;
9682 	case ESTALE:
9683 		nfs4_purge_stale_fh(error, vp, cr);
9684 	}
9685 
9686 	return (error);
9687 }
9688 
9689 /*
9690  * Called from pvn_getpages or nfs4_getpage to get a particular page.
9691  */
9692 /* ARGSUSED */
9693 static int
9694 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9695 	page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9696 	enum seg_rw rw, cred_t *cr)
9697 {
9698 	rnode4_t *rp;
9699 	uint_t bsize;
9700 	struct buf *bp;
9701 	page_t *pp;
9702 	u_offset_t lbn;
9703 	u_offset_t io_off;
9704 	u_offset_t blkoff;
9705 	u_offset_t rablkoff;
9706 	size_t io_len;
9707 	uint_t blksize;
9708 	int error;
9709 	int readahead;
9710 	int readahead_issued = 0;
9711 	int ra_window; /* readahead window */
9712 	page_t *pagefound;
9713 	page_t *savepp;
9714 
9715 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9716 		return (EIO);
9717 
9718 	rp = VTOR4(vp);
9719 	ASSERT(!IS_SHADOW(vp, rp));
9720 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9721 
9722 reread:
9723 	bp = NULL;
9724 	pp = NULL;
9725 	pagefound = NULL;
9726 
9727 	if (pl != NULL)
9728 		pl[0] = NULL;
9729 
9730 	error = 0;
9731 	lbn = off / bsize;
9732 	blkoff = lbn * bsize;
9733 
9734 	/*
9735 	 * Queueing up the readahead before doing the synchronous read
9736 	 * results in a significant increase in read throughput because
9737 	 * of the increased parallelism between the async threads and
9738 	 * the process context.
9739 	 */
9740 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9741 	    rw != S_CREATE &&
9742 	    !(vp->v_flag & VNOCACHE)) {
9743 		mutex_enter(&rp->r_statelock);
9744 
9745 		/*
9746 		 * Calculate the number of readaheads to do.
9747 		 * a) No readaheads at offset = 0.
9748 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9749 		 *    window is closed.
9750 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9751 		 *    upon how far the readahead window is open or close.
9752 		 * d) No readaheads if rp->r_nextr is not within the scope
9753 		 *    of the readahead window (random i/o).
9754 		 */
9755 
9756 		if (off == 0)
9757 			readahead = 0;
9758 		else if (blkoff == rp->r_nextr)
9759 			readahead = nfs4_nra;
9760 		else if (rp->r_nextr > blkoff &&
9761 			((ra_window = (rp->r_nextr - blkoff) / bsize)
9762 					<= (nfs4_nra - 1)))
9763 			readahead = nfs4_nra - ra_window;
9764 		else
9765 			readahead = 0;
9766 
9767 		rablkoff = rp->r_nextr;
9768 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9769 			mutex_exit(&rp->r_statelock);
9770 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9771 			    addr + (rablkoff + bsize - off),
9772 			    seg, cr, nfs4_readahead) < 0) {
9773 				mutex_enter(&rp->r_statelock);
9774 				break;
9775 			}
9776 			readahead--;
9777 			rablkoff += bsize;
9778 			/*
9779 			 * Indicate that we did a readahead so
9780 			 * readahead offset is not updated
9781 			 * by the synchronous read below.
9782 			 */
9783 			readahead_issued = 1;
9784 			mutex_enter(&rp->r_statelock);
9785 			/*
9786 			 * set readahead offset to
9787 			 * offset of last async readahead
9788 			 * request.
9789 			 */
9790 			rp->r_nextr = rablkoff;
9791 		}
9792 		mutex_exit(&rp->r_statelock);
9793 	}
9794 
9795 again:
9796 	if ((pagefound = page_exists(vp, off)) == NULL) {
9797 		if (pl == NULL) {
9798 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9799 			    nfs4_readahead);
9800 		} else if (rw == S_CREATE) {
9801 			/*
9802 			 * Block for this page is not allocated, or the offset
9803 			 * is beyond the current allocation size, or we're
9804 			 * allocating a swap slot and the page was not found,
9805 			 * so allocate it and return a zero page.
9806 			 */
9807 			if ((pp = page_create_va(vp, off,
9808 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9809 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9810 			io_len = PAGESIZE;
9811 			mutex_enter(&rp->r_statelock);
9812 			rp->r_nextr = off + PAGESIZE;
9813 			mutex_exit(&rp->r_statelock);
9814 		} else {
9815 			/*
9816 			 * Need to go to server to get a block
9817 			 */
9818 			mutex_enter(&rp->r_statelock);
9819 			if (blkoff < rp->r_size &&
9820 			    blkoff + bsize > rp->r_size) {
9821 				/*
9822 				 * If less than a block left in
9823 				 * file read less than a block.
9824 				 */
9825 				if (rp->r_size <= off) {
9826 					/*
9827 					 * Trying to access beyond EOF,
9828 					 * set up to get at least one page.
9829 					 */
9830 					blksize = off + PAGESIZE - blkoff;
9831 				} else
9832 					blksize = rp->r_size - blkoff;
9833 			} else if ((off == 0) ||
9834 				(off != rp->r_nextr && !readahead_issued)) {
9835 				blksize = PAGESIZE;
9836 				blkoff = off; /* block = page here */
9837 			} else
9838 				blksize = bsize;
9839 			mutex_exit(&rp->r_statelock);
9840 
9841 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9842 			    &io_len, blkoff, blksize, 0);
9843 
9844 			/*
9845 			 * Some other thread has entered the page,
9846 			 * so just use it.
9847 			 */
9848 			if (pp == NULL)
9849 				goto again;
9850 
9851 			/*
9852 			 * Now round the request size up to page boundaries.
9853 			 * This ensures that the entire page will be
9854 			 * initialized to zeroes if EOF is encountered.
9855 			 */
9856 			io_len = ptob(btopr(io_len));
9857 
9858 			bp = pageio_setup(pp, io_len, vp, B_READ);
9859 			ASSERT(bp != NULL);
9860 
9861 			/*
9862 			 * pageio_setup should have set b_addr to 0.  This
9863 			 * is correct since we want to do I/O on a page
9864 			 * boundary.  bp_mapin will use this addr to calculate
9865 			 * an offset, and then set b_addr to the kernel virtual
9866 			 * address it allocated for us.
9867 			 */
9868 			ASSERT(bp->b_un.b_addr == 0);
9869 
9870 			bp->b_edev = 0;
9871 			bp->b_dev = 0;
9872 			bp->b_lblkno = lbtodb(io_off);
9873 			bp->b_file = vp;
9874 			bp->b_offset = (offset_t)off;
9875 			bp_mapin(bp);
9876 
9877 			/*
9878 			 * If doing a write beyond what we believe is EOF,
9879 			 * don't bother trying to read the pages from the
9880 			 * server, we'll just zero the pages here.  We
9881 			 * don't check that the rw flag is S_WRITE here
9882 			 * because some implementations may attempt a
9883 			 * read access to the buffer before copying data.
9884 			 */
9885 			mutex_enter(&rp->r_statelock);
9886 			if (io_off >= rp->r_size && seg == segkmap) {
9887 				mutex_exit(&rp->r_statelock);
9888 				bzero(bp->b_un.b_addr, io_len);
9889 			} else {
9890 				mutex_exit(&rp->r_statelock);
9891 				error = nfs4_bio(bp, NULL, cr, FALSE);
9892 			}
9893 
9894 			/*
9895 			 * Unmap the buffer before freeing it.
9896 			 */
9897 			bp_mapout(bp);
9898 			pageio_done(bp);
9899 
9900 			savepp = pp;
9901 			do {
9902 				pp->p_fsdata = C_NOCOMMIT;
9903 			} while ((pp = pp->p_next) != savepp);
9904 
9905 			if (error == NFS_EOF) {
9906 				/*
9907 				 * If doing a write system call just return
9908 				 * zeroed pages, else user tried to get pages
9909 				 * beyond EOF, return error.  We don't check
9910 				 * that the rw flag is S_WRITE here because
9911 				 * some implementations may attempt a read
9912 				 * access to the buffer before copying data.
9913 				 */
9914 				if (seg == segkmap)
9915 					error = 0;
9916 				else
9917 					error = EFAULT;
9918 			}
9919 
9920 			if (!readahead_issued && !error) {
9921 				mutex_enter(&rp->r_statelock);
9922 				rp->r_nextr = io_off + io_len;
9923 				mutex_exit(&rp->r_statelock);
9924 			}
9925 		}
9926 	}
9927 
9928 out:
9929 	if (pl == NULL)
9930 		return (error);
9931 
9932 	if (error) {
9933 		if (pp != NULL)
9934 			pvn_read_done(pp, B_ERROR);
9935 		return (error);
9936 	}
9937 
9938 	if (pagefound) {
9939 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
9940 
9941 		/*
9942 		 * Page exists in the cache, acquire the appropriate lock.
9943 		 * If this fails, start all over again.
9944 		 */
9945 		if ((pp = page_lookup(vp, off, se)) == NULL) {
9946 #ifdef DEBUG
9947 			nfs4_lostpage++;
9948 #endif
9949 			goto reread;
9950 		}
9951 		pl[0] = pp;
9952 		pl[1] = NULL;
9953 		return (0);
9954 	}
9955 
9956 	if (pp != NULL)
9957 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
9958 
9959 	return (error);
9960 }
9961 
9962 static void
9963 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
9964 	cred_t *cr)
9965 {
9966 	int error;
9967 	page_t *pp;
9968 	u_offset_t io_off;
9969 	size_t io_len;
9970 	struct buf *bp;
9971 	uint_t bsize, blksize;
9972 	rnode4_t *rp = VTOR4(vp);
9973 	page_t *savepp;
9974 
9975 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9976 
9977 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9978 
9979 	mutex_enter(&rp->r_statelock);
9980 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
9981 		/*
9982 		 * If less than a block left in file read less
9983 		 * than a block.
9984 		 */
9985 		blksize = rp->r_size - blkoff;
9986 	} else
9987 		blksize = bsize;
9988 	mutex_exit(&rp->r_statelock);
9989 
9990 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
9991 	    &io_off, &io_len, blkoff, blksize, 1);
9992 	/*
9993 	 * The isra flag passed to the kluster function is 1, we may have
9994 	 * gotten a return value of NULL for a variety of reasons (# of free
9995 	 * pages < minfree, someone entered the page on the vnode etc). In all
9996 	 * cases, we want to punt on the readahead.
9997 	 */
9998 	if (pp == NULL)
9999 		return;
10000 
10001 	/*
10002 	 * Now round the request size up to page boundaries.
10003 	 * This ensures that the entire page will be
10004 	 * initialized to zeroes if EOF is encountered.
10005 	 */
10006 	io_len = ptob(btopr(io_len));
10007 
10008 	bp = pageio_setup(pp, io_len, vp, B_READ);
10009 	ASSERT(bp != NULL);
10010 
10011 	/*
10012 	 * pageio_setup should have set b_addr to 0.  This is correct since
10013 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10014 	 * to calculate an offset, and then set b_addr to the kernel virtual
10015 	 * address it allocated for us.
10016 	 */
10017 	ASSERT(bp->b_un.b_addr == 0);
10018 
10019 	bp->b_edev = 0;
10020 	bp->b_dev = 0;
10021 	bp->b_lblkno = lbtodb(io_off);
10022 	bp->b_file = vp;
10023 	bp->b_offset = (offset_t)blkoff;
10024 	bp_mapin(bp);
10025 
10026 	/*
10027 	 * If doing a write beyond what we believe is EOF, don't bother trying
10028 	 * to read the pages from the server, we'll just zero the pages here.
10029 	 * We don't check that the rw flag is S_WRITE here because some
10030 	 * implementations may attempt a read access to the buffer before
10031 	 * copying data.
10032 	 */
10033 	mutex_enter(&rp->r_statelock);
10034 	if (io_off >= rp->r_size && seg == segkmap) {
10035 		mutex_exit(&rp->r_statelock);
10036 		bzero(bp->b_un.b_addr, io_len);
10037 		error = 0;
10038 	} else {
10039 		mutex_exit(&rp->r_statelock);
10040 		error = nfs4_bio(bp, NULL, cr, TRUE);
10041 		if (error == NFS_EOF)
10042 			error = 0;
10043 	}
10044 
10045 	/*
10046 	 * Unmap the buffer before freeing it.
10047 	 */
10048 	bp_mapout(bp);
10049 	pageio_done(bp);
10050 
10051 	savepp = pp;
10052 	do {
10053 		pp->p_fsdata = C_NOCOMMIT;
10054 	} while ((pp = pp->p_next) != savepp);
10055 
10056 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10057 
10058 	/*
10059 	 * In case of error set readahead offset
10060 	 * to the lowest offset.
10061 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10062 	 */
10063 	if (error && rp->r_nextr > io_off) {
10064 		mutex_enter(&rp->r_statelock);
10065 		if (rp->r_nextr > io_off)
10066 			rp->r_nextr = io_off;
10067 		mutex_exit(&rp->r_statelock);
10068 	}
10069 }
10070 
10071 /*
10072  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10073  * If len == 0, do from off to EOF.
10074  *
10075  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10076  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10077  * (from pageout).
10078  */
10079 static int
10080 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr)
10081 {
10082 	int error;
10083 	rnode4_t *rp;
10084 
10085 	ASSERT(cr != NULL);
10086 
10087 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10088 		return (EIO);
10089 
10090 	rp = VTOR4(vp);
10091 	if (IS_SHADOW(vp, rp))
10092 		vp = RTOV4(rp);
10093 
10094 	/*
10095 	 * XXX - Why should this check be made here?
10096 	 */
10097 	if (vp->v_flag & VNOMAP)
10098 		return (ENOSYS);
10099 
10100 	if (len == 0 && !(flags & B_INVAL) &&
10101 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10102 		return (0);
10103 
10104 	mutex_enter(&rp->r_statelock);
10105 	rp->r_count++;
10106 	mutex_exit(&rp->r_statelock);
10107 	error = nfs4_putpages(vp, off, len, flags, cr);
10108 	mutex_enter(&rp->r_statelock);
10109 	rp->r_count--;
10110 	cv_broadcast(&rp->r_cv);
10111 	mutex_exit(&rp->r_statelock);
10112 
10113 	return (error);
10114 }
10115 
10116 /*
10117  * Write out a single page, possibly klustering adjacent dirty pages.
10118  */
10119 int
10120 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10121 	int flags, cred_t *cr)
10122 {
10123 	u_offset_t io_off;
10124 	u_offset_t lbn_off;
10125 	u_offset_t lbn;
10126 	size_t io_len;
10127 	uint_t bsize;
10128 	int error;
10129 	rnode4_t *rp;
10130 
10131 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10132 	ASSERT(pp != NULL);
10133 	ASSERT(cr != NULL);
10134 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10135 
10136 	rp = VTOR4(vp);
10137 	ASSERT(rp->r_count > 0);
10138 	ASSERT(!IS_SHADOW(vp, rp));
10139 
10140 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10141 	lbn = pp->p_offset / bsize;
10142 	lbn_off = lbn * bsize;
10143 
10144 	/*
10145 	 * Find a kluster that fits in one block, or in
10146 	 * one page if pages are bigger than blocks.  If
10147 	 * there is less file space allocated than a whole
10148 	 * page, we'll shorten the i/o request below.
10149 	 */
10150 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10151 	    roundup(bsize, PAGESIZE), flags);
10152 
10153 	/*
10154 	 * pvn_write_kluster shouldn't have returned a page with offset
10155 	 * behind the original page we were given.  Verify that.
10156 	 */
10157 	ASSERT((pp->p_offset / bsize) >= lbn);
10158 
10159 	/*
10160 	 * Now pp will have the list of kept dirty pages marked for
10161 	 * write back.  It will also handle invalidation and freeing
10162 	 * of pages that are not dirty.  Check for page length rounding
10163 	 * problems.
10164 	 */
10165 	if (io_off + io_len > lbn_off + bsize) {
10166 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10167 		io_len = lbn_off + bsize - io_off;
10168 	}
10169 	/*
10170 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10171 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10172 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10173 	 * progress and the r_size has not been made consistent with the
10174 	 * new size of the file. When the uiomove() completes the r_size is
10175 	 * updated and the R4MODINPROGRESS flag is cleared.
10176 	 *
10177 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10178 	 * consistent value of r_size. Without this handshaking, it is
10179 	 * possible that nfs4_bio() picks  up the old value of r_size
10180 	 * before the uiomove() in writerp4() completes. This will result
10181 	 * in the write through nfs4_bio() being dropped.
10182 	 *
10183 	 * More precisely, there is a window between the time the uiomove()
10184 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10185 	 * operation intervenes in this window, the page will be picked up,
10186 	 * because it is dirty (it will be unlocked, unless it was
10187 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10188 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10189 	 * checked. This will still be the old size. Therefore the page will
10190 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10191 	 * the page will be found to be clean and the write will be dropped.
10192 	 */
10193 	if (rp->r_flags & R4MODINPROGRESS) {
10194 		mutex_enter(&rp->r_statelock);
10195 		if ((rp->r_flags & R4MODINPROGRESS) &&
10196 		    rp->r_modaddr + MAXBSIZE > io_off &&
10197 		    rp->r_modaddr < io_off + io_len) {
10198 			page_t *plist;
10199 			/*
10200 			 * A write is in progress for this region of the file.
10201 			 * If we did not detect R4MODINPROGRESS here then this
10202 			 * path through nfs_putapage() would eventually go to
10203 			 * nfs4_bio() and may not write out all of the data
10204 			 * in the pages. We end up losing data. So we decide
10205 			 * to set the modified bit on each page in the page
10206 			 * list and mark the rnode with R4DIRTY. This write
10207 			 * will be restarted at some later time.
10208 			 */
10209 			plist = pp;
10210 			while (plist != NULL) {
10211 				pp = plist;
10212 				page_sub(&plist, pp);
10213 				hat_setmod(pp);
10214 				page_io_unlock(pp);
10215 				page_unlock(pp);
10216 			}
10217 			rp->r_flags |= R4DIRTY;
10218 			mutex_exit(&rp->r_statelock);
10219 			if (offp)
10220 				*offp = io_off;
10221 			if (lenp)
10222 				*lenp = io_len;
10223 			return (0);
10224 		}
10225 		mutex_exit(&rp->r_statelock);
10226 	}
10227 
10228 	if (flags & B_ASYNC) {
10229 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10230 		    nfs4_sync_putapage);
10231 	} else
10232 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10233 
10234 	if (offp)
10235 		*offp = io_off;
10236 	if (lenp)
10237 		*lenp = io_len;
10238 	return (error);
10239 }
10240 
10241 static int
10242 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10243 	int flags, cred_t *cr)
10244 {
10245 	int error;
10246 	rnode4_t *rp;
10247 
10248 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10249 
10250 	flags |= B_WRITE;
10251 
10252 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10253 
10254 	rp = VTOR4(vp);
10255 
10256 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10257 	    error == EACCES) &&
10258 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10259 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10260 			mutex_enter(&rp->r_statelock);
10261 			rp->r_flags |= R4OUTOFSPACE;
10262 			mutex_exit(&rp->r_statelock);
10263 		}
10264 		flags |= B_ERROR;
10265 		pvn_write_done(pp, flags);
10266 		/*
10267 		 * If this was not an async thread, then try again to
10268 		 * write out the pages, but this time, also destroy
10269 		 * them whether or not the write is successful.  This
10270 		 * will prevent memory from filling up with these
10271 		 * pages and destroying them is the only alternative
10272 		 * if they can't be written out.
10273 		 *
10274 		 * Don't do this if this is an async thread because
10275 		 * when the pages are unlocked in pvn_write_done,
10276 		 * some other thread could have come along, locked
10277 		 * them, and queued for an async thread.  It would be
10278 		 * possible for all of the async threads to be tied
10279 		 * up waiting to lock the pages again and they would
10280 		 * all already be locked and waiting for an async
10281 		 * thread to handle them.  Deadlock.
10282 		 */
10283 		if (!(flags & B_ASYNC)) {
10284 			error = nfs4_putpage(vp, io_off, io_len,
10285 			    B_INVAL | B_FORCE, cr);
10286 		}
10287 	} else {
10288 		if (error)
10289 			flags |= B_ERROR;
10290 		else if (rp->r_flags & R4OUTOFSPACE) {
10291 			mutex_enter(&rp->r_statelock);
10292 			rp->r_flags &= ~R4OUTOFSPACE;
10293 			mutex_exit(&rp->r_statelock);
10294 		}
10295 		pvn_write_done(pp, flags);
10296 		if (freemem < desfree)
10297 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10298 					NFS4_WRITE_NOWAIT);
10299 	}
10300 
10301 	return (error);
10302 }
10303 
10304 #ifdef DEBUG
10305 int nfs4_force_open_before_mmap = 0;
10306 #endif
10307 
10308 static int
10309 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10310 	size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr)
10311 {
10312 	struct segvn_crargs vn_a;
10313 	int error = 0;
10314 	rnode4_t *rp = VTOR4(vp);
10315 	mntinfo4_t *mi = VTOMI4(vp);
10316 
10317 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10318 		return (EIO);
10319 
10320 	if (vp->v_flag & VNOMAP)
10321 		return (ENOSYS);
10322 
10323 	if (off < 0 || (off + len) < 0)
10324 		return (ENXIO);
10325 
10326 	if (vp->v_type != VREG)
10327 		return (ENODEV);
10328 
10329 	/*
10330 	 * If the file is delegated to the client don't do anything.
10331 	 * If the file is not delegated, then validate the data cache.
10332 	 */
10333 	mutex_enter(&rp->r_statev4_lock);
10334 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10335 		mutex_exit(&rp->r_statev4_lock);
10336 		error = nfs4_validate_caches(vp, cr);
10337 		if (error)
10338 			return (error);
10339 	} else {
10340 		mutex_exit(&rp->r_statev4_lock);
10341 	}
10342 
10343 	/*
10344 	 * Check to see if the vnode is currently marked as not cachable.
10345 	 * This means portions of the file are locked (through VOP_FRLOCK).
10346 	 * In this case the map request must be refused.  We use
10347 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10348 	 */
10349 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
10350 		return (EINTR);
10351 
10352 	if (vp->v_flag & VNOCACHE) {
10353 		error = EAGAIN;
10354 		goto done;
10355 	}
10356 
10357 	/*
10358 	 * Don't allow concurrent locks and mapping if mandatory locking is
10359 	 * enabled.
10360 	 */
10361 	if (flk_has_remote_locks(vp)) {
10362 		struct vattr va;
10363 		va.va_mask = AT_MODE;
10364 		error = nfs4getattr(vp, &va, cr);
10365 		if (error != 0)
10366 			goto done;
10367 		if (MANDLOCK(vp, va.va_mode)) {
10368 			error = EAGAIN;
10369 			goto done;
10370 		}
10371 	}
10372 
10373 	/*
10374 	 * It is possible that the rnode has a lost lock request that we
10375 	 * are still trying to recover, and that the request conflicts with
10376 	 * this map request.
10377 	 *
10378 	 * An alternative approach would be for nfs4_safemap() to consider
10379 	 * queued lock requests when deciding whether to set or clear
10380 	 * VNOCACHE.  This would require the frlock code path to call
10381 	 * nfs4_safemap() after enqueing a lost request.
10382 	 */
10383 	if (nfs4_map_lost_lock_conflict(vp)) {
10384 		error = EAGAIN;
10385 		goto done;
10386 	}
10387 
10388 	as_rangelock(as);
10389 	if (!(flags & MAP_FIXED)) {
10390 		map_addr(addrp, len, off, 1, flags);
10391 		if (*addrp == NULL) {
10392 			as_rangeunlock(as);
10393 			error = ENOMEM;
10394 			goto done;
10395 		}
10396 	} else {
10397 		/*
10398 		 * User specified address - blow away any previous mappings
10399 		 */
10400 		(void) as_unmap(as, *addrp, len);
10401 	}
10402 
10403 	if (vp->v_type == VREG) {
10404 		/*
10405 		 * We need to retrieve the open stream
10406 		 */
10407 		nfs4_open_stream_t	*osp = NULL;
10408 		nfs4_open_owner_t	*oop = NULL;
10409 
10410 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10411 		if (oop != NULL) {
10412 			/* returns with 'os_sync_lock' held */
10413 			osp = find_open_stream(oop, rp);
10414 			open_owner_rele(oop);
10415 		}
10416 		if (osp == NULL) {
10417 #ifdef DEBUG
10418 			if (nfs4_force_open_before_mmap) {
10419 				error = EIO;
10420 				goto done;
10421 			}
10422 #endif
10423 			/* returns with 'os_sync_lock' held */
10424 			error = open_and_get_osp(vp, cr, &osp);
10425 			if (osp == NULL) {
10426 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10427 				    "nfs4_map: we tried to OPEN the file "
10428 				    "but again no osp, so fail with EIO"));
10429 				goto done;
10430 			}
10431 		}
10432 
10433 		if (osp->os_failed_reopen) {
10434 			mutex_exit(&osp->os_sync_lock);
10435 			open_stream_rele(osp, rp);
10436 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10437 			    "nfs4_map: os_failed_reopen set on "
10438 			    "osp %p, cr %p, rp %s", (void *)osp,
10439 			    (void *)cr, rnode4info(rp)));
10440 			error = EIO;
10441 			goto done;
10442 		}
10443 		mutex_exit(&osp->os_sync_lock);
10444 		open_stream_rele(osp, rp);
10445 	}
10446 
10447 	vn_a.vp = vp;
10448 	vn_a.offset = off;
10449 	vn_a.type = (flags & MAP_TYPE);
10450 	vn_a.prot = (uchar_t)prot;
10451 	vn_a.maxprot = (uchar_t)maxprot;
10452 	vn_a.flags = (flags & ~MAP_TYPE);
10453 	vn_a.cred = cr;
10454 	vn_a.amp = NULL;
10455 	vn_a.szc = 0;
10456 	vn_a.lgrp_mem_policy_flags = 0;
10457 
10458 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10459 	as_rangeunlock(as);
10460 
10461 done:
10462 	nfs_rw_exit(&rp->r_lkserlock);
10463 	return (error);
10464 }
10465 
10466 /*
10467  * We're most likely dealing with a kernel module that likes to READ
10468  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10469  * officially OPEN the file to create the necessary client state
10470  * for bookkeeping of os_mmap_read/write counts.
10471  *
10472  * Since VOP_MAP only passes in a pointer to the vnode rather than
10473  * a double pointer, we can't handle the case where nfs4open_otw()
10474  * returns a different vnode than the one passed into VOP_MAP (since
10475  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10476  * we return NULL and let nfs4_map() fail.  Note: the only case where
10477  * this should happen is if the file got removed and replaced with the
10478  * same name on the server (in addition to the fact that we're trying
10479  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10480  */
10481 static int
10482 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10483 {
10484 	rnode4_t		*rp, *drp;
10485 	vnode_t			*dvp, *open_vp;
10486 	char			file_name[MAXNAMELEN];
10487 	int			just_created;
10488 	nfs4_open_stream_t	*osp;
10489 	nfs4_open_owner_t	*oop;
10490 	int			error;
10491 
10492 	*ospp = NULL;
10493 	open_vp = map_vp;
10494 
10495 	rp = VTOR4(open_vp);
10496 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10497 		return (error);
10498 	drp = VTOR4(dvp);
10499 
10500 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10501 		VN_RELE(dvp);
10502 		return (EINTR);
10503 	}
10504 
10505 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10506 		nfs_rw_exit(&drp->r_rwlock);
10507 		VN_RELE(dvp);
10508 		return (error);
10509 	}
10510 
10511 	mutex_enter(&rp->r_statev4_lock);
10512 	if (rp->created_v4) {
10513 		rp->created_v4 = 0;
10514 		mutex_exit(&rp->r_statev4_lock);
10515 
10516 		dnlc_update(dvp, file_name, open_vp);
10517 		/* This is needed so we don't bump the open ref count */
10518 		just_created = 1;
10519 	} else {
10520 		mutex_exit(&rp->r_statev4_lock);
10521 		just_created = 0;
10522 	}
10523 
10524 	VN_HOLD(map_vp);
10525 
10526 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10527 		just_created);
10528 	if (error) {
10529 		nfs_rw_exit(&drp->r_rwlock);
10530 		VN_RELE(dvp);
10531 		VN_RELE(map_vp);
10532 		return (error);
10533 	}
10534 
10535 	nfs_rw_exit(&drp->r_rwlock);
10536 	VN_RELE(dvp);
10537 
10538 	/*
10539 	 * If nfs4open_otw() returned a different vnode then "undo"
10540 	 * the open and return failure to the caller.
10541 	 */
10542 	if (!VN_CMP(open_vp, map_vp)) {
10543 		nfs4_error_t e;
10544 
10545 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10546 		    "open returned a different vnode"));
10547 		/*
10548 		 * If there's an error, ignore it,
10549 		 * and let VOP_INACTIVE handle it.
10550 		 */
10551 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10552 				CLOSE_NORM, 0, 0, 0);
10553 		VN_RELE(map_vp);
10554 		return (EIO);
10555 	}
10556 
10557 	VN_RELE(map_vp);
10558 
10559 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10560 	if (!oop) {
10561 		nfs4_error_t e;
10562 
10563 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10564 		    "no open owner"));
10565 		/*
10566 		 * If there's an error, ignore it,
10567 		 * and let VOP_INACTIVE handle it.
10568 		 */
10569 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10570 				CLOSE_NORM, 0, 0, 0);
10571 		return (EIO);
10572 	}
10573 	osp = find_open_stream(oop, rp);
10574 	open_owner_rele(oop);
10575 	*ospp = osp;
10576 	return (0);
10577 }
10578 
10579 /*
10580  * Please be aware that when this function is called, the address space write
10581  * a_lock is held.  Do not put over the wire calls in this function.
10582  */
10583 /* ARGSUSED */
10584 static int
10585 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10586 	size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr)
10587 {
10588 	rnode4_t		*rp;
10589 	int			error = 0;
10590 	mntinfo4_t		*mi;
10591 
10592 	mi = VTOMI4(vp);
10593 	rp = VTOR4(vp);
10594 
10595 	if (nfs_zone() != mi->mi_zone)
10596 		return (EIO);
10597 	if (vp->v_flag & VNOMAP)
10598 		return (ENOSYS);
10599 
10600 	/*
10601 	 * Need to hold rwlock while incrementing the mapcnt so that
10602 	 * mmap'ing can be serialized with writes so that the caching
10603 	 * can be handled correctly.
10604 	 *
10605 	 * Don't need to update the open stream first, since this
10606 	 * mmap can't add any additional share access that isn't
10607 	 * already contained in the open stream (for the case where we
10608 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10609 	 * take into account os_mmap_read[write] counts).
10610 	 */
10611 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR(vp)))
10612 		return (EINTR);
10613 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10614 	nfs_rw_exit(&rp->r_rwlock);
10615 
10616 	if (vp->v_type == VREG) {
10617 		/*
10618 		 * We need to retrieve the open stream and update the counts.
10619 		 * If there is no open stream here, something is wrong.
10620 		 */
10621 		nfs4_open_stream_t	*osp = NULL;
10622 		nfs4_open_owner_t	*oop = NULL;
10623 
10624 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10625 		if (oop != NULL) {
10626 			/* returns with 'os_sync_lock' held */
10627 			osp = find_open_stream(oop, rp);
10628 			open_owner_rele(oop);
10629 		}
10630 		if (osp == NULL) {
10631 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10632 			    "nfs4_addmap: we should have an osp"
10633 			    "but we don't, so fail with EIO"));
10634 			error = EIO;
10635 			goto out;
10636 		}
10637 
10638 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10639 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10640 
10641 		/*
10642 		 * Update the map count in the open stream.
10643 		 * This is necessary in the case where we
10644 		 * open/mmap/close/, then the server reboots, and we
10645 		 * attempt to reopen.  If the mmap doesn't add share
10646 		 * access then we send an invalid reopen with
10647 		 * access = NONE.
10648 		 *
10649 		 * We need to specifically check each PROT_* so a mmap
10650 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10651 		 * read and write access.  A simple comparison of prot
10652 		 * to ~PROT_WRITE to determine read access is insufficient
10653 		 * since prot can be |= with PROT_USER, etc.
10654 		 */
10655 
10656 		/*
10657 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10658 		 */
10659 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10660 			osp->os_mmap_write += btopr(len);
10661 		if (maxprot & PROT_READ)
10662 			osp->os_mmap_read += btopr(len);
10663 		if (maxprot & PROT_EXEC)
10664 			osp->os_mmap_read += btopr(len);
10665 		/*
10666 		 * Ensure that os_mmap_read gets incremented, even if
10667 		 * maxprot were to look like PROT_NONE.
10668 		 */
10669 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10670 		    !(maxprot & PROT_EXEC))
10671 			osp->os_mmap_read += btopr(len);
10672 		osp->os_mapcnt += btopr(len);
10673 		mutex_exit(&osp->os_sync_lock);
10674 		open_stream_rele(osp, rp);
10675 	}
10676 
10677 out:
10678 	/*
10679 	 * If we got an error, then undo our
10680 	 * incrementing of 'r_mapcnt'.
10681 	 */
10682 
10683 	if (error) {
10684 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10685 		ASSERT(rp->r_mapcnt >= 0);
10686 	}
10687 	return (error);
10688 }
10689 
10690 static int
10691 nfs4_cmp(vnode_t *vp1, vnode_t *vp2)
10692 {
10693 
10694 	return (VTOR4(vp1) == VTOR4(vp2));
10695 }
10696 
10697 static int
10698 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10699 	offset_t offset, struct flk_callback *flk_cbp, cred_t *cr)
10700 {
10701 	int rc;
10702 	u_offset_t start, end;
10703 	rnode4_t *rp;
10704 	int error = 0, intr = INTR4(vp);
10705 	nfs4_error_t e;
10706 
10707 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10708 		return (EIO);
10709 
10710 	/* check for valid cmd parameter */
10711 	if (cmd != F_GETLK && cmd != F_SETLK && cmd != F_SETLKW)
10712 		return (EINVAL);
10713 
10714 	/* Verify l_type. */
10715 	switch (bfp->l_type) {
10716 	case F_RDLCK:
10717 		if (cmd != F_GETLK && !(flag & FREAD))
10718 			return (EBADF);
10719 		break;
10720 	case F_WRLCK:
10721 		if (cmd != F_GETLK && !(flag & FWRITE))
10722 			return (EBADF);
10723 		break;
10724 	case F_UNLCK:
10725 		intr = 0;
10726 		break;
10727 
10728 	default:
10729 		return (EINVAL);
10730 	}
10731 
10732 	/* check the validity of the lock range */
10733 	if (rc = flk_convert_lock_data(vp, bfp, &start, &end, offset))
10734 		return (rc);
10735 	if (rc = flk_check_lock_data(start, end, MAXEND))
10736 		return (rc);
10737 
10738 	/*
10739 	 * If the filesystem is mounted using local locking, pass the
10740 	 * request off to the local locking code.
10741 	 */
10742 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10743 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10744 			/*
10745 			 * For complete safety, we should be holding
10746 			 * r_lkserlock.  However, we can't call
10747 			 * nfs4_safelock and then fs_frlock while
10748 			 * holding r_lkserlock, so just invoke
10749 			 * nfs4_safelock and expect that this will
10750 			 * catch enough of the cases.
10751 			 */
10752 			if (!nfs4_safelock(vp, bfp, cr))
10753 				return (EAGAIN);
10754 		}
10755 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr));
10756 	}
10757 
10758 	rp = VTOR4(vp);
10759 
10760 	/*
10761 	 * Check whether the given lock request can proceed, given the
10762 	 * current file mappings.
10763 	 */
10764 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr))
10765 		return (EINTR);
10766 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10767 		if (!nfs4_safelock(vp, bfp, cr)) {
10768 			rc = EAGAIN;
10769 			goto done;
10770 		}
10771 	}
10772 
10773 	/*
10774 	 * Flush the cache after waiting for async I/O to finish.  For new
10775 	 * locks, this is so that the process gets the latest bits from the
10776 	 * server.  For unlocks, this is so that other clients see the
10777 	 * latest bits once the file has been unlocked.  If currently dirty
10778 	 * pages can't be flushed, then don't allow a lock to be set.  But
10779 	 * allow unlocks to succeed, to avoid having orphan locks on the
10780 	 * server.
10781 	 */
10782 	if (cmd != F_GETLK) {
10783 		mutex_enter(&rp->r_statelock);
10784 		while (rp->r_count > 0) {
10785 		    if (intr) {
10786 			klwp_t *lwp = ttolwp(curthread);
10787 
10788 			if (lwp != NULL)
10789 				lwp->lwp_nostop++;
10790 			if (cv_wait_sig(&rp->r_cv, &rp->r_statelock) == 0) {
10791 				if (lwp != NULL)
10792 					lwp->lwp_nostop--;
10793 				rc = EINTR;
10794 				break;
10795 			}
10796 			if (lwp != NULL)
10797 				lwp->lwp_nostop--;
10798 		    } else
10799 			cv_wait(&rp->r_cv, &rp->r_statelock);
10800 		}
10801 		mutex_exit(&rp->r_statelock);
10802 		if (rc != 0)
10803 			goto done;
10804 		error = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr);
10805 		if (error) {
10806 			if (error == ENOSPC || error == EDQUOT) {
10807 				mutex_enter(&rp->r_statelock);
10808 				if (!rp->r_error)
10809 					rp->r_error = error;
10810 				mutex_exit(&rp->r_statelock);
10811 			}
10812 			if (bfp->l_type != F_UNLCK) {
10813 				rc = ENOLCK;
10814 				goto done;
10815 			}
10816 		}
10817 	}
10818 
10819 	/*
10820 	 * Call the lock manager to do the real work of contacting
10821 	 * the server and obtaining the lock.
10822 	 */
10823 
10824 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, flag, offset,
10825 		cr, &e, NULL, NULL);
10826 	rc = e.error;
10827 
10828 	if (rc == 0)
10829 		nfs4_lockcompletion(vp, cmd);
10830 
10831 done:
10832 	nfs_rw_exit(&rp->r_lkserlock);
10833 
10834 	return (rc);
10835 }
10836 
10837 /*
10838  * Free storage space associated with the specified vnode.  The portion
10839  * to be freed is specified by bfp->l_start and bfp->l_len (already
10840  * normalized to a "whence" of 0).
10841  *
10842  * This is an experimental facility whose continued existence is not
10843  * guaranteed.  Currently, we only support the special case
10844  * of l_len == 0, meaning free to end of file.
10845  */
10846 /* ARGSUSED */
10847 static int
10848 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10849 	offset_t offset, cred_t *cr, caller_context_t *ct)
10850 {
10851 	int error;
10852 
10853 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10854 		return (EIO);
10855 	ASSERT(vp->v_type == VREG);
10856 	if (cmd != F_FREESP)
10857 		return (EINVAL);
10858 
10859 	error = convoff(vp, bfp, 0, offset);
10860 	if (!error) {
10861 		ASSERT(bfp->l_start >= 0);
10862 		if (bfp->l_len == 0) {
10863 			struct vattr va;
10864 
10865 			va.va_mask = AT_SIZE;
10866 			va.va_size = bfp->l_start;
10867 			error = nfs4setattr(vp, &va, 0, cr, NULL);
10868 		} else
10869 			error = EINVAL;
10870 	}
10871 
10872 	return (error);
10873 }
10874 
10875 /* ARGSUSED */
10876 static int
10877 nfs4_realvp(vnode_t *vp, vnode_t **vpp)
10878 {
10879 	rnode4_t *rp;
10880 	rp = VTOR4(vp);
10881 
10882 	if (IS_SHADOW(vp, rp)) {
10883 		vp = RTOV4(rp);
10884 	}
10885 	*vpp = vp;
10886 	return (0);
10887 }
10888 
10889 /*
10890  * Setup and add an address space callback to do the work of the delmap call.
10891  * The callback will (and must be) deleted in the actual callback function.
10892  *
10893  * This is done in order to take care of the problem that we have with holding
10894  * the address space's a_lock for a long period of time (e.g. if the NFS server
10895  * is down).  Callbacks will be executed in the address space code while the
10896  * a_lock is not held.  Holding the address space's a_lock causes things such
10897  * as ps and fork to hang because they are trying to acquire this lock as well.
10898  */
10899 /* ARGSUSED */
10900 static int
10901 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10902 	size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr)
10903 {
10904 	int			caller_found;
10905 	int			error;
10906 	rnode4_t		*rp;
10907 	nfs4_delmap_args_t	*dmapp;
10908 	nfs4_delmapcall_t	*delmap_call;
10909 
10910 	if (vp->v_flag & VNOMAP)
10911 		return (ENOSYS);
10912 
10913 	/*
10914 	 * A process may not change zones if it has NFS pages mmap'ed
10915 	 * in, so we can't legitimately get here from the wrong zone.
10916 	 */
10917 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10918 
10919 	rp = VTOR4(vp);
10920 
10921 	/*
10922 	 * The way that the address space of this process deletes its mapping
10923 	 * of this file is via the following call chains:
10924 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10925 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10926 	 *
10927 	 * With the use of address space callbacks we are allowed to drop the
10928 	 * address space lock, a_lock, while executing the NFS operations that
10929 	 * need to go over the wire.  Returning EAGAIN to the caller of this
10930 	 * function is what drives the execution of the callback that we add
10931 	 * below.  The callback will be executed by the address space code
10932 	 * after dropping the a_lock.  When the callback is finished, since
10933 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
10934 	 * is called again on the same segment to finish the rest of the work
10935 	 * that needs to happen during unmapping.
10936 	 *
10937 	 * This action of calling back into the segment driver causes
10938 	 * nfs4_delmap() to get called again, but since the callback was
10939 	 * already executed at this point, it already did the work and there
10940 	 * is nothing left for us to do.
10941 	 *
10942 	 * To Summarize:
10943 	 * - The first time nfs4_delmap is called by the current thread is when
10944 	 * we add the caller associated with this delmap to the delmap caller
10945 	 * list, add the callback, and return EAGAIN.
10946 	 * - The second time in this call chain when nfs4_delmap is called we
10947 	 * will find this caller in the delmap caller list and realize there
10948 	 * is no more work to do thus removing this caller from the list and
10949 	 * returning the error that was set in the callback execution.
10950 	 */
10951 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
10952 	if (caller_found) {
10953 		/*
10954 		 * 'error' is from the actual delmap operations.  To avoid
10955 		 * hangs, we need to handle the return of EAGAIN differently
10956 		 * since this is what drives the callback execution.
10957 		 * In this case, we don't want to return EAGAIN and do the
10958 		 * callback execution because there are none to execute.
10959 		 */
10960 		if (error == EAGAIN)
10961 			return (0);
10962 		else
10963 			return (error);
10964 	}
10965 
10966 	/* current caller was not in the list */
10967 	delmap_call = nfs4_init_delmapcall();
10968 
10969 	mutex_enter(&rp->r_statelock);
10970 	list_insert_tail(&rp->r_indelmap, delmap_call);
10971 	mutex_exit(&rp->r_statelock);
10972 
10973 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
10974 
10975 	dmapp->vp = vp;
10976 	dmapp->off = off;
10977 	dmapp->addr = addr;
10978 	dmapp->len = len;
10979 	dmapp->prot = prot;
10980 	dmapp->maxprot = maxprot;
10981 	dmapp->flags = flags;
10982 	dmapp->cr = cr;
10983 	dmapp->caller = delmap_call;
10984 
10985 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
10986 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
10987 
10988 	return (error ? error : EAGAIN);
10989 }
10990 
10991 static nfs4_delmapcall_t *
10992 nfs4_init_delmapcall()
10993 {
10994 	nfs4_delmapcall_t	*delmap_call;
10995 
10996 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
10997 	delmap_call->call_id = curthread;
10998 	delmap_call->error = 0;
10999 
11000 	return (delmap_call);
11001 }
11002 
11003 static void
11004 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11005 {
11006 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11007 }
11008 
11009 /*
11010  * Searches for the current delmap caller (based on curthread) in the list of
11011  * callers.  If it is found, we remove it and free the delmap caller.
11012  * Returns:
11013  *      0 if the caller wasn't found
11014  *      1 if the caller was found, removed and freed.  *errp will be set
11015  *	to what the result of the delmap was.
11016  */
11017 static int
11018 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11019 {
11020 	nfs4_delmapcall_t	*delmap_call;
11021 
11022 	/*
11023 	 * If the list doesn't exist yet, we create it and return
11024 	 * that the caller wasn't found.  No list = no callers.
11025 	 */
11026 	mutex_enter(&rp->r_statelock);
11027 	if (!(rp->r_flags & R4DELMAPLIST)) {
11028 		/* The list does not exist */
11029 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11030 		    offsetof(nfs4_delmapcall_t, call_node));
11031 		rp->r_flags |= R4DELMAPLIST;
11032 		mutex_exit(&rp->r_statelock);
11033 		return (0);
11034 	} else {
11035 		/* The list exists so search it */
11036 		for (delmap_call = list_head(&rp->r_indelmap);
11037 		    delmap_call != NULL;
11038 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11039 			if (delmap_call->call_id == curthread) {
11040 				/* current caller is in the list */
11041 				*errp = delmap_call->error;
11042 				list_remove(&rp->r_indelmap, delmap_call);
11043 				mutex_exit(&rp->r_statelock);
11044 				nfs4_free_delmapcall(delmap_call);
11045 				return (1);
11046 			}
11047 		}
11048 	}
11049 	mutex_exit(&rp->r_statelock);
11050 	return (0);
11051 }
11052 
11053 /*
11054  * Remove some pages from an mmap'd vnode.  Just update the
11055  * count of pages.  If doing close-to-open, then flush and
11056  * commit all of the pages associated with this file.
11057  * Otherwise, start an asynchronous page flush to write out
11058  * any dirty pages.  This will also associate a credential
11059  * with the rnode which can be used to write the pages.
11060  */
11061 /* ARGSUSED */
11062 static void
11063 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11064 {
11065 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11066 	rnode4_t		*rp;
11067 	mntinfo4_t		*mi;
11068 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11069 
11070 	rp = VTOR4(dmapp->vp);
11071 	mi = VTOMI4(dmapp->vp);
11072 
11073 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11074 	ASSERT(rp->r_mapcnt >= 0);
11075 
11076 	/*
11077 	 * Initiate a page flush and potential commit if there are
11078 	 * pages, the file system was not mounted readonly, the segment
11079 	 * was mapped shared, and the pages themselves were writeable.
11080 	 */
11081 	if (nfs4_has_pages(dmapp->vp) &&
11082 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11083 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11084 		mutex_enter(&rp->r_statelock);
11085 		rp->r_flags |= R4DIRTY;
11086 		mutex_exit(&rp->r_statelock);
11087 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11088 		    dmapp->len, dmapp->cr);
11089 		if (!e.error) {
11090 			mutex_enter(&rp->r_statelock);
11091 			e.error = rp->r_error;
11092 			rp->r_error = 0;
11093 			mutex_exit(&rp->r_statelock);
11094 		}
11095 	} else
11096 		e.error = 0;
11097 
11098 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11099 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11100 		    B_INVAL, dmapp->cr);
11101 
11102 	if (e.error) {
11103 		e.stat = puterrno4(e.error);
11104 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11105 			OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11106 		dmapp->caller->error = e.error;
11107 	}
11108 
11109 	/* Check to see if we need to close the file */
11110 
11111 	if (dmapp->vp->v_type == VREG) {
11112 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11113 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11114 
11115 		if (e.error != 0 || e.stat != NFS4_OK) {
11116 			/*
11117 			 * Since it is possible that e.error == 0 and
11118 			 * e.stat != NFS4_OK (and vice versa),
11119 			 * we do the proper checking in order to get both
11120 			 * e.error and e.stat reporting the correct info.
11121 			 */
11122 			if (e.stat == NFS4_OK)
11123 				e.stat = puterrno4(e.error);
11124 			if (e.error == 0)
11125 				e.error = geterrno4(e.stat);
11126 
11127 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11128 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11129 			dmapp->caller->error = e.error;
11130 		}
11131 	}
11132 
11133 	(void) as_delete_callback(as, arg);
11134 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11135 }
11136 
11137 
11138 static uint_t
11139 fattr4_maxfilesize_to_bits(uint64_t ll)
11140 {
11141 	uint_t l = 1;
11142 
11143 	if (ll == 0) {
11144 		return (0);
11145 	}
11146 
11147 	if (ll & 0xffffffff00000000) {
11148 		l += 32; ll >>= 32;
11149 	}
11150 	if (ll & 0xffff0000) {
11151 		l += 16; ll >>= 16;
11152 	}
11153 	if (ll & 0xff00) {
11154 		l += 8; ll >>= 8;
11155 	}
11156 	if (ll & 0xf0) {
11157 		l += 4; ll >>= 4;
11158 	}
11159 	if (ll & 0xc) {
11160 		l += 2; ll >>= 2;
11161 	}
11162 	if (ll & 0x2) {
11163 		l += 1;
11164 	}
11165 	return (l);
11166 }
11167 
11168 static int
11169 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr)
11170 {
11171 	int error;
11172 	hrtime_t t;
11173 	rnode4_t *rp;
11174 	nfs4_ga_res_t gar;
11175 	nfs4_ga_ext_res_t ger;
11176 
11177 	gar.n4g_ext_res = &ger;
11178 
11179 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11180 		return (EIO);
11181 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11182 		*valp = MAXPATHLEN;
11183 		return (0);
11184 	}
11185 	if (cmd == _PC_ACL_ENABLED) {
11186 		*valp = _ACL_ACE_ENABLED;
11187 		return (0);
11188 	}
11189 
11190 	rp = VTOR4(vp);
11191 	if (cmd == _PC_XATTR_EXISTS) {
11192 		/*
11193 		 * Eventually should attempt small client readdir before
11194 		 * going otw with GETATTR(FATTR4_NAMED_ATTR).  For now
11195 		 * just drive the OTW getattr.  This is required because
11196 		 * _PC_XATTR_EXISTS can only return true if attributes
11197 		 * exist -- simply checking for existance of the attrdir
11198 		 * is not sufficient.
11199 		 *
11200 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11201 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11202 		 * and we don't have any way to update the "base" object's
11203 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11204 		 * could help out.
11205 		 */
11206 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11207 		    rp->r_xattr_dir == NULL) {
11208 			*valp = rp->r_pathconf.pc4_xattr_exists;
11209 			return (0);
11210 		}
11211 	} else {  /* OLD CODE */
11212 		if (ATTRCACHE4_VALID(vp)) {
11213 			mutex_enter(&rp->r_statelock);
11214 			if (rp->r_pathconf.pc4_cache_valid) {
11215 				error = 0;
11216 				switch (cmd) {
11217 				case _PC_FILESIZEBITS:
11218 					*valp =
11219 					rp->r_pathconf.pc4_filesizebits;
11220 					break;
11221 				case _PC_LINK_MAX:
11222 					*valp =
11223 					rp->r_pathconf.pc4_link_max;
11224 					break;
11225 				case _PC_NAME_MAX:
11226 					*valp =
11227 					rp->r_pathconf.pc4_name_max;
11228 					break;
11229 				case _PC_CHOWN_RESTRICTED:
11230 					*valp =
11231 					rp->r_pathconf.pc4_chown_restricted;
11232 					break;
11233 				case _PC_NO_TRUNC:
11234 					*valp =
11235 					rp->r_pathconf.pc4_no_trunc;
11236 					break;
11237 				default:
11238 					error = EINVAL;
11239 					break;
11240 				}
11241 				mutex_exit(&rp->r_statelock);
11242 #ifdef DEBUG
11243 				nfs4_pathconf_cache_hits++;
11244 #endif
11245 				return (error);
11246 			}
11247 			mutex_exit(&rp->r_statelock);
11248 		}
11249 	}
11250 #ifdef DEBUG
11251 	nfs4_pathconf_cache_misses++;
11252 #endif
11253 
11254 	t = gethrtime();
11255 
11256 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11257 
11258 	if (error) {
11259 		mutex_enter(&rp->r_statelock);
11260 		rp->r_pathconf.pc4_cache_valid = FALSE;
11261 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11262 		mutex_exit(&rp->r_statelock);
11263 		return (error);
11264 	}
11265 
11266 	/* interpret the max filesize */
11267 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11268 		fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11269 
11270 	/* Store the attributes we just received */
11271 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11272 
11273 	switch (cmd) {
11274 	case _PC_FILESIZEBITS:
11275 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11276 		break;
11277 	case _PC_LINK_MAX:
11278 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11279 		break;
11280 	case _PC_NAME_MAX:
11281 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11282 		break;
11283 	case _PC_CHOWN_RESTRICTED:
11284 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11285 		break;
11286 	case _PC_NO_TRUNC:
11287 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11288 		break;
11289 	case _PC_XATTR_EXISTS:
11290 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists;
11291 		break;
11292 	default:
11293 		return (EINVAL);
11294 	}
11295 
11296 	return (0);
11297 }
11298 
11299 /*
11300  * Called by async thread to do synchronous pageio. Do the i/o, wait
11301  * for it to complete, and cleanup the page list when done.
11302  */
11303 static int
11304 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11305 	int flags, cred_t *cr)
11306 {
11307 	int error;
11308 
11309 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11310 
11311 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11312 	if (flags & B_READ)
11313 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11314 	else
11315 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11316 	return (error);
11317 }
11318 
11319 static int
11320 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11321 	int flags, cred_t *cr)
11322 {
11323 	int error;
11324 	rnode4_t *rp;
11325 
11326 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11327 		return (EIO);
11328 
11329 	if (pp == NULL)
11330 		return (EINVAL);
11331 
11332 	rp = VTOR4(vp);
11333 	mutex_enter(&rp->r_statelock);
11334 	rp->r_count++;
11335 	mutex_exit(&rp->r_statelock);
11336 
11337 	if (flags & B_ASYNC) {
11338 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11339 		    nfs4_sync_pageio);
11340 	} else
11341 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11342 	mutex_enter(&rp->r_statelock);
11343 	rp->r_count--;
11344 	cv_broadcast(&rp->r_cv);
11345 	mutex_exit(&rp->r_statelock);
11346 	return (error);
11347 }
11348 
11349 static void
11350 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr)
11351 {
11352 	int error;
11353 	rnode4_t *rp;
11354 	page_t *plist;
11355 	page_t *pptr;
11356 	offset3 offset;
11357 	count3 len;
11358 	k_sigset_t smask;
11359 
11360 	/*
11361 	 * We should get called with fl equal to either B_FREE or
11362 	 * B_INVAL.  Any other value is illegal.
11363 	 *
11364 	 * The page that we are either supposed to free or destroy
11365 	 * should be exclusive locked and its io lock should not
11366 	 * be held.
11367 	 */
11368 	ASSERT(fl == B_FREE || fl == B_INVAL);
11369 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11370 
11371 	rp = VTOR4(vp);
11372 
11373 	/*
11374 	 * If the page doesn't need to be committed or we shouldn't
11375 	 * even bother attempting to commit it, then just make sure
11376 	 * that the p_fsdata byte is clear and then either free or
11377 	 * destroy the page as appropriate.
11378 	 */
11379 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11380 		pp->p_fsdata = C_NOCOMMIT;
11381 		if (fl == B_FREE)
11382 			page_free(pp, dn);
11383 		else
11384 			page_destroy(pp, dn);
11385 		return;
11386 	}
11387 
11388 	/*
11389 	 * If there is a page invalidation operation going on, then
11390 	 * if this is one of the pages being destroyed, then just
11391 	 * clear the p_fsdata byte and then either free or destroy
11392 	 * the page as appropriate.
11393 	 */
11394 	mutex_enter(&rp->r_statelock);
11395 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11396 		mutex_exit(&rp->r_statelock);
11397 		pp->p_fsdata = C_NOCOMMIT;
11398 		if (fl == B_FREE)
11399 			page_free(pp, dn);
11400 		else
11401 			page_destroy(pp, dn);
11402 		return;
11403 	}
11404 
11405 	/*
11406 	 * If we are freeing this page and someone else is already
11407 	 * waiting to do a commit, then just unlock the page and
11408 	 * return.  That other thread will take care of commiting
11409 	 * this page.  The page can be freed sometime after the
11410 	 * commit has finished.  Otherwise, if the page is marked
11411 	 * as delay commit, then we may be getting called from
11412 	 * pvn_write_done, one page at a time.   This could result
11413 	 * in one commit per page, so we end up doing lots of small
11414 	 * commits instead of fewer larger commits.  This is bad,
11415 	 * we want do as few commits as possible.
11416 	 */
11417 	if (fl == B_FREE) {
11418 		if (rp->r_flags & R4COMMITWAIT) {
11419 			page_unlock(pp);
11420 			mutex_exit(&rp->r_statelock);
11421 			return;
11422 		}
11423 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11424 			pp->p_fsdata = C_COMMIT;
11425 			page_unlock(pp);
11426 			mutex_exit(&rp->r_statelock);
11427 			return;
11428 		}
11429 	}
11430 
11431 	/*
11432 	 * Check to see if there is a signal which would prevent an
11433 	 * attempt to commit the pages from being successful.  If so,
11434 	 * then don't bother with all of the work to gather pages and
11435 	 * generate the unsuccessful RPC.  Just return from here and
11436 	 * let the page be committed at some later time.
11437 	 */
11438 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11439 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11440 		sigunintr(&smask);
11441 		page_unlock(pp);
11442 		mutex_exit(&rp->r_statelock);
11443 		return;
11444 	}
11445 	sigunintr(&smask);
11446 
11447 	/*
11448 	 * We are starting to need to commit pages, so let's try
11449 	 * to commit as many as possible at once to reduce the
11450 	 * overhead.
11451 	 *
11452 	 * Set the `commit inprogress' state bit.  We must
11453 	 * first wait until any current one finishes.  Then
11454 	 * we initialize the c_pages list with this page.
11455 	 */
11456 	while (rp->r_flags & R4COMMIT) {
11457 		rp->r_flags |= R4COMMITWAIT;
11458 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11459 		rp->r_flags &= ~R4COMMITWAIT;
11460 	}
11461 	rp->r_flags |= R4COMMIT;
11462 	mutex_exit(&rp->r_statelock);
11463 	ASSERT(rp->r_commit.c_pages == NULL);
11464 	rp->r_commit.c_pages = pp;
11465 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11466 	rp->r_commit.c_commlen = PAGESIZE;
11467 
11468 	/*
11469 	 * Gather together all other pages which can be committed.
11470 	 * They will all be chained off r_commit.c_pages.
11471 	 */
11472 	nfs4_get_commit(vp);
11473 
11474 	/*
11475 	 * Clear the `commit inprogress' status and disconnect
11476 	 * the list of pages to be committed from the rnode.
11477 	 * At this same time, we also save the starting offset
11478 	 * and length of data to be committed on the server.
11479 	 */
11480 	plist = rp->r_commit.c_pages;
11481 	rp->r_commit.c_pages = NULL;
11482 	offset = rp->r_commit.c_commbase;
11483 	len = rp->r_commit.c_commlen;
11484 	mutex_enter(&rp->r_statelock);
11485 	rp->r_flags &= ~R4COMMIT;
11486 	cv_broadcast(&rp->r_commit.c_cv);
11487 	mutex_exit(&rp->r_statelock);
11488 
11489 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11490 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11491 		nfs4_async_commit(vp, plist, offset, len,
11492 		    cr, do_nfs4_async_commit);
11493 		return;
11494 	}
11495 
11496 	/*
11497 	 * Actually generate the COMMIT op over the wire operation.
11498 	 */
11499 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11500 
11501 	/*
11502 	 * If we got an error during the commit, just unlock all
11503 	 * of the pages.  The pages will get retransmitted to the
11504 	 * server during a putpage operation.
11505 	 */
11506 	if (error) {
11507 		while (plist != NULL) {
11508 			pptr = plist;
11509 			page_sub(&plist, pptr);
11510 			page_unlock(pptr);
11511 		}
11512 		return;
11513 	}
11514 
11515 	/*
11516 	 * We've tried as hard as we can to commit the data to stable
11517 	 * storage on the server.  We just unlock the rest of the pages
11518 	 * and clear the commit required state.  They will be put
11519 	 * onto the tail of the cachelist if they are nolonger
11520 	 * mapped.
11521 	 */
11522 	while (plist != pp) {
11523 		pptr = plist;
11524 		page_sub(&plist, pptr);
11525 		pptr->p_fsdata = C_NOCOMMIT;
11526 		page_unlock(pptr);
11527 	}
11528 
11529 	/*
11530 	 * It is possible that nfs4_commit didn't return error but
11531 	 * some other thread has modified the page we are going
11532 	 * to free/destroy.
11533 	 *    In this case we need to rewrite the page. Do an explicit check
11534 	 * before attempting to free/destroy the page. If modified, needs to
11535 	 * be rewritten so unlock the page and return.
11536 	 */
11537 	if (hat_ismod(pp)) {
11538 		pp->p_fsdata = C_NOCOMMIT;
11539 		page_unlock(pp);
11540 		return;
11541 	}
11542 
11543 	/*
11544 	 * Now, as appropriate, either free or destroy the page
11545 	 * that we were called with.
11546 	 */
11547 	pp->p_fsdata = C_NOCOMMIT;
11548 	if (fl == B_FREE)
11549 		page_free(pp, dn);
11550 	else
11551 		page_destroy(pp, dn);
11552 }
11553 
11554 /*
11555  * Commit requires that the current fh be the file written to.
11556  * The compound op structure is:
11557  *      PUTFH(file), COMMIT
11558  */
11559 static int
11560 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11561 {
11562 	COMPOUND4args_clnt args;
11563 	COMPOUND4res_clnt res;
11564 	COMMIT4res *cm_res;
11565 	nfs_argop4 argop[2];
11566 	nfs_resop4 *resop;
11567 	int doqueue;
11568 	mntinfo4_t *mi;
11569 	rnode4_t *rp;
11570 	cred_t *cred_otw = NULL;
11571 	bool_t needrecov = FALSE;
11572 	nfs4_recov_state_t recov_state;
11573 	nfs4_open_stream_t *osp = NULL;
11574 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11575 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11576 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11577 
11578 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11579 
11580 	rp = VTOR4(vp);
11581 
11582 	mi = VTOMI4(vp);
11583 	recov_state.rs_flags = 0;
11584 	recov_state.rs_num_retry_despite_err = 0;
11585 get_commit_cred:
11586 	/*
11587 	 * Releases the osp, if a valid open stream is provided.
11588 	 * Puts a hold on the cred_otw and the new osp (if found).
11589 	 */
11590 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11591 			&first_time, &last_time);
11592 	args.ctag = TAG_COMMIT;
11593 recov_retry:
11594 	/*
11595 	 * Commit ops: putfh file; commit
11596 	 */
11597 	args.array_len = 2;
11598 	args.array = argop;
11599 
11600 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11601 			    &recov_state, NULL);
11602 	if (e.error) {
11603 		crfree(cred_otw);
11604 		if (osp != NULL)
11605 			open_stream_rele(osp, rp);
11606 		return (e.error);
11607 	}
11608 
11609 	/* putfh directory */
11610 	argop[0].argop = OP_CPUTFH;
11611 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11612 
11613 	/* commit */
11614 	argop[1].argop = OP_COMMIT;
11615 	argop[1].nfs_argop4_u.opcommit.offset = offset;
11616 	argop[1].nfs_argop4_u.opcommit.count = count;
11617 
11618 	doqueue = 1;
11619 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
11620 
11621 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
11622 	if (!needrecov && e.error) {
11623 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
11624 			needrecov);
11625 		crfree(cred_otw);
11626 		if (e.error == EACCES && last_time == FALSE)
11627 			goto get_commit_cred;
11628 		if (osp != NULL)
11629 			open_stream_rele(osp, rp);
11630 		return (e.error);
11631 	}
11632 
11633 	if (needrecov) {
11634 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
11635 		    NULL, OP_COMMIT, NULL) == FALSE) {
11636 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11637 				&recov_state, needrecov);
11638 			if (!e.error)
11639 				(void) xdr_free(xdr_COMPOUND4res_clnt,
11640 								(caddr_t)&res);
11641 			goto recov_retry;
11642 		}
11643 		if (e.error) {
11644 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11645 				&recov_state, needrecov);
11646 			crfree(cred_otw);
11647 			if (osp != NULL)
11648 				open_stream_rele(osp, rp);
11649 			return (e.error);
11650 		}
11651 		/* fall through for res.status case */
11652 	}
11653 
11654 	if (res.status) {
11655 		e.error = geterrno4(res.status);
11656 		if (e.error == EACCES && last_time == FALSE) {
11657 			crfree(cred_otw);
11658 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11659 				&recov_state, needrecov);
11660 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11661 			goto get_commit_cred;
11662 		}
11663 		/*
11664 		 * Can't do a nfs4_purge_stale_fh here because this
11665 		 * can cause a deadlock.  nfs4_commit can
11666 		 * be called from nfs4_dispose which can be called
11667 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
11668 		 * can call back to pvn_vplist_dirty.
11669 		 */
11670 		if (e.error == ESTALE) {
11671 			mutex_enter(&rp->r_statelock);
11672 			rp->r_flags |= R4STALE;
11673 			if (!rp->r_error)
11674 				rp->r_error = e.error;
11675 			mutex_exit(&rp->r_statelock);
11676 			PURGE_ATTRCACHE4(vp);
11677 		} else {
11678 			mutex_enter(&rp->r_statelock);
11679 			if (!rp->r_error)
11680 				rp->r_error = e.error;
11681 			mutex_exit(&rp->r_statelock);
11682 		}
11683 	} else {
11684 		ASSERT(rp->r_flags & R4HAVEVERF);
11685 		resop = &res.array[1];	/* commit res */
11686 		cm_res = &resop->nfs_resop4_u.opcommit;
11687 		mutex_enter(&rp->r_statelock);
11688 		if (cm_res->writeverf == rp->r_writeverf) {
11689 			mutex_exit(&rp->r_statelock);
11690 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11691 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11692 				&recov_state, needrecov);
11693 			crfree(cred_otw);
11694 			if (osp != NULL)
11695 				open_stream_rele(osp, rp);
11696 			return (0);
11697 		}
11698 		nfs4_set_mod(vp);
11699 		rp->r_writeverf = cm_res->writeverf;
11700 		mutex_exit(&rp->r_statelock);
11701 		e.error = NFS_VERF_MISMATCH;
11702 	}
11703 
11704 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11705 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
11706 	crfree(cred_otw);
11707 	if (osp != NULL)
11708 		open_stream_rele(osp, rp);
11709 
11710 	return (e.error);
11711 }
11712 
11713 static void
11714 nfs4_set_mod(vnode_t *vp)
11715 {
11716 	page_t *pp;
11717 	kmutex_t *vphm;
11718 	rnode4_t *rp;
11719 
11720 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11721 
11722 	/* make sure we're looking at the master vnode, not a shadow */
11723 
11724 	rp = VTOR4(vp);
11725 	if (IS_SHADOW(vp, rp))
11726 		vp = RTOV4(rp);
11727 
11728 	vphm = page_vnode_mutex(vp);
11729 	mutex_enter(vphm);
11730 	/*
11731 	 * If there are no pages associated with this vnode, then
11732 	 * just return.
11733 	 */
11734 	if ((pp = vp->v_pages) == NULL) {
11735 		mutex_exit(vphm);
11736 		return;
11737 	}
11738 
11739 	do {
11740 		if (pp->p_fsdata != C_NOCOMMIT) {
11741 			hat_setmod(pp);
11742 			pp->p_fsdata = C_NOCOMMIT;
11743 		}
11744 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11745 	mutex_exit(vphm);
11746 }
11747 
11748 /*
11749  * This function is used to gather a page list of the pages which
11750  * can be committed on the server.
11751  *
11752  * The calling thread must have set R4COMMIT.  This bit is used to
11753  * serialize access to the commit structure in the rnode.  As long
11754  * as the thread has set R4COMMIT, then it can manipulate the commit
11755  * structure without requiring any other locks.
11756  *
11757  * When this function is called from nfs4_dispose() the page passed
11758  * into nfs4_dispose() will be SE_EXCL locked, and so this function
11759  * will skip it. This is not a problem since we initially add the
11760  * page to the r_commit page list.
11761  *
11762  */
11763 static void
11764 nfs4_get_commit(vnode_t *vp)
11765 {
11766 	rnode4_t *rp;
11767 	page_t *pp;
11768 	kmutex_t *vphm;
11769 
11770 	rp = VTOR4(vp);
11771 
11772 	ASSERT(rp->r_flags & R4COMMIT);
11773 
11774 	/* make sure we're looking at the master vnode, not a shadow */
11775 
11776 	if (IS_SHADOW(vp, rp))
11777 		vp = RTOV4(rp);
11778 
11779 	vphm = page_vnode_mutex(vp);
11780 	mutex_enter(vphm);
11781 
11782 	/*
11783 	 * If there are no pages associated with this vnode, then
11784 	 * just return.
11785 	 */
11786 	if ((pp = vp->v_pages) == NULL) {
11787 		mutex_exit(vphm);
11788 		return;
11789 	}
11790 
11791 	/*
11792 	 * Step through all of the pages associated with this vnode
11793 	 * looking for pages which need to be committed.
11794 	 */
11795 	do {
11796 		/*
11797 		 * First short-cut everything (without the page_lock)
11798 		 * and see if this page does not need to be committed
11799 		 * or is modified if so then we'll just skip it.
11800 		 */
11801 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
11802 			continue;
11803 
11804 		/*
11805 		 * Attempt to lock the page.  If we can't, then
11806 		 * someone else is messing with it or we have been
11807 		 * called from nfs4_dispose and this is the page that
11808 		 * nfs4_dispose was called with.. anyway just skip it.
11809 		 */
11810 		if (!page_trylock(pp, SE_EXCL))
11811 			continue;
11812 
11813 		/*
11814 		 * Lets check again now that we have the page lock.
11815 		 */
11816 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11817 			page_unlock(pp);
11818 			continue;
11819 		}
11820 
11821 		/* this had better not be a free page */
11822 		ASSERT(PP_ISFREE(pp) == 0);
11823 
11824 		/*
11825 		 * The page needs to be committed and we locked it.
11826 		 * Update the base and length parameters and add it
11827 		 * to r_pages.
11828 		 */
11829 		if (rp->r_commit.c_pages == NULL) {
11830 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11831 			rp->r_commit.c_commlen = PAGESIZE;
11832 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
11833 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
11834 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
11835 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11836 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
11837 			    <= pp->p_offset) {
11838 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11839 			    rp->r_commit.c_commbase + PAGESIZE;
11840 		}
11841 		page_add(&rp->r_commit.c_pages, pp);
11842 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11843 
11844 	mutex_exit(vphm);
11845 }
11846 
11847 /*
11848  * This routine is used to gather together a page list of the pages
11849  * which are to be committed on the server.  This routine must not
11850  * be called if the calling thread holds any locked pages.
11851  *
11852  * The calling thread must have set R4COMMIT.  This bit is used to
11853  * serialize access to the commit structure in the rnode.  As long
11854  * as the thread has set R4COMMIT, then it can manipulate the commit
11855  * structure without requiring any other locks.
11856  */
11857 static void
11858 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
11859 {
11860 
11861 	rnode4_t *rp;
11862 	page_t *pp;
11863 	u_offset_t end;
11864 	u_offset_t off;
11865 	ASSERT(len != 0);
11866 	rp = VTOR4(vp);
11867 	ASSERT(rp->r_flags & R4COMMIT);
11868 
11869 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11870 
11871 	/* make sure we're looking at the master vnode, not a shadow */
11872 
11873 	if (IS_SHADOW(vp, rp))
11874 		vp = RTOV4(rp);
11875 
11876 	/*
11877 	 * If there are no pages associated with this vnode, then
11878 	 * just return.
11879 	 */
11880 	if ((pp = vp->v_pages) == NULL)
11881 		return;
11882 	/*
11883 	 * Calculate the ending offset.
11884 	 */
11885 	end = soff + len;
11886 	for (off = soff; off < end; off += PAGESIZE) {
11887 		/*
11888 		 * Lookup each page by vp, offset.
11889 		 */
11890 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
11891 			continue;
11892 		/*
11893 		 * If this page does not need to be committed or is
11894 		 * modified, then just skip it.
11895 		 */
11896 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11897 			page_unlock(pp);
11898 			continue;
11899 		}
11900 
11901 		ASSERT(PP_ISFREE(pp) == 0);
11902 		/*
11903 		 * The page needs to be committed and we locked it.
11904 		 * Update the base and length parameters and add it
11905 		 * to r_pages.
11906 		 */
11907 		if (rp->r_commit.c_pages == NULL) {
11908 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11909 			rp->r_commit.c_commlen = PAGESIZE;
11910 		} else {
11911 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11912 			rp->r_commit.c_commbase + PAGESIZE;
11913 		}
11914 		page_add(&rp->r_commit.c_pages, pp);
11915 	}
11916 }
11917 
11918 /*
11919  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
11920  * Flushes and commits data to the server.
11921  */
11922 static int
11923 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
11924 {
11925 	int error;
11926 	verifier4 write_verf;
11927 	rnode4_t *rp = VTOR4(vp);
11928 
11929 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11930 
11931 	/*
11932 	 * Flush the data portion of the file and then commit any
11933 	 * portions which need to be committed.  This may need to
11934 	 * be done twice if the server has changed state since
11935 	 * data was last written.  The data will need to be
11936 	 * rewritten to the server and then a new commit done.
11937 	 *
11938 	 * In fact, this may need to be done several times if the
11939 	 * server is having problems and crashing while we are
11940 	 * attempting to do this.
11941 	 */
11942 
11943 top:
11944 	/*
11945 	 * Do a flush based on the poff and plen arguments.  This
11946 	 * will synchronously write out any modified pages in the
11947 	 * range specified by (poff, plen). This starts all of the
11948 	 * i/o operations which will be waited for in the next
11949 	 * call to nfs4_putpage
11950 	 */
11951 
11952 	mutex_enter(&rp->r_statelock);
11953 	write_verf = rp->r_writeverf;
11954 	mutex_exit(&rp->r_statelock);
11955 
11956 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr);
11957 	if (error == EAGAIN)
11958 		error = 0;
11959 
11960 	/*
11961 	 * Do a flush based on the poff and plen arguments.  This
11962 	 * will synchronously write out any modified pages in the
11963 	 * range specified by (poff, plen) and wait until all of
11964 	 * the asynchronous i/o's in that range are done as well.
11965 	 */
11966 	if (!error)
11967 		error = nfs4_putpage(vp, poff, plen, 0, cr);
11968 
11969 	if (error)
11970 		return (error);
11971 
11972 	mutex_enter(&rp->r_statelock);
11973 	if (rp->r_writeverf != write_verf) {
11974 		mutex_exit(&rp->r_statelock);
11975 		goto top;
11976 	}
11977 	mutex_exit(&rp->r_statelock);
11978 
11979 	/*
11980 	 * Now commit any pages which might need to be committed.
11981 	 * If the error, NFS_VERF_MISMATCH, is returned, then
11982 	 * start over with the flush operation.
11983 	 */
11984 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
11985 
11986 	if (error == NFS_VERF_MISMATCH)
11987 		goto top;
11988 
11989 	return (error);
11990 }
11991 
11992 /*
11993  * nfs4_commit_vp()  will wait for other pending commits and
11994  * will either commit the whole file or a range, plen dictates
11995  * if we commit whole file. a value of zero indicates the whole
11996  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
11997  */
11998 static int
11999 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12000 		cred_t *cr, int wait_on_writes)
12001 {
12002 	rnode4_t *rp;
12003 	page_t *plist;
12004 	offset3 offset;
12005 	count3 len;
12006 
12007 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12008 
12009 	rp = VTOR4(vp);
12010 
12011 	/*
12012 	 *  before we gather commitable pages make
12013 	 *  sure there are no outstanding async writes
12014 	 */
12015 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12016 		mutex_enter(&rp->r_statelock);
12017 		while (rp->r_count > 0) {
12018 			cv_wait(&rp->r_cv, &rp->r_statelock);
12019 		}
12020 		mutex_exit(&rp->r_statelock);
12021 	}
12022 
12023 	/*
12024 	 * Set the `commit inprogress' state bit.  We must
12025 	 * first wait until any current one finishes.
12026 	 */
12027 	mutex_enter(&rp->r_statelock);
12028 	while (rp->r_flags & R4COMMIT) {
12029 		rp->r_flags |= R4COMMITWAIT;
12030 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12031 		rp->r_flags &= ~R4COMMITWAIT;
12032 	}
12033 	rp->r_flags |= R4COMMIT;
12034 	mutex_exit(&rp->r_statelock);
12035 
12036 	/*
12037 	 * Gather all of the pages which need to be
12038 	 * committed.
12039 	 */
12040 	if (plen == 0)
12041 		nfs4_get_commit(vp);
12042 	else
12043 		nfs4_get_commit_range(vp, poff, plen);
12044 
12045 	/*
12046 	 * Clear the `commit inprogress' bit and disconnect the
12047 	 * page list which was gathered by nfs4_get_commit.
12048 	 */
12049 	plist = rp->r_commit.c_pages;
12050 	rp->r_commit.c_pages = NULL;
12051 	offset = rp->r_commit.c_commbase;
12052 	len = rp->r_commit.c_commlen;
12053 	mutex_enter(&rp->r_statelock);
12054 	rp->r_flags &= ~R4COMMIT;
12055 	cv_broadcast(&rp->r_commit.c_cv);
12056 	mutex_exit(&rp->r_statelock);
12057 
12058 	/*
12059 	 * If any pages need to be committed, commit them and
12060 	 * then unlock them so that they can be freed some
12061 	 * time later.
12062 	 */
12063 	if (plist == NULL)
12064 		return (0);
12065 
12066 	/*
12067 	 * No error occurred during the flush portion
12068 	 * of this operation, so now attempt to commit
12069 	 * the data to stable storage on the server.
12070 	 *
12071 	 * This will unlock all of the pages on the list.
12072 	 */
12073 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12074 }
12075 
12076 static int
12077 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12078 	cred_t *cr)
12079 {
12080 	int error;
12081 	page_t *pp;
12082 
12083 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12084 
12085 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12086 
12087 	/*
12088 	 * If we got an error, then just unlock all of the pages
12089 	 * on the list.
12090 	 */
12091 	if (error) {
12092 		while (plist != NULL) {
12093 			pp = plist;
12094 			page_sub(&plist, pp);
12095 			page_unlock(pp);
12096 		}
12097 		return (error);
12098 	}
12099 	/*
12100 	 * We've tried as hard as we can to commit the data to stable
12101 	 * storage on the server.  We just unlock the pages and clear
12102 	 * the commit required state.  They will get freed later.
12103 	 */
12104 	while (plist != NULL) {
12105 		pp = plist;
12106 		page_sub(&plist, pp);
12107 		pp->p_fsdata = C_NOCOMMIT;
12108 		page_unlock(pp);
12109 	}
12110 
12111 	return (error);
12112 }
12113 
12114 static void
12115 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12116 	cred_t *cr)
12117 {
12118 
12119 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12120 }
12121 
12122 /*ARGSUSED*/
12123 static int
12124 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr)
12125 {
12126 	int		error = 0;
12127 	mntinfo4_t	*mi;
12128 	vattr_t		va;
12129 	vsecattr_t	nfsace4_vsap;
12130 
12131 	mi = VTOMI4(vp);
12132 	if (nfs_zone() != mi->mi_zone)
12133 		return (EIO);
12134 	if (mi->mi_flags & MI4_ACL) {
12135 		/* if we have a delegation, return it */
12136 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12137 			(void) nfs4delegreturn(VTOR4(vp),
12138 					NFS4_DR_REOPEN|NFS4_DR_PUSH);
12139 
12140 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12141 			NFS4_ACL_SET);
12142 		if (error) /* EINVAL */
12143 			return (error);
12144 
12145 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12146 			/*
12147 			 * These are aclent_t type entries.
12148 			 */
12149 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12150 			    vp->v_type == VDIR, FALSE);
12151 			if (error)
12152 				return (error);
12153 		} else {
12154 			/*
12155 			 * These are ace_t type entries.
12156 			 */
12157 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12158 			    FALSE);
12159 			if (error)
12160 				return (error);
12161 		}
12162 		bzero(&va, sizeof (va));
12163 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12164 		vs_ace4_destroy(&nfsace4_vsap);
12165 		return (error);
12166 	}
12167 	return (ENOSYS);
12168 }
12169 
12170 static int
12171 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr)
12172 {
12173 	int		error;
12174 	mntinfo4_t	*mi;
12175 	nfs4_ga_res_t	gar;
12176 	rnode4_t	*rp = VTOR4(vp);
12177 
12178 	mi = VTOMI4(vp);
12179 	if (nfs_zone() != mi->mi_zone)
12180 		return (EIO);
12181 
12182 	bzero(&gar, sizeof (gar));
12183 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12184 
12185 	/*
12186 	 * vsecattr->vsa_mask holds the original acl request mask.
12187 	 * This is needed when determining what to return.
12188 	 * (See: nfs4_create_getsecattr_return())
12189 	 */
12190 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12191 	if (error) /* EINVAL */
12192 		return (error);
12193 
12194 	if (mi->mi_flags & MI4_ACL) {
12195 		/*
12196 		 * Check if the data is cached and the cache is valid.  If it
12197 		 * is we don't go over the wire.
12198 		 */
12199 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12200 			mutex_enter(&rp->r_statelock);
12201 			if (rp->r_secattr != NULL) {
12202 				error = nfs4_create_getsecattr_return(
12203 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12204 				    rp->r_attr.va_gid,
12205 				    vp->v_type == VDIR);
12206 				if (!error) { /* error == 0 - Success! */
12207 					mutex_exit(&rp->r_statelock);
12208 					return (error);
12209 				}
12210 			}
12211 			mutex_exit(&rp->r_statelock);
12212 		}
12213 
12214 		/*
12215 		 * The getattr otw call will always get both the acl, in
12216 		 * the form of a list of nfsace4's, and the number of acl
12217 		 * entries; independent of the value of gar.n4g_vsa.vsa_mask.
12218 		 */
12219 		gar.n4g_va.va_mask = AT_ALL;
12220 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12221 		if (error) {
12222 			vs_ace4_destroy(&gar.n4g_vsa);
12223 			if (error == ENOTSUP || error == EOPNOTSUPP)
12224 				error = fs_fab_acl(vp, vsecattr, flag, cr);
12225 			return (error);
12226 		}
12227 
12228 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12229 			/*
12230 			 * No error was returned, but according to the response
12231 			 * bitmap, neither was an acl.
12232 			 */
12233 			vs_ace4_destroy(&gar.n4g_vsa);
12234 			error = fs_fab_acl(vp, vsecattr, flag, cr);
12235 			return (error);
12236 		}
12237 
12238 		/*
12239 		 * Update the cache with the ACL.
12240 		 */
12241 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12242 
12243 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12244 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12245 		    vp->v_type == VDIR);
12246 		vs_ace4_destroy(&gar.n4g_vsa);
12247 		if ((error) && (vsecattr->vsa_mask &
12248 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12249 		    (error != EACCES)) {
12250 			error = fs_fab_acl(vp, vsecattr, flag, cr);
12251 		}
12252 		return (error);
12253 	}
12254 	error = fs_fab_acl(vp, vsecattr, flag, cr);
12255 	return (error);
12256 }
12257 
12258 /*
12259  * The function returns:
12260  * 	- 0 (zero) if the passed in "acl_mask" is a valid request.
12261  * 	- EINVAL if the passed in "acl_mask" is an invalid request.
12262  *
12263  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12264  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12265  *
12266  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12267  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12268  * - We have a count field set without the corresponding acl field set. (e.g. -
12269  * VSA_ACECNT is set, but VSA_ACE is not)
12270  */
12271 static int
12272 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12273 {
12274 	/* Shortcut the masks that are always valid. */
12275 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12276 		return (0);
12277 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12278 		return (0);
12279 
12280 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12281 		/*
12282 		 * We can't have any VSA_ACL type stuff in the mask now.
12283 		 */
12284 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12285 		    VSA_DFACLCNT))
12286 			return (EINVAL);
12287 
12288 		if (op == NFS4_ACL_SET) {
12289 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12290 				return (EINVAL);
12291 		}
12292 	}
12293 
12294 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12295 		/*
12296 		 * We can't have any VSA_ACE type stuff in the mask now.
12297 		 */
12298 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12299 			return (EINVAL);
12300 
12301 		if (op == NFS4_ACL_SET) {
12302 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12303 				return (EINVAL);
12304 
12305 			if ((acl_mask & VSA_DFACLCNT) &&
12306 			    !(acl_mask & VSA_DFACL))
12307 				return (EINVAL);
12308 		}
12309 	}
12310 	return (0);
12311 }
12312 
12313 /*
12314  * The theory behind creating the correct getsecattr return is simply this:
12315  * "Don't return anything that the caller is not expecting to have to free."
12316  */
12317 static int
12318 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12319 	uid_t uid, gid_t gid, int isdir)
12320 {
12321 	int error = 0;
12322 	/* Save the mask since the translators modify it. */
12323 	uint_t	orig_mask = vsap->vsa_mask;
12324 
12325 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12326 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid,
12327 		    FALSE, ((orig_mask & VSA_ACE) ? FALSE : TRUE));
12328 
12329 		if (error)
12330 			return (error);
12331 
12332 		/*
12333 		 * If the caller only asked for the ace count (VSA_ACECNT)
12334 		 * don't give them the full acl (VSA_ACE), free it.
12335 		 */
12336 		if (!orig_mask & VSA_ACE) {
12337 			if (vsap->vsa_aclentp != NULL) {
12338 				kmem_free(vsap->vsa_aclentp,
12339 				    vsap->vsa_aclcnt * sizeof (ace_t));
12340 				vsap->vsa_aclentp = NULL;
12341 			}
12342 		}
12343 		vsap->vsa_mask = orig_mask;
12344 
12345 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12346 	    VSA_DFACLCNT)) {
12347 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12348 		    isdir, FALSE,
12349 		    ((orig_mask & (VSA_ACL | VSA_DFACL)) ? FALSE : TRUE));
12350 
12351 		if (error)
12352 			return (error);
12353 
12354 		/*
12355 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12356 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12357 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12358 		 */
12359 		if (!orig_mask & VSA_ACL) {
12360 			if (vsap->vsa_aclentp != NULL) {
12361 				kmem_free(vsap->vsa_aclentp,
12362 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12363 				vsap->vsa_aclentp = NULL;
12364 			}
12365 		}
12366 
12367 		if (!orig_mask & VSA_DFACL) {
12368 			if (vsap->vsa_dfaclentp != NULL) {
12369 				kmem_free(vsap->vsa_dfaclentp,
12370 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12371 				vsap->vsa_dfaclentp = NULL;
12372 			}
12373 		}
12374 		vsap->vsa_mask = orig_mask;
12375 	}
12376 	return (0);
12377 }
12378 
12379 static int
12380 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr)
12381 {
12382 	int error;
12383 
12384 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12385 		return (EIO);
12386 	/*
12387 	 * check for valid cmd parameter
12388 	 */
12389 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12390 		return (EINVAL);
12391 
12392 	/*
12393 	 * Check access permissions
12394 	 */
12395 	if ((cmd & F_SHARE) &&
12396 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12397 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12398 		return (EBADF);
12399 
12400 	/*
12401 	 * If the filesystem is mounted using local locking, pass the
12402 	 * request off to the local share code.
12403 	 */
12404 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12405 		return (fs_shrlock(vp, cmd, shr, flag, cr));
12406 
12407 	switch (cmd) {
12408 	case F_SHARE:
12409 	case F_UNSHARE:
12410 		/*
12411 		 * This will be properly implemented later,
12412 		 * see RFE: 4823948 .
12413 		 */
12414 		error = EAGAIN;
12415 		break;
12416 
12417 	case F_HASREMOTELOCKS:
12418 		/*
12419 		 * NFS client can't store remote locks itself
12420 		 */
12421 		shr->s_access = 0;
12422 		error = 0;
12423 		break;
12424 
12425 	default:
12426 		error = EINVAL;
12427 		break;
12428 	}
12429 
12430 	return (error);
12431 }
12432 
12433 /*
12434  * Common code called by directory ops to update the attrcache
12435  */
12436 static int
12437 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12438 	hrtime_t t, vnode_t *vp, cred_t *cr)
12439 {
12440 	int error = 0;
12441 
12442 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12443 
12444 	if (status != NFS4_OK) {
12445 		/* getattr not done or failed */
12446 		PURGE_ATTRCACHE4(vp);
12447 		return (error);
12448 	}
12449 
12450 	if (garp) {
12451 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12452 	} else {
12453 		PURGE_ATTRCACHE4(vp);
12454 	}
12455 	return (error);
12456 }
12457 
12458 /*
12459  * Update directory caches for directory modification ops (link, rename, etc.)
12460  * When dinfo is NULL, manage dircaches in the old way.
12461  */
12462 static void
12463 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12464 		dirattr_info_t *dinfo)
12465 {
12466 	rnode4_t	*drp = VTOR4(dvp);
12467 
12468 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12469 
12470 	/* Purge rddir cache for dir since it changed */
12471 	if (drp->r_dir != NULL)
12472 		nfs4_purge_rddir_cache(dvp);
12473 
12474 	/*
12475 	 * If caller provided dinfo, then use it to manage dir caches.
12476 	 */
12477 	if (dinfo != NULL) {
12478 		if (vp != NULL) {
12479 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12480 			if (!VTOR4(vp)->created_v4) {
12481 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12482 				dnlc_update(dvp, nm, vp);
12483 			} else {
12484 				/*
12485 				 * XXX don't update if the created_v4 flag is
12486 				 * set
12487 				 */
12488 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12489 				NFS4_DEBUG(nfs4_client_state_debug,
12490 					(CE_NOTE, "nfs4_update_dircaches: "
12491 					"don't update dnlc: created_v4 flag"));
12492 			}
12493 		}
12494 
12495 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12496 				dinfo->di_cred, FALSE, cinfo);
12497 
12498 		return;
12499 	}
12500 
12501 	/*
12502 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12503 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12504 	 * attrs, the dir's attrs must be purged.
12505 	 *
12506 	 * XXX this check and dnlc update/purge should really be atomic,
12507 	 * XXX but can't use rnode statelock because it'll deadlock in
12508 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12509 	 * XXX does occur.
12510 	 *
12511 	 * XXX We also may want to check that atomic is true in the
12512 	 * XXX change_info struct. If it is not, the change_info may
12513 	 * XXX reflect changes by more than one clients which means that
12514 	 * XXX our cache may not be valid.
12515 	 */
12516 	PURGE_ATTRCACHE4(dvp);
12517 	if (drp->r_change == cinfo->before) {
12518 		/* no changes took place in the directory prior to our link */
12519 		if (vp != NULL) {
12520 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12521 			if (!VTOR4(vp)->created_v4) {
12522 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12523 				dnlc_update(dvp, nm, vp);
12524 			} else {
12525 				/*
12526 				 * XXX dont' update if the created_v4 flag
12527 				 * is set
12528 				 */
12529 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12530 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12531 					"nfs4_update_dircaches: don't"
12532 					" update dnlc: created_v4 flag"));
12533 			}
12534 		}
12535 	} else {
12536 		/* Another client modified directory - purge its dnlc cache */
12537 		dnlc_purge_vp(dvp);
12538 	}
12539 }
12540 
12541 /*
12542  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12543  * file.
12544  *
12545  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12546  * file (ie: client recovery) and otherwise set to FALSE.
12547  *
12548  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12549  * initiated) calling functions.
12550  *
12551  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12552  * of resending a 'lost' open request.
12553  *
12554  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12555  * server that hands out BAD_SEQID on open confirm.
12556  *
12557  * Errors are returned via the nfs4_error_t parameter.
12558  */
12559 void
12560 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12561 	bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12562 	bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12563 {
12564 	COMPOUND4args_clnt args;
12565 	COMPOUND4res_clnt res;
12566 	nfs_argop4 argop[2];
12567 	nfs_resop4 *resop;
12568 	int doqueue = 1;
12569 	mntinfo4_t *mi;
12570 	OPEN_CONFIRM4args *open_confirm_args;
12571 	int needrecov;
12572 
12573 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12574 #if DEBUG
12575 	mutex_enter(&oop->oo_lock);
12576 	ASSERT(oop->oo_seqid_inuse);
12577 	mutex_exit(&oop->oo_lock);
12578 #endif
12579 
12580 recov_retry_confirm:
12581 	nfs4_error_zinit(ep);
12582 	*retry_open = FALSE;
12583 
12584 	if (resend)
12585 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12586 	else
12587 		args.ctag = TAG_OPEN_CONFIRM;
12588 
12589 	args.array_len = 2;
12590 	args.array = argop;
12591 
12592 	/* putfh target fh */
12593 	argop[0].argop = OP_CPUTFH;
12594 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12595 
12596 	argop[1].argop = OP_OPEN_CONFIRM;
12597 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12598 
12599 	(*seqid) += 1;
12600 	open_confirm_args->seqid = *seqid;
12601 	open_confirm_args->open_stateid = *stateid;
12602 
12603 	mi = VTOMI4(vp);
12604 
12605 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12606 
12607 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12608 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12609 	}
12610 
12611 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12612 	if (!needrecov && ep->error)
12613 		return;
12614 
12615 	if (needrecov) {
12616 		bool_t abort = FALSE;
12617 
12618 		if (reopening_file == FALSE) {
12619 			nfs4_bseqid_entry_t *bsep = NULL;
12620 
12621 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12622 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12623 					vp, 0, args.ctag,
12624 					open_confirm_args->seqid);
12625 
12626 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp,
12627 				    NULL, NULL, NULL, OP_OPEN_CONFIRM, bsep);
12628 			if (bsep) {
12629 				kmem_free(bsep, sizeof (*bsep));
12630 				if (num_bseqid_retryp &&
12631 				    --(*num_bseqid_retryp) == 0)
12632 					abort = TRUE;
12633 			}
12634 		}
12635 		if ((ep->error == ETIMEDOUT ||
12636 					res.status == NFS4ERR_RESOURCE) &&
12637 					abort == FALSE && resend == FALSE) {
12638 			if (!ep->error)
12639 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12640 								(caddr_t)&res);
12641 
12642 			delay(SEC_TO_TICK(confirm_retry_sec));
12643 			goto recov_retry_confirm;
12644 		}
12645 		/* State may have changed so retry the entire OPEN op */
12646 		if (abort == FALSE)
12647 			*retry_open = TRUE;
12648 		else
12649 			*retry_open = FALSE;
12650 		if (!ep->error)
12651 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12652 		return;
12653 	}
12654 
12655 	if (res.status) {
12656 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12657 		return;
12658 	}
12659 
12660 	resop = &res.array[1];  /* open confirm res */
12661 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
12662 				stateid, sizeof (*stateid));
12663 
12664 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12665 }
12666 
12667 /*
12668  * Return the credentials associated with a client state object.  The
12669  * caller is responsible for freeing the credentials.
12670  */
12671 
12672 static cred_t *
12673 state_to_cred(nfs4_open_stream_t *osp)
12674 {
12675 	cred_t *cr;
12676 
12677 	/*
12678 	 * It's ok to not lock the open stream and open owner to get
12679 	 * the oo_cred since this is only written once (upon creation)
12680 	 * and will not change.
12681 	 */
12682 	cr = osp->os_open_owner->oo_cred;
12683 	crhold(cr);
12684 
12685 	return (cr);
12686 }
12687 
12688 /*
12689  * nfs4_find_sysid
12690  *
12691  * Find the sysid for the knetconfig associated with the given mi.
12692  */
12693 static struct lm_sysid *
12694 nfs4_find_sysid(mntinfo4_t *mi)
12695 {
12696 	ASSERT(nfs_zone() == mi->mi_zone);
12697 
12698 	/*
12699 	 * Switch from RDMA knconf to original mount knconf
12700 	 */
12701 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
12702 		    mi->mi_curr_serv->sv_hostname, NULL));
12703 }
12704 
12705 #ifdef DEBUG
12706 /*
12707  * Return a string version of the call type for easy reading.
12708  */
12709 static char *
12710 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
12711 {
12712 	switch (ctype) {
12713 	case NFS4_LCK_CTYPE_NORM:
12714 		return ("NORMAL");
12715 	case NFS4_LCK_CTYPE_RECLAIM:
12716 		return ("RECLAIM");
12717 	case NFS4_LCK_CTYPE_RESEND:
12718 		return ("RESEND");
12719 	case NFS4_LCK_CTYPE_REINSTATE:
12720 		return ("REINSTATE");
12721 	default:
12722 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
12723 			"type %d", ctype);
12724 		return ("");
12725 	}
12726 }
12727 #endif
12728 
12729 /*
12730  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
12731  * Unlock requests don't have an over-the-wire locktype, so we just return
12732  * something non-threatening.
12733  */
12734 
12735 static nfs_lock_type4
12736 flk_to_locktype(int cmd, int l_type)
12737 {
12738 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
12739 
12740 	switch (l_type) {
12741 	case F_UNLCK:
12742 		return (READ_LT);
12743 	case F_RDLCK:
12744 		if (cmd == F_SETLK)
12745 			return (READ_LT);
12746 		else
12747 			return (READW_LT);
12748 	case F_WRLCK:
12749 		if (cmd == F_SETLK)
12750 			return (WRITE_LT);
12751 		else
12752 			return (WRITEW_LT);
12753 	}
12754 	panic("flk_to_locktype");
12755 	/*NOTREACHED*/
12756 }
12757 
12758 /*
12759  * Do some preliminary checks for nfs4frlock.
12760  */
12761 static int
12762 nfs4frlock_validate_args(int cmd, flock64_t *flk, int flag, vnode_t *vp,
12763 	u_offset_t offset)
12764 {
12765 	int error = 0;
12766 
12767 	/*
12768 	 * If we are setting a lock, check that the file is opened
12769 	 * with the correct mode.
12770 	 */
12771 	if (cmd == F_SETLK || cmd == F_SETLKW) {
12772 		if ((flk->l_type == F_RDLCK && (flag & FREAD) == 0) ||
12773 		    (flk->l_type == F_WRLCK && (flag & FWRITE) == 0)) {
12774 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12775 			    "nfs4frlock_validate_args: file was opened with "
12776 			    "incorrect mode"));
12777 			return (EBADF);
12778 		}
12779 	}
12780 
12781 	/* Convert the offset. It may need to be restored before returning. */
12782 	if (error = convoff(vp, flk, 0, offset)) {
12783 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12784 		    "nfs4frlock_validate_args: convoff  =>  error= %d\n",
12785 		    error));
12786 		return (error);
12787 	}
12788 
12789 	return (error);
12790 }
12791 
12792 /*
12793  * Set the flock64's lm_sysid for nfs4frlock.
12794  */
12795 static int
12796 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
12797 {
12798 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12799 
12800 	/* Find the lm_sysid */
12801 	*lspp = nfs4_find_sysid(VTOMI4(vp));
12802 
12803 	if (*lspp == NULL) {
12804 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12805 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
12806 		return (ENOLCK);
12807 	}
12808 
12809 	flk->l_sysid = lm_sysidt(*lspp);
12810 
12811 	return (0);
12812 }
12813 
12814 /*
12815  * Do the remaining preliminary setup for nfs4frlock.
12816  */
12817 static void
12818 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
12819 	flock64_t *flk, short *whencep, vnode_t *vp, cred_t *search_cr,
12820 	cred_t **cred_otw)
12821 {
12822 	/*
12823 	 * set tick_delay to the base delay time.
12824 	 * (NFS4_BASE_WAIT_TIME is in secs)
12825 	 */
12826 
12827 	*tick_delayp = drv_usectohz(NFS4_BASE_WAIT_TIME * 1000 * 1000);
12828 
12829 	/*
12830 	 * If lock is relative to EOF, we need the newest length of the
12831 	 * file. Therefore invalidate the ATTR_CACHE.
12832 	 */
12833 
12834 	*whencep = flk->l_whence;
12835 
12836 	if (*whencep == 2)		/* SEEK_END */
12837 		PURGE_ATTRCACHE4(vp);
12838 
12839 	recov_statep->rs_flags = 0;
12840 	recov_statep->rs_num_retry_despite_err = 0;
12841 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
12842 }
12843 
12844 /*
12845  * Initialize and allocate the data structures necessary for
12846  * the nfs4frlock call.
12847  * Allocates argsp's op array, frees up the saved_rqstpp if there is one.
12848  */
12849 static void
12850 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
12851 	nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
12852 	bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
12853 	bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
12854 {
12855 	int		argoplist_size;
12856 	int		num_ops = 2;
12857 
12858 	*retry = FALSE;
12859 	*did_start_fop = FALSE;
12860 	*skip_get_err = FALSE;
12861 	lost_rqstp->lr_op = 0;
12862 	argoplist_size  = num_ops * sizeof (nfs_argop4);
12863 	/* fill array with zero */
12864 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
12865 
12866 	*argspp = argsp;
12867 	*respp = NULL;
12868 
12869 	argsp->array_len = num_ops;
12870 	argsp->array = *argopp;
12871 
12872 	/* initialize in case of error; will get real value down below */
12873 	argsp->ctag = TAG_NONE;
12874 
12875 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
12876 		*op_hintp = OH_LOCKU;
12877 	else
12878 		*op_hintp = OH_OTHER;
12879 }
12880 
12881 /*
12882  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
12883  * the proper nfs4_server_t for this instance of nfs4frlock.
12884  * Returns 0 (success) or an errno value.
12885  */
12886 static int
12887 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
12888 	nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
12889 	bool_t *did_start_fop, bool_t *startrecovp)
12890 {
12891 	int error = 0;
12892 	rnode4_t *rp;
12893 
12894 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12895 
12896 	if (ctype == NFS4_LCK_CTYPE_NORM) {
12897 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
12898 				recov_statep, startrecovp);
12899 		if (error)
12900 			return (error);
12901 		*did_start_fop = TRUE;
12902 	} else {
12903 		*did_start_fop = FALSE;
12904 		*startrecovp = FALSE;
12905 	}
12906 
12907 	if (!error) {
12908 		rp = VTOR4(vp);
12909 
12910 		/* If the file failed recovery, just quit. */
12911 		mutex_enter(&rp->r_statelock);
12912 		if (rp->r_flags & R4RECOVERR) {
12913 			error = EIO;
12914 		}
12915 		mutex_exit(&rp->r_statelock);
12916 	}
12917 
12918 	return (error);
12919 }
12920 
12921 /*
12922  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
12923  * resend nfs4frlock call is initiated by the recovery framework.
12924  * Acquires the lop and oop seqid synchronization.
12925  */
12926 static void
12927 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
12928 	COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
12929 	nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
12930 	LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
12931 {
12932 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
12933 	int error;
12934 
12935 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
12936 		(CE_NOTE,
12937 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
12938 	ASSERT(resend_rqstp != NULL);
12939 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
12940 	    resend_rqstp->lr_op == OP_LOCKU);
12941 
12942 	*oopp = resend_rqstp->lr_oop;
12943 	if (resend_rqstp->lr_oop) {
12944 		open_owner_hold(resend_rqstp->lr_oop);
12945 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
12946 		ASSERT(error == 0);	/* recov thread always succeeds */
12947 	}
12948 
12949 	/* Must resend this lost lock/locku request. */
12950 	ASSERT(resend_rqstp->lr_lop != NULL);
12951 	*lopp = resend_rqstp->lr_lop;
12952 	lock_owner_hold(resend_rqstp->lr_lop);
12953 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
12954 	ASSERT(error == 0);	/* recov thread always succeeds */
12955 
12956 	*ospp = resend_rqstp->lr_osp;
12957 	if (*ospp)
12958 		open_stream_hold(resend_rqstp->lr_osp);
12959 
12960 	if (resend_rqstp->lr_op == OP_LOCK) {
12961 		LOCK4args *lock_args;
12962 
12963 		argop->argop = OP_LOCK;
12964 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
12965 		lock_args->locktype = resend_rqstp->lr_locktype;
12966 		lock_args->reclaim =
12967 			(resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
12968 		lock_args->offset = resend_rqstp->lr_flk->l_start;
12969 		lock_args->length = resend_rqstp->lr_flk->l_len;
12970 		if (lock_args->length == 0)
12971 			lock_args->length = ~lock_args->length;
12972 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
12973 				mi2clientid(mi), &lock_args->locker);
12974 
12975 		switch (resend_rqstp->lr_ctype) {
12976 		case NFS4_LCK_CTYPE_RESEND:
12977 			argsp->ctag = TAG_LOCK_RESEND;
12978 			break;
12979 		case NFS4_LCK_CTYPE_REINSTATE:
12980 			argsp->ctag = TAG_LOCK_REINSTATE;
12981 			break;
12982 		case NFS4_LCK_CTYPE_RECLAIM:
12983 			argsp->ctag = TAG_LOCK_RECLAIM;
12984 			break;
12985 		default:
12986 			argsp->ctag = TAG_LOCK_UNKNOWN;
12987 			break;
12988 		}
12989 	} else {
12990 		LOCKU4args *locku_args;
12991 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
12992 
12993 		argop->argop = OP_LOCKU;
12994 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
12995 		locku_args->locktype = READ_LT;
12996 		locku_args->seqid = lop->lock_seqid + 1;
12997 		mutex_enter(&lop->lo_lock);
12998 		locku_args->lock_stateid = lop->lock_stateid;
12999 		mutex_exit(&lop->lo_lock);
13000 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13001 		locku_args->length = resend_rqstp->lr_flk->l_len;
13002 		if (locku_args->length == 0)
13003 			locku_args->length = ~locku_args->length;
13004 
13005 		switch (resend_rqstp->lr_ctype) {
13006 		case NFS4_LCK_CTYPE_RESEND:
13007 			argsp->ctag = TAG_LOCKU_RESEND;
13008 			break;
13009 		case NFS4_LCK_CTYPE_REINSTATE:
13010 			argsp->ctag = TAG_LOCKU_REINSTATE;
13011 			break;
13012 		default:
13013 			argsp->ctag = TAG_LOCK_UNKNOWN;
13014 			break;
13015 		}
13016 	}
13017 }
13018 
13019 /*
13020  * Setup the LOCKT4 arguments.
13021  */
13022 static void
13023 nfs4frlock_setup_lockt_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13024 	LOCKT4args **lockt_argsp, COMPOUND4args_clnt *argsp, flock64_t *flk,
13025 	rnode4_t *rp)
13026 {
13027 	LOCKT4args *lockt_args;
13028 
13029 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13030 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13031 	argop->argop = OP_LOCKT;
13032 	argsp->ctag = TAG_LOCKT;
13033 	lockt_args = &argop->nfs_argop4_u.oplockt;
13034 
13035 	/*
13036 	 * The locktype will be READ_LT unless it's
13037 	 * a write lock. We do this because the Solaris
13038 	 * system call allows the combination of
13039 	 * F_UNLCK and F_GETLK* and so in that case the
13040 	 * unlock is mapped to a read.
13041 	 */
13042 	if (flk->l_type == F_WRLCK)
13043 		lockt_args->locktype = WRITE_LT;
13044 	else
13045 		lockt_args->locktype = READ_LT;
13046 
13047 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13048 	/* set the lock owner4 args */
13049 	nfs4_setlockowner_args(&lockt_args->owner, rp,
13050 	    ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13051 	    flk->l_pid);
13052 	lockt_args->offset = flk->l_start;
13053 	lockt_args->length = flk->l_len;
13054 	if (flk->l_len == 0)
13055 		lockt_args->length = ~lockt_args->length;
13056 
13057 	*lockt_argsp = lockt_args;
13058 }
13059 
13060 /*
13061  * If the client is holding a delegation, and the open stream to be used
13062  * with this lock request is a delegation open stream, then re-open the stream.
13063  * Sets the nfs4_error_t to all zeros unless the open stream has already
13064  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13065  * means the caller should retry (like a recovery retry).
13066  */
13067 static void
13068 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13069 {
13070 	open_delegation_type4	dt;
13071 	bool_t			reopen_needed, force;
13072 	nfs4_open_stream_t	*osp;
13073 	open_claim_type4 	oclaim;
13074 	rnode4_t		*rp = VTOR4(vp);
13075 	mntinfo4_t		*mi = VTOMI4(vp);
13076 
13077 	ASSERT(nfs_zone() == mi->mi_zone);
13078 
13079 	nfs4_error_zinit(ep);
13080 
13081 	mutex_enter(&rp->r_statev4_lock);
13082 	dt = rp->r_deleg_type;
13083 	mutex_exit(&rp->r_statev4_lock);
13084 
13085 	if (dt != OPEN_DELEGATE_NONE) {
13086 		nfs4_open_owner_t	*oop;
13087 
13088 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13089 		if (!oop) {
13090 			ep->stat = NFS4ERR_IO;
13091 			return;
13092 		}
13093 		/* returns with 'os_sync_lock' held */
13094 		osp = find_open_stream(oop, rp);
13095 		if (!osp) {
13096 			open_owner_rele(oop);
13097 			ep->stat = NFS4ERR_IO;
13098 			return;
13099 		}
13100 
13101 		if (osp->os_failed_reopen) {
13102 			NFS4_DEBUG((nfs4_open_stream_debug ||
13103 				    nfs4_client_lock_debug), (CE_NOTE,
13104 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13105 			    "for osp %p, cr %p, rp %s", (void *)osp,
13106 			    (void *)cr, rnode4info(rp)));
13107 			mutex_exit(&osp->os_sync_lock);
13108 			open_stream_rele(osp, rp);
13109 			open_owner_rele(oop);
13110 			ep->stat = NFS4ERR_IO;
13111 			return;
13112 		}
13113 
13114 		/*
13115 		 * Determine whether a reopen is needed.  If this
13116 		 * is a delegation open stream, then send the open
13117 		 * to the server to give visibility to the open owner.
13118 		 * Even if it isn't a delegation open stream, we need
13119 		 * to check if the previous open CLAIM_DELEGATE_CUR
13120 		 * was sufficient.
13121 		 */
13122 
13123 		reopen_needed = osp->os_delegation ||
13124 		    ((lt == F_RDLCK &&
13125 			!(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13126 		    (lt == F_WRLCK &&
13127 			!(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13128 
13129 		mutex_exit(&osp->os_sync_lock);
13130 		open_owner_rele(oop);
13131 
13132 		if (reopen_needed) {
13133 			/*
13134 			 * Always use CLAIM_PREVIOUS after server reboot.
13135 			 * The server will reject CLAIM_DELEGATE_CUR if
13136 			 * it is used during the grace period.
13137 			 */
13138 			mutex_enter(&mi->mi_lock);
13139 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13140 				oclaim = CLAIM_PREVIOUS;
13141 				force = TRUE;
13142 			} else {
13143 				oclaim = CLAIM_DELEGATE_CUR;
13144 				force = FALSE;
13145 			}
13146 			mutex_exit(&mi->mi_lock);
13147 
13148 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13149 			if (ep->error == EAGAIN) {
13150 				nfs4_error_zinit(ep);
13151 				ep->stat = NFS4ERR_DELAY;
13152 			}
13153 		}
13154 		open_stream_rele(osp, rp);
13155 		osp = NULL;
13156 	}
13157 }
13158 
13159 /*
13160  * Setup the LOCKU4 arguments.
13161  * Returns errors via the nfs4_error_t.
13162  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13163  *			over-the-wire.  The caller must release the
13164  *			reference on *lopp.
13165  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13166  * (other)		unrecoverable error.
13167  */
13168 static void
13169 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13170 	LOCKU4args **locku_argsp, flock64_t *flk,
13171 	nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13172 	vnode_t *vp, int flag, u_offset_t offset, cred_t *cr,
13173 	bool_t *skip_get_err, bool_t *go_otwp)
13174 {
13175 	nfs4_lock_owner_t	*lop = NULL;
13176 	LOCKU4args		*locku_args;
13177 	pid_t			pid;
13178 	bool_t			is_spec = FALSE;
13179 	rnode4_t		*rp = VTOR4(vp);
13180 
13181 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13182 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13183 
13184 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13185 	if (ep->error || ep->stat)
13186 		return;
13187 
13188 	argop->argop = OP_LOCKU;
13189 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13190 		argsp->ctag = TAG_LOCKU_REINSTATE;
13191 	else
13192 		argsp->ctag = TAG_LOCKU;
13193 	locku_args = &argop->nfs_argop4_u.oplocku;
13194 	*locku_argsp = locku_args;
13195 
13196 	/*
13197 	 * XXX what should locku_args->locktype be?
13198 	 * setting to ALWAYS be READ_LT so at least
13199 	 * it is a valid locktype.
13200 	 */
13201 
13202 	locku_args->locktype = READ_LT;
13203 
13204 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13205 		flk->l_pid;
13206 
13207 	/*
13208 	 * Get the lock owner stateid.  If no lock owner
13209 	 * exists, return success.
13210 	 */
13211 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13212 	*lopp = lop;
13213 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13214 		is_spec = TRUE;
13215 	if (!lop || is_spec) {
13216 		/*
13217 		 * No lock owner so no locks to unlock.
13218 		 * Return success.  If there was a failed
13219 		 * reclaim earlier, the lock might still be
13220 		 * registered with the local locking code,
13221 		 * so notify it of the unlock.
13222 		 *
13223 		 * If the lockowner is using a special stateid,
13224 		 * then the original lock request (that created
13225 		 * this lockowner) was never successful, so we
13226 		 * have no lock to undo OTW.
13227 		 */
13228 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13229 			"nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13230 			"(%ld) so return success", (long)pid));
13231 
13232 		if (ctype == NFS4_LCK_CTYPE_NORM)
13233 			flk->l_pid = curproc->p_pid;
13234 		nfs4_register_lock_locally(vp, flk, flag, offset);
13235 		/*
13236 		 * Release our hold and NULL out so final_cleanup
13237 		 * doesn't try to end a lock seqid sync we
13238 		 * never started.
13239 		 */
13240 		if (is_spec) {
13241 			lock_owner_rele(lop);
13242 			*lopp = NULL;
13243 		}
13244 		*skip_get_err = TRUE;
13245 		*go_otwp = FALSE;
13246 		return;
13247 	}
13248 
13249 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13250 	if (ep->error == EAGAIN) {
13251 		lock_owner_rele(lop);
13252 		*lopp = NULL;
13253 		return;
13254 	}
13255 
13256 	mutex_enter(&lop->lo_lock);
13257 	locku_args->lock_stateid = lop->lock_stateid;
13258 	mutex_exit(&lop->lo_lock);
13259 	locku_args->seqid = lop->lock_seqid + 1;
13260 
13261 	/* leave the ref count on lop, rele after RPC call */
13262 
13263 	locku_args->offset = flk->l_start;
13264 	locku_args->length = flk->l_len;
13265 	if (flk->l_len == 0)
13266 		locku_args->length = ~locku_args->length;
13267 
13268 	*go_otwp = TRUE;
13269 }
13270 
13271 /*
13272  * Setup the LOCK4 arguments.
13273  *
13274  * Returns errors via the nfs4_error_t.
13275  * NFS4_OK		no problems
13276  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13277  * (other)		unrecoverable error
13278  */
13279 static void
13280 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13281 	nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13282 	nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13283 	flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13284 {
13285 	LOCK4args		*lock_args;
13286 	nfs4_open_owner_t	*oop = NULL;
13287 	nfs4_open_stream_t	*osp = NULL;
13288 	nfs4_lock_owner_t	*lop = NULL;
13289 	pid_t			pid;
13290 	rnode4_t		*rp = VTOR4(vp);
13291 
13292 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13293 
13294 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13295 	if (ep->error || ep->stat != NFS4_OK)
13296 		return;
13297 
13298 	argop->argop = OP_LOCK;
13299 	if (ctype == NFS4_LCK_CTYPE_NORM)
13300 		argsp->ctag = TAG_LOCK;
13301 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13302 		argsp->ctag = TAG_RELOCK;
13303 	else
13304 		argsp->ctag = TAG_LOCK_REINSTATE;
13305 	lock_args = &argop->nfs_argop4_u.oplock;
13306 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13307 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13308 	/*
13309 	 * Get the lock owner.  If no lock owner exists,
13310 	 * create a 'temporary' one and grab the open seqid
13311 	 * synchronization (which puts a hold on the open
13312 	 * owner and open stream).
13313 	 * This also grabs the lock seqid synchronization.
13314 	 */
13315 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid : flk->l_pid;
13316 	ep->stat =
13317 		nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13318 
13319 	if (ep->stat != NFS4_OK)
13320 		goto out;
13321 
13322 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13323 			&lock_args->locker);
13324 
13325 	lock_args->offset = flk->l_start;
13326 	lock_args->length = flk->l_len;
13327 	if (flk->l_len == 0)
13328 		lock_args->length = ~lock_args->length;
13329 	*lock_argsp = lock_args;
13330 out:
13331 	*oopp = oop;
13332 	*ospp = osp;
13333 	*lopp = lop;
13334 }
13335 
13336 /*
13337  * After we get the reply from the server, record the proper information
13338  * for possible resend lock requests.
13339  *
13340  * Allocates memory for the saved_rqstp if we have a lost lock to save.
13341  */
13342 static void
13343 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13344 	nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13345 	nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13346 	nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13347 {
13348 	bool_t unlock = (flk->l_type == F_UNLCK);
13349 
13350 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13351 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13352 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13353 
13354 	if (error != 0 && !unlock) {
13355 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13356 			    nfs4_client_lock_debug), (CE_NOTE,
13357 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13358 		    " for lop %p", (void *)lop));
13359 		ASSERT(lop != NULL);
13360 		mutex_enter(&lop->lo_lock);
13361 		lop->lo_pending_rqsts = 1;
13362 		mutex_exit(&lop->lo_lock);
13363 	}
13364 
13365 	lost_rqstp->lr_putfirst = FALSE;
13366 	lost_rqstp->lr_op = 0;
13367 
13368 	/*
13369 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13370 	 * recovery purposes so that the lock request that was sent
13371 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13372 	 * unmount.  This is done to have the client's local locking state
13373 	 * match the v4 server's state; that is, the request was
13374 	 * potentially received and accepted by the server but the client
13375 	 * thinks it was not.
13376 	 */
13377 	if (error == ETIMEDOUT || error == EINTR ||
13378 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13379 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13380 			    nfs4_client_lock_debug), (CE_NOTE,
13381 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13382 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13383 		    (void *)lop, (void *)oop, (void *)osp));
13384 		if (unlock)
13385 			lost_rqstp->lr_op = OP_LOCKU;
13386 		else {
13387 			lost_rqstp->lr_op = OP_LOCK;
13388 			lost_rqstp->lr_locktype = locktype;
13389 		}
13390 		/*
13391 		 * Objects are held and rele'd via the recovery code.
13392 		 * See nfs4_save_lost_rqst.
13393 		 */
13394 		lost_rqstp->lr_vp = vp;
13395 		lost_rqstp->lr_dvp = NULL;
13396 		lost_rqstp->lr_oop = oop;
13397 		lost_rqstp->lr_osp = osp;
13398 		lost_rqstp->lr_lop = lop;
13399 		lost_rqstp->lr_cr = cr;
13400 		switch (ctype) {
13401 		case NFS4_LCK_CTYPE_NORM:
13402 			flk->l_pid = ttoproc(curthread)->p_pid;
13403 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13404 			break;
13405 		case NFS4_LCK_CTYPE_REINSTATE:
13406 			lost_rqstp->lr_putfirst = TRUE;
13407 			lost_rqstp->lr_ctype = ctype;
13408 			break;
13409 		default:
13410 			break;
13411 		}
13412 		lost_rqstp->lr_flk = flk;
13413 	}
13414 }
13415 
13416 /*
13417  * Update lop's seqid.  Also update the seqid stored in a resend request,
13418  * if any.  (Some recovery errors increment the seqid, and we may have to
13419  * send the resend request again.)
13420  */
13421 
13422 static void
13423 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13424     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13425 {
13426 	if (lock_args) {
13427 		if (lock_args->locker.new_lock_owner == TRUE)
13428 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13429 		else {
13430 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13431 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13432 		}
13433 	} else if (locku_args) {
13434 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13435 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13436 	}
13437 }
13438 
13439 /*
13440  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13441  * COMPOUND4 args/res for calls that need to retry.
13442  * Switches the *cred_otwp to base_cr.
13443  */
13444 static void
13445 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13446     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13447     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13448     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13449     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13450 {
13451 	nfs4_open_owner_t	*oop = *oopp;
13452 	nfs4_open_stream_t	*osp = *ospp;
13453 	nfs4_lock_owner_t	*lop = *lopp;
13454 	nfs_argop4		*argop = (*argspp)->array;
13455 
13456 	if (*did_start_fop) {
13457 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13458 			    needrecov);
13459 		*did_start_fop = FALSE;
13460 	}
13461 	ASSERT((*argspp)->array_len == 2);
13462 	if (argop[1].argop == OP_LOCK)
13463 		nfs4args_lock_free(&argop[1]);
13464 	else if (argop[1].argop == OP_LOCKT)
13465 		nfs4args_lockt_free(&argop[1]);
13466 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13467 	if (!error)
13468 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13469 	*argspp = NULL;
13470 	*respp = NULL;
13471 
13472 	if (lop) {
13473 		nfs4_end_lock_seqid_sync(lop);
13474 		lock_owner_rele(lop);
13475 		*lopp = NULL;
13476 	}
13477 
13478 	/* need to free up the reference on osp for lock args */
13479 	if (osp != NULL) {
13480 		open_stream_rele(osp, VTOR4(vp));
13481 		*ospp = NULL;
13482 	}
13483 
13484 	/* need to free up the reference on oop for lock args */
13485 	if (oop != NULL) {
13486 		nfs4_end_open_seqid_sync(oop);
13487 		open_owner_rele(oop);
13488 		*oopp = NULL;
13489 	}
13490 
13491 	crfree(*cred_otwp);
13492 	*cred_otwp = base_cr;
13493 	crhold(*cred_otwp);
13494 }
13495 
13496 /*
13497  * Function to process the client's recovery for nfs4frlock.
13498  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13499  *
13500  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13501  * COMPOUND4 args/res for calls that need to retry.
13502  *
13503  * Note: the rp's r_lkserlock is *not* dropped during this path.
13504  */
13505 static bool_t
13506 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13507 	COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13508 	LOCK4args *lock_args, LOCKU4args *locku_args,
13509 	nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13510 	nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13511 	nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13512 	bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13513 {
13514 	nfs4_open_owner_t	*oop = *oopp;
13515 	nfs4_open_stream_t	*osp = *ospp;
13516 	nfs4_lock_owner_t	*lop = *lopp;
13517 
13518 	bool_t abort, retry;
13519 
13520 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13521 	ASSERT((*argspp) != NULL);
13522 	ASSERT((*respp) != NULL);
13523 	if (lock_args || locku_args)
13524 		ASSERT(lop != NULL);
13525 
13526 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13527 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13528 
13529 	retry = TRUE;
13530 	abort = FALSE;
13531 	if (needrecov) {
13532 		nfs4_bseqid_entry_t *bsep = NULL;
13533 		nfs_opnum4 op;
13534 
13535 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13536 
13537 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13538 			seqid4 seqid;
13539 
13540 			if (lock_args) {
13541 				if (lock_args->locker.new_lock_owner == TRUE)
13542 					seqid = lock_args->locker.locker4_u.
13543 						    open_owner.open_seqid;
13544 				else
13545 					seqid = lock_args->locker.locker4_u.
13546 						    lock_owner.lock_seqid;
13547 			} else if (locku_args) {
13548 				seqid = locku_args->seqid;
13549 			} else {
13550 				seqid = 0;
13551 			}
13552 
13553 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13554 				flk->l_pid, (*argspp)->ctag, seqid);
13555 		}
13556 
13557 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13558 			    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13559 			    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13560 			    NULL, op, bsep);
13561 
13562 		if (bsep)
13563 			kmem_free(bsep, sizeof (*bsep));
13564 	}
13565 
13566 	/*
13567 	 * Return that we do not want to retry the request for 3 cases:
13568 	 * 1. If we received EINTR or are bailing out because of a forced
13569 	 *    unmount, we came into this code path just for the sake of
13570 	 *    initiating recovery, we now need to return the error.
13571 	 * 2. If we have aborted recovery.
13572 	 * 3. We received NFS4ERR_BAD_SEQID.
13573 	 */
13574 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13575 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13576 		retry = FALSE;
13577 
13578 	if (*did_start_fop == TRUE) {
13579 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13580 		    needrecov);
13581 		*did_start_fop = FALSE;
13582 	}
13583 
13584 	if (retry == TRUE) {
13585 		nfs_argop4	*argop;
13586 
13587 		argop = (*argspp)->array;
13588 		ASSERT((*argspp)->array_len == 2);
13589 
13590 		if (argop[1].argop == OP_LOCK)
13591 			nfs4args_lock_free(&argop[1]);
13592 		else if (argop[1].argop == OP_LOCKT)
13593 			nfs4args_lockt_free(&argop[1]);
13594 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13595 		if (!ep->error)
13596 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13597 		*respp = NULL;
13598 		*argspp = NULL;
13599 	}
13600 
13601 	if (lop != NULL) {
13602 		nfs4_end_lock_seqid_sync(lop);
13603 		lock_owner_rele(lop);
13604 	}
13605 
13606 	*lopp = NULL;
13607 
13608 	/* need to free up the reference on osp for lock args */
13609 	if (osp != NULL) {
13610 		open_stream_rele(osp, rp);
13611 		*ospp = NULL;
13612 	}
13613 
13614 	/* need to free up the reference on oop for lock args */
13615 	if (oop != NULL) {
13616 		nfs4_end_open_seqid_sync(oop);
13617 		open_owner_rele(oop);
13618 		*oopp = NULL;
13619 	}
13620 
13621 	return (retry);
13622 }
13623 
13624 /*
13625  * Handles the succesful reply from the server for nfs4frlock.
13626  */
13627 static void
13628 nfs4frlock_results_ok(nfs4_lock_call_type_t ctype, int cmd, flock64_t *flk,
13629 	vnode_t *vp, int flag, u_offset_t offset,
13630 	nfs4_lost_rqst_t *resend_rqstp)
13631 {
13632 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13633 	if ((cmd == F_SETLK || cmd == F_SETLKW) &&
13634 	    (flk->l_type == F_RDLCK || flk->l_type == F_WRLCK)) {
13635 		if (ctype == NFS4_LCK_CTYPE_NORM) {
13636 			flk->l_pid = ttoproc(curthread)->p_pid;
13637 			/*
13638 			 * We do not register lost locks locally in
13639 			 * the 'resend' case since the user/application
13640 			 * doesn't think we have the lock.
13641 			 */
13642 			ASSERT(!resend_rqstp);
13643 			nfs4_register_lock_locally(vp, flk, flag, offset);
13644 		}
13645 	}
13646 }
13647 
13648 /*
13649  * Handle the DENIED reply from the server for nfs4frlock.
13650  * Returns TRUE if we should retry the request; FALSE otherwise.
13651  *
13652  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13653  * COMPOUND4 args/res for calls that need to retry.  Can also
13654  * drop and regrab the r_lkserlock.
13655  */
13656 static bool_t
13657 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13658 	LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13659 	nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13660 	vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13661 	nfs4_recov_state_t *recov_statep, int needrecov,
13662 	COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13663 	clock_t *tick_delayp, short *whencep, int *errorp,
13664 	nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13665 	bool_t *skip_get_err)
13666 {
13667 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13668 
13669 	if (lock_args) {
13670 		nfs4_open_owner_t	*oop = *oopp;
13671 		nfs4_open_stream_t	*osp = *ospp;
13672 		nfs4_lock_owner_t	*lop = *lopp;
13673 		int			intr;
13674 
13675 		/*
13676 		 * Blocking lock needs to sleep and retry from the request.
13677 		 *
13678 		 * Do not block and wait for 'resend' or 'reinstate'
13679 		 * lock requests, just return the error.
13680 		 *
13681 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13682 		 */
13683 		if (cmd == F_SETLKW) {
13684 			rnode4_t *rp = VTOR4(vp);
13685 			nfs_argop4 *argop = (*argspp)->array;
13686 
13687 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13688 
13689 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13690 				recov_statep, needrecov);
13691 			*did_start_fop = FALSE;
13692 			ASSERT((*argspp)->array_len == 2);
13693 			if (argop[1].argop == OP_LOCK)
13694 				nfs4args_lock_free(&argop[1]);
13695 			else if (argop[1].argop == OP_LOCKT)
13696 				nfs4args_lockt_free(&argop[1]);
13697 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13698 			if (*respp)
13699 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13700 							(caddr_t)*respp);
13701 			*argspp = NULL;
13702 			*respp = NULL;
13703 			nfs4_end_lock_seqid_sync(lop);
13704 			lock_owner_rele(lop);
13705 			*lopp = NULL;
13706 			if (osp != NULL) {
13707 				open_stream_rele(osp, rp);
13708 				*ospp = NULL;
13709 			}
13710 			if (oop != NULL) {
13711 				nfs4_end_open_seqid_sync(oop);
13712 				open_owner_rele(oop);
13713 				*oopp = NULL;
13714 			}
13715 
13716 			nfs_rw_exit(&rp->r_lkserlock);
13717 
13718 			intr = nfs4_block_and_wait(tick_delayp, rp);
13719 
13720 			if (intr) {
13721 				(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13722 						RW_WRITER, FALSE);
13723 				*errorp = EINTR;
13724 				return (FALSE);
13725 			}
13726 
13727 			(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13728 					RW_WRITER, FALSE);
13729 
13730 			/*
13731 			 * Make sure we are still safe to lock with
13732 			 * regards to mmapping.
13733 			 */
13734 			if (!nfs4_safelock(vp, flk, cr)) {
13735 				*errorp = EAGAIN;
13736 				return (FALSE);
13737 			}
13738 
13739 			return (TRUE);
13740 		}
13741 		if (ctype == NFS4_LCK_CTYPE_NORM)
13742 			*errorp = EAGAIN;
13743 		*skip_get_err = TRUE;
13744 		flk->l_whence = 0;
13745 		*whencep = 0;
13746 		return (FALSE);
13747 	} else if (lockt_args) {
13748 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13749 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
13750 
13751 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
13752 			flk, lockt_args);
13753 
13754 		/* according to NLM code */
13755 		*errorp = 0;
13756 		*whencep = 0;
13757 		*skip_get_err = TRUE;
13758 		return (FALSE);
13759 	}
13760 	return (FALSE);
13761 }
13762 
13763 /*
13764  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
13765  */
13766 static void
13767 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
13768 {
13769 	switch (resp->status) {
13770 	case NFS4ERR_ACCESS:
13771 	case NFS4ERR_ADMIN_REVOKED:
13772 	case NFS4ERR_BADHANDLE:
13773 	case NFS4ERR_BAD_RANGE:
13774 	case NFS4ERR_BAD_SEQID:
13775 	case NFS4ERR_BAD_STATEID:
13776 	case NFS4ERR_BADXDR:
13777 	case NFS4ERR_DEADLOCK:
13778 	case NFS4ERR_DELAY:
13779 	case NFS4ERR_EXPIRED:
13780 	case NFS4ERR_FHEXPIRED:
13781 	case NFS4ERR_GRACE:
13782 	case NFS4ERR_INVAL:
13783 	case NFS4ERR_ISDIR:
13784 	case NFS4ERR_LEASE_MOVED:
13785 	case NFS4ERR_LOCK_NOTSUPP:
13786 	case NFS4ERR_LOCK_RANGE:
13787 	case NFS4ERR_MOVED:
13788 	case NFS4ERR_NOFILEHANDLE:
13789 	case NFS4ERR_NO_GRACE:
13790 	case NFS4ERR_OLD_STATEID:
13791 	case NFS4ERR_OPENMODE:
13792 	case NFS4ERR_RECLAIM_BAD:
13793 	case NFS4ERR_RECLAIM_CONFLICT:
13794 	case NFS4ERR_RESOURCE:
13795 	case NFS4ERR_SERVERFAULT:
13796 	case NFS4ERR_STALE:
13797 	case NFS4ERR_STALE_CLIENTID:
13798 	case NFS4ERR_STALE_STATEID:
13799 		return;
13800 	default:
13801 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13802 		    "nfs4frlock_results_default: got unrecognizable "
13803 		    "res.status %d", resp->status));
13804 		*errorp = NFS4ERR_INVAL;
13805 	}
13806 }
13807 
13808 /*
13809  * The lock request was successful, so update the client's state.
13810  */
13811 static void
13812 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
13813 	LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
13814 	vnode_t *vp, flock64_t *flk, cred_t *cr,
13815 	nfs4_lost_rqst_t *resend_rqstp)
13816 {
13817 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13818 
13819 	if (lock_args) {
13820 		LOCK4res *lock_res;
13821 
13822 		lock_res = &resop->nfs_resop4_u.oplock;
13823 		/* update the stateid with server's response */
13824 
13825 		if (lock_args->locker.new_lock_owner == TRUE) {
13826 			mutex_enter(&lop->lo_lock);
13827 			lop->lo_just_created = NFS4_PERM_CREATED;
13828 			mutex_exit(&lop->lo_lock);
13829 		}
13830 
13831 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
13832 
13833 		/*
13834 		 * If the lock was the result of a resending a lost
13835 		 * request, we've synched up the stateid and seqid
13836 		 * with the server, but now the server might be out of sync
13837 		 * with what the application thinks it has for locks.
13838 		 * Clean that up here.  It's unclear whether we should do
13839 		 * this even if the filesystem has been forcibly unmounted.
13840 		 * For most servers, it's probably wasted effort, but
13841 		 * RFC3530 lets servers require that unlocks exactly match
13842 		 * the locks that are held.
13843 		 */
13844 		if (resend_rqstp != NULL &&
13845 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
13846 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
13847 		} else {
13848 			flk->l_whence = 0;
13849 		}
13850 	} else if (locku_args) {
13851 		LOCKU4res *locku_res;
13852 
13853 		locku_res = &resop->nfs_resop4_u.oplocku;
13854 
13855 		/* Update the stateid with the server's response */
13856 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
13857 	} else if (lockt_args) {
13858 		/* Switch the lock type to express success, see fcntl */
13859 		flk->l_type = F_UNLCK;
13860 		flk->l_whence = 0;
13861 	}
13862 }
13863 
13864 /*
13865  * Do final cleanup before exiting nfs4frlock.
13866  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13867  * COMPOUND4 args/res for calls that haven't already.
13868  */
13869 static void
13870 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
13871 	COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
13872 	nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
13873 	nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13874 	short whence, u_offset_t offset, struct lm_sysid *ls,
13875 	int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
13876 	bool_t did_start_fop, bool_t skip_get_err,
13877 	cred_t *cred_otw, cred_t *cred)
13878 {
13879 	mntinfo4_t	*mi = VTOMI4(vp);
13880 	rnode4_t	*rp = VTOR4(vp);
13881 	int		error = *errorp;
13882 	nfs_argop4	*argop;
13883 
13884 	ASSERT(nfs_zone() == mi->mi_zone);
13885 	/*
13886 	 * The client recovery code wants the raw status information,
13887 	 * so don't map the NFS status code to an errno value for
13888 	 * non-normal call types.
13889 	 */
13890 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13891 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
13892 			*errorp = geterrno4(resp->status);
13893 		if (did_start_fop == TRUE)
13894 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
13895 				needrecov);
13896 
13897 		if (!error && resp && resp->status == NFS4_OK) {
13898 		/*
13899 		 * We've established a new lock on the server, so invalidate
13900 		 * the pages associated with the vnode to get the most up to
13901 		 * date pages from the server after acquiring the lock. We
13902 		 * want to be sure that the read operation gets the newest data.
13903 		 * N.B.
13904 		 * We used to do this in nfs4frlock_results_ok but that doesn't
13905 		 * work since VOP_PUTPAGE can call nfs4_commit which calls
13906 		 * nfs4_start_fop. We flush the pages below after calling
13907 		 * nfs4_end_fop above
13908 		 */
13909 			int error;
13910 
13911 			error = VOP_PUTPAGE(vp, (u_offset_t)0,
13912 						0, B_INVAL, cred);
13913 
13914 			if (error && (error == ENOSPC || error == EDQUOT)) {
13915 				rnode4_t *rp = VTOR4(vp);
13916 
13917 				mutex_enter(&rp->r_statelock);
13918 				if (!rp->r_error)
13919 					rp->r_error = error;
13920 				mutex_exit(&rp->r_statelock);
13921 			}
13922 		}
13923 	}
13924 	if (argsp) {
13925 		ASSERT(argsp->array_len == 2);
13926 		argop = argsp->array;
13927 		if (argop[1].argop == OP_LOCK)
13928 			nfs4args_lock_free(&argop[1]);
13929 		else if (argop[1].argop == OP_LOCKT)
13930 			nfs4args_lockt_free(&argop[1]);
13931 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13932 		if (resp)
13933 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
13934 	}
13935 
13936 	/* free the reference on the lock owner */
13937 	if (lop != NULL) {
13938 		nfs4_end_lock_seqid_sync(lop);
13939 		lock_owner_rele(lop);
13940 	}
13941 
13942 	/* need to free up the reference on osp for lock args */
13943 	if (osp != NULL)
13944 		open_stream_rele(osp, rp);
13945 
13946 	/* need to free up the reference on oop for lock args */
13947 	if (oop != NULL) {
13948 		nfs4_end_open_seqid_sync(oop);
13949 		open_owner_rele(oop);
13950 	}
13951 
13952 	(void) convoff(vp, flk, whence, offset);
13953 
13954 	lm_rel_sysid(ls);
13955 
13956 	/*
13957 	 * Record debug information in the event we get EINVAL.
13958 	 */
13959 	mutex_enter(&mi->mi_lock);
13960 	if (*errorp == EINVAL && (lock_args || locku_args) &&
13961 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
13962 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
13963 			zcmn_err(getzoneid(), CE_NOTE,
13964 			    "%s operation failed with "
13965 			    "EINVAL probably since the server, %s,"
13966 			    " doesn't support POSIX style locking",
13967 			    lock_args ? "LOCK" : "LOCKU",
13968 			    mi->mi_curr_serv->sv_hostname);
13969 			mi->mi_flags |= MI4_LOCK_DEBUG;
13970 		}
13971 	}
13972 	mutex_exit(&mi->mi_lock);
13973 
13974 	if (cred_otw)
13975 		crfree(cred_otw);
13976 }
13977 
13978 /*
13979  * This calls the server and the local locking code.
13980  *
13981  * Client locks are registerred locally by oring the sysid with
13982  * LM_SYSID_CLIENT. The server registers locks locally using just the sysid.
13983  * We need to distinguish between the two to avoid collision in case one
13984  * machine is used as both client and server.
13985  *
13986  * Blocking lock requests will continually retry to acquire the lock
13987  * forever.
13988  *
13989  * The ctype is defined as follows:
13990  * NFS4_LCK_CTYPE_NORM: normal lock request.
13991  *
13992  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
13993  * recovery, get the pid from flk instead of curproc, and don't reregister
13994  * the lock locally.
13995  *
13996  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
13997  * that we will use the information passed in via resend_rqstp to setup the
13998  * lock/locku request.  This resend is the exact same request as the 'lost
13999  * lock', and is initiated by the recovery framework. A successful resend
14000  * request can initiate one or more reinstate requests.
14001  *
14002  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14003  * does not trigger additional reinstate requests.  This lock call type is
14004  * set for setting the v4 server's locking state back to match what the
14005  * client's local locking state is in the event of a received 'lost lock'.
14006  *
14007  * Errors are returned via the nfs4_error_t parameter.
14008  */
14009 void
14010 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14011 		int flag, u_offset_t offset, cred_t *cr, nfs4_error_t *ep,
14012 		nfs4_lost_rqst_t *resend_rqstp, int *did_reclaimp)
14013 {
14014 	COMPOUND4args_clnt	args, *argsp = NULL;
14015 	COMPOUND4res_clnt	res, *resp = NULL;
14016 	nfs_argop4	*argop;
14017 	nfs_resop4	*resop;
14018 	rnode4_t	*rp;
14019 	int		doqueue = 1;
14020 	clock_t		tick_delay;  /* delay in clock ticks */
14021 	struct lm_sysid	*ls;
14022 	LOCK4args	*lock_args = NULL;
14023 	LOCKU4args	*locku_args = NULL;
14024 	LOCKT4args	*lockt_args = NULL;
14025 	nfs4_open_owner_t *oop = NULL;
14026 	nfs4_open_stream_t *osp = NULL;
14027 	nfs4_lock_owner_t *lop = NULL;
14028 	bool_t		needrecov = FALSE;
14029 	nfs4_recov_state_t recov_state;
14030 	short		whence;
14031 	nfs4_op_hint_t	op_hint;
14032 	nfs4_lost_rqst_t lost_rqst;
14033 	bool_t		retry = FALSE;
14034 	bool_t		did_start_fop = FALSE;
14035 	bool_t		skip_get_err = FALSE;
14036 	cred_t		*cred_otw = NULL;
14037 	bool_t		recovonly;	/* just queue request */
14038 	int		frc_no_reclaim = 0;
14039 #ifdef DEBUG
14040 	char *name;
14041 #endif
14042 
14043 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14044 
14045 #ifdef DEBUG
14046 	name = fn_name(VTOSV(vp)->sv_name);
14047 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14048 	    "%s: cmd %d, type %d, offset %llu, start %"PRIx64", "
14049 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14050 	    "resend request %s", name, cmd, flk->l_type, offset, flk->l_start,
14051 	    flk->l_len, ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid :
14052 	    flk->l_pid, flk->l_sysid, nfs4frlock_get_call_type(ctype),
14053 	    resend_rqstp ? "TRUE" : "FALSE"));
14054 	kmem_free(name, MAXNAMELEN);
14055 #endif
14056 
14057 	nfs4_error_zinit(ep);
14058 	ep->error = nfs4frlock_validate_args(cmd, flk, flag, vp, offset);
14059 	if (ep->error)
14060 		return;
14061 	ep->error = nfs4frlock_get_sysid(&ls, vp, flk);
14062 	if (ep->error)
14063 		return;
14064 	nfs4frlock_pre_setup(&tick_delay, &recov_state, flk, &whence,
14065 	    vp, cr, &cred_otw);
14066 
14067 recov_retry:
14068 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14069 		&retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14070 	rp = VTOR4(vp);
14071 
14072 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14073 			    &did_start_fop, &recovonly);
14074 
14075 	if (ep->error)
14076 		goto out;
14077 
14078 	if (recovonly) {
14079 		/*
14080 		 * Leave the request for the recovery system to deal with.
14081 		 */
14082 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14083 		ASSERT(cmd != F_GETLK);
14084 		ASSERT(flk->l_type == F_UNLCK);
14085 
14086 		nfs4_error_init(ep, EINTR);
14087 		needrecov = TRUE;
14088 		lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14089 		if (lop != NULL) {
14090 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14091 				NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14092 			(void) nfs4_start_recovery(ep,
14093 				VTOMI4(vp), vp, NULL, NULL,
14094 				(lost_rqst.lr_op == OP_LOCK ||
14095 				lost_rqst.lr_op == OP_LOCKU) ?
14096 				&lost_rqst : NULL, OP_LOCKU, NULL);
14097 			lock_owner_rele(lop);
14098 			lop = NULL;
14099 		}
14100 		flk->l_pid = curproc->p_pid;
14101 		nfs4_register_lock_locally(vp, flk, flag, offset);
14102 		goto out;
14103 	}
14104 
14105 	/* putfh directory fh */
14106 	argop[0].argop = OP_CPUTFH;
14107 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14108 
14109 	/*
14110 	 * Set up the over-the-wire arguments and get references to the
14111 	 * open owner, etc.
14112 	 */
14113 
14114 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14115 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14116 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14117 			&argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14118 	} else {
14119 		bool_t go_otw = TRUE;
14120 
14121 		ASSERT(resend_rqstp == NULL);
14122 
14123 		switch (cmd) {
14124 		case F_GETLK:
14125 		case F_O_GETLK:
14126 			nfs4frlock_setup_lockt_args(ctype, &argop[1],
14127 					&lockt_args, argsp, flk, rp);
14128 			break;
14129 		case F_SETLKW:
14130 		case F_SETLK:
14131 			if (flk->l_type == F_UNLCK)
14132 				nfs4frlock_setup_locku_args(ctype,
14133 						&argop[1], &locku_args, flk,
14134 						&lop, ep, argsp,
14135 						vp, flag, offset, cr,
14136 						&skip_get_err, &go_otw);
14137 			else
14138 				nfs4frlock_setup_lock_args(ctype,
14139 					&lock_args, &oop, &osp, &lop, &argop[1],
14140 					argsp, flk, cmd, vp, cr, ep);
14141 
14142 			if (ep->error)
14143 				goto out;
14144 
14145 			switch (ep->stat) {
14146 			case NFS4_OK:
14147 				break;
14148 			case NFS4ERR_DELAY:
14149 				/* recov thread never gets this error */
14150 				ASSERT(resend_rqstp == NULL);
14151 				ASSERT(did_start_fop);
14152 
14153 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14154 				    &recov_state, TRUE);
14155 				did_start_fop = FALSE;
14156 				if (argop[1].argop == OP_LOCK)
14157 					nfs4args_lock_free(&argop[1]);
14158 				else if (argop[1].argop == OP_LOCKT)
14159 					nfs4args_lockt_free(&argop[1]);
14160 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14161 				argsp = NULL;
14162 				goto recov_retry;
14163 			default:
14164 				ep->error = EIO;
14165 				goto out;
14166 			}
14167 			break;
14168 		default:
14169 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14170 				"nfs4_frlock: invalid cmd %d", cmd));
14171 			ep->error = EINVAL;
14172 			goto out;
14173 		}
14174 
14175 		if (!go_otw)
14176 			goto out;
14177 	}
14178 
14179 	/* XXX should we use the local reclock as a cache ? */
14180 	/*
14181 	 * Unregister the lock with the local locking code before
14182 	 * contacting the server.  This avoids a potential race where
14183 	 * another process gets notified that it has been granted a lock
14184 	 * before we can unregister ourselves locally.
14185 	 */
14186 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK) {
14187 		if (ctype == NFS4_LCK_CTYPE_NORM)
14188 			flk->l_pid = ttoproc(curthread)->p_pid;
14189 		nfs4_register_lock_locally(vp, flk, flag, offset);
14190 	}
14191 
14192 	/*
14193 	 * Send the server the lock request.  Continually loop with a delay
14194 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14195 	 */
14196 	resp = &res;
14197 
14198 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14199 	    (CE_NOTE,
14200 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14201 	    rnode4info(rp)));
14202 
14203 	if (lock_args && frc_no_reclaim) {
14204 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14205 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14206 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14207 		lock_args->reclaim = FALSE;
14208 		if (did_reclaimp)
14209 			*did_reclaimp = 0;
14210 	}
14211 
14212 	/*
14213 	 * Do the OTW call.
14214 	 */
14215 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14216 
14217 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14218 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14219 
14220 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14221 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14222 	    "nfs4frlock: needrecov %d", needrecov));
14223 
14224 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14225 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14226 		    args.ctag);
14227 
14228 	/*
14229 	 * Check if one of these mutually exclusive error cases has
14230 	 * happened:
14231 	 *   need to swap credentials due to access error
14232 	 *   recovery is needed
14233 	 *   different error (only known case is missing Kerberos ticket)
14234 	 */
14235 
14236 	if ((ep->error == EACCES ||
14237 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14238 	    cred_otw != cr) {
14239 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14240 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14241 		    cr, &cred_otw);
14242 		goto recov_retry;
14243 	}
14244 
14245 	if (needrecov) {
14246 		/*
14247 		 * LOCKT requests don't need to recover from lost
14248 		 * requests since they don't create/modify state.
14249 		 */
14250 		if ((ep->error == EINTR ||
14251 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14252 		    lockt_args)
14253 			goto out;
14254 		/*
14255 		 * Do not attempt recovery for requests initiated by
14256 		 * the recovery framework.  Let the framework redrive them.
14257 		 */
14258 		if (ctype != NFS4_LCK_CTYPE_NORM)
14259 			goto out;
14260 		else {
14261 			ASSERT(resend_rqstp == NULL);
14262 		}
14263 
14264 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14265 			flk_to_locktype(cmd, flk->l_type),
14266 			oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14267 
14268 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14269 			    &resp, lock_args, locku_args, &oop, &osp, &lop,
14270 			    rp, vp, &recov_state, op_hint, &did_start_fop,
14271 			    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14272 
14273 		if (retry) {
14274 			ASSERT(oop == NULL);
14275 			ASSERT(osp == NULL);
14276 			ASSERT(lop == NULL);
14277 			goto recov_retry;
14278 		}
14279 		goto out;
14280 	}
14281 
14282 	/*
14283 	 * Bail out if have reached this point with ep->error set. Can
14284 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14285 	 * This happens if Kerberos ticket has expired or has been
14286 	 * destroyed.
14287 	 */
14288 	if (ep->error != 0)
14289 		goto out;
14290 
14291 	/*
14292 	 * Process the reply.
14293 	 */
14294 	switch (resp->status) {
14295 	case NFS4_OK:
14296 		resop = &resp->array[1];
14297 		nfs4frlock_results_ok(ctype, cmd, flk, vp, flag, offset,
14298 			resend_rqstp);
14299 		/*
14300 		 * Have a successful lock operation, now update state.
14301 		 */
14302 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14303 			resop, lop, vp, flk, cr, resend_rqstp);
14304 		break;
14305 
14306 	case NFS4ERR_DENIED:
14307 		resop = &resp->array[1];
14308 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14309 				&oop, &osp, &lop, cmd, vp, flk, op_hint,
14310 				&recov_state, needrecov, &argsp, &resp,
14311 				&tick_delay, &whence, &ep->error, resop, cr,
14312 				&did_start_fop, &skip_get_err);
14313 
14314 		if (retry) {
14315 			ASSERT(oop == NULL);
14316 			ASSERT(osp == NULL);
14317 			ASSERT(lop == NULL);
14318 			goto recov_retry;
14319 		}
14320 		break;
14321 	/*
14322 	 * If the server won't let us reclaim, fall-back to trying to lock
14323 	 * the file from scratch. Code elsewhere will check the changeinfo
14324 	 * to ensure the file hasn't been changed.
14325 	 */
14326 	case NFS4ERR_NO_GRACE:
14327 		if (lock_args && lock_args->reclaim == TRUE) {
14328 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14329 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14330 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14331 			frc_no_reclaim = 1;
14332 			/* clean up before retrying */
14333 			needrecov = 0;
14334 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14335 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14336 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14337 			goto recov_retry;
14338 		}
14339 		/* FALLTHROUGH */
14340 
14341 	default:
14342 		nfs4frlock_results_default(resp, &ep->error);
14343 		break;
14344 	}
14345 out:
14346 	/*
14347 	 * Process and cleanup from error.  Make interrupted unlock
14348 	 * requests look successful, since they will be handled by the
14349 	 * client recovery code.
14350 	 */
14351 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14352 		needrecov, oop, osp, lop, flk, whence, offset, ls, &ep->error,
14353 		lock_args, locku_args, did_start_fop,
14354 		skip_get_err, cred_otw, cr);
14355 
14356 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14357 	    (cmd == F_SETLK || cmd == F_SETLKW))
14358 		ep->error = 0;
14359 }
14360 
14361 /*
14362  * nfs4_safelock:
14363  *
14364  * Return non-zero if the given lock request can be handled without
14365  * violating the constraints on concurrent mapping and locking.
14366  */
14367 
14368 static int
14369 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14370 {
14371 	rnode4_t *rp = VTOR4(vp);
14372 	struct vattr va;
14373 	int error;
14374 
14375 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14376 	ASSERT(rp->r_mapcnt >= 0);
14377 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14378 		"(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14379 		"write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14380 		bfp->l_start, bfp->l_len, rp->r_mapcnt));
14381 
14382 	if (rp->r_mapcnt == 0)
14383 		return (1);		/* always safe if not mapped */
14384 
14385 	/*
14386 	 * If the file is already mapped and there are locks, then they
14387 	 * should be all safe locks.  So adding or removing a lock is safe
14388 	 * as long as the new request is safe (i.e., whole-file, meaning
14389 	 * length and starting offset are both zero).
14390 	 */
14391 
14392 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14393 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14394 			"cannot lock a memory mapped file unless locking the "
14395 			"entire file: start %"PRIx64", len %"PRIx64,
14396 			bfp->l_start, bfp->l_len));
14397 		return (0);
14398 	}
14399 
14400 	/* mandatory locking and mapping don't mix */
14401 	va.va_mask = AT_MODE;
14402 	error = VOP_GETATTR(vp, &va, 0, cr);
14403 	if (error != 0) {
14404 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14405 		"getattr error %d", error));
14406 		return (0);		/* treat errors conservatively */
14407 	}
14408 	if (MANDLOCK(vp, va.va_mode)) {
14409 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14410 			"cannot mandatory lock and mmap a file"));
14411 		return (0);
14412 	}
14413 
14414 	return (1);
14415 }
14416 
14417 
14418 /*
14419  * Register the lock locally within Solaris.
14420  * As the client, we "or" the sysid with LM_SYSID_CLIENT when
14421  * recording locks locally.
14422  *
14423  * This should handle conflicts/cooperation with NFS v2/v3 since all locks
14424  * are registered locally.
14425  */
14426 void
14427 nfs4_register_lock_locally(vnode_t *vp, struct flock64 *flk, int flag,
14428 	u_offset_t offset)
14429 {
14430 	int oldsysid;
14431 	int error;
14432 #ifdef DEBUG
14433 	char *name;
14434 #endif
14435 
14436 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14437 
14438 #ifdef DEBUG
14439 	name = fn_name(VTOSV(vp)->sv_name);
14440 	NFS4_DEBUG(nfs4_client_lock_debug,
14441 	    (CE_NOTE, "nfs4_register_lock_locally: %s: type %d, "
14442 	    "start %"PRIx64", length %"PRIx64", pid %ld, sysid %d",
14443 	    name, flk->l_type, flk->l_start, flk->l_len, (long)flk->l_pid,
14444 	    flk->l_sysid));
14445 	kmem_free(name, MAXNAMELEN);
14446 #endif
14447 
14448 	/* register the lock with local locking */
14449 	oldsysid = flk->l_sysid;
14450 	flk->l_sysid |= LM_SYSID_CLIENT;
14451 	error = reclock(vp, flk, SETFLCK, flag, offset, NULL);
14452 #ifdef DEBUG
14453 	if (error != 0) {
14454 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14455 			"nfs4_register_lock_locally: could not register with"
14456 			" local locking"));
14457 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14458 			"error %d, vp 0x%p, pid %d, sysid 0x%x",
14459 			error, (void *)vp, flk->l_pid, flk->l_sysid));
14460 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14461 			"type %d off 0x%" PRIx64 " len 0x%" PRIx64,
14462 			flk->l_type, flk->l_start, flk->l_len));
14463 		(void) reclock(vp, flk, 0, flag, offset, NULL);
14464 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14465 			"blocked by pid %d sysid 0x%x type %d "
14466 			"off 0x%" PRIx64 " len 0x%" PRIx64,
14467 			flk->l_pid, flk->l_sysid, flk->l_type, flk->l_start,
14468 			flk->l_len));
14469 	}
14470 #endif
14471 	flk->l_sysid = oldsysid;
14472 }
14473 
14474 /*
14475  * nfs4_lockrelease:
14476  *
14477  * Release any locks on the given vnode that are held by the current
14478  * process.  Also removes the lock owner (if one exists) from the rnode's
14479  * list.
14480  */
14481 static int
14482 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14483 {
14484 	flock64_t ld;
14485 	int ret, error;
14486 	rnode4_t *rp;
14487 	nfs4_lock_owner_t *lop;
14488 	nfs4_recov_state_t recov_state;
14489 	mntinfo4_t *mi;
14490 	bool_t possible_orphan = FALSE;
14491 	bool_t recovonly;
14492 
14493 	ASSERT((uintptr_t)vp > KERNELBASE);
14494 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14495 
14496 	rp = VTOR4(vp);
14497 	mi = VTOMI4(vp);
14498 
14499 	/*
14500 	 * If we have not locked anything then we can
14501 	 * just return since we have no work to do.
14502 	 */
14503 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14504 		return (0);
14505 	}
14506 
14507 	/*
14508 	 * We need to comprehend that another thread may
14509 	 * kick off recovery and the lock_owner we have stashed
14510 	 * in lop might be invalid so we should NOT cache it
14511 	 * locally!
14512 	 */
14513 	recov_state.rs_flags = 0;
14514 	recov_state.rs_num_retry_despite_err = 0;
14515 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14516 			    &recovonly);
14517 	if (error) {
14518 		mutex_enter(&rp->r_statelock);
14519 		rp->r_flags |= R4LODANGLERS;
14520 		mutex_exit(&rp->r_statelock);
14521 		return (error);
14522 	}
14523 
14524 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14525 
14526 	/*
14527 	 * Check if the lock owner might have a lock (request was sent but
14528 	 * no response was received).  Also check if there are any remote
14529 	 * locks on the file.  (In theory we shouldn't have to make this
14530 	 * second check if there's no lock owner, but for now we'll be
14531 	 * conservative and do it anyway.)  If either condition is true,
14532 	 * send an unlock for the entire file to the server.
14533 	 *
14534 	 * Note that no explicit synchronization is needed here.  At worst,
14535 	 * flk_has_remote_locks() will return a false positive, in which case
14536 	 * the unlock call wastes time but doesn't harm correctness.
14537 	 */
14538 
14539 	if (lop) {
14540 		mutex_enter(&lop->lo_lock);
14541 		possible_orphan = lop->lo_pending_rqsts;
14542 		mutex_exit(&lop->lo_lock);
14543 		lock_owner_rele(lop);
14544 	}
14545 
14546 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14547 
14548 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14549 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14550 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14551 	    (void *)lop));
14552 
14553 	if (possible_orphan || flk_has_remote_locks(vp)) {
14554 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14555 		ld.l_whence = 0;	/* unlock from start of file */
14556 		ld.l_start = 0;
14557 		ld.l_len = 0;		/* do entire file */
14558 
14559 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL, cr);
14560 
14561 		if (ret != 0) {
14562 			/*
14563 			 * If VOP_FRLOCK fails, make sure we unregister
14564 			 * local locks before we continue.
14565 			 */
14566 			ld.l_pid = ttoproc(curthread)->p_pid;
14567 			nfs4_register_lock_locally(vp, &ld, flag, offset);
14568 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14569 				"nfs4_lockrelease: lock release error on vp"
14570 				" %p: error %d.\n", (void *)vp, ret));
14571 		}
14572 	}
14573 
14574 	recov_state.rs_flags = 0;
14575 	recov_state.rs_num_retry_despite_err = 0;
14576 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14577 			    &recovonly);
14578 	if (error) {
14579 		mutex_enter(&rp->r_statelock);
14580 		rp->r_flags |= R4LODANGLERS;
14581 		mutex_exit(&rp->r_statelock);
14582 		return (error);
14583 	}
14584 
14585 	/*
14586 	 * So, here we're going to need to retrieve the lock-owner
14587 	 * again (in case recovery has done a switch-a-roo) and
14588 	 * remove it because we can.
14589 	 */
14590 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14591 
14592 	if (lop) {
14593 		nfs4_rnode_remove_lock_owner(rp, lop);
14594 		lock_owner_rele(lop);
14595 	}
14596 
14597 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14598 	return (0);
14599 }
14600 
14601 /*
14602  * Wait for 'tick_delay' clock ticks.
14603  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14604  * NOTE: lock_lease_time is in seconds.
14605  *
14606  * XXX For future improvements, should implement a waiting queue scheme.
14607  */
14608 static int
14609 nfs4_block_and_wait(clock_t *tick_delay, rnode4_t *rp)
14610 {
14611 	long milliseconds_delay;
14612 	time_t lock_lease_time;
14613 
14614 	/* wait tick_delay clock ticks or siginteruptus */
14615 	if (delay_sig(*tick_delay)) {
14616 		return (EINTR);
14617 	}
14618 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14619 		"reissue the lock request: blocked for %ld clock ticks: %ld "
14620 		"milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14621 
14622 	/* get the lease time */
14623 	lock_lease_time = r2lease_time(rp);
14624 
14625 	/* drv_hztousec converts ticks to microseconds */
14626 	milliseconds_delay = drv_hztousec(*tick_delay) / 1000;
14627 	if (milliseconds_delay < lock_lease_time * 1000) {
14628 		*tick_delay = 2 * *tick_delay;
14629 		if (drv_hztousec(*tick_delay) > lock_lease_time * 1000 * 1000)
14630 			*tick_delay = drv_usectohz(lock_lease_time*1000*1000);
14631 	}
14632 	return (0);
14633 }
14634 
14635 
14636 void
14637 nfs4_vnops_init(void)
14638 {
14639 }
14640 
14641 void
14642 nfs4_vnops_fini(void)
14643 {
14644 }
14645 
14646 /*
14647  * Return a reference to the directory (parent) vnode for a given vnode,
14648  * using the saved pathname information and the directory file handle.  The
14649  * caller is responsible for disposing of the reference.
14650  * Returns zero or an errno value.
14651  *
14652  * Caller should set need_start_op to FALSE if it is the recovery
14653  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14654  */
14655 int
14656 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14657 {
14658 	svnode_t *svnp;
14659 	vnode_t *dvp = NULL;
14660 	servinfo4_t *svp;
14661 	nfs4_fname_t *mfname;
14662 	int error;
14663 
14664 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14665 
14666 	if (vp->v_flag & VROOT) {
14667 		nfs4_sharedfh_t *sfh;
14668 		nfs_fh4 fh;
14669 		mntinfo4_t *mi;
14670 
14671 		ASSERT(vp->v_type == VREG);
14672 
14673 		mi = VTOMI4(vp);
14674 		svp = mi->mi_curr_serv;
14675 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14676 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14677 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14678 		sfh = sfh4_get(&fh, VTOMI4(vp));
14679 		nfs_rw_exit(&svp->sv_lock);
14680 		mfname = mi->mi_fname;
14681 		fn_hold(mfname);
14682 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14683 		sfh4_rele(&sfh);
14684 
14685 		if (dvp->v_type == VNON)
14686 			dvp->v_type = VDIR;
14687 		*dvpp = dvp;
14688 		return (0);
14689 	}
14690 
14691 	svnp = VTOSV(vp);
14692 
14693 	if (svnp == NULL) {
14694 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14695 			"shadow node is NULL"));
14696 		return (EINVAL);
14697 	}
14698 
14699 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14700 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14701 			"shadow node name or dfh val == NULL"));
14702 		return (EINVAL);
14703 	}
14704 
14705 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14706 							(int)need_start_op);
14707 	if (error != 0) {
14708 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14709 			"nfs4_make_dotdot returned %d", error));
14710 		return (error);
14711 	}
14712 	if (!dvp) {
14713 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14714 			"nfs4_make_dotdot returned a NULL dvp"));
14715 		return (EIO);
14716 	}
14717 	if (dvp->v_type == VNON)
14718 		dvp->v_type = VDIR;
14719 	ASSERT(dvp->v_type == VDIR);
14720 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14721 		mutex_enter(&dvp->v_lock);
14722 		dvp->v_flag |= V_XATTRDIR;
14723 		mutex_exit(&dvp->v_lock);
14724 	}
14725 	*dvpp = dvp;
14726 	return (0);
14727 }
14728 
14729 /*
14730  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14731  * length that fnamep can accept, including the trailing null.
14732  * Returns 0 if okay, returns an errno value if there was a problem.
14733  */
14734 
14735 int
14736 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14737 {
14738 	char *fn;
14739 	int err = 0;
14740 	servinfo4_t *svp;
14741 	svnode_t *shvp;
14742 
14743 	/*
14744 	 * If the file being opened has VROOT set, then this is
14745 	 * a "file" mount.  sv_name will not be interesting, so
14746 	 * go back to the servinfo4 to get the original mount
14747 	 * path and strip off all but the final edge.  Otherwise
14748 	 * just return the name from the shadow vnode.
14749 	 */
14750 
14751 	if (vp->v_flag & VROOT) {
14752 
14753 		svp = VTOMI4(vp)->mi_curr_serv;
14754 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14755 
14756 		fn = strrchr(svp->sv_path, '/');
14757 		if (fn == NULL)
14758 			err = EINVAL;
14759 		else
14760 			fn++;
14761 	} else {
14762 		shvp = VTOSV(vp);
14763 		fn = fn_name(shvp->sv_name);
14764 	}
14765 
14766 	if (err == 0)
14767 		if (strlen(fn) < maxlen)
14768 			(void) strcpy(fnamep, fn);
14769 		else
14770 			err = ENAMETOOLONG;
14771 
14772 	if (vp->v_flag & VROOT)
14773 		nfs_rw_exit(&svp->sv_lock);
14774 	else
14775 		kmem_free(fn, MAXNAMELEN);
14776 
14777 	return (err);
14778 }
14779 
14780 /*
14781  * Bookkeeping for a close that doesn't need to go over the wire.
14782  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14783  * it is left at 1.
14784  */
14785 void
14786 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14787 {
14788 	rnode4_t		*rp;
14789 	mntinfo4_t		*mi;
14790 
14791 	mi = VTOMI4(vp);
14792 	rp = VTOR4(vp);
14793 
14794 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14795 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14796 	ASSERT(nfs_zone() == mi->mi_zone);
14797 	ASSERT(mutex_owned(&osp->os_sync_lock));
14798 	ASSERT(*have_lockp);
14799 
14800 	if (!osp->os_valid ||
14801 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14802 		return;
14803 	}
14804 
14805 	/*
14806 	 * This removes the reference obtained at OPEN; ie,
14807 	 * when the open stream structure was created.
14808 	 *
14809 	 * We don't have to worry about calling 'open_stream_rele'
14810 	 * since we our currently holding a reference to this
14811 	 * open stream which means the count can not go to 0 with
14812 	 * this decrement.
14813 	 */
14814 	ASSERT(osp->os_ref_count >= 2);
14815 	osp->os_ref_count--;
14816 	osp->os_valid = 0;
14817 	mutex_exit(&osp->os_sync_lock);
14818 	*have_lockp = 0;
14819 
14820 	nfs4_dec_state_ref_count(mi);
14821 }
14822 
14823 /*
14824  * Close all remaining open streams on the rnode.  These open streams
14825  * could be here because:
14826  * - The close attempted at either close or delmap failed
14827  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
14828  * - Someone did mknod on a regular file but never opened it
14829  */
14830 int
14831 nfs4close_all(vnode_t *vp, cred_t *cr)
14832 {
14833 	nfs4_open_stream_t *osp;
14834 	int error;
14835 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
14836 	rnode4_t *rp;
14837 
14838 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14839 
14840 	error = 0;
14841 	rp = VTOR4(vp);
14842 
14843 	/*
14844 	 * At this point, all we know is that the last time
14845 	 * someone called vn_rele, the count was 1.  Since then,
14846 	 * the vnode could have been re-activated.  We want to
14847 	 * loop through the open streams and close each one, but
14848 	 * we have to be careful since once we release the rnode
14849 	 * hash bucket lock, someone else is free to come in and
14850 	 * re-activate the rnode and add new open streams.  The
14851 	 * strategy is take the rnode hash bucket lock, verify that
14852 	 * the count is still 1, grab the open stream off the
14853 	 * head of the list and mark it invalid, then release the
14854 	 * rnode hash bucket lock and proceed with that open stream.
14855 	 * This is ok because nfs4close_one() will acquire the proper
14856 	 * open/create to close/destroy synchronization for open
14857 	 * streams, and will ensure that if someone has reopened
14858 	 * the open stream after we've dropped the hash bucket lock
14859 	 * then we'll just simply return without destroying the
14860 	 * open stream.
14861 	 * Repeat until the list is empty.
14862 	 */
14863 
14864 	for (;;) {
14865 
14866 		/* make sure vnode hasn't been reactivated */
14867 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
14868 		mutex_enter(&vp->v_lock);
14869 		if (vp->v_count > 1) {
14870 			mutex_exit(&vp->v_lock);
14871 			rw_exit(&rp->r_hashq->r_lock);
14872 			break;
14873 		}
14874 		/*
14875 		 * Grabbing r_os_lock before releasing v_lock prevents
14876 		 * a window where the rnode/open stream could get
14877 		 * reactivated (and os_force_close set to 0) before we
14878 		 * had a chance to set os_force_close to 1.
14879 		 */
14880 		mutex_enter(&rp->r_os_lock);
14881 		mutex_exit(&vp->v_lock);
14882 
14883 		osp = list_head(&rp->r_open_streams);
14884 		if (!osp) {
14885 			/* nothing left to CLOSE OTW, so return */
14886 			mutex_exit(&rp->r_os_lock);
14887 			rw_exit(&rp->r_hashq->r_lock);
14888 			break;
14889 		}
14890 
14891 		mutex_enter(&rp->r_statev4_lock);
14892 		/* the file can't still be mem mapped */
14893 		ASSERT(rp->r_mapcnt == 0);
14894 		if (rp->created_v4)
14895 			rp->created_v4 = 0;
14896 		mutex_exit(&rp->r_statev4_lock);
14897 
14898 		/*
14899 		 * Grab a ref on this open stream; nfs4close_one
14900 		 * will mark it as invalid
14901 		 */
14902 		mutex_enter(&osp->os_sync_lock);
14903 		osp->os_ref_count++;
14904 		osp->os_force_close = 1;
14905 		mutex_exit(&osp->os_sync_lock);
14906 		mutex_exit(&rp->r_os_lock);
14907 		rw_exit(&rp->r_hashq->r_lock);
14908 
14909 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
14910 
14911 		/* Update error if it isn't already non-zero */
14912 		if (error == 0) {
14913 			if (e.error)
14914 				error = e.error;
14915 			else if (e.stat)
14916 				error = geterrno4(e.stat);
14917 		}
14918 
14919 #ifdef	DEBUG
14920 		nfs4close_all_cnt++;
14921 #endif
14922 		/* Release the ref on osp acquired above. */
14923 		open_stream_rele(osp, rp);
14924 
14925 		/* Proceed to the next open stream, if any */
14926 	}
14927 	return (error);
14928 }
14929 
14930 /*
14931  * nfs4close_one - close one open stream for a file if needed.
14932  *
14933  * "close_type" indicates which close path this is:
14934  * CLOSE_NORM: close initiated via VOP_CLOSE.
14935  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
14936  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
14937  *	the close and release of client state for this open stream
14938  *	(unless someone else has the open stream open).
14939  * CLOSE_RESEND: indicates the request is a replay of an earlier request
14940  *	(e.g., due to abort because of a signal).
14941  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
14942  *
14943  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
14944  * recovery.  Instead, the caller is expected to deal with retries.
14945  *
14946  * The caller can either pass in the osp ('provided_osp') or not.
14947  *
14948  * 'access_bits' represents the access we are closing/downgrading.
14949  *
14950  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
14951  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
14952  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
14953  *
14954  * Errors are returned via the nfs4_error_t.
14955  */
14956 void
14957 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
14958 	int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
14959 	nfs4_close_type_t close_type, size_t len, uint_t maxprot,
14960 	uint_t mmap_flags)
14961 {
14962 	nfs4_open_owner_t *oop;
14963 	nfs4_open_stream_t *osp = NULL;
14964 	int retry = 0;
14965 	int num_retries = NFS4_NUM_RECOV_RETRIES;
14966 	rnode4_t *rp;
14967 	mntinfo4_t *mi;
14968 	nfs4_recov_state_t recov_state;
14969 	cred_t *cred_otw = NULL;
14970 	bool_t recovonly = FALSE;
14971 	int isrecov;
14972 	int force_close;
14973 	int close_failed = 0;
14974 	int did_dec_count = 0;
14975 	int did_start_op = 0;
14976 	int did_force_recovlock = 0;
14977 	int did_start_seqid_sync = 0;
14978 	int have_sync_lock = 0;
14979 
14980 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14981 
14982 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
14983 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
14984 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
14985 	    len, maxprot, mmap_flags, access_bits));
14986 
14987 	nfs4_error_zinit(ep);
14988 	rp = VTOR4(vp);
14989 	mi = VTOMI4(vp);
14990 	isrecov = (close_type == CLOSE_RESEND ||
14991 			close_type == CLOSE_AFTER_RESEND);
14992 
14993 	/*
14994 	 * First get the open owner.
14995 	 */
14996 	if (!provided_osp) {
14997 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
14998 	} else {
14999 		oop = provided_osp->os_open_owner;
15000 		ASSERT(oop != NULL);
15001 		open_owner_hold(oop);
15002 	}
15003 
15004 	if (!oop) {
15005 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15006 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15007 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15008 		    (void *)provided_osp, close_type));
15009 		ep->error = EIO;
15010 		goto out;
15011 	}
15012 
15013 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15014 recov_retry:
15015 	osp = NULL;
15016 	close_failed = 0;
15017 	force_close = (close_type == CLOSE_FORCE);
15018 	retry = 0;
15019 	did_start_op = 0;
15020 	did_force_recovlock = 0;
15021 	did_start_seqid_sync = 0;
15022 	have_sync_lock = 0;
15023 	recovonly = FALSE;
15024 	recov_state.rs_flags = 0;
15025 	recov_state.rs_num_retry_despite_err = 0;
15026 
15027 	/*
15028 	 * Second synchronize with recovery.
15029 	 */
15030 	if (!isrecov) {
15031 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15032 				&recov_state, &recovonly);
15033 		if (!ep->error) {
15034 			did_start_op = 1;
15035 		} else {
15036 			close_failed = 1;
15037 			/*
15038 			 * If we couldn't get start_fop, but have to
15039 			 * cleanup state, then at least acquire the
15040 			 * mi_recovlock so we can synchronize with
15041 			 * recovery.
15042 			 */
15043 			if (close_type == CLOSE_FORCE) {
15044 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15045 					RW_READER, FALSE);
15046 				did_force_recovlock = 1;
15047 			} else
15048 				goto out;
15049 		}
15050 	}
15051 
15052 	/*
15053 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15054 	 * set 'recovonly' to TRUE since most likely this is due to
15055 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15056 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15057 	 * to retry, causing us to loop until recovery finishes.  Plus we
15058 	 * don't need protection over the open seqid since we're not going
15059 	 * OTW, hence don't need to use the seqid.
15060 	 */
15061 	if (recovonly == FALSE) {
15062 		/* need to grab the open owner sync before 'os_sync_lock' */
15063 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15064 		if (ep->error == EAGAIN) {
15065 			ASSERT(!isrecov);
15066 			if (did_start_op)
15067 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15068 					&recov_state, TRUE);
15069 			if (did_force_recovlock)
15070 				nfs_rw_exit(&mi->mi_recovlock);
15071 			goto recov_retry;
15072 		}
15073 		did_start_seqid_sync = 1;
15074 	}
15075 
15076 	/*
15077 	 * Third get an open stream and acquire 'os_sync_lock' to
15078 	 * sychronize the opening/creating of an open stream with the
15079 	 * closing/destroying of an open stream.
15080 	 */
15081 	if (!provided_osp) {
15082 		/* returns with 'os_sync_lock' held */
15083 		osp = find_open_stream(oop, rp);
15084 		if (!osp) {
15085 			ep->error = EIO;
15086 			goto out;
15087 		}
15088 	} else {
15089 		osp = provided_osp;
15090 		open_stream_hold(osp);
15091 		mutex_enter(&osp->os_sync_lock);
15092 	}
15093 	have_sync_lock = 1;
15094 
15095 	ASSERT(oop == osp->os_open_owner);
15096 
15097 	/*
15098 	 * Fourth, do any special pre-OTW CLOSE processing
15099 	 * based on the specific close type.
15100 	 */
15101 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15102 	    !did_dec_count) {
15103 		ASSERT(osp->os_open_ref_count > 0);
15104 		osp->os_open_ref_count--;
15105 		did_dec_count = 1;
15106 		if (osp->os_open_ref_count == 0)
15107 			osp->os_final_close = 1;
15108 	}
15109 
15110 	if (close_type == CLOSE_FORCE) {
15111 		/* see if somebody reopened the open stream. */
15112 		if (!osp->os_force_close) {
15113 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15114 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15115 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15116 			ep->error = 0;
15117 			ep->stat = NFS4_OK;
15118 			goto out;
15119 		}
15120 
15121 		if (!osp->os_final_close && !did_dec_count) {
15122 			osp->os_open_ref_count--;
15123 			did_dec_count = 1;
15124 		}
15125 
15126 		/*
15127 		 * We can't depend on os_open_ref_count being 0 due to the
15128 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15129 		 */
15130 #ifdef	NOTYET
15131 		ASSERT(osp->os_open_ref_count == 0);
15132 #endif
15133 		if (osp->os_open_ref_count != 0) {
15134 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15135 			    "nfs4close_one: should panic here on an "
15136 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15137 			    "since this is probably the exec problem."));
15138 
15139 			osp->os_open_ref_count = 0;
15140 		}
15141 
15142 		/*
15143 		 * There is the possibility that nfs4close_one()
15144 		 * for close_type == CLOSE_DELMAP couldn't find the
15145 		 * open stream, thus couldn't decrement its os_mapcnt;
15146 		 * therefore we can't use this ASSERT yet.
15147 		 */
15148 #ifdef	NOTYET
15149 		ASSERT(osp->os_mapcnt == 0);
15150 #endif
15151 		osp->os_mapcnt = 0;
15152 	}
15153 
15154 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15155 		ASSERT(osp->os_mapcnt >= btopr(len));
15156 
15157 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15158 			osp->os_mmap_write -= btopr(len);
15159 		if (maxprot & PROT_READ)
15160 			osp->os_mmap_read -= btopr(len);
15161 		if (maxprot & PROT_EXEC)
15162 			osp->os_mmap_read -= btopr(len);
15163 		/* mirror the PROT_NONE check in nfs4_addmap() */
15164 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15165 		    !(maxprot & PROT_EXEC))
15166 			osp->os_mmap_read -= btopr(len);
15167 		osp->os_mapcnt -= btopr(len);
15168 		did_dec_count = 1;
15169 	}
15170 
15171 	if (recovonly) {
15172 		nfs4_lost_rqst_t lost_rqst;
15173 
15174 		/* request should not already be in recovery queue */
15175 		ASSERT(lrp == NULL);
15176 		nfs4_error_init(ep, EINTR);
15177 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15178 			osp, cred_otw, vp);
15179 		mutex_exit(&osp->os_sync_lock);
15180 		have_sync_lock = 0;
15181 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15182 				lost_rqst.lr_op == OP_CLOSE ?
15183 				&lost_rqst : NULL, OP_CLOSE, NULL);
15184 		close_failed = 1;
15185 		force_close = 0;
15186 		goto close_cleanup;
15187 	}
15188 
15189 	/*
15190 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15191 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15192 	 * space, which means we stopped operating on the open stream
15193 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15194 	 * stateid could be stale, potentially triggering a false
15195 	 * setclientid), and just clean up the client's internal state.
15196 	 */
15197 	if (osp->os_orig_oo_name != oop->oo_name) {
15198 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15199 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15200 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15201 		    "oo_name %" PRIx64")",
15202 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15203 		    oop->oo_name));
15204 		close_failed = 1;
15205 	}
15206 
15207 	/* If the file failed recovery, just quit. */
15208 	mutex_enter(&rp->r_statelock);
15209 	if (rp->r_flags & R4RECOVERR) {
15210 		close_failed = 1;
15211 	}
15212 	mutex_exit(&rp->r_statelock);
15213 
15214 	/*
15215 	 * If the force close path failed to obtain start_fop
15216 	 * then skip the OTW close and just remove the state.
15217 	 */
15218 	if (close_failed)
15219 		goto close_cleanup;
15220 
15221 	/*
15222 	 * Fifth, check to see if there are still mapped pages or other
15223 	 * opens using this open stream.  If there are then we can't
15224 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15225 	 */
15226 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15227 		nfs4_lost_rqst_t	new_lost_rqst;
15228 		bool_t			needrecov = FALSE;
15229 		cred_t			*odg_cred_otw = NULL;
15230 		seqid4			open_dg_seqid = 0;
15231 
15232 		if (osp->os_delegation) {
15233 			/*
15234 			 * If this open stream was never OPENed OTW then we
15235 			 * surely can't DOWNGRADE it (especially since the
15236 			 * osp->open_stateid is really a delegation stateid
15237 			 * when os_delegation is 1).
15238 			 */
15239 			if (access_bits & FREAD)
15240 				osp->os_share_acc_read--;
15241 			if (access_bits & FWRITE)
15242 				osp->os_share_acc_write--;
15243 			osp->os_share_deny_none--;
15244 			nfs4_error_zinit(ep);
15245 			goto out;
15246 		}
15247 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15248 				lrp, ep, &odg_cred_otw, &open_dg_seqid);
15249 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15250 		if (needrecov && !isrecov) {
15251 			bool_t abort;
15252 			nfs4_bseqid_entry_t *bsep = NULL;
15253 
15254 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15255 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15256 					vp, 0,
15257 					lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15258 					open_dg_seqid);
15259 
15260 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15261 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15262 			mutex_exit(&osp->os_sync_lock);
15263 			have_sync_lock = 0;
15264 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15265 				    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15266 				    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15267 				    bsep);
15268 			if (odg_cred_otw)
15269 				crfree(odg_cred_otw);
15270 			if (bsep)
15271 				kmem_free(bsep, sizeof (*bsep));
15272 
15273 			if (abort == TRUE)
15274 				goto out;
15275 
15276 			if (did_start_seqid_sync) {
15277 				nfs4_end_open_seqid_sync(oop);
15278 				did_start_seqid_sync = 0;
15279 			}
15280 			open_stream_rele(osp, rp);
15281 
15282 			if (did_start_op)
15283 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15284 					&recov_state, FALSE);
15285 			if (did_force_recovlock)
15286 				nfs_rw_exit(&mi->mi_recovlock);
15287 
15288 			goto recov_retry;
15289 		} else {
15290 			if (odg_cred_otw)
15291 				crfree(odg_cred_otw);
15292 		}
15293 		goto out;
15294 	}
15295 
15296 	/*
15297 	 * If this open stream was created as the results of an open
15298 	 * while holding a delegation, then just release it; no need
15299 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15300 	 */
15301 	if (osp->os_delegation) {
15302 		nfs4close_notw(vp, osp, &have_sync_lock);
15303 		nfs4_error_zinit(ep);
15304 		goto out;
15305 	}
15306 
15307 	/*
15308 	 * If this stream is not valid, we're done.
15309 	 */
15310 	if (!osp->os_valid) {
15311 		nfs4_error_zinit(ep);
15312 		goto out;
15313 	}
15314 
15315 	/*
15316 	 * Last open or mmap ref has vanished, need to do an OTW close.
15317 	 * First check to see if a close is still necessary.
15318 	 */
15319 	if (osp->os_failed_reopen) {
15320 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15321 		    "don't close OTW osp %p since reopen failed.",
15322 		    (void *)osp));
15323 		/*
15324 		 * Reopen of the open stream failed, hence the
15325 		 * stateid of the open stream is invalid/stale, and
15326 		 * sending this OTW would incorrectly cause another
15327 		 * round of recovery.  In this case, we need to set
15328 		 * the 'os_valid' bit to 0 so another thread doesn't
15329 		 * come in and re-open this open stream before
15330 		 * this "closing" thread cleans up state (decrementing
15331 		 * the nfs4_server_t's state_ref_count and decrementing
15332 		 * the os_ref_count).
15333 		 */
15334 		osp->os_valid = 0;
15335 		/*
15336 		 * This removes the reference obtained at OPEN; ie,
15337 		 * when the open stream structure was created.
15338 		 *
15339 		 * We don't have to worry about calling 'open_stream_rele'
15340 		 * since we our currently holding a reference to this
15341 		 * open stream which means the count can not go to 0 with
15342 		 * this decrement.
15343 		 */
15344 		ASSERT(osp->os_ref_count >= 2);
15345 		osp->os_ref_count--;
15346 		nfs4_error_zinit(ep);
15347 		close_failed = 0;
15348 		goto close_cleanup;
15349 	}
15350 
15351 	ASSERT(osp->os_ref_count > 1);
15352 
15353 	/*
15354 	 * Sixth, try the CLOSE OTW.
15355 	 */
15356 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15357 	    close_type, ep, &have_sync_lock);
15358 
15359 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15360 		/*
15361 		 * Let the recovery thread be responsible for
15362 		 * removing the state for CLOSE.
15363 		 */
15364 		close_failed = 1;
15365 		force_close = 0;
15366 		retry = 0;
15367 	}
15368 
15369 	/* See if we need to retry with a different cred */
15370 	if ((ep->error == EACCES ||
15371 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15372 	    cred_otw != cr) {
15373 		crfree(cred_otw);
15374 		cred_otw = cr;
15375 		crhold(cred_otw);
15376 		retry = 1;
15377 	}
15378 
15379 	if (ep->error || ep->stat)
15380 		close_failed = 1;
15381 
15382 	if (retry && !isrecov && num_retries-- > 0) {
15383 		if (have_sync_lock) {
15384 			mutex_exit(&osp->os_sync_lock);
15385 			have_sync_lock = 0;
15386 		}
15387 		if (did_start_seqid_sync) {
15388 			nfs4_end_open_seqid_sync(oop);
15389 			did_start_seqid_sync = 0;
15390 		}
15391 		open_stream_rele(osp, rp);
15392 
15393 		if (did_start_op)
15394 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15395 				&recov_state, FALSE);
15396 		if (did_force_recovlock)
15397 			nfs_rw_exit(&mi->mi_recovlock);
15398 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15399 			"nfs4close_one: need to retry the close "
15400 			"operation"));
15401 		goto recov_retry;
15402 	}
15403 close_cleanup:
15404 	/*
15405 	 * Seventh and lastly, process our results.
15406 	 */
15407 	if (close_failed && force_close) {
15408 		/*
15409 		 * It's ok to drop and regrab the 'os_sync_lock' since
15410 		 * nfs4close_notw() will recheck to make sure the
15411 		 * "close"/removal of state should happen.
15412 		 */
15413 		if (!have_sync_lock) {
15414 			mutex_enter(&osp->os_sync_lock);
15415 			have_sync_lock = 1;
15416 		}
15417 		/*
15418 		 * This is last call, remove the ref on the open
15419 		 * stream created by open and clean everything up.
15420 		 */
15421 		osp->os_pending_close = 0;
15422 		nfs4close_notw(vp, osp, &have_sync_lock);
15423 		nfs4_error_zinit(ep);
15424 	}
15425 
15426 	if (!close_failed) {
15427 		if (have_sync_lock) {
15428 			osp->os_pending_close = 0;
15429 			mutex_exit(&osp->os_sync_lock);
15430 			have_sync_lock = 0;
15431 		} else {
15432 			mutex_enter(&osp->os_sync_lock);
15433 			osp->os_pending_close = 0;
15434 			mutex_exit(&osp->os_sync_lock);
15435 		}
15436 		if (did_start_op && recov_state.rs_sp != NULL) {
15437 			mutex_enter(&recov_state.rs_sp->s_lock);
15438 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15439 			mutex_exit(&recov_state.rs_sp->s_lock);
15440 		} else {
15441 			nfs4_dec_state_ref_count(mi);
15442 		}
15443 		nfs4_error_zinit(ep);
15444 	}
15445 
15446 out:
15447 	if (have_sync_lock)
15448 		mutex_exit(&osp->os_sync_lock);
15449 	if (did_start_op)
15450 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15451 		    recovonly ? TRUE : FALSE);
15452 	if (did_force_recovlock)
15453 		nfs_rw_exit(&mi->mi_recovlock);
15454 	if (cred_otw)
15455 		crfree(cred_otw);
15456 	if (osp)
15457 		open_stream_rele(osp, rp);
15458 	if (oop) {
15459 		if (did_start_seqid_sync)
15460 			nfs4_end_open_seqid_sync(oop);
15461 		open_owner_rele(oop);
15462 	}
15463 }
15464 
15465 /*
15466  * Convert information returned by the server in the LOCK4denied
15467  * structure to the form required by fcntl.
15468  */
15469 static void
15470 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15471 {
15472 	nfs4_lo_name_t *lo;
15473 
15474 #ifdef	DEBUG
15475 	if (denied_to_flk_debug) {
15476 		lockt_denied_debug = lockt_denied;
15477 		debug_enter("lockt_denied");
15478 	}
15479 #endif
15480 
15481 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15482 	flk->l_whence = 0;	/* aka SEEK_SET */
15483 	flk->l_start = lockt_denied->offset;
15484 	flk->l_len = lockt_denied->length;
15485 
15486 	/*
15487 	 * If the blocking clientid matches our client id, then we can
15488 	 * interpret the lockowner (since we built it).  If not, then
15489 	 * fabricate a sysid and pid.  Note that the l_sysid field
15490 	 * in *flk already has the local sysid.
15491 	 */
15492 
15493 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15494 
15495 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15496 			lo = (nfs4_lo_name_t *)
15497 				lockt_denied->owner.owner_val;
15498 
15499 			flk->l_pid = lo->ln_pid;
15500 		} else {
15501 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15502 			"denied_to_flk: bad lock owner length\n"));
15503 
15504 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15505 		}
15506 	} else {
15507 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15508 		"denied_to_flk: foreign clientid\n"));
15509 
15510 		/*
15511 		 * Construct a new sysid which should be different from
15512 		 * sysids of other systems.
15513 		 */
15514 
15515 		flk->l_sysid++;
15516 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15517 	}
15518 }
15519 
15520 static pid_t
15521 lo_to_pid(lock_owner4 *lop)
15522 {
15523 	pid_t pid = 0;
15524 	uchar_t *cp;
15525 	int i;
15526 
15527 	cp = (uchar_t *)&lop->clientid;
15528 
15529 	for (i = 0; i < sizeof (lop->clientid); i++)
15530 		pid += (pid_t)*cp++;
15531 
15532 	cp = (uchar_t *)lop->owner_val;
15533 
15534 	for (i = 0; i < lop->owner_len; i++)
15535 		pid += (pid_t)*cp++;
15536 
15537 	return (pid);
15538 }
15539 
15540 /*
15541  * Given a lock pointer, returns the length of that lock.
15542  * "end" is the last locked offset the "l_len" covers from
15543  * the start of the lock.
15544  */
15545 static off64_t
15546 lock_to_end(flock64_t *lock)
15547 {
15548 	off64_t lock_end;
15549 
15550 	if (lock->l_len == 0)
15551 		lock_end = (off64_t)MAXEND;
15552 	else
15553 		lock_end = lock->l_start + lock->l_len - 1;
15554 
15555 	return (lock_end);
15556 }
15557 
15558 /*
15559  * Given the end of a lock, it will return you the length "l_len" for that lock.
15560  */
15561 static off64_t
15562 end_to_len(off64_t start, off64_t end)
15563 {
15564 	off64_t lock_len;
15565 
15566 	ASSERT(end >= start);
15567 	if (end == MAXEND)
15568 		lock_len = 0;
15569 	else
15570 		lock_len = end - start + 1;
15571 
15572 	return (lock_len);
15573 }
15574 
15575 /*
15576  * On given end for a lock it determines if it is the last locked offset
15577  * or not, if so keeps it as is, else adds one to return the length for
15578  * valid start.
15579  */
15580 static off64_t
15581 start_check(off64_t x)
15582 {
15583 	if (x == MAXEND)
15584 		return (x);
15585 	else
15586 		return (x + 1);
15587 }
15588 
15589 /*
15590  * See if these two locks overlap, and if so return 1;
15591  * otherwise, return 0.
15592  */
15593 static int
15594 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15595 {
15596 	off64_t llfp_end, curfp_end;
15597 
15598 	llfp_end = lock_to_end(llfp);
15599 	curfp_end = lock_to_end(curfp);
15600 
15601 	if (((llfp_end >= curfp->l_start) &&
15602 		(llfp->l_start <= curfp->l_start)) ||
15603 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15604 		return (1);
15605 	return (0);
15606 }
15607 
15608 /*
15609  * Determine what the interseting lock region is, and add that to the
15610  * 'nl_llpp' locklist in increasing order (by l_start).
15611  */
15612 static void
15613 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15614 	locklist_t **nl_llpp, vnode_t *vp)
15615 {
15616 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15617 	off64_t lost_flp_end, local_flp_end, len, start;
15618 
15619 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15620 
15621 	if (!locks_intersect(lost_flp, local_flp))
15622 		return;
15623 
15624 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15625 	    "locks intersect"));
15626 
15627 	lost_flp_end = lock_to_end(lost_flp);
15628 	local_flp_end = lock_to_end(local_flp);
15629 
15630 	/* Find the starting point of the intersecting region */
15631 	if (local_flp->l_start > lost_flp->l_start)
15632 		start = local_flp->l_start;
15633 	else
15634 		start = lost_flp->l_start;
15635 
15636 	/* Find the lenght of the intersecting region */
15637 	if (lost_flp_end < local_flp_end)
15638 		len = end_to_len(start, lost_flp_end);
15639 	else
15640 		len = end_to_len(start, local_flp_end);
15641 
15642 	/*
15643 	 * Prepare the flock structure for the intersection found and insert
15644 	 * it into the new list in increasing l_start order. This list contains
15645 	 * intersections of locks registered by the client with the local host
15646 	 * and the lost lock.
15647 	 * The lock type of this lock is the same as that of the local_flp.
15648 	 */
15649 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15650 	intersect_llp->ll_flock.l_start = start;
15651 	intersect_llp->ll_flock.l_len = len;
15652 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15653 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15654 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15655 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15656 	intersect_llp->ll_vp = vp;
15657 
15658 	tmp_fllp = *nl_llpp;
15659 	cur_fllp = NULL;
15660 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15661 		intersect_llp->ll_flock.l_start) {
15662 			cur_fllp = tmp_fllp;
15663 			tmp_fllp = tmp_fllp->ll_next;
15664 	}
15665 	if (cur_fllp == NULL) {
15666 		/* first on the list */
15667 		intersect_llp->ll_next = *nl_llpp;
15668 		*nl_llpp = intersect_llp;
15669 	} else {
15670 		intersect_llp->ll_next = cur_fllp->ll_next;
15671 		cur_fllp->ll_next = intersect_llp;
15672 	}
15673 
15674 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15675 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15676 	    intersect_llp->ll_flock.l_start,
15677 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15678 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15679 }
15680 
15681 /*
15682  * Our local locking current state is potentially different than
15683  * what the NFSv4 server thinks we have due to a lost lock that was
15684  * resent and then received.  We need to reset our "NFSv4" locking
15685  * state to match the current local locking state for this pid since
15686  * that is what the user/application sees as what the world is.
15687  *
15688  * We cannot afford to drop the open/lock seqid sync since then we can
15689  * get confused about what the current local locking state "is" versus
15690  * "was".
15691  *
15692  * If we are unable to fix up the locks, we send SIGLOST to the affected
15693  * process.  This is not done if the filesystem has been forcibly
15694  * unmounted, in case the process has already exited and a new process
15695  * exists with the same pid.
15696  */
15697 static void
15698 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15699 		nfs4_lock_owner_t *lop)
15700 {
15701 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15702 	mntinfo4_t *mi = VTOMI4(vp);
15703 	const int cmd = F_SETLK;
15704 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15705 	flock64_t ul_fl;
15706 
15707 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15708 		"nfs4_reinstitute_local_lock_state"));
15709 
15710 	/*
15711 	 * Find active locks for this vp from the local locking code.
15712 	 * Scan through this list and find out the locks that intersect with
15713 	 * the lost lock. Once we find the lock that intersects, add the
15714 	 * intersection area as a new lock to a new list "ri_llp". The lock
15715 	 * type of the intersection region lock added to ri_llp is the same
15716 	 * as that found in the active lock list, "list". The intersecting
15717 	 * region locks are added to ri_llp in increasing l_start order.
15718 	 */
15719 	ASSERT(nfs_zone() == mi->mi_zone);
15720 
15721 	locks = flk_active_locks_for_vp(vp);
15722 	ri_llp = NULL;
15723 
15724 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15725 		ASSERT(llp->ll_vp == vp);
15726 		/*
15727 		 * Pick locks that belong to this pid/lockowner
15728 		 */
15729 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15730 			continue;
15731 
15732 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15733 	}
15734 
15735 	/*
15736 	 * Now we have the list of intersections with the lost lock. These are
15737 	 * the locks that were/are active before the server replied to the
15738 	 * last/lost lock. Issue these locks to the server here. Playing these
15739 	 * locks to the server will re-establish aur current local locking state
15740 	 * with the v4 server.
15741 	 * If we get an error, send SIGLOST to the application for that lock.
15742 	 */
15743 
15744 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15745 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15746 		    "nfs4_reinstitute_local_lock_state: need to issue "
15747 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15748 		    llp->ll_flock.l_start,
15749 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15750 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15751 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15752 		/*
15753 		 * No need to relock what we already have
15754 		 */
15755 		if (llp->ll_flock.l_type == lost_flp->l_type)
15756 			continue;
15757 
15758 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15759 	}
15760 
15761 	/*
15762 	 * Now keeping the start of the lost lock as our reference parse the
15763 	 * newly created ri_llp locklist to find the ranges that we have locked
15764 	 * with the v4 server but not in the current local locking. We need
15765 	 * to unlock these ranges.
15766 	 * These ranges can also be reffered to as those ranges, where the lost
15767 	 * lock does not overlap with the locks in the ri_llp but are locked
15768 	 * since the server replied to the lost lock.
15769 	 */
15770 	cur_start = lost_flp->l_start;
15771 	lost_flp_end = lock_to_end(lost_flp);
15772 
15773 	ul_fl.l_type = F_UNLCK;
15774 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15775 	ul_fl.l_sysid = lost_flp->l_sysid;
15776 	ul_fl.l_pid = lost_flp->l_pid;
15777 
15778 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15779 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15780 
15781 		if (llp->ll_flock.l_start <= cur_start) {
15782 			cur_start = start_check(llp_ll_flock_end);
15783 			continue;
15784 		}
15785 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15786 			"nfs4_reinstitute_local_lock_state: "
15787 			"UNLOCK [%"PRIx64" - %"PRIx64"]",
15788 			cur_start, llp->ll_flock.l_start));
15789 
15790 		ul_fl.l_start = cur_start;
15791 		ul_fl.l_len = end_to_len(cur_start,
15792 		    (llp->ll_flock.l_start - 1));
15793 
15794 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15795 		cur_start = start_check(llp_ll_flock_end);
15796 	}
15797 
15798 	/*
15799 	 * In the case where the lost lock ends after all intersecting locks,
15800 	 * unlock the last part of the lost lock range.
15801 	 */
15802 	if (cur_start != start_check(lost_flp_end)) {
15803 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15804 			"nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15805 			"lost lock region [%"PRIx64" - %"PRIx64"]",
15806 			cur_start, lost_flp->l_start + lost_flp->l_len));
15807 
15808 		ul_fl.l_start = cur_start;
15809 		/*
15810 		 * Is it an to-EOF lock? if so unlock till the end
15811 		 */
15812 		if (lost_flp->l_len == 0)
15813 			ul_fl.l_len = 0;
15814 		else
15815 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15816 
15817 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15818 	}
15819 
15820 	if (locks != NULL)
15821 		flk_free_locklist(locks);
15822 
15823 	/* Free up our newly created locklist */
15824 	for (llp = ri_llp; llp != NULL; ) {
15825 		tmp_llp = llp->ll_next;
15826 		kmem_free(llp, sizeof (locklist_t));
15827 		llp = tmp_llp;
15828 	}
15829 
15830 	/*
15831 	 * Now return back to the original calling nfs4frlock()
15832 	 * and let us naturally drop our seqid syncs.
15833 	 */
15834 }
15835 
15836 /*
15837  * Create a lost state record for the given lock reinstantiation request
15838  * and push it onto the lost state queue.
15839  */
15840 static void
15841 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
15842 	nfs4_lock_owner_t *lop)
15843 {
15844 	nfs4_lost_rqst_t req;
15845 	nfs_lock_type4 locktype;
15846 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
15847 
15848 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15849 
15850 	locktype = flk_to_locktype(cmd, flk->l_type);
15851 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
15852 				NULL, NULL, lop, flk, &req, cr, vp);
15853 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
15854 		    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
15855 		    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
15856 		    NULL);
15857 }
15858