xref: /titanic_50/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision 81fd181a33bee65d5be7a49c6093bb13b382b172)
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 2009 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 #include <sys/param.h>
32 #include <sys/types.h>
33 #include <sys/systm.h>
34 #include <sys/cred.h>
35 #include <sys/time.h>
36 #include <sys/vnode.h>
37 #include <sys/vfs.h>
38 #include <sys/vfs_opreg.h>
39 #include <sys/file.h>
40 #include <sys/filio.h>
41 #include <sys/uio.h>
42 #include <sys/buf.h>
43 #include <sys/mman.h>
44 #include <sys/pathname.h>
45 #include <sys/dirent.h>
46 #include <sys/debug.h>
47 #include <sys/vmsystm.h>
48 #include <sys/fcntl.h>
49 #include <sys/flock.h>
50 #include <sys/swap.h>
51 #include <sys/errno.h>
52 #include <sys/strsubr.h>
53 #include <sys/sysmacros.h>
54 #include <sys/kmem.h>
55 #include <sys/cmn_err.h>
56 #include <sys/pathconf.h>
57 #include <sys/utsname.h>
58 #include <sys/dnlc.h>
59 #include <sys/acl.h>
60 #include <sys/systeminfo.h>
61 #include <sys/policy.h>
62 #include <sys/sdt.h>
63 #include <sys/list.h>
64 #include <sys/stat.h>
65 #include <sys/zone.h>
66 
67 #include <rpc/types.h>
68 #include <rpc/auth.h>
69 #include <rpc/clnt.h>
70 
71 #include <nfs/nfs.h>
72 #include <nfs/nfs_clnt.h>
73 #include <nfs/nfs_acl.h>
74 #include <nfs/lm.h>
75 #include <nfs/nfs4.h>
76 #include <nfs/nfs4_kprot.h>
77 #include <nfs/rnode4.h>
78 #include <nfs/nfs4_clnt.h>
79 
80 #include <vm/hat.h>
81 #include <vm/as.h>
82 #include <vm/page.h>
83 #include <vm/pvn.h>
84 #include <vm/seg.h>
85 #include <vm/seg_map.h>
86 #include <vm/seg_kpm.h>
87 #include <vm/seg_vn.h>
88 
89 #include <fs/fs_subr.h>
90 
91 #include <sys/ddi.h>
92 #include <sys/int_fmtio.h>
93 
94 typedef struct {
95 	nfs4_ga_res_t	*di_garp;
96 	cred_t		*di_cred;
97 	hrtime_t	di_time_call;
98 } dirattr_info_t;
99 
100 typedef enum nfs4_acl_op {
101 	NFS4_ACL_GET,
102 	NFS4_ACL_SET
103 } nfs4_acl_op_t;
104 
105 static struct lm_sysid *nfs4_find_sysid(mntinfo4_t *mi);
106 
107 static void	nfs4_update_dircaches(change_info4 *, vnode_t *, vnode_t *,
108 			char *, dirattr_info_t *);
109 
110 static void	nfs4close_otw(rnode4_t *, cred_t *, nfs4_open_owner_t *,
111 		    nfs4_open_stream_t *, int *, int *, nfs4_close_type_t,
112 		    nfs4_error_t *, int *);
113 static int	nfs4_rdwrlbn(vnode_t *, page_t *, u_offset_t, size_t, int,
114 			cred_t *);
115 static int	nfs4write(vnode_t *, caddr_t, u_offset_t, int, cred_t *,
116 			stable_how4 *);
117 static int	nfs4read(vnode_t *, caddr_t, offset_t, int, size_t *,
118 			cred_t *, bool_t, struct uio *);
119 static int	nfs4setattr(vnode_t *, struct vattr *, int, cred_t *,
120 			vsecattr_t *);
121 static int	nfs4openattr(vnode_t *, vnode_t **, int, cred_t *);
122 static int	nfs4lookup(vnode_t *, char *, vnode_t **, cred_t *, int);
123 static int	nfs4lookup_xattr(vnode_t *, char *, vnode_t **, int, cred_t *);
124 static int	nfs4lookupvalidate_otw(vnode_t *, char *, vnode_t **, cred_t *);
125 static int	nfs4lookupnew_otw(vnode_t *, char *, vnode_t **, cred_t *);
126 static int	nfs4mknod(vnode_t *, char *, struct vattr *, enum vcexcl,
127 			int, vnode_t **, cred_t *);
128 static int	nfs4open_otw(vnode_t *, char *, struct vattr *, vnode_t **,
129 			cred_t *, int, int, enum createmode4, int);
130 static int	nfs4rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
131 			caller_context_t *);
132 static int	nfs4rename_persistent_fh(vnode_t *, char *, vnode_t *,
133 			vnode_t *, char *, cred_t *, nfsstat4 *);
134 static int	nfs4rename_volatile_fh(vnode_t *, char *, vnode_t *,
135 			vnode_t *, char *, cred_t *, nfsstat4 *);
136 static int	do_nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
137 static void	nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
138 static int	nfs4_bio(struct buf *, stable_how4 *, cred_t *, bool_t);
139 static int	nfs4_getapage(vnode_t *, u_offset_t, size_t, uint_t *,
140 			page_t *[], size_t, struct seg *, caddr_t,
141 			enum seg_rw, cred_t *);
142 static void	nfs4_readahead(vnode_t *, u_offset_t, caddr_t, struct seg *,
143 			cred_t *);
144 static int	nfs4_sync_putapage(vnode_t *, page_t *, u_offset_t, size_t,
145 			int, cred_t *);
146 static int	nfs4_sync_pageio(vnode_t *, page_t *, u_offset_t, size_t,
147 			int, cred_t *);
148 static int	nfs4_commit(vnode_t *, offset4, count4, cred_t *);
149 static void	nfs4_set_mod(vnode_t *);
150 static void	nfs4_get_commit(vnode_t *);
151 static void	nfs4_get_commit_range(vnode_t *, u_offset_t, size_t);
152 static int	nfs4_putpage_commit(vnode_t *, offset_t, size_t, cred_t *);
153 static int	nfs4_commit_vp(vnode_t *, u_offset_t, size_t, cred_t *, int);
154 static int	nfs4_sync_commit(vnode_t *, page_t *, offset3, count3,
155 			cred_t *);
156 static void	do_nfs4_async_commit(vnode_t *, page_t *, offset3, count3,
157 			cred_t *);
158 static int	nfs4_update_attrcache(nfsstat4, nfs4_ga_res_t *,
159 			hrtime_t, vnode_t *, cred_t *);
160 static int	nfs4_open_non_reg_file(vnode_t **, int, cred_t *);
161 static int	nfs4_safelock(vnode_t *, const struct flock64 *, cred_t *);
162 static void	nfs4_register_lock_locally(vnode_t *, struct flock64 *, int,
163 			u_offset_t);
164 static int 	nfs4_lockrelease(vnode_t *, int, offset_t, cred_t *);
165 static int	nfs4_block_and_wait(clock_t *, rnode4_t *);
166 static cred_t  *state_to_cred(nfs4_open_stream_t *);
167 static int	vtoname(vnode_t *, char *, ssize_t);
168 static void	denied_to_flk(LOCK4denied *, flock64_t *, LOCKT4args *);
169 static pid_t	lo_to_pid(lock_owner4 *);
170 static void	nfs4_reinstitute_local_lock_state(vnode_t *, flock64_t *,
171 			cred_t *, nfs4_lock_owner_t *);
172 static void	push_reinstate(vnode_t *, int, flock64_t *, cred_t *,
173 			nfs4_lock_owner_t *);
174 static int 	open_and_get_osp(vnode_t *, cred_t *, nfs4_open_stream_t **);
175 static void	nfs4_delmap_callback(struct as *, void *, uint_t);
176 static void	nfs4_free_delmapcall(nfs4_delmapcall_t *);
177 static nfs4_delmapcall_t	*nfs4_init_delmapcall();
178 static int	nfs4_find_and_delete_delmapcall(rnode4_t *, int *);
179 static int	nfs4_is_acl_mask_valid(uint_t, nfs4_acl_op_t);
180 static int	nfs4_create_getsecattr_return(vsecattr_t *, vsecattr_t *,
181 			uid_t, gid_t, int);
182 
183 /*
184  * Routines that implement the setting of v4 args for the misc. ops
185  */
186 static void	nfs4args_lock_free(nfs_argop4 *);
187 static void	nfs4args_lockt_free(nfs_argop4 *);
188 static void	nfs4args_setattr(nfs_argop4 *, vattr_t *, vsecattr_t *,
189 			int, rnode4_t *, cred_t *, bitmap4, int *,
190 			nfs4_stateid_types_t *);
191 static void	nfs4args_setattr_free(nfs_argop4 *);
192 static int	nfs4args_verify(nfs_argop4 *, vattr_t *, enum nfs_opnum4,
193 			bitmap4);
194 static void	nfs4args_verify_free(nfs_argop4 *);
195 static void	nfs4args_write(nfs_argop4 *, stable_how4, rnode4_t *, cred_t *,
196 			WRITE4args **, nfs4_stateid_types_t *);
197 
198 /*
199  * These are the vnode ops functions that implement the vnode interface to
200  * the networked file system.  See more comments below at nfs4_vnodeops.
201  */
202 static int	nfs4_open(vnode_t **, int, cred_t *, caller_context_t *);
203 static int	nfs4_close(vnode_t *, int, int, offset_t, cred_t *,
204 			caller_context_t *);
205 static int	nfs4_read(vnode_t *, struct uio *, int, cred_t *,
206 			caller_context_t *);
207 static int	nfs4_write(vnode_t *, struct uio *, int, cred_t *,
208 			caller_context_t *);
209 static int	nfs4_ioctl(vnode_t *, int, intptr_t, int, cred_t *, int *,
210 			caller_context_t *);
211 static int	nfs4_setattr(vnode_t *, struct vattr *, int, cred_t *,
212 			caller_context_t *);
213 static int	nfs4_access(vnode_t *, int, int, cred_t *, caller_context_t *);
214 static int	nfs4_readlink(vnode_t *, struct uio *, cred_t *,
215 			caller_context_t *);
216 static int	nfs4_fsync(vnode_t *, int, cred_t *, caller_context_t *);
217 static int	nfs4_create(vnode_t *, char *, struct vattr *, enum vcexcl,
218 			int, vnode_t **, cred_t *, int, caller_context_t *,
219 			vsecattr_t *);
220 static int	nfs4_remove(vnode_t *, char *, cred_t *, caller_context_t *,
221 			int);
222 static int	nfs4_link(vnode_t *, vnode_t *, char *, cred_t *,
223 			caller_context_t *, int);
224 static int	nfs4_rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
225 			caller_context_t *, int);
226 static int	nfs4_mkdir(vnode_t *, char *, struct vattr *, vnode_t **,
227 			cred_t *, caller_context_t *, int, vsecattr_t *);
228 static int	nfs4_rmdir(vnode_t *, char *, vnode_t *, cred_t *,
229 			caller_context_t *, int);
230 static int	nfs4_symlink(vnode_t *, char *, struct vattr *, char *,
231 			cred_t *, caller_context_t *, int);
232 static int	nfs4_readdir(vnode_t *, struct uio *, cred_t *, int *,
233 			caller_context_t *, int);
234 static int	nfs4_seek(vnode_t *, offset_t, offset_t *, caller_context_t *);
235 static int	nfs4_getpage(vnode_t *, offset_t, size_t, uint_t *,
236 			page_t *[], size_t, struct seg *, caddr_t,
237 			enum seg_rw, cred_t *, caller_context_t *);
238 static int	nfs4_putpage(vnode_t *, offset_t, size_t, int, cred_t *,
239 			caller_context_t *);
240 static int	nfs4_map(vnode_t *, offset_t, struct as *, caddr_t *, size_t,
241 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
242 static int	nfs4_addmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
243 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
244 static int	nfs4_cmp(vnode_t *, vnode_t *, caller_context_t *);
245 static int	nfs4_frlock(vnode_t *, int, struct flock64 *, int, offset_t,
246 			struct flk_callback *, cred_t *, caller_context_t *);
247 static int	nfs4_space(vnode_t *, int, struct flock64 *, int, offset_t,
248 			cred_t *, caller_context_t *);
249 static int	nfs4_delmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
250 			uint_t, uint_t, uint_t, cred_t *, caller_context_t *);
251 static int	nfs4_pageio(vnode_t *, page_t *, u_offset_t, size_t, int,
252 			cred_t *, caller_context_t *);
253 static void	nfs4_dispose(vnode_t *, page_t *, int, int, cred_t *,
254 			caller_context_t *);
255 static int	nfs4_setsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
256 			caller_context_t *);
257 /*
258  * These vnode ops are required to be called from outside this source file,
259  * e.g. by ephemeral mount stub vnode ops, and so may not be declared
260  * as static.
261  */
262 int	nfs4_getattr(vnode_t *, struct vattr *, int, cred_t *,
263 	    caller_context_t *);
264 void	nfs4_inactive(vnode_t *, cred_t *, caller_context_t *);
265 int	nfs4_lookup(vnode_t *, char *, vnode_t **,
266 	    struct pathname *, int, vnode_t *, cred_t *,
267 	    caller_context_t *, int *, pathname_t *);
268 int	nfs4_fid(vnode_t *, fid_t *, caller_context_t *);
269 int	nfs4_rwlock(vnode_t *, int, caller_context_t *);
270 void	nfs4_rwunlock(vnode_t *, int, caller_context_t *);
271 int	nfs4_realvp(vnode_t *, vnode_t **, caller_context_t *);
272 int	nfs4_pathconf(vnode_t *, int, ulong_t *, cred_t *,
273 	    caller_context_t *);
274 int	nfs4_getsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
275 	    caller_context_t *);
276 int	nfs4_shrlock(vnode_t *, int, struct shrlock *, int, cred_t *,
277 	    caller_context_t *);
278 
279 /*
280  * Used for nfs4_commit_vp() to indicate if we should
281  * wait on pending writes.
282  */
283 #define	NFS4_WRITE_NOWAIT	0
284 #define	NFS4_WRITE_WAIT		1
285 
286 #define	NFS4_BASE_WAIT_TIME 1	/* 1 second */
287 
288 /*
289  * Error flags used to pass information about certain special errors
290  * which need to be handled specially.
291  */
292 #define	NFS_EOF			-98
293 #define	NFS_VERF_MISMATCH	-97
294 
295 /*
296  * Flags used to differentiate between which operation drove the
297  * potential CLOSE OTW. (see nfs4_close_otw_if_necessary)
298  */
299 #define	NFS4_CLOSE_OP		0x1
300 #define	NFS4_DELMAP_OP		0x2
301 #define	NFS4_INACTIVE_OP	0x3
302 
303 #define	ISVDEV(t) ((t == VBLK) || (t == VCHR) || (t == VFIFO))
304 
305 /* ALIGN64 aligns the given buffer and adjust buffer size to 64 bit */
306 #define	ALIGN64(x, ptr, sz)						\
307 	x = ((uintptr_t)(ptr)) & (sizeof (uint64_t) - 1);		\
308 	if (x) {							\
309 		x = sizeof (uint64_t) - (x);				\
310 		sz -= (x);						\
311 		ptr += (x);						\
312 	}
313 
314 #ifdef DEBUG
315 int nfs4_client_attr_debug = 0;
316 int nfs4_client_state_debug = 0;
317 int nfs4_client_shadow_debug = 0;
318 int nfs4_client_lock_debug = 0;
319 int nfs4_seqid_sync = 0;
320 int nfs4_client_map_debug = 0;
321 static int nfs4_pageio_debug = 0;
322 int nfs4_client_inactive_debug = 0;
323 int nfs4_client_recov_debug = 0;
324 int nfs4_client_failover_debug = 0;
325 int nfs4_client_call_debug = 0;
326 int nfs4_client_lookup_debug = 0;
327 int nfs4_client_zone_debug = 0;
328 int nfs4_lost_rqst_debug = 0;
329 int nfs4_rdattrerr_debug = 0;
330 int nfs4_open_stream_debug = 0;
331 
332 int nfs4read_error_inject;
333 
334 static int nfs4_create_misses = 0;
335 
336 static int nfs4_readdir_cache_shorts = 0;
337 static int nfs4_readdir_readahead = 0;
338 
339 static int nfs4_bio_do_stop = 0;
340 
341 static int nfs4_lostpage = 0;	/* number of times we lost original page */
342 
343 int nfs4_mmap_debug = 0;
344 
345 static int nfs4_pathconf_cache_hits = 0;
346 static int nfs4_pathconf_cache_misses = 0;
347 
348 int nfs4close_all_cnt;
349 int nfs4close_one_debug = 0;
350 int nfs4close_notw_debug = 0;
351 
352 int denied_to_flk_debug = 0;
353 void *lockt_denied_debug;
354 
355 #endif
356 
357 /*
358  * How long to wait before trying again if OPEN_CONFIRM gets ETIMEDOUT
359  * or NFS4ERR_RESOURCE.
360  */
361 static int confirm_retry_sec = 30;
362 
363 static int nfs4_lookup_neg_cache = 1;
364 
365 /*
366  * number of pages to read ahead
367  * optimized for 100 base-T.
368  */
369 static int nfs4_nra = 4;
370 
371 static int nfs4_do_symlink_cache = 1;
372 
373 static int nfs4_pathconf_disable_cache = 0;
374 
375 /*
376  * These are the vnode ops routines which implement the vnode interface to
377  * the networked file system.  These routines just take their parameters,
378  * make them look networkish by putting the right info into interface structs,
379  * and then calling the appropriate remote routine(s) to do the work.
380  *
381  * Note on directory name lookup cacheing:  If we detect a stale fhandle,
382  * we purge the directory cache relative to that vnode.  This way, the
383  * user won't get burned by the cache repeatedly.  See <nfs/rnode4.h> for
384  * more details on rnode locking.
385  */
386 
387 struct vnodeops *nfs4_vnodeops;
388 
389 const fs_operation_def_t nfs4_vnodeops_template[] = {
390 	VOPNAME_OPEN,		{ .vop_open = nfs4_open },
391 	VOPNAME_CLOSE,		{ .vop_close = nfs4_close },
392 	VOPNAME_READ,		{ .vop_read = nfs4_read },
393 	VOPNAME_WRITE,		{ .vop_write = nfs4_write },
394 	VOPNAME_IOCTL,		{ .vop_ioctl = nfs4_ioctl },
395 	VOPNAME_GETATTR,	{ .vop_getattr = nfs4_getattr },
396 	VOPNAME_SETATTR,	{ .vop_setattr = nfs4_setattr },
397 	VOPNAME_ACCESS,		{ .vop_access = nfs4_access },
398 	VOPNAME_LOOKUP,		{ .vop_lookup = nfs4_lookup },
399 	VOPNAME_CREATE,		{ .vop_create = nfs4_create },
400 	VOPNAME_REMOVE,		{ .vop_remove = nfs4_remove },
401 	VOPNAME_LINK,		{ .vop_link = nfs4_link },
402 	VOPNAME_RENAME,		{ .vop_rename = nfs4_rename },
403 	VOPNAME_MKDIR,		{ .vop_mkdir = nfs4_mkdir },
404 	VOPNAME_RMDIR,		{ .vop_rmdir = nfs4_rmdir },
405 	VOPNAME_READDIR,	{ .vop_readdir = nfs4_readdir },
406 	VOPNAME_SYMLINK,	{ .vop_symlink = nfs4_symlink },
407 	VOPNAME_READLINK,	{ .vop_readlink = nfs4_readlink },
408 	VOPNAME_FSYNC,		{ .vop_fsync = nfs4_fsync },
409 	VOPNAME_INACTIVE,	{ .vop_inactive = nfs4_inactive },
410 	VOPNAME_FID,		{ .vop_fid = nfs4_fid },
411 	VOPNAME_RWLOCK,		{ .vop_rwlock = nfs4_rwlock },
412 	VOPNAME_RWUNLOCK,	{ .vop_rwunlock = nfs4_rwunlock },
413 	VOPNAME_SEEK,		{ .vop_seek = nfs4_seek },
414 	VOPNAME_FRLOCK,		{ .vop_frlock = nfs4_frlock },
415 	VOPNAME_SPACE,		{ .vop_space = nfs4_space },
416 	VOPNAME_REALVP,		{ .vop_realvp = nfs4_realvp },
417 	VOPNAME_GETPAGE,	{ .vop_getpage = nfs4_getpage },
418 	VOPNAME_PUTPAGE,	{ .vop_putpage = nfs4_putpage },
419 	VOPNAME_MAP,		{ .vop_map = nfs4_map },
420 	VOPNAME_ADDMAP,		{ .vop_addmap = nfs4_addmap },
421 	VOPNAME_DELMAP,		{ .vop_delmap = nfs4_delmap },
422 	/* no separate nfs4_dump */
423 	VOPNAME_DUMP,		{ .vop_dump = nfs_dump },
424 	VOPNAME_PATHCONF,	{ .vop_pathconf = nfs4_pathconf },
425 	VOPNAME_PAGEIO,		{ .vop_pageio = nfs4_pageio },
426 	VOPNAME_DISPOSE,	{ .vop_dispose = nfs4_dispose },
427 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = nfs4_setsecattr },
428 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = nfs4_getsecattr },
429 	VOPNAME_SHRLOCK,	{ .vop_shrlock = nfs4_shrlock },
430 	VOPNAME_VNEVENT, 	{ .vop_vnevent = fs_vnevent_support },
431 	NULL,			NULL
432 };
433 
434 /*
435  * The following are subroutines and definitions to set args or get res
436  * for the different nfsv4 ops
437  */
438 
439 void
440 nfs4args_lookup_free(nfs_argop4 *argop, int arglen)
441 {
442 	int		i;
443 
444 	for (i = 0; i < arglen; i++) {
445 		if (argop[i].argop == OP_LOOKUP) {
446 			kmem_free(
447 			    argop[i].nfs_argop4_u.oplookup.
448 			    objname.utf8string_val,
449 			    argop[i].nfs_argop4_u.oplookup.
450 			    objname.utf8string_len);
451 		}
452 	}
453 }
454 
455 static void
456 nfs4args_lock_free(nfs_argop4 *argop)
457 {
458 	locker4 *locker = &argop->nfs_argop4_u.oplock.locker;
459 
460 	if (locker->new_lock_owner == TRUE) {
461 		open_to_lock_owner4 *open_owner;
462 
463 		open_owner = &locker->locker4_u.open_owner;
464 		if (open_owner->lock_owner.owner_val != NULL) {
465 			kmem_free(open_owner->lock_owner.owner_val,
466 			    open_owner->lock_owner.owner_len);
467 		}
468 	}
469 }
470 
471 static void
472 nfs4args_lockt_free(nfs_argop4 *argop)
473 {
474 	lock_owner4 *lowner = &argop->nfs_argop4_u.oplockt.owner;
475 
476 	if (lowner->owner_val != NULL) {
477 		kmem_free(lowner->owner_val, lowner->owner_len);
478 	}
479 }
480 
481 static void
482 nfs4args_setattr(nfs_argop4 *argop, vattr_t *vap, vsecattr_t *vsap, int flags,
483     rnode4_t *rp, cred_t *cr, bitmap4 supp, int *error,
484     nfs4_stateid_types_t *sid_types)
485 {
486 	fattr4		*attr = &argop->nfs_argop4_u.opsetattr.obj_attributes;
487 	mntinfo4_t	*mi;
488 
489 	argop->argop = OP_SETATTR;
490 	/*
491 	 * The stateid is set to 0 if client is not modifying the size
492 	 * and otherwise to whatever nfs4_get_stateid() returns.
493 	 *
494 	 * XXX Note: nfs4_get_stateid() returns 0 if no lockowner and/or no
495 	 * state struct could be found for the process/file pair.  We may
496 	 * want to change this in the future (by OPENing the file).  See
497 	 * bug # 4474852.
498 	 */
499 	if (vap->va_mask & AT_SIZE) {
500 
501 		ASSERT(rp != NULL);
502 		mi = VTOMI4(RTOV4(rp));
503 
504 		argop->nfs_argop4_u.opsetattr.stateid =
505 		    nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
506 		    OP_SETATTR, sid_types, FALSE);
507 	} else {
508 		bzero(&argop->nfs_argop4_u.opsetattr.stateid,
509 		    sizeof (stateid4));
510 	}
511 
512 	*error = vattr_to_fattr4(vap, vsap, attr, flags, OP_SETATTR, supp);
513 	if (*error)
514 		bzero(attr, sizeof (*attr));
515 }
516 
517 static void
518 nfs4args_setattr_free(nfs_argop4 *argop)
519 {
520 	nfs4_fattr4_free(&argop->nfs_argop4_u.opsetattr.obj_attributes);
521 }
522 
523 static int
524 nfs4args_verify(nfs_argop4 *argop, vattr_t *vap, enum nfs_opnum4 op,
525     bitmap4 supp)
526 {
527 	fattr4 *attr;
528 	int error = 0;
529 
530 	argop->argop = op;
531 	switch (op) {
532 	case OP_VERIFY:
533 		attr = &argop->nfs_argop4_u.opverify.obj_attributes;
534 		break;
535 	case OP_NVERIFY:
536 		attr = &argop->nfs_argop4_u.opnverify.obj_attributes;
537 		break;
538 	default:
539 		return (EINVAL);
540 	}
541 	if (!error)
542 		error = vattr_to_fattr4(vap, NULL, attr, 0, op, supp);
543 	if (error)
544 		bzero(attr, sizeof (*attr));
545 	return (error);
546 }
547 
548 static void
549 nfs4args_verify_free(nfs_argop4 *argop)
550 {
551 	switch (argop->argop) {
552 	case OP_VERIFY:
553 		nfs4_fattr4_free(&argop->nfs_argop4_u.opverify.obj_attributes);
554 		break;
555 	case OP_NVERIFY:
556 		nfs4_fattr4_free(&argop->nfs_argop4_u.opnverify.obj_attributes);
557 		break;
558 	default:
559 		break;
560 	}
561 }
562 
563 static void
564 nfs4args_write(nfs_argop4 *argop, stable_how4 stable, rnode4_t *rp, cred_t *cr,
565     WRITE4args **wargs_pp, nfs4_stateid_types_t *sid_tp)
566 {
567 	WRITE4args *wargs = &argop->nfs_argop4_u.opwrite;
568 	mntinfo4_t *mi = VTOMI4(RTOV4(rp));
569 
570 	argop->argop = OP_WRITE;
571 	wargs->stable = stable;
572 	wargs->stateid = nfs4_get_w_stateid(cr, rp, curproc->p_pidp->pid_id,
573 	    mi, OP_WRITE, sid_tp);
574 	wargs->mblk = NULL;
575 	*wargs_pp = wargs;
576 }
577 
578 void
579 nfs4args_copen_free(OPEN4cargs *open_args)
580 {
581 	if (open_args->owner.owner_val) {
582 		kmem_free(open_args->owner.owner_val,
583 		    open_args->owner.owner_len);
584 	}
585 	if ((open_args->opentype == OPEN4_CREATE) &&
586 	    (open_args->mode != EXCLUSIVE4)) {
587 		nfs4_fattr4_free(&open_args->createhow4_u.createattrs);
588 	}
589 }
590 
591 /*
592  * XXX:  This is referenced in modstubs.s
593  */
594 struct vnodeops *
595 nfs4_getvnodeops(void)
596 {
597 	return (nfs4_vnodeops);
598 }
599 
600 /*
601  * The OPEN operation opens a regular file.
602  */
603 /*ARGSUSED3*/
604 static int
605 nfs4_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
606 {
607 	vnode_t *dvp = NULL;
608 	rnode4_t *rp, *drp;
609 	int error;
610 	int just_been_created;
611 	char fn[MAXNAMELEN];
612 
613 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4_open: "));
614 	if (nfs_zone() != VTOMI4(*vpp)->mi_zone)
615 		return (EIO);
616 	rp = VTOR4(*vpp);
617 
618 	/*
619 	 * Check to see if opening something besides a regular file;
620 	 * if so skip the OTW call
621 	 */
622 	if ((*vpp)->v_type != VREG) {
623 		error = nfs4_open_non_reg_file(vpp, flag, cr);
624 		return (error);
625 	}
626 
627 	/*
628 	 * XXX - would like a check right here to know if the file is
629 	 * executable or not, so as to skip OTW
630 	 */
631 
632 	if ((error = vtodv(*vpp, &dvp, cr, TRUE)) != 0)
633 		return (error);
634 
635 	drp = VTOR4(dvp);
636 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
637 		return (EINTR);
638 
639 	if ((error = vtoname(*vpp, fn, MAXNAMELEN)) != 0) {
640 		nfs_rw_exit(&drp->r_rwlock);
641 		return (error);
642 	}
643 
644 	/*
645 	 * See if this file has just been CREATEd.
646 	 * If so, clear the flag and update the dnlc, which was previously
647 	 * skipped in nfs4_create.
648 	 * XXX need better serilization on this.
649 	 * XXX move this into the nf4open_otw call, after we have
650 	 * XXX acquired the open owner seqid sync.
651 	 */
652 	mutex_enter(&rp->r_statev4_lock);
653 	if (rp->created_v4) {
654 		rp->created_v4 = 0;
655 		mutex_exit(&rp->r_statev4_lock);
656 
657 		dnlc_update(dvp, fn, *vpp);
658 		/* This is needed so we don't bump the open ref count */
659 		just_been_created = 1;
660 	} else {
661 		mutex_exit(&rp->r_statev4_lock);
662 		just_been_created = 0;
663 	}
664 
665 	/*
666 	 * If caller specified O_TRUNC/FTRUNC, then be sure to set
667 	 * FWRITE (to drive successful setattr(size=0) after open)
668 	 */
669 	if (flag & FTRUNC)
670 		flag |= FWRITE;
671 
672 	error = nfs4open_otw(dvp, fn, NULL, vpp, cr, 0, flag, 0,
673 	    just_been_created);
674 
675 	if (!error && !((*vpp)->v_flag & VROOT))
676 		dnlc_update(dvp, fn, *vpp);
677 
678 	nfs_rw_exit(&drp->r_rwlock);
679 
680 	/* release the hold from vtodv */
681 	VN_RELE(dvp);
682 
683 	/* exchange the shadow for the master vnode, if needed */
684 
685 	if (error == 0 && IS_SHADOW(*vpp, rp))
686 		sv_exchange(vpp);
687 
688 	return (error);
689 }
690 
691 /*
692  * See if there's a "lost open" request to be saved and recovered.
693  */
694 static void
695 nfs4open_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
696     nfs4_open_owner_t *oop, cred_t *cr, vnode_t *vp,
697     vnode_t *dvp, OPEN4cargs *open_args)
698 {
699 	vfs_t *vfsp;
700 	char *srccfp;
701 
702 	vfsp = (dvp ? dvp->v_vfsp : vp->v_vfsp);
703 
704 	if (error != ETIMEDOUT && error != EINTR &&
705 	    !NFS4_FRC_UNMT_ERR(error, vfsp)) {
706 		lost_rqstp->lr_op = 0;
707 		return;
708 	}
709 
710 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
711 	    "nfs4open_save_lost_rqst: error %d", error));
712 
713 	lost_rqstp->lr_op = OP_OPEN;
714 
715 	/*
716 	 * The vp (if it is not NULL) and dvp are held and rele'd via
717 	 * the recovery code.  See nfs4_save_lost_rqst.
718 	 */
719 	lost_rqstp->lr_vp = vp;
720 	lost_rqstp->lr_dvp = dvp;
721 	lost_rqstp->lr_oop = oop;
722 	lost_rqstp->lr_osp = NULL;
723 	lost_rqstp->lr_lop = NULL;
724 	lost_rqstp->lr_cr = cr;
725 	lost_rqstp->lr_flk = NULL;
726 	lost_rqstp->lr_oacc = open_args->share_access;
727 	lost_rqstp->lr_odeny = open_args->share_deny;
728 	lost_rqstp->lr_oclaim = open_args->claim;
729 	if (open_args->claim == CLAIM_DELEGATE_CUR) {
730 		lost_rqstp->lr_ostateid =
731 		    open_args->open_claim4_u.delegate_cur_info.delegate_stateid;
732 		srccfp = open_args->open_claim4_u.delegate_cur_info.cfile;
733 	} else {
734 		srccfp = open_args->open_claim4_u.cfile;
735 	}
736 	lost_rqstp->lr_ofile.utf8string_len = 0;
737 	lost_rqstp->lr_ofile.utf8string_val = NULL;
738 	(void) str_to_utf8(srccfp, &lost_rqstp->lr_ofile);
739 	lost_rqstp->lr_putfirst = FALSE;
740 }
741 
742 struct nfs4_excl_time {
743 	uint32 seconds;
744 	uint32 nseconds;
745 };
746 
747 /*
748  * The OPEN operation creates and/or opens a regular file
749  *
750  * ARGSUSED
751  */
752 static int
753 nfs4open_otw(vnode_t *dvp, char *file_name, struct vattr *in_va,
754     vnode_t **vpp, cred_t *cr, int create_flag, int open_flag,
755     enum createmode4 createmode, int file_just_been_created)
756 {
757 	rnode4_t *rp;
758 	rnode4_t *drp = VTOR4(dvp);
759 	vnode_t *vp = NULL;
760 	vnode_t *vpi = *vpp;
761 	bool_t needrecov = FALSE;
762 
763 	int doqueue = 1;
764 
765 	COMPOUND4args_clnt args;
766 	COMPOUND4res_clnt res;
767 	nfs_argop4 *argop;
768 	nfs_resop4 *resop;
769 	int argoplist_size;
770 	int idx_open, idx_fattr;
771 
772 	GETFH4res *gf_res = NULL;
773 	OPEN4res *op_res = NULL;
774 	nfs4_ga_res_t *garp;
775 	fattr4 *attr = NULL;
776 	struct nfs4_excl_time verf;
777 	bool_t did_excl_setup = FALSE;
778 	int created_osp;
779 
780 	OPEN4cargs *open_args;
781 	nfs4_open_owner_t	*oop = NULL;
782 	nfs4_open_stream_t	*osp = NULL;
783 	seqid4 seqid = 0;
784 	bool_t retry_open = FALSE;
785 	nfs4_recov_state_t recov_state;
786 	nfs4_lost_rqst_t lost_rqst;
787 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
788 	hrtime_t t;
789 	int acc = 0;
790 	cred_t *cred_otw = NULL;	/* cred used to do the RPC call */
791 	cred_t *ncr = NULL;
792 
793 	nfs4_sharedfh_t *otw_sfh;
794 	nfs4_sharedfh_t *orig_sfh;
795 	int fh_differs = 0;
796 	int numops, setgid_flag;
797 	int num_bseqid_retry = NFS4_NUM_RETRY_BAD_SEQID + 1;
798 
799 	/*
800 	 * Make sure we properly deal with setting the right gid on
801 	 * a newly created file to reflect the parent's setgid bit
802 	 */
803 	setgid_flag = 0;
804 	if (create_flag && in_va) {
805 
806 		/*
807 		 * If there is grpid mount flag used or
808 		 * the parent's directory has the setgid bit set
809 		 * _and_ the client was able to get a valid mapping
810 		 * for the parent dir's owner_group, we want to
811 		 * append NVERIFY(owner_group == dva.va_gid) and
812 		 * SETATTR to the CREATE compound.
813 		 */
814 		mutex_enter(&drp->r_statelock);
815 		if ((VTOMI4(dvp)->mi_flags & MI4_GRPID ||
816 		    drp->r_attr.va_mode & VSGID) &&
817 		    drp->r_attr.va_gid != GID_NOBODY) {
818 			in_va->va_mask |= AT_GID;
819 			in_va->va_gid = drp->r_attr.va_gid;
820 			setgid_flag = 1;
821 		}
822 		mutex_exit(&drp->r_statelock);
823 	}
824 
825 	/*
826 	 * Normal/non-create compound:
827 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new)
828 	 *
829 	 * Open(create) compound no setgid:
830 	 * PUTFH(dfh) + SAVEFH + OPEN(create) + GETFH + GETATTR(new) +
831 	 * RESTOREFH + GETATTR
832 	 *
833 	 * Open(create) setgid:
834 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new) +
835 	 * SAVEFH + PUTFH(dfh) + GETATTR(dvp) + RESTOREFH +
836 	 * NVERIFY(grp) + SETATTR
837 	 */
838 	if (setgid_flag) {
839 		numops = 10;
840 		idx_open = 1;
841 		idx_fattr = 3;
842 	} else if (create_flag) {
843 		numops = 7;
844 		idx_open = 2;
845 		idx_fattr = 4;
846 	} else {
847 		numops = 4;
848 		idx_open = 1;
849 		idx_fattr = 3;
850 	}
851 
852 	args.array_len = numops;
853 	argoplist_size = numops * sizeof (nfs_argop4);
854 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
855 
856 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw: "
857 	    "open %s open flag 0x%x cred %p", file_name, open_flag,
858 	    (void *)cr));
859 
860 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
861 	if (create_flag) {
862 		/*
863 		 * We are to create a file.  Initialize the passed in vnode
864 		 * pointer.
865 		 */
866 		vpi = NULL;
867 	} else {
868 		/*
869 		 * Check to see if the client owns a read delegation and is
870 		 * trying to open for write.  If so, then return the delegation
871 		 * to avoid the server doing a cb_recall and returning DELAY.
872 		 * NB - we don't use the statev4_lock here because we'd have
873 		 * to drop the lock anyway and the result would be stale.
874 		 */
875 		if ((open_flag & FWRITE) &&
876 		    VTOR4(vpi)->r_deleg_type == OPEN_DELEGATE_READ)
877 			(void) nfs4delegreturn(VTOR4(vpi), NFS4_DR_REOPEN);
878 
879 		/*
880 		 * If the file has a delegation, then do an access check up
881 		 * front.  This avoids having to an access check later after
882 		 * we've already done start_op, which could deadlock.
883 		 */
884 		if (VTOR4(vpi)->r_deleg_type != OPEN_DELEGATE_NONE) {
885 			if (open_flag & FREAD &&
886 			    nfs4_access(vpi, VREAD, 0, cr, NULL) == 0)
887 				acc |= VREAD;
888 			if (open_flag & FWRITE &&
889 			    nfs4_access(vpi, VWRITE, 0, cr, NULL) == 0)
890 				acc |= VWRITE;
891 		}
892 	}
893 
894 	drp = VTOR4(dvp);
895 
896 	recov_state.rs_flags = 0;
897 	recov_state.rs_num_retry_despite_err = 0;
898 	cred_otw = cr;
899 
900 recov_retry:
901 	fh_differs = 0;
902 	nfs4_error_zinit(&e);
903 
904 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, vpi, &recov_state);
905 	if (e.error) {
906 		if (ncr != NULL)
907 			crfree(ncr);
908 		kmem_free(argop, argoplist_size);
909 		return (e.error);
910 	}
911 
912 	args.ctag = TAG_OPEN;
913 	args.array_len = numops;
914 	args.array = argop;
915 
916 	/* putfh directory fh */
917 	argop[0].argop = OP_CPUTFH;
918 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
919 
920 	/* OPEN: either op 1 or op 2 depending upon create/setgid flags */
921 	argop[idx_open].argop = OP_COPEN;
922 	open_args = &argop[idx_open].nfs_argop4_u.opcopen;
923 	open_args->claim = CLAIM_NULL;
924 
925 	/* name of file */
926 	open_args->open_claim4_u.cfile = file_name;
927 	open_args->owner.owner_len = 0;
928 	open_args->owner.owner_val = NULL;
929 
930 	if (create_flag) {
931 		/* CREATE a file */
932 		open_args->opentype = OPEN4_CREATE;
933 		open_args->mode = createmode;
934 		if (createmode == EXCLUSIVE4) {
935 			if (did_excl_setup == FALSE) {
936 				verf.seconds = zone_get_hostid(NULL);
937 				if (verf.seconds != 0)
938 					verf.nseconds = newnum();
939 				else {
940 					timestruc_t now;
941 
942 					gethrestime(&now);
943 					verf.seconds = now.tv_sec;
944 					verf.nseconds = now.tv_nsec;
945 				}
946 				/*
947 				 * Since the server will use this value for the
948 				 * mtime, make sure that it can't overflow. Zero
949 				 * out the MSB. The actual value does not matter
950 				 * here, only its uniqeness.
951 				 */
952 				verf.seconds &= INT32_MAX;
953 				did_excl_setup = TRUE;
954 			}
955 
956 			/* Now copy over verifier to OPEN4args. */
957 			open_args->createhow4_u.createverf = *(uint64_t *)&verf;
958 		} else {
959 			int v_error;
960 			bitmap4 supp_attrs;
961 			servinfo4_t *svp;
962 
963 			attr = &open_args->createhow4_u.createattrs;
964 
965 			svp = drp->r_server;
966 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
967 			supp_attrs = svp->sv_supp_attrs;
968 			nfs_rw_exit(&svp->sv_lock);
969 
970 			/* GUARDED4 or UNCHECKED4 */
971 			v_error = vattr_to_fattr4(in_va, NULL, attr, 0, OP_OPEN,
972 			    supp_attrs);
973 			if (v_error) {
974 				bzero(attr, sizeof (*attr));
975 				nfs4args_copen_free(open_args);
976 				nfs4_end_op(VTOMI4(dvp), dvp, vpi,
977 				    &recov_state, FALSE);
978 				if (ncr != NULL)
979 					crfree(ncr);
980 				kmem_free(argop, argoplist_size);
981 				return (v_error);
982 			}
983 		}
984 	} else {
985 		/* NO CREATE */
986 		open_args->opentype = OPEN4_NOCREATE;
987 	}
988 
989 	if (recov_state.rs_sp != NULL) {
990 		mutex_enter(&recov_state.rs_sp->s_lock);
991 		open_args->owner.clientid = recov_state.rs_sp->clientid;
992 		mutex_exit(&recov_state.rs_sp->s_lock);
993 	} else {
994 		/* XXX should we just fail here? */
995 		open_args->owner.clientid = 0;
996 	}
997 
998 	/*
999 	 * This increments oop's ref count or creates a temporary 'just_created'
1000 	 * open owner that will become valid when this OPEN/OPEN_CONFIRM call
1001 	 * completes.
1002 	 */
1003 	mutex_enter(&VTOMI4(dvp)->mi_lock);
1004 
1005 	/* See if a permanent or just created open owner exists */
1006 	oop = find_open_owner_nolock(cr, NFS4_JUST_CREATED, VTOMI4(dvp));
1007 	if (!oop) {
1008 		/*
1009 		 * This open owner does not exist so create a temporary
1010 		 * just created one.
1011 		 */
1012 		oop = create_open_owner(cr, VTOMI4(dvp));
1013 		ASSERT(oop != NULL);
1014 	}
1015 	mutex_exit(&VTOMI4(dvp)->mi_lock);
1016 
1017 	/* this length never changes, do alloc before seqid sync */
1018 	open_args->owner.owner_len = sizeof (oop->oo_name);
1019 	open_args->owner.owner_val =
1020 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1021 
1022 	e.error = nfs4_start_open_seqid_sync(oop, VTOMI4(dvp));
1023 	if (e.error == EAGAIN) {
1024 		open_owner_rele(oop);
1025 		nfs4args_copen_free(open_args);
1026 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1027 		if (ncr != NULL) {
1028 			crfree(ncr);
1029 			ncr = NULL;
1030 		}
1031 		goto recov_retry;
1032 	}
1033 
1034 	/* Check to see if we need to do the OTW call */
1035 	if (!create_flag) {
1036 		if (!nfs4_is_otw_open_necessary(oop, open_flag, vpi,
1037 		    file_just_been_created, &e.error, acc, &recov_state)) {
1038 
1039 			/*
1040 			 * The OTW open is not necessary.  Either
1041 			 * the open can succeed without it (eg.
1042 			 * delegation, error == 0) or the open
1043 			 * must fail due to an access failure
1044 			 * (error != 0).  In either case, tidy
1045 			 * up and return.
1046 			 */
1047 
1048 			nfs4_end_open_seqid_sync(oop);
1049 			open_owner_rele(oop);
1050 			nfs4args_copen_free(open_args);
1051 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, FALSE);
1052 			if (ncr != NULL)
1053 				crfree(ncr);
1054 			kmem_free(argop, argoplist_size);
1055 			return (e.error);
1056 		}
1057 	}
1058 
1059 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1060 	    open_args->owner.owner_len);
1061 
1062 	seqid = nfs4_get_open_seqid(oop) + 1;
1063 	open_args->seqid = seqid;
1064 	open_args->share_access = 0;
1065 	if (open_flag & FREAD)
1066 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1067 	if (open_flag & FWRITE)
1068 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1069 	open_args->share_deny = OPEN4_SHARE_DENY_NONE;
1070 
1071 
1072 
1073 	/*
1074 	 * getfh w/sanity check for idx_open/idx_fattr
1075 	 */
1076 	ASSERT((idx_open + 1) == (idx_fattr - 1));
1077 	argop[idx_open + 1].argop = OP_GETFH;
1078 
1079 	/* getattr */
1080 	argop[idx_fattr].argop = OP_GETATTR;
1081 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1082 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1083 
1084 	if (setgid_flag) {
1085 		vattr_t	_v;
1086 		servinfo4_t *svp;
1087 		bitmap4	supp_attrs;
1088 
1089 		svp = drp->r_server;
1090 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1091 		supp_attrs = svp->sv_supp_attrs;
1092 		nfs_rw_exit(&svp->sv_lock);
1093 
1094 		/*
1095 		 * For setgid case, we need to:
1096 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1097 		 */
1098 		argop[4].argop = OP_SAVEFH;
1099 
1100 		argop[5].argop = OP_CPUTFH;
1101 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
1102 
1103 		argop[6].argop = OP_GETATTR;
1104 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1105 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1106 
1107 		argop[7].argop = OP_RESTOREFH;
1108 
1109 		/*
1110 		 * nverify
1111 		 */
1112 		_v.va_mask = AT_GID;
1113 		_v.va_gid = in_va->va_gid;
1114 		if (!(e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
1115 		    supp_attrs))) {
1116 
1117 			/*
1118 			 * setattr
1119 			 *
1120 			 * We _know_ we're not messing with AT_SIZE or
1121 			 * AT_XTIME, so no need for stateid or flags.
1122 			 * Also we specify NULL rp since we're only
1123 			 * interested in setting owner_group attributes.
1124 			 */
1125 			nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr,
1126 			    supp_attrs, &e.error, 0);
1127 			if (e.error)
1128 				nfs4args_verify_free(&argop[8]);
1129 		}
1130 
1131 		if (e.error) {
1132 			/*
1133 			 * XXX - Revisit the last argument to nfs4_end_op()
1134 			 *	 once 5020486 is fixed.
1135 			 */
1136 			nfs4_end_open_seqid_sync(oop);
1137 			open_owner_rele(oop);
1138 			nfs4args_copen_free(open_args);
1139 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1140 			if (ncr != NULL)
1141 				crfree(ncr);
1142 			kmem_free(argop, argoplist_size);
1143 			return (e.error);
1144 		}
1145 	} else if (create_flag) {
1146 		argop[1].argop = OP_SAVEFH;
1147 
1148 		argop[5].argop = OP_RESTOREFH;
1149 
1150 		argop[6].argop = OP_GETATTR;
1151 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1152 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1153 	}
1154 
1155 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1156 	    "nfs4open_otw: %s call, nm %s, rp %s",
1157 	    needrecov ? "recov" : "first", file_name,
1158 	    rnode4info(VTOR4(dvp))));
1159 
1160 	t = gethrtime();
1161 
1162 	rfs4call(VTOMI4(dvp), &args, &res, cred_otw, &doqueue, 0, &e);
1163 
1164 	if (!e.error && nfs4_need_to_bump_seqid(&res))
1165 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1166 
1167 	needrecov = nfs4_needs_recovery(&e, TRUE, dvp->v_vfsp);
1168 
1169 	if (e.error || needrecov) {
1170 		bool_t abort = FALSE;
1171 
1172 		if (needrecov) {
1173 			nfs4_bseqid_entry_t *bsep = NULL;
1174 
1175 			nfs4open_save_lost_rqst(e.error, &lost_rqst, oop,
1176 			    cred_otw, vpi, dvp, open_args);
1177 
1178 			if (!e.error && res.status == NFS4ERR_BAD_SEQID) {
1179 				bsep = nfs4_create_bseqid_entry(oop, NULL,
1180 				    vpi, 0, args.ctag, open_args->seqid);
1181 				num_bseqid_retry--;
1182 			}
1183 
1184 			abort = nfs4_start_recovery(&e, VTOMI4(dvp), dvp, vpi,
1185 			    NULL, lost_rqst.lr_op == OP_OPEN ?
1186 			    &lost_rqst : NULL, OP_OPEN, bsep);
1187 
1188 			if (bsep)
1189 				kmem_free(bsep, sizeof (*bsep));
1190 			/* give up if we keep getting BAD_SEQID */
1191 			if (num_bseqid_retry == 0)
1192 				abort = TRUE;
1193 			if (abort == TRUE && e.error == 0)
1194 				e.error = geterrno4(res.status);
1195 		}
1196 		nfs4_end_open_seqid_sync(oop);
1197 		open_owner_rele(oop);
1198 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1199 		nfs4args_copen_free(open_args);
1200 		if (setgid_flag) {
1201 			nfs4args_verify_free(&argop[8]);
1202 			nfs4args_setattr_free(&argop[9]);
1203 		}
1204 		if (!e.error)
1205 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1206 		if (ncr != NULL) {
1207 			crfree(ncr);
1208 			ncr = NULL;
1209 		}
1210 		if (!needrecov || abort == TRUE || e.error == EINTR ||
1211 		    NFS4_FRC_UNMT_ERR(e.error, dvp->v_vfsp)) {
1212 			kmem_free(argop, argoplist_size);
1213 			return (e.error);
1214 		}
1215 		goto recov_retry;
1216 	}
1217 
1218 	/*
1219 	 * Will check and update lease after checking the rflag for
1220 	 * OPEN_CONFIRM in the successful OPEN call.
1221 	 */
1222 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
1223 
1224 		/*
1225 		 * XXX what if we're crossing mount points from server1:/drp
1226 		 * to server2:/drp/rp.
1227 		 */
1228 
1229 		/* Signal our end of use of the open seqid */
1230 		nfs4_end_open_seqid_sync(oop);
1231 
1232 		/*
1233 		 * This will destroy the open owner if it was just created,
1234 		 * and no one else has put a reference on it.
1235 		 */
1236 		open_owner_rele(oop);
1237 		if (create_flag && (createmode != EXCLUSIVE4) &&
1238 		    res.status == NFS4ERR_BADOWNER)
1239 			nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1240 
1241 		e.error = geterrno4(res.status);
1242 		nfs4args_copen_free(open_args);
1243 		if (setgid_flag) {
1244 			nfs4args_verify_free(&argop[8]);
1245 			nfs4args_setattr_free(&argop[9]);
1246 		}
1247 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1248 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1249 		/*
1250 		 * If the reply is NFS4ERR_ACCESS, it may be because
1251 		 * we are root (no root net access).  If the real uid
1252 		 * is not root, then retry with the real uid instead.
1253 		 */
1254 		if (ncr != NULL) {
1255 			crfree(ncr);
1256 			ncr = NULL;
1257 		}
1258 		if (res.status == NFS4ERR_ACCESS &&
1259 		    (ncr = crnetadjust(cred_otw)) != NULL) {
1260 			cred_otw = ncr;
1261 			goto recov_retry;
1262 		}
1263 		kmem_free(argop, argoplist_size);
1264 		return (e.error);
1265 	}
1266 
1267 	resop = &res.array[idx_open];  /* open res */
1268 	op_res = &resop->nfs_resop4_u.opopen;
1269 
1270 #ifdef DEBUG
1271 	/*
1272 	 * verify attrset bitmap
1273 	 */
1274 	if (create_flag &&
1275 	    (createmode == UNCHECKED4 || createmode == GUARDED4)) {
1276 		/* make sure attrset returned is what we asked for */
1277 		/* XXX Ignore this 'error' for now */
1278 		if (attr->attrmask != op_res->attrset)
1279 			/* EMPTY */;
1280 	}
1281 #endif
1282 
1283 	if (op_res->rflags & OPEN4_RESULT_LOCKTYPE_POSIX) {
1284 		mutex_enter(&VTOMI4(dvp)->mi_lock);
1285 		VTOMI4(dvp)->mi_flags |= MI4_POSIX_LOCK;
1286 		mutex_exit(&VTOMI4(dvp)->mi_lock);
1287 	}
1288 
1289 	resop = &res.array[idx_open + 1];  /* getfh res */
1290 	gf_res = &resop->nfs_resop4_u.opgetfh;
1291 
1292 	otw_sfh = sfh4_get(&gf_res->object, VTOMI4(dvp));
1293 
1294 	/*
1295 	 * The open stateid has been updated on the server but not
1296 	 * on the client yet.  There is a path: makenfs4node->nfs4_attr_cache->
1297 	 * flush_pages->VOP_PUTPAGE->...->nfs4write where we will issue an OTW
1298 	 * WRITE call.  That, however, will use the old stateid, so go ahead
1299 	 * and upate the open stateid now, before any call to makenfs4node.
1300 	 */
1301 	if (vpi) {
1302 		nfs4_open_stream_t	*tmp_osp;
1303 		rnode4_t		*tmp_rp = VTOR4(vpi);
1304 
1305 		tmp_osp = find_open_stream(oop, tmp_rp);
1306 		if (tmp_osp) {
1307 			tmp_osp->open_stateid = op_res->stateid;
1308 			mutex_exit(&tmp_osp->os_sync_lock);
1309 			open_stream_rele(tmp_osp, tmp_rp);
1310 		}
1311 
1312 		/*
1313 		 * We must determine if the file handle given by the otw open
1314 		 * is the same as the file handle which was passed in with
1315 		 * *vpp.  This case can be reached if the file we are trying
1316 		 * to open has been removed and another file has been created
1317 		 * having the same file name.  The passed in vnode is released
1318 		 * later.
1319 		 */
1320 		orig_sfh = VTOR4(vpi)->r_fh;
1321 		fh_differs = nfs4cmpfh(&orig_sfh->sfh_fh, &otw_sfh->sfh_fh);
1322 	}
1323 
1324 	garp = &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res;
1325 
1326 	if (create_flag || fh_differs) {
1327 		int rnode_err = 0;
1328 
1329 		vp = makenfs4node(otw_sfh, garp, dvp->v_vfsp, t, cr,
1330 		    dvp, fn_get(VTOSV(dvp)->sv_name, file_name, otw_sfh));
1331 
1332 		if (e.error)
1333 			PURGE_ATTRCACHE4(vp);
1334 		/*
1335 		 * For the newly created vp case, make sure the rnode
1336 		 * isn't bad before using it.
1337 		 */
1338 		mutex_enter(&(VTOR4(vp))->r_statelock);
1339 		if (VTOR4(vp)->r_flags & R4RECOVERR)
1340 			rnode_err = EIO;
1341 		mutex_exit(&(VTOR4(vp))->r_statelock);
1342 
1343 		if (rnode_err) {
1344 			nfs4_end_open_seqid_sync(oop);
1345 			nfs4args_copen_free(open_args);
1346 			if (setgid_flag) {
1347 				nfs4args_verify_free(&argop[8]);
1348 				nfs4args_setattr_free(&argop[9]);
1349 			}
1350 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1351 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1352 			    needrecov);
1353 			open_owner_rele(oop);
1354 			VN_RELE(vp);
1355 			if (ncr != NULL)
1356 				crfree(ncr);
1357 			sfh4_rele(&otw_sfh);
1358 			kmem_free(argop, argoplist_size);
1359 			return (EIO);
1360 		}
1361 	} else {
1362 		vp = vpi;
1363 	}
1364 	sfh4_rele(&otw_sfh);
1365 
1366 	/*
1367 	 * It seems odd to get a full set of attrs and then not update
1368 	 * the object's attrcache in the non-create case.  Create case uses
1369 	 * the attrs since makenfs4node checks to see if the attrs need to
1370 	 * be updated (and then updates them).  The non-create case should
1371 	 * update attrs also.
1372 	 */
1373 	if (! create_flag && ! fh_differs && !e.error) {
1374 		nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
1375 	}
1376 
1377 	nfs4_error_zinit(&e);
1378 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
1379 		/* This does not do recovery for vp explicitly. */
1380 		nfs4open_confirm(vp, &seqid, &op_res->stateid, cred_otw, FALSE,
1381 		    &retry_open, oop, FALSE, &e, &num_bseqid_retry);
1382 
1383 		if (e.error || e.stat) {
1384 			nfs4_end_open_seqid_sync(oop);
1385 			nfs4args_copen_free(open_args);
1386 			if (setgid_flag) {
1387 				nfs4args_verify_free(&argop[8]);
1388 				nfs4args_setattr_free(&argop[9]);
1389 			}
1390 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1391 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1392 			    needrecov);
1393 			open_owner_rele(oop);
1394 			if (create_flag || fh_differs) {
1395 				/* rele the makenfs4node */
1396 				VN_RELE(vp);
1397 			}
1398 			if (ncr != NULL) {
1399 				crfree(ncr);
1400 				ncr = NULL;
1401 			}
1402 			if (retry_open == TRUE) {
1403 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1404 				    "nfs4open_otw: retry the open since OPEN "
1405 				    "CONFIRM failed with error %d stat %d",
1406 				    e.error, e.stat));
1407 				if (create_flag && createmode == GUARDED4) {
1408 					NFS4_DEBUG(nfs4_client_recov_debug,
1409 					    (CE_NOTE, "nfs4open_otw: switch "
1410 					    "createmode from GUARDED4 to "
1411 					    "UNCHECKED4"));
1412 					createmode = UNCHECKED4;
1413 				}
1414 				goto recov_retry;
1415 			}
1416 			if (!e.error) {
1417 				if (create_flag && (createmode != EXCLUSIVE4) &&
1418 				    e.stat == NFS4ERR_BADOWNER)
1419 					nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1420 
1421 				e.error = geterrno4(e.stat);
1422 			}
1423 			kmem_free(argop, argoplist_size);
1424 			return (e.error);
1425 		}
1426 	}
1427 
1428 	rp = VTOR4(vp);
1429 
1430 	mutex_enter(&rp->r_statev4_lock);
1431 	if (create_flag)
1432 		rp->created_v4 = 1;
1433 	mutex_exit(&rp->r_statev4_lock);
1434 
1435 	mutex_enter(&oop->oo_lock);
1436 	/* Doesn't matter if 'oo_just_created' already was set as this */
1437 	oop->oo_just_created = NFS4_PERM_CREATED;
1438 	if (oop->oo_cred_otw)
1439 		crfree(oop->oo_cred_otw);
1440 	oop->oo_cred_otw = cred_otw;
1441 	crhold(oop->oo_cred_otw);
1442 	mutex_exit(&oop->oo_lock);
1443 
1444 	/* returns with 'os_sync_lock' held */
1445 	osp = find_or_create_open_stream(oop, rp, &created_osp);
1446 	if (!osp) {
1447 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1448 		    "nfs4open_otw: failed to create an open stream"));
1449 		NFS4_DEBUG(nfs4_seqid_sync, (CE_NOTE, "nfs4open_otw: "
1450 		    "signal our end of use of the open seqid"));
1451 
1452 		nfs4_end_open_seqid_sync(oop);
1453 		open_owner_rele(oop);
1454 		nfs4args_copen_free(open_args);
1455 		if (setgid_flag) {
1456 			nfs4args_verify_free(&argop[8]);
1457 			nfs4args_setattr_free(&argop[9]);
1458 		}
1459 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1460 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1461 		if (create_flag || fh_differs)
1462 			VN_RELE(vp);
1463 		if (ncr != NULL)
1464 			crfree(ncr);
1465 
1466 		kmem_free(argop, argoplist_size);
1467 		return (EINVAL);
1468 
1469 	}
1470 
1471 	osp->open_stateid = op_res->stateid;
1472 
1473 	if (open_flag & FREAD)
1474 		osp->os_share_acc_read++;
1475 	if (open_flag & FWRITE)
1476 		osp->os_share_acc_write++;
1477 	osp->os_share_deny_none++;
1478 
1479 	/*
1480 	 * Need to reset this bitfield for the possible case where we were
1481 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
1482 	 * we could retry the CLOSE, OPENed the file again.
1483 	 */
1484 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
1485 	osp->os_final_close = 0;
1486 	osp->os_force_close = 0;
1487 #ifdef DEBUG
1488 	if (osp->os_failed_reopen)
1489 		NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE, "nfs4open_otw:"
1490 		    " clearing os_failed_reopen for osp %p, cr %p, rp %s",
1491 		    (void *)osp, (void *)cr, rnode4info(rp)));
1492 #endif
1493 	osp->os_failed_reopen = 0;
1494 
1495 	mutex_exit(&osp->os_sync_lock);
1496 
1497 	nfs4_end_open_seqid_sync(oop);
1498 
1499 	if (created_osp && recov_state.rs_sp != NULL) {
1500 		mutex_enter(&recov_state.rs_sp->s_lock);
1501 		nfs4_inc_state_ref_count_nolock(recov_state.rs_sp, VTOMI4(dvp));
1502 		mutex_exit(&recov_state.rs_sp->s_lock);
1503 	}
1504 
1505 	/* get rid of our reference to find oop */
1506 	open_owner_rele(oop);
1507 
1508 	open_stream_rele(osp, rp);
1509 
1510 	/* accept delegation, if any */
1511 	nfs4_delegation_accept(rp, CLAIM_NULL, op_res, garp, cred_otw);
1512 
1513 	nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1514 
1515 	if (createmode == EXCLUSIVE4 &&
1516 	    (in_va->va_mask & ~(AT_GID | AT_SIZE))) {
1517 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw:"
1518 		    " EXCLUSIVE4: sending a SETATTR"));
1519 		/*
1520 		 * If doing an exclusive create, then generate
1521 		 * a SETATTR to set the initial attributes.
1522 		 * Try to set the mtime and the atime to the
1523 		 * server's current time.  It is somewhat
1524 		 * expected that these fields will be used to
1525 		 * store the exclusive create cookie.  If not,
1526 		 * server implementors will need to know that
1527 		 * a SETATTR will follow an exclusive create
1528 		 * and the cookie should be destroyed if
1529 		 * appropriate.
1530 		 *
1531 		 * The AT_GID and AT_SIZE bits are turned off
1532 		 * so that the SETATTR request will not attempt
1533 		 * to process these.  The gid will be set
1534 		 * separately if appropriate.  The size is turned
1535 		 * off because it is assumed that a new file will
1536 		 * be created empty and if the file wasn't empty,
1537 		 * then the exclusive create will have failed
1538 		 * because the file must have existed already.
1539 		 * Therefore, no truncate operation is needed.
1540 		 */
1541 		in_va->va_mask &= ~(AT_GID | AT_SIZE);
1542 		in_va->va_mask |= (AT_MTIME | AT_ATIME);
1543 
1544 		e.error = nfs4setattr(vp, in_va, 0, cr, NULL);
1545 		if (e.error) {
1546 			/*
1547 			 * Couldn't correct the attributes of
1548 			 * the newly created file and the
1549 			 * attributes are wrong.  Remove the
1550 			 * file and return an error to the
1551 			 * application.
1552 			 */
1553 			/* XXX will this take care of client state ? */
1554 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1555 			    "nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1556 			    " remove file", e.error));
1557 			VN_RELE(vp);
1558 			(void) nfs4_remove(dvp, file_name, cr, NULL, 0);
1559 			/*
1560 			 * Since we've reled the vnode and removed
1561 			 * the file we now need to return the error.
1562 			 * At this point we don't want to update the
1563 			 * dircaches, call nfs4_waitfor_purge_complete
1564 			 * or set vpp to vp so we need to skip these
1565 			 * as well.
1566 			 */
1567 			goto skip_update_dircaches;
1568 		}
1569 	}
1570 
1571 	/*
1572 	 * If we created or found the correct vnode, due to create_flag or
1573 	 * fh_differs being set, then update directory cache attribute, readdir
1574 	 * and dnlc caches.
1575 	 */
1576 	if (create_flag || fh_differs) {
1577 		dirattr_info_t dinfo, *dinfop;
1578 
1579 		/*
1580 		 * Make sure getattr succeeded before using results.
1581 		 * note: op 7 is getattr(dir) for both flavors of
1582 		 * open(create).
1583 		 */
1584 		if (create_flag && res.status == NFS4_OK) {
1585 			dinfo.di_time_call = t;
1586 			dinfo.di_cred = cr;
1587 			dinfo.di_garp =
1588 			    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
1589 			dinfop = &dinfo;
1590 		} else {
1591 			dinfop = NULL;
1592 		}
1593 
1594 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1595 		    dinfop);
1596 	}
1597 
1598 	/*
1599 	 * If the page cache for this file was flushed from actions
1600 	 * above, it was done asynchronously and if that is true,
1601 	 * there is a need to wait here for it to complete.  This must
1602 	 * be done outside of start_fop/end_fop.
1603 	 */
1604 	(void) nfs4_waitfor_purge_complete(vp);
1605 
1606 	/*
1607 	 * It is implicit that we are in the open case (create_flag == 0) since
1608 	 * fh_differs can only be set to a non-zero value in the open case.
1609 	 */
1610 	if (fh_differs != 0 && vpi != NULL)
1611 		VN_RELE(vpi);
1612 
1613 	/*
1614 	 * Be sure to set *vpp to the correct value before returning.
1615 	 */
1616 	*vpp = vp;
1617 
1618 skip_update_dircaches:
1619 
1620 	nfs4args_copen_free(open_args);
1621 	if (setgid_flag) {
1622 		nfs4args_verify_free(&argop[8]);
1623 		nfs4args_setattr_free(&argop[9]);
1624 	}
1625 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1626 
1627 	if (ncr)
1628 		crfree(ncr);
1629 	kmem_free(argop, argoplist_size);
1630 	return (e.error);
1631 }
1632 
1633 /*
1634  * Reopen an open instance.  cf. nfs4open_otw().
1635  *
1636  * Errors are returned by the nfs4_error_t parameter.
1637  * - ep->error contains an errno value or zero.
1638  * - if it is zero, ep->stat is set to an NFS status code, if any.
1639  *   If the file could not be reopened, but the caller should continue, the
1640  *   file is marked dead and no error values are returned.  If the caller
1641  *   should stop recovering open files and start over, either the ep->error
1642  *   value or ep->stat will indicate an error (either something that requires
1643  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1644  *   filehandles) may be handled silently by this routine.
1645  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1646  *   will be started, so the caller should not do it.
1647  *
1648  * Gotos:
1649  * - kill_file : reopen failed in such a fashion to constitute marking the
1650  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1651  *   is for cases where recovery is not possible.
1652  * - failed_reopen : same as above, except that the file has already been
1653  *   marked dead, so no need to do it again.
1654  * - bailout : reopen failed but we are able to recover and retry the reopen -
1655  *   either within this function immediately or via the calling function.
1656  */
1657 
1658 void
1659 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1660     open_claim_type4 claim, bool_t frc_use_claim_previous,
1661     bool_t is_recov)
1662 {
1663 	COMPOUND4args_clnt args;
1664 	COMPOUND4res_clnt res;
1665 	nfs_argop4 argop[4];
1666 	nfs_resop4 *resop;
1667 	OPEN4res *op_res = NULL;
1668 	OPEN4cargs *open_args;
1669 	GETFH4res *gf_res;
1670 	rnode4_t *rp = VTOR4(vp);
1671 	int doqueue = 1;
1672 	cred_t *cr = NULL, *cred_otw = NULL;
1673 	nfs4_open_owner_t *oop = NULL;
1674 	seqid4 seqid;
1675 	nfs4_ga_res_t *garp;
1676 	char fn[MAXNAMELEN];
1677 	nfs4_recov_state_t recov = {NULL, 0};
1678 	nfs4_lost_rqst_t lost_rqst;
1679 	mntinfo4_t *mi = VTOMI4(vp);
1680 	bool_t abort;
1681 	char *failed_msg = "";
1682 	int fh_different;
1683 	hrtime_t t;
1684 	nfs4_bseqid_entry_t *bsep = NULL;
1685 
1686 	ASSERT(nfs4_consistent_type(vp));
1687 	ASSERT(nfs_zone() == mi->mi_zone);
1688 
1689 	nfs4_error_zinit(ep);
1690 
1691 	/* this is the cred used to find the open owner */
1692 	cr = state_to_cred(osp);
1693 	if (cr == NULL) {
1694 		failed_msg = "Couldn't reopen: no cred";
1695 		goto kill_file;
1696 	}
1697 	/* use this cred for OTW operations */
1698 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1699 
1700 top:
1701 	nfs4_error_zinit(ep);
1702 
1703 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1704 		/* File system has been unmounted, quit */
1705 		ep->error = EIO;
1706 		failed_msg = "Couldn't reopen: file system has been unmounted";
1707 		goto kill_file;
1708 	}
1709 
1710 	oop = osp->os_open_owner;
1711 
1712 	ASSERT(oop != NULL);
1713 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1714 		failed_msg = "can't reopen: no open owner";
1715 		goto kill_file;
1716 	}
1717 	open_owner_hold(oop);
1718 
1719 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1720 	if (ep->error) {
1721 		open_owner_rele(oop);
1722 		oop = NULL;
1723 		goto bailout;
1724 	}
1725 
1726 	/*
1727 	 * If the rnode has a delegation and the delegation has been
1728 	 * recovered and the server didn't request a recall and the caller
1729 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1730 	 * recovery) and the rnode hasn't been marked dead, then install
1731 	 * the delegation stateid in the open stream.  Otherwise, proceed
1732 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1733 	 */
1734 	mutex_enter(&rp->r_statev4_lock);
1735 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1736 	    !rp->r_deleg_return_pending &&
1737 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1738 	    !rp->r_deleg_needs_recall &&
1739 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1740 	    !(rp->r_flags & R4RECOVERR)) {
1741 		mutex_enter(&osp->os_sync_lock);
1742 		osp->os_delegation = 1;
1743 		osp->open_stateid = rp->r_deleg_stateid;
1744 		mutex_exit(&osp->os_sync_lock);
1745 		mutex_exit(&rp->r_statev4_lock);
1746 		goto bailout;
1747 	}
1748 	mutex_exit(&rp->r_statev4_lock);
1749 
1750 	/*
1751 	 * If the file failed recovery, just quit.  This failure need not
1752 	 * affect other reopens, so don't return an error.
1753 	 */
1754 	mutex_enter(&rp->r_statelock);
1755 	if (rp->r_flags & R4RECOVERR) {
1756 		mutex_exit(&rp->r_statelock);
1757 		ep->error = 0;
1758 		goto failed_reopen;
1759 	}
1760 	mutex_exit(&rp->r_statelock);
1761 
1762 	/*
1763 	 * argop is empty here
1764 	 *
1765 	 * PUTFH, OPEN, GETATTR
1766 	 */
1767 	args.ctag = TAG_REOPEN;
1768 	args.array_len = 4;
1769 	args.array = argop;
1770 
1771 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1772 	    "nfs4_reopen: file is type %d, id %s",
1773 	    vp->v_type, rnode4info(VTOR4(vp))));
1774 
1775 	argop[0].argop = OP_CPUTFH;
1776 
1777 	if (claim != CLAIM_PREVIOUS) {
1778 		/*
1779 		 * if this is a file mount then
1780 		 * use the mntinfo parentfh
1781 		 */
1782 		argop[0].nfs_argop4_u.opcputfh.sfh =
1783 		    (vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1784 		    VTOSV(vp)->sv_dfh;
1785 	} else {
1786 		/* putfh fh to reopen */
1787 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1788 	}
1789 
1790 	argop[1].argop = OP_COPEN;
1791 	open_args = &argop[1].nfs_argop4_u.opcopen;
1792 	open_args->claim = claim;
1793 
1794 	if (claim == CLAIM_NULL) {
1795 
1796 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1797 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1798 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1799 			    (void *)vp);
1800 			failed_msg = "Couldn't reopen: vtoname failed for "
1801 			    "CLAIM_NULL";
1802 			/* nothing allocated yet */
1803 			goto kill_file;
1804 		}
1805 
1806 		open_args->open_claim4_u.cfile = fn;
1807 	} else if (claim == CLAIM_PREVIOUS) {
1808 
1809 		/*
1810 		 * We have two cases to deal with here:
1811 		 * 1) We're being called to reopen files in order to satisfy
1812 		 *    a lock operation request which requires us to explicitly
1813 		 *    reopen files which were opened under a delegation.  If
1814 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1815 		 *    that case, frc_use_claim_previous is TRUE and we must
1816 		 *    use the rnode's current delegation type (r_deleg_type).
1817 		 * 2) We're reopening files during some form of recovery.
1818 		 *    In this case, frc_use_claim_previous is FALSE and we
1819 		 *    use the delegation type appropriate for recovery
1820 		 *    (r_deleg_needs_recovery).
1821 		 */
1822 		mutex_enter(&rp->r_statev4_lock);
1823 		open_args->open_claim4_u.delegate_type =
1824 		    frc_use_claim_previous ?
1825 		    rp->r_deleg_type :
1826 		    rp->r_deleg_needs_recovery;
1827 		mutex_exit(&rp->r_statev4_lock);
1828 
1829 	} else if (claim == CLAIM_DELEGATE_CUR) {
1830 
1831 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1832 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1833 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1834 			    "with %m", (void *)vp);
1835 			failed_msg = "Couldn't reopen: vtoname failed for "
1836 			    "CLAIM_DELEGATE_CUR";
1837 			/* nothing allocated yet */
1838 			goto kill_file;
1839 		}
1840 
1841 		mutex_enter(&rp->r_statev4_lock);
1842 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1843 		    rp->r_deleg_stateid;
1844 		mutex_exit(&rp->r_statev4_lock);
1845 
1846 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1847 	}
1848 	open_args->opentype = OPEN4_NOCREATE;
1849 	open_args->owner.clientid = mi2clientid(mi);
1850 	open_args->owner.owner_len = sizeof (oop->oo_name);
1851 	open_args->owner.owner_val =
1852 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1853 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1854 	    open_args->owner.owner_len);
1855 	open_args->share_access = 0;
1856 	open_args->share_deny = 0;
1857 
1858 	mutex_enter(&osp->os_sync_lock);
1859 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1860 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1861 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1862 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1863 	    osp->os_share_acc_write, osp->os_open_ref_count,
1864 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1865 
1866 	if (osp->os_share_acc_read || osp->os_mmap_read)
1867 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1868 	if (osp->os_share_acc_write || osp->os_mmap_write)
1869 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1870 	if (osp->os_share_deny_read)
1871 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1872 	if (osp->os_share_deny_write)
1873 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1874 	mutex_exit(&osp->os_sync_lock);
1875 
1876 	seqid = nfs4_get_open_seqid(oop) + 1;
1877 	open_args->seqid = seqid;
1878 
1879 	/* Construct the getfh part of the compound */
1880 	argop[2].argop = OP_GETFH;
1881 
1882 	/* Construct the getattr part of the compound */
1883 	argop[3].argop = OP_GETATTR;
1884 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1885 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1886 
1887 	t = gethrtime();
1888 
1889 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1890 
1891 	if (ep->error) {
1892 		if (!is_recov && !frc_use_claim_previous &&
1893 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1894 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1895 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1896 			    cred_otw, vp, NULL, open_args);
1897 			abort = nfs4_start_recovery(ep,
1898 			    VTOMI4(vp), vp, NULL, NULL,
1899 			    lost_rqst.lr_op == OP_OPEN ?
1900 			    &lost_rqst : NULL, OP_OPEN, NULL);
1901 			nfs4args_copen_free(open_args);
1902 			goto bailout;
1903 		}
1904 
1905 		nfs4args_copen_free(open_args);
1906 
1907 		if (ep->error == EACCES && cred_otw != cr) {
1908 			crfree(cred_otw);
1909 			cred_otw = cr;
1910 			crhold(cred_otw);
1911 			nfs4_end_open_seqid_sync(oop);
1912 			open_owner_rele(oop);
1913 			oop = NULL;
1914 			goto top;
1915 		}
1916 		if (ep->error == ETIMEDOUT)
1917 			goto bailout;
1918 		failed_msg = "Couldn't reopen: rpc error";
1919 		goto kill_file;
1920 	}
1921 
1922 	if (nfs4_need_to_bump_seqid(&res))
1923 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1924 
1925 	switch (res.status) {
1926 	case NFS4_OK:
1927 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1928 			mutex_enter(&rp->r_statelock);
1929 			rp->r_delay_interval = 0;
1930 			mutex_exit(&rp->r_statelock);
1931 		}
1932 		break;
1933 	case NFS4ERR_BAD_SEQID:
1934 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1935 		    args.ctag, open_args->seqid);
1936 
1937 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1938 		    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1939 		    NULL, OP_OPEN, bsep);
1940 
1941 		nfs4args_copen_free(open_args);
1942 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1943 		nfs4_end_open_seqid_sync(oop);
1944 		open_owner_rele(oop);
1945 		oop = NULL;
1946 		kmem_free(bsep, sizeof (*bsep));
1947 
1948 		goto kill_file;
1949 	case NFS4ERR_NO_GRACE:
1950 		nfs4args_copen_free(open_args);
1951 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1952 		nfs4_end_open_seqid_sync(oop);
1953 		open_owner_rele(oop);
1954 		oop = NULL;
1955 		if (claim == CLAIM_PREVIOUS) {
1956 			/*
1957 			 * Retry as a plain open. We don't need to worry about
1958 			 * checking the changeinfo: it is acceptable for a
1959 			 * client to re-open a file and continue processing
1960 			 * (in the absence of locks).
1961 			 */
1962 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1963 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1964 			    "will retry as CLAIM_NULL"));
1965 			claim = CLAIM_NULL;
1966 			nfs4_mi_kstat_inc_no_grace(mi);
1967 			goto top;
1968 		}
1969 		failed_msg =
1970 		    "Couldn't reopen: tried reclaim outside grace period. ";
1971 		goto kill_file;
1972 	case NFS4ERR_GRACE:
1973 		nfs4_set_grace_wait(mi);
1974 		nfs4args_copen_free(open_args);
1975 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1976 		nfs4_end_open_seqid_sync(oop);
1977 		open_owner_rele(oop);
1978 		oop = NULL;
1979 		ep->error = nfs4_wait_for_grace(mi, &recov);
1980 		if (ep->error != 0)
1981 			goto bailout;
1982 		goto top;
1983 	case NFS4ERR_DELAY:
1984 		nfs4_set_delay_wait(vp);
1985 		nfs4args_copen_free(open_args);
1986 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1987 		nfs4_end_open_seqid_sync(oop);
1988 		open_owner_rele(oop);
1989 		oop = NULL;
1990 		ep->error = nfs4_wait_for_delay(vp, &recov);
1991 		nfs4_mi_kstat_inc_delay(mi);
1992 		if (ep->error != 0)
1993 			goto bailout;
1994 		goto top;
1995 	case NFS4ERR_FHEXPIRED:
1996 		/* recover filehandle and retry */
1997 		abort = nfs4_start_recovery(ep,
1998 		    mi, vp, NULL, NULL, NULL, OP_OPEN, NULL);
1999 		nfs4args_copen_free(open_args);
2000 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2001 		nfs4_end_open_seqid_sync(oop);
2002 		open_owner_rele(oop);
2003 		oop = NULL;
2004 		if (abort == FALSE)
2005 			goto top;
2006 		failed_msg = "Couldn't reopen: recovery aborted";
2007 		goto kill_file;
2008 	case NFS4ERR_RESOURCE:
2009 	case NFS4ERR_STALE_CLIENTID:
2010 	case NFS4ERR_WRONGSEC:
2011 	case NFS4ERR_EXPIRED:
2012 		/*
2013 		 * Do not mark the file dead and let the calling
2014 		 * function initiate recovery.
2015 		 */
2016 		nfs4args_copen_free(open_args);
2017 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2018 		nfs4_end_open_seqid_sync(oop);
2019 		open_owner_rele(oop);
2020 		oop = NULL;
2021 		goto bailout;
2022 	case NFS4ERR_ACCESS:
2023 		if (cred_otw != cr) {
2024 			crfree(cred_otw);
2025 			cred_otw = cr;
2026 			crhold(cred_otw);
2027 			nfs4args_copen_free(open_args);
2028 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2029 			nfs4_end_open_seqid_sync(oop);
2030 			open_owner_rele(oop);
2031 			oop = NULL;
2032 			goto top;
2033 		}
2034 		/* fall through */
2035 	default:
2036 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2037 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2038 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2039 		    rnode4info(VTOR4(vp))));
2040 		failed_msg = "Couldn't reopen: NFSv4 error";
2041 		nfs4args_copen_free(open_args);
2042 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2043 		goto kill_file;
2044 	}
2045 
2046 	resop = &res.array[1];  /* open res */
2047 	op_res = &resop->nfs_resop4_u.opopen;
2048 
2049 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2050 
2051 	/*
2052 	 * Check if the path we reopened really is the same
2053 	 * file. We could end up in a situation where the file
2054 	 * was removed and a new file created with the same name.
2055 	 */
2056 	resop = &res.array[2];
2057 	gf_res = &resop->nfs_resop4_u.opgetfh;
2058 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2059 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2060 	if (fh_different) {
2061 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2062 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2063 			/* Oops, we don't have the same file */
2064 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2065 				failed_msg = "Couldn't reopen: Persistent "
2066 				    "file handle changed";
2067 			else
2068 				failed_msg = "Couldn't reopen: Volatile "
2069 				    "(no expire on open) file handle changed";
2070 
2071 			nfs4args_copen_free(open_args);
2072 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2073 			nfs_rw_exit(&mi->mi_fh_lock);
2074 			goto kill_file;
2075 
2076 		} else {
2077 			/*
2078 			 * We have volatile file handles that don't compare.
2079 			 * If the fids are the same then we assume that the
2080 			 * file handle expired but the rnode still refers to
2081 			 * the same file object.
2082 			 *
2083 			 * First check that we have fids or not.
2084 			 * If we don't we have a dumb server so we will
2085 			 * just assume every thing is ok for now.
2086 			 */
2087 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2088 			    rp->r_attr.va_mask & AT_NODEID &&
2089 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2090 				/*
2091 				 * We have fids, but they don't
2092 				 * compare. So kill the file.
2093 				 */
2094 				failed_msg =
2095 				    "Couldn't reopen: file handle changed"
2096 				    " due to mismatched fids";
2097 				nfs4args_copen_free(open_args);
2098 				(void) xdr_free(xdr_COMPOUND4res_clnt,
2099 				    (caddr_t)&res);
2100 				nfs_rw_exit(&mi->mi_fh_lock);
2101 				goto kill_file;
2102 			} else {
2103 				/*
2104 				 * We have volatile file handles that refers
2105 				 * to the same file (at least they have the
2106 				 * same fid) or we don't have fids so we
2107 				 * can't tell. :(. We'll be a kind and accepting
2108 				 * client so we'll update the rnode's file
2109 				 * handle with the otw handle.
2110 				 *
2111 				 * We need to drop mi->mi_fh_lock since
2112 				 * sh4_update acquires it. Since there is
2113 				 * only one recovery thread there is no
2114 				 * race.
2115 				 */
2116 				nfs_rw_exit(&mi->mi_fh_lock);
2117 				sfh4_update(rp->r_fh, &gf_res->object);
2118 			}
2119 		}
2120 	} else {
2121 		nfs_rw_exit(&mi->mi_fh_lock);
2122 	}
2123 
2124 	ASSERT(nfs4_consistent_type(vp));
2125 
2126 	/*
2127 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2128 	 * over.  Presumably if there is a persistent error it will show up
2129 	 * when we resend the OPEN.
2130 	 */
2131 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2132 		bool_t retry_open = FALSE;
2133 
2134 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2135 		    cred_otw, is_recov, &retry_open,
2136 		    oop, FALSE, ep, NULL);
2137 		if (ep->error || ep->stat) {
2138 			nfs4args_copen_free(open_args);
2139 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2140 			nfs4_end_open_seqid_sync(oop);
2141 			open_owner_rele(oop);
2142 			oop = NULL;
2143 			goto top;
2144 		}
2145 	}
2146 
2147 	mutex_enter(&osp->os_sync_lock);
2148 	osp->open_stateid = op_res->stateid;
2149 	osp->os_delegation = 0;
2150 	/*
2151 	 * Need to reset this bitfield for the possible case where we were
2152 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2153 	 * we could retry the CLOSE, OPENed the file again.
2154 	 */
2155 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2156 	osp->os_final_close = 0;
2157 	osp->os_force_close = 0;
2158 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2159 		osp->os_dc_openacc = open_args->share_access;
2160 	mutex_exit(&osp->os_sync_lock);
2161 
2162 	nfs4_end_open_seqid_sync(oop);
2163 
2164 	/* accept delegation, if any */
2165 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2166 
2167 	nfs4args_copen_free(open_args);
2168 
2169 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2170 
2171 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2172 
2173 	ASSERT(nfs4_consistent_type(vp));
2174 
2175 	open_owner_rele(oop);
2176 	crfree(cr);
2177 	crfree(cred_otw);
2178 	return;
2179 
2180 kill_file:
2181 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2182 failed_reopen:
2183 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2184 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2185 	    (void *)osp, (void *)cr, rnode4info(rp)));
2186 	mutex_enter(&osp->os_sync_lock);
2187 	osp->os_failed_reopen = 1;
2188 	mutex_exit(&osp->os_sync_lock);
2189 bailout:
2190 	if (oop != NULL) {
2191 		nfs4_end_open_seqid_sync(oop);
2192 		open_owner_rele(oop);
2193 	}
2194 	if (cr != NULL)
2195 		crfree(cr);
2196 	if (cred_otw != NULL)
2197 		crfree(cred_otw);
2198 }
2199 
2200 /* for . and .. OPENs */
2201 /* ARGSUSED */
2202 static int
2203 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2204 {
2205 	rnode4_t *rp;
2206 	nfs4_ga_res_t gar;
2207 
2208 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2209 
2210 	/*
2211 	 * If close-to-open consistency checking is turned off or
2212 	 * if there is no cached data, we can avoid
2213 	 * the over the wire getattr.  Otherwise, force a
2214 	 * call to the server to get fresh attributes and to
2215 	 * check caches. This is required for close-to-open
2216 	 * consistency.
2217 	 */
2218 	rp = VTOR4(*vpp);
2219 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2220 	    (rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2221 		return (0);
2222 
2223 	gar.n4g_va.va_mask = AT_ALL;
2224 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2225 }
2226 
2227 /*
2228  * CLOSE a file
2229  */
2230 /* ARGSUSED */
2231 static int
2232 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
2233 	caller_context_t *ct)
2234 {
2235 	rnode4_t	*rp;
2236 	int		 error = 0;
2237 	int		 r_error = 0;
2238 	int		 n4error = 0;
2239 	nfs4_error_t	 e = { 0, NFS4_OK, RPC_SUCCESS };
2240 
2241 	/*
2242 	 * Remove client state for this (lockowner, file) pair.
2243 	 * Issue otw v4 call to have the server do the same.
2244 	 */
2245 
2246 	rp = VTOR4(vp);
2247 
2248 	/*
2249 	 * zone_enter(2) prevents processes from changing zones with NFS files
2250 	 * open; if we happen to get here from the wrong zone we can't do
2251 	 * anything over the wire.
2252 	 */
2253 	if (VTOMI4(vp)->mi_zone != nfs_zone()) {
2254 		/*
2255 		 * We could attempt to clean up locks, except we're sure
2256 		 * that the current process didn't acquire any locks on
2257 		 * the file: any attempt to lock a file belong to another zone
2258 		 * will fail, and one can't lock an NFS file and then change
2259 		 * zones, as that fails too.
2260 		 *
2261 		 * Returning an error here is the sane thing to do.  A
2262 		 * subsequent call to VN_RELE() which translates to a
2263 		 * nfs4_inactive() will clean up state: if the zone of the
2264 		 * vnode's origin is still alive and kicking, the inactive
2265 		 * thread will handle the request (from the correct zone), and
2266 		 * everything (minus the OTW close call) should be OK.  If the
2267 		 * zone is going away nfs4_async_inactive() will throw away
2268 		 * delegations, open streams and cached pages inline.
2269 		 */
2270 		return (EIO);
2271 	}
2272 
2273 	/*
2274 	 * If we are using local locking for this filesystem, then
2275 	 * release all of the SYSV style record locks.  Otherwise,
2276 	 * we are doing network locking and we need to release all
2277 	 * of the network locks.  All of the locks held by this
2278 	 * process on this file are released no matter what the
2279 	 * incoming reference count is.
2280 	 */
2281 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK) {
2282 		cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
2283 		cleanshares(vp, ttoproc(curthread)->p_pid);
2284 	} else
2285 		e.error = nfs4_lockrelease(vp, flag, offset, cr);
2286 
2287 	if (e.error) {
2288 		struct lm_sysid *lmsid;
2289 		lmsid = nfs4_find_sysid(VTOMI4(vp));
2290 		if (lmsid == NULL) {
2291 			DTRACE_PROBE2(unknown__sysid, int, e.error,
2292 			    vnode_t *, vp);
2293 		} else {
2294 			cleanlocks(vp, ttoproc(curthread)->p_pid,
2295 			    (lm_sysidt(lmsid) | LM_SYSID_CLIENT));
2296 		}
2297 		return (e.error);
2298 	}
2299 
2300 	if (count > 1)
2301 		return (0);
2302 
2303 	/*
2304 	 * If the file has been `unlinked', then purge the
2305 	 * DNLC so that this vnode will get reycled quicker
2306 	 * and the .nfs* file on the server will get removed.
2307 	 */
2308 	if (rp->r_unldvp != NULL)
2309 		dnlc_purge_vp(vp);
2310 
2311 	/*
2312 	 * If the file was open for write and there are pages,
2313 	 * do a synchronous flush and commit of all of the
2314 	 * dirty and uncommitted pages.
2315 	 */
2316 	ASSERT(!e.error);
2317 	if ((flag & FWRITE) && nfs4_has_pages(vp))
2318 		error = nfs4_putpage_commit(vp, 0, 0, cr);
2319 
2320 	mutex_enter(&rp->r_statelock);
2321 	r_error = rp->r_error;
2322 	rp->r_error = 0;
2323 	mutex_exit(&rp->r_statelock);
2324 
2325 	/*
2326 	 * If this file type is one for which no explicit 'open' was
2327 	 * done, then bail now (ie. no need for protocol 'close'). If
2328 	 * there was an error w/the vm subsystem, return _that_ error,
2329 	 * otherwise, return any errors that may've been reported via
2330 	 * the rnode.
2331 	 */
2332 	if (vp->v_type != VREG)
2333 		return (error ? error : r_error);
2334 
2335 	/*
2336 	 * The sync putpage commit may have failed above, but since
2337 	 * we're working w/a regular file, we need to do the protocol
2338 	 * 'close' (nfs4close_one will figure out if an otw close is
2339 	 * needed or not). Report any errors _after_ doing the protocol
2340 	 * 'close'.
2341 	 */
2342 	nfs4close_one(vp, NULL, cr, flag, NULL, &e, CLOSE_NORM, 0, 0, 0);
2343 	n4error = e.error ? e.error : geterrno4(e.stat);
2344 
2345 	/*
2346 	 * Error reporting prio (Hi -> Lo)
2347 	 *
2348 	 *   i) nfs4_putpage_commit (error)
2349 	 *  ii) rnode's (r_error)
2350 	 * iii) nfs4close_one (n4error)
2351 	 */
2352 	return (error ? error : (r_error ? r_error : n4error));
2353 }
2354 
2355 /*
2356  * Initialize *lost_rqstp.
2357  */
2358 
2359 static void
2360 nfs4close_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
2361     nfs4_open_owner_t *oop, nfs4_open_stream_t *osp, cred_t *cr,
2362     vnode_t *vp)
2363 {
2364 	if (error != ETIMEDOUT && error != EINTR &&
2365 	    !NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
2366 		lost_rqstp->lr_op = 0;
2367 		return;
2368 	}
2369 
2370 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
2371 	    "nfs4close_save_lost_rqst: error %d", error));
2372 
2373 	lost_rqstp->lr_op = OP_CLOSE;
2374 	/*
2375 	 * The vp is held and rele'd via the recovery code.
2376 	 * See nfs4_save_lost_rqst.
2377 	 */
2378 	lost_rqstp->lr_vp = vp;
2379 	lost_rqstp->lr_dvp = NULL;
2380 	lost_rqstp->lr_oop = oop;
2381 	lost_rqstp->lr_osp = osp;
2382 	ASSERT(osp != NULL);
2383 	ASSERT(mutex_owned(&osp->os_sync_lock));
2384 	osp->os_pending_close = 1;
2385 	lost_rqstp->lr_lop = NULL;
2386 	lost_rqstp->lr_cr = cr;
2387 	lost_rqstp->lr_flk = NULL;
2388 	lost_rqstp->lr_putfirst = FALSE;
2389 }
2390 
2391 /*
2392  * Assumes you already have the open seqid sync grabbed as well as the
2393  * 'os_sync_lock'.  Note: this will release the open seqid sync and
2394  * 'os_sync_lock' if client recovery starts.  Calling functions have to
2395  * be prepared to handle this.
2396  *
2397  * 'recov' is returned as 1 if the CLOSE operation detected client recovery
2398  * was needed and was started, and that the calling function should retry
2399  * this function; otherwise it is returned as 0.
2400  *
2401  * Errors are returned via the nfs4_error_t parameter.
2402  */
2403 static void
2404 nfs4close_otw(rnode4_t *rp, cred_t *cred_otw, nfs4_open_owner_t *oop,
2405     nfs4_open_stream_t *osp, int *recov, int *did_start_seqid_syncp,
2406     nfs4_close_type_t close_type, nfs4_error_t *ep, int *have_sync_lockp)
2407 {
2408 	COMPOUND4args_clnt args;
2409 	COMPOUND4res_clnt res;
2410 	CLOSE4args *close_args;
2411 	nfs_resop4 *resop;
2412 	nfs_argop4 argop[3];
2413 	int doqueue = 1;
2414 	mntinfo4_t *mi;
2415 	seqid4 seqid;
2416 	vnode_t *vp;
2417 	bool_t needrecov = FALSE;
2418 	nfs4_lost_rqst_t lost_rqst;
2419 	hrtime_t t;
2420 
2421 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
2422 
2423 	ASSERT(MUTEX_HELD(&osp->os_sync_lock));
2424 
2425 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw"));
2426 
2427 	/* Only set this to 1 if recovery is started */
2428 	*recov = 0;
2429 
2430 	/* do the OTW call to close the file */
2431 
2432 	if (close_type == CLOSE_RESEND)
2433 		args.ctag = TAG_CLOSE_LOST;
2434 	else if (close_type == CLOSE_AFTER_RESEND)
2435 		args.ctag = TAG_CLOSE_UNDO;
2436 	else
2437 		args.ctag = TAG_CLOSE;
2438 
2439 	args.array_len = 3;
2440 	args.array = argop;
2441 
2442 	vp = RTOV4(rp);
2443 
2444 	mi = VTOMI4(vp);
2445 
2446 	/* putfh target fh */
2447 	argop[0].argop = OP_CPUTFH;
2448 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
2449 
2450 	argop[1].argop = OP_GETATTR;
2451 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
2452 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
2453 
2454 	argop[2].argop = OP_CLOSE;
2455 	close_args = &argop[2].nfs_argop4_u.opclose;
2456 
2457 	seqid = nfs4_get_open_seqid(oop) + 1;
2458 
2459 	close_args->seqid = seqid;
2460 	close_args->open_stateid = osp->open_stateid;
2461 
2462 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
2463 	    "nfs4close_otw: %s call, rp %s", needrecov ? "recov" : "first",
2464 	    rnode4info(rp)));
2465 
2466 	t = gethrtime();
2467 
2468 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
2469 
2470 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
2471 		nfs4_set_open_seqid(seqid, oop, args.ctag);
2472 	}
2473 
2474 	needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
2475 	if (ep->error && !needrecov) {
2476 		/*
2477 		 * if there was an error and no recovery is to be done
2478 		 * then then set up the file to flush its cache if
2479 		 * needed for the next caller.
2480 		 */
2481 		mutex_enter(&rp->r_statelock);
2482 		PURGE_ATTRCACHE4_LOCKED(rp);
2483 		rp->r_flags &= ~R4WRITEMODIFIED;
2484 		mutex_exit(&rp->r_statelock);
2485 		return;
2486 	}
2487 
2488 	if (needrecov) {
2489 		bool_t abort;
2490 		nfs4_bseqid_entry_t *bsep = NULL;
2491 
2492 		if (close_type != CLOSE_RESEND)
2493 			nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
2494 			    osp, cred_otw, vp);
2495 
2496 		if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
2497 			bsep = nfs4_create_bseqid_entry(oop, NULL, vp,
2498 			    0, args.ctag, close_args->seqid);
2499 
2500 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
2501 		    "nfs4close_otw: initiating recovery. error %d "
2502 		    "res.status %d", ep->error, res.status));
2503 
2504 		/*
2505 		 * Drop the 'os_sync_lock' here so we don't hit
2506 		 * a potential recursive mutex_enter via an
2507 		 * 'open_stream_hold()'.
2508 		 */
2509 		mutex_exit(&osp->os_sync_lock);
2510 		*have_sync_lockp = 0;
2511 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
2512 		    (close_type != CLOSE_RESEND &&
2513 		    lost_rqst.lr_op == OP_CLOSE) ? &lost_rqst : NULL,
2514 		    OP_CLOSE, bsep);
2515 
2516 		/* drop open seq sync, and let the calling function regrab it */
2517 		nfs4_end_open_seqid_sync(oop);
2518 		*did_start_seqid_syncp = 0;
2519 
2520 		if (bsep)
2521 			kmem_free(bsep, sizeof (*bsep));
2522 		/*
2523 		 * For signals, the caller wants to quit, so don't say to
2524 		 * retry.  For forced unmount, if it's a user thread, it
2525 		 * wants to quit.  If it's a recovery thread, the retry
2526 		 * will happen higher-up on the call stack.  Either way,
2527 		 * don't say to retry.
2528 		 */
2529 		if (abort == FALSE && ep->error != EINTR &&
2530 		    !NFS4_FRC_UNMT_ERR(ep->error, mi->mi_vfsp) &&
2531 		    close_type != CLOSE_RESEND &&
2532 		    close_type != CLOSE_AFTER_RESEND)
2533 			*recov = 1;
2534 		else
2535 			*recov = 0;
2536 
2537 		if (!ep->error)
2538 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2539 		return;
2540 	}
2541 
2542 	if (res.status) {
2543 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2544 		return;
2545 	}
2546 
2547 	mutex_enter(&rp->r_statev4_lock);
2548 	rp->created_v4 = 0;
2549 	mutex_exit(&rp->r_statev4_lock);
2550 
2551 	resop = &res.array[2];
2552 	osp->open_stateid = resop->nfs_resop4_u.opclose.open_stateid;
2553 	osp->os_valid = 0;
2554 
2555 	/*
2556 	 * This removes the reference obtained at OPEN; ie, when the
2557 	 * open stream structure was created.
2558 	 *
2559 	 * We don't have to worry about calling 'open_stream_rele'
2560 	 * since we our currently holding a reference to the open
2561 	 * stream which means the count cannot go to 0 with this
2562 	 * decrement.
2563 	 */
2564 	ASSERT(osp->os_ref_count >= 2);
2565 	osp->os_ref_count--;
2566 
2567 	if (!ep->error)
2568 		nfs4_attr_cache(vp,
2569 		    &res.array[1].nfs_resop4_u.opgetattr.ga_res,
2570 		    t, cred_otw, TRUE, NULL);
2571 
2572 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw:"
2573 	    " returning %d", ep->error));
2574 
2575 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2576 }
2577 
2578 /* ARGSUSED */
2579 static int
2580 nfs4_read(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2581     caller_context_t *ct)
2582 {
2583 	rnode4_t *rp;
2584 	u_offset_t off;
2585 	offset_t diff;
2586 	uint_t on;
2587 	uint_t n;
2588 	caddr_t base;
2589 	uint_t flags;
2590 	int error;
2591 	mntinfo4_t *mi;
2592 
2593 	rp = VTOR4(vp);
2594 
2595 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2596 
2597 	if (IS_SHADOW(vp, rp))
2598 		vp = RTOV4(rp);
2599 
2600 	if (vp->v_type != VREG)
2601 		return (EISDIR);
2602 
2603 	mi = VTOMI4(vp);
2604 
2605 	if (nfs_zone() != mi->mi_zone)
2606 		return (EIO);
2607 
2608 	if (uiop->uio_resid == 0)
2609 		return (0);
2610 
2611 	if (uiop->uio_loffset < 0 || uiop->uio_loffset + uiop->uio_resid < 0)
2612 		return (EINVAL);
2613 
2614 	mutex_enter(&rp->r_statelock);
2615 	if (rp->r_flags & R4RECOVERRP)
2616 		error = (rp->r_error ? rp->r_error : EIO);
2617 	else
2618 		error = 0;
2619 	mutex_exit(&rp->r_statelock);
2620 	if (error)
2621 		return (error);
2622 
2623 	/*
2624 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2625 	 * using client-side direct I/O and the file is not mmap'd and
2626 	 * there are no cached pages.
2627 	 */
2628 	if ((vp->v_flag & VNOCACHE) ||
2629 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2630 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2631 		size_t resid = 0;
2632 
2633 		return (nfs4read(vp, NULL, uiop->uio_loffset,
2634 		    uiop->uio_resid, &resid, cr, FALSE, uiop));
2635 	}
2636 
2637 	error = 0;
2638 
2639 	do {
2640 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2641 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2642 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2643 
2644 		if (error = nfs4_validate_caches(vp, cr))
2645 			break;
2646 
2647 		mutex_enter(&rp->r_statelock);
2648 		while (rp->r_flags & R4INCACHEPURGE) {
2649 			if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2650 				mutex_exit(&rp->r_statelock);
2651 				return (EINTR);
2652 			}
2653 		}
2654 		diff = rp->r_size - uiop->uio_loffset;
2655 		mutex_exit(&rp->r_statelock);
2656 		if (diff <= 0)
2657 			break;
2658 		if (diff < n)
2659 			n = (uint_t)diff;
2660 
2661 		if (vpm_enable) {
2662 			/*
2663 			 * Copy data.
2664 			 */
2665 			error = vpm_data_copy(vp, off + on, n, uiop,
2666 			    1, NULL, 0, S_READ);
2667 		} else {
2668 			base = segmap_getmapflt(segkmap, vp, off + on, n, 1,
2669 			    S_READ);
2670 
2671 			error = uiomove(base + on, n, UIO_READ, uiop);
2672 		}
2673 
2674 		if (!error) {
2675 			/*
2676 			 * If read a whole block or read to eof,
2677 			 * won't need this buffer again soon.
2678 			 */
2679 			mutex_enter(&rp->r_statelock);
2680 			if (n + on == MAXBSIZE ||
2681 			    uiop->uio_loffset == rp->r_size)
2682 				flags = SM_DONTNEED;
2683 			else
2684 				flags = 0;
2685 			mutex_exit(&rp->r_statelock);
2686 			if (vpm_enable) {
2687 				error = vpm_sync_pages(vp, off, n, flags);
2688 			} else {
2689 				error = segmap_release(segkmap, base, flags);
2690 			}
2691 		} else {
2692 			if (vpm_enable) {
2693 				(void) vpm_sync_pages(vp, off, n, 0);
2694 			} else {
2695 				(void) segmap_release(segkmap, base, 0);
2696 			}
2697 		}
2698 	} while (!error && uiop->uio_resid > 0);
2699 
2700 	return (error);
2701 }
2702 
2703 /* ARGSUSED */
2704 static int
2705 nfs4_write(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2706     caller_context_t *ct)
2707 {
2708 	rlim64_t limit = uiop->uio_llimit;
2709 	rnode4_t *rp;
2710 	u_offset_t off;
2711 	caddr_t base;
2712 	uint_t flags;
2713 	int remainder;
2714 	size_t n;
2715 	int on;
2716 	int error;
2717 	int resid;
2718 	u_offset_t offset;
2719 	mntinfo4_t *mi;
2720 	uint_t bsize;
2721 
2722 	rp = VTOR4(vp);
2723 
2724 	if (IS_SHADOW(vp, rp))
2725 		vp = RTOV4(rp);
2726 
2727 	if (vp->v_type != VREG)
2728 		return (EISDIR);
2729 
2730 	mi = VTOMI4(vp);
2731 
2732 	if (nfs_zone() != mi->mi_zone)
2733 		return (EIO);
2734 
2735 	if (uiop->uio_resid == 0)
2736 		return (0);
2737 
2738 	mutex_enter(&rp->r_statelock);
2739 	if (rp->r_flags & R4RECOVERRP)
2740 		error = (rp->r_error ? rp->r_error : EIO);
2741 	else
2742 		error = 0;
2743 	mutex_exit(&rp->r_statelock);
2744 	if (error)
2745 		return (error);
2746 
2747 	if (ioflag & FAPPEND) {
2748 		struct vattr va;
2749 
2750 		/*
2751 		 * Must serialize if appending.
2752 		 */
2753 		if (nfs_rw_lock_held(&rp->r_rwlock, RW_READER)) {
2754 			nfs_rw_exit(&rp->r_rwlock);
2755 			if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER,
2756 			    INTR4(vp)))
2757 				return (EINTR);
2758 		}
2759 
2760 		va.va_mask = AT_SIZE;
2761 		error = nfs4getattr(vp, &va, cr);
2762 		if (error)
2763 			return (error);
2764 		uiop->uio_loffset = va.va_size;
2765 	}
2766 
2767 	offset = uiop->uio_loffset + uiop->uio_resid;
2768 
2769 	if (uiop->uio_loffset < (offset_t)0 || offset < 0)
2770 		return (EINVAL);
2771 
2772 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
2773 		limit = MAXOFFSET_T;
2774 
2775 	/*
2776 	 * Check to make sure that the process will not exceed
2777 	 * its limit on file size.  It is okay to write up to
2778 	 * the limit, but not beyond.  Thus, the write which
2779 	 * reaches the limit will be short and the next write
2780 	 * will return an error.
2781 	 */
2782 	remainder = 0;
2783 	if (offset > uiop->uio_llimit) {
2784 		remainder = offset - uiop->uio_llimit;
2785 		uiop->uio_resid = uiop->uio_llimit - uiop->uio_loffset;
2786 		if (uiop->uio_resid <= 0) {
2787 			proc_t *p = ttoproc(curthread);
2788 
2789 			uiop->uio_resid += remainder;
2790 			mutex_enter(&p->p_lock);
2791 			(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE],
2792 			    p->p_rctls, p, RCA_UNSAFE_SIGINFO);
2793 			mutex_exit(&p->p_lock);
2794 			return (EFBIG);
2795 		}
2796 	}
2797 
2798 	/* update the change attribute, if we have a write delegation */
2799 
2800 	mutex_enter(&rp->r_statev4_lock);
2801 	if (rp->r_deleg_type == OPEN_DELEGATE_WRITE)
2802 		rp->r_deleg_change++;
2803 
2804 	mutex_exit(&rp->r_statev4_lock);
2805 
2806 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
2807 		return (EINTR);
2808 
2809 	/*
2810 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2811 	 * using client-side direct I/O and the file is not mmap'd and
2812 	 * there are no cached pages.
2813 	 */
2814 	if ((vp->v_flag & VNOCACHE) ||
2815 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2816 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2817 		size_t bufsize;
2818 		int count;
2819 		u_offset_t org_offset;
2820 		stable_how4 stab_comm;
2821 nfs4_fwrite:
2822 		if (rp->r_flags & R4STALE) {
2823 			resid = uiop->uio_resid;
2824 			offset = uiop->uio_loffset;
2825 			error = rp->r_error;
2826 			/*
2827 			 * A close may have cleared r_error, if so,
2828 			 * propagate ESTALE error return properly
2829 			 */
2830 			if (error == 0)
2831 				error = ESTALE;
2832 			goto bottom;
2833 		}
2834 
2835 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2836 		base = kmem_alloc(bufsize, KM_SLEEP);
2837 		do {
2838 			if (ioflag & FDSYNC)
2839 				stab_comm = DATA_SYNC4;
2840 			else
2841 				stab_comm = FILE_SYNC4;
2842 			resid = uiop->uio_resid;
2843 			offset = uiop->uio_loffset;
2844 			count = MIN(uiop->uio_resid, bufsize);
2845 			org_offset = uiop->uio_loffset;
2846 			error = uiomove(base, count, UIO_WRITE, uiop);
2847 			if (!error) {
2848 				error = nfs4write(vp, base, org_offset,
2849 				    count, cr, &stab_comm);
2850 				if (!error) {
2851 					mutex_enter(&rp->r_statelock);
2852 					if (rp->r_size < uiop->uio_loffset)
2853 						rp->r_size = uiop->uio_loffset;
2854 					mutex_exit(&rp->r_statelock);
2855 				}
2856 			}
2857 		} while (!error && uiop->uio_resid > 0);
2858 		kmem_free(base, bufsize);
2859 		goto bottom;
2860 	}
2861 
2862 	bsize = vp->v_vfsp->vfs_bsize;
2863 
2864 	do {
2865 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2866 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2867 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2868 
2869 		resid = uiop->uio_resid;
2870 		offset = uiop->uio_loffset;
2871 
2872 		if (rp->r_flags & R4STALE) {
2873 			error = rp->r_error;
2874 			/*
2875 			 * A close may have cleared r_error, if so,
2876 			 * propagate ESTALE error return properly
2877 			 */
2878 			if (error == 0)
2879 				error = ESTALE;
2880 			break;
2881 		}
2882 
2883 		/*
2884 		 * Don't create dirty pages faster than they
2885 		 * can be cleaned so that the system doesn't
2886 		 * get imbalanced.  If the async queue is
2887 		 * maxed out, then wait for it to drain before
2888 		 * creating more dirty pages.  Also, wait for
2889 		 * any threads doing pagewalks in the vop_getattr
2890 		 * entry points so that they don't block for
2891 		 * long periods.
2892 		 */
2893 		mutex_enter(&rp->r_statelock);
2894 		while ((mi->mi_max_threads != 0 &&
2895 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2896 		    rp->r_gcount > 0) {
2897 			if (INTR4(vp)) {
2898 				klwp_t *lwp = ttolwp(curthread);
2899 
2900 				if (lwp != NULL)
2901 					lwp->lwp_nostop++;
2902 				if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2903 					mutex_exit(&rp->r_statelock);
2904 					if (lwp != NULL)
2905 						lwp->lwp_nostop--;
2906 					error = EINTR;
2907 					goto bottom;
2908 				}
2909 				if (lwp != NULL)
2910 					lwp->lwp_nostop--;
2911 			} else
2912 				cv_wait(&rp->r_cv, &rp->r_statelock);
2913 		}
2914 		mutex_exit(&rp->r_statelock);
2915 
2916 		/*
2917 		 * Touch the page and fault it in if it is not in core
2918 		 * before segmap_getmapflt or vpm_data_copy can lock it.
2919 		 * This is to avoid the deadlock if the buffer is mapped
2920 		 * to the same file through mmap which we want to write.
2921 		 */
2922 		uio_prefaultpages((long)n, uiop);
2923 
2924 		if (vpm_enable) {
2925 			/*
2926 			 * It will use kpm mappings, so no need to
2927 			 * pass an address.
2928 			 */
2929 			error = writerp4(rp, NULL, n, uiop, 0);
2930 		} else  {
2931 			if (segmap_kpm) {
2932 				int pon = uiop->uio_loffset & PAGEOFFSET;
2933 				size_t pn = MIN(PAGESIZE - pon,
2934 				    uiop->uio_resid);
2935 				int pagecreate;
2936 
2937 				mutex_enter(&rp->r_statelock);
2938 				pagecreate = (pon == 0) && (pn == PAGESIZE ||
2939 				    uiop->uio_loffset + pn >= rp->r_size);
2940 				mutex_exit(&rp->r_statelock);
2941 
2942 				base = segmap_getmapflt(segkmap, vp, off + on,
2943 				    pn, !pagecreate, S_WRITE);
2944 
2945 				error = writerp4(rp, base + pon, n, uiop,
2946 				    pagecreate);
2947 
2948 			} else {
2949 				base = segmap_getmapflt(segkmap, vp, off + on,
2950 				    n, 0, S_READ);
2951 				error = writerp4(rp, base + on, n, uiop, 0);
2952 			}
2953 		}
2954 
2955 		if (!error) {
2956 			if (mi->mi_flags & MI4_NOAC)
2957 				flags = SM_WRITE;
2958 			else if ((uiop->uio_loffset % bsize) == 0 ||
2959 			    IS_SWAPVP(vp)) {
2960 				/*
2961 				 * Have written a whole block.
2962 				 * Start an asynchronous write
2963 				 * and mark the buffer to
2964 				 * indicate that it won't be
2965 				 * needed again soon.
2966 				 */
2967 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
2968 			} else
2969 				flags = 0;
2970 			if ((ioflag & (FSYNC|FDSYNC)) ||
2971 			    (rp->r_flags & R4OUTOFSPACE)) {
2972 				flags &= ~SM_ASYNC;
2973 				flags |= SM_WRITE;
2974 			}
2975 			if (vpm_enable) {
2976 				error = vpm_sync_pages(vp, off, n, flags);
2977 			} else {
2978 				error = segmap_release(segkmap, base, flags);
2979 			}
2980 		} else {
2981 			if (vpm_enable) {
2982 				(void) vpm_sync_pages(vp, off, n, 0);
2983 			} else {
2984 				(void) segmap_release(segkmap, base, 0);
2985 			}
2986 			/*
2987 			 * In the event that we got an access error while
2988 			 * faulting in a page for a write-only file just
2989 			 * force a write.
2990 			 */
2991 			if (error == EACCES)
2992 				goto nfs4_fwrite;
2993 		}
2994 	} while (!error && uiop->uio_resid > 0);
2995 
2996 bottom:
2997 	if (error) {
2998 		uiop->uio_resid = resid + remainder;
2999 		uiop->uio_loffset = offset;
3000 	} else {
3001 		uiop->uio_resid += remainder;
3002 
3003 		mutex_enter(&rp->r_statev4_lock);
3004 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
3005 			gethrestime(&rp->r_attr.va_mtime);
3006 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3007 		}
3008 		mutex_exit(&rp->r_statev4_lock);
3009 	}
3010 
3011 	nfs_rw_exit(&rp->r_lkserlock);
3012 
3013 	return (error);
3014 }
3015 
3016 /*
3017  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
3018  */
3019 static int
3020 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
3021     int flags, cred_t *cr)
3022 {
3023 	struct buf *bp;
3024 	int error;
3025 	page_t *savepp;
3026 	uchar_t fsdata;
3027 	stable_how4 stab_comm;
3028 
3029 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3030 	bp = pageio_setup(pp, len, vp, flags);
3031 	ASSERT(bp != NULL);
3032 
3033 	/*
3034 	 * pageio_setup should have set b_addr to 0.  This
3035 	 * is correct since we want to do I/O on a page
3036 	 * boundary.  bp_mapin will use this addr to calculate
3037 	 * an offset, and then set b_addr to the kernel virtual
3038 	 * address it allocated for us.
3039 	 */
3040 	ASSERT(bp->b_un.b_addr == 0);
3041 
3042 	bp->b_edev = 0;
3043 	bp->b_dev = 0;
3044 	bp->b_lblkno = lbtodb(off);
3045 	bp->b_file = vp;
3046 	bp->b_offset = (offset_t)off;
3047 	bp_mapin(bp);
3048 
3049 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
3050 	    freemem > desfree)
3051 		stab_comm = UNSTABLE4;
3052 	else
3053 		stab_comm = FILE_SYNC4;
3054 
3055 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
3056 
3057 	bp_mapout(bp);
3058 	pageio_done(bp);
3059 
3060 	if (stab_comm == UNSTABLE4)
3061 		fsdata = C_DELAYCOMMIT;
3062 	else
3063 		fsdata = C_NOCOMMIT;
3064 
3065 	savepp = pp;
3066 	do {
3067 		pp->p_fsdata = fsdata;
3068 	} while ((pp = pp->p_next) != savepp);
3069 
3070 	return (error);
3071 }
3072 
3073 /*
3074  */
3075 static int
3076 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
3077 {
3078 	nfs4_open_owner_t	*oop;
3079 	nfs4_open_stream_t	*osp;
3080 	rnode4_t		*rp = VTOR4(vp);
3081 	mntinfo4_t 		*mi = VTOMI4(vp);
3082 	int 			reopen_needed;
3083 
3084 	ASSERT(nfs_zone() == mi->mi_zone);
3085 
3086 
3087 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
3088 	if (!oop)
3089 		return (EIO);
3090 
3091 	/* returns with 'os_sync_lock' held */
3092 	osp = find_open_stream(oop, rp);
3093 	if (!osp) {
3094 		open_owner_rele(oop);
3095 		return (EIO);
3096 	}
3097 
3098 	if (osp->os_failed_reopen) {
3099 		mutex_exit(&osp->os_sync_lock);
3100 		open_stream_rele(osp, rp);
3101 		open_owner_rele(oop);
3102 		return (EIO);
3103 	}
3104 
3105 	/*
3106 	 * Determine whether a reopen is needed.  If this
3107 	 * is a delegation open stream, then the os_delegation bit
3108 	 * should be set.
3109 	 */
3110 
3111 	reopen_needed = osp->os_delegation;
3112 
3113 	mutex_exit(&osp->os_sync_lock);
3114 	open_owner_rele(oop);
3115 
3116 	if (reopen_needed) {
3117 		nfs4_error_zinit(ep);
3118 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
3119 		mutex_enter(&osp->os_sync_lock);
3120 		if (ep->error || ep->stat || osp->os_failed_reopen) {
3121 			mutex_exit(&osp->os_sync_lock);
3122 			open_stream_rele(osp, rp);
3123 			return (EIO);
3124 		}
3125 		mutex_exit(&osp->os_sync_lock);
3126 	}
3127 	open_stream_rele(osp, rp);
3128 
3129 	return (0);
3130 }
3131 
3132 /*
3133  * Write to file.  Writes to remote server in largest size
3134  * chunks that the server can handle.  Write is synchronous.
3135  */
3136 static int
3137 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3138     stable_how4 *stab_comm)
3139 {
3140 	mntinfo4_t *mi;
3141 	COMPOUND4args_clnt args;
3142 	COMPOUND4res_clnt res;
3143 	WRITE4args *wargs;
3144 	WRITE4res *wres;
3145 	nfs_argop4 argop[2];
3146 	nfs_resop4 *resop;
3147 	int tsize;
3148 	stable_how4 stable;
3149 	rnode4_t *rp;
3150 	int doqueue = 1;
3151 	bool_t needrecov;
3152 	nfs4_recov_state_t recov_state;
3153 	nfs4_stateid_types_t sid_types;
3154 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3155 	int recov;
3156 
3157 	rp = VTOR4(vp);
3158 	mi = VTOMI4(vp);
3159 
3160 	ASSERT(nfs_zone() == mi->mi_zone);
3161 
3162 	stable = *stab_comm;
3163 	*stab_comm = FILE_SYNC4;
3164 
3165 	needrecov = FALSE;
3166 	recov_state.rs_flags = 0;
3167 	recov_state.rs_num_retry_despite_err = 0;
3168 	nfs4_init_stateid_types(&sid_types);
3169 
3170 	/* Is curthread the recovery thread? */
3171 	mutex_enter(&mi->mi_lock);
3172 	recov = (mi->mi_recovthread == curthread);
3173 	mutex_exit(&mi->mi_lock);
3174 
3175 recov_retry:
3176 	args.ctag = TAG_WRITE;
3177 	args.array_len = 2;
3178 	args.array = argop;
3179 
3180 	if (!recov) {
3181 		e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3182 		    &recov_state, NULL);
3183 		if (e.error)
3184 			return (e.error);
3185 	}
3186 
3187 	/* 0. putfh target fh */
3188 	argop[0].argop = OP_CPUTFH;
3189 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3190 
3191 	/* 1. write */
3192 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3193 
3194 	do {
3195 
3196 		wargs->offset = (offset4)offset;
3197 		wargs->data_val = base;
3198 
3199 		if (mi->mi_io_kstats) {
3200 			mutex_enter(&mi->mi_lock);
3201 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3202 			mutex_exit(&mi->mi_lock);
3203 		}
3204 
3205 		if ((vp->v_flag & VNOCACHE) ||
3206 		    (rp->r_flags & R4DIRECTIO) ||
3207 		    (mi->mi_flags & MI4_DIRECTIO))
3208 			tsize = MIN(mi->mi_stsize, count);
3209 		else
3210 			tsize = MIN(mi->mi_curwrite, count);
3211 		wargs->data_len = (uint_t)tsize;
3212 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3213 
3214 		if (mi->mi_io_kstats) {
3215 			mutex_enter(&mi->mi_lock);
3216 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3217 			mutex_exit(&mi->mi_lock);
3218 		}
3219 
3220 		if (!recov) {
3221 			needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3222 			if (e.error && !needrecov) {
3223 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3224 				    &recov_state, needrecov);
3225 				return (e.error);
3226 			}
3227 		} else {
3228 			if (e.error)
3229 				return (e.error);
3230 		}
3231 
3232 		/*
3233 		 * Do handling of OLD_STATEID outside
3234 		 * of the normal recovery framework.
3235 		 *
3236 		 * If write receives a BAD stateid error while using a
3237 		 * delegation stateid, retry using the open stateid (if it
3238 		 * exists).  If it doesn't have an open stateid, reopen the
3239 		 * file first, then retry.
3240 		 */
3241 		if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3242 		    sid_types.cur_sid_type != SPEC_SID) {
3243 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3244 			if (!recov)
3245 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3246 				    &recov_state, needrecov);
3247 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3248 			goto recov_retry;
3249 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3250 		    sid_types.cur_sid_type == DEL_SID) {
3251 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3252 			mutex_enter(&rp->r_statev4_lock);
3253 			rp->r_deleg_return_pending = TRUE;
3254 			mutex_exit(&rp->r_statev4_lock);
3255 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3256 				if (!recov)
3257 					nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3258 					    &recov_state, needrecov);
3259 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3260 				    (caddr_t)&res);
3261 				return (EIO);
3262 			}
3263 			if (!recov)
3264 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3265 				    &recov_state, needrecov);
3266 			/* hold needed for nfs4delegreturn_thread */
3267 			VN_HOLD(vp);
3268 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3269 			    NFS4_DR_DISCARD), FALSE);
3270 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3271 			goto recov_retry;
3272 		}
3273 
3274 		if (needrecov) {
3275 			bool_t abort;
3276 
3277 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3278 			    "nfs4write: client got error %d, res.status %d"
3279 			    ", so start recovery", e.error, res.status));
3280 
3281 			abort = nfs4_start_recovery(&e,
3282 			    VTOMI4(vp), vp, NULL, &wargs->stateid,
3283 			    NULL, OP_WRITE, NULL);
3284 			if (!e.error) {
3285 				e.error = geterrno4(res.status);
3286 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3287 				    (caddr_t)&res);
3288 			}
3289 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3290 			    &recov_state, needrecov);
3291 			if (abort == FALSE)
3292 				goto recov_retry;
3293 			return (e.error);
3294 		}
3295 
3296 		if (res.status) {
3297 			e.error = geterrno4(res.status);
3298 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3299 			if (!recov)
3300 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3301 				    &recov_state, needrecov);
3302 			return (e.error);
3303 		}
3304 
3305 		resop = &res.array[1];	/* write res */
3306 		wres = &resop->nfs_resop4_u.opwrite;
3307 
3308 		if ((int)wres->count > tsize) {
3309 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3310 
3311 			zcmn_err(getzoneid(), CE_WARN,
3312 			    "nfs4write: server wrote %u, requested was %u",
3313 			    (int)wres->count, tsize);
3314 			if (!recov)
3315 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3316 				    &recov_state, needrecov);
3317 			return (EIO);
3318 		}
3319 		if (wres->committed == UNSTABLE4) {
3320 			*stab_comm = UNSTABLE4;
3321 			if (wargs->stable == DATA_SYNC4 ||
3322 			    wargs->stable == FILE_SYNC4) {
3323 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3324 				    (caddr_t)&res);
3325 				zcmn_err(getzoneid(), CE_WARN,
3326 				    "nfs4write: server %s did not commit "
3327 				    "to stable storage",
3328 				    rp->r_server->sv_hostname);
3329 				if (!recov)
3330 					nfs4_end_fop(VTOMI4(vp), vp, NULL,
3331 					    OH_WRITE, &recov_state, needrecov);
3332 				return (EIO);
3333 			}
3334 		}
3335 
3336 		tsize = (int)wres->count;
3337 		count -= tsize;
3338 		base += tsize;
3339 		offset += tsize;
3340 		if (mi->mi_io_kstats) {
3341 			mutex_enter(&mi->mi_lock);
3342 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3343 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3344 			    tsize;
3345 			mutex_exit(&mi->mi_lock);
3346 		}
3347 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3348 		mutex_enter(&rp->r_statelock);
3349 		if (rp->r_flags & R4HAVEVERF) {
3350 			if (rp->r_writeverf != wres->writeverf) {
3351 				nfs4_set_mod(vp);
3352 				rp->r_writeverf = wres->writeverf;
3353 			}
3354 		} else {
3355 			rp->r_writeverf = wres->writeverf;
3356 			rp->r_flags |= R4HAVEVERF;
3357 		}
3358 		PURGE_ATTRCACHE4_LOCKED(rp);
3359 		rp->r_flags |= R4WRITEMODIFIED;
3360 		gethrestime(&rp->r_attr.va_mtime);
3361 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3362 		mutex_exit(&rp->r_statelock);
3363 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3364 	} while (count);
3365 
3366 	if (!recov)
3367 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state,
3368 		    needrecov);
3369 
3370 	return (e.error);
3371 }
3372 
3373 /*
3374  * Read from a file.  Reads data in largest chunks our interface can handle.
3375  */
3376 static int
3377 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3378     size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3379 {
3380 	mntinfo4_t *mi;
3381 	COMPOUND4args_clnt args;
3382 	COMPOUND4res_clnt res;
3383 	READ4args *rargs;
3384 	nfs_argop4 argop[2];
3385 	int tsize;
3386 	int doqueue;
3387 	rnode4_t *rp;
3388 	int data_len;
3389 	bool_t is_eof;
3390 	bool_t needrecov = FALSE;
3391 	nfs4_recov_state_t recov_state;
3392 	nfs4_stateid_types_t sid_types;
3393 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3394 
3395 	rp = VTOR4(vp);
3396 	mi = VTOMI4(vp);
3397 	doqueue = 1;
3398 
3399 	ASSERT(nfs_zone() == mi->mi_zone);
3400 
3401 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3402 
3403 	args.array_len = 2;
3404 	args.array = argop;
3405 
3406 	nfs4_init_stateid_types(&sid_types);
3407 
3408 	recov_state.rs_flags = 0;
3409 	recov_state.rs_num_retry_despite_err = 0;
3410 
3411 recov_retry:
3412 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3413 	    &recov_state, NULL);
3414 	if (e.error)
3415 		return (e.error);
3416 
3417 	/* putfh target fh */
3418 	argop[0].argop = OP_CPUTFH;
3419 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3420 
3421 	/* read */
3422 	argop[1].argop = OP_READ;
3423 	rargs = &argop[1].nfs_argop4_u.opread;
3424 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3425 	    OP_READ, &sid_types, async);
3426 
3427 	do {
3428 		if (mi->mi_io_kstats) {
3429 			mutex_enter(&mi->mi_lock);
3430 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3431 			mutex_exit(&mi->mi_lock);
3432 		}
3433 
3434 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3435 		    "nfs4read: %s call, rp %s",
3436 		    needrecov ? "recov" : "first",
3437 		    rnode4info(rp)));
3438 
3439 		if ((vp->v_flag & VNOCACHE) ||
3440 		    (rp->r_flags & R4DIRECTIO) ||
3441 		    (mi->mi_flags & MI4_DIRECTIO))
3442 			tsize = MIN(mi->mi_tsize, count);
3443 		else
3444 			tsize = MIN(mi->mi_curread, count);
3445 
3446 		rargs->offset = (offset4)offset;
3447 		rargs->count = (count4)tsize;
3448 		rargs->res_data_val_alt = NULL;
3449 		rargs->res_mblk = NULL;
3450 		rargs->res_uiop = NULL;
3451 		rargs->res_maxsize = 0;
3452 		rargs->wlist = NULL;
3453 
3454 		if (uiop)
3455 			rargs->res_uiop = uiop;
3456 		else
3457 			rargs->res_data_val_alt = base;
3458 		rargs->res_maxsize = tsize;
3459 
3460 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3461 #ifdef	DEBUG
3462 		if (nfs4read_error_inject) {
3463 			res.status = nfs4read_error_inject;
3464 			nfs4read_error_inject = 0;
3465 		}
3466 #endif
3467 
3468 		if (mi->mi_io_kstats) {
3469 			mutex_enter(&mi->mi_lock);
3470 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3471 			mutex_exit(&mi->mi_lock);
3472 		}
3473 
3474 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3475 		if (e.error != 0 && !needrecov) {
3476 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3477 			    &recov_state, needrecov);
3478 			return (e.error);
3479 		}
3480 
3481 		/*
3482 		 * Do proper retry for OLD and BAD stateid errors outside
3483 		 * of the normal recovery framework.  There are two differences
3484 		 * between async and sync reads.  The first is that we allow
3485 		 * retry on BAD_STATEID for async reads, but not sync reads.
3486 		 * The second is that we mark the file dead for a failed
3487 		 * attempt with a special stateid for sync reads, but just
3488 		 * return EIO for async reads.
3489 		 *
3490 		 * If a sync read receives a BAD stateid error while using a
3491 		 * delegation stateid, retry using the open stateid (if it
3492 		 * exists).  If it doesn't have an open stateid, reopen the
3493 		 * file first, then retry.
3494 		 */
3495 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3496 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3497 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3498 			    &recov_state, needrecov);
3499 			if (sid_types.cur_sid_type == SPEC_SID) {
3500 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3501 				    (caddr_t)&res);
3502 				return (EIO);
3503 			}
3504 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3505 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3506 			goto recov_retry;
3507 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3508 		    !async && sid_types.cur_sid_type != SPEC_SID) {
3509 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3510 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3511 			    &recov_state, needrecov);
3512 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3513 			goto recov_retry;
3514 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3515 		    sid_types.cur_sid_type == DEL_SID) {
3516 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3517 			mutex_enter(&rp->r_statev4_lock);
3518 			rp->r_deleg_return_pending = TRUE;
3519 			mutex_exit(&rp->r_statev4_lock);
3520 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3521 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3522 				    &recov_state, needrecov);
3523 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3524 				    (caddr_t)&res);
3525 				return (EIO);
3526 			}
3527 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3528 			    &recov_state, needrecov);
3529 			/* hold needed for nfs4delegreturn_thread */
3530 			VN_HOLD(vp);
3531 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3532 			    NFS4_DR_DISCARD), FALSE);
3533 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3534 			goto recov_retry;
3535 		}
3536 		if (needrecov) {
3537 			bool_t abort;
3538 
3539 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3540 			    "nfs4read: initiating recovery\n"));
3541 			abort = nfs4_start_recovery(&e,
3542 			    mi, vp, NULL, &rargs->stateid,
3543 			    NULL, OP_READ, NULL);
3544 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3545 			    &recov_state, needrecov);
3546 			/*
3547 			 * Do not retry if we got OLD_STATEID using a special
3548 			 * stateid.  This avoids looping with a broken server.
3549 			 */
3550 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3551 			    sid_types.cur_sid_type == SPEC_SID)
3552 				abort = TRUE;
3553 
3554 			if (abort == FALSE) {
3555 				/*
3556 				 * Need to retry all possible stateids in
3557 				 * case the recovery error wasn't stateid
3558 				 * related or the stateids have become
3559 				 * stale (server reboot).
3560 				 */
3561 				nfs4_init_stateid_types(&sid_types);
3562 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3563 				    (caddr_t)&res);
3564 				goto recov_retry;
3565 			}
3566 
3567 			if (!e.error) {
3568 				e.error = geterrno4(res.status);
3569 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3570 				    (caddr_t)&res);
3571 			}
3572 			return (e.error);
3573 		}
3574 
3575 		if (res.status) {
3576 			e.error = geterrno4(res.status);
3577 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3578 			    &recov_state, needrecov);
3579 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3580 			return (e.error);
3581 		}
3582 
3583 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3584 		count -= data_len;
3585 		if (base)
3586 			base += data_len;
3587 		offset += data_len;
3588 		if (mi->mi_io_kstats) {
3589 			mutex_enter(&mi->mi_lock);
3590 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3591 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3592 			mutex_exit(&mi->mi_lock);
3593 		}
3594 		lwp_stat_update(LWP_STAT_INBLK, 1);
3595 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3596 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3597 
3598 	} while (count && !is_eof);
3599 
3600 	*residp = count;
3601 
3602 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3603 
3604 	return (e.error);
3605 }
3606 
3607 /* ARGSUSED */
3608 static int
3609 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp,
3610 	caller_context_t *ct)
3611 {
3612 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3613 		return (EIO);
3614 	switch (cmd) {
3615 		case _FIODIRECTIO:
3616 			return (nfs4_directio(vp, (int)arg, cr));
3617 		default:
3618 			return (ENOTTY);
3619 	}
3620 }
3621 
3622 /* ARGSUSED */
3623 int
3624 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3625     caller_context_t *ct)
3626 {
3627 	int error;
3628 	rnode4_t *rp = VTOR4(vp);
3629 
3630 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3631 		return (EIO);
3632 	/*
3633 	 * If it has been specified that the return value will
3634 	 * just be used as a hint, and we are only being asked
3635 	 * for size, fsid or rdevid, then return the client's
3636 	 * notion of these values without checking to make sure
3637 	 * that the attribute cache is up to date.
3638 	 * The whole point is to avoid an over the wire GETATTR
3639 	 * call.
3640 	 */
3641 	if (flags & ATTR_HINT) {
3642 		if (vap->va_mask ==
3643 		    (vap->va_mask & (AT_SIZE | AT_FSID | AT_RDEV))) {
3644 			mutex_enter(&rp->r_statelock);
3645 			if (vap->va_mask | AT_SIZE)
3646 				vap->va_size = rp->r_size;
3647 			if (vap->va_mask | AT_FSID)
3648 				vap->va_fsid = rp->r_attr.va_fsid;
3649 			if (vap->va_mask | AT_RDEV)
3650 				vap->va_rdev = rp->r_attr.va_rdev;
3651 			mutex_exit(&rp->r_statelock);
3652 			return (0);
3653 		}
3654 	}
3655 
3656 	/*
3657 	 * Only need to flush pages if asking for the mtime
3658 	 * and if there any dirty pages or any outstanding
3659 	 * asynchronous (write) requests for this file.
3660 	 */
3661 	if (vap->va_mask & AT_MTIME) {
3662 		rp = VTOR4(vp);
3663 		if (nfs4_has_pages(vp)) {
3664 			mutex_enter(&rp->r_statev4_lock);
3665 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3666 				mutex_exit(&rp->r_statev4_lock);
3667 				if (rp->r_flags & R4DIRTY ||
3668 				    rp->r_awcount > 0) {
3669 					mutex_enter(&rp->r_statelock);
3670 					rp->r_gcount++;
3671 					mutex_exit(&rp->r_statelock);
3672 					error =
3673 					    nfs4_putpage(vp, (u_offset_t)0,
3674 					    0, 0, cr, NULL);
3675 					mutex_enter(&rp->r_statelock);
3676 					if (error && (error == ENOSPC ||
3677 					    error == EDQUOT)) {
3678 						if (!rp->r_error)
3679 							rp->r_error = error;
3680 					}
3681 					if (--rp->r_gcount == 0)
3682 						cv_broadcast(&rp->r_cv);
3683 					mutex_exit(&rp->r_statelock);
3684 				}
3685 			} else {
3686 				mutex_exit(&rp->r_statev4_lock);
3687 			}
3688 		}
3689 	}
3690 	return (nfs4getattr(vp, vap, cr));
3691 }
3692 
3693 int
3694 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3695 {
3696 	/*
3697 	 * If these are the only two bits cleared
3698 	 * on the server then return 0 (OK) else
3699 	 * return 1 (BAD).
3700 	 */
3701 	on_client &= ~(S_ISUID|S_ISGID);
3702 	if (on_client == from_server)
3703 		return (0);
3704 	else
3705 		return (1);
3706 }
3707 
3708 /*ARGSUSED4*/
3709 static int
3710 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3711     caller_context_t *ct)
3712 {
3713 	if (vap->va_mask & AT_NOSET)
3714 		return (EINVAL);
3715 
3716 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3717 		return (EIO);
3718 
3719 	/*
3720 	 * Don't call secpolicy_vnode_setattr, the client cannot
3721 	 * use its cached attributes to make security decisions
3722 	 * as the server may be faking mode bits or mapping uid/gid.
3723 	 * Always just let the server to the checking.
3724 	 * If we provide the ability to remove basic priviledges
3725 	 * to setattr (e.g. basic without chmod) then we will
3726 	 * need to add a check here before calling the server.
3727 	 */
3728 
3729 	return (nfs4setattr(vp, vap, flags, cr, NULL));
3730 }
3731 
3732 /*
3733  * To replace the "guarded" version 3 setattr, we use two types of compound
3734  * setattr requests:
3735  * 1. The "normal" setattr, used when the size of the file isn't being
3736  *    changed - { Putfh <fh>; Setattr; Getattr }/
3737  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3738  *    with only ctime as the argument. If the server ctime differs from
3739  *    what is cached on the client, the verify will fail, but we would
3740  *    already have the ctime from the preceding getattr, so just set it
3741  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3742  *	Setattr; Getattr }.
3743  *
3744  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3745  * this setattr and NULL if they are not.
3746  */
3747 static int
3748 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3749     vsecattr_t *vsap)
3750 {
3751 	COMPOUND4args_clnt args;
3752 	COMPOUND4res_clnt res, *resp = NULL;
3753 	nfs4_ga_res_t *garp = NULL;
3754 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3755 	nfs_argop4 argop[5];
3756 	int verify_argop = -1;
3757 	int setattr_argop = 1;
3758 	nfs_resop4 *resop;
3759 	vattr_t va;
3760 	rnode4_t *rp;
3761 	int doqueue = 1;
3762 	uint_t mask = vap->va_mask;
3763 	mode_t omode;
3764 	vsecattr_t *vsp;
3765 	timestruc_t ctime;
3766 	bool_t needrecov = FALSE;
3767 	nfs4_recov_state_t recov_state;
3768 	nfs4_stateid_types_t sid_types;
3769 	stateid4 stateid;
3770 	hrtime_t t;
3771 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3772 	servinfo4_t *svp;
3773 	bitmap4 supp_attrs;
3774 
3775 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3776 	rp = VTOR4(vp);
3777 	nfs4_init_stateid_types(&sid_types);
3778 
3779 	/*
3780 	 * Only need to flush pages if there are any pages and
3781 	 * if the file is marked as dirty in some fashion.  The
3782 	 * file must be flushed so that we can accurately
3783 	 * determine the size of the file and the cached data
3784 	 * after the SETATTR returns.  A file is considered to
3785 	 * be dirty if it is either marked with R4DIRTY, has
3786 	 * outstanding i/o's active, or is mmap'd.  In this
3787 	 * last case, we can't tell whether there are dirty
3788 	 * pages, so we flush just to be sure.
3789 	 */
3790 	if (nfs4_has_pages(vp) &&
3791 	    ((rp->r_flags & R4DIRTY) ||
3792 	    rp->r_count > 0 ||
3793 	    rp->r_mapcnt > 0)) {
3794 		ASSERT(vp->v_type != VCHR);
3795 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr, NULL);
3796 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3797 			mutex_enter(&rp->r_statelock);
3798 			if (!rp->r_error)
3799 				rp->r_error = e.error;
3800 			mutex_exit(&rp->r_statelock);
3801 		}
3802 	}
3803 
3804 	if (mask & AT_SIZE) {
3805 		/*
3806 		 * Verification setattr compound for non-deleg AT_SIZE:
3807 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3808 		 * Set ctime local here (outside the do_again label)
3809 		 * so that subsequent retries (after failed VERIFY)
3810 		 * will use ctime from GETATTR results (from failed
3811 		 * verify compound) as VERIFY arg.
3812 		 * If file has delegation, then VERIFY(time_metadata)
3813 		 * is of little added value, so don't bother.
3814 		 */
3815 		mutex_enter(&rp->r_statev4_lock);
3816 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3817 		    rp->r_deleg_return_pending) {
3818 			numops = 5;
3819 			ctime = rp->r_attr.va_ctime;
3820 		}
3821 		mutex_exit(&rp->r_statev4_lock);
3822 	}
3823 
3824 	recov_state.rs_flags = 0;
3825 	recov_state.rs_num_retry_despite_err = 0;
3826 
3827 	args.ctag = TAG_SETATTR;
3828 do_again:
3829 recov_retry:
3830 	setattr_argop = numops - 2;
3831 
3832 	args.array = argop;
3833 	args.array_len = numops;
3834 
3835 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3836 	if (e.error)
3837 		return (e.error);
3838 
3839 
3840 	/* putfh target fh */
3841 	argop[0].argop = OP_CPUTFH;
3842 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3843 
3844 	if (numops == 5) {
3845 		/*
3846 		 * We only care about the ctime, but need to get mtime
3847 		 * and size for proper cache update.
3848 		 */
3849 		/* getattr */
3850 		argop[1].argop = OP_GETATTR;
3851 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3852 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3853 
3854 		/* verify - set later in loop */
3855 		verify_argop = 2;
3856 	}
3857 
3858 	/* setattr */
3859 	svp = rp->r_server;
3860 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3861 	supp_attrs = svp->sv_supp_attrs;
3862 	nfs_rw_exit(&svp->sv_lock);
3863 
3864 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3865 	    supp_attrs, &e.error, &sid_types);
3866 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3867 	if (e.error) {
3868 		/* req time field(s) overflow - return immediately */
3869 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3870 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3871 		    opsetattr.obj_attributes);
3872 		return (e.error);
3873 	}
3874 	omode = rp->r_attr.va_mode;
3875 
3876 	/* getattr */
3877 	argop[numops-1].argop = OP_GETATTR;
3878 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3879 	/*
3880 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3881 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3882 	 * used in updating the ACL cache.
3883 	 */
3884 	if (vsap != NULL)
3885 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3886 		    FATTR4_ACL_MASK;
3887 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3888 
3889 	/*
3890 	 * setattr iterates if the object size is set and the cached ctime
3891 	 * does not match the file ctime. In that case, verify the ctime first.
3892 	 */
3893 
3894 	do {
3895 		if (verify_argop != -1) {
3896 			/*
3897 			 * Verify that the ctime match before doing setattr.
3898 			 */
3899 			va.va_mask = AT_CTIME;
3900 			va.va_ctime = ctime;
3901 			svp = rp->r_server;
3902 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3903 			supp_attrs = svp->sv_supp_attrs;
3904 			nfs_rw_exit(&svp->sv_lock);
3905 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3906 			    OP_VERIFY, supp_attrs);
3907 			if (e.error) {
3908 				/* req time field(s) overflow - return */
3909 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3910 				    needrecov);
3911 				break;
3912 			}
3913 		}
3914 
3915 		doqueue = 1;
3916 
3917 		t = gethrtime();
3918 
3919 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3920 
3921 		/*
3922 		 * Purge the access cache and ACL cache if changing either the
3923 		 * owner of the file, the group owner, or the mode.  These may
3924 		 * change the access permissions of the file, so purge old
3925 		 * information and start over again.
3926 		 */
3927 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3928 			(void) nfs4_access_purge_rp(rp);
3929 			if (rp->r_secattr != NULL) {
3930 				mutex_enter(&rp->r_statelock);
3931 				vsp = rp->r_secattr;
3932 				rp->r_secattr = NULL;
3933 				mutex_exit(&rp->r_statelock);
3934 				if (vsp != NULL)
3935 					nfs4_acl_free_cache(vsp);
3936 			}
3937 		}
3938 
3939 		/*
3940 		 * If res.array_len == numops, then everything succeeded,
3941 		 * except for possibly the final getattr.  If only the
3942 		 * last getattr failed, give up, and don't try recovery.
3943 		 */
3944 		if (res.array_len == numops) {
3945 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3946 			    needrecov);
3947 			if (! e.error)
3948 				resp = &res;
3949 			break;
3950 		}
3951 
3952 		/*
3953 		 * if either rpc call failed or completely succeeded - done
3954 		 */
3955 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
3956 		if (e.error) {
3957 			PURGE_ATTRCACHE4(vp);
3958 			if (!needrecov) {
3959 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3960 				    needrecov);
3961 				break;
3962 			}
3963 		}
3964 
3965 		/*
3966 		 * Do proper retry for OLD_STATEID outside of the normal
3967 		 * recovery framework.
3968 		 */
3969 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3970 		    sid_types.cur_sid_type != SPEC_SID &&
3971 		    sid_types.cur_sid_type != NO_SID) {
3972 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3973 			    needrecov);
3974 			nfs4_save_stateid(&stateid, &sid_types);
3975 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3976 			    opsetattr.obj_attributes);
3977 			if (verify_argop != -1) {
3978 				nfs4args_verify_free(&argop[verify_argop]);
3979 				verify_argop = -1;
3980 			}
3981 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3982 			goto recov_retry;
3983 		}
3984 
3985 		if (needrecov) {
3986 			bool_t abort;
3987 
3988 			abort = nfs4_start_recovery(&e,
3989 			    VTOMI4(vp), vp, NULL, NULL, NULL,
3990 			    OP_SETATTR, NULL);
3991 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3992 			    needrecov);
3993 			/*
3994 			 * Do not retry if we failed with OLD_STATEID using
3995 			 * a special stateid.  This is done to avoid looping
3996 			 * with a broken server.
3997 			 */
3998 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3999 			    (sid_types.cur_sid_type == SPEC_SID ||
4000 			    sid_types.cur_sid_type == NO_SID))
4001 				abort = TRUE;
4002 			if (!e.error) {
4003 				if (res.status == NFS4ERR_BADOWNER)
4004 					nfs4_log_badowner(VTOMI4(vp),
4005 					    OP_SETATTR);
4006 
4007 				e.error = geterrno4(res.status);
4008 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4009 				    (caddr_t)&res);
4010 			}
4011 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4012 			    opsetattr.obj_attributes);
4013 			if (verify_argop != -1) {
4014 				nfs4args_verify_free(&argop[verify_argop]);
4015 				verify_argop = -1;
4016 			}
4017 			if (abort == FALSE) {
4018 				/*
4019 				 * Need to retry all possible stateids in
4020 				 * case the recovery error wasn't stateid
4021 				 * related or the stateids have become
4022 				 * stale (server reboot).
4023 				 */
4024 				nfs4_init_stateid_types(&sid_types);
4025 				goto recov_retry;
4026 			}
4027 			return (e.error);
4028 		}
4029 
4030 		/*
4031 		 * Need to call nfs4_end_op before nfs4getattr to
4032 		 * avoid potential nfs4_start_op deadlock. See RFE
4033 		 * 4777612.  Calls to nfs4_invalidate_pages() and
4034 		 * nfs4_purge_stale_fh() might also generate over the
4035 		 * wire calls which my cause nfs4_start_op() deadlock.
4036 		 */
4037 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4038 
4039 		/*
4040 		 * Check to update lease.
4041 		 */
4042 		resp = &res;
4043 		if (res.status == NFS4_OK) {
4044 			break;
4045 		}
4046 
4047 		/*
4048 		 * Check if verify failed to see if try again
4049 		 */
4050 		if ((verify_argop == -1) || (res.array_len != 3)) {
4051 			/*
4052 			 * can't continue...
4053 			 */
4054 			if (res.status == NFS4ERR_BADOWNER)
4055 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
4056 
4057 			e.error = geterrno4(res.status);
4058 		} else {
4059 			/*
4060 			 * When the verify request fails, the client ctime is
4061 			 * not in sync with the server. This is the same as
4062 			 * the version 3 "not synchronized" error, and we
4063 			 * handle it in a similar manner (XXX do we need to???).
4064 			 * Use the ctime returned in the first getattr for
4065 			 * the input to the next verify.
4066 			 * If we couldn't get the attributes, then we give up
4067 			 * because we can't complete the operation as required.
4068 			 */
4069 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
4070 		}
4071 		if (e.error) {
4072 			PURGE_ATTRCACHE4(vp);
4073 			nfs4_purge_stale_fh(e.error, vp, cr);
4074 		} else {
4075 			/*
4076 			 * retry with a new verify value
4077 			 */
4078 			ctime = garp->n4g_va.va_ctime;
4079 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4080 			resp = NULL;
4081 		}
4082 		if (!e.error) {
4083 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4084 			    opsetattr.obj_attributes);
4085 			if (verify_argop != -1) {
4086 				nfs4args_verify_free(&argop[verify_argop]);
4087 				verify_argop = -1;
4088 			}
4089 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4090 			goto do_again;
4091 		}
4092 	} while (!e.error);
4093 
4094 	if (e.error) {
4095 		/*
4096 		 * If we are here, rfs4call has an irrecoverable error - return
4097 		 */
4098 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4099 		    opsetattr.obj_attributes);
4100 		if (verify_argop != -1) {
4101 			nfs4args_verify_free(&argop[verify_argop]);
4102 			verify_argop = -1;
4103 		}
4104 		if (resp)
4105 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4106 		return (e.error);
4107 	}
4108 
4109 
4110 
4111 	/*
4112 	 * If changing the size of the file, invalidate
4113 	 * any local cached data which is no longer part
4114 	 * of the file.  We also possibly invalidate the
4115 	 * last page in the file.  We could use
4116 	 * pvn_vpzero(), but this would mark the page as
4117 	 * modified and require it to be written back to
4118 	 * the server for no particularly good reason.
4119 	 * This way, if we access it, then we bring it
4120 	 * back in.  A read should be cheaper than a
4121 	 * write.
4122 	 */
4123 	if (mask & AT_SIZE) {
4124 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
4125 	}
4126 
4127 	/* either no error or one of the postop getattr failed */
4128 
4129 	/*
4130 	 * XXX Perform a simplified version of wcc checking. Instead of
4131 	 * have another getattr to get pre-op, just purge cache if
4132 	 * any of the ops prior to and including the getattr failed.
4133 	 * If the getattr succeeded then update the attrcache accordingly.
4134 	 */
4135 
4136 	garp = NULL;
4137 	if (res.status == NFS4_OK) {
4138 		/*
4139 		 * Last getattr
4140 		 */
4141 		resop = &res.array[numops - 1];
4142 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4143 	}
4144 	/*
4145 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
4146 	 * rather than filling it.  See the function itself for details.
4147 	 */
4148 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4149 	if (garp != NULL) {
4150 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
4151 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
4152 			vs_ace4_destroy(&garp->n4g_vsa);
4153 		} else {
4154 			if (vsap != NULL) {
4155 				/*
4156 				 * The ACL was supposed to be set and to be
4157 				 * returned in the last getattr of this
4158 				 * compound, but for some reason the getattr
4159 				 * result doesn't contain the ACL.  In this
4160 				 * case, purge the ACL cache.
4161 				 */
4162 				if (rp->r_secattr != NULL) {
4163 					mutex_enter(&rp->r_statelock);
4164 					vsp = rp->r_secattr;
4165 					rp->r_secattr = NULL;
4166 					mutex_exit(&rp->r_statelock);
4167 					if (vsp != NULL)
4168 						nfs4_acl_free_cache(vsp);
4169 				}
4170 			}
4171 		}
4172 	}
4173 
4174 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4175 		/*
4176 		 * Set the size, rather than relying on getting it updated
4177 		 * via a GETATTR.  With delegations the client tries to
4178 		 * suppress GETATTR calls.
4179 		 */
4180 		mutex_enter(&rp->r_statelock);
4181 		rp->r_size = vap->va_size;
4182 		mutex_exit(&rp->r_statelock);
4183 	}
4184 
4185 	/*
4186 	 * Can free up request args and res
4187 	 */
4188 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4189 	    opsetattr.obj_attributes);
4190 	if (verify_argop != -1) {
4191 		nfs4args_verify_free(&argop[verify_argop]);
4192 		verify_argop = -1;
4193 	}
4194 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4195 
4196 	/*
4197 	 * Some servers will change the mode to clear the setuid
4198 	 * and setgid bits when changing the uid or gid.  The
4199 	 * client needs to compensate appropriately.
4200 	 */
4201 	if (mask & (AT_UID | AT_GID)) {
4202 		int terror, do_setattr;
4203 
4204 		do_setattr = 0;
4205 		va.va_mask = AT_MODE;
4206 		terror = nfs4getattr(vp, &va, cr);
4207 		if (!terror &&
4208 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4209 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4210 			va.va_mask = AT_MODE;
4211 			if (mask & AT_MODE) {
4212 				/*
4213 				 * We asked the mode to be changed and what
4214 				 * we just got from the server in getattr is
4215 				 * not what we wanted it to be, so set it now.
4216 				 */
4217 				va.va_mode = vap->va_mode;
4218 				do_setattr = 1;
4219 			} else {
4220 				/*
4221 				 * We did not ask the mode to be changed,
4222 				 * Check to see that the server just cleared
4223 				 * I_SUID and I_GUID from it. If not then
4224 				 * set mode to omode with UID/GID cleared.
4225 				 */
4226 				if (nfs4_compare_modes(va.va_mode, omode)) {
4227 					omode &= ~(S_ISUID|S_ISGID);
4228 					va.va_mode = omode;
4229 					do_setattr = 1;
4230 				}
4231 			}
4232 
4233 			if (do_setattr)
4234 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4235 		}
4236 	}
4237 
4238 	return (e.error);
4239 }
4240 
4241 /* ARGSUSED */
4242 static int
4243 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr, caller_context_t *ct)
4244 {
4245 	COMPOUND4args_clnt args;
4246 	COMPOUND4res_clnt res;
4247 	int doqueue;
4248 	uint32_t acc, resacc, argacc;
4249 	rnode4_t *rp;
4250 	cred_t *cred, *ncr, *ncrfree = NULL;
4251 	nfs4_access_type_t cacc;
4252 	int num_ops;
4253 	nfs_argop4 argop[3];
4254 	nfs_resop4 *resop;
4255 	bool_t needrecov = FALSE, do_getattr;
4256 	nfs4_recov_state_t recov_state;
4257 	int rpc_error;
4258 	hrtime_t t;
4259 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4260 	mntinfo4_t *mi = VTOMI4(vp);
4261 
4262 	if (nfs_zone() != mi->mi_zone)
4263 		return (EIO);
4264 
4265 	acc = 0;
4266 	if (mode & VREAD)
4267 		acc |= ACCESS4_READ;
4268 	if (mode & VWRITE) {
4269 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4270 			return (EROFS);
4271 		if (vp->v_type == VDIR)
4272 			acc |= ACCESS4_DELETE;
4273 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4274 	}
4275 	if (mode & VEXEC) {
4276 		if (vp->v_type == VDIR)
4277 			acc |= ACCESS4_LOOKUP;
4278 		else
4279 			acc |= ACCESS4_EXECUTE;
4280 	}
4281 
4282 	if (VTOR4(vp)->r_acache != NULL) {
4283 		e.error = nfs4_validate_caches(vp, cr);
4284 		if (e.error)
4285 			return (e.error);
4286 	}
4287 
4288 	rp = VTOR4(vp);
4289 	if (vp->v_type == VDIR)
4290 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4291 		    ACCESS4_EXTEND | ACCESS4_LOOKUP;
4292 	else
4293 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4294 		    ACCESS4_EXECUTE;
4295 	recov_state.rs_flags = 0;
4296 	recov_state.rs_num_retry_despite_err = 0;
4297 
4298 	cred = cr;
4299 	/*
4300 	 * ncr and ncrfree both initially
4301 	 * point to the memory area returned
4302 	 * by crnetadjust();
4303 	 * ncrfree not NULL when exiting means
4304 	 * that we need to release it
4305 	 */
4306 	ncr = crnetadjust(cred);
4307 	ncrfree = ncr;
4308 
4309 tryagain:
4310 	cacc = nfs4_access_check(rp, acc, cred);
4311 	if (cacc == NFS4_ACCESS_ALLOWED) {
4312 		if (ncrfree != NULL)
4313 			crfree(ncrfree);
4314 		return (0);
4315 	}
4316 	if (cacc == NFS4_ACCESS_DENIED) {
4317 		/*
4318 		 * If the cred can be adjusted, try again
4319 		 * with the new cred.
4320 		 */
4321 		if (ncr != NULL) {
4322 			cred = ncr;
4323 			ncr = NULL;
4324 			goto tryagain;
4325 		}
4326 		if (ncrfree != NULL)
4327 			crfree(ncrfree);
4328 		return (EACCES);
4329 	}
4330 
4331 recov_retry:
4332 	/*
4333 	 * Don't take with r_statev4_lock here. r_deleg_type could
4334 	 * change as soon as lock is released.  Since it is an int,
4335 	 * there is no atomicity issue.
4336 	 */
4337 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4338 	num_ops = do_getattr ? 3 : 2;
4339 
4340 	args.ctag = TAG_ACCESS;
4341 
4342 	args.array_len = num_ops;
4343 	args.array = argop;
4344 
4345 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4346 	    &recov_state, NULL)) {
4347 		if (ncrfree != NULL)
4348 			crfree(ncrfree);
4349 		return (e.error);
4350 	}
4351 
4352 	/* putfh target fh */
4353 	argop[0].argop = OP_CPUTFH;
4354 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4355 
4356 	/* access */
4357 	argop[1].argop = OP_ACCESS;
4358 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4359 
4360 	/* getattr */
4361 	if (do_getattr) {
4362 		argop[2].argop = OP_GETATTR;
4363 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4364 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4365 	}
4366 
4367 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4368 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4369 	    rnode4info(VTOR4(vp))));
4370 
4371 	doqueue = 1;
4372 	t = gethrtime();
4373 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4374 	rpc_error = e.error;
4375 
4376 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4377 	if (needrecov) {
4378 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4379 		    "nfs4_access: initiating recovery\n"));
4380 
4381 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4382 		    NULL, OP_ACCESS, NULL) == FALSE) {
4383 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4384 			    &recov_state, needrecov);
4385 			if (!e.error)
4386 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4387 				    (caddr_t)&res);
4388 			goto recov_retry;
4389 		}
4390 	}
4391 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4392 
4393 	if (e.error)
4394 		goto out;
4395 
4396 	if (res.status) {
4397 		e.error = geterrno4(res.status);
4398 		/*
4399 		 * This might generate over the wire calls throught
4400 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4401 		 * here to avoid a deadlock.
4402 		 */
4403 		nfs4_purge_stale_fh(e.error, vp, cr);
4404 		goto out;
4405 	}
4406 	resop = &res.array[1];	/* access res */
4407 
4408 	resacc = resop->nfs_resop4_u.opaccess.access;
4409 
4410 	if (do_getattr) {
4411 		resop++;	/* getattr res */
4412 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4413 		    t, cr, FALSE, NULL);
4414 	}
4415 
4416 	if (!e.error) {
4417 		nfs4_access_cache(rp, argacc, resacc, cred);
4418 		/*
4419 		 * we just cached results with cred; if cred is the
4420 		 * adjusted credentials from crnetadjust, we do not want
4421 		 * to release them before exiting: hence setting ncrfree
4422 		 * to NULL
4423 		 */
4424 		if (cred != cr)
4425 			ncrfree = NULL;
4426 		/* XXX check the supported bits too? */
4427 		if ((acc & resacc) != acc) {
4428 			/*
4429 			 * The following code implements the semantic
4430 			 * that a setuid root program has *at least* the
4431 			 * permissions of the user that is running the
4432 			 * program.  See rfs3call() for more portions
4433 			 * of the implementation of this functionality.
4434 			 */
4435 			/* XXX-LP */
4436 			if (ncr != NULL) {
4437 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4438 				    (caddr_t)&res);
4439 				cred = ncr;
4440 				ncr = NULL;
4441 				goto tryagain;
4442 			}
4443 			e.error = EACCES;
4444 		}
4445 	}
4446 
4447 out:
4448 	if (!rpc_error)
4449 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4450 
4451 	if (ncrfree != NULL)
4452 		crfree(ncrfree);
4453 
4454 	return (e.error);
4455 }
4456 
4457 /* ARGSUSED */
4458 static int
4459 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr, caller_context_t *ct)
4460 {
4461 	COMPOUND4args_clnt args;
4462 	COMPOUND4res_clnt res;
4463 	int doqueue;
4464 	rnode4_t *rp;
4465 	nfs_argop4 argop[3];
4466 	nfs_resop4 *resop;
4467 	READLINK4res *lr_res;
4468 	nfs4_ga_res_t *garp;
4469 	uint_t len;
4470 	char *linkdata;
4471 	bool_t needrecov = FALSE;
4472 	nfs4_recov_state_t recov_state;
4473 	hrtime_t t;
4474 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4475 
4476 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4477 		return (EIO);
4478 	/*
4479 	 * Can't readlink anything other than a symbolic link.
4480 	 */
4481 	if (vp->v_type != VLNK)
4482 		return (EINVAL);
4483 
4484 	rp = VTOR4(vp);
4485 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4486 		e.error = nfs4_validate_caches(vp, cr);
4487 		if (e.error)
4488 			return (e.error);
4489 		mutex_enter(&rp->r_statelock);
4490 		if (rp->r_symlink.contents != NULL) {
4491 			e.error = uiomove(rp->r_symlink.contents,
4492 			    rp->r_symlink.len, UIO_READ, uiop);
4493 			mutex_exit(&rp->r_statelock);
4494 			return (e.error);
4495 		}
4496 		mutex_exit(&rp->r_statelock);
4497 	}
4498 	recov_state.rs_flags = 0;
4499 	recov_state.rs_num_retry_despite_err = 0;
4500 
4501 recov_retry:
4502 	args.array_len = 3;
4503 	args.array = argop;
4504 	args.ctag = TAG_READLINK;
4505 
4506 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4507 	if (e.error) {
4508 		return (e.error);
4509 	}
4510 
4511 	/* 0. putfh symlink fh */
4512 	argop[0].argop = OP_CPUTFH;
4513 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4514 
4515 	/* 1. readlink */
4516 	argop[1].argop = OP_READLINK;
4517 
4518 	/* 2. getattr */
4519 	argop[2].argop = OP_GETATTR;
4520 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4521 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4522 
4523 	doqueue = 1;
4524 
4525 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4526 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4527 	    rnode4info(VTOR4(vp))));
4528 
4529 	t = gethrtime();
4530 
4531 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4532 
4533 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4534 	if (needrecov) {
4535 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4536 		    "nfs4_readlink: initiating recovery\n"));
4537 
4538 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4539 		    NULL, OP_READLINK, NULL) == FALSE) {
4540 			if (!e.error)
4541 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4542 				    (caddr_t)&res);
4543 
4544 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4545 			    needrecov);
4546 			goto recov_retry;
4547 		}
4548 	}
4549 
4550 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4551 
4552 	if (e.error)
4553 		return (e.error);
4554 
4555 	/*
4556 	 * There is an path in the code below which calls
4557 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4558 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4559 	 * here to avoid nfs4_start_op() deadlock.
4560 	 */
4561 
4562 	if (res.status && (res.array_len < args.array_len)) {
4563 		/*
4564 		 * either Putfh or Link failed
4565 		 */
4566 		e.error = geterrno4(res.status);
4567 		nfs4_purge_stale_fh(e.error, vp, cr);
4568 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4569 		return (e.error);
4570 	}
4571 
4572 	resop = &res.array[1];	/* readlink res */
4573 	lr_res = &resop->nfs_resop4_u.opreadlink;
4574 
4575 	/*
4576 	 * treat symlink names as data
4577 	 */
4578 	linkdata = utf8_to_str(&lr_res->link, &len, NULL);
4579 	if (linkdata != NULL) {
4580 		int uio_len = len - 1;
4581 		/* len includes null byte, which we won't uiomove */
4582 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4583 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4584 			mutex_enter(&rp->r_statelock);
4585 			if (rp->r_symlink.contents == NULL) {
4586 				rp->r_symlink.contents = linkdata;
4587 				rp->r_symlink.len = uio_len;
4588 				rp->r_symlink.size = len;
4589 				mutex_exit(&rp->r_statelock);
4590 			} else {
4591 				mutex_exit(&rp->r_statelock);
4592 				kmem_free(linkdata, len);
4593 			}
4594 		} else {
4595 			kmem_free(linkdata, len);
4596 		}
4597 	}
4598 	if (res.status == NFS4_OK) {
4599 		resop++;	/* getattr res */
4600 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4601 	}
4602 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4603 
4604 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4605 
4606 	/*
4607 	 * The over the wire error for attempting to readlink something
4608 	 * other than a symbolic link is ENXIO.  However, we need to
4609 	 * return EINVAL instead of ENXIO, so we map it here.
4610 	 */
4611 	return (e.error == ENXIO ? EINVAL : e.error);
4612 }
4613 
4614 /*
4615  * Flush local dirty pages to stable storage on the server.
4616  *
4617  * If FNODSYNC is specified, then there is nothing to do because
4618  * metadata changes are not cached on the client before being
4619  * sent to the server.
4620  */
4621 /* ARGSUSED */
4622 static int
4623 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
4624 {
4625 	int error;
4626 
4627 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4628 		return (0);
4629 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4630 		return (EIO);
4631 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4632 	if (!error)
4633 		error = VTOR4(vp)->r_error;
4634 	return (error);
4635 }
4636 
4637 /*
4638  * Weirdness: if the file was removed or the target of a rename
4639  * operation while it was open, it got renamed instead.  Here we
4640  * remove the renamed file.
4641  */
4642 /* ARGSUSED */
4643 void
4644 nfs4_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4645 {
4646 	rnode4_t *rp;
4647 
4648 	ASSERT(vp != DNLC_NO_VNODE);
4649 
4650 	rp = VTOR4(vp);
4651 
4652 	if (IS_SHADOW(vp, rp)) {
4653 		sv_inactive(vp);
4654 		return;
4655 	}
4656 
4657 	/*
4658 	 * If this is coming from the wrong zone, we let someone in the right
4659 	 * zone take care of it asynchronously.  We can get here due to
4660 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4661 	 * potentially turn into an expensive no-op if, for instance, v_count
4662 	 * gets incremented in the meantime, but it's still correct.
4663 	 */
4664 	if (nfs_zone() != VTOMI4(vp)->mi_zone) {
4665 		nfs4_async_inactive(vp, cr);
4666 		return;
4667 	}
4668 
4669 	/*
4670 	 * Some of the cleanup steps might require over-the-wire
4671 	 * operations.  Since VOP_INACTIVE can get called as a result of
4672 	 * other over-the-wire operations (e.g., an attribute cache update
4673 	 * can lead to a DNLC purge), doing those steps now would lead to a
4674 	 * nested call to the recovery framework, which can deadlock.  So
4675 	 * do any over-the-wire cleanups asynchronously, in a separate
4676 	 * thread.
4677 	 */
4678 
4679 	mutex_enter(&rp->r_os_lock);
4680 	mutex_enter(&rp->r_statelock);
4681 	mutex_enter(&rp->r_statev4_lock);
4682 
4683 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4684 		mutex_exit(&rp->r_statev4_lock);
4685 		mutex_exit(&rp->r_statelock);
4686 		mutex_exit(&rp->r_os_lock);
4687 		nfs4_async_inactive(vp, cr);
4688 		return;
4689 	}
4690 
4691 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4692 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4693 		mutex_exit(&rp->r_statev4_lock);
4694 		mutex_exit(&rp->r_statelock);
4695 		mutex_exit(&rp->r_os_lock);
4696 		nfs4_async_inactive(vp, cr);
4697 		return;
4698 	}
4699 
4700 	if (rp->r_unldvp != NULL) {
4701 		mutex_exit(&rp->r_statev4_lock);
4702 		mutex_exit(&rp->r_statelock);
4703 		mutex_exit(&rp->r_os_lock);
4704 		nfs4_async_inactive(vp, cr);
4705 		return;
4706 	}
4707 	mutex_exit(&rp->r_statev4_lock);
4708 	mutex_exit(&rp->r_statelock);
4709 	mutex_exit(&rp->r_os_lock);
4710 
4711 	rp4_addfree(rp, cr);
4712 }
4713 
4714 /*
4715  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4716  * various bits of state.  The caller must not refer to vp after this call.
4717  */
4718 
4719 void
4720 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4721 {
4722 	rnode4_t *rp = VTOR4(vp);
4723 	nfs4_recov_state_t recov_state;
4724 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4725 	vnode_t *unldvp;
4726 	char *unlname;
4727 	cred_t *unlcred;
4728 	COMPOUND4args_clnt args;
4729 	COMPOUND4res_clnt res, *resp;
4730 	nfs_argop4 argop[2];
4731 	int doqueue;
4732 #ifdef DEBUG
4733 	char *name;
4734 #endif
4735 
4736 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
4737 	ASSERT(!IS_SHADOW(vp, rp));
4738 
4739 #ifdef DEBUG
4740 	name = fn_name(VTOSV(vp)->sv_name);
4741 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4742 	    "release vnode %s", name));
4743 	kmem_free(name, MAXNAMELEN);
4744 #endif
4745 
4746 	if (vp->v_type == VREG) {
4747 		bool_t recov_failed = FALSE;
4748 
4749 		e.error = nfs4close_all(vp, cr);
4750 		if (e.error) {
4751 			/* Check to see if recovery failed */
4752 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4753 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4754 				recov_failed = TRUE;
4755 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4756 			if (!recov_failed) {
4757 				mutex_enter(&rp->r_statelock);
4758 				if (rp->r_flags & R4RECOVERR)
4759 					recov_failed = TRUE;
4760 				mutex_exit(&rp->r_statelock);
4761 			}
4762 			if (recov_failed) {
4763 				NFS4_DEBUG(nfs4_client_recov_debug,
4764 				    (CE_NOTE, "nfs4_inactive_otw: "
4765 				    "close failed (recovery failure)"));
4766 			}
4767 		}
4768 	}
4769 
4770 redo:
4771 	if (rp->r_unldvp == NULL) {
4772 		rp4_addfree(rp, cr);
4773 		return;
4774 	}
4775 
4776 	/*
4777 	 * Save the vnode pointer for the directory where the
4778 	 * unlinked-open file got renamed, then set it to NULL
4779 	 * to prevent another thread from getting here before
4780 	 * we're done with the remove.  While we have the
4781 	 * statelock, make local copies of the pertinent rnode
4782 	 * fields.  If we weren't to do this in an atomic way, the
4783 	 * the unl* fields could become inconsistent with respect
4784 	 * to each other due to a race condition between this
4785 	 * code and nfs_remove().  See bug report 1034328.
4786 	 */
4787 	mutex_enter(&rp->r_statelock);
4788 	if (rp->r_unldvp == NULL) {
4789 		mutex_exit(&rp->r_statelock);
4790 		rp4_addfree(rp, cr);
4791 		return;
4792 	}
4793 
4794 	unldvp = rp->r_unldvp;
4795 	rp->r_unldvp = NULL;
4796 	unlname = rp->r_unlname;
4797 	rp->r_unlname = NULL;
4798 	unlcred = rp->r_unlcred;
4799 	rp->r_unlcred = NULL;
4800 	mutex_exit(&rp->r_statelock);
4801 
4802 	/*
4803 	 * If there are any dirty pages left, then flush
4804 	 * them.  This is unfortunate because they just
4805 	 * may get thrown away during the remove operation,
4806 	 * but we have to do this for correctness.
4807 	 */
4808 	if (nfs4_has_pages(vp) &&
4809 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4810 		ASSERT(vp->v_type != VCHR);
4811 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, NULL);
4812 		if (e.error) {
4813 			mutex_enter(&rp->r_statelock);
4814 			if (!rp->r_error)
4815 				rp->r_error = e.error;
4816 			mutex_exit(&rp->r_statelock);
4817 		}
4818 	}
4819 
4820 	recov_state.rs_flags = 0;
4821 	recov_state.rs_num_retry_despite_err = 0;
4822 recov_retry_remove:
4823 	/*
4824 	 * Do the remove operation on the renamed file
4825 	 */
4826 	args.ctag = TAG_INACTIVE;
4827 
4828 	/*
4829 	 * Remove ops: putfh dir; remove
4830 	 */
4831 	args.array_len = 2;
4832 	args.array = argop;
4833 
4834 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4835 	if (e.error) {
4836 		kmem_free(unlname, MAXNAMELEN);
4837 		crfree(unlcred);
4838 		VN_RELE(unldvp);
4839 		/*
4840 		 * Try again; this time around r_unldvp will be NULL, so we'll
4841 		 * just call rp4_addfree() and return.
4842 		 */
4843 		goto redo;
4844 	}
4845 
4846 	/* putfh directory */
4847 	argop[0].argop = OP_CPUTFH;
4848 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4849 
4850 	/* remove */
4851 	argop[1].argop = OP_CREMOVE;
4852 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4853 
4854 	doqueue = 1;
4855 	resp = &res;
4856 
4857 #if 0 /* notyet */
4858 	/*
4859 	 * Can't do this yet.  We may be being called from
4860 	 * dnlc_purge_XXX while that routine is holding a
4861 	 * mutex lock to the nc_rele list.  The calls to
4862 	 * nfs3_cache_wcc_data may result in calls to
4863 	 * dnlc_purge_XXX.  This will result in a deadlock.
4864 	 */
4865 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4866 	if (e.error) {
4867 		PURGE_ATTRCACHE4(unldvp);
4868 		resp = NULL;
4869 	} else if (res.status) {
4870 		e.error = geterrno4(res.status);
4871 		PURGE_ATTRCACHE4(unldvp);
4872 		/*
4873 		 * This code is inactive right now
4874 		 * but if made active there should
4875 		 * be a nfs4_end_op() call before
4876 		 * nfs4_purge_stale_fh to avoid start_op()
4877 		 * deadlock. See BugId: 4948726
4878 		 */
4879 		nfs4_purge_stale_fh(error, unldvp, cr);
4880 	} else {
4881 		nfs_resop4 *resop;
4882 		REMOVE4res *rm_res;
4883 
4884 		resop = &res.array[1];
4885 		rm_res = &resop->nfs_resop4_u.opremove;
4886 		/*
4887 		 * Update directory cache attribute,
4888 		 * readdir and dnlc caches.
4889 		 */
4890 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4891 	}
4892 #else
4893 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4894 
4895 	PURGE_ATTRCACHE4(unldvp);
4896 #endif
4897 
4898 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4899 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4900 		    NULL, NULL, OP_REMOVE, NULL) == FALSE) {
4901 			if (!e.error)
4902 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4903 				    (caddr_t)&res);
4904 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4905 			    &recov_state, TRUE);
4906 			goto recov_retry_remove;
4907 		}
4908 	}
4909 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4910 
4911 	/*
4912 	 * Release stuff held for the remove
4913 	 */
4914 	VN_RELE(unldvp);
4915 	if (!e.error && resp)
4916 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4917 
4918 	kmem_free(unlname, MAXNAMELEN);
4919 	crfree(unlcred);
4920 	goto redo;
4921 }
4922 
4923 /*
4924  * Remote file system operations having to do with directory manipulation.
4925  */
4926 /* ARGSUSED3 */
4927 int
4928 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4929     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
4930     int *direntflags, pathname_t *realpnp)
4931 {
4932 	int error;
4933 	vnode_t *vp, *avp = NULL;
4934 	rnode4_t *drp;
4935 
4936 	*vpp = NULL;
4937 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4938 		return (EPERM);
4939 	/*
4940 	 * if LOOKUP_XATTR, must replace dvp (object) with
4941 	 * object's attrdir before continuing with lookup
4942 	 */
4943 	if (flags & LOOKUP_XATTR) {
4944 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4945 		if (error)
4946 			return (error);
4947 
4948 		dvp = avp;
4949 
4950 		/*
4951 		 * If lookup is for "", just return dvp now.  The attrdir
4952 		 * has already been activated (from nfs4lookup_xattr), and
4953 		 * the caller will RELE the original dvp -- not
4954 		 * the attrdir.  So, set vpp and return.
4955 		 * Currently, when the LOOKUP_XATTR flag is
4956 		 * passed to VOP_LOOKUP, the name is always empty, and
4957 		 * shortcircuiting here avoids 3 unneeded lock/unlock
4958 		 * pairs.
4959 		 *
4960 		 * If a non-empty name was provided, then it is the
4961 		 * attribute name, and it will be looked up below.
4962 		 */
4963 		if (*nm == '\0') {
4964 			*vpp = dvp;
4965 			return (0);
4966 		}
4967 
4968 		/*
4969 		 * The vfs layer never sends a name when asking for the
4970 		 * attrdir, so we should never get here (unless of course
4971 		 * name is passed at some time in future -- at which time
4972 		 * we'll blow up here).
4973 		 */
4974 		ASSERT(0);
4975 	}
4976 
4977 	drp = VTOR4(dvp);
4978 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4979 		return (EINTR);
4980 
4981 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
4982 	nfs_rw_exit(&drp->r_rwlock);
4983 
4984 	/*
4985 	 * If vnode is a device, create special vnode.
4986 	 */
4987 	if (!error && ISVDEV((*vpp)->v_type)) {
4988 		vp = *vpp;
4989 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
4990 		VN_RELE(vp);
4991 	}
4992 
4993 	return (error);
4994 }
4995 
4996 /* ARGSUSED */
4997 static int
4998 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
4999 {
5000 	int error;
5001 	rnode4_t *drp;
5002 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
5003 	mntinfo4_t *mi;
5004 
5005 	mi = VTOMI4(dvp);
5006 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR) &&
5007 	    !vfs_has_feature(mi->mi_vfsp, VFSFT_SYSATTR_VIEWS))
5008 		return (EINVAL);
5009 
5010 	drp = VTOR4(dvp);
5011 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
5012 		return (EINTR);
5013 
5014 	mutex_enter(&drp->r_statelock);
5015 	/*
5016 	 * If the server doesn't support xattrs just return EINVAL
5017 	 */
5018 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
5019 		mutex_exit(&drp->r_statelock);
5020 		nfs_rw_exit(&drp->r_rwlock);
5021 		return (EINVAL);
5022 	}
5023 
5024 	/*
5025 	 * If there is a cached xattr directory entry,
5026 	 * use it as long as the attributes are valid. If the
5027 	 * attributes are not valid, take the simple approach and
5028 	 * free the cached value and re-fetch a new value.
5029 	 *
5030 	 * We don't negative entry cache for now, if we did we
5031 	 * would need to check if the file has changed on every
5032 	 * lookup. But xattrs don't exist very often and failing
5033 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
5034 	 * so do an openattr over the wire for now.
5035 	 */
5036 	if (drp->r_xattr_dir != NULL) {
5037 		if (ATTRCACHE4_VALID(dvp)) {
5038 			VN_HOLD(drp->r_xattr_dir);
5039 			*vpp = drp->r_xattr_dir;
5040 			mutex_exit(&drp->r_statelock);
5041 			nfs_rw_exit(&drp->r_rwlock);
5042 			return (0);
5043 		}
5044 		VN_RELE(drp->r_xattr_dir);
5045 		drp->r_xattr_dir = NULL;
5046 	}
5047 	mutex_exit(&drp->r_statelock);
5048 
5049 	error = nfs4openattr(dvp, vpp, cflag, cr);
5050 
5051 	nfs_rw_exit(&drp->r_rwlock);
5052 
5053 	return (error);
5054 }
5055 
5056 static int
5057 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
5058 {
5059 	int error;
5060 	rnode4_t *drp;
5061 
5062 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5063 
5064 	/*
5065 	 * If lookup is for "", just return dvp.  Don't need
5066 	 * to send it over the wire, look it up in the dnlc,
5067 	 * or perform any access checks.
5068 	 */
5069 	if (*nm == '\0') {
5070 		VN_HOLD(dvp);
5071 		*vpp = dvp;
5072 		return (0);
5073 	}
5074 
5075 	/*
5076 	 * Can't do lookups in non-directories.
5077 	 */
5078 	if (dvp->v_type != VDIR)
5079 		return (ENOTDIR);
5080 
5081 	/*
5082 	 * If lookup is for ".", just return dvp.  Don't need
5083 	 * to send it over the wire or look it up in the dnlc,
5084 	 * just need to check access.
5085 	 */
5086 	if (nm[0] == '.' && nm[1] == '\0') {
5087 		error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5088 		if (error)
5089 			return (error);
5090 		VN_HOLD(dvp);
5091 		*vpp = dvp;
5092 		return (0);
5093 	}
5094 
5095 	drp = VTOR4(dvp);
5096 	if (!(drp->r_flags & R4LOOKUP)) {
5097 		mutex_enter(&drp->r_statelock);
5098 		drp->r_flags |= R4LOOKUP;
5099 		mutex_exit(&drp->r_statelock);
5100 	}
5101 
5102 	*vpp = NULL;
5103 	/*
5104 	 * Lookup this name in the DNLC.  If there is no entry
5105 	 * lookup over the wire.
5106 	 */
5107 	if (!skipdnlc)
5108 		*vpp = dnlc_lookup(dvp, nm);
5109 	if (*vpp == NULL) {
5110 		/*
5111 		 * We need to go over the wire to lookup the name.
5112 		 */
5113 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
5114 	}
5115 
5116 	/*
5117 	 * We hit on the dnlc
5118 	 */
5119 	if (*vpp != DNLC_NO_VNODE ||
5120 	    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
5121 		/*
5122 		 * But our attrs may not be valid.
5123 		 */
5124 		if (ATTRCACHE4_VALID(dvp)) {
5125 			error = nfs4_waitfor_purge_complete(dvp);
5126 			if (error) {
5127 				VN_RELE(*vpp);
5128 				*vpp = NULL;
5129 				return (error);
5130 			}
5131 
5132 			/*
5133 			 * If after the purge completes, check to make sure
5134 			 * our attrs are still valid.
5135 			 */
5136 			if (ATTRCACHE4_VALID(dvp)) {
5137 				/*
5138 				 * If we waited for a purge we may have
5139 				 * lost our vnode so look it up again.
5140 				 */
5141 				VN_RELE(*vpp);
5142 				*vpp = dnlc_lookup(dvp, nm);
5143 				if (*vpp == NULL)
5144 					return (nfs4lookupnew_otw(dvp,
5145 					    nm, vpp, cr));
5146 
5147 				/*
5148 				 * The access cache should almost always hit
5149 				 */
5150 				error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5151 
5152 				if (error) {
5153 					VN_RELE(*vpp);
5154 					*vpp = NULL;
5155 					return (error);
5156 				}
5157 				if (*vpp == DNLC_NO_VNODE) {
5158 					VN_RELE(*vpp);
5159 					*vpp = NULL;
5160 					return (ENOENT);
5161 				}
5162 				return (0);
5163 			}
5164 		}
5165 	}
5166 
5167 	ASSERT(*vpp != NULL);
5168 
5169 	/*
5170 	 * We may have gotten here we have one of the following cases:
5171 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5172 	 *		need to validate them.
5173 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5174 	 *		must validate.
5175 	 *
5176 	 * Go to the server and check if the directory has changed, if
5177 	 * it hasn't we are done and can use the dnlc entry.
5178 	 */
5179 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5180 }
5181 
5182 /*
5183  * Go to the server and check if the directory has changed, if
5184  * it hasn't we are done and can use the dnlc entry.  If it
5185  * has changed we get a new copy of its attributes and check
5186  * the access for VEXEC, then relookup the filename and
5187  * get its filehandle and attributes.
5188  *
5189  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5190  *	if the NVERIFY failed we must
5191  *		purge the caches
5192  *		cache new attributes (will set r_time_attr_inval)
5193  *		cache new access
5194  *		recheck VEXEC access
5195  *		add name to dnlc, possibly negative
5196  *		if LOOKUP succeeded
5197  *			cache new attributes
5198  *	else
5199  *		set a new r_time_attr_inval for dvp
5200  *		check to make sure we have access
5201  *
5202  * The vpp returned is the vnode passed in if the directory is valid,
5203  * a new vnode if successful lookup, or NULL on error.
5204  */
5205 static int
5206 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5207 {
5208 	COMPOUND4args_clnt args;
5209 	COMPOUND4res_clnt res;
5210 	fattr4 *ver_fattr;
5211 	fattr4_change dchange;
5212 	int32_t *ptr;
5213 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5214 	nfs_argop4 *argop;
5215 	int doqueue;
5216 	mntinfo4_t *mi;
5217 	nfs4_recov_state_t recov_state;
5218 	hrtime_t t;
5219 	int isdotdot;
5220 	vnode_t *nvp;
5221 	nfs_fh4 *fhp;
5222 	nfs4_sharedfh_t *sfhp;
5223 	nfs4_access_type_t cacc;
5224 	rnode4_t *nrp;
5225 	rnode4_t *drp = VTOR4(dvp);
5226 	nfs4_ga_res_t *garp = NULL;
5227 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5228 
5229 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5230 	ASSERT(nm != NULL);
5231 	ASSERT(nm[0] != '\0');
5232 	ASSERT(dvp->v_type == VDIR);
5233 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5234 	ASSERT(*vpp != NULL);
5235 
5236 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5237 		isdotdot = 1;
5238 		args.ctag = TAG_LOOKUP_VPARENT;
5239 	} else {
5240 		/*
5241 		 * If dvp were a stub, it should have triggered and caused
5242 		 * a mount for us to get this far.
5243 		 */
5244 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5245 
5246 		isdotdot = 0;
5247 		args.ctag = TAG_LOOKUP_VALID;
5248 	}
5249 
5250 	mi = VTOMI4(dvp);
5251 	recov_state.rs_flags = 0;
5252 	recov_state.rs_num_retry_despite_err = 0;
5253 
5254 	nvp = NULL;
5255 
5256 	/* Save the original mount point security information */
5257 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5258 
5259 recov_retry:
5260 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5261 	    &recov_state, NULL);
5262 	if (e.error) {
5263 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5264 		VN_RELE(*vpp);
5265 		*vpp = NULL;
5266 		return (e.error);
5267 	}
5268 
5269 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5270 
5271 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5272 	args.array_len = 7;
5273 	args.array = argop;
5274 
5275 	/* 0. putfh file */
5276 	argop[0].argop = OP_CPUTFH;
5277 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5278 
5279 	/* 1. nverify the change info */
5280 	argop[1].argop = OP_NVERIFY;
5281 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5282 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5283 	ver_fattr->attrlist4 = (char *)&dchange;
5284 	ptr = (int32_t *)&dchange;
5285 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5286 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5287 
5288 	/* 2. getattr directory */
5289 	argop[2].argop = OP_GETATTR;
5290 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5291 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5292 
5293 	/* 3. access directory */
5294 	argop[3].argop = OP_ACCESS;
5295 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5296 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5297 
5298 	/* 4. lookup name */
5299 	if (isdotdot) {
5300 		argop[4].argop = OP_LOOKUPP;
5301 	} else {
5302 		argop[4].argop = OP_CLOOKUP;
5303 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5304 	}
5305 
5306 	/* 5. resulting file handle */
5307 	argop[5].argop = OP_GETFH;
5308 
5309 	/* 6. resulting file attributes */
5310 	argop[6].argop = OP_GETATTR;
5311 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5312 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5313 
5314 	doqueue = 1;
5315 	t = gethrtime();
5316 
5317 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5318 
5319 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5320 		/*
5321 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5322 		 * from this thread, do not go thru the recovery thread since
5323 		 * we need the nm information.
5324 		 *
5325 		 * Not doing dotdot case because there is no specification
5326 		 * for (PUTFH, SECINFO "..") yet.
5327 		 */
5328 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5329 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5330 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5331 				    &recov_state, FALSE);
5332 			else
5333 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5334 				    &recov_state, TRUE);
5335 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5336 			kmem_free(argop, argoplist_size);
5337 			if (!e.error)
5338 				goto recov_retry;
5339 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5340 			VN_RELE(*vpp);
5341 			*vpp = NULL;
5342 			return (e.error);
5343 		}
5344 
5345 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5346 		    OP_LOOKUP, NULL) == FALSE) {
5347 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5348 			    &recov_state, TRUE);
5349 
5350 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5351 			kmem_free(argop, argoplist_size);
5352 			goto recov_retry;
5353 		}
5354 	}
5355 
5356 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5357 
5358 	if (e.error || res.array_len == 0) {
5359 		/*
5360 		 * If e.error isn't set, then reply has no ops (or we couldn't
5361 		 * be here).  The only legal way to reply without an op array
5362 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5363 		 * be in the reply for all other status values.
5364 		 *
5365 		 * For valid replies without an ops array, return ENOTSUP
5366 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5367 		 * return EIO -- don't trust status.
5368 		 */
5369 		if (e.error == 0)
5370 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5371 			    ENOTSUP : EIO;
5372 		VN_RELE(*vpp);
5373 		*vpp = NULL;
5374 		kmem_free(argop, argoplist_size);
5375 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5376 		return (e.error);
5377 	}
5378 
5379 	if (res.status != NFS4ERR_SAME) {
5380 		e.error = geterrno4(res.status);
5381 
5382 		/*
5383 		 * The NVERIFY "failed" so the directory has changed
5384 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5385 		 * cleanly.
5386 		 */
5387 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5388 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5389 			nfs4_purge_stale_fh(e.error, dvp, cr);
5390 			VN_RELE(*vpp);
5391 			*vpp = NULL;
5392 			goto exit;
5393 		}
5394 
5395 		/*
5396 		 * We know the NVERIFY "failed" so we must:
5397 		 *	purge the caches (access and indirectly dnlc if needed)
5398 		 */
5399 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5400 
5401 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5402 			nfs4_purge_stale_fh(e.error, dvp, cr);
5403 			VN_RELE(*vpp);
5404 			*vpp = NULL;
5405 			goto exit;
5406 		}
5407 
5408 		/*
5409 		 * Install new cached attributes for the directory
5410 		 */
5411 		nfs4_attr_cache(dvp,
5412 		    &res.array[2].nfs_resop4_u.opgetattr.ga_res,
5413 		    t, cr, FALSE, NULL);
5414 
5415 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5416 			nfs4_purge_stale_fh(e.error, dvp, cr);
5417 			VN_RELE(*vpp);
5418 			*vpp = NULL;
5419 			e.error = geterrno4(res.status);
5420 			goto exit;
5421 		}
5422 
5423 		/*
5424 		 * Now we know the directory is valid,
5425 		 * cache new directory access
5426 		 */
5427 		nfs4_access_cache(drp,
5428 		    args.array[3].nfs_argop4_u.opaccess.access,
5429 		    res.array[3].nfs_resop4_u.opaccess.access, cr);
5430 
5431 		/*
5432 		 * recheck VEXEC access
5433 		 */
5434 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5435 		if (cacc != NFS4_ACCESS_ALLOWED) {
5436 			/*
5437 			 * Directory permissions might have been revoked
5438 			 */
5439 			if (cacc == NFS4_ACCESS_DENIED) {
5440 				e.error = EACCES;
5441 				VN_RELE(*vpp);
5442 				*vpp = NULL;
5443 				goto exit;
5444 			}
5445 
5446 			/*
5447 			 * Somehow we must not have asked for enough
5448 			 * so try a singleton ACCESS, should never happen.
5449 			 */
5450 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5451 			if (e.error) {
5452 				VN_RELE(*vpp);
5453 				*vpp = NULL;
5454 				goto exit;
5455 			}
5456 		}
5457 
5458 		e.error = geterrno4(res.status);
5459 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5460 			/*
5461 			 * The lookup failed, probably no entry
5462 			 */
5463 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5464 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5465 			} else {
5466 				/*
5467 				 * Might be some other error, so remove
5468 				 * the dnlc entry to make sure we start all
5469 				 * over again, next time.
5470 				 */
5471 				dnlc_remove(dvp, nm);
5472 			}
5473 			VN_RELE(*vpp);
5474 			*vpp = NULL;
5475 			goto exit;
5476 		}
5477 
5478 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5479 			/*
5480 			 * The file exists but we can't get its fh for
5481 			 * some unknown reason.  Remove it from the dnlc
5482 			 * and error out to be safe.
5483 			 */
5484 			dnlc_remove(dvp, nm);
5485 			VN_RELE(*vpp);
5486 			*vpp = NULL;
5487 			goto exit;
5488 		}
5489 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5490 		if (fhp->nfs_fh4_len == 0) {
5491 			/*
5492 			 * The file exists but a bogus fh
5493 			 * some unknown reason.  Remove it from the dnlc
5494 			 * and error out to be safe.
5495 			 */
5496 			e.error = ENOENT;
5497 			dnlc_remove(dvp, nm);
5498 			VN_RELE(*vpp);
5499 			*vpp = NULL;
5500 			goto exit;
5501 		}
5502 		sfhp = sfh4_get(fhp, mi);
5503 
5504 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5505 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5506 
5507 		/*
5508 		 * Make the new rnode
5509 		 */
5510 		if (isdotdot) {
5511 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5512 			if (e.error) {
5513 				sfh4_rele(&sfhp);
5514 				VN_RELE(*vpp);
5515 				*vpp = NULL;
5516 				goto exit;
5517 			}
5518 			/*
5519 			 * XXX if nfs4_make_dotdot uses an existing rnode
5520 			 * XXX it doesn't update the attributes.
5521 			 * XXX for now just save them again to save an OTW
5522 			 */
5523 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5524 		} else {
5525 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5526 			    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
5527 			/*
5528 			 * If v_type == VNON, then garp was NULL because
5529 			 * the last op in the compound failed and makenfs4node
5530 			 * could not find the vnode for sfhp. It created
5531 			 * a new vnode, so we have nothing to purge here.
5532 			 */
5533 			if (nvp->v_type == VNON) {
5534 				vattr_t vattr;
5535 
5536 				vattr.va_mask = AT_TYPE;
5537 				/*
5538 				 * N.B. We've already called nfs4_end_fop above.
5539 				 */
5540 				e.error = nfs4getattr(nvp, &vattr, cr);
5541 				if (e.error) {
5542 					sfh4_rele(&sfhp);
5543 					VN_RELE(*vpp);
5544 					*vpp = NULL;
5545 					VN_RELE(nvp);
5546 					goto exit;
5547 				}
5548 				nvp->v_type = vattr.va_type;
5549 			}
5550 		}
5551 		sfh4_rele(&sfhp);
5552 
5553 		nrp = VTOR4(nvp);
5554 		mutex_enter(&nrp->r_statev4_lock);
5555 		if (!nrp->created_v4) {
5556 			mutex_exit(&nrp->r_statev4_lock);
5557 			dnlc_update(dvp, nm, nvp);
5558 		} else
5559 			mutex_exit(&nrp->r_statev4_lock);
5560 
5561 		VN_RELE(*vpp);
5562 		*vpp = nvp;
5563 	} else {
5564 		hrtime_t now;
5565 		hrtime_t delta = 0;
5566 
5567 		e.error = 0;
5568 
5569 		/*
5570 		 * Because the NVERIFY "succeeded" we know that the
5571 		 * directory attributes are still valid
5572 		 * so update r_time_attr_inval
5573 		 */
5574 		now = gethrtime();
5575 		mutex_enter(&drp->r_statelock);
5576 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5577 			delta = now - drp->r_time_attr_saved;
5578 			if (delta < mi->mi_acdirmin)
5579 				delta = mi->mi_acdirmin;
5580 			else if (delta > mi->mi_acdirmax)
5581 				delta = mi->mi_acdirmax;
5582 		}
5583 		drp->r_time_attr_inval = now + delta;
5584 		mutex_exit(&drp->r_statelock);
5585 		dnlc_update(dvp, nm, *vpp);
5586 
5587 		/*
5588 		 * Even though we have a valid directory attr cache
5589 		 * and dnlc entry, we may not have access.
5590 		 * This should almost always hit the cache.
5591 		 */
5592 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5593 		if (e.error) {
5594 			VN_RELE(*vpp);
5595 			*vpp = NULL;
5596 		}
5597 
5598 		if (*vpp == DNLC_NO_VNODE) {
5599 			VN_RELE(*vpp);
5600 			*vpp = NULL;
5601 			e.error = ENOENT;
5602 		}
5603 	}
5604 
5605 exit:
5606 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5607 	kmem_free(argop, argoplist_size);
5608 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5609 	return (e.error);
5610 }
5611 
5612 /*
5613  * We need to go over the wire to lookup the name, but
5614  * while we are there verify the directory has not
5615  * changed but if it has, get new attributes and check access
5616  *
5617  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5618  *					NVERIFY GETATTR ACCESS
5619  *
5620  * With the results:
5621  *	if the NVERIFY failed we must purge the caches, add new attributes,
5622  *		and cache new access.
5623  *	set a new r_time_attr_inval
5624  *	add name to dnlc, possibly negative
5625  *	if LOOKUP succeeded
5626  *		cache new attributes
5627  */
5628 static int
5629 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5630 {
5631 	COMPOUND4args_clnt args;
5632 	COMPOUND4res_clnt res;
5633 	fattr4 *ver_fattr;
5634 	fattr4_change dchange;
5635 	int32_t *ptr;
5636 	nfs4_ga_res_t *garp = NULL;
5637 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5638 	nfs_argop4 *argop;
5639 	int doqueue;
5640 	mntinfo4_t *mi;
5641 	nfs4_recov_state_t recov_state;
5642 	hrtime_t t;
5643 	int isdotdot;
5644 	vnode_t *nvp;
5645 	nfs_fh4 *fhp;
5646 	nfs4_sharedfh_t *sfhp;
5647 	nfs4_access_type_t cacc;
5648 	rnode4_t *nrp;
5649 	rnode4_t *drp = VTOR4(dvp);
5650 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5651 
5652 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5653 	ASSERT(nm != NULL);
5654 	ASSERT(nm[0] != '\0');
5655 	ASSERT(dvp->v_type == VDIR);
5656 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5657 	ASSERT(*vpp == NULL);
5658 
5659 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5660 		isdotdot = 1;
5661 		args.ctag = TAG_LOOKUP_PARENT;
5662 	} else {
5663 		/*
5664 		 * If dvp were a stub, it should have triggered and caused
5665 		 * a mount for us to get this far.
5666 		 */
5667 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5668 
5669 		isdotdot = 0;
5670 		args.ctag = TAG_LOOKUP;
5671 	}
5672 
5673 	mi = VTOMI4(dvp);
5674 	recov_state.rs_flags = 0;
5675 	recov_state.rs_num_retry_despite_err = 0;
5676 
5677 	nvp = NULL;
5678 
5679 	/* Save the original mount point security information */
5680 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5681 
5682 recov_retry:
5683 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5684 	    &recov_state, NULL);
5685 	if (e.error) {
5686 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5687 		return (e.error);
5688 	}
5689 
5690 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5691 
5692 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5693 	args.array_len = 9;
5694 	args.array = argop;
5695 
5696 	/* 0. putfh file */
5697 	argop[0].argop = OP_CPUTFH;
5698 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5699 
5700 	/* 1. savefh for the nverify */
5701 	argop[1].argop = OP_SAVEFH;
5702 
5703 	/* 2. lookup name */
5704 	if (isdotdot) {
5705 		argop[2].argop = OP_LOOKUPP;
5706 	} else {
5707 		argop[2].argop = OP_CLOOKUP;
5708 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5709 	}
5710 
5711 	/* 3. resulting file handle */
5712 	argop[3].argop = OP_GETFH;
5713 
5714 	/* 4. resulting file attributes */
5715 	argop[4].argop = OP_GETATTR;
5716 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5717 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5718 
5719 	/* 5. restorefh back the directory for the nverify */
5720 	argop[5].argop = OP_RESTOREFH;
5721 
5722 	/* 6. nverify the change info */
5723 	argop[6].argop = OP_NVERIFY;
5724 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5725 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5726 	ver_fattr->attrlist4 = (char *)&dchange;
5727 	ptr = (int32_t *)&dchange;
5728 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5729 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5730 
5731 	/* 7. getattr directory */
5732 	argop[7].argop = OP_GETATTR;
5733 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5734 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5735 
5736 	/* 8. access directory */
5737 	argop[8].argop = OP_ACCESS;
5738 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5739 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5740 
5741 	doqueue = 1;
5742 	t = gethrtime();
5743 
5744 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5745 
5746 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5747 		/*
5748 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5749 		 * from this thread, do not go thru the recovery thread since
5750 		 * we need the nm information.
5751 		 *
5752 		 * Not doing dotdot case because there is no specification
5753 		 * for (PUTFH, SECINFO "..") yet.
5754 		 */
5755 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5756 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5757 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5758 				    &recov_state, FALSE);
5759 			else
5760 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5761 				    &recov_state, TRUE);
5762 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5763 			kmem_free(argop, argoplist_size);
5764 			if (!e.error)
5765 				goto recov_retry;
5766 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5767 			return (e.error);
5768 		}
5769 
5770 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5771 		    OP_LOOKUP, NULL) == FALSE) {
5772 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5773 			    &recov_state, TRUE);
5774 
5775 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5776 			kmem_free(argop, argoplist_size);
5777 			goto recov_retry;
5778 		}
5779 	}
5780 
5781 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5782 
5783 	if (e.error || res.array_len == 0) {
5784 		/*
5785 		 * If e.error isn't set, then reply has no ops (or we couldn't
5786 		 * be here).  The only legal way to reply without an op array
5787 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5788 		 * be in the reply for all other status values.
5789 		 *
5790 		 * For valid replies without an ops array, return ENOTSUP
5791 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5792 		 * return EIO -- don't trust status.
5793 		 */
5794 		if (e.error == 0)
5795 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5796 			    ENOTSUP : EIO;
5797 
5798 		kmem_free(argop, argoplist_size);
5799 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5800 		return (e.error);
5801 	}
5802 
5803 	e.error = geterrno4(res.status);
5804 
5805 	/*
5806 	 * The PUTFH and SAVEFH may have failed.
5807 	 */
5808 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5809 	    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5810 		nfs4_purge_stale_fh(e.error, dvp, cr);
5811 		goto exit;
5812 	}
5813 
5814 	/*
5815 	 * Check if the file exists, if it does delay entering
5816 	 * into the dnlc until after we update the directory
5817 	 * attributes so we don't cause it to get purged immediately.
5818 	 */
5819 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5820 		/*
5821 		 * The lookup failed, probably no entry
5822 		 */
5823 		if (e.error == ENOENT && nfs4_lookup_neg_cache)
5824 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5825 		goto exit;
5826 	}
5827 
5828 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5829 		/*
5830 		 * The file exists but we can't get its fh for
5831 		 * some unknown reason. Error out to be safe.
5832 		 */
5833 		goto exit;
5834 	}
5835 
5836 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5837 	if (fhp->nfs_fh4_len == 0) {
5838 		/*
5839 		 * The file exists but a bogus fh
5840 		 * some unknown reason.  Error out to be safe.
5841 		 */
5842 		e.error = EIO;
5843 		goto exit;
5844 	}
5845 	sfhp = sfh4_get(fhp, mi);
5846 
5847 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5848 		sfh4_rele(&sfhp);
5849 		goto exit;
5850 	}
5851 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5852 
5853 	/*
5854 	 * The RESTOREFH may have failed
5855 	 */
5856 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5857 		sfh4_rele(&sfhp);
5858 		e.error = EIO;
5859 		goto exit;
5860 	}
5861 
5862 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5863 		/*
5864 		 * First make sure the NVERIFY failed as we expected,
5865 		 * if it didn't then be conservative and error out
5866 		 * as we can't trust the directory.
5867 		 */
5868 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5869 			sfh4_rele(&sfhp);
5870 			e.error = EIO;
5871 			goto exit;
5872 		}
5873 
5874 		/*
5875 		 * We know the NVERIFY "failed" so the directory has changed,
5876 		 * so we must:
5877 		 *	purge the caches (access and indirectly dnlc if needed)
5878 		 */
5879 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5880 
5881 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5882 			sfh4_rele(&sfhp);
5883 			goto exit;
5884 		}
5885 		nfs4_attr_cache(dvp,
5886 		    &res.array[7].nfs_resop4_u.opgetattr.ga_res,
5887 		    t, cr, FALSE, NULL);
5888 
5889 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5890 			nfs4_purge_stale_fh(e.error, dvp, cr);
5891 			sfh4_rele(&sfhp);
5892 			e.error = geterrno4(res.status);
5893 			goto exit;
5894 		}
5895 
5896 		/*
5897 		 * Now we know the directory is valid,
5898 		 * cache new directory access
5899 		 */
5900 		nfs4_access_cache(drp,
5901 		    args.array[8].nfs_argop4_u.opaccess.access,
5902 		    res.array[8].nfs_resop4_u.opaccess.access, cr);
5903 
5904 		/*
5905 		 * recheck VEXEC access
5906 		 */
5907 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5908 		if (cacc != NFS4_ACCESS_ALLOWED) {
5909 			/*
5910 			 * Directory permissions might have been revoked
5911 			 */
5912 			if (cacc == NFS4_ACCESS_DENIED) {
5913 				sfh4_rele(&sfhp);
5914 				e.error = EACCES;
5915 				goto exit;
5916 			}
5917 
5918 			/*
5919 			 * Somehow we must not have asked for enough
5920 			 * so try a singleton ACCESS should never happen
5921 			 */
5922 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5923 			if (e.error) {
5924 				sfh4_rele(&sfhp);
5925 				goto exit;
5926 			}
5927 		}
5928 
5929 		e.error = geterrno4(res.status);
5930 	} else {
5931 		hrtime_t now;
5932 		hrtime_t delta = 0;
5933 
5934 		e.error = 0;
5935 
5936 		/*
5937 		 * Because the NVERIFY "succeeded" we know that the
5938 		 * directory attributes are still valid
5939 		 * so update r_time_attr_inval
5940 		 */
5941 		now = gethrtime();
5942 		mutex_enter(&drp->r_statelock);
5943 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5944 			delta = now - drp->r_time_attr_saved;
5945 			if (delta < mi->mi_acdirmin)
5946 				delta = mi->mi_acdirmin;
5947 			else if (delta > mi->mi_acdirmax)
5948 				delta = mi->mi_acdirmax;
5949 		}
5950 		drp->r_time_attr_inval = now + delta;
5951 		mutex_exit(&drp->r_statelock);
5952 
5953 		/*
5954 		 * Even though we have a valid directory attr cache,
5955 		 * we may not have access.
5956 		 * This should almost always hit the cache.
5957 		 */
5958 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5959 		if (e.error) {
5960 			sfh4_rele(&sfhp);
5961 			goto exit;
5962 		}
5963 	}
5964 
5965 	/*
5966 	 * Now we have successfully completed the lookup, if the
5967 	 * directory has changed we now have the valid attributes.
5968 	 * We also know we have directory access.
5969 	 * Create the new rnode and insert it in the dnlc.
5970 	 */
5971 	if (isdotdot) {
5972 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5973 		if (e.error) {
5974 			sfh4_rele(&sfhp);
5975 			goto exit;
5976 		}
5977 		/*
5978 		 * XXX if nfs4_make_dotdot uses an existing rnode
5979 		 * XXX it doesn't update the attributes.
5980 		 * XXX for now just save them again to save an OTW
5981 		 */
5982 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5983 	} else {
5984 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5985 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
5986 	}
5987 	sfh4_rele(&sfhp);
5988 
5989 	nrp = VTOR4(nvp);
5990 	mutex_enter(&nrp->r_statev4_lock);
5991 	if (!nrp->created_v4) {
5992 		mutex_exit(&nrp->r_statev4_lock);
5993 		dnlc_update(dvp, nm, nvp);
5994 	} else
5995 		mutex_exit(&nrp->r_statev4_lock);
5996 
5997 	*vpp = nvp;
5998 
5999 exit:
6000 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6001 	kmem_free(argop, argoplist_size);
6002 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
6003 	return (e.error);
6004 }
6005 
6006 #ifdef DEBUG
6007 void
6008 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
6009 {
6010 	uint_t i, len;
6011 	zoneid_t zoneid = getzoneid();
6012 	char *s;
6013 
6014 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
6015 	for (i = 0; i < argcnt; i++) {
6016 		nfs_argop4 *op = &argbase[i];
6017 		switch (op->argop) {
6018 		case OP_CPUTFH:
6019 		case OP_PUTFH:
6020 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
6021 			break;
6022 		case OP_PUTROOTFH:
6023 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
6024 			break;
6025 		case OP_CLOOKUP:
6026 			s = op->nfs_argop4_u.opclookup.cname;
6027 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6028 			break;
6029 		case OP_LOOKUP:
6030 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
6031 			    &len, NULL);
6032 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6033 			kmem_free(s, len);
6034 			break;
6035 		case OP_LOOKUPP:
6036 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
6037 			break;
6038 		case OP_GETFH:
6039 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
6040 			break;
6041 		case OP_GETATTR:
6042 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
6043 			break;
6044 		case OP_OPENATTR:
6045 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
6046 			break;
6047 		default:
6048 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
6049 			    op->argop);
6050 			break;
6051 		}
6052 	}
6053 }
6054 #endif
6055 
6056 /*
6057  * nfs4lookup_setup - constructs a multi-lookup compound request.
6058  *
6059  * Given the path "nm1/nm2/.../nmn", the following compound requests
6060  * may be created:
6061  *
6062  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
6063  * is faster, for now.
6064  *
6065  * l4_getattrs indicates the type of compound requested.
6066  *
6067  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
6068  *
6069  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
6070  *
6071  *   total number of ops is n + 1.
6072  *
6073  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
6074  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
6075  *      before the last component, and only get attributes
6076  *      for the last component.  Note that the second-to-last
6077  *	pathname component is XATTR_RPATH, which does NOT go
6078  *	over-the-wire as a lookup.
6079  *
6080  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
6081  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
6082  *
6083  *   and total number of ops is n + 5.
6084  *
6085  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
6086  *      attribute directory: create lookups plus an OPENATTR
6087  *	replacing the last lookup.  Note that the last pathname
6088  *	component is XATTR_RPATH, which does NOT go over-the-wire
6089  *	as a lookup.
6090  *
6091  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
6092  *		Openattr; Getfh; Getattr }
6093  *
6094  *   and total number of ops is n + 5.
6095  *
6096  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6097  *	nodes too.
6098  *
6099  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6100  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6101  *
6102  *   and total number of ops is 3*n + 1.
6103  *
6104  * All cases: returns the index in the arg array of the final LOOKUP op, or
6105  * -1 if no LOOKUPs were used.
6106  */
6107 int
6108 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6109 {
6110 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6111 	nfs_argop4 *argbase, *argop;
6112 	int arglen, argcnt;
6113 	int n = 1;	/* number of components */
6114 	int nga = 1;	/* number of Getattr's in request */
6115 	char c = '\0', *s, *p;
6116 	int lookup_idx = -1;
6117 	int argoplist_size;
6118 
6119 	/* set lookuparg response result to 0 */
6120 	lookupargp->resp->status = NFS4_OK;
6121 
6122 	/* skip leading "/" or "." e.g. ".//./" if there is */
6123 	for (; ; nm++) {
6124 		if (*nm != '/' && *nm != '.')
6125 			break;
6126 
6127 		/* ".." is counted as 1 component */
6128 		if (*nm == '.' && *(nm + 1) != '/')
6129 			break;
6130 	}
6131 
6132 	/*
6133 	 * Find n = number of components - nm must be null terminated
6134 	 * Skip "." components.
6135 	 */
6136 	if (*nm != '\0')
6137 		for (n = 1, s = nm; *s != '\0'; s++) {
6138 			if ((*s == '/') && (*(s + 1) != '/') &&
6139 			    (*(s + 1) != '\0') &&
6140 			    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6141 			    *(s + 2) == '\0')))
6142 				n++;
6143 		}
6144 	else
6145 		n = 0;
6146 
6147 	/*
6148 	 * nga is number of components that need Getfh+Getattr
6149 	 */
6150 	switch (l4_getattrs) {
6151 	case LKP4_NO_ATTRIBUTES:
6152 		nga = 0;
6153 		break;
6154 	case LKP4_ALL_ATTRIBUTES:
6155 		nga = n;
6156 		/*
6157 		 * Always have at least 1 getfh, getattr pair
6158 		 */
6159 		if (nga == 0)
6160 			nga++;
6161 		break;
6162 	case LKP4_LAST_ATTRDIR:
6163 	case LKP4_LAST_NAMED_ATTR:
6164 		nga = n+1;
6165 		break;
6166 	}
6167 
6168 	/*
6169 	 * If change to use the filehandle attr instead of getfh
6170 	 * the following line can be deleted.
6171 	 */
6172 	nga *= 2;
6173 
6174 	/*
6175 	 * calculate number of ops in request as
6176 	 * header + trailer + lookups + getattrs
6177 	 */
6178 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6179 
6180 	argoplist_size = arglen * sizeof (nfs_argop4);
6181 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6182 	lookupargp->argsp->array = argop;
6183 
6184 	argcnt = lookupargp->header_len;
6185 	argop += argcnt;
6186 
6187 	/*
6188 	 * loop and create a lookup op and possibly getattr/getfh for
6189 	 * each component. Skip "." components.
6190 	 */
6191 	for (s = nm; *s != '\0'; s = p) {
6192 		/*
6193 		 * Set up a pathname struct for each component if needed
6194 		 */
6195 		while (*s == '/')
6196 			s++;
6197 		if (*s == '\0')
6198 			break;
6199 
6200 		for (p = s; (*p != '/') && (*p != '\0'); p++)
6201 			;
6202 		c = *p;
6203 		*p = '\0';
6204 
6205 		if (s[0] == '.' && s[1] == '\0') {
6206 			*p = c;
6207 			continue;
6208 		}
6209 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6210 		    strcmp(s, XATTR_RPATH) == 0) {
6211 			/* getfh XXX may not be needed in future */
6212 			argop->argop = OP_GETFH;
6213 			argop++;
6214 			argcnt++;
6215 
6216 			/* getattr */
6217 			argop->argop = OP_GETATTR;
6218 			argop->nfs_argop4_u.opgetattr.attr_request =
6219 			    lookupargp->ga_bits;
6220 			argop->nfs_argop4_u.opgetattr.mi =
6221 			    lookupargp->mi;
6222 			argop++;
6223 			argcnt++;
6224 
6225 			/* openattr */
6226 			argop->argop = OP_OPENATTR;
6227 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6228 		    strcmp(s, XATTR_RPATH) == 0) {
6229 			/* openattr */
6230 			argop->argop = OP_OPENATTR;
6231 			argop++;
6232 			argcnt++;
6233 
6234 			/* getfh XXX may not be needed in future */
6235 			argop->argop = OP_GETFH;
6236 			argop++;
6237 			argcnt++;
6238 
6239 			/* getattr */
6240 			argop->argop = OP_GETATTR;
6241 			argop->nfs_argop4_u.opgetattr.attr_request =
6242 			    lookupargp->ga_bits;
6243 			argop->nfs_argop4_u.opgetattr.mi =
6244 			    lookupargp->mi;
6245 			argop++;
6246 			argcnt++;
6247 			*p = c;
6248 			continue;
6249 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6250 			/* lookupp */
6251 			argop->argop = OP_LOOKUPP;
6252 		} else {
6253 			/* lookup */
6254 			argop->argop = OP_LOOKUP;
6255 			(void) str_to_utf8(s,
6256 			    &argop->nfs_argop4_u.oplookup.objname);
6257 		}
6258 		lookup_idx = argcnt;
6259 		argop++;
6260 		argcnt++;
6261 
6262 		*p = c;
6263 
6264 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6265 			/* getfh XXX may not be needed in future */
6266 			argop->argop = OP_GETFH;
6267 			argop++;
6268 			argcnt++;
6269 
6270 			/* getattr */
6271 			argop->argop = OP_GETATTR;
6272 			argop->nfs_argop4_u.opgetattr.attr_request =
6273 			    lookupargp->ga_bits;
6274 			argop->nfs_argop4_u.opgetattr.mi =
6275 			    lookupargp->mi;
6276 			argop++;
6277 			argcnt++;
6278 		}
6279 	}
6280 
6281 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6282 	    ((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6283 		if (needgetfh) {
6284 			/* stick in a post-lookup getfh */
6285 			argop->argop = OP_GETFH;
6286 			argcnt++;
6287 			argop++;
6288 		}
6289 		/* post-lookup getattr */
6290 		argop->argop = OP_GETATTR;
6291 		argop->nfs_argop4_u.opgetattr.attr_request =
6292 		    lookupargp->ga_bits;
6293 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6294 		argcnt++;
6295 	}
6296 	argcnt += lookupargp->trailer_len;	/* actual op count */
6297 	lookupargp->argsp->array_len = argcnt;
6298 	lookupargp->arglen = arglen;
6299 
6300 #ifdef DEBUG
6301 	if (nfs4_client_lookup_debug)
6302 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6303 #endif
6304 
6305 	return (lookup_idx);
6306 }
6307 
6308 static int
6309 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6310 {
6311 	COMPOUND4args_clnt	args;
6312 	COMPOUND4res_clnt	res;
6313 	GETFH4res	*gf_res = NULL;
6314 	nfs_argop4	argop[4];
6315 	nfs_resop4	*resop = NULL;
6316 	nfs4_sharedfh_t *sfhp;
6317 	hrtime_t t;
6318 	nfs4_error_t	e;
6319 
6320 	rnode4_t	*drp;
6321 	int		doqueue = 1;
6322 	vnode_t		*vp;
6323 	int		needrecov = 0;
6324 	nfs4_recov_state_t recov_state;
6325 
6326 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6327 
6328 	*avp = NULL;
6329 	recov_state.rs_flags = 0;
6330 	recov_state.rs_num_retry_despite_err = 0;
6331 
6332 recov_retry:
6333 	/* COMPOUND: putfh, openattr, getfh, getattr */
6334 	args.array_len = 4;
6335 	args.array = argop;
6336 	args.ctag = TAG_OPENATTR;
6337 
6338 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6339 	if (e.error)
6340 		return (e.error);
6341 
6342 	drp = VTOR4(dvp);
6343 
6344 	/* putfh */
6345 	argop[0].argop = OP_CPUTFH;
6346 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6347 
6348 	/* openattr */
6349 	argop[1].argop = OP_OPENATTR;
6350 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6351 
6352 	/* getfh */
6353 	argop[2].argop = OP_GETFH;
6354 
6355 	/* getattr */
6356 	argop[3].argop = OP_GETATTR;
6357 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6358 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6359 
6360 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6361 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6362 	    rnode4info(drp)));
6363 
6364 	t = gethrtime();
6365 
6366 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6367 
6368 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6369 	if (needrecov) {
6370 		bool_t abort;
6371 
6372 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6373 		    "nfs4openattr: initiating recovery\n"));
6374 
6375 		abort = nfs4_start_recovery(&e,
6376 		    VTOMI4(dvp), dvp, NULL, NULL, NULL,
6377 		    OP_OPENATTR, NULL);
6378 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6379 		if (!e.error) {
6380 			e.error = geterrno4(res.status);
6381 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6382 		}
6383 		if (abort == FALSE)
6384 			goto recov_retry;
6385 		return (e.error);
6386 	}
6387 
6388 	if (e.error) {
6389 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6390 		return (e.error);
6391 	}
6392 
6393 	if (res.status) {
6394 		/*
6395 		 * If OTW errro is NOTSUPP, then it should be
6396 		 * translated to EINVAL.  All Solaris file system
6397 		 * implementations return EINVAL to the syscall layer
6398 		 * when the attrdir cannot be created due to an
6399 		 * implementation restriction or noxattr mount option.
6400 		 */
6401 		if (res.status == NFS4ERR_NOTSUPP) {
6402 			mutex_enter(&drp->r_statelock);
6403 			if (drp->r_xattr_dir)
6404 				VN_RELE(drp->r_xattr_dir);
6405 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6406 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6407 			mutex_exit(&drp->r_statelock);
6408 
6409 			e.error = EINVAL;
6410 		} else {
6411 			e.error = geterrno4(res.status);
6412 		}
6413 
6414 		if (e.error) {
6415 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6416 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6417 			    needrecov);
6418 			return (e.error);
6419 		}
6420 	}
6421 
6422 	resop = &res.array[0];  /* putfh res */
6423 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6424 
6425 	resop = &res.array[1];  /* openattr res */
6426 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6427 
6428 	resop = &res.array[2];  /* getfh res */
6429 	gf_res = &resop->nfs_resop4_u.opgetfh;
6430 	if (gf_res->object.nfs_fh4_len == 0) {
6431 		*avp = NULL;
6432 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6433 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6434 		return (ENOENT);
6435 	}
6436 
6437 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6438 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6439 	    dvp->v_vfsp, t, cr, dvp,
6440 	    fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH, sfhp));
6441 	sfh4_rele(&sfhp);
6442 
6443 	if (e.error)
6444 		PURGE_ATTRCACHE4(vp);
6445 
6446 	mutex_enter(&vp->v_lock);
6447 	vp->v_flag |= V_XATTRDIR;
6448 	mutex_exit(&vp->v_lock);
6449 
6450 	*avp = vp;
6451 
6452 	mutex_enter(&drp->r_statelock);
6453 	if (drp->r_xattr_dir)
6454 		VN_RELE(drp->r_xattr_dir);
6455 	VN_HOLD(vp);
6456 	drp->r_xattr_dir = vp;
6457 
6458 	/*
6459 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6460 	 * NULL.  xattrs could be created at any time, and we have no
6461 	 * way to update pc4_xattr_exists in the base object if/when
6462 	 * it happens.
6463 	 */
6464 	drp->r_pathconf.pc4_xattr_valid = 0;
6465 
6466 	mutex_exit(&drp->r_statelock);
6467 
6468 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6469 
6470 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6471 
6472 	return (0);
6473 }
6474 
6475 /* ARGSUSED */
6476 static int
6477 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6478 	int mode, vnode_t **vpp, cred_t *cr, int flags, caller_context_t *ct,
6479 	vsecattr_t *vsecp)
6480 {
6481 	int error;
6482 	vnode_t *vp = NULL;
6483 	rnode4_t *rp;
6484 	struct vattr vattr;
6485 	rnode4_t *drp;
6486 	vnode_t *tempvp;
6487 	enum createmode4 createmode;
6488 	bool_t must_trunc = FALSE;
6489 	int	truncating = 0;
6490 
6491 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6492 		return (EPERM);
6493 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6494 		return (EINVAL);
6495 	}
6496 
6497 	/* . and .. have special meaning in the protocol, reject them. */
6498 
6499 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6500 		return (EISDIR);
6501 
6502 	drp = VTOR4(dvp);
6503 
6504 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6505 		return (EINTR);
6506 
6507 top:
6508 	/*
6509 	 * We make a copy of the attributes because the caller does not
6510 	 * expect us to change what va points to.
6511 	 */
6512 	vattr = *va;
6513 
6514 	/*
6515 	 * If the pathname is "", then dvp is the root vnode of
6516 	 * a remote file mounted over a local directory.
6517 	 * All that needs to be done is access
6518 	 * checking and truncation.  Note that we avoid doing
6519 	 * open w/ create because the parent directory might
6520 	 * be in pseudo-fs and the open would fail.
6521 	 */
6522 	if (*nm == '\0') {
6523 		error = 0;
6524 		VN_HOLD(dvp);
6525 		vp = dvp;
6526 		must_trunc = TRUE;
6527 	} else {
6528 		/*
6529 		 * We need to go over the wire, just to be sure whether the
6530 		 * file exists or not.  Using the DNLC can be dangerous in
6531 		 * this case when making a decision regarding existence.
6532 		 */
6533 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6534 	}
6535 
6536 	if (exclusive)
6537 		createmode = EXCLUSIVE4;
6538 	else
6539 		createmode = GUARDED4;
6540 
6541 	/*
6542 	 * error would be set if the file does not exist on the
6543 	 * server, so lets go create it.
6544 	 */
6545 	if (error) {
6546 		goto create_otw;
6547 	}
6548 
6549 	/*
6550 	 * File does exist on the server
6551 	 */
6552 	if (exclusive == EXCL)
6553 		error = EEXIST;
6554 	else if (vp->v_type == VDIR && (mode & VWRITE))
6555 		error = EISDIR;
6556 	else {
6557 		/*
6558 		 * If vnode is a device, create special vnode.
6559 		 */
6560 		if (ISVDEV(vp->v_type)) {
6561 			tempvp = vp;
6562 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6563 			VN_RELE(tempvp);
6564 		}
6565 		if (!(error = VOP_ACCESS(vp, mode, 0, cr, ct))) {
6566 			if ((vattr.va_mask & AT_SIZE) &&
6567 			    vp->v_type == VREG) {
6568 				rp = VTOR4(vp);
6569 				/*
6570 				 * Check here for large file handled
6571 				 * by LF-unaware process (as
6572 				 * ufs_create() does)
6573 				 */
6574 				if (!(flags & FOFFMAX)) {
6575 					mutex_enter(&rp->r_statelock);
6576 					if (rp->r_size > MAXOFF32_T)
6577 						error = EOVERFLOW;
6578 					mutex_exit(&rp->r_statelock);
6579 				}
6580 
6581 				/* if error is set then we need to return */
6582 				if (error) {
6583 					nfs_rw_exit(&drp->r_rwlock);
6584 					VN_RELE(vp);
6585 					return (error);
6586 				}
6587 
6588 				if (must_trunc) {
6589 					vattr.va_mask = AT_SIZE;
6590 					error = nfs4setattr(vp, &vattr, 0, cr,
6591 					    NULL);
6592 				} else {
6593 				/*
6594 				 * we know we have a regular file that already
6595 				 * exists and we may end up truncating the file
6596 				 * as a result of the open_otw, so flush out
6597 				 * any dirty pages for this file first.
6598 				 */
6599 					if (nfs4_has_pages(vp) &&
6600 					    ((rp->r_flags & R4DIRTY) ||
6601 					    rp->r_count > 0 ||
6602 					    rp->r_mapcnt > 0)) {
6603 						error = nfs4_putpage(vp,
6604 						    (offset_t)0, 0, 0, cr, ct);
6605 						if (error && (error == ENOSPC ||
6606 						    error == EDQUOT)) {
6607 							mutex_enter(
6608 							    &rp->r_statelock);
6609 							if (!rp->r_error)
6610 								rp->r_error =
6611 								    error;
6612 							mutex_exit(
6613 							    &rp->r_statelock);
6614 						}
6615 					}
6616 					vattr.va_mask = (AT_SIZE |
6617 					    AT_TYPE | AT_MODE);
6618 					vattr.va_type = VREG;
6619 					createmode = UNCHECKED4;
6620 					truncating = 1;
6621 					goto create_otw;
6622 				}
6623 			}
6624 		}
6625 	}
6626 	nfs_rw_exit(&drp->r_rwlock);
6627 	if (error) {
6628 		VN_RELE(vp);
6629 	} else {
6630 		vnode_t *tvp;
6631 		rnode4_t *trp;
6632 		/*
6633 		 * existing file got truncated, notify.
6634 		 */
6635 		tvp = vp;
6636 		if (vp->v_type == VREG) {
6637 			trp = VTOR4(vp);
6638 			if (IS_SHADOW(vp, trp))
6639 				tvp = RTOV4(trp);
6640 		}
6641 		vnevent_create(tvp, ct);
6642 		*vpp = vp;
6643 	}
6644 	return (error);
6645 
6646 create_otw:
6647 	dnlc_remove(dvp, nm);
6648 
6649 	ASSERT(vattr.va_mask & AT_TYPE);
6650 
6651 	/*
6652 	 * If not a regular file let nfs4mknod() handle it.
6653 	 */
6654 	if (vattr.va_type != VREG) {
6655 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6656 		nfs_rw_exit(&drp->r_rwlock);
6657 		return (error);
6658 	}
6659 
6660 	/*
6661 	 * It _is_ a regular file.
6662 	 */
6663 	ASSERT(vattr.va_mask & AT_MODE);
6664 	if (MANDMODE(vattr.va_mode)) {
6665 		nfs_rw_exit(&drp->r_rwlock);
6666 		return (EACCES);
6667 	}
6668 
6669 	/*
6670 	 * If this happens to be a mknod of a regular file, then flags will
6671 	 * have neither FREAD or FWRITE.  However, we must set at least one
6672 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6673 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6674 	 * set (based on openmode specified by app).
6675 	 */
6676 	if ((flags & (FREAD|FWRITE)) == 0)
6677 		flags |= (FREAD|FWRITE);
6678 
6679 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6680 
6681 	if (vp != NULL) {
6682 		/* if create was successful, throw away the file's pages */
6683 		if (!error && (vattr.va_mask & AT_SIZE))
6684 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6685 			    cr);
6686 		/* release the lookup hold */
6687 		VN_RELE(vp);
6688 		vp = NULL;
6689 	}
6690 
6691 	/*
6692 	 * validate that we opened a regular file. This handles a misbehaving
6693 	 * server that returns an incorrect FH.
6694 	 */
6695 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6696 		error = EISDIR;
6697 		VN_RELE(*vpp);
6698 	}
6699 
6700 	/*
6701 	 * If this is not an exclusive create, then the CREATE
6702 	 * request will be made with the GUARDED mode set.  This
6703 	 * means that the server will return EEXIST if the file
6704 	 * exists.  The file could exist because of a retransmitted
6705 	 * request.  In this case, we recover by starting over and
6706 	 * checking to see whether the file exists.  This second
6707 	 * time through it should and a CREATE request will not be
6708 	 * sent.
6709 	 *
6710 	 * This handles the problem of a dangling CREATE request
6711 	 * which contains attributes which indicate that the file
6712 	 * should be truncated.  This retransmitted request could
6713 	 * possibly truncate valid data in the file if not caught
6714 	 * by the duplicate request mechanism on the server or if
6715 	 * not caught by other means.  The scenario is:
6716 	 *
6717 	 * Client transmits CREATE request with size = 0
6718 	 * Client times out, retransmits request.
6719 	 * Response to the first request arrives from the server
6720 	 *  and the client proceeds on.
6721 	 * Client writes data to the file.
6722 	 * The server now processes retransmitted CREATE request
6723 	 *  and truncates file.
6724 	 *
6725 	 * The use of the GUARDED CREATE request prevents this from
6726 	 * happening because the retransmitted CREATE would fail
6727 	 * with EEXIST and would not truncate the file.
6728 	 */
6729 	if (error == EEXIST && exclusive == NONEXCL) {
6730 #ifdef DEBUG
6731 		nfs4_create_misses++;
6732 #endif
6733 		goto top;
6734 	}
6735 	nfs_rw_exit(&drp->r_rwlock);
6736 	if (truncating && !error && *vpp) {
6737 		vnode_t *tvp;
6738 		rnode4_t *trp;
6739 		/*
6740 		 * existing file got truncated, notify.
6741 		 */
6742 		tvp = *vpp;
6743 		trp = VTOR4(tvp);
6744 		if (IS_SHADOW(tvp, trp))
6745 			tvp = RTOV4(trp);
6746 		vnevent_create(tvp, ct);
6747 	}
6748 	return (error);
6749 }
6750 
6751 /*
6752  * Create compound (for mkdir, mknod, symlink):
6753  * { Putfh <dfh>; Create; Getfh; Getattr }
6754  * It's okay if setattr failed to set gid - this is not considered
6755  * an error, but purge attrs in that case.
6756  */
6757 static int
6758 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6759     vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6760 {
6761 	int need_end_op = FALSE;
6762 	COMPOUND4args_clnt args;
6763 	COMPOUND4res_clnt res, *resp = NULL;
6764 	nfs_argop4 *argop;
6765 	nfs_resop4 *resop;
6766 	int doqueue;
6767 	mntinfo4_t *mi;
6768 	rnode4_t *drp = VTOR4(dvp);
6769 	change_info4 *cinfo;
6770 	GETFH4res *gf_res;
6771 	struct vattr vattr;
6772 	vnode_t *vp;
6773 	fattr4 *crattr;
6774 	bool_t needrecov = FALSE;
6775 	nfs4_recov_state_t recov_state;
6776 	nfs4_sharedfh_t *sfhp = NULL;
6777 	hrtime_t t;
6778 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6779 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6780 	dirattr_info_t dinfo, *dinfop;
6781 	servinfo4_t *svp;
6782 	bitmap4 supp_attrs;
6783 
6784 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6785 	    type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6786 
6787 	mi = VTOMI4(dvp);
6788 
6789 	/*
6790 	 * Make sure we properly deal with setting the right gid
6791 	 * on a new directory to reflect the parent's setgid bit
6792 	 */
6793 	setgid_flag = 0;
6794 	if (type == NF4DIR) {
6795 		struct vattr dva;
6796 
6797 		va->va_mode &= ~VSGID;
6798 		dva.va_mask = AT_MODE | AT_GID;
6799 		if (VOP_GETATTR(dvp, &dva, 0, cr, NULL) == 0) {
6800 
6801 			/*
6802 			 * If the parent's directory has the setgid bit set
6803 			 * _and_ the client was able to get a valid mapping
6804 			 * for the parent dir's owner_group, we want to
6805 			 * append NVERIFY(owner_group == dva.va_gid) and
6806 			 * SETTATTR to the CREATE compound.
6807 			 */
6808 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6809 				setgid_flag = 1;
6810 				va->va_mode |= VSGID;
6811 				if (dva.va_gid != GID_NOBODY) {
6812 					va->va_mask |= AT_GID;
6813 					va->va_gid = dva.va_gid;
6814 				}
6815 			}
6816 		}
6817 	}
6818 
6819 	/*
6820 	 * Create ops:
6821 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6822 	 *	5:restorefh(dir) 6:getattr(dir)
6823 	 *
6824 	 * if (setgid)
6825 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6826 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6827 	 *	8:nverify 9:setattr
6828 	 */
6829 	if (setgid_flag) {
6830 		numops = 10;
6831 		idx_create = 1;
6832 		idx_fattr = 3;
6833 	} else {
6834 		numops = 7;
6835 		idx_create = 2;
6836 		idx_fattr = 4;
6837 	}
6838 
6839 	ASSERT(nfs_zone() == mi->mi_zone);
6840 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6841 		return (EINTR);
6842 	}
6843 	recov_state.rs_flags = 0;
6844 	recov_state.rs_num_retry_despite_err = 0;
6845 
6846 	argoplist_size = numops * sizeof (nfs_argop4);
6847 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6848 
6849 recov_retry:
6850 	if (type == NF4LNK)
6851 		args.ctag = TAG_SYMLINK;
6852 	else if (type == NF4DIR)
6853 		args.ctag = TAG_MKDIR;
6854 	else
6855 		args.ctag = TAG_MKNOD;
6856 
6857 	args.array_len = numops;
6858 	args.array = argop;
6859 
6860 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6861 		nfs_rw_exit(&drp->r_rwlock);
6862 		kmem_free(argop, argoplist_size);
6863 		return (e.error);
6864 	}
6865 	need_end_op = TRUE;
6866 
6867 
6868 	/* 0: putfh directory */
6869 	argop[0].argop = OP_CPUTFH;
6870 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6871 
6872 	/* 1/2: Create object */
6873 	argop[idx_create].argop = OP_CCREATE;
6874 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6875 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6876 	if (type == NF4LNK) {
6877 		/*
6878 		 * symlink, treat name as data
6879 		 */
6880 		ASSERT(data != NULL);
6881 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6882 		    (char *)data;
6883 	}
6884 	if (type == NF4BLK || type == NF4CHR) {
6885 		ASSERT(data != NULL);
6886 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6887 		    *((specdata4 *)data);
6888 	}
6889 
6890 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6891 
6892 	svp = drp->r_server;
6893 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6894 	supp_attrs = svp->sv_supp_attrs;
6895 	nfs_rw_exit(&svp->sv_lock);
6896 
6897 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6898 		nfs_rw_exit(&drp->r_rwlock);
6899 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6900 		e.error = EINVAL;
6901 		kmem_free(argop, argoplist_size);
6902 		return (e.error);
6903 	}
6904 
6905 	/* 2/3: getfh fh of created object */
6906 	ASSERT(idx_create + 1 == idx_fattr - 1);
6907 	argop[idx_create + 1].argop = OP_GETFH;
6908 
6909 	/* 3/4: getattr of new object */
6910 	argop[idx_fattr].argop = OP_GETATTR;
6911 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6912 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6913 
6914 	if (setgid_flag) {
6915 		vattr_t	_v;
6916 
6917 		argop[4].argop = OP_SAVEFH;
6918 
6919 		argop[5].argop = OP_CPUTFH;
6920 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6921 
6922 		argop[6].argop = OP_GETATTR;
6923 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6924 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6925 
6926 		argop[7].argop = OP_RESTOREFH;
6927 
6928 		/*
6929 		 * nverify
6930 		 *
6931 		 * XXX - Revisit the last argument to nfs4_end_op()
6932 		 *	 once 5020486 is fixed.
6933 		 */
6934 		_v.va_mask = AT_GID;
6935 		_v.va_gid = va->va_gid;
6936 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6937 		    supp_attrs)) {
6938 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6939 			nfs_rw_exit(&drp->r_rwlock);
6940 			nfs4_fattr4_free(crattr);
6941 			kmem_free(argop, argoplist_size);
6942 			return (e.error);
6943 		}
6944 
6945 		/*
6946 		 * setattr
6947 		 *
6948 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
6949 		 * so no need for stateid or flags. Also we specify NULL
6950 		 * rp since we're only interested in setting owner_group
6951 		 * attributes.
6952 		 */
6953 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
6954 		    &e.error, 0);
6955 
6956 		if (e.error) {
6957 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6958 			nfs_rw_exit(&drp->r_rwlock);
6959 			nfs4_fattr4_free(crattr);
6960 			nfs4args_verify_free(&argop[8]);
6961 			kmem_free(argop, argoplist_size);
6962 			return (e.error);
6963 		}
6964 	} else {
6965 		argop[1].argop = OP_SAVEFH;
6966 
6967 		argop[5].argop = OP_RESTOREFH;
6968 
6969 		argop[6].argop = OP_GETATTR;
6970 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6971 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6972 	}
6973 
6974 	dnlc_remove(dvp, nm);
6975 
6976 	doqueue = 1;
6977 	t = gethrtime();
6978 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
6979 
6980 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
6981 	if (e.error) {
6982 		PURGE_ATTRCACHE4(dvp);
6983 		if (!needrecov)
6984 			goto out;
6985 	}
6986 
6987 	if (needrecov) {
6988 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
6989 		    OP_CREATE, NULL) == FALSE) {
6990 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6991 			    needrecov);
6992 			need_end_op = FALSE;
6993 			nfs4_fattr4_free(crattr);
6994 			if (setgid_flag) {
6995 				nfs4args_verify_free(&argop[8]);
6996 				nfs4args_setattr_free(&argop[9]);
6997 			}
6998 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6999 			goto recov_retry;
7000 		}
7001 	}
7002 
7003 	resp = &res;
7004 
7005 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
7006 
7007 		if (res.status == NFS4ERR_BADOWNER)
7008 			nfs4_log_badowner(mi, OP_CREATE);
7009 
7010 		e.error = geterrno4(res.status);
7011 
7012 		/*
7013 		 * This check is left over from when create was implemented
7014 		 * using a setattr op (instead of createattrs).  If the
7015 		 * putfh/create/getfh failed, the error was returned.  If
7016 		 * setattr/getattr failed, we keep going.
7017 		 *
7018 		 * It might be better to get rid of the GETFH also, and just
7019 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
7020 		 * Then if any of the operations failed, we could return the
7021 		 * error now, and remove much of the error code below.
7022 		 */
7023 		if (res.array_len <= idx_fattr) {
7024 			/*
7025 			 * Either Putfh, Create or Getfh failed.
7026 			 */
7027 			PURGE_ATTRCACHE4(dvp);
7028 			/*
7029 			 * nfs4_purge_stale_fh() may generate otw calls through
7030 			 * nfs4_invalidate_pages. Hence the need to call
7031 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
7032 			 */
7033 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7034 			    needrecov);
7035 			need_end_op = FALSE;
7036 			nfs4_purge_stale_fh(e.error, dvp, cr);
7037 			goto out;
7038 		}
7039 	}
7040 
7041 	resop = &res.array[idx_create];	/* create res */
7042 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
7043 
7044 	resop = &res.array[idx_create + 1]; /* getfh res */
7045 	gf_res = &resop->nfs_resop4_u.opgetfh;
7046 
7047 	sfhp = sfh4_get(&gf_res->object, mi);
7048 	if (e.error) {
7049 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
7050 		    fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7051 		if (vp->v_type == VNON) {
7052 			vattr.va_mask = AT_TYPE;
7053 			/*
7054 			 * Need to call nfs4_end_op before nfs4getattr to avoid
7055 			 * potential nfs4_start_op deadlock. See RFE 4777612.
7056 			 */
7057 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7058 			    needrecov);
7059 			need_end_op = FALSE;
7060 			e.error = nfs4getattr(vp, &vattr, cr);
7061 			if (e.error) {
7062 				VN_RELE(vp);
7063 				*vpp = NULL;
7064 				goto out;
7065 			}
7066 			vp->v_type = vattr.va_type;
7067 		}
7068 		e.error = 0;
7069 	} else {
7070 		*vpp = vp = makenfs4node(sfhp,
7071 		    &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
7072 		    dvp->v_vfsp, t, cr,
7073 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7074 	}
7075 
7076 	/*
7077 	 * If compound succeeded, then update dir attrs
7078 	 */
7079 	if (res.status == NFS4_OK) {
7080 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
7081 		dinfo.di_cred = cr;
7082 		dinfo.di_time_call = t;
7083 		dinfop = &dinfo;
7084 	} else
7085 		dinfop = NULL;
7086 
7087 	/* Update directory cache attribute, readdir and dnlc caches */
7088 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
7089 
7090 out:
7091 	if (sfhp != NULL)
7092 		sfh4_rele(&sfhp);
7093 	nfs_rw_exit(&drp->r_rwlock);
7094 	nfs4_fattr4_free(crattr);
7095 	if (setgid_flag) {
7096 		nfs4args_verify_free(&argop[8]);
7097 		nfs4args_setattr_free(&argop[9]);
7098 	}
7099 	if (resp)
7100 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7101 	if (need_end_op)
7102 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7103 
7104 	kmem_free(argop, argoplist_size);
7105 	return (e.error);
7106 }
7107 
7108 /* ARGSUSED */
7109 static int
7110 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7111     int mode, vnode_t **vpp, cred_t *cr)
7112 {
7113 	int error;
7114 	vnode_t *vp;
7115 	nfs_ftype4 type;
7116 	specdata4 spec, *specp = NULL;
7117 
7118 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7119 
7120 	switch (va->va_type) {
7121 	case VCHR:
7122 	case VBLK:
7123 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7124 		spec.specdata1 = getmajor(va->va_rdev);
7125 		spec.specdata2 = getminor(va->va_rdev);
7126 		specp = &spec;
7127 		break;
7128 
7129 	case VFIFO:
7130 		type = NF4FIFO;
7131 		break;
7132 	case VSOCK:
7133 		type = NF4SOCK;
7134 		break;
7135 
7136 	default:
7137 		return (EINVAL);
7138 	}
7139 
7140 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7141 	if (error) {
7142 		return (error);
7143 	}
7144 
7145 	/*
7146 	 * This might not be needed any more; special case to deal
7147 	 * with problematic v2/v3 servers.  Since create was unable
7148 	 * to set group correctly, not sure what hope setattr has.
7149 	 */
7150 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7151 		va->va_mask = AT_GID;
7152 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7153 	}
7154 
7155 	/*
7156 	 * If vnode is a device create special vnode
7157 	 */
7158 	if (ISVDEV(vp->v_type)) {
7159 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7160 		VN_RELE(vp);
7161 	} else {
7162 		*vpp = vp;
7163 	}
7164 	return (error);
7165 }
7166 
7167 /*
7168  * Remove requires that the current fh be the target directory.
7169  * After the operation, the current fh is unchanged.
7170  * The compound op structure is:
7171  *      PUTFH(targetdir), REMOVE
7172  *
7173  * Weirdness: if the vnode to be removed is open
7174  * we rename it instead of removing it and nfs_inactive
7175  * will remove the new name.
7176  */
7177 /* ARGSUSED */
7178 static int
7179 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr, caller_context_t *ct, int flags)
7180 {
7181 	COMPOUND4args_clnt args;
7182 	COMPOUND4res_clnt res, *resp = NULL;
7183 	REMOVE4res *rm_res;
7184 	nfs_argop4 argop[3];
7185 	nfs_resop4 *resop;
7186 	vnode_t *vp;
7187 	char *tmpname;
7188 	int doqueue;
7189 	mntinfo4_t *mi;
7190 	rnode4_t *rp;
7191 	rnode4_t *drp;
7192 	int needrecov = 0;
7193 	nfs4_recov_state_t recov_state;
7194 	int isopen;
7195 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7196 	dirattr_info_t dinfo;
7197 
7198 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7199 		return (EPERM);
7200 	drp = VTOR4(dvp);
7201 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7202 		return (EINTR);
7203 
7204 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7205 	if (e.error) {
7206 		nfs_rw_exit(&drp->r_rwlock);
7207 		return (e.error);
7208 	}
7209 
7210 	if (vp->v_type == VDIR) {
7211 		VN_RELE(vp);
7212 		nfs_rw_exit(&drp->r_rwlock);
7213 		return (EISDIR);
7214 	}
7215 
7216 	/*
7217 	 * First just remove the entry from the name cache, as it
7218 	 * is most likely the only entry for this vp.
7219 	 */
7220 	dnlc_remove(dvp, nm);
7221 
7222 	rp = VTOR4(vp);
7223 
7224 	/*
7225 	 * For regular file types, check to see if the file is open by looking
7226 	 * at the open streams.
7227 	 * For all other types, check the reference count on the vnode.  Since
7228 	 * they are not opened OTW they never have an open stream.
7229 	 *
7230 	 * If the file is open, rename it to .nfsXXXX.
7231 	 */
7232 	if (vp->v_type != VREG) {
7233 		/*
7234 		 * If the file has a v_count > 1 then there may be more than one
7235 		 * entry in the name cache due multiple links or an open file,
7236 		 * but we don't have the real reference count so flush all
7237 		 * possible entries.
7238 		 */
7239 		if (vp->v_count > 1)
7240 			dnlc_purge_vp(vp);
7241 
7242 		/*
7243 		 * Now we have the real reference count.
7244 		 */
7245 		isopen = vp->v_count > 1;
7246 	} else {
7247 		mutex_enter(&rp->r_os_lock);
7248 		isopen = list_head(&rp->r_open_streams) != NULL;
7249 		mutex_exit(&rp->r_os_lock);
7250 	}
7251 
7252 	mutex_enter(&rp->r_statelock);
7253 	if (isopen &&
7254 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7255 		mutex_exit(&rp->r_statelock);
7256 		tmpname = newname();
7257 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr, ct);
7258 		if (e.error)
7259 			kmem_free(tmpname, MAXNAMELEN);
7260 		else {
7261 			mutex_enter(&rp->r_statelock);
7262 			if (rp->r_unldvp == NULL) {
7263 				VN_HOLD(dvp);
7264 				rp->r_unldvp = dvp;
7265 				if (rp->r_unlcred != NULL)
7266 					crfree(rp->r_unlcred);
7267 				crhold(cr);
7268 				rp->r_unlcred = cr;
7269 				rp->r_unlname = tmpname;
7270 			} else {
7271 				kmem_free(rp->r_unlname, MAXNAMELEN);
7272 				rp->r_unlname = tmpname;
7273 			}
7274 			mutex_exit(&rp->r_statelock);
7275 		}
7276 		VN_RELE(vp);
7277 		nfs_rw_exit(&drp->r_rwlock);
7278 		return (e.error);
7279 	}
7280 	/*
7281 	 * Actually remove the file/dir
7282 	 */
7283 	mutex_exit(&rp->r_statelock);
7284 
7285 	/*
7286 	 * We need to flush any dirty pages which happen to
7287 	 * be hanging around before removing the file.
7288 	 * This shouldn't happen very often since in NFSv4
7289 	 * we should be close to open consistent.
7290 	 */
7291 	if (nfs4_has_pages(vp) &&
7292 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7293 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, ct);
7294 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7295 			mutex_enter(&rp->r_statelock);
7296 			if (!rp->r_error)
7297 				rp->r_error = e.error;
7298 			mutex_exit(&rp->r_statelock);
7299 		}
7300 	}
7301 
7302 	mi = VTOMI4(dvp);
7303 
7304 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7305 	recov_state.rs_flags = 0;
7306 	recov_state.rs_num_retry_despite_err = 0;
7307 
7308 recov_retry:
7309 	/*
7310 	 * Remove ops: putfh dir; remove
7311 	 */
7312 	args.ctag = TAG_REMOVE;
7313 	args.array_len = 3;
7314 	args.array = argop;
7315 
7316 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7317 	if (e.error) {
7318 		nfs_rw_exit(&drp->r_rwlock);
7319 		VN_RELE(vp);
7320 		return (e.error);
7321 	}
7322 
7323 	/* putfh directory */
7324 	argop[0].argop = OP_CPUTFH;
7325 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7326 
7327 	/* remove */
7328 	argop[1].argop = OP_CREMOVE;
7329 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7330 
7331 	/* getattr dir */
7332 	argop[2].argop = OP_GETATTR;
7333 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7334 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7335 
7336 	doqueue = 1;
7337 	dinfo.di_time_call = gethrtime();
7338 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7339 
7340 	PURGE_ATTRCACHE4(vp);
7341 
7342 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7343 	if (e.error)
7344 		PURGE_ATTRCACHE4(dvp);
7345 
7346 	if (needrecov) {
7347 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7348 		    NULL, NULL, NULL, OP_REMOVE, NULL) == FALSE) {
7349 			if (!e.error)
7350 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7351 				    (caddr_t)&res);
7352 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7353 			    needrecov);
7354 			goto recov_retry;
7355 		}
7356 	}
7357 
7358 	/*
7359 	 * Matching nfs4_end_op() for start_op() above.
7360 	 * There is a path in the code below which calls
7361 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7362 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7363 	 * here to avoid nfs4_start_op() deadlock.
7364 	 */
7365 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7366 
7367 	if (!e.error) {
7368 		resp = &res;
7369 
7370 		if (res.status) {
7371 			e.error = geterrno4(res.status);
7372 			PURGE_ATTRCACHE4(dvp);
7373 			nfs4_purge_stale_fh(e.error, dvp, cr);
7374 		} else {
7375 			resop = &res.array[1];	/* remove res */
7376 			rm_res = &resop->nfs_resop4_u.opremove;
7377 
7378 			dinfo.di_garp =
7379 			    &res.array[2].nfs_resop4_u.opgetattr.ga_res;
7380 			dinfo.di_cred = cr;
7381 
7382 			/* Update directory attr, readdir and dnlc caches */
7383 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7384 			    &dinfo);
7385 		}
7386 	}
7387 	nfs_rw_exit(&drp->r_rwlock);
7388 	if (resp)
7389 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7390 
7391 	if (e.error == 0) {
7392 		vnode_t *tvp;
7393 		rnode4_t *trp;
7394 		trp = VTOR4(vp);
7395 		tvp = vp;
7396 		if (IS_SHADOW(vp, trp))
7397 			tvp = RTOV4(trp);
7398 		vnevent_remove(tvp, dvp, nm, ct);
7399 	}
7400 	VN_RELE(vp);
7401 	return (e.error);
7402 }
7403 
7404 /*
7405  * Link requires that the current fh be the target directory and the
7406  * saved fh be the source fh. After the operation, the current fh is unchanged.
7407  * Thus the compound op structure is:
7408  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7409  *	GETATTR(file)
7410  */
7411 /* ARGSUSED */
7412 static int
7413 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr,
7414     caller_context_t *ct, int flags)
7415 {
7416 	COMPOUND4args_clnt args;
7417 	COMPOUND4res_clnt res, *resp = NULL;
7418 	LINK4res *ln_res;
7419 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7420 	nfs_argop4 *argop;
7421 	nfs_resop4 *resop;
7422 	vnode_t *realvp, *nvp;
7423 	int doqueue;
7424 	mntinfo4_t *mi;
7425 	rnode4_t *tdrp;
7426 	bool_t needrecov = FALSE;
7427 	nfs4_recov_state_t recov_state;
7428 	hrtime_t t;
7429 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7430 	dirattr_info_t dinfo;
7431 
7432 	ASSERT(*tnm != '\0');
7433 	ASSERT(tdvp->v_type == VDIR);
7434 	ASSERT(nfs4_consistent_type(tdvp));
7435 	ASSERT(nfs4_consistent_type(svp));
7436 
7437 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7438 		return (EPERM);
7439 	if (VOP_REALVP(svp, &realvp, ct) == 0) {
7440 		svp = realvp;
7441 		ASSERT(nfs4_consistent_type(svp));
7442 	}
7443 
7444 	tdrp = VTOR4(tdvp);
7445 	mi = VTOMI4(svp);
7446 
7447 	if (!(mi->mi_flags & MI4_LINK)) {
7448 		return (EOPNOTSUPP);
7449 	}
7450 	recov_state.rs_flags = 0;
7451 	recov_state.rs_num_retry_despite_err = 0;
7452 
7453 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7454 		return (EINTR);
7455 
7456 recov_retry:
7457 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7458 
7459 	args.ctag = TAG_LINK;
7460 
7461 	/*
7462 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7463 	 * restorefh; getattr(fl)
7464 	 */
7465 	args.array_len = 7;
7466 	args.array = argop;
7467 
7468 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7469 	if (e.error) {
7470 		kmem_free(argop, argoplist_size);
7471 		nfs_rw_exit(&tdrp->r_rwlock);
7472 		return (e.error);
7473 	}
7474 
7475 	/* 0. putfh file */
7476 	argop[0].argop = OP_CPUTFH;
7477 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7478 
7479 	/* 1. save current fh to free up the space for the dir */
7480 	argop[1].argop = OP_SAVEFH;
7481 
7482 	/* 2. putfh targetdir */
7483 	argop[2].argop = OP_CPUTFH;
7484 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7485 
7486 	/* 3. link: current_fh is targetdir, saved_fh is source */
7487 	argop[3].argop = OP_CLINK;
7488 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7489 
7490 	/* 4. Get attributes of dir */
7491 	argop[4].argop = OP_GETATTR;
7492 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7493 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7494 
7495 	/* 5. If link was successful, restore current vp to file */
7496 	argop[5].argop = OP_RESTOREFH;
7497 
7498 	/* 6. Get attributes of linked object */
7499 	argop[6].argop = OP_GETATTR;
7500 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7501 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7502 
7503 	dnlc_remove(tdvp, tnm);
7504 
7505 	doqueue = 1;
7506 	t = gethrtime();
7507 
7508 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7509 
7510 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7511 	if (e.error != 0 && !needrecov) {
7512 		PURGE_ATTRCACHE4(tdvp);
7513 		PURGE_ATTRCACHE4(svp);
7514 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7515 		goto out;
7516 	}
7517 
7518 	if (needrecov) {
7519 		bool_t abort;
7520 
7521 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7522 		    NULL, NULL, OP_LINK, NULL);
7523 		if (abort == FALSE) {
7524 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7525 			    needrecov);
7526 			kmem_free(argop, argoplist_size);
7527 			if (!e.error)
7528 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7529 				    (caddr_t)&res);
7530 			goto recov_retry;
7531 		} else {
7532 			if (e.error != 0) {
7533 				PURGE_ATTRCACHE4(tdvp);
7534 				PURGE_ATTRCACHE4(svp);
7535 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7536 				    &recov_state, needrecov);
7537 				goto out;
7538 			}
7539 			/* fall through for res.status case */
7540 		}
7541 	}
7542 
7543 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7544 
7545 	resp = &res;
7546 	if (res.status) {
7547 		/* If link succeeded, then don't return error */
7548 		e.error = geterrno4(res.status);
7549 		if (res.array_len <= 4) {
7550 			/*
7551 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7552 			 */
7553 			PURGE_ATTRCACHE4(svp);
7554 			PURGE_ATTRCACHE4(tdvp);
7555 			if (e.error == EOPNOTSUPP) {
7556 				mutex_enter(&mi->mi_lock);
7557 				mi->mi_flags &= ~MI4_LINK;
7558 				mutex_exit(&mi->mi_lock);
7559 			}
7560 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7561 			/* XXX-LP */
7562 			if (e.error == EISDIR && crgetuid(cr) != 0)
7563 				e.error = EPERM;
7564 			goto out;
7565 		}
7566 	}
7567 
7568 	/* either no error or one of the postop getattr failed */
7569 
7570 	/*
7571 	 * XXX - if LINK succeeded, but no attrs were returned for link
7572 	 * file, purge its cache.
7573 	 *
7574 	 * XXX Perform a simplified version of wcc checking. Instead of
7575 	 * have another getattr to get pre-op, just purge cache if
7576 	 * any of the ops prior to and including the getattr failed.
7577 	 * If the getattr succeeded then update the attrcache accordingly.
7578 	 */
7579 
7580 	/*
7581 	 * update cache with link file postattrs.
7582 	 * Note: at this point resop points to link res.
7583 	 */
7584 	resop = &res.array[3];	/* link res */
7585 	ln_res = &resop->nfs_resop4_u.oplink;
7586 	if (res.status == NFS4_OK)
7587 		e.error = nfs4_update_attrcache(res.status,
7588 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res,
7589 		    t, svp, cr);
7590 
7591 	/*
7592 	 * Call makenfs4node to create the new shadow vp for tnm.
7593 	 * We pass NULL attrs because we just cached attrs for
7594 	 * the src object.  All we're trying to accomplish is to
7595 	 * to create the new shadow vnode.
7596 	 */
7597 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7598 	    tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm, VTOR4(svp)->r_fh));
7599 
7600 	/* Update target cache attribute, readdir and dnlc caches */
7601 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7602 	dinfo.di_time_call = t;
7603 	dinfo.di_cred = cr;
7604 
7605 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7606 	ASSERT(nfs4_consistent_type(tdvp));
7607 	ASSERT(nfs4_consistent_type(svp));
7608 	ASSERT(nfs4_consistent_type(nvp));
7609 	VN_RELE(nvp);
7610 
7611 	if (!e.error) {
7612 		vnode_t *tvp;
7613 		rnode4_t *trp;
7614 		/*
7615 		 * Notify the source file of this link operation.
7616 		 */
7617 		trp = VTOR4(svp);
7618 		tvp = svp;
7619 		if (IS_SHADOW(svp, trp))
7620 			tvp = RTOV4(trp);
7621 		vnevent_link(tvp, ct);
7622 	}
7623 out:
7624 	kmem_free(argop, argoplist_size);
7625 	if (resp)
7626 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7627 
7628 	nfs_rw_exit(&tdrp->r_rwlock);
7629 
7630 	return (e.error);
7631 }
7632 
7633 /* ARGSUSED */
7634 static int
7635 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7636     caller_context_t *ct, int flags)
7637 {
7638 	vnode_t *realvp;
7639 
7640 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7641 		return (EPERM);
7642 	if (VOP_REALVP(ndvp, &realvp, ct) == 0)
7643 		ndvp = realvp;
7644 
7645 	return (nfs4rename(odvp, onm, ndvp, nnm, cr, ct));
7646 }
7647 
7648 /*
7649  * nfs4rename does the real work of renaming in NFS Version 4.
7650  *
7651  * A file handle is considered volatile for renaming purposes if either
7652  * of the volatile bits are turned on. However, the compound may differ
7653  * based on the likelihood of the filehandle to change during rename.
7654  */
7655 static int
7656 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7657     caller_context_t *ct)
7658 {
7659 	int error;
7660 	mntinfo4_t *mi;
7661 	vnode_t *nvp = NULL;
7662 	vnode_t *ovp = NULL;
7663 	char *tmpname = NULL;
7664 	rnode4_t *rp;
7665 	rnode4_t *odrp;
7666 	rnode4_t *ndrp;
7667 	int did_link = 0;
7668 	int do_link = 1;
7669 	nfsstat4 stat = NFS4_OK;
7670 
7671 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7672 	ASSERT(nfs4_consistent_type(odvp));
7673 	ASSERT(nfs4_consistent_type(ndvp));
7674 
7675 	if (onm[0] == '.' && (onm[1] == '\0' ||
7676 	    (onm[1] == '.' && onm[2] == '\0')))
7677 		return (EINVAL);
7678 
7679 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7680 	    (nnm[1] == '.' && nnm[2] == '\0')))
7681 		return (EINVAL);
7682 
7683 	odrp = VTOR4(odvp);
7684 	ndrp = VTOR4(ndvp);
7685 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7686 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7687 			return (EINTR);
7688 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7689 			nfs_rw_exit(&odrp->r_rwlock);
7690 			return (EINTR);
7691 		}
7692 	} else {
7693 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7694 			return (EINTR);
7695 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7696 			nfs_rw_exit(&ndrp->r_rwlock);
7697 			return (EINTR);
7698 		}
7699 	}
7700 
7701 	/*
7702 	 * Lookup the target file.  If it exists, it needs to be
7703 	 * checked to see whether it is a mount point and whether
7704 	 * it is active (open).
7705 	 */
7706 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7707 	if (!error) {
7708 		int	isactive;
7709 
7710 		ASSERT(nfs4_consistent_type(nvp));
7711 		/*
7712 		 * If this file has been mounted on, then just
7713 		 * return busy because renaming to it would remove
7714 		 * the mounted file system from the name space.
7715 		 */
7716 		if (vn_ismntpt(nvp)) {
7717 			VN_RELE(nvp);
7718 			nfs_rw_exit(&odrp->r_rwlock);
7719 			nfs_rw_exit(&ndrp->r_rwlock);
7720 			return (EBUSY);
7721 		}
7722 
7723 		/*
7724 		 * First just remove the entry from the name cache, as it
7725 		 * is most likely the only entry for this vp.
7726 		 */
7727 		dnlc_remove(ndvp, nnm);
7728 
7729 		rp = VTOR4(nvp);
7730 
7731 		if (nvp->v_type != VREG) {
7732 			/*
7733 			 * Purge the name cache of all references to this vnode
7734 			 * so that we can check the reference count to infer
7735 			 * whether it is active or not.
7736 			 */
7737 			if (nvp->v_count > 1)
7738 				dnlc_purge_vp(nvp);
7739 
7740 			isactive = nvp->v_count > 1;
7741 		} else {
7742 			mutex_enter(&rp->r_os_lock);
7743 			isactive = list_head(&rp->r_open_streams) != NULL;
7744 			mutex_exit(&rp->r_os_lock);
7745 		}
7746 
7747 		/*
7748 		 * If the vnode is active and is not a directory,
7749 		 * arrange to rename it to a
7750 		 * temporary file so that it will continue to be
7751 		 * accessible.  This implements the "unlink-open-file"
7752 		 * semantics for the target of a rename operation.
7753 		 * Before doing this though, make sure that the
7754 		 * source and target files are not already the same.
7755 		 */
7756 		if (isactive && nvp->v_type != VDIR) {
7757 			/*
7758 			 * Lookup the source name.
7759 			 */
7760 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7761 
7762 			/*
7763 			 * The source name *should* already exist.
7764 			 */
7765 			if (error) {
7766 				VN_RELE(nvp);
7767 				nfs_rw_exit(&odrp->r_rwlock);
7768 				nfs_rw_exit(&ndrp->r_rwlock);
7769 				return (error);
7770 			}
7771 
7772 			ASSERT(nfs4_consistent_type(ovp));
7773 
7774 			/*
7775 			 * Compare the two vnodes.  If they are the same,
7776 			 * just release all held vnodes and return success.
7777 			 */
7778 			if (VN_CMP(ovp, nvp)) {
7779 				VN_RELE(ovp);
7780 				VN_RELE(nvp);
7781 				nfs_rw_exit(&odrp->r_rwlock);
7782 				nfs_rw_exit(&ndrp->r_rwlock);
7783 				return (0);
7784 			}
7785 
7786 			/*
7787 			 * Can't mix and match directories and non-
7788 			 * directories in rename operations.  We already
7789 			 * know that the target is not a directory.  If
7790 			 * the source is a directory, return an error.
7791 			 */
7792 			if (ovp->v_type == VDIR) {
7793 				VN_RELE(ovp);
7794 				VN_RELE(nvp);
7795 				nfs_rw_exit(&odrp->r_rwlock);
7796 				nfs_rw_exit(&ndrp->r_rwlock);
7797 				return (ENOTDIR);
7798 			}
7799 link_call:
7800 			/*
7801 			 * The target file exists, is not the same as
7802 			 * the source file, and is active.  We first
7803 			 * try to Link it to a temporary filename to
7804 			 * avoid having the server removing the file
7805 			 * completely (which could cause data loss to
7806 			 * the user's POV in the event the Rename fails
7807 			 * -- see bug 1165874).
7808 			 */
7809 			/*
7810 			 * The do_link and did_link booleans are
7811 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7812 			 * returned for the Rename.  Some servers can
7813 			 * not Rename over an Open file, so they return
7814 			 * this error.  The client needs to Remove the
7815 			 * newly created Link and do two Renames, just
7816 			 * as if the server didn't support LINK.
7817 			 */
7818 			tmpname = newname();
7819 			error = 0;
7820 
7821 			if (do_link) {
7822 				error = nfs4_link(ndvp, nvp, tmpname, cr,
7823 				    NULL, 0);
7824 			}
7825 			if (error == EOPNOTSUPP || !do_link) {
7826 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7827 				    cr, NULL, 0);
7828 				did_link = 0;
7829 			} else {
7830 				did_link = 1;
7831 			}
7832 			if (error) {
7833 				kmem_free(tmpname, MAXNAMELEN);
7834 				VN_RELE(ovp);
7835 				VN_RELE(nvp);
7836 				nfs_rw_exit(&odrp->r_rwlock);
7837 				nfs_rw_exit(&ndrp->r_rwlock);
7838 				return (error);
7839 			}
7840 
7841 			mutex_enter(&rp->r_statelock);
7842 			if (rp->r_unldvp == NULL) {
7843 				VN_HOLD(ndvp);
7844 				rp->r_unldvp = ndvp;
7845 				if (rp->r_unlcred != NULL)
7846 					crfree(rp->r_unlcred);
7847 				crhold(cr);
7848 				rp->r_unlcred = cr;
7849 				rp->r_unlname = tmpname;
7850 			} else {
7851 				if (rp->r_unlname)
7852 					kmem_free(rp->r_unlname, MAXNAMELEN);
7853 				rp->r_unlname = tmpname;
7854 			}
7855 			mutex_exit(&rp->r_statelock);
7856 		}
7857 
7858 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7859 
7860 		ASSERT(nfs4_consistent_type(nvp));
7861 	}
7862 
7863 	if (ovp == NULL) {
7864 		/*
7865 		 * When renaming directories to be a subdirectory of a
7866 		 * different parent, the dnlc entry for ".." will no
7867 		 * longer be valid, so it must be removed.
7868 		 *
7869 		 * We do a lookup here to determine whether we are renaming
7870 		 * a directory and we need to check if we are renaming
7871 		 * an unlinked file.  This might have already been done
7872 		 * in previous code, so we check ovp == NULL to avoid
7873 		 * doing it twice.
7874 		 */
7875 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7876 		/*
7877 		 * The source name *should* already exist.
7878 		 */
7879 		if (error) {
7880 			nfs_rw_exit(&odrp->r_rwlock);
7881 			nfs_rw_exit(&ndrp->r_rwlock);
7882 			if (nvp) {
7883 				VN_RELE(nvp);
7884 			}
7885 			return (error);
7886 		}
7887 		ASSERT(ovp != NULL);
7888 		ASSERT(nfs4_consistent_type(ovp));
7889 	}
7890 
7891 	/*
7892 	 * Is the object being renamed a dir, and if so, is
7893 	 * it being renamed to a child of itself?  The underlying
7894 	 * fs should ultimately return EINVAL for this case;
7895 	 * however, buggy beta non-Solaris NFSv4 servers at
7896 	 * interop testing events have allowed this behavior,
7897 	 * and it caused our client to panic due to a recursive
7898 	 * mutex_enter in fn_move.
7899 	 *
7900 	 * The tedious locking in fn_move could be changed to
7901 	 * deal with this case, and the client could avoid the
7902 	 * panic; however, the client would just confuse itself
7903 	 * later and misbehave.  A better way to handle the broken
7904 	 * server is to detect this condition and return EINVAL
7905 	 * without ever sending the the bogus rename to the server.
7906 	 * We know the rename is invalid -- just fail it now.
7907 	 */
7908 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7909 		VN_RELE(ovp);
7910 		nfs_rw_exit(&odrp->r_rwlock);
7911 		nfs_rw_exit(&ndrp->r_rwlock);
7912 		if (nvp) {
7913 			VN_RELE(nvp);
7914 		}
7915 		return (EINVAL);
7916 	}
7917 
7918 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7919 
7920 	/*
7921 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7922 	 * possible for the filehandle to change due to the rename.
7923 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7924 	 * the fh will not change because of the rename, but we still need
7925 	 * to update its rnode entry with the new name for
7926 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7927 	 * has no effect on these for now, but for future improvements,
7928 	 * we might want to use it too to simplify handling of files
7929 	 * that are open with that flag on. (XXX)
7930 	 */
7931 	mi = VTOMI4(odvp);
7932 	if (NFS4_VOLATILE_FH(mi))
7933 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7934 		    &stat);
7935 	else
7936 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7937 		    &stat);
7938 
7939 	ASSERT(nfs4_consistent_type(odvp));
7940 	ASSERT(nfs4_consistent_type(ndvp));
7941 	ASSERT(nfs4_consistent_type(ovp));
7942 
7943 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
7944 		do_link = 0;
7945 		/*
7946 		 * Before the 'link_call' code, we did a nfs4_lookup
7947 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
7948 		 * call we call VN_RELE to match that hold.  We need
7949 		 * to place an additional VN_HOLD here since we will
7950 		 * be hitting that VN_RELE again.
7951 		 */
7952 		VN_HOLD(nvp);
7953 
7954 		(void) nfs4_remove(ndvp, tmpname, cr, NULL, 0);
7955 
7956 		/* Undo the unlinked file naming stuff we just did */
7957 		mutex_enter(&rp->r_statelock);
7958 		if (rp->r_unldvp) {
7959 			VN_RELE(ndvp);
7960 			rp->r_unldvp = NULL;
7961 			if (rp->r_unlcred != NULL)
7962 				crfree(rp->r_unlcred);
7963 			rp->r_unlcred = NULL;
7964 			/* rp->r_unlanme points to tmpname */
7965 			if (rp->r_unlname)
7966 				kmem_free(rp->r_unlname, MAXNAMELEN);
7967 			rp->r_unlname = NULL;
7968 		}
7969 		mutex_exit(&rp->r_statelock);
7970 
7971 		if (nvp) {
7972 			VN_RELE(nvp);
7973 		}
7974 		goto link_call;
7975 	}
7976 
7977 	if (error) {
7978 		VN_RELE(ovp);
7979 		nfs_rw_exit(&odrp->r_rwlock);
7980 		nfs_rw_exit(&ndrp->r_rwlock);
7981 		if (nvp) {
7982 			VN_RELE(nvp);
7983 		}
7984 		return (error);
7985 	}
7986 
7987 	/*
7988 	 * when renaming directories to be a subdirectory of a
7989 	 * different parent, the dnlc entry for ".." will no
7990 	 * longer be valid, so it must be removed
7991 	 */
7992 	rp = VTOR4(ovp);
7993 	if (ndvp != odvp) {
7994 		if (ovp->v_type == VDIR) {
7995 			dnlc_remove(ovp, "..");
7996 			if (rp->r_dir != NULL)
7997 				nfs4_purge_rddir_cache(ovp);
7998 		}
7999 	}
8000 
8001 	/*
8002 	 * If we are renaming the unlinked file, update the
8003 	 * r_unldvp and r_unlname as needed.
8004 	 */
8005 	mutex_enter(&rp->r_statelock);
8006 	if (rp->r_unldvp != NULL) {
8007 		if (strcmp(rp->r_unlname, onm) == 0) {
8008 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
8009 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
8010 			if (ndvp != rp->r_unldvp) {
8011 				VN_RELE(rp->r_unldvp);
8012 				rp->r_unldvp = ndvp;
8013 				VN_HOLD(ndvp);
8014 			}
8015 		}
8016 	}
8017 	mutex_exit(&rp->r_statelock);
8018 
8019 	/*
8020 	 * Notify the rename vnevents to source vnode, and to the target
8021 	 * vnode if it already existed.
8022 	 */
8023 	if (error == 0) {
8024 		vnode_t *tvp;
8025 		rnode4_t *trp;
8026 		/*
8027 		 * Notify the vnode. Each links is represented by
8028 		 * a different vnode, in nfsv4.
8029 		 */
8030 		if (nvp) {
8031 			trp = VTOR4(nvp);
8032 			tvp = nvp;
8033 			if (IS_SHADOW(nvp, trp))
8034 				tvp = RTOV4(trp);
8035 			vnevent_rename_dest(tvp, ndvp, nnm, ct);
8036 		}
8037 
8038 		/*
8039 		 * if the source and destination directory are not the
8040 		 * same notify the destination directory.
8041 		 */
8042 		if (VTOR4(odvp) != VTOR4(ndvp)) {
8043 			trp = VTOR4(ndvp);
8044 			tvp = ndvp;
8045 			if (IS_SHADOW(ndvp, trp))
8046 				tvp = RTOV4(trp);
8047 			vnevent_rename_dest_dir(tvp, ct);
8048 		}
8049 
8050 		trp = VTOR4(ovp);
8051 		tvp = ovp;
8052 		if (IS_SHADOW(ovp, trp))
8053 			tvp = RTOV4(trp);
8054 		vnevent_rename_src(tvp, odvp, onm, ct);
8055 	}
8056 
8057 	if (nvp) {
8058 		VN_RELE(nvp);
8059 	}
8060 	VN_RELE(ovp);
8061 
8062 	nfs_rw_exit(&odrp->r_rwlock);
8063 	nfs_rw_exit(&ndrp->r_rwlock);
8064 
8065 	return (error);
8066 }
8067 
8068 /*
8069  * When the parent directory has changed, sv_dfh must be updated
8070  */
8071 static void
8072 update_parentdir_sfh(vnode_t *vp, vnode_t *ndvp)
8073 {
8074 	svnode_t *sv = VTOSV(vp);
8075 	nfs4_sharedfh_t *old_dfh = sv->sv_dfh;
8076 	nfs4_sharedfh_t *new_dfh = VTOR4(ndvp)->r_fh;
8077 
8078 	sfh4_hold(new_dfh);
8079 	sv->sv_dfh = new_dfh;
8080 	sfh4_rele(&old_dfh);
8081 }
8082 
8083 /*
8084  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
8085  * when it is known that the filehandle is persistent through rename.
8086  *
8087  * Rename requires that the current fh be the target directory and the
8088  * saved fh be the source directory. After the operation, the current fh
8089  * is unchanged.
8090  * The compound op structure for persistent fh rename is:
8091  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
8092  * Rather than bother with the directory postop args, we'll simply
8093  * update that a change occurred in the cache, so no post-op getattrs.
8094  */
8095 static int
8096 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
8097     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8098 {
8099 	COMPOUND4args_clnt args;
8100 	COMPOUND4res_clnt res, *resp = NULL;
8101 	nfs_argop4 *argop;
8102 	nfs_resop4 *resop;
8103 	int doqueue, argoplist_size;
8104 	mntinfo4_t *mi;
8105 	rnode4_t *odrp = VTOR4(odvp);
8106 	rnode4_t *ndrp = VTOR4(ndvp);
8107 	RENAME4res *rn_res;
8108 	bool_t needrecov;
8109 	nfs4_recov_state_t recov_state;
8110 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8111 	dirattr_info_t dinfo, *dinfop;
8112 
8113 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8114 
8115 	recov_state.rs_flags = 0;
8116 	recov_state.rs_num_retry_despite_err = 0;
8117 
8118 	/*
8119 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
8120 	 *
8121 	 * If source/target are different dirs, then append putfh(src); getattr
8122 	 */
8123 	args.array_len = (odvp == ndvp) ? 5 : 7;
8124 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8125 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8126 
8127 recov_retry:
8128 	*statp = NFS4_OK;
8129 
8130 	/* No need to Lookup the file, persistent fh */
8131 	args.ctag = TAG_RENAME;
8132 
8133 	mi = VTOMI4(odvp);
8134 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8135 	if (e.error) {
8136 		kmem_free(argop, argoplist_size);
8137 		return (e.error);
8138 	}
8139 
8140 	/* 0: putfh source directory */
8141 	argop[0].argop = OP_CPUTFH;
8142 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8143 
8144 	/* 1: Save source fh to free up current for target */
8145 	argop[1].argop = OP_SAVEFH;
8146 
8147 	/* 2: putfh targetdir */
8148 	argop[2].argop = OP_CPUTFH;
8149 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8150 
8151 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8152 	argop[3].argop = OP_CRENAME;
8153 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8154 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8155 
8156 	/* 4: getattr (targetdir) */
8157 	argop[4].argop = OP_GETATTR;
8158 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8159 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8160 
8161 	if (ndvp != odvp) {
8162 
8163 		/* 5: putfh (sourcedir) */
8164 		argop[5].argop = OP_CPUTFH;
8165 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8166 
8167 		/* 6: getattr (sourcedir) */
8168 		argop[6].argop = OP_GETATTR;
8169 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8170 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8171 	}
8172 
8173 	dnlc_remove(odvp, onm);
8174 	dnlc_remove(ndvp, nnm);
8175 
8176 	doqueue = 1;
8177 	dinfo.di_time_call = gethrtime();
8178 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8179 
8180 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8181 	if (e.error) {
8182 		PURGE_ATTRCACHE4(odvp);
8183 		PURGE_ATTRCACHE4(ndvp);
8184 	} else {
8185 		*statp = res.status;
8186 	}
8187 
8188 	if (needrecov) {
8189 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8190 		    OP_RENAME, NULL) == FALSE) {
8191 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8192 			if (!e.error)
8193 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8194 				    (caddr_t)&res);
8195 			goto recov_retry;
8196 		}
8197 	}
8198 
8199 	if (!e.error) {
8200 		resp = &res;
8201 		/*
8202 		 * as long as OP_RENAME
8203 		 */
8204 		if (res.status != NFS4_OK && res.array_len <= 4) {
8205 			e.error = geterrno4(res.status);
8206 			PURGE_ATTRCACHE4(odvp);
8207 			PURGE_ATTRCACHE4(ndvp);
8208 			/*
8209 			 * System V defines rename to return EEXIST, not
8210 			 * ENOTEMPTY if the target directory is not empty.
8211 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8212 			 * which geterrno4 maps to ENOTEMPTY.
8213 			 */
8214 			if (e.error == ENOTEMPTY)
8215 				e.error = EEXIST;
8216 		} else {
8217 
8218 			resop = &res.array[3];	/* rename res */
8219 			rn_res = &resop->nfs_resop4_u.oprename;
8220 
8221 			if (res.status == NFS4_OK) {
8222 				/*
8223 				 * Update target attribute, readdir and dnlc
8224 				 * caches.
8225 				 */
8226 				dinfo.di_garp =
8227 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8228 				dinfo.di_cred = cr;
8229 				dinfop = &dinfo;
8230 			} else
8231 				dinfop = NULL;
8232 
8233 			nfs4_update_dircaches(&rn_res->target_cinfo,
8234 			    ndvp, NULL, NULL, dinfop);
8235 
8236 			/*
8237 			 * Update source attribute, readdir and dnlc caches
8238 			 *
8239 			 */
8240 			if (ndvp != odvp) {
8241 				update_parentdir_sfh(renvp, ndvp);
8242 
8243 				if (dinfop)
8244 					dinfo.di_garp =
8245 					    &(res.array[6].nfs_resop4_u.
8246 					    opgetattr.ga_res);
8247 
8248 				nfs4_update_dircaches(&rn_res->source_cinfo,
8249 				    odvp, NULL, NULL, dinfop);
8250 			}
8251 
8252 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8253 			    nnm);
8254 		}
8255 	}
8256 
8257 	if (resp)
8258 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8259 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8260 	kmem_free(argop, argoplist_size);
8261 
8262 	return (e.error);
8263 }
8264 
8265 /*
8266  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8267  * it is possible for the filehandle to change due to the rename.
8268  *
8269  * The compound req in this case includes a post-rename lookup and getattr
8270  * to ensure that we have the correct fh and attributes for the object.
8271  *
8272  * Rename requires that the current fh be the target directory and the
8273  * saved fh be the source directory. After the operation, the current fh
8274  * is unchanged.
8275  *
8276  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8277  * update the filehandle for the renamed object.  We also get the old
8278  * filehandle for historical reasons; this should be taken out sometime.
8279  * This results in a rather cumbersome compound...
8280  *
8281  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8282  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8283  *
8284  */
8285 static int
8286 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8287     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8288 {
8289 	COMPOUND4args_clnt args;
8290 	COMPOUND4res_clnt res, *resp = NULL;
8291 	int argoplist_size;
8292 	nfs_argop4 *argop;
8293 	nfs_resop4 *resop;
8294 	int doqueue;
8295 	mntinfo4_t *mi;
8296 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8297 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8298 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8299 	RENAME4res *rn_res;
8300 	GETFH4res *ngf_res;
8301 	bool_t needrecov;
8302 	nfs4_recov_state_t recov_state;
8303 	hrtime_t t;
8304 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8305 	dirattr_info_t dinfo, *dinfop = &dinfo;
8306 
8307 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8308 
8309 	recov_state.rs_flags = 0;
8310 	recov_state.rs_num_retry_despite_err = 0;
8311 
8312 recov_retry:
8313 	*statp = NFS4_OK;
8314 
8315 	/*
8316 	 * There is a window between the RPC and updating the path and
8317 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8318 	 * code, so that it doesn't try to use the old path during that
8319 	 * window.
8320 	 */
8321 	mutex_enter(&orp->r_statelock);
8322 	while (orp->r_flags & R4RECEXPFH) {
8323 		klwp_t *lwp = ttolwp(curthread);
8324 
8325 		if (lwp != NULL)
8326 			lwp->lwp_nostop++;
8327 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8328 			mutex_exit(&orp->r_statelock);
8329 			if (lwp != NULL)
8330 				lwp->lwp_nostop--;
8331 			return (EINTR);
8332 		}
8333 		if (lwp != NULL)
8334 			lwp->lwp_nostop--;
8335 	}
8336 	orp->r_flags |= R4RECEXPFH;
8337 	mutex_exit(&orp->r_statelock);
8338 
8339 	mi = VTOMI4(odvp);
8340 
8341 	args.ctag = TAG_RENAME_VFH;
8342 	args.array_len = (odvp == ndvp) ? 10 : 12;
8343 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8344 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8345 
8346 	/*
8347 	 * Rename ops:
8348 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8349 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8350 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8351 	 *
8352 	 *    if (odvp != ndvp)
8353 	 *	add putfh(sourcedir), getattr(sourcedir) }
8354 	 */
8355 	args.array = argop;
8356 
8357 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8358 	    &recov_state, NULL);
8359 	if (e.error) {
8360 		kmem_free(argop, argoplist_size);
8361 		mutex_enter(&orp->r_statelock);
8362 		orp->r_flags &= ~R4RECEXPFH;
8363 		cv_broadcast(&orp->r_cv);
8364 		mutex_exit(&orp->r_statelock);
8365 		return (e.error);
8366 	}
8367 
8368 	/* 0: putfh source directory */
8369 	argop[0].argop = OP_CPUTFH;
8370 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8371 
8372 	/* 1: Save source fh to free up current for target */
8373 	argop[1].argop = OP_SAVEFH;
8374 
8375 	/* 2: Lookup pre-rename fh of renamed object */
8376 	argop[2].argop = OP_CLOOKUP;
8377 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8378 
8379 	/* 3: getfh fh of renamed object (before rename) */
8380 	argop[3].argop = OP_GETFH;
8381 
8382 	/* 4: putfh targetdir */
8383 	argop[4].argop = OP_CPUTFH;
8384 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8385 
8386 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8387 	argop[5].argop = OP_CRENAME;
8388 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8389 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8390 
8391 	/* 6: getattr of target dir (post op attrs) */
8392 	argop[6].argop = OP_GETATTR;
8393 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8394 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8395 
8396 	/* 7: Lookup post-rename fh of renamed object */
8397 	argop[7].argop = OP_CLOOKUP;
8398 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8399 
8400 	/* 8: getfh fh of renamed object (after rename) */
8401 	argop[8].argop = OP_GETFH;
8402 
8403 	/* 9: getattr of renamed object */
8404 	argop[9].argop = OP_GETATTR;
8405 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8406 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8407 
8408 	/*
8409 	 * If source/target dirs are different, then get new post-op
8410 	 * attrs for source dir also.
8411 	 */
8412 	if (ndvp != odvp) {
8413 		/* 10: putfh (sourcedir) */
8414 		argop[10].argop = OP_CPUTFH;
8415 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8416 
8417 		/* 11: getattr (sourcedir) */
8418 		argop[11].argop = OP_GETATTR;
8419 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8420 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8421 	}
8422 
8423 	dnlc_remove(odvp, onm);
8424 	dnlc_remove(ndvp, nnm);
8425 
8426 	doqueue = 1;
8427 	t = gethrtime();
8428 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8429 
8430 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8431 	if (e.error) {
8432 		PURGE_ATTRCACHE4(odvp);
8433 		PURGE_ATTRCACHE4(ndvp);
8434 		if (!needrecov) {
8435 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8436 			    &recov_state, needrecov);
8437 			goto out;
8438 		}
8439 	} else {
8440 		*statp = res.status;
8441 	}
8442 
8443 	if (needrecov) {
8444 		bool_t abort;
8445 
8446 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8447 		    OP_RENAME, NULL);
8448 		if (abort == FALSE) {
8449 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8450 			    &recov_state, needrecov);
8451 			kmem_free(argop, argoplist_size);
8452 			if (!e.error)
8453 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8454 				    (caddr_t)&res);
8455 			mutex_enter(&orp->r_statelock);
8456 			orp->r_flags &= ~R4RECEXPFH;
8457 			cv_broadcast(&orp->r_cv);
8458 			mutex_exit(&orp->r_statelock);
8459 			goto recov_retry;
8460 		} else {
8461 			if (e.error != 0) {
8462 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8463 				    &recov_state, needrecov);
8464 				goto out;
8465 			}
8466 			/* fall through for res.status case */
8467 		}
8468 	}
8469 
8470 	resp = &res;
8471 	/*
8472 	 * If OP_RENAME (or any prev op) failed, then return an error.
8473 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8474 	 */
8475 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8476 		/*
8477 		 * Error in an op other than last Getattr
8478 		 */
8479 		e.error = geterrno4(res.status);
8480 		PURGE_ATTRCACHE4(odvp);
8481 		PURGE_ATTRCACHE4(ndvp);
8482 		/*
8483 		 * System V defines rename to return EEXIST, not
8484 		 * ENOTEMPTY if the target directory is not empty.
8485 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8486 		 * which geterrno4 maps to ENOTEMPTY.
8487 		 */
8488 		if (e.error == ENOTEMPTY)
8489 			e.error = EEXIST;
8490 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8491 		    needrecov);
8492 		goto out;
8493 	}
8494 
8495 	/* rename results */
8496 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8497 
8498 	if (res.status == NFS4_OK) {
8499 		/* Update target attribute, readdir and dnlc caches */
8500 		dinfo.di_garp =
8501 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
8502 		dinfo.di_cred = cr;
8503 		dinfo.di_time_call = t;
8504 	} else
8505 		dinfop = NULL;
8506 
8507 	/* Update source cache attribute, readdir and dnlc caches */
8508 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8509 
8510 	/* Update source cache attribute, readdir and dnlc caches */
8511 	if (ndvp != odvp) {
8512 		update_parentdir_sfh(ovp, ndvp);
8513 
8514 		/*
8515 		 * If dinfop is non-NULL, then compound succeded, so
8516 		 * set di_garp to attrs for source dir.  dinfop is only
8517 		 * set to NULL when compound fails.
8518 		 */
8519 		if (dinfop)
8520 			dinfo.di_garp =
8521 			    &res.array[11].nfs_resop4_u.opgetattr.ga_res;
8522 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8523 		    dinfop);
8524 	}
8525 
8526 	/*
8527 	 * Update the rnode with the new component name and args,
8528 	 * and if the file handle changed, also update it with the new fh.
8529 	 * This is only necessary if the target object has an rnode
8530 	 * entry and there is no need to create one for it.
8531 	 */
8532 	resop = &res.array[8];	/* getfh new res */
8533 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8534 
8535 	/*
8536 	 * Update the path and filehandle for the renamed object.
8537 	 */
8538 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8539 
8540 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8541 
8542 	if (res.status == NFS4_OK) {
8543 		resop++;	/* getattr res */
8544 		e.error = nfs4_update_attrcache(res.status,
8545 		    &resop->nfs_resop4_u.opgetattr.ga_res,
8546 		    t, ovp, cr);
8547 	}
8548 
8549 out:
8550 	kmem_free(argop, argoplist_size);
8551 	if (resp)
8552 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8553 	mutex_enter(&orp->r_statelock);
8554 	orp->r_flags &= ~R4RECEXPFH;
8555 	cv_broadcast(&orp->r_cv);
8556 	mutex_exit(&orp->r_statelock);
8557 
8558 	return (e.error);
8559 }
8560 
8561 /* ARGSUSED */
8562 static int
8563 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr,
8564     caller_context_t *ct, int flags, vsecattr_t *vsecp)
8565 {
8566 	int error;
8567 	vnode_t *vp;
8568 
8569 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8570 		return (EPERM);
8571 	/*
8572 	 * As ".." has special meaning and rather than send a mkdir
8573 	 * over the wire to just let the server freak out, we just
8574 	 * short circuit it here and return EEXIST
8575 	 */
8576 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8577 		return (EEXIST);
8578 
8579 	/*
8580 	 * Decision to get the right gid and setgid bit of the
8581 	 * new directory is now made in call_nfs4_create_req.
8582 	 */
8583 	va->va_mask |= AT_MODE;
8584 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8585 	if (error)
8586 		return (error);
8587 
8588 	*vpp = vp;
8589 	return (0);
8590 }
8591 
8592 
8593 /*
8594  * rmdir is using the same remove v4 op as does remove.
8595  * Remove requires that the current fh be the target directory.
8596  * After the operation, the current fh is unchanged.
8597  * The compound op structure is:
8598  *      PUTFH(targetdir), REMOVE
8599  */
8600 /*ARGSUSED4*/
8601 static int
8602 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr,
8603     caller_context_t *ct, int flags)
8604 {
8605 	int need_end_op = FALSE;
8606 	COMPOUND4args_clnt args;
8607 	COMPOUND4res_clnt res, *resp = NULL;
8608 	REMOVE4res *rm_res;
8609 	nfs_argop4 argop[3];
8610 	nfs_resop4 *resop;
8611 	vnode_t *vp;
8612 	int doqueue;
8613 	mntinfo4_t *mi;
8614 	rnode4_t *drp;
8615 	bool_t needrecov = FALSE;
8616 	nfs4_recov_state_t recov_state;
8617 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8618 	dirattr_info_t dinfo, *dinfop;
8619 
8620 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8621 		return (EPERM);
8622 	/*
8623 	 * As ".." has special meaning and rather than send a rmdir
8624 	 * over the wire to just let the server freak out, we just
8625 	 * short circuit it here and return EEXIST
8626 	 */
8627 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8628 		return (EEXIST);
8629 
8630 	drp = VTOR4(dvp);
8631 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8632 		return (EINTR);
8633 
8634 	/*
8635 	 * Attempt to prevent a rmdir(".") from succeeding.
8636 	 */
8637 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8638 	if (e.error) {
8639 		nfs_rw_exit(&drp->r_rwlock);
8640 		return (e.error);
8641 	}
8642 	if (vp == cdir) {
8643 		VN_RELE(vp);
8644 		nfs_rw_exit(&drp->r_rwlock);
8645 		return (EINVAL);
8646 	}
8647 
8648 	/*
8649 	 * Since nfsv4 remove op works on both files and directories,
8650 	 * check that the removed object is indeed a directory.
8651 	 */
8652 	if (vp->v_type != VDIR) {
8653 		VN_RELE(vp);
8654 		nfs_rw_exit(&drp->r_rwlock);
8655 		return (ENOTDIR);
8656 	}
8657 
8658 	/*
8659 	 * First just remove the entry from the name cache, as it
8660 	 * is most likely an entry for this vp.
8661 	 */
8662 	dnlc_remove(dvp, nm);
8663 
8664 	/*
8665 	 * If there vnode reference count is greater than one, then
8666 	 * there may be additional references in the DNLC which will
8667 	 * need to be purged.  First, trying removing the entry for
8668 	 * the parent directory and see if that removes the additional
8669 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8670 	 * to completely remove any references to the directory which
8671 	 * might still exist in the DNLC.
8672 	 */
8673 	if (vp->v_count > 1) {
8674 		dnlc_remove(vp, "..");
8675 		if (vp->v_count > 1)
8676 			dnlc_purge_vp(vp);
8677 	}
8678 
8679 	mi = VTOMI4(dvp);
8680 	recov_state.rs_flags = 0;
8681 	recov_state.rs_num_retry_despite_err = 0;
8682 
8683 recov_retry:
8684 	args.ctag = TAG_RMDIR;
8685 
8686 	/*
8687 	 * Rmdir ops: putfh dir; remove
8688 	 */
8689 	args.array_len = 3;
8690 	args.array = argop;
8691 
8692 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8693 	if (e.error) {
8694 		nfs_rw_exit(&drp->r_rwlock);
8695 		return (e.error);
8696 	}
8697 	need_end_op = TRUE;
8698 
8699 	/* putfh directory */
8700 	argop[0].argop = OP_CPUTFH;
8701 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8702 
8703 	/* remove */
8704 	argop[1].argop = OP_CREMOVE;
8705 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8706 
8707 	/* getattr (postop attrs for dir that contained removed dir) */
8708 	argop[2].argop = OP_GETATTR;
8709 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8710 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8711 
8712 	dinfo.di_time_call = gethrtime();
8713 	doqueue = 1;
8714 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8715 
8716 	PURGE_ATTRCACHE4(vp);
8717 
8718 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8719 	if (e.error) {
8720 		PURGE_ATTRCACHE4(dvp);
8721 	}
8722 
8723 	if (needrecov) {
8724 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8725 		    NULL, OP_REMOVE, NULL) == FALSE) {
8726 			if (!e.error)
8727 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8728 				    (caddr_t)&res);
8729 
8730 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8731 			    needrecov);
8732 			need_end_op = FALSE;
8733 			goto recov_retry;
8734 		}
8735 	}
8736 
8737 	if (!e.error) {
8738 		resp = &res;
8739 
8740 		/*
8741 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8742 		 * failed.
8743 		 */
8744 		if (res.status != NFS4_OK && res.array_len <= 2) {
8745 			e.error = geterrno4(res.status);
8746 			PURGE_ATTRCACHE4(dvp);
8747 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8748 			    &recov_state, needrecov);
8749 			need_end_op = FALSE;
8750 			nfs4_purge_stale_fh(e.error, dvp, cr);
8751 			/*
8752 			 * System V defines rmdir to return EEXIST, not
8753 			 * ENOTEMPTY if the directory is not empty.  Over
8754 			 * the wire, the error is NFSERR_ENOTEMPTY which
8755 			 * geterrno4 maps to ENOTEMPTY.
8756 			 */
8757 			if (e.error == ENOTEMPTY)
8758 				e.error = EEXIST;
8759 		} else {
8760 			resop = &res.array[1];	/* remove res */
8761 			rm_res = &resop->nfs_resop4_u.opremove;
8762 
8763 			if (res.status == NFS4_OK) {
8764 				resop = &res.array[2];	/* dir attrs */
8765 				dinfo.di_garp =
8766 				    &resop->nfs_resop4_u.opgetattr.ga_res;
8767 				dinfo.di_cred = cr;
8768 				dinfop = &dinfo;
8769 			} else
8770 				dinfop = NULL;
8771 
8772 			/* Update dir attribute, readdir and dnlc caches */
8773 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8774 			    dinfop);
8775 
8776 			/* destroy rddir cache for dir that was removed */
8777 			if (VTOR4(vp)->r_dir != NULL)
8778 				nfs4_purge_rddir_cache(vp);
8779 		}
8780 	}
8781 
8782 	if (need_end_op)
8783 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8784 
8785 	nfs_rw_exit(&drp->r_rwlock);
8786 
8787 	if (resp)
8788 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8789 
8790 	if (e.error == 0) {
8791 		vnode_t *tvp;
8792 		rnode4_t *trp;
8793 		trp = VTOR4(vp);
8794 		tvp = vp;
8795 		if (IS_SHADOW(vp, trp))
8796 			tvp = RTOV4(trp);
8797 		vnevent_rmdir(tvp, dvp, nm, ct);
8798 	}
8799 
8800 	VN_RELE(vp);
8801 
8802 	return (e.error);
8803 }
8804 
8805 /* ARGSUSED */
8806 static int
8807 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr,
8808     caller_context_t *ct, int flags)
8809 {
8810 	int error;
8811 	vnode_t *vp;
8812 	rnode4_t *rp;
8813 	char *contents;
8814 	mntinfo4_t *mi = VTOMI4(dvp);
8815 
8816 	if (nfs_zone() != mi->mi_zone)
8817 		return (EPERM);
8818 	if (!(mi->mi_flags & MI4_SYMLINK))
8819 		return (EOPNOTSUPP);
8820 
8821 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8822 	if (error)
8823 		return (error);
8824 
8825 	ASSERT(nfs4_consistent_type(vp));
8826 	rp = VTOR4(vp);
8827 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8828 
8829 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8830 
8831 		if (contents != NULL) {
8832 			mutex_enter(&rp->r_statelock);
8833 			if (rp->r_symlink.contents == NULL) {
8834 				rp->r_symlink.len = strlen(tnm);
8835 				bcopy(tnm, contents, rp->r_symlink.len);
8836 				rp->r_symlink.contents = contents;
8837 				rp->r_symlink.size = MAXPATHLEN;
8838 				mutex_exit(&rp->r_statelock);
8839 			} else {
8840 				mutex_exit(&rp->r_statelock);
8841 				kmem_free((void *)contents, MAXPATHLEN);
8842 			}
8843 		}
8844 	}
8845 	VN_RELE(vp);
8846 
8847 	return (error);
8848 }
8849 
8850 
8851 /*
8852  * Read directory entries.
8853  * There are some weird things to look out for here.  The uio_loffset
8854  * field is either 0 or it is the offset returned from a previous
8855  * readdir.  It is an opaque value used by the server to find the
8856  * correct directory block to read. The count field is the number
8857  * of blocks to read on the server.  This is advisory only, the server
8858  * may return only one block's worth of entries.  Entries may be compressed
8859  * on the server.
8860  */
8861 /* ARGSUSED */
8862 static int
8863 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp,
8864 	caller_context_t *ct, int flags)
8865 {
8866 	int error;
8867 	uint_t count;
8868 	rnode4_t *rp;
8869 	rddir4_cache *rdc;
8870 	rddir4_cache *rrdc;
8871 
8872 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8873 		return (EIO);
8874 	rp = VTOR4(vp);
8875 
8876 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8877 
8878 	/*
8879 	 * Make sure that the directory cache is valid.
8880 	 */
8881 	if (rp->r_dir != NULL) {
8882 		if (nfs_disable_rddir_cache != 0) {
8883 			/*
8884 			 * Setting nfs_disable_rddir_cache in /etc/system
8885 			 * allows interoperability with servers that do not
8886 			 * properly update the attributes of directories.
8887 			 * Any cached information gets purged before an
8888 			 * access is made to it.
8889 			 */
8890 			nfs4_purge_rddir_cache(vp);
8891 		}
8892 
8893 		error = nfs4_validate_caches(vp, cr);
8894 		if (error)
8895 			return (error);
8896 	}
8897 
8898 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8899 
8900 	/*
8901 	 * Short circuit last readdir which always returns 0 bytes.
8902 	 * This can be done after the directory has been read through
8903 	 * completely at least once.  This will set r_direof which
8904 	 * can be used to find the value of the last cookie.
8905 	 */
8906 	mutex_enter(&rp->r_statelock);
8907 	if (rp->r_direof != NULL &&
8908 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8909 		mutex_exit(&rp->r_statelock);
8910 #ifdef DEBUG
8911 		nfs4_readdir_cache_shorts++;
8912 #endif
8913 		if (eofp)
8914 			*eofp = 1;
8915 		return (0);
8916 	}
8917 
8918 	/*
8919 	 * Look for a cache entry.  Cache entries are identified
8920 	 * by the NFS cookie value and the byte count requested.
8921 	 */
8922 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8923 
8924 	/*
8925 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8926 	 */
8927 	if (rdc == NULL) {
8928 		mutex_exit(&rp->r_statelock);
8929 		return (EINTR);
8930 	}
8931 
8932 	/*
8933 	 * Check to see if we need to fill this entry in.
8934 	 */
8935 	if (rdc->flags & RDDIRREQ) {
8936 		rdc->flags &= ~RDDIRREQ;
8937 		rdc->flags |= RDDIR;
8938 		mutex_exit(&rp->r_statelock);
8939 
8940 		/*
8941 		 * Do the readdir.
8942 		 */
8943 		nfs4readdir(vp, rdc, cr);
8944 
8945 		/*
8946 		 * Reacquire the lock, so that we can continue
8947 		 */
8948 		mutex_enter(&rp->r_statelock);
8949 		/*
8950 		 * The entry is now complete
8951 		 */
8952 		rdc->flags &= ~RDDIR;
8953 	}
8954 
8955 	ASSERT(!(rdc->flags & RDDIR));
8956 
8957 	/*
8958 	 * If an error occurred while attempting
8959 	 * to fill the cache entry, mark the entry invalid and
8960 	 * just return the error.
8961 	 */
8962 	if (rdc->error) {
8963 		error = rdc->error;
8964 		rdc->flags |= RDDIRREQ;
8965 		rddir4_cache_rele(rp, rdc);
8966 		mutex_exit(&rp->r_statelock);
8967 		return (error);
8968 	}
8969 
8970 	/*
8971 	 * The cache entry is complete and good,
8972 	 * copyout the dirent structs to the calling
8973 	 * thread.
8974 	 */
8975 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
8976 
8977 	/*
8978 	 * If no error occurred during the copyout,
8979 	 * update the offset in the uio struct to
8980 	 * contain the value of the next NFS 4 cookie
8981 	 * and set the eof value appropriately.
8982 	 */
8983 	if (!error) {
8984 		uiop->uio_loffset = rdc->nfs4_ncookie;
8985 		if (eofp)
8986 			*eofp = rdc->eof;
8987 	}
8988 
8989 	/*
8990 	 * Decide whether to do readahead.  Don't if we
8991 	 * have already read to the end of directory.
8992 	 */
8993 	if (rdc->eof) {
8994 		/*
8995 		 * Make the entry the direof only if it is cached
8996 		 */
8997 		if (rdc->flags & RDDIRCACHED)
8998 			rp->r_direof = rdc;
8999 		rddir4_cache_rele(rp, rdc);
9000 		mutex_exit(&rp->r_statelock);
9001 		return (error);
9002 	}
9003 
9004 	/* Determine if a readdir readahead should be done */
9005 	if (!(rp->r_flags & R4LOOKUP)) {
9006 		rddir4_cache_rele(rp, rdc);
9007 		mutex_exit(&rp->r_statelock);
9008 		return (error);
9009 	}
9010 
9011 	/*
9012 	 * Now look for a readahead entry.
9013 	 *
9014 	 * Check to see whether we found an entry for the readahead.
9015 	 * If so, we don't need to do anything further, so free the new
9016 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
9017 	 * it to the cache, and then initiate an asynchronous readdir
9018 	 * operation to fill it.
9019 	 */
9020 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
9021 
9022 	/*
9023 	 * A readdir cache entry could not be obtained for the readahead.  In
9024 	 * this case we skip the readahead and return.
9025 	 */
9026 	if (rrdc == NULL) {
9027 		rddir4_cache_rele(rp, rdc);
9028 		mutex_exit(&rp->r_statelock);
9029 		return (error);
9030 	}
9031 
9032 	/*
9033 	 * Check to see if we need to fill this entry in.
9034 	 */
9035 	if (rrdc->flags & RDDIRREQ) {
9036 		rrdc->flags &= ~RDDIRREQ;
9037 		rrdc->flags |= RDDIR;
9038 		rddir4_cache_rele(rp, rdc);
9039 		mutex_exit(&rp->r_statelock);
9040 #ifdef DEBUG
9041 		nfs4_readdir_readahead++;
9042 #endif
9043 		/*
9044 		 * Do the readdir.
9045 		 */
9046 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
9047 		return (error);
9048 	}
9049 
9050 	rddir4_cache_rele(rp, rrdc);
9051 	rddir4_cache_rele(rp, rdc);
9052 	mutex_exit(&rp->r_statelock);
9053 	return (error);
9054 }
9055 
9056 static int
9057 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9058 {
9059 	int error;
9060 	rnode4_t *rp;
9061 
9062 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9063 
9064 	rp = VTOR4(vp);
9065 
9066 	/*
9067 	 * Obtain the readdir results for the caller.
9068 	 */
9069 	nfs4readdir(vp, rdc, cr);
9070 
9071 	mutex_enter(&rp->r_statelock);
9072 	/*
9073 	 * The entry is now complete
9074 	 */
9075 	rdc->flags &= ~RDDIR;
9076 
9077 	error = rdc->error;
9078 	if (error)
9079 		rdc->flags |= RDDIRREQ;
9080 	rddir4_cache_rele(rp, rdc);
9081 	mutex_exit(&rp->r_statelock);
9082 
9083 	return (error);
9084 }
9085 
9086 /*
9087  * Read directory entries.
9088  * There are some weird things to look out for here.  The uio_loffset
9089  * field is either 0 or it is the offset returned from a previous
9090  * readdir.  It is an opaque value used by the server to find the
9091  * correct directory block to read. The count field is the number
9092  * of blocks to read on the server.  This is advisory only, the server
9093  * may return only one block's worth of entries.  Entries may be compressed
9094  * on the server.
9095  *
9096  * Generates the following compound request:
9097  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9098  *    must include a Lookupp as well. In this case, send:
9099  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9100  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9101  *
9102  * Get complete attributes and filehandles for entries if this is the
9103  * first read of the directory. Otherwise, just get fileid's.
9104  */
9105 static void
9106 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9107 {
9108 	COMPOUND4args_clnt args;
9109 	COMPOUND4res_clnt res;
9110 	READDIR4args *rargs;
9111 	READDIR4res_clnt *rd_res;
9112 	bitmap4 rd_bitsval;
9113 	nfs_argop4 argop[5];
9114 	nfs_resop4 *resop;
9115 	rnode4_t *rp = VTOR4(vp);
9116 	mntinfo4_t *mi = VTOMI4(vp);
9117 	int doqueue;
9118 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9119 	vnode_t *dvp;
9120 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9121 	int num_ops, res_opcnt;
9122 	bool_t needrecov = FALSE;
9123 	nfs4_recov_state_t recov_state;
9124 	hrtime_t t;
9125 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9126 
9127 	ASSERT(nfs_zone() == mi->mi_zone);
9128 	ASSERT(rdc->flags & RDDIR);
9129 	ASSERT(rdc->entries == NULL);
9130 
9131 	/*
9132 	 * If rp were a stub, it should have triggered and caused
9133 	 * a mount for us to get this far.
9134 	 */
9135 	ASSERT(!RP_ISSTUB(rp));
9136 
9137 	num_ops = 2;
9138 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9139 		/*
9140 		 * Since nfsv4 readdir may not return entries for "." and "..",
9141 		 * the client must recreate them:
9142 		 * To find the correct nodeid, do the following:
9143 		 * For current node, get nodeid from dnlc.
9144 		 * - if current node is rootvp, set pnodeid to nodeid.
9145 		 * - else if parent is in the dnlc, get its nodeid from there.
9146 		 * - else add LOOKUPP+GETATTR to compound.
9147 		 */
9148 		nodeid = rp->r_attr.va_nodeid;
9149 		if (vp->v_flag & VROOT) {
9150 			pnodeid = nodeid;	/* root of mount point */
9151 		} else {
9152 			dvp = dnlc_lookup(vp, "..");
9153 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9154 				/* parent in dnlc cache - no need for otw */
9155 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9156 			} else {
9157 				/*
9158 				 * parent not in dnlc cache,
9159 				 * do lookupp to get its id
9160 				 */
9161 				num_ops = 5;
9162 				pnodeid = 0; /* set later by getattr parent */
9163 			}
9164 			if (dvp)
9165 				VN_RELE(dvp);
9166 		}
9167 	}
9168 	recov_state.rs_flags = 0;
9169 	recov_state.rs_num_retry_despite_err = 0;
9170 
9171 	/* Save the original mount point security flavor */
9172 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9173 
9174 recov_retry:
9175 	args.ctag = TAG_READDIR;
9176 
9177 	args.array = argop;
9178 	args.array_len = num_ops;
9179 
9180 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9181 	    &recov_state, NULL)) {
9182 		/*
9183 		 * If readdir a node that is a stub for a crossed mount point,
9184 		 * keep the original secinfo flavor for the current file
9185 		 * system, not the crossed one.
9186 		 */
9187 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9188 		rdc->error = e.error;
9189 		return;
9190 	}
9191 
9192 	/*
9193 	 * Determine which attrs to request for dirents.  This code
9194 	 * must be protected by nfs4_start/end_fop because of r_server
9195 	 * (which will change during failover recovery).
9196 	 *
9197 	 */
9198 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9199 		/*
9200 		 * Get all vattr attrs plus filehandle and rdattr_error
9201 		 */
9202 		rd_bitsval = NFS4_VATTR_MASK |
9203 		    FATTR4_RDATTR_ERROR_MASK |
9204 		    FATTR4_FILEHANDLE_MASK;
9205 
9206 		if (rp->r_flags & R4READDIRWATTR) {
9207 			mutex_enter(&rp->r_statelock);
9208 			rp->r_flags &= ~R4READDIRWATTR;
9209 			mutex_exit(&rp->r_statelock);
9210 		}
9211 	} else {
9212 		servinfo4_t *svp = rp->r_server;
9213 
9214 		/*
9215 		 * Already read directory. Use readdir with
9216 		 * no attrs (except for mounted_on_fileid) for updates.
9217 		 */
9218 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9219 
9220 		/*
9221 		 * request mounted on fileid if supported, else request
9222 		 * fileid.  maybe we should verify that fileid is supported
9223 		 * and request something else if not.
9224 		 */
9225 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9226 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9227 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9228 		nfs_rw_exit(&svp->sv_lock);
9229 	}
9230 
9231 	/* putfh directory fh */
9232 	argop[0].argop = OP_CPUTFH;
9233 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9234 
9235 	argop[1].argop = OP_READDIR;
9236 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9237 	/*
9238 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9239 	 * cookie 0 should be used over-the-wire to start reading at
9240 	 * the beginning of the directory excluding "." and "..".
9241 	 */
9242 	if (rdc->nfs4_cookie == 0 ||
9243 	    rdc->nfs4_cookie == 1 ||
9244 	    rdc->nfs4_cookie == 2) {
9245 		rargs->cookie = (nfs_cookie4)0;
9246 		rargs->cookieverf = 0;
9247 	} else {
9248 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9249 		mutex_enter(&rp->r_statelock);
9250 		rargs->cookieverf = rp->r_cookieverf4;
9251 		mutex_exit(&rp->r_statelock);
9252 	}
9253 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9254 	rargs->maxcount = mi->mi_tsize;
9255 	rargs->attr_request = rd_bitsval;
9256 	rargs->rdc = rdc;
9257 	rargs->dvp = vp;
9258 	rargs->mi = mi;
9259 	rargs->cr = cr;
9260 
9261 
9262 	/*
9263 	 * If count < than the minimum required, we return no entries
9264 	 * and fail with EINVAL
9265 	 */
9266 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9267 		rdc->error = EINVAL;
9268 		goto out;
9269 	}
9270 
9271 	if (args.array_len == 5) {
9272 		/*
9273 		 * Add lookupp and getattr for parent nodeid.
9274 		 */
9275 		argop[2].argop = OP_LOOKUPP;
9276 
9277 		argop[3].argop = OP_GETFH;
9278 
9279 		/* getattr parent */
9280 		argop[4].argop = OP_GETATTR;
9281 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9282 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9283 	}
9284 
9285 	doqueue = 1;
9286 
9287 	if (mi->mi_io_kstats) {
9288 		mutex_enter(&mi->mi_lock);
9289 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9290 		mutex_exit(&mi->mi_lock);
9291 	}
9292 
9293 	/* capture the time of this call */
9294 	rargs->t = t = gethrtime();
9295 
9296 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9297 
9298 	if (mi->mi_io_kstats) {
9299 		mutex_enter(&mi->mi_lock);
9300 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9301 		mutex_exit(&mi->mi_lock);
9302 	}
9303 
9304 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9305 
9306 	/*
9307 	 * If RPC error occurred and it isn't an error that
9308 	 * triggers recovery, then go ahead and fail now.
9309 	 */
9310 	if (e.error != 0 && !needrecov) {
9311 		rdc->error = e.error;
9312 		goto out;
9313 	}
9314 
9315 	if (needrecov) {
9316 		bool_t abort;
9317 
9318 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9319 		    "nfs4readdir: initiating recovery.\n"));
9320 
9321 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9322 		    NULL, OP_READDIR, NULL);
9323 		if (abort == FALSE) {
9324 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9325 			    &recov_state, needrecov);
9326 			if (!e.error)
9327 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9328 				    (caddr_t)&res);
9329 			if (rdc->entries != NULL) {
9330 				kmem_free(rdc->entries, rdc->entlen);
9331 				rdc->entries = NULL;
9332 			}
9333 			goto recov_retry;
9334 		}
9335 
9336 		if (e.error != 0) {
9337 			rdc->error = e.error;
9338 			goto out;
9339 		}
9340 
9341 		/* fall through for res.status case */
9342 	}
9343 
9344 	res_opcnt = res.array_len;
9345 
9346 	/*
9347 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9348 	 * failure here.  Subsequent ops are for filling out dot-dot
9349 	 * dirent, and if they fail, we still want to give the caller
9350 	 * the dirents returned by (the successful) READDIR op, so we need
9351 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9352 	 *
9353 	 * One example where PUTFH+READDIR ops would succeed but
9354 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9355 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9356 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9357 	 * x perm.  We need to come up with a non-vendor-specific way
9358 	 * for a POSIX server to return d_ino from dotdot's dirent if
9359 	 * client only requests mounted_on_fileid, and just say the
9360 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9361 	 * client requested any mandatory attrs, server would be required
9362 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9363 	 * for dotdot.
9364 	 */
9365 
9366 	if (res.status) {
9367 		if (res_opcnt <= 2) {
9368 			e.error = geterrno4(res.status);
9369 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9370 			    &recov_state, needrecov);
9371 			nfs4_purge_stale_fh(e.error, vp, cr);
9372 			rdc->error = e.error;
9373 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9374 			if (rdc->entries != NULL) {
9375 				kmem_free(rdc->entries, rdc->entlen);
9376 				rdc->entries = NULL;
9377 			}
9378 			/*
9379 			 * If readdir a node that is a stub for a
9380 			 * crossed mount point, keep the original
9381 			 * secinfo flavor for the current file system,
9382 			 * not the crossed one.
9383 			 */
9384 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9385 			return;
9386 		}
9387 	}
9388 
9389 	resop = &res.array[1];	/* readdir res */
9390 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9391 
9392 	mutex_enter(&rp->r_statelock);
9393 	rp->r_cookieverf4 = rd_res->cookieverf;
9394 	mutex_exit(&rp->r_statelock);
9395 
9396 	/*
9397 	 * For "." and ".." entries
9398 	 * e.g.
9399 	 *	seek(cookie=0) -> "." entry with d_off = 1
9400 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9401 	 */
9402 	if (cookie == (nfs_cookie4) 0) {
9403 		if (rd_res->dotp)
9404 			rd_res->dotp->d_ino = nodeid;
9405 		if (rd_res->dotdotp)
9406 			rd_res->dotdotp->d_ino = pnodeid;
9407 	}
9408 	if (cookie == (nfs_cookie4) 1) {
9409 		if (rd_res->dotdotp)
9410 			rd_res->dotdotp->d_ino = pnodeid;
9411 	}
9412 
9413 
9414 	/* LOOKUPP+GETATTR attemped */
9415 	if (args.array_len == 5 && rd_res->dotdotp) {
9416 		if (res.status == NFS4_OK && res_opcnt == 5) {
9417 			nfs_fh4 *fhp;
9418 			nfs4_sharedfh_t *sfhp;
9419 			vnode_t *pvp;
9420 			nfs4_ga_res_t *garp;
9421 
9422 			resop++;	/* lookupp */
9423 			resop++;	/* getfh   */
9424 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9425 
9426 			resop++;	/* getattr of parent */
9427 
9428 			/*
9429 			 * First, take care of finishing the
9430 			 * readdir results.
9431 			 */
9432 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9433 			/*
9434 			 * The d_ino of .. must be the inode number
9435 			 * of the mounted filesystem.
9436 			 */
9437 			if (garp->n4g_va.va_mask & AT_NODEID)
9438 				rd_res->dotdotp->d_ino =
9439 				    garp->n4g_va.va_nodeid;
9440 
9441 
9442 			/*
9443 			 * Next, create the ".." dnlc entry
9444 			 */
9445 			sfhp = sfh4_get(fhp, mi);
9446 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9447 				dnlc_update(vp, "..", pvp);
9448 				VN_RELE(pvp);
9449 			}
9450 			sfh4_rele(&sfhp);
9451 		}
9452 	}
9453 
9454 	if (mi->mi_io_kstats) {
9455 		mutex_enter(&mi->mi_lock);
9456 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9457 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9458 		mutex_exit(&mi->mi_lock);
9459 	}
9460 
9461 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9462 
9463 out:
9464 	/*
9465 	 * If readdir a node that is a stub for a crossed mount point,
9466 	 * keep the original secinfo flavor for the current file system,
9467 	 * not the crossed one.
9468 	 */
9469 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9470 
9471 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9472 }
9473 
9474 
9475 static int
9476 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9477 {
9478 	rnode4_t *rp = VTOR4(bp->b_vp);
9479 	int count;
9480 	int error;
9481 	cred_t *cred_otw = NULL;
9482 	offset_t offset;
9483 	nfs4_open_stream_t *osp = NULL;
9484 	bool_t first_time = TRUE;	/* first time getting otw cred */
9485 	bool_t last_time = FALSE;	/* last time getting otw cred */
9486 
9487 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9488 
9489 	DTRACE_IO1(start, struct buf *, bp);
9490 	offset = ldbtob(bp->b_lblkno);
9491 
9492 	if (bp->b_flags & B_READ) {
9493 	read_again:
9494 		/*
9495 		 * Releases the osp, if it is provided.
9496 		 * Puts a hold on the cred_otw and the new osp (if found).
9497 		 */
9498 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9499 		    &first_time, &last_time);
9500 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9501 		    offset, bp->b_bcount, &bp->b_resid, cred_otw,
9502 		    readahead, NULL);
9503 		crfree(cred_otw);
9504 		if (!error) {
9505 			if (bp->b_resid) {
9506 				/*
9507 				 * Didn't get it all because we hit EOF,
9508 				 * zero all the memory beyond the EOF.
9509 				 */
9510 				/* bzero(rdaddr + */
9511 				bzero(bp->b_un.b_addr +
9512 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9513 			}
9514 			mutex_enter(&rp->r_statelock);
9515 			if (bp->b_resid == bp->b_bcount &&
9516 			    offset >= rp->r_size) {
9517 				/*
9518 				 * We didn't read anything at all as we are
9519 				 * past EOF.  Return an error indicator back
9520 				 * but don't destroy the pages (yet).
9521 				 */
9522 				error = NFS_EOF;
9523 			}
9524 			mutex_exit(&rp->r_statelock);
9525 		} else if (error == EACCES && last_time == FALSE) {
9526 				goto read_again;
9527 		}
9528 	} else {
9529 		if (!(rp->r_flags & R4STALE)) {
9530 write_again:
9531 			/*
9532 			 * Releases the osp, if it is provided.
9533 			 * Puts a hold on the cred_otw and the new
9534 			 * osp (if found).
9535 			 */
9536 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9537 			    &first_time, &last_time);
9538 			mutex_enter(&rp->r_statelock);
9539 			count = MIN(bp->b_bcount, rp->r_size - offset);
9540 			mutex_exit(&rp->r_statelock);
9541 			if (count < 0)
9542 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9543 #ifdef DEBUG
9544 			if (count == 0) {
9545 				zoneid_t zoneid = getzoneid();
9546 
9547 				zcmn_err(zoneid, CE_WARN,
9548 				    "nfs4_bio: zero length write at %lld",
9549 				    offset);
9550 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9551 				    "b_bcount=%ld, file size=%lld",
9552 				    rp->r_flags, (long)bp->b_bcount,
9553 				    rp->r_size);
9554 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9555 				if (nfs4_bio_do_stop)
9556 					debug_enter("nfs4_bio");
9557 			}
9558 #endif
9559 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9560 			    count, cred_otw, stab_comm);
9561 			if (error == EACCES && last_time == FALSE) {
9562 				crfree(cred_otw);
9563 				goto write_again;
9564 			}
9565 			bp->b_error = error;
9566 			if (error && error != EINTR &&
9567 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9568 				/*
9569 				 * Don't print EDQUOT errors on the console.
9570 				 * Don't print asynchronous EACCES errors.
9571 				 * Don't print EFBIG errors.
9572 				 * Print all other write errors.
9573 				 */
9574 				if (error != EDQUOT && error != EFBIG &&
9575 				    (error != EACCES ||
9576 				    !(bp->b_flags & B_ASYNC)))
9577 					nfs4_write_error(bp->b_vp,
9578 					    error, cred_otw);
9579 				/*
9580 				 * Update r_error and r_flags as appropriate.
9581 				 * If the error was ESTALE, then mark the
9582 				 * rnode as not being writeable and save
9583 				 * the error status.  Otherwise, save any
9584 				 * errors which occur from asynchronous
9585 				 * page invalidations.  Any errors occurring
9586 				 * from other operations should be saved
9587 				 * by the caller.
9588 				 */
9589 				mutex_enter(&rp->r_statelock);
9590 				if (error == ESTALE) {
9591 					rp->r_flags |= R4STALE;
9592 					if (!rp->r_error)
9593 						rp->r_error = error;
9594 				} else if (!rp->r_error &&
9595 				    (bp->b_flags &
9596 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9597 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9598 					rp->r_error = error;
9599 				}
9600 				mutex_exit(&rp->r_statelock);
9601 			}
9602 			crfree(cred_otw);
9603 		} else {
9604 			error = rp->r_error;
9605 			/*
9606 			 * A close may have cleared r_error, if so,
9607 			 * propagate ESTALE error return properly
9608 			 */
9609 			if (error == 0)
9610 				error = ESTALE;
9611 		}
9612 	}
9613 
9614 	if (error != 0 && error != NFS_EOF)
9615 		bp->b_flags |= B_ERROR;
9616 
9617 	if (osp)
9618 		open_stream_rele(osp, rp);
9619 
9620 	DTRACE_IO1(done, struct buf *, bp);
9621 
9622 	return (error);
9623 }
9624 
9625 /* ARGSUSED */
9626 int
9627 nfs4_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
9628 {
9629 	return (EREMOTE);
9630 }
9631 
9632 /* ARGSUSED2 */
9633 int
9634 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9635 {
9636 	rnode4_t *rp = VTOR4(vp);
9637 
9638 	if (!write_lock) {
9639 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9640 		return (V_WRITELOCK_FALSE);
9641 	}
9642 
9643 	if ((rp->r_flags & R4DIRECTIO) ||
9644 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9645 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9646 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9647 			return (V_WRITELOCK_FALSE);
9648 		nfs_rw_exit(&rp->r_rwlock);
9649 	}
9650 
9651 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9652 	return (V_WRITELOCK_TRUE);
9653 }
9654 
9655 /* ARGSUSED */
9656 void
9657 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9658 {
9659 	rnode4_t *rp = VTOR4(vp);
9660 
9661 	nfs_rw_exit(&rp->r_rwlock);
9662 }
9663 
9664 /* ARGSUSED */
9665 static int
9666 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp, caller_context_t *ct)
9667 {
9668 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9669 		return (EIO);
9670 
9671 	/*
9672 	 * Because we stuff the readdir cookie into the offset field
9673 	 * someone may attempt to do an lseek with the cookie which
9674 	 * we want to succeed.
9675 	 */
9676 	if (vp->v_type == VDIR)
9677 		return (0);
9678 	if (*noffp < 0)
9679 		return (EINVAL);
9680 	return (0);
9681 }
9682 
9683 
9684 /*
9685  * Return all the pages from [off..off+len) in file
9686  */
9687 /* ARGSUSED */
9688 static int
9689 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9690     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9691 	enum seg_rw rw, cred_t *cr, caller_context_t *ct)
9692 {
9693 	rnode4_t *rp;
9694 	int error;
9695 	mntinfo4_t *mi;
9696 
9697 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9698 		return (EIO);
9699 	rp = VTOR4(vp);
9700 	if (IS_SHADOW(vp, rp))
9701 		vp = RTOV4(rp);
9702 
9703 	if (vp->v_flag & VNOMAP)
9704 		return (ENOSYS);
9705 
9706 	if (protp != NULL)
9707 		*protp = PROT_ALL;
9708 
9709 	/*
9710 	 * Now validate that the caches are up to date.
9711 	 */
9712 	if (error = nfs4_validate_caches(vp, cr))
9713 		return (error);
9714 
9715 	mi = VTOMI4(vp);
9716 retry:
9717 	mutex_enter(&rp->r_statelock);
9718 
9719 	/*
9720 	 * Don't create dirty pages faster than they
9721 	 * can be cleaned so that the system doesn't
9722 	 * get imbalanced.  If the async queue is
9723 	 * maxed out, then wait for it to drain before
9724 	 * creating more dirty pages.  Also, wait for
9725 	 * any threads doing pagewalks in the vop_getattr
9726 	 * entry points so that they don't block for
9727 	 * long periods.
9728 	 */
9729 	if (rw == S_CREATE) {
9730 		while ((mi->mi_max_threads != 0 &&
9731 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
9732 		    rp->r_gcount > 0)
9733 			cv_wait(&rp->r_cv, &rp->r_statelock);
9734 	}
9735 
9736 	/*
9737 	 * If we are getting called as a side effect of an nfs_write()
9738 	 * operation the local file size might not be extended yet.
9739 	 * In this case we want to be able to return pages of zeroes.
9740 	 */
9741 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9742 		NFS4_DEBUG(nfs4_pageio_debug,
9743 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9744 		    "len=%llu, size=%llu, attrsize =%llu", off,
9745 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9746 		mutex_exit(&rp->r_statelock);
9747 		return (EFAULT);		/* beyond EOF */
9748 	}
9749 
9750 	mutex_exit(&rp->r_statelock);
9751 
9752 	if (len <= PAGESIZE) {
9753 		error = nfs4_getapage(vp, off, len, protp, pl, plsz,
9754 		    seg, addr, rw, cr);
9755 		NFS4_DEBUG(nfs4_pageio_debug && error,
9756 		    (CE_NOTE, "getpage error %d; off=%lld, "
9757 		    "len=%lld", error, off, (u_longlong_t)len));
9758 	} else {
9759 		error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9760 		    pl, plsz, seg, addr, rw, cr);
9761 		NFS4_DEBUG(nfs4_pageio_debug && error,
9762 		    (CE_NOTE, "getpages error %d; off=%lld, "
9763 		    "len=%lld", error, off, (u_longlong_t)len));
9764 	}
9765 
9766 	switch (error) {
9767 	case NFS_EOF:
9768 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9769 		goto retry;
9770 	case ESTALE:
9771 		nfs4_purge_stale_fh(error, vp, cr);
9772 	}
9773 
9774 	return (error);
9775 }
9776 
9777 /*
9778  * Called from pvn_getpages or nfs4_getpage to get a particular page.
9779  */
9780 /* ARGSUSED */
9781 static int
9782 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9783     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9784     enum seg_rw rw, cred_t *cr)
9785 {
9786 	rnode4_t *rp;
9787 	uint_t bsize;
9788 	struct buf *bp;
9789 	page_t *pp;
9790 	u_offset_t lbn;
9791 	u_offset_t io_off;
9792 	u_offset_t blkoff;
9793 	u_offset_t rablkoff;
9794 	size_t io_len;
9795 	uint_t blksize;
9796 	int error;
9797 	int readahead;
9798 	int readahead_issued = 0;
9799 	int ra_window; /* readahead window */
9800 	page_t *pagefound;
9801 	page_t *savepp;
9802 
9803 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9804 		return (EIO);
9805 
9806 	rp = VTOR4(vp);
9807 	ASSERT(!IS_SHADOW(vp, rp));
9808 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9809 
9810 reread:
9811 	bp = NULL;
9812 	pp = NULL;
9813 	pagefound = NULL;
9814 
9815 	if (pl != NULL)
9816 		pl[0] = NULL;
9817 
9818 	error = 0;
9819 	lbn = off / bsize;
9820 	blkoff = lbn * bsize;
9821 
9822 	/*
9823 	 * Queueing up the readahead before doing the synchronous read
9824 	 * results in a significant increase in read throughput because
9825 	 * of the increased parallelism between the async threads and
9826 	 * the process context.
9827 	 */
9828 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9829 	    rw != S_CREATE &&
9830 	    !(vp->v_flag & VNOCACHE)) {
9831 		mutex_enter(&rp->r_statelock);
9832 
9833 		/*
9834 		 * Calculate the number of readaheads to do.
9835 		 * a) No readaheads at offset = 0.
9836 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9837 		 *    window is closed.
9838 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9839 		 *    upon how far the readahead window is open or close.
9840 		 * d) No readaheads if rp->r_nextr is not within the scope
9841 		 *    of the readahead window (random i/o).
9842 		 */
9843 
9844 		if (off == 0)
9845 			readahead = 0;
9846 		else if (blkoff == rp->r_nextr)
9847 			readahead = nfs4_nra;
9848 		else if (rp->r_nextr > blkoff &&
9849 		    ((ra_window = (rp->r_nextr - blkoff) / bsize)
9850 		    <= (nfs4_nra - 1)))
9851 			readahead = nfs4_nra - ra_window;
9852 		else
9853 			readahead = 0;
9854 
9855 		rablkoff = rp->r_nextr;
9856 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9857 			mutex_exit(&rp->r_statelock);
9858 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9859 			    addr + (rablkoff + bsize - off),
9860 			    seg, cr, nfs4_readahead) < 0) {
9861 				mutex_enter(&rp->r_statelock);
9862 				break;
9863 			}
9864 			readahead--;
9865 			rablkoff += bsize;
9866 			/*
9867 			 * Indicate that we did a readahead so
9868 			 * readahead offset is not updated
9869 			 * by the synchronous read below.
9870 			 */
9871 			readahead_issued = 1;
9872 			mutex_enter(&rp->r_statelock);
9873 			/*
9874 			 * set readahead offset to
9875 			 * offset of last async readahead
9876 			 * request.
9877 			 */
9878 			rp->r_nextr = rablkoff;
9879 		}
9880 		mutex_exit(&rp->r_statelock);
9881 	}
9882 
9883 again:
9884 	if ((pagefound = page_exists(vp, off)) == NULL) {
9885 		if (pl == NULL) {
9886 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9887 			    nfs4_readahead);
9888 		} else if (rw == S_CREATE) {
9889 			/*
9890 			 * Block for this page is not allocated, or the offset
9891 			 * is beyond the current allocation size, or we're
9892 			 * allocating a swap slot and the page was not found,
9893 			 * so allocate it and return a zero page.
9894 			 */
9895 			if ((pp = page_create_va(vp, off,
9896 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9897 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9898 			io_len = PAGESIZE;
9899 			mutex_enter(&rp->r_statelock);
9900 			rp->r_nextr = off + PAGESIZE;
9901 			mutex_exit(&rp->r_statelock);
9902 		} else {
9903 			/*
9904 			 * Need to go to server to get a block
9905 			 */
9906 			mutex_enter(&rp->r_statelock);
9907 			if (blkoff < rp->r_size &&
9908 			    blkoff + bsize > rp->r_size) {
9909 				/*
9910 				 * If less than a block left in
9911 				 * file read less than a block.
9912 				 */
9913 				if (rp->r_size <= off) {
9914 					/*
9915 					 * Trying to access beyond EOF,
9916 					 * set up to get at least one page.
9917 					 */
9918 					blksize = off + PAGESIZE - blkoff;
9919 				} else
9920 					blksize = rp->r_size - blkoff;
9921 			} else if ((off == 0) ||
9922 			    (off != rp->r_nextr && !readahead_issued)) {
9923 				blksize = PAGESIZE;
9924 				blkoff = off; /* block = page here */
9925 			} else
9926 				blksize = bsize;
9927 			mutex_exit(&rp->r_statelock);
9928 
9929 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9930 			    &io_len, blkoff, blksize, 0);
9931 
9932 			/*
9933 			 * Some other thread has entered the page,
9934 			 * so just use it.
9935 			 */
9936 			if (pp == NULL)
9937 				goto again;
9938 
9939 			/*
9940 			 * Now round the request size up to page boundaries.
9941 			 * This ensures that the entire page will be
9942 			 * initialized to zeroes if EOF is encountered.
9943 			 */
9944 			io_len = ptob(btopr(io_len));
9945 
9946 			bp = pageio_setup(pp, io_len, vp, B_READ);
9947 			ASSERT(bp != NULL);
9948 
9949 			/*
9950 			 * pageio_setup should have set b_addr to 0.  This
9951 			 * is correct since we want to do I/O on a page
9952 			 * boundary.  bp_mapin will use this addr to calculate
9953 			 * an offset, and then set b_addr to the kernel virtual
9954 			 * address it allocated for us.
9955 			 */
9956 			ASSERT(bp->b_un.b_addr == 0);
9957 
9958 			bp->b_edev = 0;
9959 			bp->b_dev = 0;
9960 			bp->b_lblkno = lbtodb(io_off);
9961 			bp->b_file = vp;
9962 			bp->b_offset = (offset_t)off;
9963 			bp_mapin(bp);
9964 
9965 			/*
9966 			 * If doing a write beyond what we believe is EOF,
9967 			 * don't bother trying to read the pages from the
9968 			 * server, we'll just zero the pages here.  We
9969 			 * don't check that the rw flag is S_WRITE here
9970 			 * because some implementations may attempt a
9971 			 * read access to the buffer before copying data.
9972 			 */
9973 			mutex_enter(&rp->r_statelock);
9974 			if (io_off >= rp->r_size && seg == segkmap) {
9975 				mutex_exit(&rp->r_statelock);
9976 				bzero(bp->b_un.b_addr, io_len);
9977 			} else {
9978 				mutex_exit(&rp->r_statelock);
9979 				error = nfs4_bio(bp, NULL, cr, FALSE);
9980 			}
9981 
9982 			/*
9983 			 * Unmap the buffer before freeing it.
9984 			 */
9985 			bp_mapout(bp);
9986 			pageio_done(bp);
9987 
9988 			savepp = pp;
9989 			do {
9990 				pp->p_fsdata = C_NOCOMMIT;
9991 			} while ((pp = pp->p_next) != savepp);
9992 
9993 			if (error == NFS_EOF) {
9994 				/*
9995 				 * If doing a write system call just return
9996 				 * zeroed pages, else user tried to get pages
9997 				 * beyond EOF, return error.  We don't check
9998 				 * that the rw flag is S_WRITE here because
9999 				 * some implementations may attempt a read
10000 				 * access to the buffer before copying data.
10001 				 */
10002 				if (seg == segkmap)
10003 					error = 0;
10004 				else
10005 					error = EFAULT;
10006 			}
10007 
10008 			if (!readahead_issued && !error) {
10009 				mutex_enter(&rp->r_statelock);
10010 				rp->r_nextr = io_off + io_len;
10011 				mutex_exit(&rp->r_statelock);
10012 			}
10013 		}
10014 	}
10015 
10016 out:
10017 	if (pl == NULL)
10018 		return (error);
10019 
10020 	if (error) {
10021 		if (pp != NULL)
10022 			pvn_read_done(pp, B_ERROR);
10023 		return (error);
10024 	}
10025 
10026 	if (pagefound) {
10027 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
10028 
10029 		/*
10030 		 * Page exists in the cache, acquire the appropriate lock.
10031 		 * If this fails, start all over again.
10032 		 */
10033 		if ((pp = page_lookup(vp, off, se)) == NULL) {
10034 #ifdef DEBUG
10035 			nfs4_lostpage++;
10036 #endif
10037 			goto reread;
10038 		}
10039 		pl[0] = pp;
10040 		pl[1] = NULL;
10041 		return (0);
10042 	}
10043 
10044 	if (pp != NULL)
10045 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
10046 
10047 	return (error);
10048 }
10049 
10050 static void
10051 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
10052     cred_t *cr)
10053 {
10054 	int error;
10055 	page_t *pp;
10056 	u_offset_t io_off;
10057 	size_t io_len;
10058 	struct buf *bp;
10059 	uint_t bsize, blksize;
10060 	rnode4_t *rp = VTOR4(vp);
10061 	page_t *savepp;
10062 
10063 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10064 
10065 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10066 
10067 	mutex_enter(&rp->r_statelock);
10068 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
10069 		/*
10070 		 * If less than a block left in file read less
10071 		 * than a block.
10072 		 */
10073 		blksize = rp->r_size - blkoff;
10074 	} else
10075 		blksize = bsize;
10076 	mutex_exit(&rp->r_statelock);
10077 
10078 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
10079 	    &io_off, &io_len, blkoff, blksize, 1);
10080 	/*
10081 	 * The isra flag passed to the kluster function is 1, we may have
10082 	 * gotten a return value of NULL for a variety of reasons (# of free
10083 	 * pages < minfree, someone entered the page on the vnode etc). In all
10084 	 * cases, we want to punt on the readahead.
10085 	 */
10086 	if (pp == NULL)
10087 		return;
10088 
10089 	/*
10090 	 * Now round the request size up to page boundaries.
10091 	 * This ensures that the entire page will be
10092 	 * initialized to zeroes if EOF is encountered.
10093 	 */
10094 	io_len = ptob(btopr(io_len));
10095 
10096 	bp = pageio_setup(pp, io_len, vp, B_READ);
10097 	ASSERT(bp != NULL);
10098 
10099 	/*
10100 	 * pageio_setup should have set b_addr to 0.  This is correct since
10101 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10102 	 * to calculate an offset, and then set b_addr to the kernel virtual
10103 	 * address it allocated for us.
10104 	 */
10105 	ASSERT(bp->b_un.b_addr == 0);
10106 
10107 	bp->b_edev = 0;
10108 	bp->b_dev = 0;
10109 	bp->b_lblkno = lbtodb(io_off);
10110 	bp->b_file = vp;
10111 	bp->b_offset = (offset_t)blkoff;
10112 	bp_mapin(bp);
10113 
10114 	/*
10115 	 * If doing a write beyond what we believe is EOF, don't bother trying
10116 	 * to read the pages from the server, we'll just zero the pages here.
10117 	 * We don't check that the rw flag is S_WRITE here because some
10118 	 * implementations may attempt a read access to the buffer before
10119 	 * copying data.
10120 	 */
10121 	mutex_enter(&rp->r_statelock);
10122 	if (io_off >= rp->r_size && seg == segkmap) {
10123 		mutex_exit(&rp->r_statelock);
10124 		bzero(bp->b_un.b_addr, io_len);
10125 		error = 0;
10126 	} else {
10127 		mutex_exit(&rp->r_statelock);
10128 		error = nfs4_bio(bp, NULL, cr, TRUE);
10129 		if (error == NFS_EOF)
10130 			error = 0;
10131 	}
10132 
10133 	/*
10134 	 * Unmap the buffer before freeing it.
10135 	 */
10136 	bp_mapout(bp);
10137 	pageio_done(bp);
10138 
10139 	savepp = pp;
10140 	do {
10141 		pp->p_fsdata = C_NOCOMMIT;
10142 	} while ((pp = pp->p_next) != savepp);
10143 
10144 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10145 
10146 	/*
10147 	 * In case of error set readahead offset
10148 	 * to the lowest offset.
10149 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10150 	 */
10151 	if (error && rp->r_nextr > io_off) {
10152 		mutex_enter(&rp->r_statelock);
10153 		if (rp->r_nextr > io_off)
10154 			rp->r_nextr = io_off;
10155 		mutex_exit(&rp->r_statelock);
10156 	}
10157 }
10158 
10159 /*
10160  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10161  * If len == 0, do from off to EOF.
10162  *
10163  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10164  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10165  * (from pageout).
10166  */
10167 /* ARGSUSED */
10168 static int
10169 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
10170 	caller_context_t *ct)
10171 {
10172 	int error;
10173 	rnode4_t *rp;
10174 
10175 	ASSERT(cr != NULL);
10176 
10177 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10178 		return (EIO);
10179 
10180 	rp = VTOR4(vp);
10181 	if (IS_SHADOW(vp, rp))
10182 		vp = RTOV4(rp);
10183 
10184 	/*
10185 	 * XXX - Why should this check be made here?
10186 	 */
10187 	if (vp->v_flag & VNOMAP)
10188 		return (ENOSYS);
10189 
10190 	if (len == 0 && !(flags & B_INVAL) &&
10191 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10192 		return (0);
10193 
10194 	mutex_enter(&rp->r_statelock);
10195 	rp->r_count++;
10196 	mutex_exit(&rp->r_statelock);
10197 	error = nfs4_putpages(vp, off, len, flags, cr);
10198 	mutex_enter(&rp->r_statelock);
10199 	rp->r_count--;
10200 	cv_broadcast(&rp->r_cv);
10201 	mutex_exit(&rp->r_statelock);
10202 
10203 	return (error);
10204 }
10205 
10206 /*
10207  * Write out a single page, possibly klustering adjacent dirty pages.
10208  */
10209 int
10210 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10211     int flags, cred_t *cr)
10212 {
10213 	u_offset_t io_off;
10214 	u_offset_t lbn_off;
10215 	u_offset_t lbn;
10216 	size_t io_len;
10217 	uint_t bsize;
10218 	int error;
10219 	rnode4_t *rp;
10220 
10221 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10222 	ASSERT(pp != NULL);
10223 	ASSERT(cr != NULL);
10224 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10225 
10226 	rp = VTOR4(vp);
10227 	ASSERT(rp->r_count > 0);
10228 	ASSERT(!IS_SHADOW(vp, rp));
10229 
10230 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10231 	lbn = pp->p_offset / bsize;
10232 	lbn_off = lbn * bsize;
10233 
10234 	/*
10235 	 * Find a kluster that fits in one block, or in
10236 	 * one page if pages are bigger than blocks.  If
10237 	 * there is less file space allocated than a whole
10238 	 * page, we'll shorten the i/o request below.
10239 	 */
10240 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10241 	    roundup(bsize, PAGESIZE), flags);
10242 
10243 	/*
10244 	 * pvn_write_kluster shouldn't have returned a page with offset
10245 	 * behind the original page we were given.  Verify that.
10246 	 */
10247 	ASSERT((pp->p_offset / bsize) >= lbn);
10248 
10249 	/*
10250 	 * Now pp will have the list of kept dirty pages marked for
10251 	 * write back.  It will also handle invalidation and freeing
10252 	 * of pages that are not dirty.  Check for page length rounding
10253 	 * problems.
10254 	 */
10255 	if (io_off + io_len > lbn_off + bsize) {
10256 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10257 		io_len = lbn_off + bsize - io_off;
10258 	}
10259 	/*
10260 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10261 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10262 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10263 	 * progress and the r_size has not been made consistent with the
10264 	 * new size of the file. When the uiomove() completes the r_size is
10265 	 * updated and the R4MODINPROGRESS flag is cleared.
10266 	 *
10267 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10268 	 * consistent value of r_size. Without this handshaking, it is
10269 	 * possible that nfs4_bio() picks  up the old value of r_size
10270 	 * before the uiomove() in writerp4() completes. This will result
10271 	 * in the write through nfs4_bio() being dropped.
10272 	 *
10273 	 * More precisely, there is a window between the time the uiomove()
10274 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10275 	 * operation intervenes in this window, the page will be picked up,
10276 	 * because it is dirty (it will be unlocked, unless it was
10277 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10278 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10279 	 * checked. This will still be the old size. Therefore the page will
10280 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10281 	 * the page will be found to be clean and the write will be dropped.
10282 	 */
10283 	if (rp->r_flags & R4MODINPROGRESS) {
10284 		mutex_enter(&rp->r_statelock);
10285 		if ((rp->r_flags & R4MODINPROGRESS) &&
10286 		    rp->r_modaddr + MAXBSIZE > io_off &&
10287 		    rp->r_modaddr < io_off + io_len) {
10288 			page_t *plist;
10289 			/*
10290 			 * A write is in progress for this region of the file.
10291 			 * If we did not detect R4MODINPROGRESS here then this
10292 			 * path through nfs_putapage() would eventually go to
10293 			 * nfs4_bio() and may not write out all of the data
10294 			 * in the pages. We end up losing data. So we decide
10295 			 * to set the modified bit on each page in the page
10296 			 * list and mark the rnode with R4DIRTY. This write
10297 			 * will be restarted at some later time.
10298 			 */
10299 			plist = pp;
10300 			while (plist != NULL) {
10301 				pp = plist;
10302 				page_sub(&plist, pp);
10303 				hat_setmod(pp);
10304 				page_io_unlock(pp);
10305 				page_unlock(pp);
10306 			}
10307 			rp->r_flags |= R4DIRTY;
10308 			mutex_exit(&rp->r_statelock);
10309 			if (offp)
10310 				*offp = io_off;
10311 			if (lenp)
10312 				*lenp = io_len;
10313 			return (0);
10314 		}
10315 		mutex_exit(&rp->r_statelock);
10316 	}
10317 
10318 	if (flags & B_ASYNC) {
10319 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10320 		    nfs4_sync_putapage);
10321 	} else
10322 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10323 
10324 	if (offp)
10325 		*offp = io_off;
10326 	if (lenp)
10327 		*lenp = io_len;
10328 	return (error);
10329 }
10330 
10331 static int
10332 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10333     int flags, cred_t *cr)
10334 {
10335 	int error;
10336 	rnode4_t *rp;
10337 
10338 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10339 
10340 	flags |= B_WRITE;
10341 
10342 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10343 
10344 	rp = VTOR4(vp);
10345 
10346 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10347 	    error == EACCES) &&
10348 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10349 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10350 			mutex_enter(&rp->r_statelock);
10351 			rp->r_flags |= R4OUTOFSPACE;
10352 			mutex_exit(&rp->r_statelock);
10353 		}
10354 		flags |= B_ERROR;
10355 		pvn_write_done(pp, flags);
10356 		/*
10357 		 * If this was not an async thread, then try again to
10358 		 * write out the pages, but this time, also destroy
10359 		 * them whether or not the write is successful.  This
10360 		 * will prevent memory from filling up with these
10361 		 * pages and destroying them is the only alternative
10362 		 * if they can't be written out.
10363 		 *
10364 		 * Don't do this if this is an async thread because
10365 		 * when the pages are unlocked in pvn_write_done,
10366 		 * some other thread could have come along, locked
10367 		 * them, and queued for an async thread.  It would be
10368 		 * possible for all of the async threads to be tied
10369 		 * up waiting to lock the pages again and they would
10370 		 * all already be locked and waiting for an async
10371 		 * thread to handle them.  Deadlock.
10372 		 */
10373 		if (!(flags & B_ASYNC)) {
10374 			error = nfs4_putpage(vp, io_off, io_len,
10375 			    B_INVAL | B_FORCE, cr, NULL);
10376 		}
10377 	} else {
10378 		if (error)
10379 			flags |= B_ERROR;
10380 		else if (rp->r_flags & R4OUTOFSPACE) {
10381 			mutex_enter(&rp->r_statelock);
10382 			rp->r_flags &= ~R4OUTOFSPACE;
10383 			mutex_exit(&rp->r_statelock);
10384 		}
10385 		pvn_write_done(pp, flags);
10386 		if (freemem < desfree)
10387 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10388 			    NFS4_WRITE_NOWAIT);
10389 	}
10390 
10391 	return (error);
10392 }
10393 
10394 #ifdef DEBUG
10395 int nfs4_force_open_before_mmap = 0;
10396 #endif
10397 
10398 /* ARGSUSED */
10399 static int
10400 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10401     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10402     caller_context_t *ct)
10403 {
10404 	struct segvn_crargs vn_a;
10405 	int error = 0;
10406 	rnode4_t *rp = VTOR4(vp);
10407 	mntinfo4_t *mi = VTOMI4(vp);
10408 
10409 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10410 		return (EIO);
10411 
10412 	if (vp->v_flag & VNOMAP)
10413 		return (ENOSYS);
10414 
10415 	if (off < 0 || (off + len) < 0)
10416 		return (ENXIO);
10417 
10418 	if (vp->v_type != VREG)
10419 		return (ENODEV);
10420 
10421 	/*
10422 	 * If the file is delegated to the client don't do anything.
10423 	 * If the file is not delegated, then validate the data cache.
10424 	 */
10425 	mutex_enter(&rp->r_statev4_lock);
10426 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10427 		mutex_exit(&rp->r_statev4_lock);
10428 		error = nfs4_validate_caches(vp, cr);
10429 		if (error)
10430 			return (error);
10431 	} else {
10432 		mutex_exit(&rp->r_statev4_lock);
10433 	}
10434 
10435 	/*
10436 	 * Check to see if the vnode is currently marked as not cachable.
10437 	 * This means portions of the file are locked (through VOP_FRLOCK).
10438 	 * In this case the map request must be refused.  We use
10439 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10440 	 *
10441 	 * Atomically increment r_inmap after acquiring r_rwlock. The
10442 	 * idea here is to acquire r_rwlock to block read/write and
10443 	 * not to protect r_inmap. r_inmap will inform nfs4_read/write()
10444 	 * that we are in nfs4_map(). Now, r_rwlock is acquired in order
10445 	 * and we can prevent the deadlock that would have occurred
10446 	 * when nfs4_addmap() would have acquired it out of order.
10447 	 *
10448 	 * Since we are not protecting r_inmap by any lock, we do not
10449 	 * hold any lock when we decrement it. We atomically decrement
10450 	 * r_inmap after we release r_lkserlock.
10451 	 */
10452 
10453 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR4(vp)))
10454 		return (EINTR);
10455 	atomic_add_int(&rp->r_inmap, 1);
10456 	nfs_rw_exit(&rp->r_rwlock);
10457 
10458 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp))) {
10459 		atomic_add_int(&rp->r_inmap, -1);
10460 		return (EINTR);
10461 	}
10462 
10463 
10464 	if (vp->v_flag & VNOCACHE) {
10465 		error = EAGAIN;
10466 		goto done;
10467 	}
10468 
10469 	/*
10470 	 * Don't allow concurrent locks and mapping if mandatory locking is
10471 	 * enabled.
10472 	 */
10473 	if (flk_has_remote_locks(vp)) {
10474 		struct vattr va;
10475 		va.va_mask = AT_MODE;
10476 		error = nfs4getattr(vp, &va, cr);
10477 		if (error != 0)
10478 			goto done;
10479 		if (MANDLOCK(vp, va.va_mode)) {
10480 			error = EAGAIN;
10481 			goto done;
10482 		}
10483 	}
10484 
10485 	/*
10486 	 * It is possible that the rnode has a lost lock request that we
10487 	 * are still trying to recover, and that the request conflicts with
10488 	 * this map request.
10489 	 *
10490 	 * An alternative approach would be for nfs4_safemap() to consider
10491 	 * queued lock requests when deciding whether to set or clear
10492 	 * VNOCACHE.  This would require the frlock code path to call
10493 	 * nfs4_safemap() after enqueing a lost request.
10494 	 */
10495 	if (nfs4_map_lost_lock_conflict(vp)) {
10496 		error = EAGAIN;
10497 		goto done;
10498 	}
10499 
10500 	as_rangelock(as);
10501 	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
10502 	if (error != 0) {
10503 		as_rangeunlock(as);
10504 		goto done;
10505 	}
10506 
10507 	if (vp->v_type == VREG) {
10508 		/*
10509 		 * We need to retrieve the open stream
10510 		 */
10511 		nfs4_open_stream_t	*osp = NULL;
10512 		nfs4_open_owner_t	*oop = NULL;
10513 
10514 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10515 		if (oop != NULL) {
10516 			/* returns with 'os_sync_lock' held */
10517 			osp = find_open_stream(oop, rp);
10518 			open_owner_rele(oop);
10519 		}
10520 		if (osp == NULL) {
10521 #ifdef DEBUG
10522 			if (nfs4_force_open_before_mmap) {
10523 				error = EIO;
10524 				goto done;
10525 			}
10526 #endif
10527 			/* returns with 'os_sync_lock' held */
10528 			error = open_and_get_osp(vp, cr, &osp);
10529 			if (osp == NULL) {
10530 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10531 				    "nfs4_map: we tried to OPEN the file "
10532 				    "but again no osp, so fail with EIO"));
10533 				goto done;
10534 			}
10535 		}
10536 
10537 		if (osp->os_failed_reopen) {
10538 			mutex_exit(&osp->os_sync_lock);
10539 			open_stream_rele(osp, rp);
10540 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10541 			    "nfs4_map: os_failed_reopen set on "
10542 			    "osp %p, cr %p, rp %s", (void *)osp,
10543 			    (void *)cr, rnode4info(rp)));
10544 			error = EIO;
10545 			goto done;
10546 		}
10547 		mutex_exit(&osp->os_sync_lock);
10548 		open_stream_rele(osp, rp);
10549 	}
10550 
10551 	vn_a.vp = vp;
10552 	vn_a.offset = off;
10553 	vn_a.type = (flags & MAP_TYPE);
10554 	vn_a.prot = (uchar_t)prot;
10555 	vn_a.maxprot = (uchar_t)maxprot;
10556 	vn_a.flags = (flags & ~MAP_TYPE);
10557 	vn_a.cred = cr;
10558 	vn_a.amp = NULL;
10559 	vn_a.szc = 0;
10560 	vn_a.lgrp_mem_policy_flags = 0;
10561 
10562 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10563 	as_rangeunlock(as);
10564 
10565 done:
10566 	nfs_rw_exit(&rp->r_lkserlock);
10567 	atomic_add_int(&rp->r_inmap, -1);
10568 	return (error);
10569 }
10570 
10571 /*
10572  * We're most likely dealing with a kernel module that likes to READ
10573  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10574  * officially OPEN the file to create the necessary client state
10575  * for bookkeeping of os_mmap_read/write counts.
10576  *
10577  * Since VOP_MAP only passes in a pointer to the vnode rather than
10578  * a double pointer, we can't handle the case where nfs4open_otw()
10579  * returns a different vnode than the one passed into VOP_MAP (since
10580  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10581  * we return NULL and let nfs4_map() fail.  Note: the only case where
10582  * this should happen is if the file got removed and replaced with the
10583  * same name on the server (in addition to the fact that we're trying
10584  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10585  */
10586 static int
10587 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10588 {
10589 	rnode4_t		*rp, *drp;
10590 	vnode_t			*dvp, *open_vp;
10591 	char			file_name[MAXNAMELEN];
10592 	int			just_created;
10593 	nfs4_open_stream_t	*osp;
10594 	nfs4_open_owner_t	*oop;
10595 	int			error;
10596 
10597 	*ospp = NULL;
10598 	open_vp = map_vp;
10599 
10600 	rp = VTOR4(open_vp);
10601 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10602 		return (error);
10603 	drp = VTOR4(dvp);
10604 
10605 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10606 		VN_RELE(dvp);
10607 		return (EINTR);
10608 	}
10609 
10610 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10611 		nfs_rw_exit(&drp->r_rwlock);
10612 		VN_RELE(dvp);
10613 		return (error);
10614 	}
10615 
10616 	mutex_enter(&rp->r_statev4_lock);
10617 	if (rp->created_v4) {
10618 		rp->created_v4 = 0;
10619 		mutex_exit(&rp->r_statev4_lock);
10620 
10621 		dnlc_update(dvp, file_name, open_vp);
10622 		/* This is needed so we don't bump the open ref count */
10623 		just_created = 1;
10624 	} else {
10625 		mutex_exit(&rp->r_statev4_lock);
10626 		just_created = 0;
10627 	}
10628 
10629 	VN_HOLD(map_vp);
10630 
10631 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10632 	    just_created);
10633 	if (error) {
10634 		nfs_rw_exit(&drp->r_rwlock);
10635 		VN_RELE(dvp);
10636 		VN_RELE(map_vp);
10637 		return (error);
10638 	}
10639 
10640 	nfs_rw_exit(&drp->r_rwlock);
10641 	VN_RELE(dvp);
10642 
10643 	/*
10644 	 * If nfs4open_otw() returned a different vnode then "undo"
10645 	 * the open and return failure to the caller.
10646 	 */
10647 	if (!VN_CMP(open_vp, map_vp)) {
10648 		nfs4_error_t e;
10649 
10650 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10651 		    "open returned a different vnode"));
10652 		/*
10653 		 * If there's an error, ignore it,
10654 		 * and let VOP_INACTIVE handle it.
10655 		 */
10656 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10657 		    CLOSE_NORM, 0, 0, 0);
10658 		VN_RELE(map_vp);
10659 		return (EIO);
10660 	}
10661 
10662 	VN_RELE(map_vp);
10663 
10664 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10665 	if (!oop) {
10666 		nfs4_error_t e;
10667 
10668 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10669 		    "no open owner"));
10670 		/*
10671 		 * If there's an error, ignore it,
10672 		 * and let VOP_INACTIVE handle it.
10673 		 */
10674 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10675 		    CLOSE_NORM, 0, 0, 0);
10676 		return (EIO);
10677 	}
10678 	osp = find_open_stream(oop, rp);
10679 	open_owner_rele(oop);
10680 	*ospp = osp;
10681 	return (0);
10682 }
10683 
10684 /*
10685  * Please be aware that when this function is called, the address space write
10686  * a_lock is held.  Do not put over the wire calls in this function.
10687  */
10688 /* ARGSUSED */
10689 static int
10690 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10691     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10692     caller_context_t *ct)
10693 {
10694 	rnode4_t		*rp;
10695 	int			error = 0;
10696 	mntinfo4_t		*mi;
10697 
10698 	mi = VTOMI4(vp);
10699 	rp = VTOR4(vp);
10700 
10701 	if (nfs_zone() != mi->mi_zone)
10702 		return (EIO);
10703 	if (vp->v_flag & VNOMAP)
10704 		return (ENOSYS);
10705 
10706 	/*
10707 	 * Don't need to update the open stream first, since this
10708 	 * mmap can't add any additional share access that isn't
10709 	 * already contained in the open stream (for the case where we
10710 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10711 	 * take into account os_mmap_read[write] counts).
10712 	 */
10713 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10714 
10715 	if (vp->v_type == VREG) {
10716 		/*
10717 		 * We need to retrieve the open stream and update the counts.
10718 		 * If there is no open stream here, something is wrong.
10719 		 */
10720 		nfs4_open_stream_t	*osp = NULL;
10721 		nfs4_open_owner_t	*oop = NULL;
10722 
10723 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10724 		if (oop != NULL) {
10725 			/* returns with 'os_sync_lock' held */
10726 			osp = find_open_stream(oop, rp);
10727 			open_owner_rele(oop);
10728 		}
10729 		if (osp == NULL) {
10730 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10731 			    "nfs4_addmap: we should have an osp"
10732 			    "but we don't, so fail with EIO"));
10733 			error = EIO;
10734 			goto out;
10735 		}
10736 
10737 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10738 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10739 
10740 		/*
10741 		 * Update the map count in the open stream.
10742 		 * This is necessary in the case where we
10743 		 * open/mmap/close/, then the server reboots, and we
10744 		 * attempt to reopen.  If the mmap doesn't add share
10745 		 * access then we send an invalid reopen with
10746 		 * access = NONE.
10747 		 *
10748 		 * We need to specifically check each PROT_* so a mmap
10749 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10750 		 * read and write access.  A simple comparison of prot
10751 		 * to ~PROT_WRITE to determine read access is insufficient
10752 		 * since prot can be |= with PROT_USER, etc.
10753 		 */
10754 
10755 		/*
10756 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10757 		 */
10758 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10759 			osp->os_mmap_write += btopr(len);
10760 		if (maxprot & PROT_READ)
10761 			osp->os_mmap_read += btopr(len);
10762 		if (maxprot & PROT_EXEC)
10763 			osp->os_mmap_read += btopr(len);
10764 		/*
10765 		 * Ensure that os_mmap_read gets incremented, even if
10766 		 * maxprot were to look like PROT_NONE.
10767 		 */
10768 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10769 		    !(maxprot & PROT_EXEC))
10770 			osp->os_mmap_read += btopr(len);
10771 		osp->os_mapcnt += btopr(len);
10772 		mutex_exit(&osp->os_sync_lock);
10773 		open_stream_rele(osp, rp);
10774 	}
10775 
10776 out:
10777 	/*
10778 	 * If we got an error, then undo our
10779 	 * incrementing of 'r_mapcnt'.
10780 	 */
10781 
10782 	if (error) {
10783 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10784 		ASSERT(rp->r_mapcnt >= 0);
10785 	}
10786 	return (error);
10787 }
10788 
10789 /* ARGSUSED */
10790 static int
10791 nfs4_cmp(vnode_t *vp1, vnode_t *vp2, caller_context_t *ct)
10792 {
10793 
10794 	return (VTOR4(vp1) == VTOR4(vp2));
10795 }
10796 
10797 /* ARGSUSED */
10798 static int
10799 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10800     offset_t offset, struct flk_callback *flk_cbp, cred_t *cr,
10801     caller_context_t *ct)
10802 {
10803 	int rc;
10804 	u_offset_t start, end;
10805 	rnode4_t *rp;
10806 	int error = 0, intr = INTR4(vp);
10807 	nfs4_error_t e;
10808 
10809 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10810 		return (EIO);
10811 
10812 	/* check for valid cmd parameter */
10813 	if (cmd != F_GETLK && cmd != F_SETLK && cmd != F_SETLKW)
10814 		return (EINVAL);
10815 
10816 	/* Verify l_type. */
10817 	switch (bfp->l_type) {
10818 	case F_RDLCK:
10819 		if (cmd != F_GETLK && !(flag & FREAD))
10820 			return (EBADF);
10821 		break;
10822 	case F_WRLCK:
10823 		if (cmd != F_GETLK && !(flag & FWRITE))
10824 			return (EBADF);
10825 		break;
10826 	case F_UNLCK:
10827 		intr = 0;
10828 		break;
10829 
10830 	default:
10831 		return (EINVAL);
10832 	}
10833 
10834 	/* check the validity of the lock range */
10835 	if (rc = flk_convert_lock_data(vp, bfp, &start, &end, offset))
10836 		return (rc);
10837 	if (rc = flk_check_lock_data(start, end, MAXEND))
10838 		return (rc);
10839 
10840 	/*
10841 	 * If the filesystem is mounted using local locking, pass the
10842 	 * request off to the local locking code.
10843 	 */
10844 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10845 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10846 			/*
10847 			 * For complete safety, we should be holding
10848 			 * r_lkserlock.  However, we can't call
10849 			 * nfs4_safelock and then fs_frlock while
10850 			 * holding r_lkserlock, so just invoke
10851 			 * nfs4_safelock and expect that this will
10852 			 * catch enough of the cases.
10853 			 */
10854 			if (!nfs4_safelock(vp, bfp, cr))
10855 				return (EAGAIN);
10856 		}
10857 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
10858 	}
10859 
10860 	rp = VTOR4(vp);
10861 
10862 	/*
10863 	 * Check whether the given lock request can proceed, given the
10864 	 * current file mappings.
10865 	 */
10866 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr))
10867 		return (EINTR);
10868 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10869 		if (!nfs4_safelock(vp, bfp, cr)) {
10870 			rc = EAGAIN;
10871 			goto done;
10872 		}
10873 	}
10874 
10875 	/*
10876 	 * Flush the cache after waiting for async I/O to finish.  For new
10877 	 * locks, this is so that the process gets the latest bits from the
10878 	 * server.  For unlocks, this is so that other clients see the
10879 	 * latest bits once the file has been unlocked.  If currently dirty
10880 	 * pages can't be flushed, then don't allow a lock to be set.  But
10881 	 * allow unlocks to succeed, to avoid having orphan locks on the
10882 	 * server.
10883 	 */
10884 	if (cmd != F_GETLK) {
10885 		mutex_enter(&rp->r_statelock);
10886 		while (rp->r_count > 0) {
10887 			if (intr) {
10888 				klwp_t *lwp = ttolwp(curthread);
10889 
10890 				if (lwp != NULL)
10891 					lwp->lwp_nostop++;
10892 				if (cv_wait_sig(&rp->r_cv,
10893 				    &rp->r_statelock) == 0) {
10894 					if (lwp != NULL)
10895 						lwp->lwp_nostop--;
10896 					rc = EINTR;
10897 					break;
10898 				}
10899 				if (lwp != NULL)
10900 					lwp->lwp_nostop--;
10901 				} else
10902 					cv_wait(&rp->r_cv, &rp->r_statelock);
10903 		}
10904 		mutex_exit(&rp->r_statelock);
10905 		if (rc != 0)
10906 			goto done;
10907 		error = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr, ct);
10908 		if (error) {
10909 			if (error == ENOSPC || error == EDQUOT) {
10910 				mutex_enter(&rp->r_statelock);
10911 				if (!rp->r_error)
10912 					rp->r_error = error;
10913 				mutex_exit(&rp->r_statelock);
10914 			}
10915 			if (bfp->l_type != F_UNLCK) {
10916 				rc = ENOLCK;
10917 				goto done;
10918 			}
10919 		}
10920 	}
10921 
10922 	/*
10923 	 * Call the lock manager to do the real work of contacting
10924 	 * the server and obtaining the lock.
10925 	 */
10926 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, flag, offset,
10927 	    cr, &e, NULL, NULL);
10928 	rc = e.error;
10929 
10930 	if (rc == 0)
10931 		nfs4_lockcompletion(vp, cmd);
10932 
10933 done:
10934 	nfs_rw_exit(&rp->r_lkserlock);
10935 
10936 	return (rc);
10937 }
10938 
10939 /*
10940  * Free storage space associated with the specified vnode.  The portion
10941  * to be freed is specified by bfp->l_start and bfp->l_len (already
10942  * normalized to a "whence" of 0).
10943  *
10944  * This is an experimental facility whose continued existence is not
10945  * guaranteed.  Currently, we only support the special case
10946  * of l_len == 0, meaning free to end of file.
10947  */
10948 /* ARGSUSED */
10949 static int
10950 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10951     offset_t offset, cred_t *cr, caller_context_t *ct)
10952 {
10953 	int error;
10954 
10955 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10956 		return (EIO);
10957 	ASSERT(vp->v_type == VREG);
10958 	if (cmd != F_FREESP)
10959 		return (EINVAL);
10960 
10961 	error = convoff(vp, bfp, 0, offset);
10962 	if (!error) {
10963 		ASSERT(bfp->l_start >= 0);
10964 		if (bfp->l_len == 0) {
10965 			struct vattr va;
10966 
10967 			va.va_mask = AT_SIZE;
10968 			va.va_size = bfp->l_start;
10969 			error = nfs4setattr(vp, &va, 0, cr, NULL);
10970 		} else
10971 			error = EINVAL;
10972 	}
10973 
10974 	return (error);
10975 }
10976 
10977 /* ARGSUSED */
10978 int
10979 nfs4_realvp(vnode_t *vp, vnode_t **vpp, caller_context_t *ct)
10980 {
10981 	rnode4_t *rp;
10982 	rp = VTOR4(vp);
10983 
10984 	if (vp->v_type == VREG && IS_SHADOW(vp, rp)) {
10985 		vp = RTOV4(rp);
10986 	}
10987 	*vpp = vp;
10988 	return (0);
10989 }
10990 
10991 /*
10992  * Setup and add an address space callback to do the work of the delmap call.
10993  * The callback will (and must be) deleted in the actual callback function.
10994  *
10995  * This is done in order to take care of the problem that we have with holding
10996  * the address space's a_lock for a long period of time (e.g. if the NFS server
10997  * is down).  Callbacks will be executed in the address space code while the
10998  * a_lock is not held.  Holding the address space's a_lock causes things such
10999  * as ps and fork to hang because they are trying to acquire this lock as well.
11000  */
11001 /* ARGSUSED */
11002 static int
11003 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
11004     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
11005     caller_context_t *ct)
11006 {
11007 	int			caller_found;
11008 	int			error;
11009 	rnode4_t		*rp;
11010 	nfs4_delmap_args_t	*dmapp;
11011 	nfs4_delmapcall_t	*delmap_call;
11012 
11013 	if (vp->v_flag & VNOMAP)
11014 		return (ENOSYS);
11015 
11016 	/*
11017 	 * A process may not change zones if it has NFS pages mmap'ed
11018 	 * in, so we can't legitimately get here from the wrong zone.
11019 	 */
11020 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11021 
11022 	rp = VTOR4(vp);
11023 
11024 	/*
11025 	 * The way that the address space of this process deletes its mapping
11026 	 * of this file is via the following call chains:
11027 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11028 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11029 	 *
11030 	 * With the use of address space callbacks we are allowed to drop the
11031 	 * address space lock, a_lock, while executing the NFS operations that
11032 	 * need to go over the wire.  Returning EAGAIN to the caller of this
11033 	 * function is what drives the execution of the callback that we add
11034 	 * below.  The callback will be executed by the address space code
11035 	 * after dropping the a_lock.  When the callback is finished, since
11036 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
11037 	 * is called again on the same segment to finish the rest of the work
11038 	 * that needs to happen during unmapping.
11039 	 *
11040 	 * This action of calling back into the segment driver causes
11041 	 * nfs4_delmap() to get called again, but since the callback was
11042 	 * already executed at this point, it already did the work and there
11043 	 * is nothing left for us to do.
11044 	 *
11045 	 * To Summarize:
11046 	 * - The first time nfs4_delmap is called by the current thread is when
11047 	 * we add the caller associated with this delmap to the delmap caller
11048 	 * list, add the callback, and return EAGAIN.
11049 	 * - The second time in this call chain when nfs4_delmap is called we
11050 	 * will find this caller in the delmap caller list and realize there
11051 	 * is no more work to do thus removing this caller from the list and
11052 	 * returning the error that was set in the callback execution.
11053 	 */
11054 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
11055 	if (caller_found) {
11056 		/*
11057 		 * 'error' is from the actual delmap operations.  To avoid
11058 		 * hangs, we need to handle the return of EAGAIN differently
11059 		 * since this is what drives the callback execution.
11060 		 * In this case, we don't want to return EAGAIN and do the
11061 		 * callback execution because there are none to execute.
11062 		 */
11063 		if (error == EAGAIN)
11064 			return (0);
11065 		else
11066 			return (error);
11067 	}
11068 
11069 	/* current caller was not in the list */
11070 	delmap_call = nfs4_init_delmapcall();
11071 
11072 	mutex_enter(&rp->r_statelock);
11073 	list_insert_tail(&rp->r_indelmap, delmap_call);
11074 	mutex_exit(&rp->r_statelock);
11075 
11076 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
11077 
11078 	dmapp->vp = vp;
11079 	dmapp->off = off;
11080 	dmapp->addr = addr;
11081 	dmapp->len = len;
11082 	dmapp->prot = prot;
11083 	dmapp->maxprot = maxprot;
11084 	dmapp->flags = flags;
11085 	dmapp->cr = cr;
11086 	dmapp->caller = delmap_call;
11087 
11088 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
11089 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
11090 
11091 	return (error ? error : EAGAIN);
11092 }
11093 
11094 static nfs4_delmapcall_t *
11095 nfs4_init_delmapcall()
11096 {
11097 	nfs4_delmapcall_t	*delmap_call;
11098 
11099 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
11100 	delmap_call->call_id = curthread;
11101 	delmap_call->error = 0;
11102 
11103 	return (delmap_call);
11104 }
11105 
11106 static void
11107 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11108 {
11109 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11110 }
11111 
11112 /*
11113  * Searches for the current delmap caller (based on curthread) in the list of
11114  * callers.  If it is found, we remove it and free the delmap caller.
11115  * Returns:
11116  *      0 if the caller wasn't found
11117  *      1 if the caller was found, removed and freed.  *errp will be set
11118  *	to what the result of the delmap was.
11119  */
11120 static int
11121 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11122 {
11123 	nfs4_delmapcall_t	*delmap_call;
11124 
11125 	/*
11126 	 * If the list doesn't exist yet, we create it and return
11127 	 * that the caller wasn't found.  No list = no callers.
11128 	 */
11129 	mutex_enter(&rp->r_statelock);
11130 	if (!(rp->r_flags & R4DELMAPLIST)) {
11131 		/* The list does not exist */
11132 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11133 		    offsetof(nfs4_delmapcall_t, call_node));
11134 		rp->r_flags |= R4DELMAPLIST;
11135 		mutex_exit(&rp->r_statelock);
11136 		return (0);
11137 	} else {
11138 		/* The list exists so search it */
11139 		for (delmap_call = list_head(&rp->r_indelmap);
11140 		    delmap_call != NULL;
11141 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11142 			if (delmap_call->call_id == curthread) {
11143 				/* current caller is in the list */
11144 				*errp = delmap_call->error;
11145 				list_remove(&rp->r_indelmap, delmap_call);
11146 				mutex_exit(&rp->r_statelock);
11147 				nfs4_free_delmapcall(delmap_call);
11148 				return (1);
11149 			}
11150 		}
11151 	}
11152 	mutex_exit(&rp->r_statelock);
11153 	return (0);
11154 }
11155 
11156 /*
11157  * Remove some pages from an mmap'd vnode.  Just update the
11158  * count of pages.  If doing close-to-open, then flush and
11159  * commit all of the pages associated with this file.
11160  * Otherwise, start an asynchronous page flush to write out
11161  * any dirty pages.  This will also associate a credential
11162  * with the rnode which can be used to write the pages.
11163  */
11164 /* ARGSUSED */
11165 static void
11166 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11167 {
11168 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11169 	rnode4_t		*rp;
11170 	mntinfo4_t		*mi;
11171 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11172 
11173 	rp = VTOR4(dmapp->vp);
11174 	mi = VTOMI4(dmapp->vp);
11175 
11176 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11177 	ASSERT(rp->r_mapcnt >= 0);
11178 
11179 	/*
11180 	 * Initiate a page flush and potential commit if there are
11181 	 * pages, the file system was not mounted readonly, the segment
11182 	 * was mapped shared, and the pages themselves were writeable.
11183 	 */
11184 	if (nfs4_has_pages(dmapp->vp) &&
11185 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11186 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11187 		mutex_enter(&rp->r_statelock);
11188 		rp->r_flags |= R4DIRTY;
11189 		mutex_exit(&rp->r_statelock);
11190 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11191 		    dmapp->len, dmapp->cr);
11192 		if (!e.error) {
11193 			mutex_enter(&rp->r_statelock);
11194 			e.error = rp->r_error;
11195 			rp->r_error = 0;
11196 			mutex_exit(&rp->r_statelock);
11197 		}
11198 	} else
11199 		e.error = 0;
11200 
11201 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11202 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11203 		    B_INVAL, dmapp->cr, NULL);
11204 
11205 	if (e.error) {
11206 		e.stat = puterrno4(e.error);
11207 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11208 		    OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11209 		dmapp->caller->error = e.error;
11210 	}
11211 
11212 	/* Check to see if we need to close the file */
11213 
11214 	if (dmapp->vp->v_type == VREG) {
11215 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11216 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11217 
11218 		if (e.error != 0 || e.stat != NFS4_OK) {
11219 			/*
11220 			 * Since it is possible that e.error == 0 and
11221 			 * e.stat != NFS4_OK (and vice versa),
11222 			 * we do the proper checking in order to get both
11223 			 * e.error and e.stat reporting the correct info.
11224 			 */
11225 			if (e.stat == NFS4_OK)
11226 				e.stat = puterrno4(e.error);
11227 			if (e.error == 0)
11228 				e.error = geterrno4(e.stat);
11229 
11230 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11231 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11232 			dmapp->caller->error = e.error;
11233 		}
11234 	}
11235 
11236 	(void) as_delete_callback(as, arg);
11237 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11238 }
11239 
11240 
11241 static uint_t
11242 fattr4_maxfilesize_to_bits(uint64_t ll)
11243 {
11244 	uint_t l = 1;
11245 
11246 	if (ll == 0) {
11247 		return (0);
11248 	}
11249 
11250 	if (ll & 0xffffffff00000000) {
11251 		l += 32; ll >>= 32;
11252 	}
11253 	if (ll & 0xffff0000) {
11254 		l += 16; ll >>= 16;
11255 	}
11256 	if (ll & 0xff00) {
11257 		l += 8; ll >>= 8;
11258 	}
11259 	if (ll & 0xf0) {
11260 		l += 4; ll >>= 4;
11261 	}
11262 	if (ll & 0xc) {
11263 		l += 2; ll >>= 2;
11264 	}
11265 	if (ll & 0x2) {
11266 		l += 1;
11267 	}
11268 	return (l);
11269 }
11270 
11271 static int
11272 nfs4_have_xattrs(vnode_t *vp, ulong_t *valp, cred_t *cr)
11273 {
11274 	vnode_t *avp = NULL;
11275 	int error;
11276 
11277 	if ((error = nfs4lookup_xattr(vp, "", &avp,
11278 	    LOOKUP_XATTR, cr)) == 0)
11279 		error = do_xattr_exists_check(avp, valp, cr);
11280 	if (avp)
11281 		VN_RELE(avp);
11282 
11283 	return (error);
11284 }
11285 
11286 /* ARGSUSED */
11287 int
11288 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
11289 	caller_context_t *ct)
11290 {
11291 	int error;
11292 	hrtime_t t;
11293 	rnode4_t *rp;
11294 	nfs4_ga_res_t gar;
11295 	nfs4_ga_ext_res_t ger;
11296 
11297 	gar.n4g_ext_res = &ger;
11298 
11299 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11300 		return (EIO);
11301 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11302 		*valp = MAXPATHLEN;
11303 		return (0);
11304 	}
11305 	if (cmd == _PC_ACL_ENABLED) {
11306 		*valp = _ACL_ACE_ENABLED;
11307 		return (0);
11308 	}
11309 
11310 	rp = VTOR4(vp);
11311 	if (cmd == _PC_XATTR_EXISTS) {
11312 		/*
11313 		 * The existence of the xattr directory is not sufficient
11314 		 * for determining whether generic user attributes exists.
11315 		 * The attribute directory could only be a transient directory
11316 		 * used for Solaris sysattr support.  Do a small readdir
11317 		 * to verify if the only entries are sysattrs or not.
11318 		 *
11319 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11320 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11321 		 * and we don't have any way to update the "base" object's
11322 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11323 		 * could help out.
11324 		 */
11325 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11326 		    rp->r_xattr_dir == NULL) {
11327 			return (nfs4_have_xattrs(vp, valp, cr));
11328 		}
11329 	} else {  /* OLD CODE */
11330 		if (ATTRCACHE4_VALID(vp)) {
11331 			mutex_enter(&rp->r_statelock);
11332 			if (rp->r_pathconf.pc4_cache_valid) {
11333 				error = 0;
11334 				switch (cmd) {
11335 				case _PC_FILESIZEBITS:
11336 					*valp =
11337 					    rp->r_pathconf.pc4_filesizebits;
11338 					break;
11339 				case _PC_LINK_MAX:
11340 					*valp =
11341 					    rp->r_pathconf.pc4_link_max;
11342 					break;
11343 				case _PC_NAME_MAX:
11344 					*valp =
11345 					    rp->r_pathconf.pc4_name_max;
11346 					break;
11347 				case _PC_CHOWN_RESTRICTED:
11348 					*valp =
11349 					    rp->r_pathconf.pc4_chown_restricted;
11350 					break;
11351 				case _PC_NO_TRUNC:
11352 					*valp =
11353 					    rp->r_pathconf.pc4_no_trunc;
11354 					break;
11355 				default:
11356 					error = EINVAL;
11357 					break;
11358 				}
11359 				mutex_exit(&rp->r_statelock);
11360 #ifdef DEBUG
11361 				nfs4_pathconf_cache_hits++;
11362 #endif
11363 				return (error);
11364 			}
11365 			mutex_exit(&rp->r_statelock);
11366 		}
11367 	}
11368 #ifdef DEBUG
11369 	nfs4_pathconf_cache_misses++;
11370 #endif
11371 
11372 	t = gethrtime();
11373 
11374 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11375 
11376 	if (error) {
11377 		mutex_enter(&rp->r_statelock);
11378 		rp->r_pathconf.pc4_cache_valid = FALSE;
11379 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11380 		mutex_exit(&rp->r_statelock);
11381 		return (error);
11382 	}
11383 
11384 	/* interpret the max filesize */
11385 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11386 	    fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11387 
11388 	/* Store the attributes we just received */
11389 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11390 
11391 	switch (cmd) {
11392 	case _PC_FILESIZEBITS:
11393 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11394 		break;
11395 	case _PC_LINK_MAX:
11396 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11397 		break;
11398 	case _PC_NAME_MAX:
11399 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11400 		break;
11401 	case _PC_CHOWN_RESTRICTED:
11402 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11403 		break;
11404 	case _PC_NO_TRUNC:
11405 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11406 		break;
11407 	case _PC_XATTR_EXISTS:
11408 		if (gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists) {
11409 			if (error = nfs4_have_xattrs(vp, valp, cr))
11410 				return (error);
11411 		}
11412 		break;
11413 	default:
11414 		return (EINVAL);
11415 	}
11416 
11417 	return (0);
11418 }
11419 
11420 /*
11421  * Called by async thread to do synchronous pageio. Do the i/o, wait
11422  * for it to complete, and cleanup the page list when done.
11423  */
11424 static int
11425 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11426     int flags, cred_t *cr)
11427 {
11428 	int error;
11429 
11430 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11431 
11432 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11433 	if (flags & B_READ)
11434 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11435 	else
11436 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11437 	return (error);
11438 }
11439 
11440 /* ARGSUSED */
11441 static int
11442 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11443 	int flags, cred_t *cr, caller_context_t *ct)
11444 {
11445 	int error;
11446 	rnode4_t *rp;
11447 
11448 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11449 		return (EIO);
11450 
11451 	if (pp == NULL)
11452 		return (EINVAL);
11453 
11454 	rp = VTOR4(vp);
11455 	mutex_enter(&rp->r_statelock);
11456 	rp->r_count++;
11457 	mutex_exit(&rp->r_statelock);
11458 
11459 	if (flags & B_ASYNC) {
11460 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11461 		    nfs4_sync_pageio);
11462 	} else
11463 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11464 	mutex_enter(&rp->r_statelock);
11465 	rp->r_count--;
11466 	cv_broadcast(&rp->r_cv);
11467 	mutex_exit(&rp->r_statelock);
11468 	return (error);
11469 }
11470 
11471 /* ARGSUSED */
11472 static void
11473 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr,
11474 	caller_context_t *ct)
11475 {
11476 	int error;
11477 	rnode4_t *rp;
11478 	page_t *plist;
11479 	page_t *pptr;
11480 	offset3 offset;
11481 	count3 len;
11482 	k_sigset_t smask;
11483 
11484 	/*
11485 	 * We should get called with fl equal to either B_FREE or
11486 	 * B_INVAL.  Any other value is illegal.
11487 	 *
11488 	 * The page that we are either supposed to free or destroy
11489 	 * should be exclusive locked and its io lock should not
11490 	 * be held.
11491 	 */
11492 	ASSERT(fl == B_FREE || fl == B_INVAL);
11493 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11494 
11495 	rp = VTOR4(vp);
11496 
11497 	/*
11498 	 * If the page doesn't need to be committed or we shouldn't
11499 	 * even bother attempting to commit it, then just make sure
11500 	 * that the p_fsdata byte is clear and then either free or
11501 	 * destroy the page as appropriate.
11502 	 */
11503 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11504 		pp->p_fsdata = C_NOCOMMIT;
11505 		if (fl == B_FREE)
11506 			page_free(pp, dn);
11507 		else
11508 			page_destroy(pp, dn);
11509 		return;
11510 	}
11511 
11512 	/*
11513 	 * If there is a page invalidation operation going on, then
11514 	 * if this is one of the pages being destroyed, then just
11515 	 * clear the p_fsdata byte and then either free or destroy
11516 	 * the page as appropriate.
11517 	 */
11518 	mutex_enter(&rp->r_statelock);
11519 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11520 		mutex_exit(&rp->r_statelock);
11521 		pp->p_fsdata = C_NOCOMMIT;
11522 		if (fl == B_FREE)
11523 			page_free(pp, dn);
11524 		else
11525 			page_destroy(pp, dn);
11526 		return;
11527 	}
11528 
11529 	/*
11530 	 * If we are freeing this page and someone else is already
11531 	 * waiting to do a commit, then just unlock the page and
11532 	 * return.  That other thread will take care of commiting
11533 	 * this page.  The page can be freed sometime after the
11534 	 * commit has finished.  Otherwise, if the page is marked
11535 	 * as delay commit, then we may be getting called from
11536 	 * pvn_write_done, one page at a time.   This could result
11537 	 * in one commit per page, so we end up doing lots of small
11538 	 * commits instead of fewer larger commits.  This is bad,
11539 	 * we want do as few commits as possible.
11540 	 */
11541 	if (fl == B_FREE) {
11542 		if (rp->r_flags & R4COMMITWAIT) {
11543 			page_unlock(pp);
11544 			mutex_exit(&rp->r_statelock);
11545 			return;
11546 		}
11547 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11548 			pp->p_fsdata = C_COMMIT;
11549 			page_unlock(pp);
11550 			mutex_exit(&rp->r_statelock);
11551 			return;
11552 		}
11553 	}
11554 
11555 	/*
11556 	 * Check to see if there is a signal which would prevent an
11557 	 * attempt to commit the pages from being successful.  If so,
11558 	 * then don't bother with all of the work to gather pages and
11559 	 * generate the unsuccessful RPC.  Just return from here and
11560 	 * let the page be committed at some later time.
11561 	 */
11562 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11563 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11564 		sigunintr(&smask);
11565 		page_unlock(pp);
11566 		mutex_exit(&rp->r_statelock);
11567 		return;
11568 	}
11569 	sigunintr(&smask);
11570 
11571 	/*
11572 	 * We are starting to need to commit pages, so let's try
11573 	 * to commit as many as possible at once to reduce the
11574 	 * overhead.
11575 	 *
11576 	 * Set the `commit inprogress' state bit.  We must
11577 	 * first wait until any current one finishes.  Then
11578 	 * we initialize the c_pages list with this page.
11579 	 */
11580 	while (rp->r_flags & R4COMMIT) {
11581 		rp->r_flags |= R4COMMITWAIT;
11582 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11583 		rp->r_flags &= ~R4COMMITWAIT;
11584 	}
11585 	rp->r_flags |= R4COMMIT;
11586 	mutex_exit(&rp->r_statelock);
11587 	ASSERT(rp->r_commit.c_pages == NULL);
11588 	rp->r_commit.c_pages = pp;
11589 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11590 	rp->r_commit.c_commlen = PAGESIZE;
11591 
11592 	/*
11593 	 * Gather together all other pages which can be committed.
11594 	 * They will all be chained off r_commit.c_pages.
11595 	 */
11596 	nfs4_get_commit(vp);
11597 
11598 	/*
11599 	 * Clear the `commit inprogress' status and disconnect
11600 	 * the list of pages to be committed from the rnode.
11601 	 * At this same time, we also save the starting offset
11602 	 * and length of data to be committed on the server.
11603 	 */
11604 	plist = rp->r_commit.c_pages;
11605 	rp->r_commit.c_pages = NULL;
11606 	offset = rp->r_commit.c_commbase;
11607 	len = rp->r_commit.c_commlen;
11608 	mutex_enter(&rp->r_statelock);
11609 	rp->r_flags &= ~R4COMMIT;
11610 	cv_broadcast(&rp->r_commit.c_cv);
11611 	mutex_exit(&rp->r_statelock);
11612 
11613 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11614 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11615 		nfs4_async_commit(vp, plist, offset, len,
11616 		    cr, do_nfs4_async_commit);
11617 		return;
11618 	}
11619 
11620 	/*
11621 	 * Actually generate the COMMIT op over the wire operation.
11622 	 */
11623 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11624 
11625 	/*
11626 	 * If we got an error during the commit, just unlock all
11627 	 * of the pages.  The pages will get retransmitted to the
11628 	 * server during a putpage operation.
11629 	 */
11630 	if (error) {
11631 		while (plist != NULL) {
11632 			pptr = plist;
11633 			page_sub(&plist, pptr);
11634 			page_unlock(pptr);
11635 		}
11636 		return;
11637 	}
11638 
11639 	/*
11640 	 * We've tried as hard as we can to commit the data to stable
11641 	 * storage on the server.  We just unlock the rest of the pages
11642 	 * and clear the commit required state.  They will be put
11643 	 * onto the tail of the cachelist if they are nolonger
11644 	 * mapped.
11645 	 */
11646 	while (plist != pp) {
11647 		pptr = plist;
11648 		page_sub(&plist, pptr);
11649 		pptr->p_fsdata = C_NOCOMMIT;
11650 		page_unlock(pptr);
11651 	}
11652 
11653 	/*
11654 	 * It is possible that nfs4_commit didn't return error but
11655 	 * some other thread has modified the page we are going
11656 	 * to free/destroy.
11657 	 *    In this case we need to rewrite the page. Do an explicit check
11658 	 * before attempting to free/destroy the page. If modified, needs to
11659 	 * be rewritten so unlock the page and return.
11660 	 */
11661 	if (hat_ismod(pp)) {
11662 		pp->p_fsdata = C_NOCOMMIT;
11663 		page_unlock(pp);
11664 		return;
11665 	}
11666 
11667 	/*
11668 	 * Now, as appropriate, either free or destroy the page
11669 	 * that we were called with.
11670 	 */
11671 	pp->p_fsdata = C_NOCOMMIT;
11672 	if (fl == B_FREE)
11673 		page_free(pp, dn);
11674 	else
11675 		page_destroy(pp, dn);
11676 }
11677 
11678 /*
11679  * Commit requires that the current fh be the file written to.
11680  * The compound op structure is:
11681  *      PUTFH(file), COMMIT
11682  */
11683 static int
11684 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11685 {
11686 	COMPOUND4args_clnt args;
11687 	COMPOUND4res_clnt res;
11688 	COMMIT4res *cm_res;
11689 	nfs_argop4 argop[2];
11690 	nfs_resop4 *resop;
11691 	int doqueue;
11692 	mntinfo4_t *mi;
11693 	rnode4_t *rp;
11694 	cred_t *cred_otw = NULL;
11695 	bool_t needrecov = FALSE;
11696 	nfs4_recov_state_t recov_state;
11697 	nfs4_open_stream_t *osp = NULL;
11698 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11699 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11700 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11701 
11702 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11703 
11704 	rp = VTOR4(vp);
11705 
11706 	mi = VTOMI4(vp);
11707 	recov_state.rs_flags = 0;
11708 	recov_state.rs_num_retry_despite_err = 0;
11709 get_commit_cred:
11710 	/*
11711 	 * Releases the osp, if a valid open stream is provided.
11712 	 * Puts a hold on the cred_otw and the new osp (if found).
11713 	 */
11714 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11715 	    &first_time, &last_time);
11716 	args.ctag = TAG_COMMIT;
11717 recov_retry:
11718 	/*
11719 	 * Commit ops: putfh file; commit
11720 	 */
11721 	args.array_len = 2;
11722 	args.array = argop;
11723 
11724 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11725 	    &recov_state, NULL);
11726 	if (e.error) {
11727 		crfree(cred_otw);
11728 		if (osp != NULL)
11729 			open_stream_rele(osp, rp);
11730 		return (e.error);
11731 	}
11732 
11733 	/* putfh directory */
11734 	argop[0].argop = OP_CPUTFH;
11735 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11736 
11737 	/* commit */
11738 	argop[1].argop = OP_COMMIT;
11739 	argop[1].nfs_argop4_u.opcommit.offset = offset;
11740 	argop[1].nfs_argop4_u.opcommit.count = count;
11741 
11742 	doqueue = 1;
11743 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
11744 
11745 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
11746 	if (!needrecov && e.error) {
11747 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
11748 		    needrecov);
11749 		crfree(cred_otw);
11750 		if (e.error == EACCES && last_time == FALSE)
11751 			goto get_commit_cred;
11752 		if (osp != NULL)
11753 			open_stream_rele(osp, rp);
11754 		return (e.error);
11755 	}
11756 
11757 	if (needrecov) {
11758 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
11759 		    NULL, OP_COMMIT, NULL) == FALSE) {
11760 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11761 			    &recov_state, needrecov);
11762 			if (!e.error)
11763 				(void) xdr_free(xdr_COMPOUND4res_clnt,
11764 				    (caddr_t)&res);
11765 			goto recov_retry;
11766 		}
11767 		if (e.error) {
11768 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11769 			    &recov_state, needrecov);
11770 			crfree(cred_otw);
11771 			if (osp != NULL)
11772 				open_stream_rele(osp, rp);
11773 			return (e.error);
11774 		}
11775 		/* fall through for res.status case */
11776 	}
11777 
11778 	if (res.status) {
11779 		e.error = geterrno4(res.status);
11780 		if (e.error == EACCES && last_time == FALSE) {
11781 			crfree(cred_otw);
11782 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11783 			    &recov_state, needrecov);
11784 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11785 			goto get_commit_cred;
11786 		}
11787 		/*
11788 		 * Can't do a nfs4_purge_stale_fh here because this
11789 		 * can cause a deadlock.  nfs4_commit can
11790 		 * be called from nfs4_dispose which can be called
11791 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
11792 		 * can call back to pvn_vplist_dirty.
11793 		 */
11794 		if (e.error == ESTALE) {
11795 			mutex_enter(&rp->r_statelock);
11796 			rp->r_flags |= R4STALE;
11797 			if (!rp->r_error)
11798 				rp->r_error = e.error;
11799 			mutex_exit(&rp->r_statelock);
11800 			PURGE_ATTRCACHE4(vp);
11801 		} else {
11802 			mutex_enter(&rp->r_statelock);
11803 			if (!rp->r_error)
11804 				rp->r_error = e.error;
11805 			mutex_exit(&rp->r_statelock);
11806 		}
11807 	} else {
11808 		ASSERT(rp->r_flags & R4HAVEVERF);
11809 		resop = &res.array[1];	/* commit res */
11810 		cm_res = &resop->nfs_resop4_u.opcommit;
11811 		mutex_enter(&rp->r_statelock);
11812 		if (cm_res->writeverf == rp->r_writeverf) {
11813 			mutex_exit(&rp->r_statelock);
11814 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11815 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11816 			    &recov_state, needrecov);
11817 			crfree(cred_otw);
11818 			if (osp != NULL)
11819 				open_stream_rele(osp, rp);
11820 			return (0);
11821 		}
11822 		nfs4_set_mod(vp);
11823 		rp->r_writeverf = cm_res->writeverf;
11824 		mutex_exit(&rp->r_statelock);
11825 		e.error = NFS_VERF_MISMATCH;
11826 	}
11827 
11828 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11829 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
11830 	crfree(cred_otw);
11831 	if (osp != NULL)
11832 		open_stream_rele(osp, rp);
11833 
11834 	return (e.error);
11835 }
11836 
11837 static void
11838 nfs4_set_mod(vnode_t *vp)
11839 {
11840 	page_t *pp;
11841 	kmutex_t *vphm;
11842 	rnode4_t *rp;
11843 
11844 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11845 
11846 	/* make sure we're looking at the master vnode, not a shadow */
11847 
11848 	rp = VTOR4(vp);
11849 	if (IS_SHADOW(vp, rp))
11850 		vp = RTOV4(rp);
11851 
11852 	vphm = page_vnode_mutex(vp);
11853 	mutex_enter(vphm);
11854 	/*
11855 	 * If there are no pages associated with this vnode, then
11856 	 * just return.
11857 	 */
11858 	if ((pp = vp->v_pages) == NULL) {
11859 		mutex_exit(vphm);
11860 		return;
11861 	}
11862 
11863 	do {
11864 		if (pp->p_fsdata != C_NOCOMMIT) {
11865 			hat_setmod(pp);
11866 			pp->p_fsdata = C_NOCOMMIT;
11867 		}
11868 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11869 	mutex_exit(vphm);
11870 }
11871 
11872 /*
11873  * This function is used to gather a page list of the pages which
11874  * can be committed on the server.
11875  *
11876  * The calling thread must have set R4COMMIT.  This bit is used to
11877  * serialize access to the commit structure in the rnode.  As long
11878  * as the thread has set R4COMMIT, then it can manipulate the commit
11879  * structure without requiring any other locks.
11880  *
11881  * When this function is called from nfs4_dispose() the page passed
11882  * into nfs4_dispose() will be SE_EXCL locked, and so this function
11883  * will skip it. This is not a problem since we initially add the
11884  * page to the r_commit page list.
11885  *
11886  */
11887 static void
11888 nfs4_get_commit(vnode_t *vp)
11889 {
11890 	rnode4_t *rp;
11891 	page_t *pp;
11892 	kmutex_t *vphm;
11893 
11894 	rp = VTOR4(vp);
11895 
11896 	ASSERT(rp->r_flags & R4COMMIT);
11897 
11898 	/* make sure we're looking at the master vnode, not a shadow */
11899 
11900 	if (IS_SHADOW(vp, rp))
11901 		vp = RTOV4(rp);
11902 
11903 	vphm = page_vnode_mutex(vp);
11904 	mutex_enter(vphm);
11905 
11906 	/*
11907 	 * If there are no pages associated with this vnode, then
11908 	 * just return.
11909 	 */
11910 	if ((pp = vp->v_pages) == NULL) {
11911 		mutex_exit(vphm);
11912 		return;
11913 	}
11914 
11915 	/*
11916 	 * Step through all of the pages associated with this vnode
11917 	 * looking for pages which need to be committed.
11918 	 */
11919 	do {
11920 		/*
11921 		 * First short-cut everything (without the page_lock)
11922 		 * and see if this page does not need to be committed
11923 		 * or is modified if so then we'll just skip it.
11924 		 */
11925 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
11926 			continue;
11927 
11928 		/*
11929 		 * Attempt to lock the page.  If we can't, then
11930 		 * someone else is messing with it or we have been
11931 		 * called from nfs4_dispose and this is the page that
11932 		 * nfs4_dispose was called with.. anyway just skip it.
11933 		 */
11934 		if (!page_trylock(pp, SE_EXCL))
11935 			continue;
11936 
11937 		/*
11938 		 * Lets check again now that we have the page lock.
11939 		 */
11940 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11941 			page_unlock(pp);
11942 			continue;
11943 		}
11944 
11945 		/* this had better not be a free page */
11946 		ASSERT(PP_ISFREE(pp) == 0);
11947 
11948 		/*
11949 		 * The page needs to be committed and we locked it.
11950 		 * Update the base and length parameters and add it
11951 		 * to r_pages.
11952 		 */
11953 		if (rp->r_commit.c_pages == NULL) {
11954 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11955 			rp->r_commit.c_commlen = PAGESIZE;
11956 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
11957 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
11958 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
11959 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11960 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
11961 		    <= pp->p_offset) {
11962 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11963 			    rp->r_commit.c_commbase + PAGESIZE;
11964 		}
11965 		page_add(&rp->r_commit.c_pages, pp);
11966 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11967 
11968 	mutex_exit(vphm);
11969 }
11970 
11971 /*
11972  * This routine is used to gather together a page list of the pages
11973  * which are to be committed on the server.  This routine must not
11974  * be called if the calling thread holds any locked pages.
11975  *
11976  * The calling thread must have set R4COMMIT.  This bit is used to
11977  * serialize access to the commit structure in the rnode.  As long
11978  * as the thread has set R4COMMIT, then it can manipulate the commit
11979  * structure without requiring any other locks.
11980  */
11981 static void
11982 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
11983 {
11984 
11985 	rnode4_t *rp;
11986 	page_t *pp;
11987 	u_offset_t end;
11988 	u_offset_t off;
11989 	ASSERT(len != 0);
11990 	rp = VTOR4(vp);
11991 	ASSERT(rp->r_flags & R4COMMIT);
11992 
11993 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11994 
11995 	/* make sure we're looking at the master vnode, not a shadow */
11996 
11997 	if (IS_SHADOW(vp, rp))
11998 		vp = RTOV4(rp);
11999 
12000 	/*
12001 	 * If there are no pages associated with this vnode, then
12002 	 * just return.
12003 	 */
12004 	if ((pp = vp->v_pages) == NULL)
12005 		return;
12006 	/*
12007 	 * Calculate the ending offset.
12008 	 */
12009 	end = soff + len;
12010 	for (off = soff; off < end; off += PAGESIZE) {
12011 		/*
12012 		 * Lookup each page by vp, offset.
12013 		 */
12014 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
12015 			continue;
12016 		/*
12017 		 * If this page does not need to be committed or is
12018 		 * modified, then just skip it.
12019 		 */
12020 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
12021 			page_unlock(pp);
12022 			continue;
12023 		}
12024 
12025 		ASSERT(PP_ISFREE(pp) == 0);
12026 		/*
12027 		 * The page needs to be committed and we locked it.
12028 		 * Update the base and length parameters and add it
12029 		 * to r_pages.
12030 		 */
12031 		if (rp->r_commit.c_pages == NULL) {
12032 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
12033 			rp->r_commit.c_commlen = PAGESIZE;
12034 		} else {
12035 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
12036 			    rp->r_commit.c_commbase + PAGESIZE;
12037 		}
12038 		page_add(&rp->r_commit.c_pages, pp);
12039 	}
12040 }
12041 
12042 /*
12043  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
12044  * Flushes and commits data to the server.
12045  */
12046 static int
12047 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
12048 {
12049 	int error;
12050 	verifier4 write_verf;
12051 	rnode4_t *rp = VTOR4(vp);
12052 
12053 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12054 
12055 	/*
12056 	 * Flush the data portion of the file and then commit any
12057 	 * portions which need to be committed.  This may need to
12058 	 * be done twice if the server has changed state since
12059 	 * data was last written.  The data will need to be
12060 	 * rewritten to the server and then a new commit done.
12061 	 *
12062 	 * In fact, this may need to be done several times if the
12063 	 * server is having problems and crashing while we are
12064 	 * attempting to do this.
12065 	 */
12066 
12067 top:
12068 	/*
12069 	 * Do a flush based on the poff and plen arguments.  This
12070 	 * will synchronously write out any modified pages in the
12071 	 * range specified by (poff, plen). This starts all of the
12072 	 * i/o operations which will be waited for in the next
12073 	 * call to nfs4_putpage
12074 	 */
12075 
12076 	mutex_enter(&rp->r_statelock);
12077 	write_verf = rp->r_writeverf;
12078 	mutex_exit(&rp->r_statelock);
12079 
12080 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr, NULL);
12081 	if (error == EAGAIN)
12082 		error = 0;
12083 
12084 	/*
12085 	 * Do a flush based on the poff and plen arguments.  This
12086 	 * will synchronously write out any modified pages in the
12087 	 * range specified by (poff, plen) and wait until all of
12088 	 * the asynchronous i/o's in that range are done as well.
12089 	 */
12090 	if (!error)
12091 		error = nfs4_putpage(vp, poff, plen, 0, cr, NULL);
12092 
12093 	if (error)
12094 		return (error);
12095 
12096 	mutex_enter(&rp->r_statelock);
12097 	if (rp->r_writeverf != write_verf) {
12098 		mutex_exit(&rp->r_statelock);
12099 		goto top;
12100 	}
12101 	mutex_exit(&rp->r_statelock);
12102 
12103 	/*
12104 	 * Now commit any pages which might need to be committed.
12105 	 * If the error, NFS_VERF_MISMATCH, is returned, then
12106 	 * start over with the flush operation.
12107 	 */
12108 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
12109 
12110 	if (error == NFS_VERF_MISMATCH)
12111 		goto top;
12112 
12113 	return (error);
12114 }
12115 
12116 /*
12117  * nfs4_commit_vp()  will wait for other pending commits and
12118  * will either commit the whole file or a range, plen dictates
12119  * if we commit whole file. a value of zero indicates the whole
12120  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
12121  */
12122 static int
12123 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12124     cred_t *cr, int wait_on_writes)
12125 {
12126 	rnode4_t *rp;
12127 	page_t *plist;
12128 	offset3 offset;
12129 	count3 len;
12130 
12131 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12132 
12133 	rp = VTOR4(vp);
12134 
12135 	/*
12136 	 *  before we gather commitable pages make
12137 	 *  sure there are no outstanding async writes
12138 	 */
12139 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12140 		mutex_enter(&rp->r_statelock);
12141 		while (rp->r_count > 0) {
12142 			cv_wait(&rp->r_cv, &rp->r_statelock);
12143 		}
12144 		mutex_exit(&rp->r_statelock);
12145 	}
12146 
12147 	/*
12148 	 * Set the `commit inprogress' state bit.  We must
12149 	 * first wait until any current one finishes.
12150 	 */
12151 	mutex_enter(&rp->r_statelock);
12152 	while (rp->r_flags & R4COMMIT) {
12153 		rp->r_flags |= R4COMMITWAIT;
12154 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12155 		rp->r_flags &= ~R4COMMITWAIT;
12156 	}
12157 	rp->r_flags |= R4COMMIT;
12158 	mutex_exit(&rp->r_statelock);
12159 
12160 	/*
12161 	 * Gather all of the pages which need to be
12162 	 * committed.
12163 	 */
12164 	if (plen == 0)
12165 		nfs4_get_commit(vp);
12166 	else
12167 		nfs4_get_commit_range(vp, poff, plen);
12168 
12169 	/*
12170 	 * Clear the `commit inprogress' bit and disconnect the
12171 	 * page list which was gathered by nfs4_get_commit.
12172 	 */
12173 	plist = rp->r_commit.c_pages;
12174 	rp->r_commit.c_pages = NULL;
12175 	offset = rp->r_commit.c_commbase;
12176 	len = rp->r_commit.c_commlen;
12177 	mutex_enter(&rp->r_statelock);
12178 	rp->r_flags &= ~R4COMMIT;
12179 	cv_broadcast(&rp->r_commit.c_cv);
12180 	mutex_exit(&rp->r_statelock);
12181 
12182 	/*
12183 	 * If any pages need to be committed, commit them and
12184 	 * then unlock them so that they can be freed some
12185 	 * time later.
12186 	 */
12187 	if (plist == NULL)
12188 		return (0);
12189 
12190 	/*
12191 	 * No error occurred during the flush portion
12192 	 * of this operation, so now attempt to commit
12193 	 * the data to stable storage on the server.
12194 	 *
12195 	 * This will unlock all of the pages on the list.
12196 	 */
12197 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12198 }
12199 
12200 static int
12201 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12202     cred_t *cr)
12203 {
12204 	int error;
12205 	page_t *pp;
12206 
12207 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12208 
12209 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12210 
12211 	/*
12212 	 * If we got an error, then just unlock all of the pages
12213 	 * on the list.
12214 	 */
12215 	if (error) {
12216 		while (plist != NULL) {
12217 			pp = plist;
12218 			page_sub(&plist, pp);
12219 			page_unlock(pp);
12220 		}
12221 		return (error);
12222 	}
12223 	/*
12224 	 * We've tried as hard as we can to commit the data to stable
12225 	 * storage on the server.  We just unlock the pages and clear
12226 	 * the commit required state.  They will get freed later.
12227 	 */
12228 	while (plist != NULL) {
12229 		pp = plist;
12230 		page_sub(&plist, pp);
12231 		pp->p_fsdata = C_NOCOMMIT;
12232 		page_unlock(pp);
12233 	}
12234 
12235 	return (error);
12236 }
12237 
12238 static void
12239 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12240     cred_t *cr)
12241 {
12242 
12243 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12244 }
12245 
12246 /*ARGSUSED*/
12247 static int
12248 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12249 	caller_context_t *ct)
12250 {
12251 	int		error = 0;
12252 	mntinfo4_t	*mi;
12253 	vattr_t		va;
12254 	vsecattr_t	nfsace4_vsap;
12255 
12256 	mi = VTOMI4(vp);
12257 	if (nfs_zone() != mi->mi_zone)
12258 		return (EIO);
12259 	if (mi->mi_flags & MI4_ACL) {
12260 		/* if we have a delegation, return it */
12261 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12262 			(void) nfs4delegreturn(VTOR4(vp),
12263 			    NFS4_DR_REOPEN|NFS4_DR_PUSH);
12264 
12265 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12266 		    NFS4_ACL_SET);
12267 		if (error) /* EINVAL */
12268 			return (error);
12269 
12270 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12271 			/*
12272 			 * These are aclent_t type entries.
12273 			 */
12274 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12275 			    vp->v_type == VDIR, FALSE);
12276 			if (error)
12277 				return (error);
12278 		} else {
12279 			/*
12280 			 * These are ace_t type entries.
12281 			 */
12282 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12283 			    FALSE);
12284 			if (error)
12285 				return (error);
12286 		}
12287 		bzero(&va, sizeof (va));
12288 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12289 		vs_ace4_destroy(&nfsace4_vsap);
12290 		return (error);
12291 	}
12292 	return (ENOSYS);
12293 }
12294 
12295 /* ARGSUSED */
12296 int
12297 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12298 	caller_context_t *ct)
12299 {
12300 	int		error;
12301 	mntinfo4_t	*mi;
12302 	nfs4_ga_res_t	gar;
12303 	rnode4_t	*rp = VTOR4(vp);
12304 
12305 	mi = VTOMI4(vp);
12306 	if (nfs_zone() != mi->mi_zone)
12307 		return (EIO);
12308 
12309 	bzero(&gar, sizeof (gar));
12310 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12311 
12312 	/*
12313 	 * vsecattr->vsa_mask holds the original acl request mask.
12314 	 * This is needed when determining what to return.
12315 	 * (See: nfs4_create_getsecattr_return())
12316 	 */
12317 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12318 	if (error) /* EINVAL */
12319 		return (error);
12320 
12321 	if (mi->mi_flags & MI4_ACL) {
12322 		/*
12323 		 * Check if the data is cached and the cache is valid.  If it
12324 		 * is we don't go over the wire.
12325 		 */
12326 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12327 			mutex_enter(&rp->r_statelock);
12328 			if (rp->r_secattr != NULL) {
12329 				error = nfs4_create_getsecattr_return(
12330 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12331 				    rp->r_attr.va_gid,
12332 				    vp->v_type == VDIR);
12333 				if (!error) { /* error == 0 - Success! */
12334 					mutex_exit(&rp->r_statelock);
12335 					return (error);
12336 				}
12337 			}
12338 			mutex_exit(&rp->r_statelock);
12339 		}
12340 
12341 		/*
12342 		 * The getattr otw call will always get both the acl, in
12343 		 * the form of a list of nfsace4's, and the number of acl
12344 		 * entries; independent of the value of gar.n4g_vsa.vsa_mask.
12345 		 */
12346 		gar.n4g_va.va_mask = AT_ALL;
12347 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12348 		if (error) {
12349 			vs_ace4_destroy(&gar.n4g_vsa);
12350 			if (error == ENOTSUP || error == EOPNOTSUPP)
12351 				error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12352 			return (error);
12353 		}
12354 
12355 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12356 			/*
12357 			 * No error was returned, but according to the response
12358 			 * bitmap, neither was an acl.
12359 			 */
12360 			vs_ace4_destroy(&gar.n4g_vsa);
12361 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12362 			return (error);
12363 		}
12364 
12365 		/*
12366 		 * Update the cache with the ACL.
12367 		 */
12368 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12369 
12370 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12371 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12372 		    vp->v_type == VDIR);
12373 		vs_ace4_destroy(&gar.n4g_vsa);
12374 		if ((error) && (vsecattr->vsa_mask &
12375 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12376 		    (error != EACCES)) {
12377 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12378 		}
12379 		return (error);
12380 	}
12381 	error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12382 	return (error);
12383 }
12384 
12385 /*
12386  * The function returns:
12387  * 	- 0 (zero) if the passed in "acl_mask" is a valid request.
12388  * 	- EINVAL if the passed in "acl_mask" is an invalid request.
12389  *
12390  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12391  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12392  *
12393  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12394  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12395  * - We have a count field set without the corresponding acl field set. (e.g. -
12396  * VSA_ACECNT is set, but VSA_ACE is not)
12397  */
12398 static int
12399 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12400 {
12401 	/* Shortcut the masks that are always valid. */
12402 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12403 		return (0);
12404 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12405 		return (0);
12406 
12407 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12408 		/*
12409 		 * We can't have any VSA_ACL type stuff in the mask now.
12410 		 */
12411 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12412 		    VSA_DFACLCNT))
12413 			return (EINVAL);
12414 
12415 		if (op == NFS4_ACL_SET) {
12416 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12417 				return (EINVAL);
12418 		}
12419 	}
12420 
12421 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12422 		/*
12423 		 * We can't have any VSA_ACE type stuff in the mask now.
12424 		 */
12425 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12426 			return (EINVAL);
12427 
12428 		if (op == NFS4_ACL_SET) {
12429 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12430 				return (EINVAL);
12431 
12432 			if ((acl_mask & VSA_DFACLCNT) &&
12433 			    !(acl_mask & VSA_DFACL))
12434 				return (EINVAL);
12435 		}
12436 	}
12437 	return (0);
12438 }
12439 
12440 /*
12441  * The theory behind creating the correct getsecattr return is simply this:
12442  * "Don't return anything that the caller is not expecting to have to free."
12443  */
12444 static int
12445 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12446     uid_t uid, gid_t gid, int isdir)
12447 {
12448 	int error = 0;
12449 	/* Save the mask since the translators modify it. */
12450 	uint_t	orig_mask = vsap->vsa_mask;
12451 
12452 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12453 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid,
12454 		    FALSE, ((orig_mask & VSA_ACE) ? FALSE : TRUE));
12455 
12456 		if (error)
12457 			return (error);
12458 
12459 		/*
12460 		 * If the caller only asked for the ace count (VSA_ACECNT)
12461 		 * don't give them the full acl (VSA_ACE), free it.
12462 		 */
12463 		if (!orig_mask & VSA_ACE) {
12464 			if (vsap->vsa_aclentp != NULL) {
12465 				kmem_free(vsap->vsa_aclentp,
12466 				    vsap->vsa_aclcnt * sizeof (ace_t));
12467 				vsap->vsa_aclentp = NULL;
12468 			}
12469 		}
12470 		vsap->vsa_mask = orig_mask;
12471 
12472 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12473 	    VSA_DFACLCNT)) {
12474 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12475 		    isdir, FALSE,
12476 		    ((orig_mask & (VSA_ACL | VSA_DFACL)) ? FALSE : TRUE));
12477 
12478 		if (error)
12479 			return (error);
12480 
12481 		/*
12482 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12483 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12484 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12485 		 */
12486 		if (!orig_mask & VSA_ACL) {
12487 			if (vsap->vsa_aclentp != NULL) {
12488 				kmem_free(vsap->vsa_aclentp,
12489 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12490 				vsap->vsa_aclentp = NULL;
12491 			}
12492 		}
12493 
12494 		if (!orig_mask & VSA_DFACL) {
12495 			if (vsap->vsa_dfaclentp != NULL) {
12496 				kmem_free(vsap->vsa_dfaclentp,
12497 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12498 				vsap->vsa_dfaclentp = NULL;
12499 			}
12500 		}
12501 		vsap->vsa_mask = orig_mask;
12502 	}
12503 	return (0);
12504 }
12505 
12506 /* ARGSUSED */
12507 int
12508 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr,
12509     caller_context_t *ct)
12510 {
12511 	int error;
12512 
12513 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12514 		return (EIO);
12515 	/*
12516 	 * check for valid cmd parameter
12517 	 */
12518 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12519 		return (EINVAL);
12520 
12521 	/*
12522 	 * Check access permissions
12523 	 */
12524 	if ((cmd & F_SHARE) &&
12525 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12526 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12527 		return (EBADF);
12528 
12529 	/*
12530 	 * If the filesystem is mounted using local locking, pass the
12531 	 * request off to the local share code.
12532 	 */
12533 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12534 		return (fs_shrlock(vp, cmd, shr, flag, cr, ct));
12535 
12536 	switch (cmd) {
12537 	case F_SHARE:
12538 	case F_UNSHARE:
12539 		/*
12540 		 * This will be properly implemented later,
12541 		 * see RFE: 4823948 .
12542 		 */
12543 		error = EAGAIN;
12544 		break;
12545 
12546 	case F_HASREMOTELOCKS:
12547 		/*
12548 		 * NFS client can't store remote locks itself
12549 		 */
12550 		shr->s_access = 0;
12551 		error = 0;
12552 		break;
12553 
12554 	default:
12555 		error = EINVAL;
12556 		break;
12557 	}
12558 
12559 	return (error);
12560 }
12561 
12562 /*
12563  * Common code called by directory ops to update the attrcache
12564  */
12565 static int
12566 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12567     hrtime_t t, vnode_t *vp, cred_t *cr)
12568 {
12569 	int error = 0;
12570 
12571 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12572 
12573 	if (status != NFS4_OK) {
12574 		/* getattr not done or failed */
12575 		PURGE_ATTRCACHE4(vp);
12576 		return (error);
12577 	}
12578 
12579 	if (garp) {
12580 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12581 	} else {
12582 		PURGE_ATTRCACHE4(vp);
12583 	}
12584 	return (error);
12585 }
12586 
12587 /*
12588  * Update directory caches for directory modification ops (link, rename, etc.)
12589  * When dinfo is NULL, manage dircaches in the old way.
12590  */
12591 static void
12592 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12593     dirattr_info_t *dinfo)
12594 {
12595 	rnode4_t	*drp = VTOR4(dvp);
12596 
12597 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12598 
12599 	/* Purge rddir cache for dir since it changed */
12600 	if (drp->r_dir != NULL)
12601 		nfs4_purge_rddir_cache(dvp);
12602 
12603 	/*
12604 	 * If caller provided dinfo, then use it to manage dir caches.
12605 	 */
12606 	if (dinfo != NULL) {
12607 		if (vp != NULL) {
12608 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12609 			if (!VTOR4(vp)->created_v4) {
12610 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12611 				dnlc_update(dvp, nm, vp);
12612 			} else {
12613 				/*
12614 				 * XXX don't update if the created_v4 flag is
12615 				 * set
12616 				 */
12617 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12618 				NFS4_DEBUG(nfs4_client_state_debug,
12619 				    (CE_NOTE, "nfs4_update_dircaches: "
12620 				    "don't update dnlc: created_v4 flag"));
12621 			}
12622 		}
12623 
12624 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12625 		    dinfo->di_cred, FALSE, cinfo);
12626 
12627 		return;
12628 	}
12629 
12630 	/*
12631 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12632 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12633 	 * attrs, the dir's attrs must be purged.
12634 	 *
12635 	 * XXX this check and dnlc update/purge should really be atomic,
12636 	 * XXX but can't use rnode statelock because it'll deadlock in
12637 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12638 	 * XXX does occur.
12639 	 *
12640 	 * XXX We also may want to check that atomic is true in the
12641 	 * XXX change_info struct. If it is not, the change_info may
12642 	 * XXX reflect changes by more than one clients which means that
12643 	 * XXX our cache may not be valid.
12644 	 */
12645 	PURGE_ATTRCACHE4(dvp);
12646 	if (drp->r_change == cinfo->before) {
12647 		/* no changes took place in the directory prior to our link */
12648 		if (vp != NULL) {
12649 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12650 			if (!VTOR4(vp)->created_v4) {
12651 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12652 				dnlc_update(dvp, nm, vp);
12653 			} else {
12654 				/*
12655 				 * XXX dont' update if the created_v4 flag
12656 				 * is set
12657 				 */
12658 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12659 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12660 				    "nfs4_update_dircaches: don't"
12661 				    " update dnlc: created_v4 flag"));
12662 			}
12663 		}
12664 	} else {
12665 		/* Another client modified directory - purge its dnlc cache */
12666 		dnlc_purge_vp(dvp);
12667 	}
12668 }
12669 
12670 /*
12671  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12672  * file.
12673  *
12674  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12675  * file (ie: client recovery) and otherwise set to FALSE.
12676  *
12677  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12678  * initiated) calling functions.
12679  *
12680  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12681  * of resending a 'lost' open request.
12682  *
12683  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12684  * server that hands out BAD_SEQID on open confirm.
12685  *
12686  * Errors are returned via the nfs4_error_t parameter.
12687  */
12688 void
12689 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12690     bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12691     bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12692 {
12693 	COMPOUND4args_clnt args;
12694 	COMPOUND4res_clnt res;
12695 	nfs_argop4 argop[2];
12696 	nfs_resop4 *resop;
12697 	int doqueue = 1;
12698 	mntinfo4_t *mi;
12699 	OPEN_CONFIRM4args *open_confirm_args;
12700 	int needrecov;
12701 
12702 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12703 #if DEBUG
12704 	mutex_enter(&oop->oo_lock);
12705 	ASSERT(oop->oo_seqid_inuse);
12706 	mutex_exit(&oop->oo_lock);
12707 #endif
12708 
12709 recov_retry_confirm:
12710 	nfs4_error_zinit(ep);
12711 	*retry_open = FALSE;
12712 
12713 	if (resend)
12714 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12715 	else
12716 		args.ctag = TAG_OPEN_CONFIRM;
12717 
12718 	args.array_len = 2;
12719 	args.array = argop;
12720 
12721 	/* putfh target fh */
12722 	argop[0].argop = OP_CPUTFH;
12723 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12724 
12725 	argop[1].argop = OP_OPEN_CONFIRM;
12726 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12727 
12728 	(*seqid) += 1;
12729 	open_confirm_args->seqid = *seqid;
12730 	open_confirm_args->open_stateid = *stateid;
12731 
12732 	mi = VTOMI4(vp);
12733 
12734 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12735 
12736 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12737 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12738 	}
12739 
12740 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12741 	if (!needrecov && ep->error)
12742 		return;
12743 
12744 	if (needrecov) {
12745 		bool_t abort = FALSE;
12746 
12747 		if (reopening_file == FALSE) {
12748 			nfs4_bseqid_entry_t *bsep = NULL;
12749 
12750 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12751 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12752 				    vp, 0, args.ctag,
12753 				    open_confirm_args->seqid);
12754 
12755 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp,
12756 			    NULL, NULL, NULL, OP_OPEN_CONFIRM, bsep);
12757 			if (bsep) {
12758 				kmem_free(bsep, sizeof (*bsep));
12759 				if (num_bseqid_retryp &&
12760 				    --(*num_bseqid_retryp) == 0)
12761 					abort = TRUE;
12762 			}
12763 		}
12764 		if ((ep->error == ETIMEDOUT ||
12765 		    res.status == NFS4ERR_RESOURCE) &&
12766 		    abort == FALSE && resend == FALSE) {
12767 			if (!ep->error)
12768 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12769 				    (caddr_t)&res);
12770 
12771 			delay(SEC_TO_TICK(confirm_retry_sec));
12772 			goto recov_retry_confirm;
12773 		}
12774 		/* State may have changed so retry the entire OPEN op */
12775 		if (abort == FALSE)
12776 			*retry_open = TRUE;
12777 		else
12778 			*retry_open = FALSE;
12779 		if (!ep->error)
12780 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12781 		return;
12782 	}
12783 
12784 	if (res.status) {
12785 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12786 		return;
12787 	}
12788 
12789 	resop = &res.array[1];  /* open confirm res */
12790 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
12791 	    stateid, sizeof (*stateid));
12792 
12793 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12794 }
12795 
12796 /*
12797  * Return the credentials associated with a client state object.  The
12798  * caller is responsible for freeing the credentials.
12799  */
12800 
12801 static cred_t *
12802 state_to_cred(nfs4_open_stream_t *osp)
12803 {
12804 	cred_t *cr;
12805 
12806 	/*
12807 	 * It's ok to not lock the open stream and open owner to get
12808 	 * the oo_cred since this is only written once (upon creation)
12809 	 * and will not change.
12810 	 */
12811 	cr = osp->os_open_owner->oo_cred;
12812 	crhold(cr);
12813 
12814 	return (cr);
12815 }
12816 
12817 /*
12818  * nfs4_find_sysid
12819  *
12820  * Find the sysid for the knetconfig associated with the given mi.
12821  */
12822 static struct lm_sysid *
12823 nfs4_find_sysid(mntinfo4_t *mi)
12824 {
12825 	ASSERT(nfs_zone() == mi->mi_zone);
12826 
12827 	/*
12828 	 * Switch from RDMA knconf to original mount knconf
12829 	 */
12830 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
12831 	    mi->mi_curr_serv->sv_hostname, NULL));
12832 }
12833 
12834 #ifdef DEBUG
12835 /*
12836  * Return a string version of the call type for easy reading.
12837  */
12838 static char *
12839 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
12840 {
12841 	switch (ctype) {
12842 	case NFS4_LCK_CTYPE_NORM:
12843 		return ("NORMAL");
12844 	case NFS4_LCK_CTYPE_RECLAIM:
12845 		return ("RECLAIM");
12846 	case NFS4_LCK_CTYPE_RESEND:
12847 		return ("RESEND");
12848 	case NFS4_LCK_CTYPE_REINSTATE:
12849 		return ("REINSTATE");
12850 	default:
12851 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
12852 		    "type %d", ctype);
12853 		return ("");
12854 	}
12855 }
12856 #endif
12857 
12858 /*
12859  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
12860  * Unlock requests don't have an over-the-wire locktype, so we just return
12861  * something non-threatening.
12862  */
12863 
12864 static nfs_lock_type4
12865 flk_to_locktype(int cmd, int l_type)
12866 {
12867 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
12868 
12869 	switch (l_type) {
12870 	case F_UNLCK:
12871 		return (READ_LT);
12872 	case F_RDLCK:
12873 		if (cmd == F_SETLK)
12874 			return (READ_LT);
12875 		else
12876 			return (READW_LT);
12877 	case F_WRLCK:
12878 		if (cmd == F_SETLK)
12879 			return (WRITE_LT);
12880 		else
12881 			return (WRITEW_LT);
12882 	}
12883 	panic("flk_to_locktype");
12884 	/*NOTREACHED*/
12885 }
12886 
12887 /*
12888  * Do some preliminary checks for nfs4frlock.
12889  */
12890 static int
12891 nfs4frlock_validate_args(int cmd, flock64_t *flk, int flag, vnode_t *vp,
12892     u_offset_t offset)
12893 {
12894 	int error = 0;
12895 
12896 	/*
12897 	 * If we are setting a lock, check that the file is opened
12898 	 * with the correct mode.
12899 	 */
12900 	if (cmd == F_SETLK || cmd == F_SETLKW) {
12901 		if ((flk->l_type == F_RDLCK && (flag & FREAD) == 0) ||
12902 		    (flk->l_type == F_WRLCK && (flag & FWRITE) == 0)) {
12903 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12904 			    "nfs4frlock_validate_args: file was opened with "
12905 			    "incorrect mode"));
12906 			return (EBADF);
12907 		}
12908 	}
12909 
12910 	/* Convert the offset. It may need to be restored before returning. */
12911 	if (error = convoff(vp, flk, 0, offset)) {
12912 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12913 		    "nfs4frlock_validate_args: convoff  =>  error= %d\n",
12914 		    error));
12915 		return (error);
12916 	}
12917 
12918 	return (error);
12919 }
12920 
12921 /*
12922  * Set the flock64's lm_sysid for nfs4frlock.
12923  */
12924 static int
12925 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
12926 {
12927 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12928 
12929 	/* Find the lm_sysid */
12930 	*lspp = nfs4_find_sysid(VTOMI4(vp));
12931 
12932 	if (*lspp == NULL) {
12933 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12934 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
12935 		return (ENOLCK);
12936 	}
12937 
12938 	flk->l_sysid = lm_sysidt(*lspp);
12939 
12940 	return (0);
12941 }
12942 
12943 /*
12944  * Do the remaining preliminary setup for nfs4frlock.
12945  */
12946 static void
12947 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
12948     flock64_t *flk, short *whencep, vnode_t *vp, cred_t *search_cr,
12949     cred_t **cred_otw)
12950 {
12951 	/*
12952 	 * set tick_delay to the base delay time.
12953 	 * (NFS4_BASE_WAIT_TIME is in secs)
12954 	 */
12955 
12956 	*tick_delayp = drv_usectohz(NFS4_BASE_WAIT_TIME * 1000 * 1000);
12957 
12958 	/*
12959 	 * If lock is relative to EOF, we need the newest length of the
12960 	 * file. Therefore invalidate the ATTR_CACHE.
12961 	 */
12962 
12963 	*whencep = flk->l_whence;
12964 
12965 	if (*whencep == 2)		/* SEEK_END */
12966 		PURGE_ATTRCACHE4(vp);
12967 
12968 	recov_statep->rs_flags = 0;
12969 	recov_statep->rs_num_retry_despite_err = 0;
12970 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
12971 }
12972 
12973 /*
12974  * Initialize and allocate the data structures necessary for
12975  * the nfs4frlock call.
12976  * Allocates argsp's op array, frees up the saved_rqstpp if there is one.
12977  */
12978 static void
12979 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
12980     nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
12981     bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
12982     bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
12983 {
12984 	int		argoplist_size;
12985 	int		num_ops = 2;
12986 
12987 	*retry = FALSE;
12988 	*did_start_fop = FALSE;
12989 	*skip_get_err = FALSE;
12990 	lost_rqstp->lr_op = 0;
12991 	argoplist_size  = num_ops * sizeof (nfs_argop4);
12992 	/* fill array with zero */
12993 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
12994 
12995 	*argspp = argsp;
12996 	*respp = NULL;
12997 
12998 	argsp->array_len = num_ops;
12999 	argsp->array = *argopp;
13000 
13001 	/* initialize in case of error; will get real value down below */
13002 	argsp->ctag = TAG_NONE;
13003 
13004 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
13005 		*op_hintp = OH_LOCKU;
13006 	else
13007 		*op_hintp = OH_OTHER;
13008 }
13009 
13010 /*
13011  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
13012  * the proper nfs4_server_t for this instance of nfs4frlock.
13013  * Returns 0 (success) or an errno value.
13014  */
13015 static int
13016 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
13017     nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
13018     bool_t *did_start_fop, bool_t *startrecovp)
13019 {
13020 	int error = 0;
13021 	rnode4_t *rp;
13022 
13023 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13024 
13025 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13026 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
13027 		    recov_statep, startrecovp);
13028 		if (error)
13029 			return (error);
13030 		*did_start_fop = TRUE;
13031 	} else {
13032 		*did_start_fop = FALSE;
13033 		*startrecovp = FALSE;
13034 	}
13035 
13036 	if (!error) {
13037 		rp = VTOR4(vp);
13038 
13039 		/* If the file failed recovery, just quit. */
13040 		mutex_enter(&rp->r_statelock);
13041 		if (rp->r_flags & R4RECOVERR) {
13042 			error = EIO;
13043 		}
13044 		mutex_exit(&rp->r_statelock);
13045 	}
13046 
13047 	return (error);
13048 }
13049 
13050 /*
13051  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
13052  * resend nfs4frlock call is initiated by the recovery framework.
13053  * Acquires the lop and oop seqid synchronization.
13054  */
13055 static void
13056 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
13057     COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
13058     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13059     LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
13060 {
13061 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
13062 	int error;
13063 
13064 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
13065 	    (CE_NOTE,
13066 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
13067 	ASSERT(resend_rqstp != NULL);
13068 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
13069 	    resend_rqstp->lr_op == OP_LOCKU);
13070 
13071 	*oopp = resend_rqstp->lr_oop;
13072 	if (resend_rqstp->lr_oop) {
13073 		open_owner_hold(resend_rqstp->lr_oop);
13074 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
13075 		ASSERT(error == 0);	/* recov thread always succeeds */
13076 	}
13077 
13078 	/* Must resend this lost lock/locku request. */
13079 	ASSERT(resend_rqstp->lr_lop != NULL);
13080 	*lopp = resend_rqstp->lr_lop;
13081 	lock_owner_hold(resend_rqstp->lr_lop);
13082 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
13083 	ASSERT(error == 0);	/* recov thread always succeeds */
13084 
13085 	*ospp = resend_rqstp->lr_osp;
13086 	if (*ospp)
13087 		open_stream_hold(resend_rqstp->lr_osp);
13088 
13089 	if (resend_rqstp->lr_op == OP_LOCK) {
13090 		LOCK4args *lock_args;
13091 
13092 		argop->argop = OP_LOCK;
13093 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
13094 		lock_args->locktype = resend_rqstp->lr_locktype;
13095 		lock_args->reclaim =
13096 		    (resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
13097 		lock_args->offset = resend_rqstp->lr_flk->l_start;
13098 		lock_args->length = resend_rqstp->lr_flk->l_len;
13099 		if (lock_args->length == 0)
13100 			lock_args->length = ~lock_args->length;
13101 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
13102 		    mi2clientid(mi), &lock_args->locker);
13103 
13104 		switch (resend_rqstp->lr_ctype) {
13105 		case NFS4_LCK_CTYPE_RESEND:
13106 			argsp->ctag = TAG_LOCK_RESEND;
13107 			break;
13108 		case NFS4_LCK_CTYPE_REINSTATE:
13109 			argsp->ctag = TAG_LOCK_REINSTATE;
13110 			break;
13111 		case NFS4_LCK_CTYPE_RECLAIM:
13112 			argsp->ctag = TAG_LOCK_RECLAIM;
13113 			break;
13114 		default:
13115 			argsp->ctag = TAG_LOCK_UNKNOWN;
13116 			break;
13117 		}
13118 	} else {
13119 		LOCKU4args *locku_args;
13120 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
13121 
13122 		argop->argop = OP_LOCKU;
13123 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
13124 		locku_args->locktype = READ_LT;
13125 		locku_args->seqid = lop->lock_seqid + 1;
13126 		mutex_enter(&lop->lo_lock);
13127 		locku_args->lock_stateid = lop->lock_stateid;
13128 		mutex_exit(&lop->lo_lock);
13129 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13130 		locku_args->length = resend_rqstp->lr_flk->l_len;
13131 		if (locku_args->length == 0)
13132 			locku_args->length = ~locku_args->length;
13133 
13134 		switch (resend_rqstp->lr_ctype) {
13135 		case NFS4_LCK_CTYPE_RESEND:
13136 			argsp->ctag = TAG_LOCKU_RESEND;
13137 			break;
13138 		case NFS4_LCK_CTYPE_REINSTATE:
13139 			argsp->ctag = TAG_LOCKU_REINSTATE;
13140 			break;
13141 		default:
13142 			argsp->ctag = TAG_LOCK_UNKNOWN;
13143 			break;
13144 		}
13145 	}
13146 }
13147 
13148 /*
13149  * Setup the LOCKT4 arguments.
13150  */
13151 static void
13152 nfs4frlock_setup_lockt_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13153     LOCKT4args **lockt_argsp, COMPOUND4args_clnt *argsp, flock64_t *flk,
13154     rnode4_t *rp)
13155 {
13156 	LOCKT4args *lockt_args;
13157 
13158 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13159 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13160 	argop->argop = OP_LOCKT;
13161 	argsp->ctag = TAG_LOCKT;
13162 	lockt_args = &argop->nfs_argop4_u.oplockt;
13163 
13164 	/*
13165 	 * The locktype will be READ_LT unless it's
13166 	 * a write lock. We do this because the Solaris
13167 	 * system call allows the combination of
13168 	 * F_UNLCK and F_GETLK* and so in that case the
13169 	 * unlock is mapped to a read.
13170 	 */
13171 	if (flk->l_type == F_WRLCK)
13172 		lockt_args->locktype = WRITE_LT;
13173 	else
13174 		lockt_args->locktype = READ_LT;
13175 
13176 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13177 	/* set the lock owner4 args */
13178 	nfs4_setlockowner_args(&lockt_args->owner, rp,
13179 	    ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13180 	    flk->l_pid);
13181 	lockt_args->offset = flk->l_start;
13182 	lockt_args->length = flk->l_len;
13183 	if (flk->l_len == 0)
13184 		lockt_args->length = ~lockt_args->length;
13185 
13186 	*lockt_argsp = lockt_args;
13187 }
13188 
13189 /*
13190  * If the client is holding a delegation, and the open stream to be used
13191  * with this lock request is a delegation open stream, then re-open the stream.
13192  * Sets the nfs4_error_t to all zeros unless the open stream has already
13193  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13194  * means the caller should retry (like a recovery retry).
13195  */
13196 static void
13197 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13198 {
13199 	open_delegation_type4	dt;
13200 	bool_t			reopen_needed, force;
13201 	nfs4_open_stream_t	*osp;
13202 	open_claim_type4 	oclaim;
13203 	rnode4_t		*rp = VTOR4(vp);
13204 	mntinfo4_t		*mi = VTOMI4(vp);
13205 
13206 	ASSERT(nfs_zone() == mi->mi_zone);
13207 
13208 	nfs4_error_zinit(ep);
13209 
13210 	mutex_enter(&rp->r_statev4_lock);
13211 	dt = rp->r_deleg_type;
13212 	mutex_exit(&rp->r_statev4_lock);
13213 
13214 	if (dt != OPEN_DELEGATE_NONE) {
13215 		nfs4_open_owner_t	*oop;
13216 
13217 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13218 		if (!oop) {
13219 			ep->stat = NFS4ERR_IO;
13220 			return;
13221 		}
13222 		/* returns with 'os_sync_lock' held */
13223 		osp = find_open_stream(oop, rp);
13224 		if (!osp) {
13225 			open_owner_rele(oop);
13226 			ep->stat = NFS4ERR_IO;
13227 			return;
13228 		}
13229 
13230 		if (osp->os_failed_reopen) {
13231 			NFS4_DEBUG((nfs4_open_stream_debug ||
13232 			    nfs4_client_lock_debug), (CE_NOTE,
13233 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13234 			    "for osp %p, cr %p, rp %s", (void *)osp,
13235 			    (void *)cr, rnode4info(rp)));
13236 			mutex_exit(&osp->os_sync_lock);
13237 			open_stream_rele(osp, rp);
13238 			open_owner_rele(oop);
13239 			ep->stat = NFS4ERR_IO;
13240 			return;
13241 		}
13242 
13243 		/*
13244 		 * Determine whether a reopen is needed.  If this
13245 		 * is a delegation open stream, then send the open
13246 		 * to the server to give visibility to the open owner.
13247 		 * Even if it isn't a delegation open stream, we need
13248 		 * to check if the previous open CLAIM_DELEGATE_CUR
13249 		 * was sufficient.
13250 		 */
13251 
13252 		reopen_needed = osp->os_delegation ||
13253 		    ((lt == F_RDLCK &&
13254 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13255 		    (lt == F_WRLCK &&
13256 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13257 
13258 		mutex_exit(&osp->os_sync_lock);
13259 		open_owner_rele(oop);
13260 
13261 		if (reopen_needed) {
13262 			/*
13263 			 * Always use CLAIM_PREVIOUS after server reboot.
13264 			 * The server will reject CLAIM_DELEGATE_CUR if
13265 			 * it is used during the grace period.
13266 			 */
13267 			mutex_enter(&mi->mi_lock);
13268 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13269 				oclaim = CLAIM_PREVIOUS;
13270 				force = TRUE;
13271 			} else {
13272 				oclaim = CLAIM_DELEGATE_CUR;
13273 				force = FALSE;
13274 			}
13275 			mutex_exit(&mi->mi_lock);
13276 
13277 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13278 			if (ep->error == EAGAIN) {
13279 				nfs4_error_zinit(ep);
13280 				ep->stat = NFS4ERR_DELAY;
13281 			}
13282 		}
13283 		open_stream_rele(osp, rp);
13284 		osp = NULL;
13285 	}
13286 }
13287 
13288 /*
13289  * Setup the LOCKU4 arguments.
13290  * Returns errors via the nfs4_error_t.
13291  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13292  *			over-the-wire.  The caller must release the
13293  *			reference on *lopp.
13294  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13295  * (other)		unrecoverable error.
13296  */
13297 static void
13298 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13299     LOCKU4args **locku_argsp, flock64_t *flk,
13300     nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13301     vnode_t *vp, int flag, u_offset_t offset, cred_t *cr,
13302     bool_t *skip_get_err, bool_t *go_otwp)
13303 {
13304 	nfs4_lock_owner_t	*lop = NULL;
13305 	LOCKU4args		*locku_args;
13306 	pid_t			pid;
13307 	bool_t			is_spec = FALSE;
13308 	rnode4_t		*rp = VTOR4(vp);
13309 
13310 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13311 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13312 
13313 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13314 	if (ep->error || ep->stat)
13315 		return;
13316 
13317 	argop->argop = OP_LOCKU;
13318 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13319 		argsp->ctag = TAG_LOCKU_REINSTATE;
13320 	else
13321 		argsp->ctag = TAG_LOCKU;
13322 	locku_args = &argop->nfs_argop4_u.oplocku;
13323 	*locku_argsp = locku_args;
13324 
13325 	/*
13326 	 * XXX what should locku_args->locktype be?
13327 	 * setting to ALWAYS be READ_LT so at least
13328 	 * it is a valid locktype.
13329 	 */
13330 
13331 	locku_args->locktype = READ_LT;
13332 
13333 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13334 	    flk->l_pid;
13335 
13336 	/*
13337 	 * Get the lock owner stateid.  If no lock owner
13338 	 * exists, return success.
13339 	 */
13340 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13341 	*lopp = lop;
13342 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13343 		is_spec = TRUE;
13344 	if (!lop || is_spec) {
13345 		/*
13346 		 * No lock owner so no locks to unlock.
13347 		 * Return success.  If there was a failed
13348 		 * reclaim earlier, the lock might still be
13349 		 * registered with the local locking code,
13350 		 * so notify it of the unlock.
13351 		 *
13352 		 * If the lockowner is using a special stateid,
13353 		 * then the original lock request (that created
13354 		 * this lockowner) was never successful, so we
13355 		 * have no lock to undo OTW.
13356 		 */
13357 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13358 		    "nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13359 		    "(%ld) so return success", (long)pid));
13360 
13361 		if (ctype == NFS4_LCK_CTYPE_NORM)
13362 			flk->l_pid = curproc->p_pid;
13363 		nfs4_register_lock_locally(vp, flk, flag, offset);
13364 		/*
13365 		 * Release our hold and NULL out so final_cleanup
13366 		 * doesn't try to end a lock seqid sync we
13367 		 * never started.
13368 		 */
13369 		if (is_spec) {
13370 			lock_owner_rele(lop);
13371 			*lopp = NULL;
13372 		}
13373 		*skip_get_err = TRUE;
13374 		*go_otwp = FALSE;
13375 		return;
13376 	}
13377 
13378 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13379 	if (ep->error == EAGAIN) {
13380 		lock_owner_rele(lop);
13381 		*lopp = NULL;
13382 		return;
13383 	}
13384 
13385 	mutex_enter(&lop->lo_lock);
13386 	locku_args->lock_stateid = lop->lock_stateid;
13387 	mutex_exit(&lop->lo_lock);
13388 	locku_args->seqid = lop->lock_seqid + 1;
13389 
13390 	/* leave the ref count on lop, rele after RPC call */
13391 
13392 	locku_args->offset = flk->l_start;
13393 	locku_args->length = flk->l_len;
13394 	if (flk->l_len == 0)
13395 		locku_args->length = ~locku_args->length;
13396 
13397 	*go_otwp = TRUE;
13398 }
13399 
13400 /*
13401  * Setup the LOCK4 arguments.
13402  *
13403  * Returns errors via the nfs4_error_t.
13404  * NFS4_OK		no problems
13405  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13406  * (other)		unrecoverable error
13407  */
13408 static void
13409 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13410     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13411     nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13412     flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13413 {
13414 	LOCK4args		*lock_args;
13415 	nfs4_open_owner_t	*oop = NULL;
13416 	nfs4_open_stream_t	*osp = NULL;
13417 	nfs4_lock_owner_t	*lop = NULL;
13418 	pid_t			pid;
13419 	rnode4_t		*rp = VTOR4(vp);
13420 
13421 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13422 
13423 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13424 	if (ep->error || ep->stat != NFS4_OK)
13425 		return;
13426 
13427 	argop->argop = OP_LOCK;
13428 	if (ctype == NFS4_LCK_CTYPE_NORM)
13429 		argsp->ctag = TAG_LOCK;
13430 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13431 		argsp->ctag = TAG_RELOCK;
13432 	else
13433 		argsp->ctag = TAG_LOCK_REINSTATE;
13434 	lock_args = &argop->nfs_argop4_u.oplock;
13435 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13436 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13437 	/*
13438 	 * Get the lock owner.  If no lock owner exists,
13439 	 * create a 'temporary' one and grab the open seqid
13440 	 * synchronization (which puts a hold on the open
13441 	 * owner and open stream).
13442 	 * This also grabs the lock seqid synchronization.
13443 	 */
13444 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid : flk->l_pid;
13445 	ep->stat =
13446 	    nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13447 
13448 	if (ep->stat != NFS4_OK)
13449 		goto out;
13450 
13451 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13452 	    &lock_args->locker);
13453 
13454 	lock_args->offset = flk->l_start;
13455 	lock_args->length = flk->l_len;
13456 	if (flk->l_len == 0)
13457 		lock_args->length = ~lock_args->length;
13458 	*lock_argsp = lock_args;
13459 out:
13460 	*oopp = oop;
13461 	*ospp = osp;
13462 	*lopp = lop;
13463 }
13464 
13465 /*
13466  * After we get the reply from the server, record the proper information
13467  * for possible resend lock requests.
13468  *
13469  * Allocates memory for the saved_rqstp if we have a lost lock to save.
13470  */
13471 static void
13472 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13473     nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13474     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13475     nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13476 {
13477 	bool_t unlock = (flk->l_type == F_UNLCK);
13478 
13479 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13480 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13481 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13482 
13483 	if (error != 0 && !unlock) {
13484 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13485 		    nfs4_client_lock_debug), (CE_NOTE,
13486 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13487 		    " for lop %p", (void *)lop));
13488 		ASSERT(lop != NULL);
13489 		mutex_enter(&lop->lo_lock);
13490 		lop->lo_pending_rqsts = 1;
13491 		mutex_exit(&lop->lo_lock);
13492 	}
13493 
13494 	lost_rqstp->lr_putfirst = FALSE;
13495 	lost_rqstp->lr_op = 0;
13496 
13497 	/*
13498 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13499 	 * recovery purposes so that the lock request that was sent
13500 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13501 	 * unmount.  This is done to have the client's local locking state
13502 	 * match the v4 server's state; that is, the request was
13503 	 * potentially received and accepted by the server but the client
13504 	 * thinks it was not.
13505 	 */
13506 	if (error == ETIMEDOUT || error == EINTR ||
13507 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13508 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13509 		    nfs4_client_lock_debug), (CE_NOTE,
13510 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13511 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13512 		    (void *)lop, (void *)oop, (void *)osp));
13513 		if (unlock)
13514 			lost_rqstp->lr_op = OP_LOCKU;
13515 		else {
13516 			lost_rqstp->lr_op = OP_LOCK;
13517 			lost_rqstp->lr_locktype = locktype;
13518 		}
13519 		/*
13520 		 * Objects are held and rele'd via the recovery code.
13521 		 * See nfs4_save_lost_rqst.
13522 		 */
13523 		lost_rqstp->lr_vp = vp;
13524 		lost_rqstp->lr_dvp = NULL;
13525 		lost_rqstp->lr_oop = oop;
13526 		lost_rqstp->lr_osp = osp;
13527 		lost_rqstp->lr_lop = lop;
13528 		lost_rqstp->lr_cr = cr;
13529 		switch (ctype) {
13530 		case NFS4_LCK_CTYPE_NORM:
13531 			flk->l_pid = ttoproc(curthread)->p_pid;
13532 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13533 			break;
13534 		case NFS4_LCK_CTYPE_REINSTATE:
13535 			lost_rqstp->lr_putfirst = TRUE;
13536 			lost_rqstp->lr_ctype = ctype;
13537 			break;
13538 		default:
13539 			break;
13540 		}
13541 		lost_rqstp->lr_flk = flk;
13542 	}
13543 }
13544 
13545 /*
13546  * Update lop's seqid.  Also update the seqid stored in a resend request,
13547  * if any.  (Some recovery errors increment the seqid, and we may have to
13548  * send the resend request again.)
13549  */
13550 
13551 static void
13552 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13553     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13554 {
13555 	if (lock_args) {
13556 		if (lock_args->locker.new_lock_owner == TRUE)
13557 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13558 		else {
13559 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13560 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13561 		}
13562 	} else if (locku_args) {
13563 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13564 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13565 	}
13566 }
13567 
13568 /*
13569  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13570  * COMPOUND4 args/res for calls that need to retry.
13571  * Switches the *cred_otwp to base_cr.
13572  */
13573 static void
13574 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13575     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13576     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13577     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13578     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13579 {
13580 	nfs4_open_owner_t	*oop = *oopp;
13581 	nfs4_open_stream_t	*osp = *ospp;
13582 	nfs4_lock_owner_t	*lop = *lopp;
13583 	nfs_argop4		*argop = (*argspp)->array;
13584 
13585 	if (*did_start_fop) {
13586 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13587 		    needrecov);
13588 		*did_start_fop = FALSE;
13589 	}
13590 	ASSERT((*argspp)->array_len == 2);
13591 	if (argop[1].argop == OP_LOCK)
13592 		nfs4args_lock_free(&argop[1]);
13593 	else if (argop[1].argop == OP_LOCKT)
13594 		nfs4args_lockt_free(&argop[1]);
13595 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13596 	if (!error)
13597 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13598 	*argspp = NULL;
13599 	*respp = NULL;
13600 
13601 	if (lop) {
13602 		nfs4_end_lock_seqid_sync(lop);
13603 		lock_owner_rele(lop);
13604 		*lopp = NULL;
13605 	}
13606 
13607 	/* need to free up the reference on osp for lock args */
13608 	if (osp != NULL) {
13609 		open_stream_rele(osp, VTOR4(vp));
13610 		*ospp = NULL;
13611 	}
13612 
13613 	/* need to free up the reference on oop for lock args */
13614 	if (oop != NULL) {
13615 		nfs4_end_open_seqid_sync(oop);
13616 		open_owner_rele(oop);
13617 		*oopp = NULL;
13618 	}
13619 
13620 	crfree(*cred_otwp);
13621 	*cred_otwp = base_cr;
13622 	crhold(*cred_otwp);
13623 }
13624 
13625 /*
13626  * Function to process the client's recovery for nfs4frlock.
13627  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13628  *
13629  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13630  * COMPOUND4 args/res for calls that need to retry.
13631  *
13632  * Note: the rp's r_lkserlock is *not* dropped during this path.
13633  */
13634 static bool_t
13635 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13636     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13637     LOCK4args *lock_args, LOCKU4args *locku_args,
13638     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13639     nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13640     nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13641     bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13642 {
13643 	nfs4_open_owner_t	*oop = *oopp;
13644 	nfs4_open_stream_t	*osp = *ospp;
13645 	nfs4_lock_owner_t	*lop = *lopp;
13646 
13647 	bool_t abort, retry;
13648 
13649 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13650 	ASSERT((*argspp) != NULL);
13651 	ASSERT((*respp) != NULL);
13652 	if (lock_args || locku_args)
13653 		ASSERT(lop != NULL);
13654 
13655 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13656 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13657 
13658 	retry = TRUE;
13659 	abort = FALSE;
13660 	if (needrecov) {
13661 		nfs4_bseqid_entry_t *bsep = NULL;
13662 		nfs_opnum4 op;
13663 
13664 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13665 
13666 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13667 			seqid4 seqid;
13668 
13669 			if (lock_args) {
13670 				if (lock_args->locker.new_lock_owner == TRUE)
13671 					seqid = lock_args->locker.locker4_u.
13672 					    open_owner.open_seqid;
13673 				else
13674 					seqid = lock_args->locker.locker4_u.
13675 					    lock_owner.lock_seqid;
13676 			} else if (locku_args) {
13677 				seqid = locku_args->seqid;
13678 			} else {
13679 				seqid = 0;
13680 			}
13681 
13682 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13683 			    flk->l_pid, (*argspp)->ctag, seqid);
13684 		}
13685 
13686 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13687 		    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13688 		    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13689 		    NULL, op, bsep);
13690 
13691 		if (bsep)
13692 			kmem_free(bsep, sizeof (*bsep));
13693 	}
13694 
13695 	/*
13696 	 * Return that we do not want to retry the request for 3 cases:
13697 	 * 1. If we received EINTR or are bailing out because of a forced
13698 	 *    unmount, we came into this code path just for the sake of
13699 	 *    initiating recovery, we now need to return the error.
13700 	 * 2. If we have aborted recovery.
13701 	 * 3. We received NFS4ERR_BAD_SEQID.
13702 	 */
13703 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13704 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13705 		retry = FALSE;
13706 
13707 	if (*did_start_fop == TRUE) {
13708 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13709 		    needrecov);
13710 		*did_start_fop = FALSE;
13711 	}
13712 
13713 	if (retry == TRUE) {
13714 		nfs_argop4	*argop;
13715 
13716 		argop = (*argspp)->array;
13717 		ASSERT((*argspp)->array_len == 2);
13718 
13719 		if (argop[1].argop == OP_LOCK)
13720 			nfs4args_lock_free(&argop[1]);
13721 		else if (argop[1].argop == OP_LOCKT)
13722 			nfs4args_lockt_free(&argop[1]);
13723 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13724 		if (!ep->error)
13725 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13726 		*respp = NULL;
13727 		*argspp = NULL;
13728 	}
13729 
13730 	if (lop != NULL) {
13731 		nfs4_end_lock_seqid_sync(lop);
13732 		lock_owner_rele(lop);
13733 	}
13734 
13735 	*lopp = NULL;
13736 
13737 	/* need to free up the reference on osp for lock args */
13738 	if (osp != NULL) {
13739 		open_stream_rele(osp, rp);
13740 		*ospp = NULL;
13741 	}
13742 
13743 	/* need to free up the reference on oop for lock args */
13744 	if (oop != NULL) {
13745 		nfs4_end_open_seqid_sync(oop);
13746 		open_owner_rele(oop);
13747 		*oopp = NULL;
13748 	}
13749 
13750 	return (retry);
13751 }
13752 
13753 /*
13754  * Handles the successful reply from the server for nfs4frlock.
13755  */
13756 static void
13757 nfs4frlock_results_ok(nfs4_lock_call_type_t ctype, int cmd, flock64_t *flk,
13758     vnode_t *vp, int flag, u_offset_t offset,
13759     nfs4_lost_rqst_t *resend_rqstp)
13760 {
13761 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13762 	if ((cmd == F_SETLK || cmd == F_SETLKW) &&
13763 	    (flk->l_type == F_RDLCK || flk->l_type == F_WRLCK)) {
13764 		if (ctype == NFS4_LCK_CTYPE_NORM) {
13765 			flk->l_pid = ttoproc(curthread)->p_pid;
13766 			/*
13767 			 * We do not register lost locks locally in
13768 			 * the 'resend' case since the user/application
13769 			 * doesn't think we have the lock.
13770 			 */
13771 			ASSERT(!resend_rqstp);
13772 			nfs4_register_lock_locally(vp, flk, flag, offset);
13773 		}
13774 	}
13775 }
13776 
13777 /*
13778  * Handle the DENIED reply from the server for nfs4frlock.
13779  * Returns TRUE if we should retry the request; FALSE otherwise.
13780  *
13781  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13782  * COMPOUND4 args/res for calls that need to retry.  Can also
13783  * drop and regrab the r_lkserlock.
13784  */
13785 static bool_t
13786 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13787     LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13788     nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13789     vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13790     nfs4_recov_state_t *recov_statep, int needrecov,
13791     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13792     clock_t *tick_delayp, short *whencep, int *errorp,
13793     nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13794     bool_t *skip_get_err)
13795 {
13796 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13797 
13798 	if (lock_args) {
13799 		nfs4_open_owner_t	*oop = *oopp;
13800 		nfs4_open_stream_t	*osp = *ospp;
13801 		nfs4_lock_owner_t	*lop = *lopp;
13802 		int			intr;
13803 
13804 		/*
13805 		 * Blocking lock needs to sleep and retry from the request.
13806 		 *
13807 		 * Do not block and wait for 'resend' or 'reinstate'
13808 		 * lock requests, just return the error.
13809 		 *
13810 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13811 		 */
13812 		if (cmd == F_SETLKW) {
13813 			rnode4_t *rp = VTOR4(vp);
13814 			nfs_argop4 *argop = (*argspp)->array;
13815 
13816 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13817 
13818 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13819 			    recov_statep, needrecov);
13820 			*did_start_fop = FALSE;
13821 			ASSERT((*argspp)->array_len == 2);
13822 			if (argop[1].argop == OP_LOCK)
13823 				nfs4args_lock_free(&argop[1]);
13824 			else if (argop[1].argop == OP_LOCKT)
13825 				nfs4args_lockt_free(&argop[1]);
13826 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13827 			if (*respp)
13828 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13829 				    (caddr_t)*respp);
13830 			*argspp = NULL;
13831 			*respp = NULL;
13832 			nfs4_end_lock_seqid_sync(lop);
13833 			lock_owner_rele(lop);
13834 			*lopp = NULL;
13835 			if (osp != NULL) {
13836 				open_stream_rele(osp, rp);
13837 				*ospp = NULL;
13838 			}
13839 			if (oop != NULL) {
13840 				nfs4_end_open_seqid_sync(oop);
13841 				open_owner_rele(oop);
13842 				*oopp = NULL;
13843 			}
13844 
13845 			nfs_rw_exit(&rp->r_lkserlock);
13846 
13847 			intr = nfs4_block_and_wait(tick_delayp, rp);
13848 
13849 			if (intr) {
13850 				(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13851 				    RW_WRITER, FALSE);
13852 				*errorp = EINTR;
13853 				return (FALSE);
13854 			}
13855 
13856 			(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13857 			    RW_WRITER, FALSE);
13858 
13859 			/*
13860 			 * Make sure we are still safe to lock with
13861 			 * regards to mmapping.
13862 			 */
13863 			if (!nfs4_safelock(vp, flk, cr)) {
13864 				*errorp = EAGAIN;
13865 				return (FALSE);
13866 			}
13867 
13868 			return (TRUE);
13869 		}
13870 		if (ctype == NFS4_LCK_CTYPE_NORM)
13871 			*errorp = EAGAIN;
13872 		*skip_get_err = TRUE;
13873 		flk->l_whence = 0;
13874 		*whencep = 0;
13875 		return (FALSE);
13876 	} else if (lockt_args) {
13877 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13878 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
13879 
13880 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
13881 		    flk, lockt_args);
13882 
13883 		/* according to NLM code */
13884 		*errorp = 0;
13885 		*whencep = 0;
13886 		*skip_get_err = TRUE;
13887 		return (FALSE);
13888 	}
13889 	return (FALSE);
13890 }
13891 
13892 /*
13893  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
13894  */
13895 static void
13896 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
13897 {
13898 	switch (resp->status) {
13899 	case NFS4ERR_ACCESS:
13900 	case NFS4ERR_ADMIN_REVOKED:
13901 	case NFS4ERR_BADHANDLE:
13902 	case NFS4ERR_BAD_RANGE:
13903 	case NFS4ERR_BAD_SEQID:
13904 	case NFS4ERR_BAD_STATEID:
13905 	case NFS4ERR_BADXDR:
13906 	case NFS4ERR_DEADLOCK:
13907 	case NFS4ERR_DELAY:
13908 	case NFS4ERR_EXPIRED:
13909 	case NFS4ERR_FHEXPIRED:
13910 	case NFS4ERR_GRACE:
13911 	case NFS4ERR_INVAL:
13912 	case NFS4ERR_ISDIR:
13913 	case NFS4ERR_LEASE_MOVED:
13914 	case NFS4ERR_LOCK_NOTSUPP:
13915 	case NFS4ERR_LOCK_RANGE:
13916 	case NFS4ERR_MOVED:
13917 	case NFS4ERR_NOFILEHANDLE:
13918 	case NFS4ERR_NO_GRACE:
13919 	case NFS4ERR_OLD_STATEID:
13920 	case NFS4ERR_OPENMODE:
13921 	case NFS4ERR_RECLAIM_BAD:
13922 	case NFS4ERR_RECLAIM_CONFLICT:
13923 	case NFS4ERR_RESOURCE:
13924 	case NFS4ERR_SERVERFAULT:
13925 	case NFS4ERR_STALE:
13926 	case NFS4ERR_STALE_CLIENTID:
13927 	case NFS4ERR_STALE_STATEID:
13928 		return;
13929 	default:
13930 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13931 		    "nfs4frlock_results_default: got unrecognizable "
13932 		    "res.status %d", resp->status));
13933 		*errorp = NFS4ERR_INVAL;
13934 	}
13935 }
13936 
13937 /*
13938  * The lock request was successful, so update the client's state.
13939  */
13940 static void
13941 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
13942     LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
13943     vnode_t *vp, flock64_t *flk, cred_t *cr,
13944     nfs4_lost_rqst_t *resend_rqstp)
13945 {
13946 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13947 
13948 	if (lock_args) {
13949 		LOCK4res *lock_res;
13950 
13951 		lock_res = &resop->nfs_resop4_u.oplock;
13952 		/* update the stateid with server's response */
13953 
13954 		if (lock_args->locker.new_lock_owner == TRUE) {
13955 			mutex_enter(&lop->lo_lock);
13956 			lop->lo_just_created = NFS4_PERM_CREATED;
13957 			mutex_exit(&lop->lo_lock);
13958 		}
13959 
13960 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
13961 
13962 		/*
13963 		 * If the lock was the result of a resending a lost
13964 		 * request, we've synched up the stateid and seqid
13965 		 * with the server, but now the server might be out of sync
13966 		 * with what the application thinks it has for locks.
13967 		 * Clean that up here.  It's unclear whether we should do
13968 		 * this even if the filesystem has been forcibly unmounted.
13969 		 * For most servers, it's probably wasted effort, but
13970 		 * RFC3530 lets servers require that unlocks exactly match
13971 		 * the locks that are held.
13972 		 */
13973 		if (resend_rqstp != NULL &&
13974 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
13975 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
13976 		} else {
13977 			flk->l_whence = 0;
13978 		}
13979 	} else if (locku_args) {
13980 		LOCKU4res *locku_res;
13981 
13982 		locku_res = &resop->nfs_resop4_u.oplocku;
13983 
13984 		/* Update the stateid with the server's response */
13985 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
13986 	} else if (lockt_args) {
13987 		/* Switch the lock type to express success, see fcntl */
13988 		flk->l_type = F_UNLCK;
13989 		flk->l_whence = 0;
13990 	}
13991 }
13992 
13993 /*
13994  * Do final cleanup before exiting nfs4frlock.
13995  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13996  * COMPOUND4 args/res for calls that haven't already.
13997  */
13998 static void
13999 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
14000     COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
14001     nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
14002     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
14003     short whence, u_offset_t offset, struct lm_sysid *ls,
14004     int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
14005     bool_t did_start_fop, bool_t skip_get_err,
14006     cred_t *cred_otw, cred_t *cred)
14007 {
14008 	mntinfo4_t	*mi = VTOMI4(vp);
14009 	rnode4_t	*rp = VTOR4(vp);
14010 	int		error = *errorp;
14011 	nfs_argop4	*argop;
14012 	int	do_flush_pages = 0;
14013 
14014 	ASSERT(nfs_zone() == mi->mi_zone);
14015 	/*
14016 	 * The client recovery code wants the raw status information,
14017 	 * so don't map the NFS status code to an errno value for
14018 	 * non-normal call types.
14019 	 */
14020 	if (ctype == NFS4_LCK_CTYPE_NORM) {
14021 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
14022 			*errorp = geterrno4(resp->status);
14023 		if (did_start_fop == TRUE)
14024 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
14025 			    needrecov);
14026 
14027 		/*
14028 		 * We've established a new lock on the server, so invalidate
14029 		 * the pages associated with the vnode to get the most up to
14030 		 * date pages from the server after acquiring the lock. We
14031 		 * want to be sure that the read operation gets the newest data.
14032 		 * N.B.
14033 		 * We used to do this in nfs4frlock_results_ok but that doesn't
14034 		 * work since VOP_PUTPAGE can call nfs4_commit which calls
14035 		 * nfs4_start_fop. We flush the pages below after calling
14036 		 * nfs4_end_fop above
14037 		 * The flush of the page cache must be done after
14038 		 * nfs4_end_open_seqid_sync() to avoid a 4-way hang.
14039 		 */
14040 		if (!error && resp && resp->status == NFS4_OK)
14041 			do_flush_pages = 1;
14042 	}
14043 	if (argsp) {
14044 		ASSERT(argsp->array_len == 2);
14045 		argop = argsp->array;
14046 		if (argop[1].argop == OP_LOCK)
14047 			nfs4args_lock_free(&argop[1]);
14048 		else if (argop[1].argop == OP_LOCKT)
14049 			nfs4args_lockt_free(&argop[1]);
14050 		kmem_free(argop, 2 * sizeof (nfs_argop4));
14051 		if (resp)
14052 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
14053 	}
14054 
14055 	/* free the reference on the lock owner */
14056 	if (lop != NULL) {
14057 		nfs4_end_lock_seqid_sync(lop);
14058 		lock_owner_rele(lop);
14059 	}
14060 
14061 	/* need to free up the reference on osp for lock args */
14062 	if (osp != NULL)
14063 		open_stream_rele(osp, rp);
14064 
14065 	/* need to free up the reference on oop for lock args */
14066 	if (oop != NULL) {
14067 		nfs4_end_open_seqid_sync(oop);
14068 		open_owner_rele(oop);
14069 	}
14070 
14071 	if (do_flush_pages)
14072 		nfs4_flush_pages(vp, cred);
14073 
14074 	(void) convoff(vp, flk, whence, offset);
14075 
14076 	lm_rel_sysid(ls);
14077 
14078 	/*
14079 	 * Record debug information in the event we get EINVAL.
14080 	 */
14081 	mutex_enter(&mi->mi_lock);
14082 	if (*errorp == EINVAL && (lock_args || locku_args) &&
14083 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
14084 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
14085 			zcmn_err(getzoneid(), CE_NOTE,
14086 			    "%s operation failed with "
14087 			    "EINVAL probably since the server, %s,"
14088 			    " doesn't support POSIX style locking",
14089 			    lock_args ? "LOCK" : "LOCKU",
14090 			    mi->mi_curr_serv->sv_hostname);
14091 			mi->mi_flags |= MI4_LOCK_DEBUG;
14092 		}
14093 	}
14094 	mutex_exit(&mi->mi_lock);
14095 
14096 	if (cred_otw)
14097 		crfree(cred_otw);
14098 }
14099 
14100 /*
14101  * This calls the server and the local locking code.
14102  *
14103  * Client locks are registerred locally by oring the sysid with
14104  * LM_SYSID_CLIENT. The server registers locks locally using just the sysid.
14105  * We need to distinguish between the two to avoid collision in case one
14106  * machine is used as both client and server.
14107  *
14108  * Blocking lock requests will continually retry to acquire the lock
14109  * forever.
14110  *
14111  * The ctype is defined as follows:
14112  * NFS4_LCK_CTYPE_NORM: normal lock request.
14113  *
14114  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
14115  * recovery, get the pid from flk instead of curproc, and don't reregister
14116  * the lock locally.
14117  *
14118  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
14119  * that we will use the information passed in via resend_rqstp to setup the
14120  * lock/locku request.  This resend is the exact same request as the 'lost
14121  * lock', and is initiated by the recovery framework. A successful resend
14122  * request can initiate one or more reinstate requests.
14123  *
14124  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14125  * does not trigger additional reinstate requests.  This lock call type is
14126  * set for setting the v4 server's locking state back to match what the
14127  * client's local locking state is in the event of a received 'lost lock'.
14128  *
14129  * Errors are returned via the nfs4_error_t parameter.
14130  */
14131 void
14132 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14133     int flag, u_offset_t offset, cred_t *cr, nfs4_error_t *ep,
14134     nfs4_lost_rqst_t *resend_rqstp, int *did_reclaimp)
14135 {
14136 	COMPOUND4args_clnt	args, *argsp = NULL;
14137 	COMPOUND4res_clnt	res, *resp = NULL;
14138 	nfs_argop4	*argop;
14139 	nfs_resop4	*resop;
14140 	rnode4_t	*rp;
14141 	int		doqueue = 1;
14142 	clock_t		tick_delay;  /* delay in clock ticks */
14143 	struct lm_sysid	*ls;
14144 	LOCK4args	*lock_args = NULL;
14145 	LOCKU4args	*locku_args = NULL;
14146 	LOCKT4args	*lockt_args = NULL;
14147 	nfs4_open_owner_t *oop = NULL;
14148 	nfs4_open_stream_t *osp = NULL;
14149 	nfs4_lock_owner_t *lop = NULL;
14150 	bool_t		needrecov = FALSE;
14151 	nfs4_recov_state_t recov_state;
14152 	short		whence;
14153 	nfs4_op_hint_t	op_hint;
14154 	nfs4_lost_rqst_t lost_rqst;
14155 	bool_t		retry = FALSE;
14156 	bool_t		did_start_fop = FALSE;
14157 	bool_t		skip_get_err = FALSE;
14158 	cred_t		*cred_otw = NULL;
14159 	bool_t		recovonly;	/* just queue request */
14160 	int		frc_no_reclaim = 0;
14161 #ifdef DEBUG
14162 	char *name;
14163 #endif
14164 
14165 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14166 
14167 #ifdef DEBUG
14168 	name = fn_name(VTOSV(vp)->sv_name);
14169 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14170 	    "%s: cmd %d, type %d, offset %llu, start %"PRIx64", "
14171 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14172 	    "resend request %s", name, cmd, flk->l_type, offset, flk->l_start,
14173 	    flk->l_len, ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid :
14174 	    flk->l_pid, flk->l_sysid, nfs4frlock_get_call_type(ctype),
14175 	    resend_rqstp ? "TRUE" : "FALSE"));
14176 	kmem_free(name, MAXNAMELEN);
14177 #endif
14178 
14179 	nfs4_error_zinit(ep);
14180 	ep->error = nfs4frlock_validate_args(cmd, flk, flag, vp, offset);
14181 	if (ep->error)
14182 		return;
14183 	ep->error = nfs4frlock_get_sysid(&ls, vp, flk);
14184 	if (ep->error)
14185 		return;
14186 	nfs4frlock_pre_setup(&tick_delay, &recov_state, flk, &whence,
14187 	    vp, cr, &cred_otw);
14188 
14189 recov_retry:
14190 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14191 	    &retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14192 	rp = VTOR4(vp);
14193 
14194 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14195 	    &did_start_fop, &recovonly);
14196 
14197 	if (ep->error)
14198 		goto out;
14199 
14200 	if (recovonly) {
14201 		/*
14202 		 * Leave the request for the recovery system to deal with.
14203 		 */
14204 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14205 		ASSERT(cmd != F_GETLK);
14206 		ASSERT(flk->l_type == F_UNLCK);
14207 
14208 		nfs4_error_init(ep, EINTR);
14209 		needrecov = TRUE;
14210 		lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14211 		if (lop != NULL) {
14212 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14213 			    NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14214 			(void) nfs4_start_recovery(ep,
14215 			    VTOMI4(vp), vp, NULL, NULL,
14216 			    (lost_rqst.lr_op == OP_LOCK ||
14217 			    lost_rqst.lr_op == OP_LOCKU) ?
14218 			    &lost_rqst : NULL, OP_LOCKU, NULL);
14219 			lock_owner_rele(lop);
14220 			lop = NULL;
14221 		}
14222 		flk->l_pid = curproc->p_pid;
14223 		nfs4_register_lock_locally(vp, flk, flag, offset);
14224 		goto out;
14225 	}
14226 
14227 	/* putfh directory fh */
14228 	argop[0].argop = OP_CPUTFH;
14229 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14230 
14231 	/*
14232 	 * Set up the over-the-wire arguments and get references to the
14233 	 * open owner, etc.
14234 	 */
14235 
14236 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14237 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14238 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14239 		    &argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14240 	} else {
14241 		bool_t go_otw = TRUE;
14242 
14243 		ASSERT(resend_rqstp == NULL);
14244 
14245 		switch (cmd) {
14246 		case F_GETLK:
14247 		case F_O_GETLK:
14248 			nfs4frlock_setup_lockt_args(ctype, &argop[1],
14249 			    &lockt_args, argsp, flk, rp);
14250 			break;
14251 		case F_SETLKW:
14252 		case F_SETLK:
14253 			if (flk->l_type == F_UNLCK)
14254 				nfs4frlock_setup_locku_args(ctype,
14255 				    &argop[1], &locku_args, flk,
14256 				    &lop, ep, argsp,
14257 				    vp, flag, offset, cr,
14258 				    &skip_get_err, &go_otw);
14259 			else
14260 				nfs4frlock_setup_lock_args(ctype,
14261 				    &lock_args, &oop, &osp, &lop, &argop[1],
14262 				    argsp, flk, cmd, vp, cr, ep);
14263 
14264 			if (ep->error)
14265 				goto out;
14266 
14267 			switch (ep->stat) {
14268 			case NFS4_OK:
14269 				break;
14270 			case NFS4ERR_DELAY:
14271 				/* recov thread never gets this error */
14272 				ASSERT(resend_rqstp == NULL);
14273 				ASSERT(did_start_fop);
14274 
14275 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14276 				    &recov_state, TRUE);
14277 				did_start_fop = FALSE;
14278 				if (argop[1].argop == OP_LOCK)
14279 					nfs4args_lock_free(&argop[1]);
14280 				else if (argop[1].argop == OP_LOCKT)
14281 					nfs4args_lockt_free(&argop[1]);
14282 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14283 				argsp = NULL;
14284 				goto recov_retry;
14285 			default:
14286 				ep->error = EIO;
14287 				goto out;
14288 			}
14289 			break;
14290 		default:
14291 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14292 			    "nfs4_frlock: invalid cmd %d", cmd));
14293 			ep->error = EINVAL;
14294 			goto out;
14295 		}
14296 
14297 		if (!go_otw)
14298 			goto out;
14299 	}
14300 
14301 	/* XXX should we use the local reclock as a cache ? */
14302 	/*
14303 	 * Unregister the lock with the local locking code before
14304 	 * contacting the server.  This avoids a potential race where
14305 	 * another process gets notified that it has been granted a lock
14306 	 * before we can unregister ourselves locally.
14307 	 */
14308 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK) {
14309 		if (ctype == NFS4_LCK_CTYPE_NORM)
14310 			flk->l_pid = ttoproc(curthread)->p_pid;
14311 		nfs4_register_lock_locally(vp, flk, flag, offset);
14312 	}
14313 
14314 	/*
14315 	 * Send the server the lock request.  Continually loop with a delay
14316 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14317 	 */
14318 	resp = &res;
14319 
14320 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14321 	    (CE_NOTE,
14322 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14323 	    rnode4info(rp)));
14324 
14325 	if (lock_args && frc_no_reclaim) {
14326 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14327 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14328 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14329 		lock_args->reclaim = FALSE;
14330 		if (did_reclaimp)
14331 			*did_reclaimp = 0;
14332 	}
14333 
14334 	/*
14335 	 * Do the OTW call.
14336 	 */
14337 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14338 
14339 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14340 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14341 
14342 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14343 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14344 	    "nfs4frlock: needrecov %d", needrecov));
14345 
14346 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14347 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14348 		    args.ctag);
14349 
14350 	/*
14351 	 * Check if one of these mutually exclusive error cases has
14352 	 * happened:
14353 	 *   need to swap credentials due to access error
14354 	 *   recovery is needed
14355 	 *   different error (only known case is missing Kerberos ticket)
14356 	 */
14357 
14358 	if ((ep->error == EACCES ||
14359 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14360 	    cred_otw != cr) {
14361 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14362 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14363 		    cr, &cred_otw);
14364 		goto recov_retry;
14365 	}
14366 
14367 	if (needrecov) {
14368 		/*
14369 		 * LOCKT requests don't need to recover from lost
14370 		 * requests since they don't create/modify state.
14371 		 */
14372 		if ((ep->error == EINTR ||
14373 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14374 		    lockt_args)
14375 			goto out;
14376 		/*
14377 		 * Do not attempt recovery for requests initiated by
14378 		 * the recovery framework.  Let the framework redrive them.
14379 		 */
14380 		if (ctype != NFS4_LCK_CTYPE_NORM)
14381 			goto out;
14382 		else {
14383 			ASSERT(resend_rqstp == NULL);
14384 		}
14385 
14386 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14387 		    flk_to_locktype(cmd, flk->l_type),
14388 		    oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14389 
14390 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14391 		    &resp, lock_args, locku_args, &oop, &osp, &lop,
14392 		    rp, vp, &recov_state, op_hint, &did_start_fop,
14393 		    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14394 
14395 		if (retry) {
14396 			ASSERT(oop == NULL);
14397 			ASSERT(osp == NULL);
14398 			ASSERT(lop == NULL);
14399 			goto recov_retry;
14400 		}
14401 		goto out;
14402 	}
14403 
14404 	/*
14405 	 * Bail out if have reached this point with ep->error set. Can
14406 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14407 	 * This happens if Kerberos ticket has expired or has been
14408 	 * destroyed.
14409 	 */
14410 	if (ep->error != 0)
14411 		goto out;
14412 
14413 	/*
14414 	 * Process the reply.
14415 	 */
14416 	switch (resp->status) {
14417 	case NFS4_OK:
14418 		resop = &resp->array[1];
14419 		nfs4frlock_results_ok(ctype, cmd, flk, vp, flag, offset,
14420 		    resend_rqstp);
14421 		/*
14422 		 * Have a successful lock operation, now update state.
14423 		 */
14424 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14425 		    resop, lop, vp, flk, cr, resend_rqstp);
14426 		break;
14427 
14428 	case NFS4ERR_DENIED:
14429 		resop = &resp->array[1];
14430 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14431 		    &oop, &osp, &lop, cmd, vp, flk, op_hint,
14432 		    &recov_state, needrecov, &argsp, &resp,
14433 		    &tick_delay, &whence, &ep->error, resop, cr,
14434 		    &did_start_fop, &skip_get_err);
14435 
14436 		if (retry) {
14437 			ASSERT(oop == NULL);
14438 			ASSERT(osp == NULL);
14439 			ASSERT(lop == NULL);
14440 			goto recov_retry;
14441 		}
14442 		break;
14443 	/*
14444 	 * If the server won't let us reclaim, fall-back to trying to lock
14445 	 * the file from scratch. Code elsewhere will check the changeinfo
14446 	 * to ensure the file hasn't been changed.
14447 	 */
14448 	case NFS4ERR_NO_GRACE:
14449 		if (lock_args && lock_args->reclaim == TRUE) {
14450 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14451 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14452 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14453 			frc_no_reclaim = 1;
14454 			/* clean up before retrying */
14455 			needrecov = 0;
14456 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14457 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14458 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14459 			goto recov_retry;
14460 		}
14461 		/* FALLTHROUGH */
14462 
14463 	default:
14464 		nfs4frlock_results_default(resp, &ep->error);
14465 		break;
14466 	}
14467 out:
14468 	/*
14469 	 * Process and cleanup from error.  Make interrupted unlock
14470 	 * requests look successful, since they will be handled by the
14471 	 * client recovery code.
14472 	 */
14473 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14474 	    needrecov, oop, osp, lop, flk, whence, offset, ls, &ep->error,
14475 	    lock_args, locku_args, did_start_fop,
14476 	    skip_get_err, cred_otw, cr);
14477 
14478 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14479 	    (cmd == F_SETLK || cmd == F_SETLKW))
14480 		ep->error = 0;
14481 }
14482 
14483 /*
14484  * nfs4_safelock:
14485  *
14486  * Return non-zero if the given lock request can be handled without
14487  * violating the constraints on concurrent mapping and locking.
14488  */
14489 
14490 static int
14491 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14492 {
14493 	rnode4_t *rp = VTOR4(vp);
14494 	struct vattr va;
14495 	int error;
14496 
14497 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14498 	ASSERT(rp->r_mapcnt >= 0);
14499 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14500 	    "(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14501 	    "write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14502 	    bfp->l_start, bfp->l_len, rp->r_mapcnt));
14503 
14504 	if (rp->r_mapcnt == 0)
14505 		return (1);		/* always safe if not mapped */
14506 
14507 	/*
14508 	 * If the file is already mapped and there are locks, then they
14509 	 * should be all safe locks.  So adding or removing a lock is safe
14510 	 * as long as the new request is safe (i.e., whole-file, meaning
14511 	 * length and starting offset are both zero).
14512 	 */
14513 
14514 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14515 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14516 		    "cannot lock a memory mapped file unless locking the "
14517 		    "entire file: start %"PRIx64", len %"PRIx64,
14518 		    bfp->l_start, bfp->l_len));
14519 		return (0);
14520 	}
14521 
14522 	/* mandatory locking and mapping don't mix */
14523 	va.va_mask = AT_MODE;
14524 	error = VOP_GETATTR(vp, &va, 0, cr, NULL);
14525 	if (error != 0) {
14526 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14527 		    "getattr error %d", error));
14528 		return (0);		/* treat errors conservatively */
14529 	}
14530 	if (MANDLOCK(vp, va.va_mode)) {
14531 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14532 		    "cannot mandatory lock and mmap a file"));
14533 		return (0);
14534 	}
14535 
14536 	return (1);
14537 }
14538 
14539 
14540 /*
14541  * Register the lock locally within Solaris.
14542  * As the client, we "or" the sysid with LM_SYSID_CLIENT when
14543  * recording locks locally.
14544  *
14545  * This should handle conflicts/cooperation with NFS v2/v3 since all locks
14546  * are registered locally.
14547  */
14548 void
14549 nfs4_register_lock_locally(vnode_t *vp, struct flock64 *flk, int flag,
14550     u_offset_t offset)
14551 {
14552 	int oldsysid;
14553 	int error;
14554 #ifdef DEBUG
14555 	char *name;
14556 #endif
14557 
14558 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14559 
14560 #ifdef DEBUG
14561 	name = fn_name(VTOSV(vp)->sv_name);
14562 	NFS4_DEBUG(nfs4_client_lock_debug,
14563 	    (CE_NOTE, "nfs4_register_lock_locally: %s: type %d, "
14564 	    "start %"PRIx64", length %"PRIx64", pid %ld, sysid %d",
14565 	    name, flk->l_type, flk->l_start, flk->l_len, (long)flk->l_pid,
14566 	    flk->l_sysid));
14567 	kmem_free(name, MAXNAMELEN);
14568 #endif
14569 
14570 	/* register the lock with local locking */
14571 	oldsysid = flk->l_sysid;
14572 	flk->l_sysid |= LM_SYSID_CLIENT;
14573 	error = reclock(vp, flk, SETFLCK, flag, offset, NULL);
14574 #ifdef DEBUG
14575 	if (error != 0) {
14576 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14577 		    "nfs4_register_lock_locally: could not register with"
14578 		    " local locking"));
14579 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14580 		    "error %d, vp 0x%p, pid %d, sysid 0x%x",
14581 		    error, (void *)vp, flk->l_pid, flk->l_sysid));
14582 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14583 		    "type %d off 0x%" PRIx64 " len 0x%" PRIx64,
14584 		    flk->l_type, flk->l_start, flk->l_len));
14585 		(void) reclock(vp, flk, 0, flag, offset, NULL);
14586 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14587 		    "blocked by pid %d sysid 0x%x type %d "
14588 		    "off 0x%" PRIx64 " len 0x%" PRIx64,
14589 		    flk->l_pid, flk->l_sysid, flk->l_type, flk->l_start,
14590 		    flk->l_len));
14591 	}
14592 #endif
14593 	flk->l_sysid = oldsysid;
14594 }
14595 
14596 /*
14597  * nfs4_lockrelease:
14598  *
14599  * Release any locks on the given vnode that are held by the current
14600  * process.  Also removes the lock owner (if one exists) from the rnode's
14601  * list.
14602  */
14603 static int
14604 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14605 {
14606 	flock64_t ld;
14607 	int ret, error;
14608 	rnode4_t *rp;
14609 	nfs4_lock_owner_t *lop;
14610 	nfs4_recov_state_t recov_state;
14611 	mntinfo4_t *mi;
14612 	bool_t possible_orphan = FALSE;
14613 	bool_t recovonly;
14614 
14615 	ASSERT((uintptr_t)vp > KERNELBASE);
14616 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14617 
14618 	rp = VTOR4(vp);
14619 	mi = VTOMI4(vp);
14620 
14621 	/*
14622 	 * If we have not locked anything then we can
14623 	 * just return since we have no work to do.
14624 	 */
14625 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14626 		return (0);
14627 	}
14628 
14629 	/*
14630 	 * We need to comprehend that another thread may
14631 	 * kick off recovery and the lock_owner we have stashed
14632 	 * in lop might be invalid so we should NOT cache it
14633 	 * locally!
14634 	 */
14635 	recov_state.rs_flags = 0;
14636 	recov_state.rs_num_retry_despite_err = 0;
14637 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14638 	    &recovonly);
14639 	if (error) {
14640 		mutex_enter(&rp->r_statelock);
14641 		rp->r_flags |= R4LODANGLERS;
14642 		mutex_exit(&rp->r_statelock);
14643 		return (error);
14644 	}
14645 
14646 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14647 
14648 	/*
14649 	 * Check if the lock owner might have a lock (request was sent but
14650 	 * no response was received).  Also check if there are any remote
14651 	 * locks on the file.  (In theory we shouldn't have to make this
14652 	 * second check if there's no lock owner, but for now we'll be
14653 	 * conservative and do it anyway.)  If either condition is true,
14654 	 * send an unlock for the entire file to the server.
14655 	 *
14656 	 * Note that no explicit synchronization is needed here.  At worst,
14657 	 * flk_has_remote_locks() will return a false positive, in which case
14658 	 * the unlock call wastes time but doesn't harm correctness.
14659 	 */
14660 
14661 	if (lop) {
14662 		mutex_enter(&lop->lo_lock);
14663 		possible_orphan = lop->lo_pending_rqsts;
14664 		mutex_exit(&lop->lo_lock);
14665 		lock_owner_rele(lop);
14666 	}
14667 
14668 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14669 
14670 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14671 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14672 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14673 	    (void *)lop));
14674 
14675 	if (possible_orphan || flk_has_remote_locks(vp)) {
14676 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14677 		ld.l_whence = 0;	/* unlock from start of file */
14678 		ld.l_start = 0;
14679 		ld.l_len = 0;		/* do entire file */
14680 
14681 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL,
14682 		    cr, NULL);
14683 
14684 		if (ret != 0) {
14685 			/*
14686 			 * If VOP_FRLOCK fails, make sure we unregister
14687 			 * local locks before we continue.
14688 			 */
14689 			ld.l_pid = ttoproc(curthread)->p_pid;
14690 			nfs4_register_lock_locally(vp, &ld, flag, offset);
14691 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14692 			    "nfs4_lockrelease: lock release error on vp"
14693 			    " %p: error %d.\n", (void *)vp, ret));
14694 		}
14695 	}
14696 
14697 	recov_state.rs_flags = 0;
14698 	recov_state.rs_num_retry_despite_err = 0;
14699 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14700 	    &recovonly);
14701 	if (error) {
14702 		mutex_enter(&rp->r_statelock);
14703 		rp->r_flags |= R4LODANGLERS;
14704 		mutex_exit(&rp->r_statelock);
14705 		return (error);
14706 	}
14707 
14708 	/*
14709 	 * So, here we're going to need to retrieve the lock-owner
14710 	 * again (in case recovery has done a switch-a-roo) and
14711 	 * remove it because we can.
14712 	 */
14713 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14714 
14715 	if (lop) {
14716 		nfs4_rnode_remove_lock_owner(rp, lop);
14717 		lock_owner_rele(lop);
14718 	}
14719 
14720 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14721 	return (0);
14722 }
14723 
14724 /*
14725  * Wait for 'tick_delay' clock ticks.
14726  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14727  * NOTE: lock_lease_time is in seconds.
14728  *
14729  * XXX For future improvements, should implement a waiting queue scheme.
14730  */
14731 static int
14732 nfs4_block_and_wait(clock_t *tick_delay, rnode4_t *rp)
14733 {
14734 	long milliseconds_delay;
14735 	time_t lock_lease_time;
14736 
14737 	/* wait tick_delay clock ticks or siginteruptus */
14738 	if (delay_sig(*tick_delay)) {
14739 		return (EINTR);
14740 	}
14741 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14742 	    "reissue the lock request: blocked for %ld clock ticks: %ld "
14743 	    "milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14744 
14745 	/* get the lease time */
14746 	lock_lease_time = r2lease_time(rp);
14747 
14748 	/* drv_hztousec converts ticks to microseconds */
14749 	milliseconds_delay = drv_hztousec(*tick_delay) / 1000;
14750 	if (milliseconds_delay < lock_lease_time * 1000) {
14751 		*tick_delay = 2 * *tick_delay;
14752 		if (drv_hztousec(*tick_delay) > lock_lease_time * 1000 * 1000)
14753 			*tick_delay = drv_usectohz(lock_lease_time*1000*1000);
14754 	}
14755 	return (0);
14756 }
14757 
14758 
14759 void
14760 nfs4_vnops_init(void)
14761 {
14762 }
14763 
14764 void
14765 nfs4_vnops_fini(void)
14766 {
14767 }
14768 
14769 /*
14770  * Return a reference to the directory (parent) vnode for a given vnode,
14771  * using the saved pathname information and the directory file handle.  The
14772  * caller is responsible for disposing of the reference.
14773  * Returns zero or an errno value.
14774  *
14775  * Caller should set need_start_op to FALSE if it is the recovery
14776  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14777  */
14778 int
14779 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14780 {
14781 	svnode_t *svnp;
14782 	vnode_t *dvp = NULL;
14783 	servinfo4_t *svp;
14784 	nfs4_fname_t *mfname;
14785 	int error;
14786 
14787 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14788 
14789 	if (vp->v_flag & VROOT) {
14790 		nfs4_sharedfh_t *sfh;
14791 		nfs_fh4 fh;
14792 		mntinfo4_t *mi;
14793 
14794 		ASSERT(vp->v_type == VREG);
14795 
14796 		mi = VTOMI4(vp);
14797 		svp = mi->mi_curr_serv;
14798 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14799 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14800 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14801 		sfh = sfh4_get(&fh, VTOMI4(vp));
14802 		nfs_rw_exit(&svp->sv_lock);
14803 		mfname = mi->mi_fname;
14804 		fn_hold(mfname);
14805 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14806 		sfh4_rele(&sfh);
14807 
14808 		if (dvp->v_type == VNON)
14809 			dvp->v_type = VDIR;
14810 		*dvpp = dvp;
14811 		return (0);
14812 	}
14813 
14814 	svnp = VTOSV(vp);
14815 
14816 	if (svnp == NULL) {
14817 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14818 		    "shadow node is NULL"));
14819 		return (EINVAL);
14820 	}
14821 
14822 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14823 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14824 		    "shadow node name or dfh val == NULL"));
14825 		return (EINVAL);
14826 	}
14827 
14828 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14829 	    (int)need_start_op);
14830 	if (error != 0) {
14831 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14832 		    "nfs4_make_dotdot returned %d", error));
14833 		return (error);
14834 	}
14835 	if (!dvp) {
14836 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14837 		    "nfs4_make_dotdot returned a NULL dvp"));
14838 		return (EIO);
14839 	}
14840 	if (dvp->v_type == VNON)
14841 		dvp->v_type = VDIR;
14842 	ASSERT(dvp->v_type == VDIR);
14843 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14844 		mutex_enter(&dvp->v_lock);
14845 		dvp->v_flag |= V_XATTRDIR;
14846 		mutex_exit(&dvp->v_lock);
14847 	}
14848 	*dvpp = dvp;
14849 	return (0);
14850 }
14851 
14852 /*
14853  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14854  * length that fnamep can accept, including the trailing null.
14855  * Returns 0 if okay, returns an errno value if there was a problem.
14856  */
14857 
14858 int
14859 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14860 {
14861 	char *fn;
14862 	int err = 0;
14863 	servinfo4_t *svp;
14864 	svnode_t *shvp;
14865 
14866 	/*
14867 	 * If the file being opened has VROOT set, then this is
14868 	 * a "file" mount.  sv_name will not be interesting, so
14869 	 * go back to the servinfo4 to get the original mount
14870 	 * path and strip off all but the final edge.  Otherwise
14871 	 * just return the name from the shadow vnode.
14872 	 */
14873 
14874 	if (vp->v_flag & VROOT) {
14875 
14876 		svp = VTOMI4(vp)->mi_curr_serv;
14877 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14878 
14879 		fn = strrchr(svp->sv_path, '/');
14880 		if (fn == NULL)
14881 			err = EINVAL;
14882 		else
14883 			fn++;
14884 	} else {
14885 		shvp = VTOSV(vp);
14886 		fn = fn_name(shvp->sv_name);
14887 	}
14888 
14889 	if (err == 0)
14890 		if (strlen(fn) < maxlen)
14891 			(void) strcpy(fnamep, fn);
14892 		else
14893 			err = ENAMETOOLONG;
14894 
14895 	if (vp->v_flag & VROOT)
14896 		nfs_rw_exit(&svp->sv_lock);
14897 	else
14898 		kmem_free(fn, MAXNAMELEN);
14899 
14900 	return (err);
14901 }
14902 
14903 /*
14904  * Bookkeeping for a close that doesn't need to go over the wire.
14905  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14906  * it is left at 1.
14907  */
14908 void
14909 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14910 {
14911 	rnode4_t		*rp;
14912 	mntinfo4_t		*mi;
14913 
14914 	mi = VTOMI4(vp);
14915 	rp = VTOR4(vp);
14916 
14917 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14918 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14919 	ASSERT(nfs_zone() == mi->mi_zone);
14920 	ASSERT(mutex_owned(&osp->os_sync_lock));
14921 	ASSERT(*have_lockp);
14922 
14923 	if (!osp->os_valid ||
14924 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14925 		return;
14926 	}
14927 
14928 	/*
14929 	 * This removes the reference obtained at OPEN; ie,
14930 	 * when the open stream structure was created.
14931 	 *
14932 	 * We don't have to worry about calling 'open_stream_rele'
14933 	 * since we our currently holding a reference to this
14934 	 * open stream which means the count can not go to 0 with
14935 	 * this decrement.
14936 	 */
14937 	ASSERT(osp->os_ref_count >= 2);
14938 	osp->os_ref_count--;
14939 	osp->os_valid = 0;
14940 	mutex_exit(&osp->os_sync_lock);
14941 	*have_lockp = 0;
14942 
14943 	nfs4_dec_state_ref_count(mi);
14944 }
14945 
14946 /*
14947  * Close all remaining open streams on the rnode.  These open streams
14948  * could be here because:
14949  * - The close attempted at either close or delmap failed
14950  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
14951  * - Someone did mknod on a regular file but never opened it
14952  */
14953 int
14954 nfs4close_all(vnode_t *vp, cred_t *cr)
14955 {
14956 	nfs4_open_stream_t *osp;
14957 	int error;
14958 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
14959 	rnode4_t *rp;
14960 
14961 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14962 
14963 	error = 0;
14964 	rp = VTOR4(vp);
14965 
14966 	/*
14967 	 * At this point, all we know is that the last time
14968 	 * someone called vn_rele, the count was 1.  Since then,
14969 	 * the vnode could have been re-activated.  We want to
14970 	 * loop through the open streams and close each one, but
14971 	 * we have to be careful since once we release the rnode
14972 	 * hash bucket lock, someone else is free to come in and
14973 	 * re-activate the rnode and add new open streams.  The
14974 	 * strategy is take the rnode hash bucket lock, verify that
14975 	 * the count is still 1, grab the open stream off the
14976 	 * head of the list and mark it invalid, then release the
14977 	 * rnode hash bucket lock and proceed with that open stream.
14978 	 * This is ok because nfs4close_one() will acquire the proper
14979 	 * open/create to close/destroy synchronization for open
14980 	 * streams, and will ensure that if someone has reopened
14981 	 * the open stream after we've dropped the hash bucket lock
14982 	 * then we'll just simply return without destroying the
14983 	 * open stream.
14984 	 * Repeat until the list is empty.
14985 	 */
14986 
14987 	for (;;) {
14988 
14989 		/* make sure vnode hasn't been reactivated */
14990 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
14991 		mutex_enter(&vp->v_lock);
14992 		if (vp->v_count > 1) {
14993 			mutex_exit(&vp->v_lock);
14994 			rw_exit(&rp->r_hashq->r_lock);
14995 			break;
14996 		}
14997 		/*
14998 		 * Grabbing r_os_lock before releasing v_lock prevents
14999 		 * a window where the rnode/open stream could get
15000 		 * reactivated (and os_force_close set to 0) before we
15001 		 * had a chance to set os_force_close to 1.
15002 		 */
15003 		mutex_enter(&rp->r_os_lock);
15004 		mutex_exit(&vp->v_lock);
15005 
15006 		osp = list_head(&rp->r_open_streams);
15007 		if (!osp) {
15008 			/* nothing left to CLOSE OTW, so return */
15009 			mutex_exit(&rp->r_os_lock);
15010 			rw_exit(&rp->r_hashq->r_lock);
15011 			break;
15012 		}
15013 
15014 		mutex_enter(&rp->r_statev4_lock);
15015 		/* the file can't still be mem mapped */
15016 		ASSERT(rp->r_mapcnt == 0);
15017 		if (rp->created_v4)
15018 			rp->created_v4 = 0;
15019 		mutex_exit(&rp->r_statev4_lock);
15020 
15021 		/*
15022 		 * Grab a ref on this open stream; nfs4close_one
15023 		 * will mark it as invalid
15024 		 */
15025 		mutex_enter(&osp->os_sync_lock);
15026 		osp->os_ref_count++;
15027 		osp->os_force_close = 1;
15028 		mutex_exit(&osp->os_sync_lock);
15029 		mutex_exit(&rp->r_os_lock);
15030 		rw_exit(&rp->r_hashq->r_lock);
15031 
15032 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
15033 
15034 		/* Update error if it isn't already non-zero */
15035 		if (error == 0) {
15036 			if (e.error)
15037 				error = e.error;
15038 			else if (e.stat)
15039 				error = geterrno4(e.stat);
15040 		}
15041 
15042 #ifdef	DEBUG
15043 		nfs4close_all_cnt++;
15044 #endif
15045 		/* Release the ref on osp acquired above. */
15046 		open_stream_rele(osp, rp);
15047 
15048 		/* Proceed to the next open stream, if any */
15049 	}
15050 	return (error);
15051 }
15052 
15053 /*
15054  * nfs4close_one - close one open stream for a file if needed.
15055  *
15056  * "close_type" indicates which close path this is:
15057  * CLOSE_NORM: close initiated via VOP_CLOSE.
15058  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
15059  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
15060  *	the close and release of client state for this open stream
15061  *	(unless someone else has the open stream open).
15062  * CLOSE_RESEND: indicates the request is a replay of an earlier request
15063  *	(e.g., due to abort because of a signal).
15064  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
15065  *
15066  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
15067  * recovery.  Instead, the caller is expected to deal with retries.
15068  *
15069  * The caller can either pass in the osp ('provided_osp') or not.
15070  *
15071  * 'access_bits' represents the access we are closing/downgrading.
15072  *
15073  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
15074  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
15075  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
15076  *
15077  * Errors are returned via the nfs4_error_t.
15078  */
15079 void
15080 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
15081     int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
15082     nfs4_close_type_t close_type, size_t len, uint_t maxprot,
15083     uint_t mmap_flags)
15084 {
15085 	nfs4_open_owner_t *oop;
15086 	nfs4_open_stream_t *osp = NULL;
15087 	int retry = 0;
15088 	int num_retries = NFS4_NUM_RECOV_RETRIES;
15089 	rnode4_t *rp;
15090 	mntinfo4_t *mi;
15091 	nfs4_recov_state_t recov_state;
15092 	cred_t *cred_otw = NULL;
15093 	bool_t recovonly = FALSE;
15094 	int isrecov;
15095 	int force_close;
15096 	int close_failed = 0;
15097 	int did_dec_count = 0;
15098 	int did_start_op = 0;
15099 	int did_force_recovlock = 0;
15100 	int did_start_seqid_sync = 0;
15101 	int have_sync_lock = 0;
15102 
15103 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15104 
15105 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
15106 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
15107 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
15108 	    len, maxprot, mmap_flags, access_bits));
15109 
15110 	nfs4_error_zinit(ep);
15111 	rp = VTOR4(vp);
15112 	mi = VTOMI4(vp);
15113 	isrecov = (close_type == CLOSE_RESEND ||
15114 	    close_type == CLOSE_AFTER_RESEND);
15115 
15116 	/*
15117 	 * First get the open owner.
15118 	 */
15119 	if (!provided_osp) {
15120 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
15121 	} else {
15122 		oop = provided_osp->os_open_owner;
15123 		ASSERT(oop != NULL);
15124 		open_owner_hold(oop);
15125 	}
15126 
15127 	if (!oop) {
15128 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15129 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15130 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15131 		    (void *)provided_osp, close_type));
15132 		ep->error = EIO;
15133 		goto out;
15134 	}
15135 
15136 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15137 recov_retry:
15138 	osp = NULL;
15139 	close_failed = 0;
15140 	force_close = (close_type == CLOSE_FORCE);
15141 	retry = 0;
15142 	did_start_op = 0;
15143 	did_force_recovlock = 0;
15144 	did_start_seqid_sync = 0;
15145 	have_sync_lock = 0;
15146 	recovonly = FALSE;
15147 	recov_state.rs_flags = 0;
15148 	recov_state.rs_num_retry_despite_err = 0;
15149 
15150 	/*
15151 	 * Second synchronize with recovery.
15152 	 */
15153 	if (!isrecov) {
15154 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15155 		    &recov_state, &recovonly);
15156 		if (!ep->error) {
15157 			did_start_op = 1;
15158 		} else {
15159 			close_failed = 1;
15160 			/*
15161 			 * If we couldn't get start_fop, but have to
15162 			 * cleanup state, then at least acquire the
15163 			 * mi_recovlock so we can synchronize with
15164 			 * recovery.
15165 			 */
15166 			if (close_type == CLOSE_FORCE) {
15167 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15168 				    RW_READER, FALSE);
15169 				did_force_recovlock = 1;
15170 			} else
15171 				goto out;
15172 		}
15173 	}
15174 
15175 	/*
15176 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15177 	 * set 'recovonly' to TRUE since most likely this is due to
15178 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15179 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15180 	 * to retry, causing us to loop until recovery finishes.  Plus we
15181 	 * don't need protection over the open seqid since we're not going
15182 	 * OTW, hence don't need to use the seqid.
15183 	 */
15184 	if (recovonly == FALSE) {
15185 		/* need to grab the open owner sync before 'os_sync_lock' */
15186 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15187 		if (ep->error == EAGAIN) {
15188 			ASSERT(!isrecov);
15189 			if (did_start_op)
15190 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15191 				    &recov_state, TRUE);
15192 			if (did_force_recovlock)
15193 				nfs_rw_exit(&mi->mi_recovlock);
15194 			goto recov_retry;
15195 		}
15196 		did_start_seqid_sync = 1;
15197 	}
15198 
15199 	/*
15200 	 * Third get an open stream and acquire 'os_sync_lock' to
15201 	 * sychronize the opening/creating of an open stream with the
15202 	 * closing/destroying of an open stream.
15203 	 */
15204 	if (!provided_osp) {
15205 		/* returns with 'os_sync_lock' held */
15206 		osp = find_open_stream(oop, rp);
15207 		if (!osp) {
15208 			ep->error = EIO;
15209 			goto out;
15210 		}
15211 	} else {
15212 		osp = provided_osp;
15213 		open_stream_hold(osp);
15214 		mutex_enter(&osp->os_sync_lock);
15215 	}
15216 	have_sync_lock = 1;
15217 
15218 	ASSERT(oop == osp->os_open_owner);
15219 
15220 	/*
15221 	 * Fourth, do any special pre-OTW CLOSE processing
15222 	 * based on the specific close type.
15223 	 */
15224 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15225 	    !did_dec_count) {
15226 		ASSERT(osp->os_open_ref_count > 0);
15227 		osp->os_open_ref_count--;
15228 		did_dec_count = 1;
15229 		if (osp->os_open_ref_count == 0)
15230 			osp->os_final_close = 1;
15231 	}
15232 
15233 	if (close_type == CLOSE_FORCE) {
15234 		/* see if somebody reopened the open stream. */
15235 		if (!osp->os_force_close) {
15236 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15237 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15238 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15239 			ep->error = 0;
15240 			ep->stat = NFS4_OK;
15241 			goto out;
15242 		}
15243 
15244 		if (!osp->os_final_close && !did_dec_count) {
15245 			osp->os_open_ref_count--;
15246 			did_dec_count = 1;
15247 		}
15248 
15249 		/*
15250 		 * We can't depend on os_open_ref_count being 0 due to the
15251 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15252 		 */
15253 #ifdef	NOTYET
15254 		ASSERT(osp->os_open_ref_count == 0);
15255 #endif
15256 		if (osp->os_open_ref_count != 0) {
15257 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15258 			    "nfs4close_one: should panic here on an "
15259 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15260 			    "since this is probably the exec problem."));
15261 
15262 			osp->os_open_ref_count = 0;
15263 		}
15264 
15265 		/*
15266 		 * There is the possibility that nfs4close_one()
15267 		 * for close_type == CLOSE_DELMAP couldn't find the
15268 		 * open stream, thus couldn't decrement its os_mapcnt;
15269 		 * therefore we can't use this ASSERT yet.
15270 		 */
15271 #ifdef	NOTYET
15272 		ASSERT(osp->os_mapcnt == 0);
15273 #endif
15274 		osp->os_mapcnt = 0;
15275 	}
15276 
15277 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15278 		ASSERT(osp->os_mapcnt >= btopr(len));
15279 
15280 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15281 			osp->os_mmap_write -= btopr(len);
15282 		if (maxprot & PROT_READ)
15283 			osp->os_mmap_read -= btopr(len);
15284 		if (maxprot & PROT_EXEC)
15285 			osp->os_mmap_read -= btopr(len);
15286 		/* mirror the PROT_NONE check in nfs4_addmap() */
15287 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15288 		    !(maxprot & PROT_EXEC))
15289 			osp->os_mmap_read -= btopr(len);
15290 		osp->os_mapcnt -= btopr(len);
15291 		did_dec_count = 1;
15292 	}
15293 
15294 	if (recovonly) {
15295 		nfs4_lost_rqst_t lost_rqst;
15296 
15297 		/* request should not already be in recovery queue */
15298 		ASSERT(lrp == NULL);
15299 		nfs4_error_init(ep, EINTR);
15300 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15301 		    osp, cred_otw, vp);
15302 		mutex_exit(&osp->os_sync_lock);
15303 		have_sync_lock = 0;
15304 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15305 		    lost_rqst.lr_op == OP_CLOSE ?
15306 		    &lost_rqst : NULL, OP_CLOSE, NULL);
15307 		close_failed = 1;
15308 		force_close = 0;
15309 		goto close_cleanup;
15310 	}
15311 
15312 	/*
15313 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15314 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15315 	 * space, which means we stopped operating on the open stream
15316 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15317 	 * stateid could be stale, potentially triggering a false
15318 	 * setclientid), and just clean up the client's internal state.
15319 	 */
15320 	if (osp->os_orig_oo_name != oop->oo_name) {
15321 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15322 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15323 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15324 		    "oo_name %" PRIx64")",
15325 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15326 		    oop->oo_name));
15327 		close_failed = 1;
15328 	}
15329 
15330 	/* If the file failed recovery, just quit. */
15331 	mutex_enter(&rp->r_statelock);
15332 	if (rp->r_flags & R4RECOVERR) {
15333 		close_failed = 1;
15334 	}
15335 	mutex_exit(&rp->r_statelock);
15336 
15337 	/*
15338 	 * If the force close path failed to obtain start_fop
15339 	 * then skip the OTW close and just remove the state.
15340 	 */
15341 	if (close_failed)
15342 		goto close_cleanup;
15343 
15344 	/*
15345 	 * Fifth, check to see if there are still mapped pages or other
15346 	 * opens using this open stream.  If there are then we can't
15347 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15348 	 */
15349 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15350 		nfs4_lost_rqst_t	new_lost_rqst;
15351 		bool_t			needrecov = FALSE;
15352 		cred_t			*odg_cred_otw = NULL;
15353 		seqid4			open_dg_seqid = 0;
15354 
15355 		if (osp->os_delegation) {
15356 			/*
15357 			 * If this open stream was never OPENed OTW then we
15358 			 * surely can't DOWNGRADE it (especially since the
15359 			 * osp->open_stateid is really a delegation stateid
15360 			 * when os_delegation is 1).
15361 			 */
15362 			if (access_bits & FREAD)
15363 				osp->os_share_acc_read--;
15364 			if (access_bits & FWRITE)
15365 				osp->os_share_acc_write--;
15366 			osp->os_share_deny_none--;
15367 			nfs4_error_zinit(ep);
15368 			goto out;
15369 		}
15370 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15371 		    lrp, ep, &odg_cred_otw, &open_dg_seqid);
15372 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15373 		if (needrecov && !isrecov) {
15374 			bool_t abort;
15375 			nfs4_bseqid_entry_t *bsep = NULL;
15376 
15377 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15378 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15379 				    vp, 0,
15380 				    lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15381 				    open_dg_seqid);
15382 
15383 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15384 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15385 			mutex_exit(&osp->os_sync_lock);
15386 			have_sync_lock = 0;
15387 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15388 			    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15389 			    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15390 			    bsep);
15391 			if (odg_cred_otw)
15392 				crfree(odg_cred_otw);
15393 			if (bsep)
15394 				kmem_free(bsep, sizeof (*bsep));
15395 
15396 			if (abort == TRUE)
15397 				goto out;
15398 
15399 			if (did_start_seqid_sync) {
15400 				nfs4_end_open_seqid_sync(oop);
15401 				did_start_seqid_sync = 0;
15402 			}
15403 			open_stream_rele(osp, rp);
15404 
15405 			if (did_start_op)
15406 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15407 				    &recov_state, FALSE);
15408 			if (did_force_recovlock)
15409 				nfs_rw_exit(&mi->mi_recovlock);
15410 
15411 			goto recov_retry;
15412 		} else {
15413 			if (odg_cred_otw)
15414 				crfree(odg_cred_otw);
15415 		}
15416 		goto out;
15417 	}
15418 
15419 	/*
15420 	 * If this open stream was created as the results of an open
15421 	 * while holding a delegation, then just release it; no need
15422 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15423 	 */
15424 	if (osp->os_delegation) {
15425 		nfs4close_notw(vp, osp, &have_sync_lock);
15426 		nfs4_error_zinit(ep);
15427 		goto out;
15428 	}
15429 
15430 	/*
15431 	 * If this stream is not valid, we're done.
15432 	 */
15433 	if (!osp->os_valid) {
15434 		nfs4_error_zinit(ep);
15435 		goto out;
15436 	}
15437 
15438 	/*
15439 	 * Last open or mmap ref has vanished, need to do an OTW close.
15440 	 * First check to see if a close is still necessary.
15441 	 */
15442 	if (osp->os_failed_reopen) {
15443 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15444 		    "don't close OTW osp %p since reopen failed.",
15445 		    (void *)osp));
15446 		/*
15447 		 * Reopen of the open stream failed, hence the
15448 		 * stateid of the open stream is invalid/stale, and
15449 		 * sending this OTW would incorrectly cause another
15450 		 * round of recovery.  In this case, we need to set
15451 		 * the 'os_valid' bit to 0 so another thread doesn't
15452 		 * come in and re-open this open stream before
15453 		 * this "closing" thread cleans up state (decrementing
15454 		 * the nfs4_server_t's state_ref_count and decrementing
15455 		 * the os_ref_count).
15456 		 */
15457 		osp->os_valid = 0;
15458 		/*
15459 		 * This removes the reference obtained at OPEN; ie,
15460 		 * when the open stream structure was created.
15461 		 *
15462 		 * We don't have to worry about calling 'open_stream_rele'
15463 		 * since we our currently holding a reference to this
15464 		 * open stream which means the count can not go to 0 with
15465 		 * this decrement.
15466 		 */
15467 		ASSERT(osp->os_ref_count >= 2);
15468 		osp->os_ref_count--;
15469 		nfs4_error_zinit(ep);
15470 		close_failed = 0;
15471 		goto close_cleanup;
15472 	}
15473 
15474 	ASSERT(osp->os_ref_count > 1);
15475 
15476 	/*
15477 	 * Sixth, try the CLOSE OTW.
15478 	 */
15479 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15480 	    close_type, ep, &have_sync_lock);
15481 
15482 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15483 		/*
15484 		 * Let the recovery thread be responsible for
15485 		 * removing the state for CLOSE.
15486 		 */
15487 		close_failed = 1;
15488 		force_close = 0;
15489 		retry = 0;
15490 	}
15491 
15492 	/* See if we need to retry with a different cred */
15493 	if ((ep->error == EACCES ||
15494 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15495 	    cred_otw != cr) {
15496 		crfree(cred_otw);
15497 		cred_otw = cr;
15498 		crhold(cred_otw);
15499 		retry = 1;
15500 	}
15501 
15502 	if (ep->error || ep->stat)
15503 		close_failed = 1;
15504 
15505 	if (retry && !isrecov && num_retries-- > 0) {
15506 		if (have_sync_lock) {
15507 			mutex_exit(&osp->os_sync_lock);
15508 			have_sync_lock = 0;
15509 		}
15510 		if (did_start_seqid_sync) {
15511 			nfs4_end_open_seqid_sync(oop);
15512 			did_start_seqid_sync = 0;
15513 		}
15514 		open_stream_rele(osp, rp);
15515 
15516 		if (did_start_op)
15517 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15518 			    &recov_state, FALSE);
15519 		if (did_force_recovlock)
15520 			nfs_rw_exit(&mi->mi_recovlock);
15521 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15522 		    "nfs4close_one: need to retry the close "
15523 		    "operation"));
15524 		goto recov_retry;
15525 	}
15526 close_cleanup:
15527 	/*
15528 	 * Seventh and lastly, process our results.
15529 	 */
15530 	if (close_failed && force_close) {
15531 		/*
15532 		 * It's ok to drop and regrab the 'os_sync_lock' since
15533 		 * nfs4close_notw() will recheck to make sure the
15534 		 * "close"/removal of state should happen.
15535 		 */
15536 		if (!have_sync_lock) {
15537 			mutex_enter(&osp->os_sync_lock);
15538 			have_sync_lock = 1;
15539 		}
15540 		/*
15541 		 * This is last call, remove the ref on the open
15542 		 * stream created by open and clean everything up.
15543 		 */
15544 		osp->os_pending_close = 0;
15545 		nfs4close_notw(vp, osp, &have_sync_lock);
15546 		nfs4_error_zinit(ep);
15547 	}
15548 
15549 	if (!close_failed) {
15550 		if (have_sync_lock) {
15551 			osp->os_pending_close = 0;
15552 			mutex_exit(&osp->os_sync_lock);
15553 			have_sync_lock = 0;
15554 		} else {
15555 			mutex_enter(&osp->os_sync_lock);
15556 			osp->os_pending_close = 0;
15557 			mutex_exit(&osp->os_sync_lock);
15558 		}
15559 		if (did_start_op && recov_state.rs_sp != NULL) {
15560 			mutex_enter(&recov_state.rs_sp->s_lock);
15561 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15562 			mutex_exit(&recov_state.rs_sp->s_lock);
15563 		} else {
15564 			nfs4_dec_state_ref_count(mi);
15565 		}
15566 		nfs4_error_zinit(ep);
15567 	}
15568 
15569 out:
15570 	if (have_sync_lock)
15571 		mutex_exit(&osp->os_sync_lock);
15572 	if (did_start_op)
15573 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15574 		    recovonly ? TRUE : FALSE);
15575 	if (did_force_recovlock)
15576 		nfs_rw_exit(&mi->mi_recovlock);
15577 	if (cred_otw)
15578 		crfree(cred_otw);
15579 	if (osp)
15580 		open_stream_rele(osp, rp);
15581 	if (oop) {
15582 		if (did_start_seqid_sync)
15583 			nfs4_end_open_seqid_sync(oop);
15584 		open_owner_rele(oop);
15585 	}
15586 }
15587 
15588 /*
15589  * Convert information returned by the server in the LOCK4denied
15590  * structure to the form required by fcntl.
15591  */
15592 static void
15593 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15594 {
15595 	nfs4_lo_name_t *lo;
15596 
15597 #ifdef	DEBUG
15598 	if (denied_to_flk_debug) {
15599 		lockt_denied_debug = lockt_denied;
15600 		debug_enter("lockt_denied");
15601 	}
15602 #endif
15603 
15604 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15605 	flk->l_whence = 0;	/* aka SEEK_SET */
15606 	flk->l_start = lockt_denied->offset;
15607 	flk->l_len = lockt_denied->length;
15608 
15609 	/*
15610 	 * If the blocking clientid matches our client id, then we can
15611 	 * interpret the lockowner (since we built it).  If not, then
15612 	 * fabricate a sysid and pid.  Note that the l_sysid field
15613 	 * in *flk already has the local sysid.
15614 	 */
15615 
15616 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15617 
15618 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15619 			lo = (nfs4_lo_name_t *)
15620 			    lockt_denied->owner.owner_val;
15621 
15622 			flk->l_pid = lo->ln_pid;
15623 		} else {
15624 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15625 			    "denied_to_flk: bad lock owner length\n"));
15626 
15627 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15628 		}
15629 	} else {
15630 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15631 		"denied_to_flk: foreign clientid\n"));
15632 
15633 		/*
15634 		 * Construct a new sysid which should be different from
15635 		 * sysids of other systems.
15636 		 */
15637 
15638 		flk->l_sysid++;
15639 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15640 	}
15641 }
15642 
15643 static pid_t
15644 lo_to_pid(lock_owner4 *lop)
15645 {
15646 	pid_t pid = 0;
15647 	uchar_t *cp;
15648 	int i;
15649 
15650 	cp = (uchar_t *)&lop->clientid;
15651 
15652 	for (i = 0; i < sizeof (lop->clientid); i++)
15653 		pid += (pid_t)*cp++;
15654 
15655 	cp = (uchar_t *)lop->owner_val;
15656 
15657 	for (i = 0; i < lop->owner_len; i++)
15658 		pid += (pid_t)*cp++;
15659 
15660 	return (pid);
15661 }
15662 
15663 /*
15664  * Given a lock pointer, returns the length of that lock.
15665  * "end" is the last locked offset the "l_len" covers from
15666  * the start of the lock.
15667  */
15668 static off64_t
15669 lock_to_end(flock64_t *lock)
15670 {
15671 	off64_t lock_end;
15672 
15673 	if (lock->l_len == 0)
15674 		lock_end = (off64_t)MAXEND;
15675 	else
15676 		lock_end = lock->l_start + lock->l_len - 1;
15677 
15678 	return (lock_end);
15679 }
15680 
15681 /*
15682  * Given the end of a lock, it will return you the length "l_len" for that lock.
15683  */
15684 static off64_t
15685 end_to_len(off64_t start, off64_t end)
15686 {
15687 	off64_t lock_len;
15688 
15689 	ASSERT(end >= start);
15690 	if (end == MAXEND)
15691 		lock_len = 0;
15692 	else
15693 		lock_len = end - start + 1;
15694 
15695 	return (lock_len);
15696 }
15697 
15698 /*
15699  * On given end for a lock it determines if it is the last locked offset
15700  * or not, if so keeps it as is, else adds one to return the length for
15701  * valid start.
15702  */
15703 static off64_t
15704 start_check(off64_t x)
15705 {
15706 	if (x == MAXEND)
15707 		return (x);
15708 	else
15709 		return (x + 1);
15710 }
15711 
15712 /*
15713  * See if these two locks overlap, and if so return 1;
15714  * otherwise, return 0.
15715  */
15716 static int
15717 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15718 {
15719 	off64_t llfp_end, curfp_end;
15720 
15721 	llfp_end = lock_to_end(llfp);
15722 	curfp_end = lock_to_end(curfp);
15723 
15724 	if (((llfp_end >= curfp->l_start) &&
15725 	    (llfp->l_start <= curfp->l_start)) ||
15726 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15727 		return (1);
15728 	return (0);
15729 }
15730 
15731 /*
15732  * Determine what the intersecting lock region is, and add that to the
15733  * 'nl_llpp' locklist in increasing order (by l_start).
15734  */
15735 static void
15736 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15737     locklist_t **nl_llpp, vnode_t *vp)
15738 {
15739 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15740 	off64_t lost_flp_end, local_flp_end, len, start;
15741 
15742 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15743 
15744 	if (!locks_intersect(lost_flp, local_flp))
15745 		return;
15746 
15747 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15748 	    "locks intersect"));
15749 
15750 	lost_flp_end = lock_to_end(lost_flp);
15751 	local_flp_end = lock_to_end(local_flp);
15752 
15753 	/* Find the starting point of the intersecting region */
15754 	if (local_flp->l_start > lost_flp->l_start)
15755 		start = local_flp->l_start;
15756 	else
15757 		start = lost_flp->l_start;
15758 
15759 	/* Find the lenght of the intersecting region */
15760 	if (lost_flp_end < local_flp_end)
15761 		len = end_to_len(start, lost_flp_end);
15762 	else
15763 		len = end_to_len(start, local_flp_end);
15764 
15765 	/*
15766 	 * Prepare the flock structure for the intersection found and insert
15767 	 * it into the new list in increasing l_start order. This list contains
15768 	 * intersections of locks registered by the client with the local host
15769 	 * and the lost lock.
15770 	 * The lock type of this lock is the same as that of the local_flp.
15771 	 */
15772 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15773 	intersect_llp->ll_flock.l_start = start;
15774 	intersect_llp->ll_flock.l_len = len;
15775 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15776 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15777 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15778 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15779 	intersect_llp->ll_vp = vp;
15780 
15781 	tmp_fllp = *nl_llpp;
15782 	cur_fllp = NULL;
15783 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15784 	    intersect_llp->ll_flock.l_start) {
15785 			cur_fllp = tmp_fllp;
15786 			tmp_fllp = tmp_fllp->ll_next;
15787 	}
15788 	if (cur_fllp == NULL) {
15789 		/* first on the list */
15790 		intersect_llp->ll_next = *nl_llpp;
15791 		*nl_llpp = intersect_llp;
15792 	} else {
15793 		intersect_llp->ll_next = cur_fllp->ll_next;
15794 		cur_fllp->ll_next = intersect_llp;
15795 	}
15796 
15797 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15798 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15799 	    intersect_llp->ll_flock.l_start,
15800 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15801 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15802 }
15803 
15804 /*
15805  * Our local locking current state is potentially different than
15806  * what the NFSv4 server thinks we have due to a lost lock that was
15807  * resent and then received.  We need to reset our "NFSv4" locking
15808  * state to match the current local locking state for this pid since
15809  * that is what the user/application sees as what the world is.
15810  *
15811  * We cannot afford to drop the open/lock seqid sync since then we can
15812  * get confused about what the current local locking state "is" versus
15813  * "was".
15814  *
15815  * If we are unable to fix up the locks, we send SIGLOST to the affected
15816  * process.  This is not done if the filesystem has been forcibly
15817  * unmounted, in case the process has already exited and a new process
15818  * exists with the same pid.
15819  */
15820 static void
15821 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15822     nfs4_lock_owner_t *lop)
15823 {
15824 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15825 	mntinfo4_t *mi = VTOMI4(vp);
15826 	const int cmd = F_SETLK;
15827 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15828 	flock64_t ul_fl;
15829 
15830 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15831 	    "nfs4_reinstitute_local_lock_state"));
15832 
15833 	/*
15834 	 * Find active locks for this vp from the local locking code.
15835 	 * Scan through this list and find out the locks that intersect with
15836 	 * the lost lock. Once we find the lock that intersects, add the
15837 	 * intersection area as a new lock to a new list "ri_llp". The lock
15838 	 * type of the intersection region lock added to ri_llp is the same
15839 	 * as that found in the active lock list, "list". The intersecting
15840 	 * region locks are added to ri_llp in increasing l_start order.
15841 	 */
15842 	ASSERT(nfs_zone() == mi->mi_zone);
15843 
15844 	locks = flk_active_locks_for_vp(vp);
15845 	ri_llp = NULL;
15846 
15847 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15848 		ASSERT(llp->ll_vp == vp);
15849 		/*
15850 		 * Pick locks that belong to this pid/lockowner
15851 		 */
15852 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15853 			continue;
15854 
15855 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15856 	}
15857 
15858 	/*
15859 	 * Now we have the list of intersections with the lost lock. These are
15860 	 * the locks that were/are active before the server replied to the
15861 	 * last/lost lock. Issue these locks to the server here. Playing these
15862 	 * locks to the server will re-establish aur current local locking state
15863 	 * with the v4 server.
15864 	 * If we get an error, send SIGLOST to the application for that lock.
15865 	 */
15866 
15867 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15868 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15869 		    "nfs4_reinstitute_local_lock_state: need to issue "
15870 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15871 		    llp->ll_flock.l_start,
15872 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15873 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15874 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15875 		/*
15876 		 * No need to relock what we already have
15877 		 */
15878 		if (llp->ll_flock.l_type == lost_flp->l_type)
15879 			continue;
15880 
15881 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15882 	}
15883 
15884 	/*
15885 	 * Now keeping the start of the lost lock as our reference parse the
15886 	 * newly created ri_llp locklist to find the ranges that we have locked
15887 	 * with the v4 server but not in the current local locking. We need
15888 	 * to unlock these ranges.
15889 	 * These ranges can also be reffered to as those ranges, where the lost
15890 	 * lock does not overlap with the locks in the ri_llp but are locked
15891 	 * since the server replied to the lost lock.
15892 	 */
15893 	cur_start = lost_flp->l_start;
15894 	lost_flp_end = lock_to_end(lost_flp);
15895 
15896 	ul_fl.l_type = F_UNLCK;
15897 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15898 	ul_fl.l_sysid = lost_flp->l_sysid;
15899 	ul_fl.l_pid = lost_flp->l_pid;
15900 
15901 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15902 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15903 
15904 		if (llp->ll_flock.l_start <= cur_start) {
15905 			cur_start = start_check(llp_ll_flock_end);
15906 			continue;
15907 		}
15908 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15909 		    "nfs4_reinstitute_local_lock_state: "
15910 		    "UNLOCK [%"PRIx64" - %"PRIx64"]",
15911 		    cur_start, llp->ll_flock.l_start));
15912 
15913 		ul_fl.l_start = cur_start;
15914 		ul_fl.l_len = end_to_len(cur_start,
15915 		    (llp->ll_flock.l_start - 1));
15916 
15917 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15918 		cur_start = start_check(llp_ll_flock_end);
15919 	}
15920 
15921 	/*
15922 	 * In the case where the lost lock ends after all intersecting locks,
15923 	 * unlock the last part of the lost lock range.
15924 	 */
15925 	if (cur_start != start_check(lost_flp_end)) {
15926 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15927 		    "nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15928 		    "lost lock region [%"PRIx64" - %"PRIx64"]",
15929 		    cur_start, lost_flp->l_start + lost_flp->l_len));
15930 
15931 		ul_fl.l_start = cur_start;
15932 		/*
15933 		 * Is it an to-EOF lock? if so unlock till the end
15934 		 */
15935 		if (lost_flp->l_len == 0)
15936 			ul_fl.l_len = 0;
15937 		else
15938 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15939 
15940 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15941 	}
15942 
15943 	if (locks != NULL)
15944 		flk_free_locklist(locks);
15945 
15946 	/* Free up our newly created locklist */
15947 	for (llp = ri_llp; llp != NULL; ) {
15948 		tmp_llp = llp->ll_next;
15949 		kmem_free(llp, sizeof (locklist_t));
15950 		llp = tmp_llp;
15951 	}
15952 
15953 	/*
15954 	 * Now return back to the original calling nfs4frlock()
15955 	 * and let us naturally drop our seqid syncs.
15956 	 */
15957 }
15958 
15959 /*
15960  * Create a lost state record for the given lock reinstantiation request
15961  * and push it onto the lost state queue.
15962  */
15963 static void
15964 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
15965     nfs4_lock_owner_t *lop)
15966 {
15967 	nfs4_lost_rqst_t req;
15968 	nfs_lock_type4 locktype;
15969 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
15970 
15971 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15972 
15973 	locktype = flk_to_locktype(cmd, flk->l_type);
15974 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
15975 	    NULL, NULL, lop, flk, &req, cr, vp);
15976 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
15977 	    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
15978 	    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
15979 	    NULL);
15980 }
15981