xref: /titanic_41/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision 728f047ccdb8a96a1aecc448cb87706241a08c94)
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 2008 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 
66 #include <rpc/types.h>
67 #include <rpc/auth.h>
68 #include <rpc/clnt.h>
69 
70 #include <nfs/nfs.h>
71 #include <nfs/nfs_clnt.h>
72 #include <nfs/nfs_acl.h>
73 #include <nfs/lm.h>
74 #include <nfs/nfs4.h>
75 #include <nfs/nfs4_kprot.h>
76 #include <nfs/rnode4.h>
77 #include <nfs/nfs4_clnt.h>
78 
79 #include <vm/hat.h>
80 #include <vm/as.h>
81 #include <vm/page.h>
82 #include <vm/pvn.h>
83 #include <vm/seg.h>
84 #include <vm/seg_map.h>
85 #include <vm/seg_kpm.h>
86 #include <vm/seg_vn.h>
87 
88 #include <fs/fs_subr.h>
89 
90 #include <sys/ddi.h>
91 #include <sys/int_fmtio.h>
92 
93 typedef struct {
94 	nfs4_ga_res_t	*di_garp;
95 	cred_t		*di_cred;
96 	hrtime_t	di_time_call;
97 } dirattr_info_t;
98 
99 typedef enum nfs4_acl_op {
100 	NFS4_ACL_GET,
101 	NFS4_ACL_SET
102 } nfs4_acl_op_t;
103 
104 static struct lm_sysid *nfs4_find_sysid(mntinfo4_t *mi);
105 
106 static void	nfs4_update_dircaches(change_info4 *, vnode_t *, vnode_t *,
107 			char *, dirattr_info_t *);
108 
109 static void	nfs4close_otw(rnode4_t *, cred_t *, nfs4_open_owner_t *,
110 		    nfs4_open_stream_t *, int *, int *, nfs4_close_type_t,
111 		    nfs4_error_t *, int *);
112 static int	nfs4_rdwrlbn(vnode_t *, page_t *, u_offset_t, size_t, int,
113 			cred_t *);
114 static int	nfs4write(vnode_t *, caddr_t, u_offset_t, int, cred_t *,
115 			stable_how4 *);
116 static int	nfs4read(vnode_t *, caddr_t, offset_t, int, size_t *,
117 			cred_t *, bool_t, struct uio *);
118 static int	nfs4setattr(vnode_t *, struct vattr *, int, cred_t *,
119 			vsecattr_t *);
120 static int	nfs4openattr(vnode_t *, vnode_t **, int, cred_t *);
121 static int	nfs4lookup(vnode_t *, char *, vnode_t **, cred_t *, int);
122 static int	nfs4lookup_xattr(vnode_t *, char *, vnode_t **, int, cred_t *);
123 static int	nfs4lookupvalidate_otw(vnode_t *, char *, vnode_t **, cred_t *);
124 static int	nfs4lookupnew_otw(vnode_t *, char *, vnode_t **, cred_t *);
125 static int	nfs4mknod(vnode_t *, char *, struct vattr *, enum vcexcl,
126 			int, vnode_t **, cred_t *);
127 static int	nfs4open_otw(vnode_t *, char *, struct vattr *, vnode_t **,
128 			cred_t *, int, int, enum createmode4, int);
129 static int	nfs4rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
130 			caller_context_t *);
131 static int	nfs4rename_persistent_fh(vnode_t *, char *, vnode_t *,
132 			vnode_t *, char *, cred_t *, nfsstat4 *);
133 static int	nfs4rename_volatile_fh(vnode_t *, char *, vnode_t *,
134 			vnode_t *, char *, cred_t *, nfsstat4 *);
135 static int	do_nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
136 static void	nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
137 static int	nfs4_bio(struct buf *, stable_how4 *, cred_t *, bool_t);
138 static int	nfs4_getapage(vnode_t *, u_offset_t, size_t, uint_t *,
139 			page_t *[], size_t, struct seg *, caddr_t,
140 			enum seg_rw, cred_t *);
141 static void	nfs4_readahead(vnode_t *, u_offset_t, caddr_t, struct seg *,
142 			cred_t *);
143 static int	nfs4_sync_putapage(vnode_t *, page_t *, u_offset_t, size_t,
144 			int, cred_t *);
145 static int	nfs4_sync_pageio(vnode_t *, page_t *, u_offset_t, size_t,
146 			int, cred_t *);
147 static int	nfs4_commit(vnode_t *, offset4, count4, cred_t *);
148 static void	nfs4_set_mod(vnode_t *);
149 static void	nfs4_get_commit(vnode_t *);
150 static void	nfs4_get_commit_range(vnode_t *, u_offset_t, size_t);
151 static int	nfs4_putpage_commit(vnode_t *, offset_t, size_t, cred_t *);
152 static int	nfs4_commit_vp(vnode_t *, u_offset_t, size_t, cred_t *, int);
153 static int	nfs4_sync_commit(vnode_t *, page_t *, offset3, count3,
154 			cred_t *);
155 static void	do_nfs4_async_commit(vnode_t *, page_t *, offset3, count3,
156 			cred_t *);
157 static int	nfs4_update_attrcache(nfsstat4, nfs4_ga_res_t *,
158 			hrtime_t, vnode_t *, cred_t *);
159 static int	nfs4_open_non_reg_file(vnode_t **, int, cred_t *);
160 static int	nfs4_safelock(vnode_t *, const struct flock64 *, cred_t *);
161 static void	nfs4_register_lock_locally(vnode_t *, struct flock64 *, int,
162 			u_offset_t);
163 static int 	nfs4_lockrelease(vnode_t *, int, offset_t, cred_t *);
164 static int	nfs4_block_and_wait(clock_t *, rnode4_t *);
165 static cred_t  *state_to_cred(nfs4_open_stream_t *);
166 static int	vtoname(vnode_t *, char *, ssize_t);
167 static void	denied_to_flk(LOCK4denied *, flock64_t *, LOCKT4args *);
168 static pid_t	lo_to_pid(lock_owner4 *);
169 static void	nfs4_reinstitute_local_lock_state(vnode_t *, flock64_t *,
170 			cred_t *, nfs4_lock_owner_t *);
171 static void	push_reinstate(vnode_t *, int, flock64_t *, cred_t *,
172 			nfs4_lock_owner_t *);
173 static int 	open_and_get_osp(vnode_t *, cred_t *, nfs4_open_stream_t **);
174 static void	nfs4_delmap_callback(struct as *, void *, uint_t);
175 static void	nfs4_free_delmapcall(nfs4_delmapcall_t *);
176 static nfs4_delmapcall_t	*nfs4_init_delmapcall();
177 static int	nfs4_find_and_delete_delmapcall(rnode4_t *, int *);
178 static int	nfs4_is_acl_mask_valid(uint_t, nfs4_acl_op_t);
179 static int	nfs4_create_getsecattr_return(vsecattr_t *, vsecattr_t *,
180 			uid_t, gid_t, int);
181 
182 /*
183  * Routines that implement the setting of v4 args for the misc. ops
184  */
185 static void	nfs4args_lock_free(nfs_argop4 *);
186 static void	nfs4args_lockt_free(nfs_argop4 *);
187 static void	nfs4args_setattr(nfs_argop4 *, vattr_t *, vsecattr_t *,
188 			int, rnode4_t *, cred_t *, bitmap4, int *,
189 			nfs4_stateid_types_t *);
190 static void	nfs4args_setattr_free(nfs_argop4 *);
191 static int	nfs4args_verify(nfs_argop4 *, vattr_t *, enum nfs_opnum4,
192 			bitmap4);
193 static void	nfs4args_verify_free(nfs_argop4 *);
194 static void	nfs4args_write(nfs_argop4 *, stable_how4, rnode4_t *, cred_t *,
195 			WRITE4args **, nfs4_stateid_types_t *);
196 
197 /*
198  * These are the vnode ops functions that implement the vnode interface to
199  * the networked file system.  See more comments below at nfs4_vnodeops.
200  */
201 static int	nfs4_open(vnode_t **, int, cred_t *, caller_context_t *);
202 static int	nfs4_close(vnode_t *, int, int, offset_t, cred_t *,
203 			caller_context_t *);
204 static int	nfs4_read(vnode_t *, struct uio *, int, cred_t *,
205 			caller_context_t *);
206 static int	nfs4_write(vnode_t *, struct uio *, int, cred_t *,
207 			caller_context_t *);
208 static int	nfs4_ioctl(vnode_t *, int, intptr_t, int, cred_t *, int *,
209 			caller_context_t *);
210 static int	nfs4_setattr(vnode_t *, struct vattr *, int, cred_t *,
211 			caller_context_t *);
212 static int	nfs4_access(vnode_t *, int, int, cred_t *, caller_context_t *);
213 static int	nfs4_readlink(vnode_t *, struct uio *, cred_t *,
214 			caller_context_t *);
215 static int	nfs4_fsync(vnode_t *, int, cred_t *, caller_context_t *);
216 static int	nfs4_create(vnode_t *, char *, struct vattr *, enum vcexcl,
217 			int, vnode_t **, cred_t *, int, caller_context_t *,
218 			vsecattr_t *);
219 static int	nfs4_remove(vnode_t *, char *, cred_t *, caller_context_t *,
220 			int);
221 static int	nfs4_link(vnode_t *, vnode_t *, char *, cred_t *,
222 			caller_context_t *, int);
223 static int	nfs4_rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
224 			caller_context_t *, int);
225 static int	nfs4_mkdir(vnode_t *, char *, struct vattr *, vnode_t **,
226 			cred_t *, caller_context_t *, int, vsecattr_t *);
227 static int	nfs4_rmdir(vnode_t *, char *, vnode_t *, cred_t *,
228 			caller_context_t *, int);
229 static int	nfs4_symlink(vnode_t *, char *, struct vattr *, char *,
230 			cred_t *, caller_context_t *, int);
231 static int	nfs4_readdir(vnode_t *, struct uio *, cred_t *, int *,
232 			caller_context_t *, int);
233 static int	nfs4_seek(vnode_t *, offset_t, offset_t *, caller_context_t *);
234 static int	nfs4_getpage(vnode_t *, offset_t, size_t, uint_t *,
235 			page_t *[], size_t, struct seg *, caddr_t,
236 			enum seg_rw, cred_t *, caller_context_t *);
237 static int	nfs4_putpage(vnode_t *, offset_t, size_t, int, cred_t *,
238 			caller_context_t *);
239 static int	nfs4_map(vnode_t *, offset_t, struct as *, caddr_t *, size_t,
240 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
241 static int	nfs4_addmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
242 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
243 static int	nfs4_cmp(vnode_t *, vnode_t *, caller_context_t *);
244 static int	nfs4_frlock(vnode_t *, int, struct flock64 *, int, offset_t,
245 			struct flk_callback *, cred_t *, caller_context_t *);
246 static int	nfs4_space(vnode_t *, int, struct flock64 *, int, offset_t,
247 			cred_t *, caller_context_t *);
248 static int	nfs4_delmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
249 			uint_t, uint_t, uint_t, cred_t *, caller_context_t *);
250 static int	nfs4_pageio(vnode_t *, page_t *, u_offset_t, size_t, int,
251 			cred_t *, caller_context_t *);
252 static void	nfs4_dispose(vnode_t *, page_t *, int, int, cred_t *,
253 			caller_context_t *);
254 static int	nfs4_setsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
255 			caller_context_t *);
256 /*
257  * These vnode ops are required to be called from outside this source file,
258  * e.g. by ephemeral mount stub vnode ops, and so may not be declared
259  * as static.
260  */
261 int	nfs4_getattr(vnode_t *, struct vattr *, int, cred_t *,
262 	    caller_context_t *);
263 void	nfs4_inactive(vnode_t *, cred_t *, caller_context_t *);
264 int	nfs4_lookup(vnode_t *, char *, vnode_t **,
265 	    struct pathname *, int, vnode_t *, cred_t *,
266 	    caller_context_t *, int *, pathname_t *);
267 int	nfs4_fid(vnode_t *, fid_t *, caller_context_t *);
268 int	nfs4_rwlock(vnode_t *, int, caller_context_t *);
269 void	nfs4_rwunlock(vnode_t *, int, caller_context_t *);
270 int	nfs4_realvp(vnode_t *, vnode_t **, caller_context_t *);
271 int	nfs4_pathconf(vnode_t *, int, ulong_t *, cred_t *,
272 	    caller_context_t *);
273 int	nfs4_getsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
274 	    caller_context_t *);
275 int	nfs4_shrlock(vnode_t *, int, struct shrlock *, int, cred_t *,
276 	    caller_context_t *);
277 
278 /*
279  * Used for nfs4_commit_vp() to indicate if we should
280  * wait on pending writes.
281  */
282 #define	NFS4_WRITE_NOWAIT	0
283 #define	NFS4_WRITE_WAIT		1
284 
285 #define	NFS4_BASE_WAIT_TIME 1	/* 1 second */
286 
287 /*
288  * Error flags used to pass information about certain special errors
289  * which need to be handled specially.
290  */
291 #define	NFS_EOF			-98
292 #define	NFS_VERF_MISMATCH	-97
293 
294 /*
295  * Flags used to differentiate between which operation drove the
296  * potential CLOSE OTW. (see nfs4_close_otw_if_necessary)
297  */
298 #define	NFS4_CLOSE_OP		0x1
299 #define	NFS4_DELMAP_OP		0x2
300 #define	NFS4_INACTIVE_OP	0x3
301 
302 #define	ISVDEV(t) ((t == VBLK) || (t == VCHR) || (t == VFIFO))
303 
304 /* ALIGN64 aligns the given buffer and adjust buffer size to 64 bit */
305 #define	ALIGN64(x, ptr, sz)						\
306 	x = ((uintptr_t)(ptr)) & (sizeof (uint64_t) - 1);		\
307 	if (x) {							\
308 		x = sizeof (uint64_t) - (x);				\
309 		sz -= (x);						\
310 		ptr += (x);						\
311 	}
312 
313 #ifdef DEBUG
314 int nfs4_client_attr_debug = 0;
315 int nfs4_client_state_debug = 0;
316 int nfs4_client_shadow_debug = 0;
317 int nfs4_client_lock_debug = 0;
318 int nfs4_seqid_sync = 0;
319 int nfs4_client_map_debug = 0;
320 static int nfs4_pageio_debug = 0;
321 int nfs4_client_inactive_debug = 0;
322 int nfs4_client_recov_debug = 0;
323 int nfs4_client_failover_debug = 0;
324 int nfs4_client_call_debug = 0;
325 int nfs4_client_lookup_debug = 0;
326 int nfs4_client_zone_debug = 0;
327 int nfs4_lost_rqst_debug = 0;
328 int nfs4_rdattrerr_debug = 0;
329 int nfs4_open_stream_debug = 0;
330 
331 int nfs4read_error_inject;
332 
333 static int nfs4_create_misses = 0;
334 
335 static int nfs4_readdir_cache_shorts = 0;
336 static int nfs4_readdir_readahead = 0;
337 
338 static int nfs4_bio_do_stop = 0;
339 
340 static int nfs4_lostpage = 0;	/* number of times we lost original page */
341 
342 int nfs4_mmap_debug = 0;
343 
344 static int nfs4_pathconf_cache_hits = 0;
345 static int nfs4_pathconf_cache_misses = 0;
346 
347 int nfs4close_all_cnt;
348 int nfs4close_one_debug = 0;
349 int nfs4close_notw_debug = 0;
350 
351 int denied_to_flk_debug = 0;
352 void *lockt_denied_debug;
353 
354 #endif
355 
356 /*
357  * How long to wait before trying again if OPEN_CONFIRM gets ETIMEDOUT
358  * or NFS4ERR_RESOURCE.
359  */
360 static int confirm_retry_sec = 30;
361 
362 static int nfs4_lookup_neg_cache = 1;
363 
364 /*
365  * number of pages to read ahead
366  * optimized for 100 base-T.
367  */
368 static int nfs4_nra = 4;
369 
370 static int nfs4_do_symlink_cache = 1;
371 
372 static int nfs4_pathconf_disable_cache = 0;
373 
374 /*
375  * These are the vnode ops routines which implement the vnode interface to
376  * the networked file system.  These routines just take their parameters,
377  * make them look networkish by putting the right info into interface structs,
378  * and then calling the appropriate remote routine(s) to do the work.
379  *
380  * Note on directory name lookup cacheing:  If we detect a stale fhandle,
381  * we purge the directory cache relative to that vnode.  This way, the
382  * user won't get burned by the cache repeatedly.  See <nfs/rnode4.h> for
383  * more details on rnode locking.
384  */
385 
386 struct vnodeops *nfs4_vnodeops;
387 
388 const fs_operation_def_t nfs4_vnodeops_template[] = {
389 	VOPNAME_OPEN,		{ .vop_open = nfs4_open },
390 	VOPNAME_CLOSE,		{ .vop_close = nfs4_close },
391 	VOPNAME_READ,		{ .vop_read = nfs4_read },
392 	VOPNAME_WRITE,		{ .vop_write = nfs4_write },
393 	VOPNAME_IOCTL,		{ .vop_ioctl = nfs4_ioctl },
394 	VOPNAME_GETATTR,	{ .vop_getattr = nfs4_getattr },
395 	VOPNAME_SETATTR,	{ .vop_setattr = nfs4_setattr },
396 	VOPNAME_ACCESS,		{ .vop_access = nfs4_access },
397 	VOPNAME_LOOKUP,		{ .vop_lookup = nfs4_lookup },
398 	VOPNAME_CREATE,		{ .vop_create = nfs4_create },
399 	VOPNAME_REMOVE,		{ .vop_remove = nfs4_remove },
400 	VOPNAME_LINK,		{ .vop_link = nfs4_link },
401 	VOPNAME_RENAME,		{ .vop_rename = nfs4_rename },
402 	VOPNAME_MKDIR,		{ .vop_mkdir = nfs4_mkdir },
403 	VOPNAME_RMDIR,		{ .vop_rmdir = nfs4_rmdir },
404 	VOPNAME_READDIR,	{ .vop_readdir = nfs4_readdir },
405 	VOPNAME_SYMLINK,	{ .vop_symlink = nfs4_symlink },
406 	VOPNAME_READLINK,	{ .vop_readlink = nfs4_readlink },
407 	VOPNAME_FSYNC,		{ .vop_fsync = nfs4_fsync },
408 	VOPNAME_INACTIVE,	{ .vop_inactive = nfs4_inactive },
409 	VOPNAME_FID,		{ .vop_fid = nfs4_fid },
410 	VOPNAME_RWLOCK,		{ .vop_rwlock = nfs4_rwlock },
411 	VOPNAME_RWUNLOCK,	{ .vop_rwunlock = nfs4_rwunlock },
412 	VOPNAME_SEEK,		{ .vop_seek = nfs4_seek },
413 	VOPNAME_FRLOCK,		{ .vop_frlock = nfs4_frlock },
414 	VOPNAME_SPACE,		{ .vop_space = nfs4_space },
415 	VOPNAME_REALVP,		{ .vop_realvp = nfs4_realvp },
416 	VOPNAME_GETPAGE,	{ .vop_getpage = nfs4_getpage },
417 	VOPNAME_PUTPAGE,	{ .vop_putpage = nfs4_putpage },
418 	VOPNAME_MAP,		{ .vop_map = nfs4_map },
419 	VOPNAME_ADDMAP,		{ .vop_addmap = nfs4_addmap },
420 	VOPNAME_DELMAP,		{ .vop_delmap = nfs4_delmap },
421 	/* no separate nfs4_dump */
422 	VOPNAME_DUMP,		{ .vop_dump = nfs_dump },
423 	VOPNAME_PATHCONF,	{ .vop_pathconf = nfs4_pathconf },
424 	VOPNAME_PAGEIO,		{ .vop_pageio = nfs4_pageio },
425 	VOPNAME_DISPOSE,	{ .vop_dispose = nfs4_dispose },
426 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = nfs4_setsecattr },
427 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = nfs4_getsecattr },
428 	VOPNAME_SHRLOCK,	{ .vop_shrlock = nfs4_shrlock },
429 	VOPNAME_VNEVENT, 	{ .vop_vnevent = fs_vnevent_support },
430 	NULL,			NULL
431 };
432 
433 /*
434  * The following are subroutines and definitions to set args or get res
435  * for the different nfsv4 ops
436  */
437 
438 void
439 nfs4args_lookup_free(nfs_argop4 *argop, int arglen)
440 {
441 	int		i;
442 
443 	for (i = 0; i < arglen; i++) {
444 		if (argop[i].argop == OP_LOOKUP) {
445 			kmem_free(
446 			    argop[i].nfs_argop4_u.oplookup.
447 			    objname.utf8string_val,
448 			    argop[i].nfs_argop4_u.oplookup.
449 			    objname.utf8string_len);
450 		}
451 	}
452 }
453 
454 static void
455 nfs4args_lock_free(nfs_argop4 *argop)
456 {
457 	locker4 *locker = &argop->nfs_argop4_u.oplock.locker;
458 
459 	if (locker->new_lock_owner == TRUE) {
460 		open_to_lock_owner4 *open_owner;
461 
462 		open_owner = &locker->locker4_u.open_owner;
463 		if (open_owner->lock_owner.owner_val != NULL) {
464 			kmem_free(open_owner->lock_owner.owner_val,
465 			    open_owner->lock_owner.owner_len);
466 		}
467 	}
468 }
469 
470 static void
471 nfs4args_lockt_free(nfs_argop4 *argop)
472 {
473 	lock_owner4 *lowner = &argop->nfs_argop4_u.oplockt.owner;
474 
475 	if (lowner->owner_val != NULL) {
476 		kmem_free(lowner->owner_val, lowner->owner_len);
477 	}
478 }
479 
480 static void
481 nfs4args_setattr(nfs_argop4 *argop, vattr_t *vap, vsecattr_t *vsap, int flags,
482     rnode4_t *rp, cred_t *cr, bitmap4 supp, int *error,
483     nfs4_stateid_types_t *sid_types)
484 {
485 	fattr4		*attr = &argop->nfs_argop4_u.opsetattr.obj_attributes;
486 	mntinfo4_t	*mi;
487 
488 	argop->argop = OP_SETATTR;
489 	/*
490 	 * The stateid is set to 0 if client is not modifying the size
491 	 * and otherwise to whatever nfs4_get_stateid() returns.
492 	 *
493 	 * XXX Note: nfs4_get_stateid() returns 0 if no lockowner and/or no
494 	 * state struct could be found for the process/file pair.  We may
495 	 * want to change this in the future (by OPENing the file).  See
496 	 * bug # 4474852.
497 	 */
498 	if (vap->va_mask & AT_SIZE) {
499 
500 		ASSERT(rp != NULL);
501 		mi = VTOMI4(RTOV4(rp));
502 
503 		argop->nfs_argop4_u.opsetattr.stateid =
504 		    nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
505 		    OP_SETATTR, sid_types, FALSE);
506 	} else {
507 		bzero(&argop->nfs_argop4_u.opsetattr.stateid,
508 		    sizeof (stateid4));
509 	}
510 
511 	*error = vattr_to_fattr4(vap, vsap, attr, flags, OP_SETATTR, supp);
512 	if (*error)
513 		bzero(attr, sizeof (*attr));
514 }
515 
516 static void
517 nfs4args_setattr_free(nfs_argop4 *argop)
518 {
519 	nfs4_fattr4_free(&argop->nfs_argop4_u.opsetattr.obj_attributes);
520 }
521 
522 static int
523 nfs4args_verify(nfs_argop4 *argop, vattr_t *vap, enum nfs_opnum4 op,
524     bitmap4 supp)
525 {
526 	fattr4 *attr;
527 	int error = 0;
528 
529 	argop->argop = op;
530 	switch (op) {
531 	case OP_VERIFY:
532 		attr = &argop->nfs_argop4_u.opverify.obj_attributes;
533 		break;
534 	case OP_NVERIFY:
535 		attr = &argop->nfs_argop4_u.opnverify.obj_attributes;
536 		break;
537 	default:
538 		return (EINVAL);
539 	}
540 	if (!error)
541 		error = vattr_to_fattr4(vap, NULL, attr, 0, op, supp);
542 	if (error)
543 		bzero(attr, sizeof (*attr));
544 	return (error);
545 }
546 
547 static void
548 nfs4args_verify_free(nfs_argop4 *argop)
549 {
550 	switch (argop->argop) {
551 	case OP_VERIFY:
552 		nfs4_fattr4_free(&argop->nfs_argop4_u.opverify.obj_attributes);
553 		break;
554 	case OP_NVERIFY:
555 		nfs4_fattr4_free(&argop->nfs_argop4_u.opnverify.obj_attributes);
556 		break;
557 	default:
558 		break;
559 	}
560 }
561 
562 static void
563 nfs4args_write(nfs_argop4 *argop, stable_how4 stable, rnode4_t *rp, cred_t *cr,
564     WRITE4args **wargs_pp, nfs4_stateid_types_t *sid_tp)
565 {
566 	WRITE4args *wargs = &argop->nfs_argop4_u.opwrite;
567 	mntinfo4_t *mi = VTOMI4(RTOV4(rp));
568 
569 	argop->argop = OP_WRITE;
570 	wargs->stable = stable;
571 	wargs->stateid = nfs4_get_w_stateid(cr, rp, curproc->p_pidp->pid_id,
572 	    mi, OP_WRITE, sid_tp);
573 	wargs->mblk = NULL;
574 	*wargs_pp = wargs;
575 }
576 
577 void
578 nfs4args_copen_free(OPEN4cargs *open_args)
579 {
580 	if (open_args->owner.owner_val) {
581 		kmem_free(open_args->owner.owner_val,
582 		    open_args->owner.owner_len);
583 	}
584 	if ((open_args->opentype == OPEN4_CREATE) &&
585 	    (open_args->mode != EXCLUSIVE4)) {
586 		nfs4_fattr4_free(&open_args->createhow4_u.createattrs);
587 	}
588 }
589 
590 /*
591  * XXX:  This is referenced in modstubs.s
592  */
593 struct vnodeops *
594 nfs4_getvnodeops(void)
595 {
596 	return (nfs4_vnodeops);
597 }
598 
599 /*
600  * The OPEN operation opens a regular file.
601  */
602 /*ARGSUSED3*/
603 static int
604 nfs4_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
605 {
606 	vnode_t *dvp = NULL;
607 	rnode4_t *rp, *drp;
608 	int error;
609 	int just_been_created;
610 	char fn[MAXNAMELEN];
611 
612 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4_open: "));
613 	if (nfs_zone() != VTOMI4(*vpp)->mi_zone)
614 		return (EIO);
615 	rp = VTOR4(*vpp);
616 
617 	/*
618 	 * Check to see if opening something besides a regular file;
619 	 * if so skip the OTW call
620 	 */
621 	if ((*vpp)->v_type != VREG) {
622 		error = nfs4_open_non_reg_file(vpp, flag, cr);
623 		return (error);
624 	}
625 
626 	/*
627 	 * XXX - would like a check right here to know if the file is
628 	 * executable or not, so as to skip OTW
629 	 */
630 
631 	if ((error = vtodv(*vpp, &dvp, cr, TRUE)) != 0)
632 		return (error);
633 
634 	drp = VTOR4(dvp);
635 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
636 		return (EINTR);
637 
638 	if ((error = vtoname(*vpp, fn, MAXNAMELEN)) != 0) {
639 		nfs_rw_exit(&drp->r_rwlock);
640 		return (error);
641 	}
642 
643 	/*
644 	 * See if this file has just been CREATEd.
645 	 * If so, clear the flag and update the dnlc, which was previously
646 	 * skipped in nfs4_create.
647 	 * XXX need better serilization on this.
648 	 * XXX move this into the nf4open_otw call, after we have
649 	 * XXX acquired the open owner seqid sync.
650 	 */
651 	mutex_enter(&rp->r_statev4_lock);
652 	if (rp->created_v4) {
653 		rp->created_v4 = 0;
654 		mutex_exit(&rp->r_statev4_lock);
655 
656 		dnlc_update(dvp, fn, *vpp);
657 		/* This is needed so we don't bump the open ref count */
658 		just_been_created = 1;
659 	} else {
660 		mutex_exit(&rp->r_statev4_lock);
661 		just_been_created = 0;
662 	}
663 
664 	/*
665 	 * If caller specified O_TRUNC/FTRUNC, then be sure to set
666 	 * FWRITE (to drive successful setattr(size=0) after open)
667 	 */
668 	if (flag & FTRUNC)
669 		flag |= FWRITE;
670 
671 	error = nfs4open_otw(dvp, fn, NULL, vpp, cr, 0, flag, 0,
672 	    just_been_created);
673 
674 	if (!error && !((*vpp)->v_flag & VROOT))
675 		dnlc_update(dvp, fn, *vpp);
676 
677 	nfs_rw_exit(&drp->r_rwlock);
678 
679 	/* release the hold from vtodv */
680 	VN_RELE(dvp);
681 
682 	/* exchange the shadow for the master vnode, if needed */
683 
684 	if (error == 0 && IS_SHADOW(*vpp, rp))
685 		sv_exchange(vpp);
686 
687 	return (error);
688 }
689 
690 /*
691  * See if there's a "lost open" request to be saved and recovered.
692  */
693 static void
694 nfs4open_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
695     nfs4_open_owner_t *oop, cred_t *cr, vnode_t *vp,
696     vnode_t *dvp, OPEN4cargs *open_args)
697 {
698 	vfs_t *vfsp;
699 	char *srccfp;
700 
701 	vfsp = (dvp ? dvp->v_vfsp : vp->v_vfsp);
702 
703 	if (error != ETIMEDOUT && error != EINTR &&
704 	    !NFS4_FRC_UNMT_ERR(error, vfsp)) {
705 		lost_rqstp->lr_op = 0;
706 		return;
707 	}
708 
709 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
710 	    "nfs4open_save_lost_rqst: error %d", error));
711 
712 	lost_rqstp->lr_op = OP_OPEN;
713 
714 	/*
715 	 * The vp (if it is not NULL) and dvp are held and rele'd via
716 	 * the recovery code.  See nfs4_save_lost_rqst.
717 	 */
718 	lost_rqstp->lr_vp = vp;
719 	lost_rqstp->lr_dvp = dvp;
720 	lost_rqstp->lr_oop = oop;
721 	lost_rqstp->lr_osp = NULL;
722 	lost_rqstp->lr_lop = NULL;
723 	lost_rqstp->lr_cr = cr;
724 	lost_rqstp->lr_flk = NULL;
725 	lost_rqstp->lr_oacc = open_args->share_access;
726 	lost_rqstp->lr_odeny = open_args->share_deny;
727 	lost_rqstp->lr_oclaim = open_args->claim;
728 	if (open_args->claim == CLAIM_DELEGATE_CUR) {
729 		lost_rqstp->lr_ostateid =
730 		    open_args->open_claim4_u.delegate_cur_info.delegate_stateid;
731 		srccfp = open_args->open_claim4_u.delegate_cur_info.cfile;
732 	} else {
733 		srccfp = open_args->open_claim4_u.cfile;
734 	}
735 	lost_rqstp->lr_ofile.utf8string_len = 0;
736 	lost_rqstp->lr_ofile.utf8string_val = NULL;
737 	(void) str_to_utf8(srccfp, &lost_rqstp->lr_ofile);
738 	lost_rqstp->lr_putfirst = FALSE;
739 }
740 
741 struct nfs4_excl_time {
742 	uint32 seconds;
743 	uint32 nseconds;
744 };
745 
746 /*
747  * The OPEN operation creates and/or opens a regular file
748  *
749  * ARGSUSED
750  */
751 static int
752 nfs4open_otw(vnode_t *dvp, char *file_name, struct vattr *in_va,
753     vnode_t **vpp, cred_t *cr, int create_flag, int open_flag,
754     enum createmode4 createmode, int file_just_been_created)
755 {
756 	rnode4_t *rp;
757 	rnode4_t *drp = VTOR4(dvp);
758 	vnode_t *vp = NULL;
759 	vnode_t *vpi = *vpp;
760 	bool_t needrecov = FALSE;
761 
762 	int doqueue = 1;
763 
764 	COMPOUND4args_clnt args;
765 	COMPOUND4res_clnt res;
766 	nfs_argop4 *argop;
767 	nfs_resop4 *resop;
768 	int argoplist_size;
769 	int idx_open, idx_fattr;
770 
771 	GETFH4res *gf_res = NULL;
772 	OPEN4res *op_res = NULL;
773 	nfs4_ga_res_t *garp;
774 	fattr4 *attr = NULL;
775 	struct nfs4_excl_time verf;
776 	bool_t did_excl_setup = FALSE;
777 	int created_osp;
778 
779 	OPEN4cargs *open_args;
780 	nfs4_open_owner_t	*oop = NULL;
781 	nfs4_open_stream_t	*osp = NULL;
782 	seqid4 seqid = 0;
783 	bool_t retry_open = FALSE;
784 	nfs4_recov_state_t recov_state;
785 	nfs4_lost_rqst_t lost_rqst;
786 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
787 	hrtime_t t;
788 	int acc = 0;
789 	cred_t *cred_otw = NULL;	/* cred used to do the RPC call */
790 	cred_t *ncr = NULL;
791 
792 	nfs4_sharedfh_t *otw_sfh;
793 	nfs4_sharedfh_t *orig_sfh;
794 	int fh_differs = 0;
795 	int numops, setgid_flag;
796 	int num_bseqid_retry = NFS4_NUM_RETRY_BAD_SEQID + 1;
797 
798 	/*
799 	 * Make sure we properly deal with setting the right gid on
800 	 * a newly created file to reflect the parent's setgid bit
801 	 */
802 	setgid_flag = 0;
803 	if (create_flag && in_va) {
804 
805 		/*
806 		 * If the parent's directory has the setgid bit set
807 		 * _and_ the client was able to get a valid mapping
808 		 * for the parent dir's owner_group, we want to
809 		 * append NVERIFY(owner_group == dva.va_gid) and
810 		 * SETATTR to the CREATE compound.
811 		 */
812 		mutex_enter(&drp->r_statelock);
813 		if (drp->r_attr.va_mode & VSGID &&
814 		    drp->r_attr.va_gid != GID_NOBODY) {
815 			in_va->va_gid = drp->r_attr.va_gid;
816 			setgid_flag = 1;
817 		}
818 		mutex_exit(&drp->r_statelock);
819 	}
820 
821 	/*
822 	 * Normal/non-create compound:
823 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new)
824 	 *
825 	 * Open(create) compound no setgid:
826 	 * PUTFH(dfh) + SAVEFH + OPEN(create) + GETFH + GETATTR(new) +
827 	 * RESTOREFH + GETATTR
828 	 *
829 	 * Open(create) setgid:
830 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new) +
831 	 * SAVEFH + PUTFH(dfh) + GETATTR(dvp) + RESTOREFH +
832 	 * NVERIFY(grp) + SETATTR
833 	 */
834 	if (setgid_flag) {
835 		numops = 10;
836 		idx_open = 1;
837 		idx_fattr = 3;
838 	} else if (create_flag) {
839 		numops = 7;
840 		idx_open = 2;
841 		idx_fattr = 4;
842 	} else {
843 		numops = 4;
844 		idx_open = 1;
845 		idx_fattr = 3;
846 	}
847 
848 	args.array_len = numops;
849 	argoplist_size = numops * sizeof (nfs_argop4);
850 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
851 
852 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw: "
853 	    "open %s open flag 0x%x cred %p", file_name, open_flag,
854 	    (void *)cr));
855 
856 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
857 	if (create_flag) {
858 		/*
859 		 * We are to create a file.  Initialize the passed in vnode
860 		 * pointer.
861 		 */
862 		vpi = NULL;
863 	} else {
864 		/*
865 		 * Check to see if the client owns a read delegation and is
866 		 * trying to open for write.  If so, then return the delegation
867 		 * to avoid the server doing a cb_recall and returning DELAY.
868 		 * NB - we don't use the statev4_lock here because we'd have
869 		 * to drop the lock anyway and the result would be stale.
870 		 */
871 		if ((open_flag & FWRITE) &&
872 		    VTOR4(vpi)->r_deleg_type == OPEN_DELEGATE_READ)
873 			(void) nfs4delegreturn(VTOR4(vpi), NFS4_DR_REOPEN);
874 
875 		/*
876 		 * If the file has a delegation, then do an access check up
877 		 * front.  This avoids having to an access check later after
878 		 * we've already done start_op, which could deadlock.
879 		 */
880 		if (VTOR4(vpi)->r_deleg_type != OPEN_DELEGATE_NONE) {
881 			if (open_flag & FREAD &&
882 			    nfs4_access(vpi, VREAD, 0, cr, NULL) == 0)
883 				acc |= VREAD;
884 			if (open_flag & FWRITE &&
885 			    nfs4_access(vpi, VWRITE, 0, cr, NULL) == 0)
886 				acc |= VWRITE;
887 		}
888 	}
889 
890 	drp = VTOR4(dvp);
891 
892 	recov_state.rs_flags = 0;
893 	recov_state.rs_num_retry_despite_err = 0;
894 	cred_otw = cr;
895 
896 recov_retry:
897 	fh_differs = 0;
898 	nfs4_error_zinit(&e);
899 
900 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, vpi, &recov_state);
901 	if (e.error) {
902 		if (ncr != NULL)
903 			crfree(ncr);
904 		kmem_free(argop, argoplist_size);
905 		return (e.error);
906 	}
907 
908 	args.ctag = TAG_OPEN;
909 	args.array_len = numops;
910 	args.array = argop;
911 
912 	/* putfh directory fh */
913 	argop[0].argop = OP_CPUTFH;
914 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
915 
916 	/* OPEN: either op 1 or op 2 depending upon create/setgid flags */
917 	argop[idx_open].argop = OP_COPEN;
918 	open_args = &argop[idx_open].nfs_argop4_u.opcopen;
919 	open_args->claim = CLAIM_NULL;
920 
921 	/* name of file */
922 	open_args->open_claim4_u.cfile = file_name;
923 	open_args->owner.owner_len = 0;
924 	open_args->owner.owner_val = NULL;
925 
926 	if (create_flag) {
927 		/* CREATE a file */
928 		open_args->opentype = OPEN4_CREATE;
929 		open_args->mode = createmode;
930 		if (createmode == EXCLUSIVE4) {
931 			if (did_excl_setup == FALSE) {
932 				verf.seconds = nfs_atoi(hw_serial);
933 				if (verf.seconds != 0)
934 					verf.nseconds = newnum();
935 				else {
936 					timestruc_t now;
937 
938 					gethrestime(&now);
939 					verf.seconds = now.tv_sec;
940 					verf.nseconds = now.tv_nsec;
941 				}
942 				/*
943 				 * Since the server will use this value for the
944 				 * mtime, make sure that it can't overflow. Zero
945 				 * out the MSB. The actual value does not matter
946 				 * here, only its uniqeness.
947 				 */
948 				verf.seconds &= INT32_MAX;
949 				did_excl_setup = TRUE;
950 			}
951 
952 			/* Now copy over verifier to OPEN4args. */
953 			open_args->createhow4_u.createverf = *(uint64_t *)&verf;
954 		} else {
955 			int v_error;
956 			bitmap4 supp_attrs;
957 			servinfo4_t *svp;
958 
959 			attr = &open_args->createhow4_u.createattrs;
960 
961 			svp = drp->r_server;
962 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
963 			supp_attrs = svp->sv_supp_attrs;
964 			nfs_rw_exit(&svp->sv_lock);
965 
966 			/* GUARDED4 or UNCHECKED4 */
967 			v_error = vattr_to_fattr4(in_va, NULL, attr, 0, OP_OPEN,
968 			    supp_attrs);
969 			if (v_error) {
970 				bzero(attr, sizeof (*attr));
971 				nfs4args_copen_free(open_args);
972 				nfs4_end_op(VTOMI4(dvp), dvp, vpi,
973 				    &recov_state, FALSE);
974 				if (ncr != NULL)
975 					crfree(ncr);
976 				kmem_free(argop, argoplist_size);
977 				return (v_error);
978 			}
979 		}
980 	} else {
981 		/* NO CREATE */
982 		open_args->opentype = OPEN4_NOCREATE;
983 	}
984 
985 	if (recov_state.rs_sp != NULL) {
986 		mutex_enter(&recov_state.rs_sp->s_lock);
987 		open_args->owner.clientid = recov_state.rs_sp->clientid;
988 		mutex_exit(&recov_state.rs_sp->s_lock);
989 	} else {
990 		/* XXX should we just fail here? */
991 		open_args->owner.clientid = 0;
992 	}
993 
994 	/*
995 	 * This increments oop's ref count or creates a temporary 'just_created'
996 	 * open owner that will become valid when this OPEN/OPEN_CONFIRM call
997 	 * completes.
998 	 */
999 	mutex_enter(&VTOMI4(dvp)->mi_lock);
1000 
1001 	/* See if a permanent or just created open owner exists */
1002 	oop = find_open_owner_nolock(cr, NFS4_JUST_CREATED, VTOMI4(dvp));
1003 	if (!oop) {
1004 		/*
1005 		 * This open owner does not exist so create a temporary
1006 		 * just created one.
1007 		 */
1008 		oop = create_open_owner(cr, VTOMI4(dvp));
1009 		ASSERT(oop != NULL);
1010 	}
1011 	mutex_exit(&VTOMI4(dvp)->mi_lock);
1012 
1013 	/* this length never changes, do alloc before seqid sync */
1014 	open_args->owner.owner_len = sizeof (oop->oo_name);
1015 	open_args->owner.owner_val =
1016 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1017 
1018 	e.error = nfs4_start_open_seqid_sync(oop, VTOMI4(dvp));
1019 	if (e.error == EAGAIN) {
1020 		open_owner_rele(oop);
1021 		nfs4args_copen_free(open_args);
1022 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1023 		if (ncr != NULL) {
1024 			crfree(ncr);
1025 			ncr = NULL;
1026 		}
1027 		goto recov_retry;
1028 	}
1029 
1030 	/* Check to see if we need to do the OTW call */
1031 	if (!create_flag) {
1032 		if (!nfs4_is_otw_open_necessary(oop, open_flag, vpi,
1033 		    file_just_been_created, &e.error, acc, &recov_state)) {
1034 
1035 			/*
1036 			 * The OTW open is not necessary.  Either
1037 			 * the open can succeed without it (eg.
1038 			 * delegation, error == 0) or the open
1039 			 * must fail due to an access failure
1040 			 * (error != 0).  In either case, tidy
1041 			 * up and return.
1042 			 */
1043 
1044 			nfs4_end_open_seqid_sync(oop);
1045 			open_owner_rele(oop);
1046 			nfs4args_copen_free(open_args);
1047 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, FALSE);
1048 			if (ncr != NULL)
1049 				crfree(ncr);
1050 			kmem_free(argop, argoplist_size);
1051 			return (e.error);
1052 		}
1053 	}
1054 
1055 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1056 	    open_args->owner.owner_len);
1057 
1058 	seqid = nfs4_get_open_seqid(oop) + 1;
1059 	open_args->seqid = seqid;
1060 	open_args->share_access = 0;
1061 	if (open_flag & FREAD)
1062 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1063 	if (open_flag & FWRITE)
1064 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1065 	open_args->share_deny = OPEN4_SHARE_DENY_NONE;
1066 
1067 
1068 
1069 	/*
1070 	 * getfh w/sanity check for idx_open/idx_fattr
1071 	 */
1072 	ASSERT((idx_open + 1) == (idx_fattr - 1));
1073 	argop[idx_open + 1].argop = OP_GETFH;
1074 
1075 	/* getattr */
1076 	argop[idx_fattr].argop = OP_GETATTR;
1077 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1078 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1079 
1080 	if (setgid_flag) {
1081 		vattr_t	_v;
1082 		servinfo4_t *svp;
1083 		bitmap4	supp_attrs;
1084 
1085 		svp = drp->r_server;
1086 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1087 		supp_attrs = svp->sv_supp_attrs;
1088 		nfs_rw_exit(&svp->sv_lock);
1089 
1090 		/*
1091 		 * For setgid case, we need to:
1092 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1093 		 */
1094 		argop[4].argop = OP_SAVEFH;
1095 
1096 		argop[5].argop = OP_CPUTFH;
1097 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
1098 
1099 		argop[6].argop = OP_GETATTR;
1100 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1101 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1102 
1103 		argop[7].argop = OP_RESTOREFH;
1104 
1105 		/*
1106 		 * nverify
1107 		 */
1108 		_v.va_mask = AT_GID;
1109 		_v.va_gid = in_va->va_gid;
1110 		if (!(e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
1111 		    supp_attrs))) {
1112 
1113 			/*
1114 			 * setattr
1115 			 *
1116 			 * We _know_ we're not messing with AT_SIZE or
1117 			 * AT_XTIME, so no need for stateid or flags.
1118 			 * Also we specify NULL rp since we're only
1119 			 * interested in setting owner_group attributes.
1120 			 */
1121 			nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr,
1122 			    supp_attrs, &e.error, 0);
1123 			if (e.error)
1124 				nfs4args_verify_free(&argop[8]);
1125 		}
1126 
1127 		if (e.error) {
1128 			/*
1129 			 * XXX - Revisit the last argument to nfs4_end_op()
1130 			 *	 once 5020486 is fixed.
1131 			 */
1132 			nfs4_end_open_seqid_sync(oop);
1133 			open_owner_rele(oop);
1134 			nfs4args_copen_free(open_args);
1135 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1136 			if (ncr != NULL)
1137 				crfree(ncr);
1138 			kmem_free(argop, argoplist_size);
1139 			return (e.error);
1140 		}
1141 	} else if (create_flag) {
1142 		/*
1143 		 * For setgid case, we need to:
1144 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1145 		 */
1146 		argop[1].argop = OP_SAVEFH;
1147 
1148 		argop[5].argop = OP_RESTOREFH;
1149 
1150 		argop[6].argop = OP_GETATTR;
1151 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1152 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1153 	}
1154 
1155 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1156 	    "nfs4open_otw: %s call, nm %s, rp %s",
1157 	    needrecov ? "recov" : "first", file_name,
1158 	    rnode4info(VTOR4(dvp))));
1159 
1160 	t = gethrtime();
1161 
1162 	rfs4call(VTOMI4(dvp), &args, &res, cred_otw, &doqueue, 0, &e);
1163 
1164 	if (!e.error && nfs4_need_to_bump_seqid(&res))
1165 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1166 
1167 	needrecov = nfs4_needs_recovery(&e, TRUE, dvp->v_vfsp);
1168 
1169 	if (e.error || needrecov) {
1170 		bool_t abort = FALSE;
1171 
1172 		if (needrecov) {
1173 			nfs4_bseqid_entry_t *bsep = NULL;
1174 
1175 			nfs4open_save_lost_rqst(e.error, &lost_rqst, oop,
1176 			    cred_otw, vpi, dvp, open_args);
1177 
1178 			if (!e.error && res.status == NFS4ERR_BAD_SEQID) {
1179 				bsep = nfs4_create_bseqid_entry(oop, NULL,
1180 				    vpi, 0, args.ctag, open_args->seqid);
1181 				num_bseqid_retry--;
1182 			}
1183 
1184 			abort = nfs4_start_recovery(&e, VTOMI4(dvp), dvp, vpi,
1185 			    NULL, lost_rqst.lr_op == OP_OPEN ?
1186 			    &lost_rqst : NULL, OP_OPEN, bsep);
1187 
1188 			if (bsep)
1189 				kmem_free(bsep, sizeof (*bsep));
1190 			/* give up if we keep getting BAD_SEQID */
1191 			if (num_bseqid_retry == 0)
1192 				abort = TRUE;
1193 			if (abort == TRUE && e.error == 0)
1194 				e.error = geterrno4(res.status);
1195 		}
1196 		nfs4_end_open_seqid_sync(oop);
1197 		open_owner_rele(oop);
1198 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1199 		nfs4args_copen_free(open_args);
1200 		if (setgid_flag) {
1201 			nfs4args_verify_free(&argop[8]);
1202 			nfs4args_setattr_free(&argop[9]);
1203 		}
1204 		if (!e.error)
1205 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1206 		if (ncr != NULL) {
1207 			crfree(ncr);
1208 			ncr = NULL;
1209 		}
1210 		if (!needrecov || abort == TRUE || e.error == EINTR ||
1211 		    NFS4_FRC_UNMT_ERR(e.error, dvp->v_vfsp)) {
1212 			kmem_free(argop, argoplist_size);
1213 			return (e.error);
1214 		}
1215 		goto recov_retry;
1216 	}
1217 
1218 	/*
1219 	 * Will check and update lease after checking the rflag for
1220 	 * OPEN_CONFIRM in the successful OPEN call.
1221 	 */
1222 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
1223 
1224 		/*
1225 		 * XXX what if we're crossing mount points from server1:/drp
1226 		 * to server2:/drp/rp.
1227 		 */
1228 
1229 		/* Signal our end of use of the open seqid */
1230 		nfs4_end_open_seqid_sync(oop);
1231 
1232 		/*
1233 		 * This will destroy the open owner if it was just created,
1234 		 * and no one else has put a reference on it.
1235 		 */
1236 		open_owner_rele(oop);
1237 		if (create_flag && (createmode != EXCLUSIVE4) &&
1238 		    res.status == NFS4ERR_BADOWNER)
1239 			nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1240 
1241 		e.error = geterrno4(res.status);
1242 		nfs4args_copen_free(open_args);
1243 		if (setgid_flag) {
1244 			nfs4args_verify_free(&argop[8]);
1245 			nfs4args_setattr_free(&argop[9]);
1246 		}
1247 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1248 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1249 		/*
1250 		 * If the reply is NFS4ERR_ACCESS, it may be because
1251 		 * we are root (no root net access).  If the real uid
1252 		 * is not root, then retry with the real uid instead.
1253 		 */
1254 		if (ncr != NULL) {
1255 			crfree(ncr);
1256 			ncr = NULL;
1257 		}
1258 		if (res.status == NFS4ERR_ACCESS &&
1259 		    (ncr = crnetadjust(cred_otw)) != NULL) {
1260 			cred_otw = ncr;
1261 			goto recov_retry;
1262 		}
1263 		kmem_free(argop, argoplist_size);
1264 		return (e.error);
1265 	}
1266 
1267 	resop = &res.array[idx_open];  /* open res */
1268 	op_res = &resop->nfs_resop4_u.opopen;
1269 
1270 #ifdef DEBUG
1271 	/*
1272 	 * verify attrset bitmap
1273 	 */
1274 	if (create_flag &&
1275 	    (createmode == UNCHECKED4 || createmode == GUARDED4)) {
1276 		/* make sure attrset returned is what we asked for */
1277 		/* XXX Ignore this 'error' for now */
1278 		if (attr->attrmask != op_res->attrset)
1279 			/* EMPTY */;
1280 	}
1281 #endif
1282 
1283 	if (op_res->rflags & OPEN4_RESULT_LOCKTYPE_POSIX) {
1284 		mutex_enter(&VTOMI4(dvp)->mi_lock);
1285 		VTOMI4(dvp)->mi_flags |= MI4_POSIX_LOCK;
1286 		mutex_exit(&VTOMI4(dvp)->mi_lock);
1287 	}
1288 
1289 	resop = &res.array[idx_open + 1];  /* getfh res */
1290 	gf_res = &resop->nfs_resop4_u.opgetfh;
1291 
1292 	otw_sfh = sfh4_get(&gf_res->object, VTOMI4(dvp));
1293 
1294 	/*
1295 	 * The open stateid has been updated on the server but not
1296 	 * on the client yet.  There is a path: makenfs4node->nfs4_attr_cache->
1297 	 * flush_pages->VOP_PUTPAGE->...->nfs4write where we will issue an OTW
1298 	 * WRITE call.  That, however, will use the old stateid, so go ahead
1299 	 * and upate the open stateid now, before any call to makenfs4node.
1300 	 */
1301 	if (vpi) {
1302 		nfs4_open_stream_t	*tmp_osp;
1303 		rnode4_t		*tmp_rp = VTOR4(vpi);
1304 
1305 		tmp_osp = find_open_stream(oop, tmp_rp);
1306 		if (tmp_osp) {
1307 			tmp_osp->open_stateid = op_res->stateid;
1308 			mutex_exit(&tmp_osp->os_sync_lock);
1309 			open_stream_rele(tmp_osp, tmp_rp);
1310 		}
1311 
1312 		/*
1313 		 * We must determine if the file handle given by the otw open
1314 		 * is the same as the file handle which was passed in with
1315 		 * *vpp.  This case can be reached if the file we are trying
1316 		 * to open has been removed and another file has been created
1317 		 * having the same file name.  The passed in vnode is released
1318 		 * later.
1319 		 */
1320 		orig_sfh = VTOR4(vpi)->r_fh;
1321 		fh_differs = nfs4cmpfh(&orig_sfh->sfh_fh, &otw_sfh->sfh_fh);
1322 	}
1323 
1324 	garp = &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res;
1325 
1326 	if (create_flag || fh_differs) {
1327 		int rnode_err = 0;
1328 
1329 		vp = makenfs4node(otw_sfh, garp, dvp->v_vfsp, t, cr,
1330 		    dvp, fn_get(VTOSV(dvp)->sv_name, file_name));
1331 
1332 		if (e.error)
1333 			PURGE_ATTRCACHE4(vp);
1334 		/*
1335 		 * For the newly created vp case, make sure the rnode
1336 		 * isn't bad before using it.
1337 		 */
1338 		mutex_enter(&(VTOR4(vp))->r_statelock);
1339 		if (VTOR4(vp)->r_flags & R4RECOVERR)
1340 			rnode_err = EIO;
1341 		mutex_exit(&(VTOR4(vp))->r_statelock);
1342 
1343 		if (rnode_err) {
1344 			nfs4_end_open_seqid_sync(oop);
1345 			nfs4args_copen_free(open_args);
1346 			if (setgid_flag) {
1347 				nfs4args_verify_free(&argop[8]);
1348 				nfs4args_setattr_free(&argop[9]);
1349 			}
1350 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1351 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1352 			    needrecov);
1353 			open_owner_rele(oop);
1354 			VN_RELE(vp);
1355 			if (ncr != NULL)
1356 				crfree(ncr);
1357 			sfh4_rele(&otw_sfh);
1358 			kmem_free(argop, argoplist_size);
1359 			return (EIO);
1360 		}
1361 	} else {
1362 		vp = vpi;
1363 	}
1364 	sfh4_rele(&otw_sfh);
1365 
1366 	/*
1367 	 * It seems odd to get a full set of attrs and then not update
1368 	 * the object's attrcache in the non-create case.  Create case uses
1369 	 * the attrs since makenfs4node checks to see if the attrs need to
1370 	 * be updated (and then updates them).  The non-create case should
1371 	 * update attrs also.
1372 	 */
1373 	if (! create_flag && ! fh_differs && !e.error) {
1374 		nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
1375 	}
1376 
1377 	nfs4_error_zinit(&e);
1378 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
1379 		/* This does not do recovery for vp explicitly. */
1380 		nfs4open_confirm(vp, &seqid, &op_res->stateid, cred_otw, FALSE,
1381 		    &retry_open, oop, FALSE, &e, &num_bseqid_retry);
1382 
1383 		if (e.error || e.stat) {
1384 			nfs4_end_open_seqid_sync(oop);
1385 			nfs4args_copen_free(open_args);
1386 			if (setgid_flag) {
1387 				nfs4args_verify_free(&argop[8]);
1388 				nfs4args_setattr_free(&argop[9]);
1389 			}
1390 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1391 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1392 			    needrecov);
1393 			open_owner_rele(oop);
1394 			if (create_flag || fh_differs) {
1395 				/* rele the makenfs4node */
1396 				VN_RELE(vp);
1397 			}
1398 			if (ncr != NULL) {
1399 				crfree(ncr);
1400 				ncr = NULL;
1401 			}
1402 			if (retry_open == TRUE) {
1403 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1404 				    "nfs4open_otw: retry the open since OPEN "
1405 				    "CONFIRM failed with error %d stat %d",
1406 				    e.error, e.stat));
1407 				if (create_flag && createmode == GUARDED4) {
1408 					NFS4_DEBUG(nfs4_client_recov_debug,
1409 					    (CE_NOTE, "nfs4open_otw: switch "
1410 					    "createmode from GUARDED4 to "
1411 					    "UNCHECKED4"));
1412 					createmode = UNCHECKED4;
1413 				}
1414 				goto recov_retry;
1415 			}
1416 			if (!e.error) {
1417 				if (create_flag && (createmode != EXCLUSIVE4) &&
1418 				    e.stat == NFS4ERR_BADOWNER)
1419 					nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1420 
1421 				e.error = geterrno4(e.stat);
1422 			}
1423 			kmem_free(argop, argoplist_size);
1424 			return (e.error);
1425 		}
1426 	}
1427 
1428 	rp = VTOR4(vp);
1429 
1430 	mutex_enter(&rp->r_statev4_lock);
1431 	if (create_flag)
1432 		rp->created_v4 = 1;
1433 	mutex_exit(&rp->r_statev4_lock);
1434 
1435 	mutex_enter(&oop->oo_lock);
1436 	/* Doesn't matter if 'oo_just_created' already was set as this */
1437 	oop->oo_just_created = NFS4_PERM_CREATED;
1438 	if (oop->oo_cred_otw)
1439 		crfree(oop->oo_cred_otw);
1440 	oop->oo_cred_otw = cred_otw;
1441 	crhold(oop->oo_cred_otw);
1442 	mutex_exit(&oop->oo_lock);
1443 
1444 	/* returns with 'os_sync_lock' held */
1445 	osp = find_or_create_open_stream(oop, rp, &created_osp);
1446 	if (!osp) {
1447 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1448 		    "nfs4open_otw: failed to create an open stream"));
1449 		NFS4_DEBUG(nfs4_seqid_sync, (CE_NOTE, "nfs4open_otw: "
1450 		    "signal our end of use of the open seqid"));
1451 
1452 		nfs4_end_open_seqid_sync(oop);
1453 		open_owner_rele(oop);
1454 		nfs4args_copen_free(open_args);
1455 		if (setgid_flag) {
1456 			nfs4args_verify_free(&argop[8]);
1457 			nfs4args_setattr_free(&argop[9]);
1458 		}
1459 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1460 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1461 		if (create_flag || fh_differs)
1462 			VN_RELE(vp);
1463 		if (ncr != NULL)
1464 			crfree(ncr);
1465 
1466 		kmem_free(argop, argoplist_size);
1467 		return (EINVAL);
1468 
1469 	}
1470 
1471 	osp->open_stateid = op_res->stateid;
1472 
1473 	if (open_flag & FREAD)
1474 		osp->os_share_acc_read++;
1475 	if (open_flag & FWRITE)
1476 		osp->os_share_acc_write++;
1477 	osp->os_share_deny_none++;
1478 
1479 	/*
1480 	 * Need to reset this bitfield for the possible case where we were
1481 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
1482 	 * we could retry the CLOSE, OPENed the file again.
1483 	 */
1484 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
1485 	osp->os_final_close = 0;
1486 	osp->os_force_close = 0;
1487 #ifdef DEBUG
1488 	if (osp->os_failed_reopen)
1489 		NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE, "nfs4open_otw:"
1490 		    " clearing os_failed_reopen for osp %p, cr %p, rp %s",
1491 		    (void *)osp, (void *)cr, rnode4info(rp)));
1492 #endif
1493 	osp->os_failed_reopen = 0;
1494 
1495 	mutex_exit(&osp->os_sync_lock);
1496 
1497 	nfs4_end_open_seqid_sync(oop);
1498 
1499 	if (created_osp && recov_state.rs_sp != NULL) {
1500 		mutex_enter(&recov_state.rs_sp->s_lock);
1501 		nfs4_inc_state_ref_count_nolock(recov_state.rs_sp, VTOMI4(dvp));
1502 		mutex_exit(&recov_state.rs_sp->s_lock);
1503 	}
1504 
1505 	/* get rid of our reference to find oop */
1506 	open_owner_rele(oop);
1507 
1508 	open_stream_rele(osp, rp);
1509 
1510 	/* accept delegation, if any */
1511 	nfs4_delegation_accept(rp, CLAIM_NULL, op_res, garp, cred_otw);
1512 
1513 	nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1514 
1515 	if (createmode == EXCLUSIVE4 &&
1516 	    (in_va->va_mask & ~(AT_GID | AT_SIZE))) {
1517 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw:"
1518 		    " EXCLUSIVE4: sending a SETATTR"));
1519 		/*
1520 		 * If doing an exclusive create, then generate
1521 		 * a SETATTR to set the initial attributes.
1522 		 * Try to set the mtime and the atime to the
1523 		 * server's current time.  It is somewhat
1524 		 * expected that these fields will be used to
1525 		 * store the exclusive create cookie.  If not,
1526 		 * server implementors will need to know that
1527 		 * a SETATTR will follow an exclusive create
1528 		 * and the cookie should be destroyed if
1529 		 * appropriate.
1530 		 *
1531 		 * The AT_GID and AT_SIZE bits are turned off
1532 		 * so that the SETATTR request will not attempt
1533 		 * to process these.  The gid will be set
1534 		 * separately if appropriate.  The size is turned
1535 		 * off because it is assumed that a new file will
1536 		 * be created empty and if the file wasn't empty,
1537 		 * then the exclusive create will have failed
1538 		 * because the file must have existed already.
1539 		 * Therefore, no truncate operation is needed.
1540 		 */
1541 		in_va->va_mask &= ~(AT_GID | AT_SIZE);
1542 		in_va->va_mask |= (AT_MTIME | AT_ATIME);
1543 
1544 		e.error = nfs4setattr(vp, in_va, 0, cr, NULL);
1545 		if (e.error) {
1546 			/*
1547 			 * Couldn't correct the attributes of
1548 			 * the newly created file and the
1549 			 * attributes are wrong.  Remove the
1550 			 * file and return an error to the
1551 			 * application.
1552 			 */
1553 			/* XXX will this take care of client state ? */
1554 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1555 			    "nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1556 			    " remove file", e.error));
1557 			VN_RELE(vp);
1558 			(void) nfs4_remove(dvp, file_name, cr, NULL, 0);
1559 			/*
1560 			 * Since we've reled the vnode and removed
1561 			 * the file we now need to return the error.
1562 			 * At this point we don't want to update the
1563 			 * dircaches, call nfs4_waitfor_purge_complete
1564 			 * or set vpp to vp so we need to skip these
1565 			 * as well.
1566 			 */
1567 			goto skip_update_dircaches;
1568 		}
1569 	}
1570 
1571 	/*
1572 	 * If we created or found the correct vnode, due to create_flag or
1573 	 * fh_differs being set, then update directory cache attribute, readdir
1574 	 * and dnlc caches.
1575 	 */
1576 	if (create_flag || fh_differs) {
1577 		dirattr_info_t dinfo, *dinfop;
1578 
1579 		/*
1580 		 * Make sure getattr succeeded before using results.
1581 		 * note: op 7 is getattr(dir) for both flavors of
1582 		 * open(create).
1583 		 */
1584 		if (create_flag && res.status == NFS4_OK) {
1585 			dinfo.di_time_call = t;
1586 			dinfo.di_cred = cr;
1587 			dinfo.di_garp =
1588 			    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
1589 			dinfop = &dinfo;
1590 		} else {
1591 			dinfop = NULL;
1592 		}
1593 
1594 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1595 		    dinfop);
1596 	}
1597 
1598 	/*
1599 	 * If the page cache for this file was flushed from actions
1600 	 * above, it was done asynchronously and if that is true,
1601 	 * there is a need to wait here for it to complete.  This must
1602 	 * be done outside of start_fop/end_fop.
1603 	 */
1604 	(void) nfs4_waitfor_purge_complete(vp);
1605 
1606 	/*
1607 	 * It is implicit that we are in the open case (create_flag == 0) since
1608 	 * fh_differs can only be set to a non-zero value in the open case.
1609 	 */
1610 	if (fh_differs != 0 && vpi != NULL)
1611 		VN_RELE(vpi);
1612 
1613 	/*
1614 	 * Be sure to set *vpp to the correct value before returning.
1615 	 */
1616 	*vpp = vp;
1617 
1618 skip_update_dircaches:
1619 
1620 	nfs4args_copen_free(open_args);
1621 	if (setgid_flag) {
1622 		nfs4args_verify_free(&argop[8]);
1623 		nfs4args_setattr_free(&argop[9]);
1624 	}
1625 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1626 
1627 	if (ncr)
1628 		crfree(ncr);
1629 	kmem_free(argop, argoplist_size);
1630 	return (e.error);
1631 }
1632 
1633 /*
1634  * Reopen an open instance.  cf. nfs4open_otw().
1635  *
1636  * Errors are returned by the nfs4_error_t parameter.
1637  * - ep->error contains an errno value or zero.
1638  * - if it is zero, ep->stat is set to an NFS status code, if any.
1639  *   If the file could not be reopened, but the caller should continue, the
1640  *   file is marked dead and no error values are returned.  If the caller
1641  *   should stop recovering open files and start over, either the ep->error
1642  *   value or ep->stat will indicate an error (either something that requires
1643  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1644  *   filehandles) may be handled silently by this routine.
1645  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1646  *   will be started, so the caller should not do it.
1647  *
1648  * Gotos:
1649  * - kill_file : reopen failed in such a fashion to constitute marking the
1650  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1651  *   is for cases where recovery is not possible.
1652  * - failed_reopen : same as above, except that the file has already been
1653  *   marked dead, so no need to do it again.
1654  * - bailout : reopen failed but we are able to recover and retry the reopen -
1655  *   either within this function immediately or via the calling function.
1656  */
1657 
1658 void
1659 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1660     open_claim_type4 claim, bool_t frc_use_claim_previous,
1661     bool_t is_recov)
1662 {
1663 	COMPOUND4args_clnt args;
1664 	COMPOUND4res_clnt res;
1665 	nfs_argop4 argop[4];
1666 	nfs_resop4 *resop;
1667 	OPEN4res *op_res = NULL;
1668 	OPEN4cargs *open_args;
1669 	GETFH4res *gf_res;
1670 	rnode4_t *rp = VTOR4(vp);
1671 	int doqueue = 1;
1672 	cred_t *cr = NULL, *cred_otw = NULL;
1673 	nfs4_open_owner_t *oop = NULL;
1674 	seqid4 seqid;
1675 	nfs4_ga_res_t *garp;
1676 	char fn[MAXNAMELEN];
1677 	nfs4_recov_state_t recov = {NULL, 0};
1678 	nfs4_lost_rqst_t lost_rqst;
1679 	mntinfo4_t *mi = VTOMI4(vp);
1680 	bool_t abort;
1681 	char *failed_msg = "";
1682 	int fh_different;
1683 	hrtime_t t;
1684 	nfs4_bseqid_entry_t *bsep = NULL;
1685 
1686 	ASSERT(nfs4_consistent_type(vp));
1687 	ASSERT(nfs_zone() == mi->mi_zone);
1688 
1689 	nfs4_error_zinit(ep);
1690 
1691 	/* this is the cred used to find the open owner */
1692 	cr = state_to_cred(osp);
1693 	if (cr == NULL) {
1694 		failed_msg = "Couldn't reopen: no cred";
1695 		goto kill_file;
1696 	}
1697 	/* use this cred for OTW operations */
1698 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1699 
1700 top:
1701 	nfs4_error_zinit(ep);
1702 
1703 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1704 		/* File system has been unmounted, quit */
1705 		ep->error = EIO;
1706 		failed_msg = "Couldn't reopen: file system has been unmounted";
1707 		goto kill_file;
1708 	}
1709 
1710 	oop = osp->os_open_owner;
1711 
1712 	ASSERT(oop != NULL);
1713 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1714 		failed_msg = "can't reopen: no open owner";
1715 		goto kill_file;
1716 	}
1717 	open_owner_hold(oop);
1718 
1719 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1720 	if (ep->error) {
1721 		open_owner_rele(oop);
1722 		oop = NULL;
1723 		goto bailout;
1724 	}
1725 
1726 	/*
1727 	 * If the rnode has a delegation and the delegation has been
1728 	 * recovered and the server didn't request a recall and the caller
1729 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1730 	 * recovery) and the rnode hasn't been marked dead, then install
1731 	 * the delegation stateid in the open stream.  Otherwise, proceed
1732 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1733 	 */
1734 	mutex_enter(&rp->r_statev4_lock);
1735 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1736 	    !rp->r_deleg_return_pending &&
1737 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1738 	    !rp->r_deleg_needs_recall &&
1739 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1740 	    !(rp->r_flags & R4RECOVERR)) {
1741 		mutex_enter(&osp->os_sync_lock);
1742 		osp->os_delegation = 1;
1743 		osp->open_stateid = rp->r_deleg_stateid;
1744 		mutex_exit(&osp->os_sync_lock);
1745 		mutex_exit(&rp->r_statev4_lock);
1746 		goto bailout;
1747 	}
1748 	mutex_exit(&rp->r_statev4_lock);
1749 
1750 	/*
1751 	 * If the file failed recovery, just quit.  This failure need not
1752 	 * affect other reopens, so don't return an error.
1753 	 */
1754 	mutex_enter(&rp->r_statelock);
1755 	if (rp->r_flags & R4RECOVERR) {
1756 		mutex_exit(&rp->r_statelock);
1757 		ep->error = 0;
1758 		goto failed_reopen;
1759 	}
1760 	mutex_exit(&rp->r_statelock);
1761 
1762 	/*
1763 	 * argop is empty here
1764 	 *
1765 	 * PUTFH, OPEN, GETATTR
1766 	 */
1767 	args.ctag = TAG_REOPEN;
1768 	args.array_len = 4;
1769 	args.array = argop;
1770 
1771 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1772 	    "nfs4_reopen: file is type %d, id %s",
1773 	    vp->v_type, rnode4info(VTOR4(vp))));
1774 
1775 	argop[0].argop = OP_CPUTFH;
1776 
1777 	if (claim != CLAIM_PREVIOUS) {
1778 		/*
1779 		 * if this is a file mount then
1780 		 * use the mntinfo parentfh
1781 		 */
1782 		argop[0].nfs_argop4_u.opcputfh.sfh =
1783 		    (vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1784 		    VTOSV(vp)->sv_dfh;
1785 	} else {
1786 		/* putfh fh to reopen */
1787 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1788 	}
1789 
1790 	argop[1].argop = OP_COPEN;
1791 	open_args = &argop[1].nfs_argop4_u.opcopen;
1792 	open_args->claim = claim;
1793 
1794 	if (claim == CLAIM_NULL) {
1795 
1796 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1797 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1798 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1799 			    (void *)vp);
1800 			failed_msg = "Couldn't reopen: vtoname failed for "
1801 			    "CLAIM_NULL";
1802 			/* nothing allocated yet */
1803 			goto kill_file;
1804 		}
1805 
1806 		open_args->open_claim4_u.cfile = fn;
1807 	} else if (claim == CLAIM_PREVIOUS) {
1808 
1809 		/*
1810 		 * We have two cases to deal with here:
1811 		 * 1) We're being called to reopen files in order to satisfy
1812 		 *    a lock operation request which requires us to explicitly
1813 		 *    reopen files which were opened under a delegation.  If
1814 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1815 		 *    that case, frc_use_claim_previous is TRUE and we must
1816 		 *    use the rnode's current delegation type (r_deleg_type).
1817 		 * 2) We're reopening files during some form of recovery.
1818 		 *    In this case, frc_use_claim_previous is FALSE and we
1819 		 *    use the delegation type appropriate for recovery
1820 		 *    (r_deleg_needs_recovery).
1821 		 */
1822 		mutex_enter(&rp->r_statev4_lock);
1823 		open_args->open_claim4_u.delegate_type =
1824 		    frc_use_claim_previous ?
1825 		    rp->r_deleg_type :
1826 		    rp->r_deleg_needs_recovery;
1827 		mutex_exit(&rp->r_statev4_lock);
1828 
1829 	} else if (claim == CLAIM_DELEGATE_CUR) {
1830 
1831 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1832 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1833 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1834 			    "with %m", (void *)vp);
1835 			failed_msg = "Couldn't reopen: vtoname failed for "
1836 			    "CLAIM_DELEGATE_CUR";
1837 			/* nothing allocated yet */
1838 			goto kill_file;
1839 		}
1840 
1841 		mutex_enter(&rp->r_statev4_lock);
1842 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1843 		    rp->r_deleg_stateid;
1844 		mutex_exit(&rp->r_statev4_lock);
1845 
1846 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1847 	}
1848 	open_args->opentype = OPEN4_NOCREATE;
1849 	open_args->owner.clientid = mi2clientid(mi);
1850 	open_args->owner.owner_len = sizeof (oop->oo_name);
1851 	open_args->owner.owner_val =
1852 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1853 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1854 	    open_args->owner.owner_len);
1855 	open_args->share_access = 0;
1856 	open_args->share_deny = 0;
1857 
1858 	mutex_enter(&osp->os_sync_lock);
1859 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1860 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1861 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1862 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1863 	    osp->os_share_acc_write, osp->os_open_ref_count,
1864 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1865 
1866 	if (osp->os_share_acc_read || osp->os_mmap_read)
1867 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1868 	if (osp->os_share_acc_write || osp->os_mmap_write)
1869 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1870 	if (osp->os_share_deny_read)
1871 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1872 	if (osp->os_share_deny_write)
1873 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1874 	mutex_exit(&osp->os_sync_lock);
1875 
1876 	seqid = nfs4_get_open_seqid(oop) + 1;
1877 	open_args->seqid = seqid;
1878 
1879 	/* Construct the getfh part of the compound */
1880 	argop[2].argop = OP_GETFH;
1881 
1882 	/* Construct the getattr part of the compound */
1883 	argop[3].argop = OP_GETATTR;
1884 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1885 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1886 
1887 	t = gethrtime();
1888 
1889 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1890 
1891 	if (ep->error) {
1892 		if (!is_recov && !frc_use_claim_previous &&
1893 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1894 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1895 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1896 			    cred_otw, vp, NULL, open_args);
1897 			abort = nfs4_start_recovery(ep,
1898 			    VTOMI4(vp), vp, NULL, NULL,
1899 			    lost_rqst.lr_op == OP_OPEN ?
1900 			    &lost_rqst : NULL, OP_OPEN, NULL);
1901 			nfs4args_copen_free(open_args);
1902 			goto bailout;
1903 		}
1904 
1905 		nfs4args_copen_free(open_args);
1906 
1907 		if (ep->error == EACCES && cred_otw != cr) {
1908 			crfree(cred_otw);
1909 			cred_otw = cr;
1910 			crhold(cred_otw);
1911 			nfs4_end_open_seqid_sync(oop);
1912 			open_owner_rele(oop);
1913 			oop = NULL;
1914 			goto top;
1915 		}
1916 		if (ep->error == ETIMEDOUT)
1917 			goto bailout;
1918 		failed_msg = "Couldn't reopen: rpc error";
1919 		goto kill_file;
1920 	}
1921 
1922 	if (nfs4_need_to_bump_seqid(&res))
1923 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1924 
1925 	switch (res.status) {
1926 	case NFS4_OK:
1927 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1928 			mutex_enter(&rp->r_statelock);
1929 			rp->r_delay_interval = 0;
1930 			mutex_exit(&rp->r_statelock);
1931 		}
1932 		break;
1933 	case NFS4ERR_BAD_SEQID:
1934 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1935 		    args.ctag, open_args->seqid);
1936 
1937 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1938 		    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1939 		    NULL, OP_OPEN, bsep);
1940 
1941 		nfs4args_copen_free(open_args);
1942 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1943 		nfs4_end_open_seqid_sync(oop);
1944 		open_owner_rele(oop);
1945 		oop = NULL;
1946 		kmem_free(bsep, sizeof (*bsep));
1947 
1948 		goto kill_file;
1949 	case NFS4ERR_NO_GRACE:
1950 		nfs4args_copen_free(open_args);
1951 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1952 		nfs4_end_open_seqid_sync(oop);
1953 		open_owner_rele(oop);
1954 		oop = NULL;
1955 		if (claim == CLAIM_PREVIOUS) {
1956 			/*
1957 			 * Retry as a plain open. We don't need to worry about
1958 			 * checking the changeinfo: it is acceptable for a
1959 			 * client to re-open a file and continue processing
1960 			 * (in the absence of locks).
1961 			 */
1962 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1963 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1964 			    "will retry as CLAIM_NULL"));
1965 			claim = CLAIM_NULL;
1966 			nfs4_mi_kstat_inc_no_grace(mi);
1967 			goto top;
1968 		}
1969 		failed_msg =
1970 		    "Couldn't reopen: tried reclaim outside grace period. ";
1971 		goto kill_file;
1972 	case NFS4ERR_GRACE:
1973 		nfs4_set_grace_wait(mi);
1974 		nfs4args_copen_free(open_args);
1975 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1976 		nfs4_end_open_seqid_sync(oop);
1977 		open_owner_rele(oop);
1978 		oop = NULL;
1979 		ep->error = nfs4_wait_for_grace(mi, &recov);
1980 		if (ep->error != 0)
1981 			goto bailout;
1982 		goto top;
1983 	case NFS4ERR_DELAY:
1984 		nfs4_set_delay_wait(vp);
1985 		nfs4args_copen_free(open_args);
1986 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1987 		nfs4_end_open_seqid_sync(oop);
1988 		open_owner_rele(oop);
1989 		oop = NULL;
1990 		ep->error = nfs4_wait_for_delay(vp, &recov);
1991 		nfs4_mi_kstat_inc_delay(mi);
1992 		if (ep->error != 0)
1993 			goto bailout;
1994 		goto top;
1995 	case NFS4ERR_FHEXPIRED:
1996 		/* recover filehandle and retry */
1997 		abort = nfs4_start_recovery(ep,
1998 		    mi, vp, NULL, NULL, NULL, OP_OPEN, NULL);
1999 		nfs4args_copen_free(open_args);
2000 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2001 		nfs4_end_open_seqid_sync(oop);
2002 		open_owner_rele(oop);
2003 		oop = NULL;
2004 		if (abort == FALSE)
2005 			goto top;
2006 		failed_msg = "Couldn't reopen: recovery aborted";
2007 		goto kill_file;
2008 	case NFS4ERR_RESOURCE:
2009 	case NFS4ERR_STALE_CLIENTID:
2010 	case NFS4ERR_WRONGSEC:
2011 	case NFS4ERR_EXPIRED:
2012 		/*
2013 		 * Do not mark the file dead and let the calling
2014 		 * function initiate recovery.
2015 		 */
2016 		nfs4args_copen_free(open_args);
2017 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2018 		nfs4_end_open_seqid_sync(oop);
2019 		open_owner_rele(oop);
2020 		oop = NULL;
2021 		goto bailout;
2022 	case NFS4ERR_ACCESS:
2023 		if (cred_otw != cr) {
2024 			crfree(cred_otw);
2025 			cred_otw = cr;
2026 			crhold(cred_otw);
2027 			nfs4args_copen_free(open_args);
2028 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2029 			nfs4_end_open_seqid_sync(oop);
2030 			open_owner_rele(oop);
2031 			oop = NULL;
2032 			goto top;
2033 		}
2034 		/* fall through */
2035 	default:
2036 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2037 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2038 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2039 		    rnode4info(VTOR4(vp))));
2040 		failed_msg = "Couldn't reopen: NFSv4 error";
2041 		nfs4args_copen_free(open_args);
2042 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2043 		goto kill_file;
2044 	}
2045 
2046 	resop = &res.array[1];  /* open res */
2047 	op_res = &resop->nfs_resop4_u.opopen;
2048 
2049 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2050 
2051 	/*
2052 	 * Check if the path we reopened really is the same
2053 	 * file. We could end up in a situation where the file
2054 	 * was removed and a new file created with the same name.
2055 	 */
2056 	resop = &res.array[2];
2057 	gf_res = &resop->nfs_resop4_u.opgetfh;
2058 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2059 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2060 	if (fh_different) {
2061 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2062 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2063 			/* Oops, we don't have the same file */
2064 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2065 				failed_msg = "Couldn't reopen: Persistent "
2066 				    "file handle changed";
2067 			else
2068 				failed_msg = "Couldn't reopen: Volatile "
2069 				    "(no expire on open) file handle changed";
2070 
2071 			nfs4args_copen_free(open_args);
2072 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2073 			nfs_rw_exit(&mi->mi_fh_lock);
2074 			goto kill_file;
2075 
2076 		} else {
2077 			/*
2078 			 * We have volatile file handles that don't compare.
2079 			 * If the fids are the same then we assume that the
2080 			 * file handle expired but the rnode still refers to
2081 			 * the same file object.
2082 			 *
2083 			 * First check that we have fids or not.
2084 			 * If we don't we have a dumb server so we will
2085 			 * just assume every thing is ok for now.
2086 			 */
2087 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2088 			    rp->r_attr.va_mask & AT_NODEID &&
2089 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2090 				/*
2091 				 * We have fids, but they don't
2092 				 * compare. So kill the file.
2093 				 */
2094 				failed_msg =
2095 				    "Couldn't reopen: file handle changed"
2096 				    " due to mismatched fids";
2097 				nfs4args_copen_free(open_args);
2098 				(void) xdr_free(xdr_COMPOUND4res_clnt,
2099 				    (caddr_t)&res);
2100 				nfs_rw_exit(&mi->mi_fh_lock);
2101 				goto kill_file;
2102 			} else {
2103 				/*
2104 				 * We have volatile file handles that refers
2105 				 * to the same file (at least they have the
2106 				 * same fid) or we don't have fids so we
2107 				 * can't tell. :(. We'll be a kind and accepting
2108 				 * client so we'll update the rnode's file
2109 				 * handle with the otw handle.
2110 				 *
2111 				 * We need to drop mi->mi_fh_lock since
2112 				 * sh4_update acquires it. Since there is
2113 				 * only one recovery thread there is no
2114 				 * race.
2115 				 */
2116 				nfs_rw_exit(&mi->mi_fh_lock);
2117 				sfh4_update(rp->r_fh, &gf_res->object);
2118 			}
2119 		}
2120 	} else {
2121 		nfs_rw_exit(&mi->mi_fh_lock);
2122 	}
2123 
2124 	ASSERT(nfs4_consistent_type(vp));
2125 
2126 	/*
2127 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2128 	 * over.  Presumably if there is a persistent error it will show up
2129 	 * when we resend the OPEN.
2130 	 */
2131 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2132 		bool_t retry_open = FALSE;
2133 
2134 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2135 		    cred_otw, is_recov, &retry_open,
2136 		    oop, FALSE, ep, NULL);
2137 		if (ep->error || ep->stat) {
2138 			nfs4args_copen_free(open_args);
2139 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2140 			nfs4_end_open_seqid_sync(oop);
2141 			open_owner_rele(oop);
2142 			oop = NULL;
2143 			goto top;
2144 		}
2145 	}
2146 
2147 	mutex_enter(&osp->os_sync_lock);
2148 	osp->open_stateid = op_res->stateid;
2149 	osp->os_delegation = 0;
2150 	/*
2151 	 * Need to reset this bitfield for the possible case where we were
2152 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2153 	 * we could retry the CLOSE, OPENed the file again.
2154 	 */
2155 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2156 	osp->os_final_close = 0;
2157 	osp->os_force_close = 0;
2158 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2159 		osp->os_dc_openacc = open_args->share_access;
2160 	mutex_exit(&osp->os_sync_lock);
2161 
2162 	nfs4_end_open_seqid_sync(oop);
2163 
2164 	/* accept delegation, if any */
2165 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2166 
2167 	nfs4args_copen_free(open_args);
2168 
2169 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2170 
2171 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2172 
2173 	ASSERT(nfs4_consistent_type(vp));
2174 
2175 	open_owner_rele(oop);
2176 	crfree(cr);
2177 	crfree(cred_otw);
2178 	return;
2179 
2180 kill_file:
2181 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2182 failed_reopen:
2183 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2184 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2185 	    (void *)osp, (void *)cr, rnode4info(rp)));
2186 	mutex_enter(&osp->os_sync_lock);
2187 	osp->os_failed_reopen = 1;
2188 	mutex_exit(&osp->os_sync_lock);
2189 bailout:
2190 	if (oop != NULL) {
2191 		nfs4_end_open_seqid_sync(oop);
2192 		open_owner_rele(oop);
2193 	}
2194 	if (cr != NULL)
2195 		crfree(cr);
2196 	if (cred_otw != NULL)
2197 		crfree(cred_otw);
2198 }
2199 
2200 /* for . and .. OPENs */
2201 /* ARGSUSED */
2202 static int
2203 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2204 {
2205 	rnode4_t *rp;
2206 	nfs4_ga_res_t gar;
2207 
2208 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2209 
2210 	/*
2211 	 * If close-to-open consistency checking is turned off or
2212 	 * if there is no cached data, we can avoid
2213 	 * the over the wire getattr.  Otherwise, force a
2214 	 * call to the server to get fresh attributes and to
2215 	 * check caches. This is required for close-to-open
2216 	 * consistency.
2217 	 */
2218 	rp = VTOR4(*vpp);
2219 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2220 	    (rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2221 		return (0);
2222 
2223 	gar.n4g_va.va_mask = AT_ALL;
2224 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2225 }
2226 
2227 /*
2228  * CLOSE a file
2229  */
2230 /* ARGSUSED */
2231 static int
2232 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
2233 	caller_context_t *ct)
2234 {
2235 	rnode4_t	*rp;
2236 	int		 error = 0;
2237 	int		 r_error = 0;
2238 	int		 n4error = 0;
2239 	nfs4_error_t	 e = { 0, NFS4_OK, RPC_SUCCESS };
2240 
2241 	/*
2242 	 * Remove client state for this (lockowner, file) pair.
2243 	 * Issue otw v4 call to have the server do the same.
2244 	 */
2245 
2246 	rp = VTOR4(vp);
2247 
2248 	/*
2249 	 * zone_enter(2) prevents processes from changing zones with NFS files
2250 	 * open; if we happen to get here from the wrong zone we can't do
2251 	 * anything over the wire.
2252 	 */
2253 	if (VTOMI4(vp)->mi_zone != nfs_zone()) {
2254 		/*
2255 		 * We could attempt to clean up locks, except we're sure
2256 		 * that the current process didn't acquire any locks on
2257 		 * the file: any attempt to lock a file belong to another zone
2258 		 * will fail, and one can't lock an NFS file and then change
2259 		 * zones, as that fails too.
2260 		 *
2261 		 * Returning an error here is the sane thing to do.  A
2262 		 * subsequent call to VN_RELE() which translates to a
2263 		 * nfs4_inactive() will clean up state: if the zone of the
2264 		 * vnode's origin is still alive and kicking, the inactive
2265 		 * thread will handle the request (from the correct zone), and
2266 		 * everything (minus the OTW close call) should be OK.  If the
2267 		 * zone is going away nfs4_async_inactive() will throw away
2268 		 * delegations, open streams and cached pages inline.
2269 		 */
2270 		return (EIO);
2271 	}
2272 
2273 	/*
2274 	 * If we are using local locking for this filesystem, then
2275 	 * release all of the SYSV style record locks.  Otherwise,
2276 	 * we are doing network locking and we need to release all
2277 	 * of the network locks.  All of the locks held by this
2278 	 * process on this file are released no matter what the
2279 	 * incoming reference count is.
2280 	 */
2281 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK) {
2282 		cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
2283 		cleanshares(vp, ttoproc(curthread)->p_pid);
2284 	} else
2285 		e.error = nfs4_lockrelease(vp, flag, offset, cr);
2286 
2287 	if (e.error) {
2288 		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 && !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 			    INTR(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 && !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 			goto bottom;
2827 		}
2828 
2829 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2830 		base = kmem_alloc(bufsize, KM_SLEEP);
2831 		do {
2832 			if (ioflag & FDSYNC)
2833 				stab_comm = DATA_SYNC4;
2834 			else
2835 				stab_comm = FILE_SYNC4;
2836 			resid = uiop->uio_resid;
2837 			offset = uiop->uio_loffset;
2838 			count = MIN(uiop->uio_resid, bufsize);
2839 			org_offset = uiop->uio_loffset;
2840 			error = uiomove(base, count, UIO_WRITE, uiop);
2841 			if (!error) {
2842 				error = nfs4write(vp, base, org_offset,
2843 				    count, cr, &stab_comm);
2844 				if (!error) {
2845 					mutex_enter(&rp->r_statelock);
2846 					if (rp->r_size < uiop->uio_loffset)
2847 						rp->r_size = uiop->uio_loffset;
2848 					mutex_exit(&rp->r_statelock);
2849 				}
2850 			}
2851 		} while (!error && uiop->uio_resid > 0);
2852 		kmem_free(base, bufsize);
2853 		goto bottom;
2854 	}
2855 
2856 	bsize = vp->v_vfsp->vfs_bsize;
2857 
2858 	do {
2859 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2860 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2861 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2862 
2863 		resid = uiop->uio_resid;
2864 		offset = uiop->uio_loffset;
2865 
2866 		if (rp->r_flags & R4STALE) {
2867 			error = rp->r_error;
2868 			break;
2869 		}
2870 
2871 		/*
2872 		 * Don't create dirty pages faster than they
2873 		 * can be cleaned so that the system doesn't
2874 		 * get imbalanced.  If the async queue is
2875 		 * maxed out, then wait for it to drain before
2876 		 * creating more dirty pages.  Also, wait for
2877 		 * any threads doing pagewalks in the vop_getattr
2878 		 * entry points so that they don't block for
2879 		 * long periods.
2880 		 */
2881 		mutex_enter(&rp->r_statelock);
2882 		while ((mi->mi_max_threads != 0 &&
2883 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2884 		    rp->r_gcount > 0)
2885 			cv_wait(&rp->r_cv, &rp->r_statelock);
2886 		mutex_exit(&rp->r_statelock);
2887 
2888 		if (vpm_enable) {
2889 			/*
2890 			 * It will use kpm mappings, so no need to
2891 			 * pass an address.
2892 			 */
2893 			error = writerp4(rp, NULL, n, uiop, 0);
2894 		} else  {
2895 			if (segmap_kpm) {
2896 				int pon = uiop->uio_loffset & PAGEOFFSET;
2897 				size_t pn = MIN(PAGESIZE - pon,
2898 				    uiop->uio_resid);
2899 				int pagecreate;
2900 
2901 				mutex_enter(&rp->r_statelock);
2902 				pagecreate = (pon == 0) && (pn == PAGESIZE ||
2903 				    uiop->uio_loffset + pn >= rp->r_size);
2904 				mutex_exit(&rp->r_statelock);
2905 
2906 				base = segmap_getmapflt(segkmap, vp, off + on,
2907 				    pn, !pagecreate, S_WRITE);
2908 
2909 				error = writerp4(rp, base + pon, n, uiop,
2910 				    pagecreate);
2911 
2912 			} else {
2913 				base = segmap_getmapflt(segkmap, vp, off + on,
2914 				    n, 0, S_READ);
2915 				error = writerp4(rp, base + on, n, uiop, 0);
2916 			}
2917 		}
2918 
2919 		if (!error) {
2920 			if (mi->mi_flags & MI4_NOAC)
2921 				flags = SM_WRITE;
2922 			else if ((uiop->uio_loffset % bsize) == 0 ||
2923 			    IS_SWAPVP(vp)) {
2924 				/*
2925 				 * Have written a whole block.
2926 				 * Start an asynchronous write
2927 				 * and mark the buffer to
2928 				 * indicate that it won't be
2929 				 * needed again soon.
2930 				 */
2931 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
2932 			} else
2933 				flags = 0;
2934 			if ((ioflag & (FSYNC|FDSYNC)) ||
2935 			    (rp->r_flags & R4OUTOFSPACE)) {
2936 				flags &= ~SM_ASYNC;
2937 				flags |= SM_WRITE;
2938 			}
2939 			if (vpm_enable) {
2940 				error = vpm_sync_pages(vp, off, n, flags);
2941 			} else {
2942 				error = segmap_release(segkmap, base, flags);
2943 			}
2944 		} else {
2945 			if (vpm_enable) {
2946 				(void) vpm_sync_pages(vp, off, n, 0);
2947 			} else {
2948 				(void) segmap_release(segkmap, base, 0);
2949 			}
2950 			/*
2951 			 * In the event that we got an access error while
2952 			 * faulting in a page for a write-only file just
2953 			 * force a write.
2954 			 */
2955 			if (error == EACCES)
2956 				goto nfs4_fwrite;
2957 		}
2958 	} while (!error && uiop->uio_resid > 0);
2959 
2960 bottom:
2961 	if (error) {
2962 		uiop->uio_resid = resid + remainder;
2963 		uiop->uio_loffset = offset;
2964 	} else {
2965 		uiop->uio_resid += remainder;
2966 
2967 		mutex_enter(&rp->r_statev4_lock);
2968 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
2969 			gethrestime(&rp->r_attr.va_mtime);
2970 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
2971 		}
2972 		mutex_exit(&rp->r_statev4_lock);
2973 	}
2974 
2975 	nfs_rw_exit(&rp->r_lkserlock);
2976 
2977 	return (error);
2978 }
2979 
2980 /*
2981  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
2982  */
2983 static int
2984 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
2985     int flags, cred_t *cr)
2986 {
2987 	struct buf *bp;
2988 	int error;
2989 	page_t *savepp;
2990 	uchar_t fsdata;
2991 	stable_how4 stab_comm;
2992 
2993 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
2994 	bp = pageio_setup(pp, len, vp, flags);
2995 	ASSERT(bp != NULL);
2996 
2997 	/*
2998 	 * pageio_setup should have set b_addr to 0.  This
2999 	 * is correct since we want to do I/O on a page
3000 	 * boundary.  bp_mapin will use this addr to calculate
3001 	 * an offset, and then set b_addr to the kernel virtual
3002 	 * address it allocated for us.
3003 	 */
3004 	ASSERT(bp->b_un.b_addr == 0);
3005 
3006 	bp->b_edev = 0;
3007 	bp->b_dev = 0;
3008 	bp->b_lblkno = lbtodb(off);
3009 	bp->b_file = vp;
3010 	bp->b_offset = (offset_t)off;
3011 	bp_mapin(bp);
3012 
3013 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
3014 	    freemem > desfree)
3015 		stab_comm = UNSTABLE4;
3016 	else
3017 		stab_comm = FILE_SYNC4;
3018 
3019 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
3020 
3021 	bp_mapout(bp);
3022 	pageio_done(bp);
3023 
3024 	if (stab_comm == UNSTABLE4)
3025 		fsdata = C_DELAYCOMMIT;
3026 	else
3027 		fsdata = C_NOCOMMIT;
3028 
3029 	savepp = pp;
3030 	do {
3031 		pp->p_fsdata = fsdata;
3032 	} while ((pp = pp->p_next) != savepp);
3033 
3034 	return (error);
3035 }
3036 
3037 /*
3038  */
3039 static int
3040 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
3041 {
3042 	nfs4_open_owner_t	*oop;
3043 	nfs4_open_stream_t	*osp;
3044 	rnode4_t		*rp = VTOR4(vp);
3045 	mntinfo4_t 		*mi = VTOMI4(vp);
3046 	int 			reopen_needed;
3047 
3048 	ASSERT(nfs_zone() == mi->mi_zone);
3049 
3050 
3051 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
3052 	if (!oop)
3053 		return (EIO);
3054 
3055 	/* returns with 'os_sync_lock' held */
3056 	osp = find_open_stream(oop, rp);
3057 	if (!osp) {
3058 		open_owner_rele(oop);
3059 		return (EIO);
3060 	}
3061 
3062 	if (osp->os_failed_reopen) {
3063 		mutex_exit(&osp->os_sync_lock);
3064 		open_stream_rele(osp, rp);
3065 		open_owner_rele(oop);
3066 		return (EIO);
3067 	}
3068 
3069 	/*
3070 	 * Determine whether a reopen is needed.  If this
3071 	 * is a delegation open stream, then the os_delegation bit
3072 	 * should be set.
3073 	 */
3074 
3075 	reopen_needed = osp->os_delegation;
3076 
3077 	mutex_exit(&osp->os_sync_lock);
3078 	open_owner_rele(oop);
3079 
3080 	if (reopen_needed) {
3081 		nfs4_error_zinit(ep);
3082 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
3083 		mutex_enter(&osp->os_sync_lock);
3084 		if (ep->error || ep->stat || osp->os_failed_reopen) {
3085 			mutex_exit(&osp->os_sync_lock);
3086 			open_stream_rele(osp, rp);
3087 			return (EIO);
3088 		}
3089 		mutex_exit(&osp->os_sync_lock);
3090 	}
3091 	open_stream_rele(osp, rp);
3092 
3093 	return (0);
3094 }
3095 
3096 /*
3097  * Write to file.  Writes to remote server in largest size
3098  * chunks that the server can handle.  Write is synchronous.
3099  */
3100 static int
3101 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3102     stable_how4 *stab_comm)
3103 {
3104 	mntinfo4_t *mi;
3105 	COMPOUND4args_clnt args;
3106 	COMPOUND4res_clnt res;
3107 	WRITE4args *wargs;
3108 	WRITE4res *wres;
3109 	nfs_argop4 argop[2];
3110 	nfs_resop4 *resop;
3111 	int tsize;
3112 	stable_how4 stable;
3113 	rnode4_t *rp;
3114 	int doqueue = 1;
3115 	bool_t needrecov;
3116 	nfs4_recov_state_t recov_state;
3117 	nfs4_stateid_types_t sid_types;
3118 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3119 	int recov;
3120 
3121 	rp = VTOR4(vp);
3122 	mi = VTOMI4(vp);
3123 
3124 	ASSERT(nfs_zone() == mi->mi_zone);
3125 
3126 	stable = *stab_comm;
3127 	*stab_comm = FILE_SYNC4;
3128 
3129 	needrecov = FALSE;
3130 	recov_state.rs_flags = 0;
3131 	recov_state.rs_num_retry_despite_err = 0;
3132 	nfs4_init_stateid_types(&sid_types);
3133 
3134 	/* Is curthread the recovery thread? */
3135 	mutex_enter(&mi->mi_lock);
3136 	recov = (mi->mi_recovthread == curthread);
3137 	mutex_exit(&mi->mi_lock);
3138 
3139 recov_retry:
3140 	args.ctag = TAG_WRITE;
3141 	args.array_len = 2;
3142 	args.array = argop;
3143 
3144 	if (!recov) {
3145 		e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3146 		    &recov_state, NULL);
3147 		if (e.error)
3148 			return (e.error);
3149 	}
3150 
3151 	/* 0. putfh target fh */
3152 	argop[0].argop = OP_CPUTFH;
3153 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3154 
3155 	/* 1. write */
3156 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3157 
3158 	do {
3159 
3160 		wargs->offset = (offset4)offset;
3161 		wargs->data_val = base;
3162 
3163 		if (mi->mi_io_kstats) {
3164 			mutex_enter(&mi->mi_lock);
3165 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3166 			mutex_exit(&mi->mi_lock);
3167 		}
3168 
3169 		if ((vp->v_flag & VNOCACHE) ||
3170 		    (rp->r_flags & R4DIRECTIO) ||
3171 		    (mi->mi_flags & MI4_DIRECTIO))
3172 			tsize = MIN(mi->mi_stsize, count);
3173 		else
3174 			tsize = MIN(mi->mi_curwrite, count);
3175 		wargs->data_len = (uint_t)tsize;
3176 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3177 
3178 		if (mi->mi_io_kstats) {
3179 			mutex_enter(&mi->mi_lock);
3180 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3181 			mutex_exit(&mi->mi_lock);
3182 		}
3183 
3184 		if (!recov) {
3185 			needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3186 			if (e.error && !needrecov) {
3187 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3188 				    &recov_state, needrecov);
3189 				return (e.error);
3190 			}
3191 		} else {
3192 			if (e.error)
3193 				return (e.error);
3194 		}
3195 
3196 		/*
3197 		 * Do handling of OLD_STATEID outside
3198 		 * of the normal recovery framework.
3199 		 *
3200 		 * If write receives a BAD stateid error while using a
3201 		 * delegation stateid, retry using the open stateid (if it
3202 		 * exists).  If it doesn't have an open stateid, reopen the
3203 		 * file first, then retry.
3204 		 */
3205 		if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3206 		    sid_types.cur_sid_type != SPEC_SID) {
3207 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3208 			if (!recov)
3209 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3210 				    &recov_state, needrecov);
3211 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3212 			goto recov_retry;
3213 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3214 		    sid_types.cur_sid_type == DEL_SID) {
3215 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3216 			mutex_enter(&rp->r_statev4_lock);
3217 			rp->r_deleg_return_pending = TRUE;
3218 			mutex_exit(&rp->r_statev4_lock);
3219 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3220 				if (!recov)
3221 					nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3222 					    &recov_state, needrecov);
3223 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3224 				    (caddr_t)&res);
3225 				return (EIO);
3226 			}
3227 			if (!recov)
3228 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3229 				    &recov_state, needrecov);
3230 			/* hold needed for nfs4delegreturn_thread */
3231 			VN_HOLD(vp);
3232 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3233 			    NFS4_DR_DISCARD), FALSE);
3234 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3235 			goto recov_retry;
3236 		}
3237 
3238 		if (needrecov) {
3239 			bool_t abort;
3240 
3241 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3242 			    "nfs4write: client got error %d, res.status %d"
3243 			    ", so start recovery", e.error, res.status));
3244 
3245 			abort = nfs4_start_recovery(&e,
3246 			    VTOMI4(vp), vp, NULL, &wargs->stateid,
3247 			    NULL, OP_WRITE, NULL);
3248 			if (!e.error) {
3249 				e.error = geterrno4(res.status);
3250 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3251 				    (caddr_t)&res);
3252 			}
3253 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3254 			    &recov_state, needrecov);
3255 			if (abort == FALSE)
3256 				goto recov_retry;
3257 			return (e.error);
3258 		}
3259 
3260 		if (res.status) {
3261 			e.error = geterrno4(res.status);
3262 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3263 			if (!recov)
3264 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3265 				    &recov_state, needrecov);
3266 			return (e.error);
3267 		}
3268 
3269 		resop = &res.array[1];	/* write res */
3270 		wres = &resop->nfs_resop4_u.opwrite;
3271 
3272 		if ((int)wres->count > tsize) {
3273 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3274 
3275 			zcmn_err(getzoneid(), CE_WARN,
3276 			    "nfs4write: server wrote %u, requested was %u",
3277 			    (int)wres->count, tsize);
3278 			if (!recov)
3279 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3280 				    &recov_state, needrecov);
3281 			return (EIO);
3282 		}
3283 		if (wres->committed == UNSTABLE4) {
3284 			*stab_comm = UNSTABLE4;
3285 			if (wargs->stable == DATA_SYNC4 ||
3286 			    wargs->stable == FILE_SYNC4) {
3287 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3288 				    (caddr_t)&res);
3289 				zcmn_err(getzoneid(), CE_WARN,
3290 				    "nfs4write: server %s did not commit "
3291 				    "to stable storage",
3292 				    rp->r_server->sv_hostname);
3293 				if (!recov)
3294 					nfs4_end_fop(VTOMI4(vp), vp, NULL,
3295 					    OH_WRITE, &recov_state, needrecov);
3296 				return (EIO);
3297 			}
3298 		}
3299 
3300 		tsize = (int)wres->count;
3301 		count -= tsize;
3302 		base += tsize;
3303 		offset += tsize;
3304 		if (mi->mi_io_kstats) {
3305 			mutex_enter(&mi->mi_lock);
3306 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3307 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3308 			    tsize;
3309 			mutex_exit(&mi->mi_lock);
3310 		}
3311 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3312 		mutex_enter(&rp->r_statelock);
3313 		if (rp->r_flags & R4HAVEVERF) {
3314 			if (rp->r_writeverf != wres->writeverf) {
3315 				nfs4_set_mod(vp);
3316 				rp->r_writeverf = wres->writeverf;
3317 			}
3318 		} else {
3319 			rp->r_writeverf = wres->writeverf;
3320 			rp->r_flags |= R4HAVEVERF;
3321 		}
3322 		PURGE_ATTRCACHE4_LOCKED(rp);
3323 		rp->r_flags |= R4WRITEMODIFIED;
3324 		gethrestime(&rp->r_attr.va_mtime);
3325 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3326 		mutex_exit(&rp->r_statelock);
3327 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3328 	} while (count);
3329 
3330 	if (!recov)
3331 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state,
3332 		    needrecov);
3333 
3334 	return (e.error);
3335 }
3336 
3337 /*
3338  * Read from a file.  Reads data in largest chunks our interface can handle.
3339  */
3340 static int
3341 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3342     size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3343 {
3344 	mntinfo4_t *mi;
3345 	COMPOUND4args_clnt args;
3346 	COMPOUND4res_clnt res;
3347 	READ4args *rargs;
3348 	nfs_argop4 argop[2];
3349 	int tsize;
3350 	int doqueue;
3351 	rnode4_t *rp;
3352 	int data_len;
3353 	bool_t is_eof;
3354 	bool_t needrecov = FALSE;
3355 	nfs4_recov_state_t recov_state;
3356 	nfs4_stateid_types_t sid_types;
3357 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3358 
3359 	rp = VTOR4(vp);
3360 	mi = VTOMI4(vp);
3361 	doqueue = 1;
3362 
3363 	ASSERT(nfs_zone() == mi->mi_zone);
3364 
3365 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3366 
3367 	args.array_len = 2;
3368 	args.array = argop;
3369 
3370 	nfs4_init_stateid_types(&sid_types);
3371 
3372 	recov_state.rs_flags = 0;
3373 	recov_state.rs_num_retry_despite_err = 0;
3374 
3375 recov_retry:
3376 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3377 	    &recov_state, NULL);
3378 	if (e.error)
3379 		return (e.error);
3380 
3381 	/* putfh target fh */
3382 	argop[0].argop = OP_CPUTFH;
3383 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3384 
3385 	/* read */
3386 	argop[1].argop = OP_READ;
3387 	rargs = &argop[1].nfs_argop4_u.opread;
3388 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3389 	    OP_READ, &sid_types, async);
3390 
3391 	do {
3392 		if (mi->mi_io_kstats) {
3393 			mutex_enter(&mi->mi_lock);
3394 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3395 			mutex_exit(&mi->mi_lock);
3396 		}
3397 
3398 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3399 		    "nfs4read: %s call, rp %s",
3400 		    needrecov ? "recov" : "first",
3401 		    rnode4info(rp)));
3402 
3403 		if ((vp->v_flag & VNOCACHE) ||
3404 		    (rp->r_flags & R4DIRECTIO) ||
3405 		    (mi->mi_flags & MI4_DIRECTIO))
3406 			tsize = MIN(mi->mi_tsize, count);
3407 		else
3408 			tsize = MIN(mi->mi_curread, count);
3409 
3410 		rargs->offset = (offset4)offset;
3411 		rargs->count = (count4)tsize;
3412 		rargs->res_data_val_alt = NULL;
3413 		rargs->res_mblk = NULL;
3414 		rargs->res_uiop = NULL;
3415 		rargs->res_maxsize = 0;
3416 		rargs->wlist = NULL;
3417 
3418 		if (uiop)
3419 			rargs->res_uiop = uiop;
3420 		else
3421 			rargs->res_data_val_alt = base;
3422 		rargs->res_maxsize = tsize;
3423 
3424 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3425 #ifdef	DEBUG
3426 		if (nfs4read_error_inject) {
3427 			res.status = nfs4read_error_inject;
3428 			nfs4read_error_inject = 0;
3429 		}
3430 #endif
3431 
3432 		if (mi->mi_io_kstats) {
3433 			mutex_enter(&mi->mi_lock);
3434 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3435 			mutex_exit(&mi->mi_lock);
3436 		}
3437 
3438 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3439 		if (e.error != 0 && !needrecov) {
3440 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3441 			    &recov_state, needrecov);
3442 			return (e.error);
3443 		}
3444 
3445 		/*
3446 		 * Do proper retry for OLD and BAD stateid errors outside
3447 		 * of the normal recovery framework.  There are two differences
3448 		 * between async and sync reads.  The first is that we allow
3449 		 * retry on BAD_STATEID for async reads, but not sync reads.
3450 		 * The second is that we mark the file dead for a failed
3451 		 * attempt with a special stateid for sync reads, but just
3452 		 * return EIO for async reads.
3453 		 *
3454 		 * If a sync read receives a BAD stateid error while using a
3455 		 * delegation stateid, retry using the open stateid (if it
3456 		 * exists).  If it doesn't have an open stateid, reopen the
3457 		 * file first, then retry.
3458 		 */
3459 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3460 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3461 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3462 			    &recov_state, needrecov);
3463 			if (sid_types.cur_sid_type == SPEC_SID) {
3464 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3465 				    (caddr_t)&res);
3466 				return (EIO);
3467 			}
3468 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3469 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3470 			goto recov_retry;
3471 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3472 		    !async && sid_types.cur_sid_type != SPEC_SID) {
3473 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3474 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3475 			    &recov_state, needrecov);
3476 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3477 			goto recov_retry;
3478 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3479 		    sid_types.cur_sid_type == DEL_SID) {
3480 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3481 			mutex_enter(&rp->r_statev4_lock);
3482 			rp->r_deleg_return_pending = TRUE;
3483 			mutex_exit(&rp->r_statev4_lock);
3484 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3485 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3486 				    &recov_state, needrecov);
3487 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3488 				    (caddr_t)&res);
3489 				return (EIO);
3490 			}
3491 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3492 			    &recov_state, needrecov);
3493 			/* hold needed for nfs4delegreturn_thread */
3494 			VN_HOLD(vp);
3495 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3496 			    NFS4_DR_DISCARD), FALSE);
3497 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3498 			goto recov_retry;
3499 		}
3500 		if (needrecov) {
3501 			bool_t abort;
3502 
3503 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3504 			    "nfs4read: initiating recovery\n"));
3505 			abort = nfs4_start_recovery(&e,
3506 			    mi, vp, NULL, &rargs->stateid,
3507 			    NULL, OP_READ, NULL);
3508 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3509 			    &recov_state, needrecov);
3510 			/*
3511 			 * Do not retry if we got OLD_STATEID using a special
3512 			 * stateid.  This avoids looping with a broken server.
3513 			 */
3514 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3515 			    sid_types.cur_sid_type == SPEC_SID)
3516 				abort = TRUE;
3517 
3518 			if (abort == FALSE) {
3519 				/*
3520 				 * Need to retry all possible stateids in
3521 				 * case the recovery error wasn't stateid
3522 				 * related or the stateids have become
3523 				 * stale (server reboot).
3524 				 */
3525 				nfs4_init_stateid_types(&sid_types);
3526 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3527 				    (caddr_t)&res);
3528 				goto recov_retry;
3529 			}
3530 
3531 			if (!e.error) {
3532 				e.error = geterrno4(res.status);
3533 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3534 				    (caddr_t)&res);
3535 			}
3536 			return (e.error);
3537 		}
3538 
3539 		if (res.status) {
3540 			e.error = geterrno4(res.status);
3541 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3542 			    &recov_state, needrecov);
3543 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3544 			return (e.error);
3545 		}
3546 
3547 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3548 		count -= data_len;
3549 		if (base)
3550 			base += data_len;
3551 		offset += data_len;
3552 		if (mi->mi_io_kstats) {
3553 			mutex_enter(&mi->mi_lock);
3554 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3555 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3556 			mutex_exit(&mi->mi_lock);
3557 		}
3558 		lwp_stat_update(LWP_STAT_INBLK, 1);
3559 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3560 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3561 
3562 	} while (count && !is_eof);
3563 
3564 	*residp = count;
3565 
3566 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3567 
3568 	return (e.error);
3569 }
3570 
3571 /* ARGSUSED */
3572 static int
3573 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp,
3574 	caller_context_t *ct)
3575 {
3576 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3577 		return (EIO);
3578 	switch (cmd) {
3579 		case _FIODIRECTIO:
3580 			return (nfs4_directio(vp, (int)arg, cr));
3581 		default:
3582 			return (ENOTTY);
3583 	}
3584 }
3585 
3586 /* ARGSUSED */
3587 int
3588 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3589     caller_context_t *ct)
3590 {
3591 	int error;
3592 	rnode4_t *rp = VTOR4(vp);
3593 
3594 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3595 		return (EIO);
3596 	/*
3597 	 * If it has been specified that the return value will
3598 	 * just be used as a hint, and we are only being asked
3599 	 * for size, fsid or rdevid, then return the client's
3600 	 * notion of these values without checking to make sure
3601 	 * that the attribute cache is up to date.
3602 	 * The whole point is to avoid an over the wire GETATTR
3603 	 * call.
3604 	 */
3605 	if (flags & ATTR_HINT) {
3606 		if (vap->va_mask ==
3607 		    (vap->va_mask & (AT_SIZE | AT_FSID | AT_RDEV))) {
3608 			mutex_enter(&rp->r_statelock);
3609 			if (vap->va_mask | AT_SIZE)
3610 				vap->va_size = rp->r_size;
3611 			if (vap->va_mask | AT_FSID)
3612 				vap->va_fsid = rp->r_attr.va_fsid;
3613 			if (vap->va_mask | AT_RDEV)
3614 				vap->va_rdev = rp->r_attr.va_rdev;
3615 			mutex_exit(&rp->r_statelock);
3616 			return (0);
3617 		}
3618 	}
3619 
3620 	/*
3621 	 * Only need to flush pages if asking for the mtime
3622 	 * and if there any dirty pages or any outstanding
3623 	 * asynchronous (write) requests for this file.
3624 	 */
3625 	if (vap->va_mask & AT_MTIME) {
3626 		rp = VTOR4(vp);
3627 		if (nfs4_has_pages(vp)) {
3628 			mutex_enter(&rp->r_statev4_lock);
3629 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3630 				mutex_exit(&rp->r_statev4_lock);
3631 				if (rp->r_flags & R4DIRTY ||
3632 				    rp->r_awcount > 0) {
3633 					mutex_enter(&rp->r_statelock);
3634 					rp->r_gcount++;
3635 					mutex_exit(&rp->r_statelock);
3636 					error =
3637 					    nfs4_putpage(vp, (u_offset_t)0,
3638 					    0, 0, cr, NULL);
3639 					mutex_enter(&rp->r_statelock);
3640 					if (error && (error == ENOSPC ||
3641 					    error == EDQUOT)) {
3642 						if (!rp->r_error)
3643 							rp->r_error = error;
3644 					}
3645 					if (--rp->r_gcount == 0)
3646 						cv_broadcast(&rp->r_cv);
3647 					mutex_exit(&rp->r_statelock);
3648 				}
3649 			} else {
3650 				mutex_exit(&rp->r_statev4_lock);
3651 			}
3652 		}
3653 	}
3654 	return (nfs4getattr(vp, vap, cr));
3655 }
3656 
3657 int
3658 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3659 {
3660 	/*
3661 	 * If these are the only two bits cleared
3662 	 * on the server then return 0 (OK) else
3663 	 * return 1 (BAD).
3664 	 */
3665 	on_client &= ~(S_ISUID|S_ISGID);
3666 	if (on_client == from_server)
3667 		return (0);
3668 	else
3669 		return (1);
3670 }
3671 
3672 /*ARGSUSED4*/
3673 static int
3674 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3675     caller_context_t *ct)
3676 {
3677 	if (vap->va_mask & AT_NOSET)
3678 		return (EINVAL);
3679 
3680 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3681 		return (EIO);
3682 
3683 	/*
3684 	 * Don't call secpolicy_vnode_setattr, the client cannot
3685 	 * use its cached attributes to make security decisions
3686 	 * as the server may be faking mode bits or mapping uid/gid.
3687 	 * Always just let the server to the checking.
3688 	 * If we provide the ability to remove basic priviledges
3689 	 * to setattr (e.g. basic without chmod) then we will
3690 	 * need to add a check here before calling the server.
3691 	 */
3692 
3693 	return (nfs4setattr(vp, vap, flags, cr, NULL));
3694 }
3695 
3696 /*
3697  * To replace the "guarded" version 3 setattr, we use two types of compound
3698  * setattr requests:
3699  * 1. The "normal" setattr, used when the size of the file isn't being
3700  *    changed - { Putfh <fh>; Setattr; Getattr }/
3701  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3702  *    with only ctime as the argument. If the server ctime differs from
3703  *    what is cached on the client, the verify will fail, but we would
3704  *    already have the ctime from the preceding getattr, so just set it
3705  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3706  *	Setattr; Getattr }.
3707  *
3708  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3709  * this setattr and NULL if they are not.
3710  */
3711 static int
3712 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3713     vsecattr_t *vsap)
3714 {
3715 	COMPOUND4args_clnt args;
3716 	COMPOUND4res_clnt res, *resp = NULL;
3717 	nfs4_ga_res_t *garp = NULL;
3718 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3719 	nfs_argop4 argop[5];
3720 	int verify_argop = -1;
3721 	int setattr_argop = 1;
3722 	nfs_resop4 *resop;
3723 	vattr_t va;
3724 	rnode4_t *rp;
3725 	int doqueue = 1;
3726 	uint_t mask = vap->va_mask;
3727 	mode_t omode;
3728 	vsecattr_t *vsp;
3729 	timestruc_t ctime;
3730 	bool_t needrecov = FALSE;
3731 	nfs4_recov_state_t recov_state;
3732 	nfs4_stateid_types_t sid_types;
3733 	stateid4 stateid;
3734 	hrtime_t t;
3735 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3736 	servinfo4_t *svp;
3737 	bitmap4 supp_attrs;
3738 
3739 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3740 	rp = VTOR4(vp);
3741 	nfs4_init_stateid_types(&sid_types);
3742 
3743 	/*
3744 	 * Only need to flush pages if there are any pages and
3745 	 * if the file is marked as dirty in some fashion.  The
3746 	 * file must be flushed so that we can accurately
3747 	 * determine the size of the file and the cached data
3748 	 * after the SETATTR returns.  A file is considered to
3749 	 * be dirty if it is either marked with R4DIRTY, has
3750 	 * outstanding i/o's active, or is mmap'd.  In this
3751 	 * last case, we can't tell whether there are dirty
3752 	 * pages, so we flush just to be sure.
3753 	 */
3754 	if (nfs4_has_pages(vp) &&
3755 	    ((rp->r_flags & R4DIRTY) ||
3756 	    rp->r_count > 0 ||
3757 	    rp->r_mapcnt > 0)) {
3758 		ASSERT(vp->v_type != VCHR);
3759 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr, NULL);
3760 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3761 			mutex_enter(&rp->r_statelock);
3762 			if (!rp->r_error)
3763 				rp->r_error = e.error;
3764 			mutex_exit(&rp->r_statelock);
3765 		}
3766 	}
3767 
3768 	if (mask & AT_SIZE) {
3769 		/*
3770 		 * Verification setattr compound for non-deleg AT_SIZE:
3771 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3772 		 * Set ctime local here (outside the do_again label)
3773 		 * so that subsequent retries (after failed VERIFY)
3774 		 * will use ctime from GETATTR results (from failed
3775 		 * verify compound) as VERIFY arg.
3776 		 * If file has delegation, then VERIFY(time_metadata)
3777 		 * is of little added value, so don't bother.
3778 		 */
3779 		mutex_enter(&rp->r_statev4_lock);
3780 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3781 		    rp->r_deleg_return_pending) {
3782 			numops = 5;
3783 			ctime = rp->r_attr.va_ctime;
3784 		}
3785 		mutex_exit(&rp->r_statev4_lock);
3786 	}
3787 
3788 	recov_state.rs_flags = 0;
3789 	recov_state.rs_num_retry_despite_err = 0;
3790 
3791 	args.ctag = TAG_SETATTR;
3792 do_again:
3793 recov_retry:
3794 	setattr_argop = numops - 2;
3795 
3796 	args.array = argop;
3797 	args.array_len = numops;
3798 
3799 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3800 	if (e.error)
3801 		return (e.error);
3802 
3803 
3804 	/* putfh target fh */
3805 	argop[0].argop = OP_CPUTFH;
3806 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3807 
3808 	if (numops == 5) {
3809 		/*
3810 		 * We only care about the ctime, but need to get mtime
3811 		 * and size for proper cache update.
3812 		 */
3813 		/* getattr */
3814 		argop[1].argop = OP_GETATTR;
3815 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3816 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3817 
3818 		/* verify - set later in loop */
3819 		verify_argop = 2;
3820 	}
3821 
3822 	/* setattr */
3823 	svp = rp->r_server;
3824 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3825 	supp_attrs = svp->sv_supp_attrs;
3826 	nfs_rw_exit(&svp->sv_lock);
3827 
3828 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3829 	    supp_attrs, &e.error, &sid_types);
3830 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3831 	if (e.error) {
3832 		/* req time field(s) overflow - return immediately */
3833 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3834 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3835 		    opsetattr.obj_attributes);
3836 		return (e.error);
3837 	}
3838 	omode = rp->r_attr.va_mode;
3839 
3840 	/* getattr */
3841 	argop[numops-1].argop = OP_GETATTR;
3842 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3843 	/*
3844 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3845 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3846 	 * used in updating the ACL cache.
3847 	 */
3848 	if (vsap != NULL)
3849 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3850 		    FATTR4_ACL_MASK;
3851 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3852 
3853 	/*
3854 	 * setattr iterates if the object size is set and the cached ctime
3855 	 * does not match the file ctime. In that case, verify the ctime first.
3856 	 */
3857 
3858 	do {
3859 		if (verify_argop != -1) {
3860 			/*
3861 			 * Verify that the ctime match before doing setattr.
3862 			 */
3863 			va.va_mask = AT_CTIME;
3864 			va.va_ctime = ctime;
3865 			svp = rp->r_server;
3866 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3867 			supp_attrs = svp->sv_supp_attrs;
3868 			nfs_rw_exit(&svp->sv_lock);
3869 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3870 			    OP_VERIFY, supp_attrs);
3871 			if (e.error) {
3872 				/* req time field(s) overflow - return */
3873 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3874 				    needrecov);
3875 				break;
3876 			}
3877 		}
3878 
3879 		doqueue = 1;
3880 
3881 		t = gethrtime();
3882 
3883 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3884 
3885 		/*
3886 		 * Purge the access cache and ACL cache if changing either the
3887 		 * owner of the file, the group owner, or the mode.  These may
3888 		 * change the access permissions of the file, so purge old
3889 		 * information and start over again.
3890 		 */
3891 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3892 			(void) nfs4_access_purge_rp(rp);
3893 			if (rp->r_secattr != NULL) {
3894 				mutex_enter(&rp->r_statelock);
3895 				vsp = rp->r_secattr;
3896 				rp->r_secattr = NULL;
3897 				mutex_exit(&rp->r_statelock);
3898 				if (vsp != NULL)
3899 					nfs4_acl_free_cache(vsp);
3900 			}
3901 		}
3902 
3903 		/*
3904 		 * If res.array_len == numops, then everything succeeded,
3905 		 * except for possibly the final getattr.  If only the
3906 		 * last getattr failed, give up, and don't try recovery.
3907 		 */
3908 		if (res.array_len == numops) {
3909 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3910 			    needrecov);
3911 			if (! e.error)
3912 				resp = &res;
3913 			break;
3914 		}
3915 
3916 		/*
3917 		 * if either rpc call failed or completely succeeded - done
3918 		 */
3919 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
3920 		if (e.error) {
3921 			PURGE_ATTRCACHE4(vp);
3922 			if (!needrecov) {
3923 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3924 				    needrecov);
3925 				break;
3926 			}
3927 		}
3928 
3929 		/*
3930 		 * Do proper retry for OLD_STATEID outside of the normal
3931 		 * recovery framework.
3932 		 */
3933 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3934 		    sid_types.cur_sid_type != SPEC_SID &&
3935 		    sid_types.cur_sid_type != NO_SID) {
3936 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3937 			    needrecov);
3938 			nfs4_save_stateid(&stateid, &sid_types);
3939 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3940 			    opsetattr.obj_attributes);
3941 			if (verify_argop != -1) {
3942 				nfs4args_verify_free(&argop[verify_argop]);
3943 				verify_argop = -1;
3944 			}
3945 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3946 			goto recov_retry;
3947 		}
3948 
3949 		if (needrecov) {
3950 			bool_t abort;
3951 
3952 			abort = nfs4_start_recovery(&e,
3953 			    VTOMI4(vp), vp, NULL, NULL, NULL,
3954 			    OP_SETATTR, NULL);
3955 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3956 			    needrecov);
3957 			/*
3958 			 * Do not retry if we failed with OLD_STATEID using
3959 			 * a special stateid.  This is done to avoid looping
3960 			 * with a broken server.
3961 			 */
3962 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3963 			    (sid_types.cur_sid_type == SPEC_SID ||
3964 			    sid_types.cur_sid_type == NO_SID))
3965 				abort = TRUE;
3966 			if (!e.error) {
3967 				if (res.status == NFS4ERR_BADOWNER)
3968 					nfs4_log_badowner(VTOMI4(vp),
3969 					    OP_SETATTR);
3970 
3971 				e.error = geterrno4(res.status);
3972 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3973 				    (caddr_t)&res);
3974 			}
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 			if (abort == FALSE) {
3982 				/*
3983 				 * Need to retry all possible stateids in
3984 				 * case the recovery error wasn't stateid
3985 				 * related or the stateids have become
3986 				 * stale (server reboot).
3987 				 */
3988 				nfs4_init_stateid_types(&sid_types);
3989 				goto recov_retry;
3990 			}
3991 			return (e.error);
3992 		}
3993 
3994 		/*
3995 		 * Need to call nfs4_end_op before nfs4getattr to
3996 		 * avoid potential nfs4_start_op deadlock. See RFE
3997 		 * 4777612.  Calls to nfs4_invalidate_pages() and
3998 		 * nfs4_purge_stale_fh() might also generate over the
3999 		 * wire calls which my cause nfs4_start_op() deadlock.
4000 		 */
4001 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4002 
4003 		/*
4004 		 * Check to update lease.
4005 		 */
4006 		resp = &res;
4007 		if (res.status == NFS4_OK) {
4008 			break;
4009 		}
4010 
4011 		/*
4012 		 * Check if verify failed to see if try again
4013 		 */
4014 		if ((verify_argop == -1) || (res.array_len != 3)) {
4015 			/*
4016 			 * can't continue...
4017 			 */
4018 			if (res.status == NFS4ERR_BADOWNER)
4019 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
4020 
4021 			e.error = geterrno4(res.status);
4022 		} else {
4023 			/*
4024 			 * When the verify request fails, the client ctime is
4025 			 * not in sync with the server. This is the same as
4026 			 * the version 3 "not synchronized" error, and we
4027 			 * handle it in a similar manner (XXX do we need to???).
4028 			 * Use the ctime returned in the first getattr for
4029 			 * the input to the next verify.
4030 			 * If we couldn't get the attributes, then we give up
4031 			 * because we can't complete the operation as required.
4032 			 */
4033 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
4034 		}
4035 		if (e.error) {
4036 			PURGE_ATTRCACHE4(vp);
4037 			nfs4_purge_stale_fh(e.error, vp, cr);
4038 		} else {
4039 			/*
4040 			 * retry with a new verify value
4041 			 */
4042 			ctime = garp->n4g_va.va_ctime;
4043 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4044 			resp = NULL;
4045 		}
4046 		if (!e.error) {
4047 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4048 			    opsetattr.obj_attributes);
4049 			if (verify_argop != -1) {
4050 				nfs4args_verify_free(&argop[verify_argop]);
4051 				verify_argop = -1;
4052 			}
4053 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4054 			goto do_again;
4055 		}
4056 	} while (!e.error);
4057 
4058 	if (e.error) {
4059 		/*
4060 		 * If we are here, rfs4call has an irrecoverable error - return
4061 		 */
4062 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4063 		    opsetattr.obj_attributes);
4064 		if (verify_argop != -1) {
4065 			nfs4args_verify_free(&argop[verify_argop]);
4066 			verify_argop = -1;
4067 		}
4068 		if (resp)
4069 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4070 		return (e.error);
4071 	}
4072 
4073 
4074 
4075 	/*
4076 	 * If changing the size of the file, invalidate
4077 	 * any local cached data which is no longer part
4078 	 * of the file.  We also possibly invalidate the
4079 	 * last page in the file.  We could use
4080 	 * pvn_vpzero(), but this would mark the page as
4081 	 * modified and require it to be written back to
4082 	 * the server for no particularly good reason.
4083 	 * This way, if we access it, then we bring it
4084 	 * back in.  A read should be cheaper than a
4085 	 * write.
4086 	 */
4087 	if (mask & AT_SIZE) {
4088 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
4089 	}
4090 
4091 	/* either no error or one of the postop getattr failed */
4092 
4093 	/*
4094 	 * XXX Perform a simplified version of wcc checking. Instead of
4095 	 * have another getattr to get pre-op, just purge cache if
4096 	 * any of the ops prior to and including the getattr failed.
4097 	 * If the getattr succeeded then update the attrcache accordingly.
4098 	 */
4099 
4100 	garp = NULL;
4101 	if (res.status == NFS4_OK) {
4102 		/*
4103 		 * Last getattr
4104 		 */
4105 		resop = &res.array[numops - 1];
4106 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4107 	}
4108 	/*
4109 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
4110 	 * rather than filling it.  See the function itself for details.
4111 	 */
4112 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4113 	if (garp != NULL) {
4114 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
4115 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
4116 			vs_ace4_destroy(&garp->n4g_vsa);
4117 		} else {
4118 			if (vsap != NULL) {
4119 				/*
4120 				 * The ACL was supposed to be set and to be
4121 				 * returned in the last getattr of this
4122 				 * compound, but for some reason the getattr
4123 				 * result doesn't contain the ACL.  In this
4124 				 * case, purge the ACL cache.
4125 				 */
4126 				if (rp->r_secattr != NULL) {
4127 					mutex_enter(&rp->r_statelock);
4128 					vsp = rp->r_secattr;
4129 					rp->r_secattr = NULL;
4130 					mutex_exit(&rp->r_statelock);
4131 					if (vsp != NULL)
4132 						nfs4_acl_free_cache(vsp);
4133 				}
4134 			}
4135 		}
4136 	}
4137 
4138 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4139 		/*
4140 		 * Set the size, rather than relying on getting it updated
4141 		 * via a GETATTR.  With delegations the client tries to
4142 		 * suppress GETATTR calls.
4143 		 */
4144 		mutex_enter(&rp->r_statelock);
4145 		rp->r_size = vap->va_size;
4146 		mutex_exit(&rp->r_statelock);
4147 	}
4148 
4149 	/*
4150 	 * Can free up request args and res
4151 	 */
4152 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4153 	    opsetattr.obj_attributes);
4154 	if (verify_argop != -1) {
4155 		nfs4args_verify_free(&argop[verify_argop]);
4156 		verify_argop = -1;
4157 	}
4158 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4159 
4160 	/*
4161 	 * Some servers will change the mode to clear the setuid
4162 	 * and setgid bits when changing the uid or gid.  The
4163 	 * client needs to compensate appropriately.
4164 	 */
4165 	if (mask & (AT_UID | AT_GID)) {
4166 		int terror, do_setattr;
4167 
4168 		do_setattr = 0;
4169 		va.va_mask = AT_MODE;
4170 		terror = nfs4getattr(vp, &va, cr);
4171 		if (!terror &&
4172 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4173 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4174 			va.va_mask = AT_MODE;
4175 			if (mask & AT_MODE) {
4176 				/*
4177 				 * We asked the mode to be changed and what
4178 				 * we just got from the server in getattr is
4179 				 * not what we wanted it to be, so set it now.
4180 				 */
4181 				va.va_mode = vap->va_mode;
4182 				do_setattr = 1;
4183 			} else {
4184 				/*
4185 				 * We did not ask the mode to be changed,
4186 				 * Check to see that the server just cleared
4187 				 * I_SUID and I_GUID from it. If not then
4188 				 * set mode to omode with UID/GID cleared.
4189 				 */
4190 				if (nfs4_compare_modes(va.va_mode, omode)) {
4191 					omode &= ~(S_ISUID|S_ISGID);
4192 					va.va_mode = omode;
4193 					do_setattr = 1;
4194 				}
4195 			}
4196 
4197 			if (do_setattr)
4198 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4199 		}
4200 	}
4201 
4202 	return (e.error);
4203 }
4204 
4205 /* ARGSUSED */
4206 static int
4207 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr, caller_context_t *ct)
4208 {
4209 	COMPOUND4args_clnt args;
4210 	COMPOUND4res_clnt res;
4211 	int doqueue;
4212 	uint32_t acc, resacc, argacc;
4213 	rnode4_t *rp;
4214 	cred_t *cred, *ncr, *ncrfree = NULL;
4215 	nfs4_access_type_t cacc;
4216 	int num_ops;
4217 	nfs_argop4 argop[3];
4218 	nfs_resop4 *resop;
4219 	bool_t needrecov = FALSE, do_getattr;
4220 	nfs4_recov_state_t recov_state;
4221 	int rpc_error;
4222 	hrtime_t t;
4223 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4224 	mntinfo4_t *mi = VTOMI4(vp);
4225 
4226 	if (nfs_zone() != mi->mi_zone)
4227 		return (EIO);
4228 
4229 	acc = 0;
4230 	if (mode & VREAD)
4231 		acc |= ACCESS4_READ;
4232 	if (mode & VWRITE) {
4233 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4234 			return (EROFS);
4235 		if (vp->v_type == VDIR)
4236 			acc |= ACCESS4_DELETE;
4237 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4238 	}
4239 	if (mode & VEXEC) {
4240 		if (vp->v_type == VDIR)
4241 			acc |= ACCESS4_LOOKUP;
4242 		else
4243 			acc |= ACCESS4_EXECUTE;
4244 	}
4245 
4246 	if (VTOR4(vp)->r_acache != NULL) {
4247 		e.error = nfs4_validate_caches(vp, cr);
4248 		if (e.error)
4249 			return (e.error);
4250 	}
4251 
4252 	rp = VTOR4(vp);
4253 	if (vp->v_type == VDIR)
4254 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4255 		    ACCESS4_EXTEND | ACCESS4_LOOKUP;
4256 	else
4257 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4258 		    ACCESS4_EXECUTE;
4259 	recov_state.rs_flags = 0;
4260 	recov_state.rs_num_retry_despite_err = 0;
4261 
4262 	cred = cr;
4263 	/*
4264 	 * ncr and ncrfree both initially
4265 	 * point to the memory area returned
4266 	 * by crnetadjust();
4267 	 * ncrfree not NULL when exiting means
4268 	 * that we need to release it
4269 	 */
4270 	ncr = crnetadjust(cred);
4271 	ncrfree = ncr;
4272 
4273 tryagain:
4274 	cacc = nfs4_access_check(rp, acc, cred);
4275 	if (cacc == NFS4_ACCESS_ALLOWED) {
4276 		if (ncrfree != NULL)
4277 			crfree(ncrfree);
4278 		return (0);
4279 	}
4280 	if (cacc == NFS4_ACCESS_DENIED) {
4281 		/*
4282 		 * If the cred can be adjusted, try again
4283 		 * with the new cred.
4284 		 */
4285 		if (ncr != NULL) {
4286 			cred = ncr;
4287 			ncr = NULL;
4288 			goto tryagain;
4289 		}
4290 		if (ncrfree != NULL)
4291 			crfree(ncrfree);
4292 		return (EACCES);
4293 	}
4294 
4295 recov_retry:
4296 	/*
4297 	 * Don't take with r_statev4_lock here. r_deleg_type could
4298 	 * change as soon as lock is released.  Since it is an int,
4299 	 * there is no atomicity issue.
4300 	 */
4301 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4302 	num_ops = do_getattr ? 3 : 2;
4303 
4304 	args.ctag = TAG_ACCESS;
4305 
4306 	args.array_len = num_ops;
4307 	args.array = argop;
4308 
4309 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4310 	    &recov_state, NULL)) {
4311 		if (ncrfree != NULL)
4312 			crfree(ncrfree);
4313 		return (e.error);
4314 	}
4315 
4316 	/* putfh target fh */
4317 	argop[0].argop = OP_CPUTFH;
4318 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4319 
4320 	/* access */
4321 	argop[1].argop = OP_ACCESS;
4322 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4323 
4324 	/* getattr */
4325 	if (do_getattr) {
4326 		argop[2].argop = OP_GETATTR;
4327 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4328 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4329 	}
4330 
4331 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4332 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4333 	    rnode4info(VTOR4(vp))));
4334 
4335 	doqueue = 1;
4336 	t = gethrtime();
4337 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4338 	rpc_error = e.error;
4339 
4340 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4341 	if (needrecov) {
4342 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4343 		    "nfs4_access: initiating recovery\n"));
4344 
4345 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4346 		    NULL, OP_ACCESS, NULL) == FALSE) {
4347 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4348 			    &recov_state, needrecov);
4349 			if (!e.error)
4350 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4351 				    (caddr_t)&res);
4352 			goto recov_retry;
4353 		}
4354 	}
4355 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4356 
4357 	if (e.error)
4358 		goto out;
4359 
4360 	if (res.status) {
4361 		e.error = geterrno4(res.status);
4362 		/*
4363 		 * This might generate over the wire calls throught
4364 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4365 		 * here to avoid a deadlock.
4366 		 */
4367 		nfs4_purge_stale_fh(e.error, vp, cr);
4368 		goto out;
4369 	}
4370 	resop = &res.array[1];	/* access res */
4371 
4372 	resacc = resop->nfs_resop4_u.opaccess.access;
4373 
4374 	if (do_getattr) {
4375 		resop++;	/* getattr res */
4376 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4377 		    t, cr, FALSE, NULL);
4378 	}
4379 
4380 	if (!e.error) {
4381 		nfs4_access_cache(rp, argacc, resacc, cred);
4382 		/*
4383 		 * we just cached results with cred; if cred is the
4384 		 * adjusted credentials from crnetadjust, we do not want
4385 		 * to release them before exiting: hence setting ncrfree
4386 		 * to NULL
4387 		 */
4388 		if (cred != cr)
4389 			ncrfree = NULL;
4390 		/* XXX check the supported bits too? */
4391 		if ((acc & resacc) != acc) {
4392 			/*
4393 			 * The following code implements the semantic
4394 			 * that a setuid root program has *at least* the
4395 			 * permissions of the user that is running the
4396 			 * program.  See rfs3call() for more portions
4397 			 * of the implementation of this functionality.
4398 			 */
4399 			/* XXX-LP */
4400 			if (ncr != NULL) {
4401 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4402 				    (caddr_t)&res);
4403 				cred = ncr;
4404 				ncr = NULL;
4405 				goto tryagain;
4406 			}
4407 			e.error = EACCES;
4408 		}
4409 	}
4410 
4411 out:
4412 	if (!rpc_error)
4413 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4414 
4415 	if (ncrfree != NULL)
4416 		crfree(ncrfree);
4417 
4418 	return (e.error);
4419 }
4420 
4421 /* ARGSUSED */
4422 static int
4423 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr, caller_context_t *ct)
4424 {
4425 	COMPOUND4args_clnt args;
4426 	COMPOUND4res_clnt res;
4427 	int doqueue;
4428 	rnode4_t *rp;
4429 	nfs_argop4 argop[3];
4430 	nfs_resop4 *resop;
4431 	READLINK4res *lr_res;
4432 	nfs4_ga_res_t *garp;
4433 	uint_t len;
4434 	char *linkdata;
4435 	bool_t needrecov = FALSE;
4436 	nfs4_recov_state_t recov_state;
4437 	hrtime_t t;
4438 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4439 
4440 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4441 		return (EIO);
4442 	/*
4443 	 * Can't readlink anything other than a symbolic link.
4444 	 */
4445 	if (vp->v_type != VLNK)
4446 		return (EINVAL);
4447 
4448 	rp = VTOR4(vp);
4449 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4450 		e.error = nfs4_validate_caches(vp, cr);
4451 		if (e.error)
4452 			return (e.error);
4453 		mutex_enter(&rp->r_statelock);
4454 		if (rp->r_symlink.contents != NULL) {
4455 			e.error = uiomove(rp->r_symlink.contents,
4456 			    rp->r_symlink.len, UIO_READ, uiop);
4457 			mutex_exit(&rp->r_statelock);
4458 			return (e.error);
4459 		}
4460 		mutex_exit(&rp->r_statelock);
4461 	}
4462 	recov_state.rs_flags = 0;
4463 	recov_state.rs_num_retry_despite_err = 0;
4464 
4465 recov_retry:
4466 	args.array_len = 3;
4467 	args.array = argop;
4468 	args.ctag = TAG_READLINK;
4469 
4470 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4471 	if (e.error) {
4472 		return (e.error);
4473 	}
4474 
4475 	/* 0. putfh symlink fh */
4476 	argop[0].argop = OP_CPUTFH;
4477 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4478 
4479 	/* 1. readlink */
4480 	argop[1].argop = OP_READLINK;
4481 
4482 	/* 2. getattr */
4483 	argop[2].argop = OP_GETATTR;
4484 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4485 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4486 
4487 	doqueue = 1;
4488 
4489 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4490 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4491 	    rnode4info(VTOR4(vp))));
4492 
4493 	t = gethrtime();
4494 
4495 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4496 
4497 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4498 	if (needrecov) {
4499 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4500 		    "nfs4_readlink: initiating recovery\n"));
4501 
4502 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4503 		    NULL, OP_READLINK, NULL) == FALSE) {
4504 			if (!e.error)
4505 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4506 				    (caddr_t)&res);
4507 
4508 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4509 			    needrecov);
4510 			goto recov_retry;
4511 		}
4512 	}
4513 
4514 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4515 
4516 	if (e.error)
4517 		return (e.error);
4518 
4519 	/*
4520 	 * There is an path in the code below which calls
4521 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4522 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4523 	 * here to avoid nfs4_start_op() deadlock.
4524 	 */
4525 
4526 	if (res.status && (res.array_len < args.array_len)) {
4527 		/*
4528 		 * either Putfh or Link failed
4529 		 */
4530 		e.error = geterrno4(res.status);
4531 		nfs4_purge_stale_fh(e.error, vp, cr);
4532 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4533 		return (e.error);
4534 	}
4535 
4536 	resop = &res.array[1];	/* readlink res */
4537 	lr_res = &resop->nfs_resop4_u.opreadlink;
4538 
4539 	/*
4540 	 * treat symlink names as data
4541 	 */
4542 	linkdata = utf8_to_str(&lr_res->link, &len, NULL);
4543 	if (linkdata != NULL) {
4544 		int uio_len = len - 1;
4545 		/* len includes null byte, which we won't uiomove */
4546 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4547 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4548 			mutex_enter(&rp->r_statelock);
4549 			if (rp->r_symlink.contents == NULL) {
4550 				rp->r_symlink.contents = linkdata;
4551 				rp->r_symlink.len = uio_len;
4552 				rp->r_symlink.size = len;
4553 				mutex_exit(&rp->r_statelock);
4554 			} else {
4555 				mutex_exit(&rp->r_statelock);
4556 				kmem_free(linkdata, len);
4557 			}
4558 		} else {
4559 			kmem_free(linkdata, len);
4560 		}
4561 	}
4562 	if (res.status == NFS4_OK) {
4563 		resop++;	/* getattr res */
4564 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4565 	}
4566 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4567 
4568 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4569 
4570 	/*
4571 	 * The over the wire error for attempting to readlink something
4572 	 * other than a symbolic link is ENXIO.  However, we need to
4573 	 * return EINVAL instead of ENXIO, so we map it here.
4574 	 */
4575 	return (e.error == ENXIO ? EINVAL : e.error);
4576 }
4577 
4578 /*
4579  * Flush local dirty pages to stable storage on the server.
4580  *
4581  * If FNODSYNC is specified, then there is nothing to do because
4582  * metadata changes are not cached on the client before being
4583  * sent to the server.
4584  */
4585 /* ARGSUSED */
4586 static int
4587 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
4588 {
4589 	int error;
4590 
4591 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4592 		return (0);
4593 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4594 		return (EIO);
4595 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4596 	if (!error)
4597 		error = VTOR4(vp)->r_error;
4598 	return (error);
4599 }
4600 
4601 /*
4602  * Weirdness: if the file was removed or the target of a rename
4603  * operation while it was open, it got renamed instead.  Here we
4604  * remove the renamed file.
4605  */
4606 /* ARGSUSED */
4607 void
4608 nfs4_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4609 {
4610 	rnode4_t *rp;
4611 
4612 	ASSERT(vp != DNLC_NO_VNODE);
4613 
4614 	rp = VTOR4(vp);
4615 
4616 	if (IS_SHADOW(vp, rp)) {
4617 		sv_inactive(vp);
4618 		return;
4619 	}
4620 
4621 	/*
4622 	 * If this is coming from the wrong zone, we let someone in the right
4623 	 * zone take care of it asynchronously.  We can get here due to
4624 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4625 	 * potentially turn into an expensive no-op if, for instance, v_count
4626 	 * gets incremented in the meantime, but it's still correct.
4627 	 */
4628 	if (nfs_zone() != VTOMI4(vp)->mi_zone) {
4629 		nfs4_async_inactive(vp, cr);
4630 		return;
4631 	}
4632 
4633 	/*
4634 	 * Some of the cleanup steps might require over-the-wire
4635 	 * operations.  Since VOP_INACTIVE can get called as a result of
4636 	 * other over-the-wire operations (e.g., an attribute cache update
4637 	 * can lead to a DNLC purge), doing those steps now would lead to a
4638 	 * nested call to the recovery framework, which can deadlock.  So
4639 	 * do any over-the-wire cleanups asynchronously, in a separate
4640 	 * thread.
4641 	 */
4642 
4643 	mutex_enter(&rp->r_os_lock);
4644 	mutex_enter(&rp->r_statelock);
4645 	mutex_enter(&rp->r_statev4_lock);
4646 
4647 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4648 		mutex_exit(&rp->r_statev4_lock);
4649 		mutex_exit(&rp->r_statelock);
4650 		mutex_exit(&rp->r_os_lock);
4651 		nfs4_async_inactive(vp, cr);
4652 		return;
4653 	}
4654 
4655 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4656 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4657 		mutex_exit(&rp->r_statev4_lock);
4658 		mutex_exit(&rp->r_statelock);
4659 		mutex_exit(&rp->r_os_lock);
4660 		nfs4_async_inactive(vp, cr);
4661 		return;
4662 	}
4663 
4664 	if (rp->r_unldvp != NULL) {
4665 		mutex_exit(&rp->r_statev4_lock);
4666 		mutex_exit(&rp->r_statelock);
4667 		mutex_exit(&rp->r_os_lock);
4668 		nfs4_async_inactive(vp, cr);
4669 		return;
4670 	}
4671 	mutex_exit(&rp->r_statev4_lock);
4672 	mutex_exit(&rp->r_statelock);
4673 	mutex_exit(&rp->r_os_lock);
4674 
4675 	rp4_addfree(rp, cr);
4676 }
4677 
4678 /*
4679  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4680  * various bits of state.  The caller must not refer to vp after this call.
4681  */
4682 
4683 void
4684 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4685 {
4686 	rnode4_t *rp = VTOR4(vp);
4687 	nfs4_recov_state_t recov_state;
4688 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4689 	vnode_t *unldvp;
4690 	char *unlname;
4691 	cred_t *unlcred;
4692 	COMPOUND4args_clnt args;
4693 	COMPOUND4res_clnt res, *resp;
4694 	nfs_argop4 argop[2];
4695 	int doqueue;
4696 #ifdef DEBUG
4697 	char *name;
4698 #endif
4699 
4700 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
4701 	ASSERT(!IS_SHADOW(vp, rp));
4702 
4703 #ifdef DEBUG
4704 	name = fn_name(VTOSV(vp)->sv_name);
4705 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4706 	    "release vnode %s", name));
4707 	kmem_free(name, MAXNAMELEN);
4708 #endif
4709 
4710 	if (vp->v_type == VREG) {
4711 		bool_t recov_failed = FALSE;
4712 
4713 		e.error = nfs4close_all(vp, cr);
4714 		if (e.error) {
4715 			/* Check to see if recovery failed */
4716 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4717 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4718 				recov_failed = TRUE;
4719 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4720 			if (!recov_failed) {
4721 				mutex_enter(&rp->r_statelock);
4722 				if (rp->r_flags & R4RECOVERR)
4723 					recov_failed = TRUE;
4724 				mutex_exit(&rp->r_statelock);
4725 			}
4726 			if (recov_failed) {
4727 				NFS4_DEBUG(nfs4_client_recov_debug,
4728 				    (CE_NOTE, "nfs4_inactive_otw: "
4729 				    "close failed (recovery failure)"));
4730 			}
4731 		}
4732 	}
4733 
4734 redo:
4735 	if (rp->r_unldvp == NULL) {
4736 		rp4_addfree(rp, cr);
4737 		return;
4738 	}
4739 
4740 	/*
4741 	 * Save the vnode pointer for the directory where the
4742 	 * unlinked-open file got renamed, then set it to NULL
4743 	 * to prevent another thread from getting here before
4744 	 * we're done with the remove.  While we have the
4745 	 * statelock, make local copies of the pertinent rnode
4746 	 * fields.  If we weren't to do this in an atomic way, the
4747 	 * the unl* fields could become inconsistent with respect
4748 	 * to each other due to a race condition between this
4749 	 * code and nfs_remove().  See bug report 1034328.
4750 	 */
4751 	mutex_enter(&rp->r_statelock);
4752 	if (rp->r_unldvp == NULL) {
4753 		mutex_exit(&rp->r_statelock);
4754 		rp4_addfree(rp, cr);
4755 		return;
4756 	}
4757 
4758 	unldvp = rp->r_unldvp;
4759 	rp->r_unldvp = NULL;
4760 	unlname = rp->r_unlname;
4761 	rp->r_unlname = NULL;
4762 	unlcred = rp->r_unlcred;
4763 	rp->r_unlcred = NULL;
4764 	mutex_exit(&rp->r_statelock);
4765 
4766 	/*
4767 	 * If there are any dirty pages left, then flush
4768 	 * them.  This is unfortunate because they just
4769 	 * may get thrown away during the remove operation,
4770 	 * but we have to do this for correctness.
4771 	 */
4772 	if (nfs4_has_pages(vp) &&
4773 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4774 		ASSERT(vp->v_type != VCHR);
4775 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, NULL);
4776 		if (e.error) {
4777 			mutex_enter(&rp->r_statelock);
4778 			if (!rp->r_error)
4779 				rp->r_error = e.error;
4780 			mutex_exit(&rp->r_statelock);
4781 		}
4782 	}
4783 
4784 	recov_state.rs_flags = 0;
4785 	recov_state.rs_num_retry_despite_err = 0;
4786 recov_retry_remove:
4787 	/*
4788 	 * Do the remove operation on the renamed file
4789 	 */
4790 	args.ctag = TAG_INACTIVE;
4791 
4792 	/*
4793 	 * Remove ops: putfh dir; remove
4794 	 */
4795 	args.array_len = 2;
4796 	args.array = argop;
4797 
4798 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4799 	if (e.error) {
4800 		kmem_free(unlname, MAXNAMELEN);
4801 		crfree(unlcred);
4802 		VN_RELE(unldvp);
4803 		/*
4804 		 * Try again; this time around r_unldvp will be NULL, so we'll
4805 		 * just call rp4_addfree() and return.
4806 		 */
4807 		goto redo;
4808 	}
4809 
4810 	/* putfh directory */
4811 	argop[0].argop = OP_CPUTFH;
4812 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4813 
4814 	/* remove */
4815 	argop[1].argop = OP_CREMOVE;
4816 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4817 
4818 	doqueue = 1;
4819 	resp = &res;
4820 
4821 #if 0 /* notyet */
4822 	/*
4823 	 * Can't do this yet.  We may be being called from
4824 	 * dnlc_purge_XXX while that routine is holding a
4825 	 * mutex lock to the nc_rele list.  The calls to
4826 	 * nfs3_cache_wcc_data may result in calls to
4827 	 * dnlc_purge_XXX.  This will result in a deadlock.
4828 	 */
4829 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4830 	if (e.error) {
4831 		PURGE_ATTRCACHE4(unldvp);
4832 		resp = NULL;
4833 	} else if (res.status) {
4834 		e.error = geterrno4(res.status);
4835 		PURGE_ATTRCACHE4(unldvp);
4836 		/*
4837 		 * This code is inactive right now
4838 		 * but if made active there should
4839 		 * be a nfs4_end_op() call before
4840 		 * nfs4_purge_stale_fh to avoid start_op()
4841 		 * deadlock. See BugId: 4948726
4842 		 */
4843 		nfs4_purge_stale_fh(error, unldvp, cr);
4844 	} else {
4845 		nfs_resop4 *resop;
4846 		REMOVE4res *rm_res;
4847 
4848 		resop = &res.array[1];
4849 		rm_res = &resop->nfs_resop4_u.opremove;
4850 		/*
4851 		 * Update directory cache attribute,
4852 		 * readdir and dnlc caches.
4853 		 */
4854 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4855 	}
4856 #else
4857 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4858 
4859 	PURGE_ATTRCACHE4(unldvp);
4860 #endif
4861 
4862 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4863 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4864 		    NULL, NULL, OP_REMOVE, NULL) == FALSE) {
4865 			if (!e.error)
4866 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4867 				    (caddr_t)&res);
4868 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4869 			    &recov_state, TRUE);
4870 			goto recov_retry_remove;
4871 		}
4872 	}
4873 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4874 
4875 	/*
4876 	 * Release stuff held for the remove
4877 	 */
4878 	VN_RELE(unldvp);
4879 	if (!e.error && resp)
4880 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4881 
4882 	kmem_free(unlname, MAXNAMELEN);
4883 	crfree(unlcred);
4884 	goto redo;
4885 }
4886 
4887 /*
4888  * Remote file system operations having to do with directory manipulation.
4889  */
4890 /* ARGSUSED3 */
4891 int
4892 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4893     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
4894     int *direntflags, pathname_t *realpnp)
4895 {
4896 	int error;
4897 	vnode_t *vp, *avp = NULL;
4898 	rnode4_t *drp;
4899 
4900 	*vpp = NULL;
4901 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4902 		return (EPERM);
4903 	/*
4904 	 * if LOOKUP_XATTR, must replace dvp (object) with
4905 	 * object's attrdir before continuing with lookup
4906 	 */
4907 	if (flags & LOOKUP_XATTR) {
4908 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4909 		if (error)
4910 			return (error);
4911 
4912 		dvp = avp;
4913 
4914 		/*
4915 		 * If lookup is for "", just return dvp now.  The attrdir
4916 		 * has already been activated (from nfs4lookup_xattr), and
4917 		 * the caller will RELE the original dvp -- not
4918 		 * the attrdir.  So, set vpp and return.
4919 		 * Currently, when the LOOKUP_XATTR flag is
4920 		 * passed to VOP_LOOKUP, the name is always empty, and
4921 		 * shortcircuiting here avoids 3 unneeded lock/unlock
4922 		 * pairs.
4923 		 *
4924 		 * If a non-empty name was provided, then it is the
4925 		 * attribute name, and it will be looked up below.
4926 		 */
4927 		if (*nm == '\0') {
4928 			*vpp = dvp;
4929 			return (0);
4930 		}
4931 
4932 		/*
4933 		 * The vfs layer never sends a name when asking for the
4934 		 * attrdir, so we should never get here (unless of course
4935 		 * name is passed at some time in future -- at which time
4936 		 * we'll blow up here).
4937 		 */
4938 		ASSERT(0);
4939 	}
4940 
4941 	drp = VTOR4(dvp);
4942 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4943 		return (EINTR);
4944 
4945 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
4946 	nfs_rw_exit(&drp->r_rwlock);
4947 
4948 	/*
4949 	 * If vnode is a device, create special vnode.
4950 	 */
4951 	if (!error && ISVDEV((*vpp)->v_type)) {
4952 		vp = *vpp;
4953 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
4954 		VN_RELE(vp);
4955 	}
4956 
4957 	return (error);
4958 }
4959 
4960 /* ARGSUSED */
4961 static int
4962 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
4963 {
4964 	int error;
4965 	rnode4_t *drp;
4966 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
4967 	mntinfo4_t *mi;
4968 
4969 	mi = VTOMI4(dvp);
4970 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR) &&
4971 	    !vfs_has_feature(mi->mi_vfsp, VFSFT_XVATTR))
4972 		return (EINVAL);
4973 
4974 	drp = VTOR4(dvp);
4975 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4976 		return (EINTR);
4977 
4978 	mutex_enter(&drp->r_statelock);
4979 	/*
4980 	 * If the server doesn't support xattrs just return EINVAL
4981 	 */
4982 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
4983 		mutex_exit(&drp->r_statelock);
4984 		nfs_rw_exit(&drp->r_rwlock);
4985 		return (EINVAL);
4986 	}
4987 
4988 	/*
4989 	 * If there is a cached xattr directory entry,
4990 	 * use it as long as the attributes are valid. If the
4991 	 * attributes are not valid, take the simple approach and
4992 	 * free the cached value and re-fetch a new value.
4993 	 *
4994 	 * We don't negative entry cache for now, if we did we
4995 	 * would need to check if the file has changed on every
4996 	 * lookup. But xattrs don't exist very often and failing
4997 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
4998 	 * so do an openattr over the wire for now.
4999 	 */
5000 	if (drp->r_xattr_dir != NULL) {
5001 		if (ATTRCACHE4_VALID(dvp)) {
5002 			VN_HOLD(drp->r_xattr_dir);
5003 			*vpp = drp->r_xattr_dir;
5004 			mutex_exit(&drp->r_statelock);
5005 			nfs_rw_exit(&drp->r_rwlock);
5006 			return (0);
5007 		}
5008 		VN_RELE(drp->r_xattr_dir);
5009 		drp->r_xattr_dir = NULL;
5010 	}
5011 	mutex_exit(&drp->r_statelock);
5012 
5013 	error = nfs4openattr(dvp, vpp, cflag, cr);
5014 
5015 	nfs_rw_exit(&drp->r_rwlock);
5016 
5017 	return (error);
5018 }
5019 
5020 static int
5021 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
5022 {
5023 	int error;
5024 	rnode4_t *drp;
5025 
5026 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5027 
5028 	/*
5029 	 * If lookup is for "", just return dvp.  Don't need
5030 	 * to send it over the wire, look it up in the dnlc,
5031 	 * or perform any access checks.
5032 	 */
5033 	if (*nm == '\0') {
5034 		VN_HOLD(dvp);
5035 		*vpp = dvp;
5036 		return (0);
5037 	}
5038 
5039 	/*
5040 	 * Can't do lookups in non-directories.
5041 	 */
5042 	if (dvp->v_type != VDIR)
5043 		return (ENOTDIR);
5044 
5045 	/*
5046 	 * If lookup is for ".", just return dvp.  Don't need
5047 	 * to send it over the wire or look it up in the dnlc,
5048 	 * just need to check access.
5049 	 */
5050 	if (nm[0] == '.' && nm[1] == '\0') {
5051 		error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5052 		if (error)
5053 			return (error);
5054 		VN_HOLD(dvp);
5055 		*vpp = dvp;
5056 		return (0);
5057 	}
5058 
5059 	drp = VTOR4(dvp);
5060 	if (!(drp->r_flags & R4LOOKUP)) {
5061 		mutex_enter(&drp->r_statelock);
5062 		drp->r_flags |= R4LOOKUP;
5063 		mutex_exit(&drp->r_statelock);
5064 	}
5065 
5066 	*vpp = NULL;
5067 	/*
5068 	 * Lookup this name in the DNLC.  If there is no entry
5069 	 * lookup over the wire.
5070 	 */
5071 	if (!skipdnlc)
5072 		*vpp = dnlc_lookup(dvp, nm);
5073 	if (*vpp == NULL) {
5074 		/*
5075 		 * We need to go over the wire to lookup the name.
5076 		 */
5077 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
5078 	}
5079 
5080 	/*
5081 	 * We hit on the dnlc
5082 	 */
5083 	if (*vpp != DNLC_NO_VNODE ||
5084 	    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
5085 		/*
5086 		 * But our attrs may not be valid.
5087 		 */
5088 		if (ATTRCACHE4_VALID(dvp)) {
5089 			error = nfs4_waitfor_purge_complete(dvp);
5090 			if (error) {
5091 				VN_RELE(*vpp);
5092 				*vpp = NULL;
5093 				return (error);
5094 			}
5095 
5096 			/*
5097 			 * If after the purge completes, check to make sure
5098 			 * our attrs are still valid.
5099 			 */
5100 			if (ATTRCACHE4_VALID(dvp)) {
5101 				/*
5102 				 * If we waited for a purge we may have
5103 				 * lost our vnode so look it up again.
5104 				 */
5105 				VN_RELE(*vpp);
5106 				*vpp = dnlc_lookup(dvp, nm);
5107 				if (*vpp == NULL)
5108 					return (nfs4lookupnew_otw(dvp,
5109 					    nm, vpp, cr));
5110 
5111 				/*
5112 				 * The access cache should almost always hit
5113 				 */
5114 				error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5115 
5116 				if (error) {
5117 					VN_RELE(*vpp);
5118 					*vpp = NULL;
5119 					return (error);
5120 				}
5121 				if (*vpp == DNLC_NO_VNODE) {
5122 					VN_RELE(*vpp);
5123 					*vpp = NULL;
5124 					return (ENOENT);
5125 				}
5126 				return (0);
5127 			}
5128 		}
5129 	}
5130 
5131 	ASSERT(*vpp != NULL);
5132 
5133 	/*
5134 	 * We may have gotten here we have one of the following cases:
5135 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5136 	 *		need to validate them.
5137 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5138 	 *		must validate.
5139 	 *
5140 	 * Go to the server and check if the directory has changed, if
5141 	 * it hasn't we are done and can use the dnlc entry.
5142 	 */
5143 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5144 }
5145 
5146 /*
5147  * Go to the server and check if the directory has changed, if
5148  * it hasn't we are done and can use the dnlc entry.  If it
5149  * has changed we get a new copy of its attributes and check
5150  * the access for VEXEC, then relookup the filename and
5151  * get its filehandle and attributes.
5152  *
5153  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5154  *	if the NVERIFY failed we must
5155  *		purge the caches
5156  *		cache new attributes (will set r_time_attr_inval)
5157  *		cache new access
5158  *		recheck VEXEC access
5159  *		add name to dnlc, possibly negative
5160  *		if LOOKUP succeeded
5161  *			cache new attributes
5162  *	else
5163  *		set a new r_time_attr_inval for dvp
5164  *		check to make sure we have access
5165  *
5166  * The vpp returned is the vnode passed in if the directory is valid,
5167  * a new vnode if successful lookup, or NULL on error.
5168  */
5169 static int
5170 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5171 {
5172 	COMPOUND4args_clnt args;
5173 	COMPOUND4res_clnt res;
5174 	fattr4 *ver_fattr;
5175 	fattr4_change dchange;
5176 	int32_t *ptr;
5177 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5178 	nfs_argop4 *argop;
5179 	int doqueue;
5180 	mntinfo4_t *mi;
5181 	nfs4_recov_state_t recov_state;
5182 	hrtime_t t;
5183 	int isdotdot;
5184 	vnode_t *nvp;
5185 	nfs_fh4 *fhp;
5186 	nfs4_sharedfh_t *sfhp;
5187 	nfs4_access_type_t cacc;
5188 	rnode4_t *nrp;
5189 	rnode4_t *drp = VTOR4(dvp);
5190 	nfs4_ga_res_t *garp = NULL;
5191 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5192 
5193 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5194 	ASSERT(nm != NULL);
5195 	ASSERT(nm[0] != '\0');
5196 	ASSERT(dvp->v_type == VDIR);
5197 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5198 	ASSERT(*vpp != NULL);
5199 
5200 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5201 		isdotdot = 1;
5202 		args.ctag = TAG_LOOKUP_VPARENT;
5203 	} else {
5204 		/*
5205 		 * If dvp were a stub, it should have triggered and caused
5206 		 * a mount for us to get this far.
5207 		 */
5208 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5209 
5210 		isdotdot = 0;
5211 		args.ctag = TAG_LOOKUP_VALID;
5212 	}
5213 
5214 	mi = VTOMI4(dvp);
5215 	recov_state.rs_flags = 0;
5216 	recov_state.rs_num_retry_despite_err = 0;
5217 
5218 	nvp = NULL;
5219 
5220 	/* Save the original mount point security information */
5221 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5222 
5223 recov_retry:
5224 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5225 	    &recov_state, NULL);
5226 	if (e.error) {
5227 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5228 		VN_RELE(*vpp);
5229 		*vpp = NULL;
5230 		return (e.error);
5231 	}
5232 
5233 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5234 
5235 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5236 	args.array_len = 7;
5237 	args.array = argop;
5238 
5239 	/* 0. putfh file */
5240 	argop[0].argop = OP_CPUTFH;
5241 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5242 
5243 	/* 1. nverify the change info */
5244 	argop[1].argop = OP_NVERIFY;
5245 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5246 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5247 	ver_fattr->attrlist4 = (char *)&dchange;
5248 	ptr = (int32_t *)&dchange;
5249 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5250 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5251 
5252 	/* 2. getattr directory */
5253 	argop[2].argop = OP_GETATTR;
5254 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5255 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5256 
5257 	/* 3. access directory */
5258 	argop[3].argop = OP_ACCESS;
5259 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5260 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5261 
5262 	/* 4. lookup name */
5263 	if (isdotdot) {
5264 		argop[4].argop = OP_LOOKUPP;
5265 	} else {
5266 		argop[4].argop = OP_CLOOKUP;
5267 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5268 	}
5269 
5270 	/* 5. resulting file handle */
5271 	argop[5].argop = OP_GETFH;
5272 
5273 	/* 6. resulting file attributes */
5274 	argop[6].argop = OP_GETATTR;
5275 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5276 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5277 
5278 	doqueue = 1;
5279 	t = gethrtime();
5280 
5281 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5282 
5283 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5284 		/*
5285 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5286 		 * from this thread, do not go thru the recovery thread since
5287 		 * we need the nm information.
5288 		 *
5289 		 * Not doing dotdot case because there is no specification
5290 		 * for (PUTFH, SECINFO "..") yet.
5291 		 */
5292 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5293 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5294 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5295 				    &recov_state, FALSE);
5296 			else
5297 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5298 				    &recov_state, TRUE);
5299 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5300 			kmem_free(argop, argoplist_size);
5301 			if (!e.error)
5302 				goto recov_retry;
5303 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5304 			VN_RELE(*vpp);
5305 			*vpp = NULL;
5306 			return (e.error);
5307 		}
5308 
5309 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5310 		    OP_LOOKUP, NULL) == FALSE) {
5311 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5312 			    &recov_state, TRUE);
5313 
5314 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5315 			kmem_free(argop, argoplist_size);
5316 			goto recov_retry;
5317 		}
5318 	}
5319 
5320 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5321 
5322 	if (e.error || res.array_len == 0) {
5323 		/*
5324 		 * If e.error isn't set, then reply has no ops (or we couldn't
5325 		 * be here).  The only legal way to reply without an op array
5326 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5327 		 * be in the reply for all other status values.
5328 		 *
5329 		 * For valid replies without an ops array, return ENOTSUP
5330 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5331 		 * return EIO -- don't trust status.
5332 		 */
5333 		if (e.error == 0)
5334 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5335 			    ENOTSUP : EIO;
5336 		VN_RELE(*vpp);
5337 		*vpp = NULL;
5338 		kmem_free(argop, argoplist_size);
5339 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5340 		return (e.error);
5341 	}
5342 
5343 	if (res.status != NFS4ERR_SAME) {
5344 		e.error = geterrno4(res.status);
5345 
5346 		/*
5347 		 * The NVERIFY "failed" so the directory has changed
5348 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5349 		 * cleanly.
5350 		 */
5351 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5352 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5353 			nfs4_purge_stale_fh(e.error, dvp, cr);
5354 			VN_RELE(*vpp);
5355 			*vpp = NULL;
5356 			goto exit;
5357 		}
5358 
5359 		/*
5360 		 * We know the NVERIFY "failed" so we must:
5361 		 *	purge the caches (access and indirectly dnlc if needed)
5362 		 */
5363 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5364 
5365 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5366 			nfs4_purge_stale_fh(e.error, dvp, cr);
5367 			VN_RELE(*vpp);
5368 			*vpp = NULL;
5369 			goto exit;
5370 		}
5371 
5372 		/*
5373 		 * Install new cached attributes for the directory
5374 		 */
5375 		nfs4_attr_cache(dvp,
5376 		    &res.array[2].nfs_resop4_u.opgetattr.ga_res,
5377 		    t, cr, FALSE, NULL);
5378 
5379 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5380 			nfs4_purge_stale_fh(e.error, dvp, cr);
5381 			VN_RELE(*vpp);
5382 			*vpp = NULL;
5383 			e.error = geterrno4(res.status);
5384 			goto exit;
5385 		}
5386 
5387 		/*
5388 		 * Now we know the directory is valid,
5389 		 * cache new directory access
5390 		 */
5391 		nfs4_access_cache(drp,
5392 		    args.array[3].nfs_argop4_u.opaccess.access,
5393 		    res.array[3].nfs_resop4_u.opaccess.access, cr);
5394 
5395 		/*
5396 		 * recheck VEXEC access
5397 		 */
5398 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5399 		if (cacc != NFS4_ACCESS_ALLOWED) {
5400 			/*
5401 			 * Directory permissions might have been revoked
5402 			 */
5403 			if (cacc == NFS4_ACCESS_DENIED) {
5404 				e.error = EACCES;
5405 				VN_RELE(*vpp);
5406 				*vpp = NULL;
5407 				goto exit;
5408 			}
5409 
5410 			/*
5411 			 * Somehow we must not have asked for enough
5412 			 * so try a singleton ACCESS, should never happen.
5413 			 */
5414 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5415 			if (e.error) {
5416 				VN_RELE(*vpp);
5417 				*vpp = NULL;
5418 				goto exit;
5419 			}
5420 		}
5421 
5422 		e.error = geterrno4(res.status);
5423 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5424 			/*
5425 			 * The lookup failed, probably no entry
5426 			 */
5427 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5428 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5429 			} else {
5430 				/*
5431 				 * Might be some other error, so remove
5432 				 * the dnlc entry to make sure we start all
5433 				 * over again, next time.
5434 				 */
5435 				dnlc_remove(dvp, nm);
5436 			}
5437 			VN_RELE(*vpp);
5438 			*vpp = NULL;
5439 			goto exit;
5440 		}
5441 
5442 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5443 			/*
5444 			 * The file exists but we can't get its fh for
5445 			 * some unknown reason.  Remove it from the dnlc
5446 			 * and error out to be safe.
5447 			 */
5448 			dnlc_remove(dvp, nm);
5449 			VN_RELE(*vpp);
5450 			*vpp = NULL;
5451 			goto exit;
5452 		}
5453 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5454 		if (fhp->nfs_fh4_len == 0) {
5455 			/*
5456 			 * The file exists but a bogus fh
5457 			 * some unknown reason.  Remove it from the dnlc
5458 			 * and error out to be safe.
5459 			 */
5460 			e.error = ENOENT;
5461 			dnlc_remove(dvp, nm);
5462 			VN_RELE(*vpp);
5463 			*vpp = NULL;
5464 			goto exit;
5465 		}
5466 		sfhp = sfh4_get(fhp, mi);
5467 
5468 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5469 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5470 
5471 		/*
5472 		 * Make the new rnode
5473 		 */
5474 		if (isdotdot) {
5475 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5476 			if (e.error) {
5477 				sfh4_rele(&sfhp);
5478 				VN_RELE(*vpp);
5479 				*vpp = NULL;
5480 				goto exit;
5481 			}
5482 			/*
5483 			 * XXX if nfs4_make_dotdot uses an existing rnode
5484 			 * XXX it doesn't update the attributes.
5485 			 * XXX for now just save them again to save an OTW
5486 			 */
5487 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5488 		} else {
5489 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5490 			    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5491 			/*
5492 			 * If v_type == VNON, then garp was NULL because
5493 			 * the last op in the compound failed and makenfs4node
5494 			 * could not find the vnode for sfhp. It created
5495 			 * a new vnode, so we have nothing to purge here.
5496 			 */
5497 			if (nvp->v_type == VNON) {
5498 				vattr_t vattr;
5499 
5500 				vattr.va_mask = AT_TYPE;
5501 				/*
5502 				 * N.B. We've already called nfs4_end_fop above.
5503 				 */
5504 				e.error = nfs4getattr(nvp, &vattr, cr);
5505 				if (e.error) {
5506 					sfh4_rele(&sfhp);
5507 					VN_RELE(*vpp);
5508 					*vpp = NULL;
5509 					VN_RELE(nvp);
5510 					goto exit;
5511 				}
5512 				nvp->v_type = vattr.va_type;
5513 			}
5514 		}
5515 		sfh4_rele(&sfhp);
5516 
5517 		nrp = VTOR4(nvp);
5518 		mutex_enter(&nrp->r_statev4_lock);
5519 		if (!nrp->created_v4) {
5520 			mutex_exit(&nrp->r_statev4_lock);
5521 			dnlc_update(dvp, nm, nvp);
5522 		} else
5523 			mutex_exit(&nrp->r_statev4_lock);
5524 
5525 		VN_RELE(*vpp);
5526 		*vpp = nvp;
5527 	} else {
5528 		hrtime_t now;
5529 		hrtime_t delta = 0;
5530 
5531 		e.error = 0;
5532 
5533 		/*
5534 		 * Because the NVERIFY "succeeded" we know that the
5535 		 * directory attributes are still valid
5536 		 * so update r_time_attr_inval
5537 		 */
5538 		now = gethrtime();
5539 		mutex_enter(&drp->r_statelock);
5540 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5541 			delta = now - drp->r_time_attr_saved;
5542 			if (delta < mi->mi_acdirmin)
5543 				delta = mi->mi_acdirmin;
5544 			else if (delta > mi->mi_acdirmax)
5545 				delta = mi->mi_acdirmax;
5546 		}
5547 		drp->r_time_attr_inval = now + delta;
5548 		mutex_exit(&drp->r_statelock);
5549 		dnlc_update(dvp, nm, *vpp);
5550 
5551 		/*
5552 		 * Even though we have a valid directory attr cache
5553 		 * and dnlc entry, we may not have access.
5554 		 * This should almost always hit the cache.
5555 		 */
5556 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5557 		if (e.error) {
5558 			VN_RELE(*vpp);
5559 			*vpp = NULL;
5560 		}
5561 
5562 		if (*vpp == DNLC_NO_VNODE) {
5563 			VN_RELE(*vpp);
5564 			*vpp = NULL;
5565 			e.error = ENOENT;
5566 		}
5567 	}
5568 
5569 exit:
5570 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5571 	kmem_free(argop, argoplist_size);
5572 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5573 	return (e.error);
5574 }
5575 
5576 /*
5577  * We need to go over the wire to lookup the name, but
5578  * while we are there verify the directory has not
5579  * changed but if it has, get new attributes and check access
5580  *
5581  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5582  *					NVERIFY GETATTR ACCESS
5583  *
5584  * With the results:
5585  *	if the NVERIFY failed we must purge the caches, add new attributes,
5586  *		and cache new access.
5587  *	set a new r_time_attr_inval
5588  *	add name to dnlc, possibly negative
5589  *	if LOOKUP succeeded
5590  *		cache new attributes
5591  */
5592 static int
5593 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5594 {
5595 	COMPOUND4args_clnt args;
5596 	COMPOUND4res_clnt res;
5597 	fattr4 *ver_fattr;
5598 	fattr4_change dchange;
5599 	int32_t *ptr;
5600 	nfs4_ga_res_t *garp = NULL;
5601 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5602 	nfs_argop4 *argop;
5603 	int doqueue;
5604 	mntinfo4_t *mi;
5605 	nfs4_recov_state_t recov_state;
5606 	hrtime_t t;
5607 	int isdotdot;
5608 	vnode_t *nvp;
5609 	nfs_fh4 *fhp;
5610 	nfs4_sharedfh_t *sfhp;
5611 	nfs4_access_type_t cacc;
5612 	rnode4_t *nrp;
5613 	rnode4_t *drp = VTOR4(dvp);
5614 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5615 
5616 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5617 	ASSERT(nm != NULL);
5618 	ASSERT(nm[0] != '\0');
5619 	ASSERT(dvp->v_type == VDIR);
5620 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5621 	ASSERT(*vpp == NULL);
5622 
5623 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5624 		isdotdot = 1;
5625 		args.ctag = TAG_LOOKUP_PARENT;
5626 	} else {
5627 		/*
5628 		 * If dvp were a stub, it should have triggered and caused
5629 		 * a mount for us to get this far.
5630 		 */
5631 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5632 
5633 		isdotdot = 0;
5634 		args.ctag = TAG_LOOKUP;
5635 	}
5636 
5637 	mi = VTOMI4(dvp);
5638 	recov_state.rs_flags = 0;
5639 	recov_state.rs_num_retry_despite_err = 0;
5640 
5641 	nvp = NULL;
5642 
5643 	/* Save the original mount point security information */
5644 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5645 
5646 recov_retry:
5647 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5648 	    &recov_state, NULL);
5649 	if (e.error) {
5650 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5651 		return (e.error);
5652 	}
5653 
5654 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5655 
5656 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5657 	args.array_len = 9;
5658 	args.array = argop;
5659 
5660 	/* 0. putfh file */
5661 	argop[0].argop = OP_CPUTFH;
5662 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5663 
5664 	/* 1. savefh for the nverify */
5665 	argop[1].argop = OP_SAVEFH;
5666 
5667 	/* 2. lookup name */
5668 	if (isdotdot) {
5669 		argop[2].argop = OP_LOOKUPP;
5670 	} else {
5671 		argop[2].argop = OP_CLOOKUP;
5672 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5673 	}
5674 
5675 	/* 3. resulting file handle */
5676 	argop[3].argop = OP_GETFH;
5677 
5678 	/* 4. resulting file attributes */
5679 	argop[4].argop = OP_GETATTR;
5680 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5681 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5682 
5683 	/* 5. restorefh back the directory for the nverify */
5684 	argop[5].argop = OP_RESTOREFH;
5685 
5686 	/* 6. nverify the change info */
5687 	argop[6].argop = OP_NVERIFY;
5688 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5689 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5690 	ver_fattr->attrlist4 = (char *)&dchange;
5691 	ptr = (int32_t *)&dchange;
5692 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5693 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5694 
5695 	/* 7. getattr directory */
5696 	argop[7].argop = OP_GETATTR;
5697 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5698 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5699 
5700 	/* 8. access directory */
5701 	argop[8].argop = OP_ACCESS;
5702 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5703 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5704 
5705 	doqueue = 1;
5706 	t = gethrtime();
5707 
5708 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5709 
5710 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5711 		/*
5712 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5713 		 * from this thread, do not go thru the recovery thread since
5714 		 * we need the nm information.
5715 		 *
5716 		 * Not doing dotdot case because there is no specification
5717 		 * for (PUTFH, SECINFO "..") yet.
5718 		 */
5719 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5720 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5721 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5722 				    &recov_state, FALSE);
5723 			else
5724 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5725 				    &recov_state, TRUE);
5726 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5727 			kmem_free(argop, argoplist_size);
5728 			if (!e.error)
5729 				goto recov_retry;
5730 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5731 			return (e.error);
5732 		}
5733 
5734 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5735 		    OP_LOOKUP, NULL) == FALSE) {
5736 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5737 			    &recov_state, TRUE);
5738 
5739 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5740 			kmem_free(argop, argoplist_size);
5741 			goto recov_retry;
5742 		}
5743 	}
5744 
5745 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5746 
5747 	if (e.error || res.array_len == 0) {
5748 		/*
5749 		 * If e.error isn't set, then reply has no ops (or we couldn't
5750 		 * be here).  The only legal way to reply without an op array
5751 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5752 		 * be in the reply for all other status values.
5753 		 *
5754 		 * For valid replies without an ops array, return ENOTSUP
5755 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5756 		 * return EIO -- don't trust status.
5757 		 */
5758 		if (e.error == 0)
5759 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5760 			    ENOTSUP : EIO;
5761 
5762 		kmem_free(argop, argoplist_size);
5763 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5764 		return (e.error);
5765 	}
5766 
5767 	e.error = geterrno4(res.status);
5768 
5769 	/*
5770 	 * The PUTFH and SAVEFH may have failed.
5771 	 */
5772 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5773 	    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5774 		nfs4_purge_stale_fh(e.error, dvp, cr);
5775 		goto exit;
5776 	}
5777 
5778 	/*
5779 	 * Check if the file exists, if it does delay entering
5780 	 * into the dnlc until after we update the directory
5781 	 * attributes so we don't cause it to get purged immediately.
5782 	 */
5783 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5784 		/*
5785 		 * The lookup failed, probably no entry
5786 		 */
5787 		if (e.error == ENOENT && nfs4_lookup_neg_cache)
5788 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5789 		goto exit;
5790 	}
5791 
5792 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5793 		/*
5794 		 * The file exists but we can't get its fh for
5795 		 * some unknown reason. Error out to be safe.
5796 		 */
5797 		goto exit;
5798 	}
5799 
5800 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5801 	if (fhp->nfs_fh4_len == 0) {
5802 		/*
5803 		 * The file exists but a bogus fh
5804 		 * some unknown reason.  Error out to be safe.
5805 		 */
5806 		e.error = EIO;
5807 		goto exit;
5808 	}
5809 	sfhp = sfh4_get(fhp, mi);
5810 
5811 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5812 		sfh4_rele(&sfhp);
5813 		goto exit;
5814 	}
5815 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5816 
5817 	/*
5818 	 * The RESTOREFH may have failed
5819 	 */
5820 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5821 		sfh4_rele(&sfhp);
5822 		e.error = EIO;
5823 		goto exit;
5824 	}
5825 
5826 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5827 		/*
5828 		 * First make sure the NVERIFY failed as we expected,
5829 		 * if it didn't then be conservative and error out
5830 		 * as we can't trust the directory.
5831 		 */
5832 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5833 			sfh4_rele(&sfhp);
5834 			e.error = EIO;
5835 			goto exit;
5836 		}
5837 
5838 		/*
5839 		 * We know the NVERIFY "failed" so the directory has changed,
5840 		 * so we must:
5841 		 *	purge the caches (access and indirectly dnlc if needed)
5842 		 */
5843 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5844 
5845 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5846 			sfh4_rele(&sfhp);
5847 			goto exit;
5848 		}
5849 		nfs4_attr_cache(dvp,
5850 		    &res.array[7].nfs_resop4_u.opgetattr.ga_res,
5851 		    t, cr, FALSE, NULL);
5852 
5853 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5854 			nfs4_purge_stale_fh(e.error, dvp, cr);
5855 			sfh4_rele(&sfhp);
5856 			e.error = geterrno4(res.status);
5857 			goto exit;
5858 		}
5859 
5860 		/*
5861 		 * Now we know the directory is valid,
5862 		 * cache new directory access
5863 		 */
5864 		nfs4_access_cache(drp,
5865 		    args.array[8].nfs_argop4_u.opaccess.access,
5866 		    res.array[8].nfs_resop4_u.opaccess.access, cr);
5867 
5868 		/*
5869 		 * recheck VEXEC access
5870 		 */
5871 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5872 		if (cacc != NFS4_ACCESS_ALLOWED) {
5873 			/*
5874 			 * Directory permissions might have been revoked
5875 			 */
5876 			if (cacc == NFS4_ACCESS_DENIED) {
5877 				sfh4_rele(&sfhp);
5878 				e.error = EACCES;
5879 				goto exit;
5880 			}
5881 
5882 			/*
5883 			 * Somehow we must not have asked for enough
5884 			 * so try a singleton ACCESS should never happen
5885 			 */
5886 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5887 			if (e.error) {
5888 				sfh4_rele(&sfhp);
5889 				goto exit;
5890 			}
5891 		}
5892 
5893 		e.error = geterrno4(res.status);
5894 	} else {
5895 		hrtime_t now;
5896 		hrtime_t delta = 0;
5897 
5898 		e.error = 0;
5899 
5900 		/*
5901 		 * Because the NVERIFY "succeeded" we know that the
5902 		 * directory attributes are still valid
5903 		 * so update r_time_attr_inval
5904 		 */
5905 		now = gethrtime();
5906 		mutex_enter(&drp->r_statelock);
5907 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5908 			delta = now - drp->r_time_attr_saved;
5909 			if (delta < mi->mi_acdirmin)
5910 				delta = mi->mi_acdirmin;
5911 			else if (delta > mi->mi_acdirmax)
5912 				delta = mi->mi_acdirmax;
5913 		}
5914 		drp->r_time_attr_inval = now + delta;
5915 		mutex_exit(&drp->r_statelock);
5916 
5917 		/*
5918 		 * Even though we have a valid directory attr cache,
5919 		 * we may not have access.
5920 		 * This should almost always hit the cache.
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 	/*
5930 	 * Now we have successfully completed the lookup, if the
5931 	 * directory has changed we now have the valid attributes.
5932 	 * We also know we have directory access.
5933 	 * Create the new rnode and insert it in the dnlc.
5934 	 */
5935 	if (isdotdot) {
5936 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5937 		if (e.error) {
5938 			sfh4_rele(&sfhp);
5939 			goto exit;
5940 		}
5941 		/*
5942 		 * XXX if nfs4_make_dotdot uses an existing rnode
5943 		 * XXX it doesn't update the attributes.
5944 		 * XXX for now just save them again to save an OTW
5945 		 */
5946 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5947 	} else {
5948 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5949 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5950 	}
5951 	sfh4_rele(&sfhp);
5952 
5953 	nrp = VTOR4(nvp);
5954 	mutex_enter(&nrp->r_statev4_lock);
5955 	if (!nrp->created_v4) {
5956 		mutex_exit(&nrp->r_statev4_lock);
5957 		dnlc_update(dvp, nm, nvp);
5958 	} else
5959 		mutex_exit(&nrp->r_statev4_lock);
5960 
5961 	*vpp = nvp;
5962 
5963 exit:
5964 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5965 	kmem_free(argop, argoplist_size);
5966 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5967 	return (e.error);
5968 }
5969 
5970 #ifdef DEBUG
5971 void
5972 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
5973 {
5974 	uint_t i, len;
5975 	zoneid_t zoneid = getzoneid();
5976 	char *s;
5977 
5978 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
5979 	for (i = 0; i < argcnt; i++) {
5980 		nfs_argop4 *op = &argbase[i];
5981 		switch (op->argop) {
5982 		case OP_CPUTFH:
5983 		case OP_PUTFH:
5984 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
5985 			break;
5986 		case OP_PUTROOTFH:
5987 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
5988 			break;
5989 		case OP_CLOOKUP:
5990 			s = op->nfs_argop4_u.opclookup.cname;
5991 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5992 			break;
5993 		case OP_LOOKUP:
5994 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
5995 			    &len, NULL);
5996 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5997 			kmem_free(s, len);
5998 			break;
5999 		case OP_LOOKUPP:
6000 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
6001 			break;
6002 		case OP_GETFH:
6003 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
6004 			break;
6005 		case OP_GETATTR:
6006 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
6007 			break;
6008 		case OP_OPENATTR:
6009 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
6010 			break;
6011 		default:
6012 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
6013 			    op->argop);
6014 			break;
6015 		}
6016 	}
6017 }
6018 #endif
6019 
6020 /*
6021  * nfs4lookup_setup - constructs a multi-lookup compound request.
6022  *
6023  * Given the path "nm1/nm2/.../nmn", the following compound requests
6024  * may be created:
6025  *
6026  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
6027  * is faster, for now.
6028  *
6029  * l4_getattrs indicates the type of compound requested.
6030  *
6031  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
6032  *
6033  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
6034  *
6035  *   total number of ops is n + 1.
6036  *
6037  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
6038  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
6039  *      before the last component, and only get attributes
6040  *      for the last component.  Note that the second-to-last
6041  *	pathname component is XATTR_RPATH, which does NOT go
6042  *	over-the-wire as a lookup.
6043  *
6044  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
6045  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
6046  *
6047  *   and total number of ops is n + 5.
6048  *
6049  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
6050  *      attribute directory: create lookups plus an OPENATTR
6051  *	replacing the last lookup.  Note that the last pathname
6052  *	component is XATTR_RPATH, which does NOT go over-the-wire
6053  *	as a lookup.
6054  *
6055  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
6056  *		Openattr; Getfh; Getattr }
6057  *
6058  *   and total number of ops is n + 5.
6059  *
6060  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6061  *	nodes too.
6062  *
6063  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6064  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6065  *
6066  *   and total number of ops is 3*n + 1.
6067  *
6068  * All cases: returns the index in the arg array of the final LOOKUP op, or
6069  * -1 if no LOOKUPs were used.
6070  */
6071 int
6072 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6073 {
6074 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6075 	nfs_argop4 *argbase, *argop;
6076 	int arglen, argcnt;
6077 	int n = 1;	/* number of components */
6078 	int nga = 1;	/* number of Getattr's in request */
6079 	char c = '\0', *s, *p;
6080 	int lookup_idx = -1;
6081 	int argoplist_size;
6082 
6083 	/* set lookuparg response result to 0 */
6084 	lookupargp->resp->status = NFS4_OK;
6085 
6086 	/* skip leading "/" or "." e.g. ".//./" if there is */
6087 	for (; ; nm++) {
6088 		if (*nm != '/' && *nm != '.')
6089 			break;
6090 
6091 		/* ".." is counted as 1 component */
6092 		if (*nm == '.' && *(nm + 1) == '.')
6093 			break;
6094 	}
6095 
6096 	/*
6097 	 * Find n = number of components - nm must be null terminated
6098 	 * Skip "." components.
6099 	 */
6100 	if (*nm != '\0')
6101 		for (n = 1, s = nm; *s != '\0'; s++) {
6102 			if ((*s == '/') && (*(s + 1) != '/') &&
6103 			    (*(s + 1) != '\0') &&
6104 			    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6105 			    *(s + 2) == '\0')))
6106 				n++;
6107 		}
6108 	else
6109 		n = 0;
6110 
6111 	/*
6112 	 * nga is number of components that need Getfh+Getattr
6113 	 */
6114 	switch (l4_getattrs) {
6115 	case LKP4_NO_ATTRIBUTES:
6116 		nga = 0;
6117 		break;
6118 	case LKP4_ALL_ATTRIBUTES:
6119 		nga = n;
6120 		/*
6121 		 * Always have at least 1 getfh, getattr pair
6122 		 */
6123 		if (nga == 0)
6124 			nga++;
6125 		break;
6126 	case LKP4_LAST_ATTRDIR:
6127 	case LKP4_LAST_NAMED_ATTR:
6128 		nga = n+1;
6129 		break;
6130 	}
6131 
6132 	/*
6133 	 * If change to use the filehandle attr instead of getfh
6134 	 * the following line can be deleted.
6135 	 */
6136 	nga *= 2;
6137 
6138 	/*
6139 	 * calculate number of ops in request as
6140 	 * header + trailer + lookups + getattrs
6141 	 */
6142 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6143 
6144 	argoplist_size = arglen * sizeof (nfs_argop4);
6145 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6146 	lookupargp->argsp->array = argop;
6147 
6148 	argcnt = lookupargp->header_len;
6149 	argop += argcnt;
6150 
6151 	/*
6152 	 * loop and create a lookup op and possibly getattr/getfh for
6153 	 * each component. Skip "." components.
6154 	 */
6155 	for (s = nm; *s != '\0'; s = p) {
6156 		/*
6157 		 * Set up a pathname struct for each component if needed
6158 		 */
6159 		while (*s == '/')
6160 			s++;
6161 		if (*s == '\0')
6162 			break;
6163 
6164 		for (p = s; (*p != '/') && (*p != '\0'); p++)
6165 			;
6166 		c = *p;
6167 		*p = '\0';
6168 
6169 		if (s[0] == '.' && s[1] == '\0') {
6170 			*p = c;
6171 			continue;
6172 		}
6173 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6174 		    strcmp(s, XATTR_RPATH) == 0) {
6175 			/* getfh XXX may not be needed in future */
6176 			argop->argop = OP_GETFH;
6177 			argop++;
6178 			argcnt++;
6179 
6180 			/* getattr */
6181 			argop->argop = OP_GETATTR;
6182 			argop->nfs_argop4_u.opgetattr.attr_request =
6183 			    lookupargp->ga_bits;
6184 			argop->nfs_argop4_u.opgetattr.mi =
6185 			    lookupargp->mi;
6186 			argop++;
6187 			argcnt++;
6188 
6189 			/* openattr */
6190 			argop->argop = OP_OPENATTR;
6191 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6192 		    strcmp(s, XATTR_RPATH) == 0) {
6193 			/* openattr */
6194 			argop->argop = OP_OPENATTR;
6195 			argop++;
6196 			argcnt++;
6197 
6198 			/* getfh XXX may not be needed in future */
6199 			argop->argop = OP_GETFH;
6200 			argop++;
6201 			argcnt++;
6202 
6203 			/* getattr */
6204 			argop->argop = OP_GETATTR;
6205 			argop->nfs_argop4_u.opgetattr.attr_request =
6206 			    lookupargp->ga_bits;
6207 			argop->nfs_argop4_u.opgetattr.mi =
6208 			    lookupargp->mi;
6209 			argop++;
6210 			argcnt++;
6211 			*p = c;
6212 			continue;
6213 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6214 			/* lookupp */
6215 			argop->argop = OP_LOOKUPP;
6216 		} else {
6217 			/* lookup */
6218 			argop->argop = OP_LOOKUP;
6219 			(void) str_to_utf8(s,
6220 			    &argop->nfs_argop4_u.oplookup.objname);
6221 		}
6222 		lookup_idx = argcnt;
6223 		argop++;
6224 		argcnt++;
6225 
6226 		*p = c;
6227 
6228 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6229 			/* getfh XXX may not be needed in future */
6230 			argop->argop = OP_GETFH;
6231 			argop++;
6232 			argcnt++;
6233 
6234 			/* getattr */
6235 			argop->argop = OP_GETATTR;
6236 			argop->nfs_argop4_u.opgetattr.attr_request =
6237 			    lookupargp->ga_bits;
6238 			argop->nfs_argop4_u.opgetattr.mi =
6239 			    lookupargp->mi;
6240 			argop++;
6241 			argcnt++;
6242 		}
6243 	}
6244 
6245 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6246 	    ((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6247 		if (needgetfh) {
6248 			/* stick in a post-lookup getfh */
6249 			argop->argop = OP_GETFH;
6250 			argcnt++;
6251 			argop++;
6252 		}
6253 		/* post-lookup getattr */
6254 		argop->argop = OP_GETATTR;
6255 		argop->nfs_argop4_u.opgetattr.attr_request =
6256 		    lookupargp->ga_bits;
6257 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6258 		argcnt++;
6259 	}
6260 	argcnt += lookupargp->trailer_len;	/* actual op count */
6261 	lookupargp->argsp->array_len = argcnt;
6262 	lookupargp->arglen = arglen;
6263 
6264 #ifdef DEBUG
6265 	if (nfs4_client_lookup_debug)
6266 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6267 #endif
6268 
6269 	return (lookup_idx);
6270 }
6271 
6272 static int
6273 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6274 {
6275 	COMPOUND4args_clnt	args;
6276 	COMPOUND4res_clnt	res;
6277 	GETFH4res	*gf_res = NULL;
6278 	nfs_argop4	argop[4];
6279 	nfs_resop4	*resop = NULL;
6280 	nfs4_sharedfh_t *sfhp;
6281 	hrtime_t t;
6282 	nfs4_error_t	e;
6283 
6284 	rnode4_t	*drp;
6285 	int		doqueue = 1;
6286 	vnode_t		*vp;
6287 	int		needrecov = 0;
6288 	nfs4_recov_state_t recov_state;
6289 
6290 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6291 
6292 	*avp = NULL;
6293 	recov_state.rs_flags = 0;
6294 	recov_state.rs_num_retry_despite_err = 0;
6295 
6296 recov_retry:
6297 	/* COMPOUND: putfh, openattr, getfh, getattr */
6298 	args.array_len = 4;
6299 	args.array = argop;
6300 	args.ctag = TAG_OPENATTR;
6301 
6302 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6303 	if (e.error)
6304 		return (e.error);
6305 
6306 	drp = VTOR4(dvp);
6307 
6308 	/* putfh */
6309 	argop[0].argop = OP_CPUTFH;
6310 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6311 
6312 	/* openattr */
6313 	argop[1].argop = OP_OPENATTR;
6314 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6315 
6316 	/* getfh */
6317 	argop[2].argop = OP_GETFH;
6318 
6319 	/* getattr */
6320 	argop[3].argop = OP_GETATTR;
6321 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6322 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6323 
6324 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6325 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6326 	    rnode4info(drp)));
6327 
6328 	t = gethrtime();
6329 
6330 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6331 
6332 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6333 	if (needrecov) {
6334 		bool_t abort;
6335 
6336 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6337 		    "nfs4openattr: initiating recovery\n"));
6338 
6339 		abort = nfs4_start_recovery(&e,
6340 		    VTOMI4(dvp), dvp, NULL, NULL, NULL,
6341 		    OP_OPENATTR, NULL);
6342 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6343 		if (!e.error) {
6344 			e.error = geterrno4(res.status);
6345 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6346 		}
6347 		if (abort == FALSE)
6348 			goto recov_retry;
6349 		return (e.error);
6350 	}
6351 
6352 	if (e.error) {
6353 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6354 		return (e.error);
6355 	}
6356 
6357 	if (res.status) {
6358 		/*
6359 		 * If OTW errro is NOTSUPP, then it should be
6360 		 * translated to EINVAL.  All Solaris file system
6361 		 * implementations return EINVAL to the syscall layer
6362 		 * when the attrdir cannot be created due to an
6363 		 * implementation restriction or noxattr mount option.
6364 		 */
6365 		if (res.status == NFS4ERR_NOTSUPP) {
6366 			mutex_enter(&drp->r_statelock);
6367 			if (drp->r_xattr_dir)
6368 				VN_RELE(drp->r_xattr_dir);
6369 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6370 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6371 			mutex_exit(&drp->r_statelock);
6372 
6373 			e.error = EINVAL;
6374 		} else {
6375 			e.error = geterrno4(res.status);
6376 		}
6377 
6378 		if (e.error) {
6379 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6380 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6381 			    needrecov);
6382 			return (e.error);
6383 		}
6384 	}
6385 
6386 	resop = &res.array[0];  /* putfh res */
6387 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6388 
6389 	resop = &res.array[1];  /* openattr res */
6390 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6391 
6392 	resop = &res.array[2];  /* getfh res */
6393 	gf_res = &resop->nfs_resop4_u.opgetfh;
6394 	if (gf_res->object.nfs_fh4_len == 0) {
6395 		*avp = NULL;
6396 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6397 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6398 		return (ENOENT);
6399 	}
6400 
6401 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6402 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6403 	    dvp->v_vfsp, t, cr, dvp,
6404 	    fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH));
6405 	sfh4_rele(&sfhp);
6406 
6407 	if (e.error)
6408 		PURGE_ATTRCACHE4(vp);
6409 
6410 	mutex_enter(&vp->v_lock);
6411 	vp->v_flag |= V_XATTRDIR;
6412 	mutex_exit(&vp->v_lock);
6413 
6414 	*avp = vp;
6415 
6416 	mutex_enter(&drp->r_statelock);
6417 	if (drp->r_xattr_dir)
6418 		VN_RELE(drp->r_xattr_dir);
6419 	VN_HOLD(vp);
6420 	drp->r_xattr_dir = vp;
6421 
6422 	/*
6423 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6424 	 * NULL.  xattrs could be created at any time, and we have no
6425 	 * way to update pc4_xattr_exists in the base object if/when
6426 	 * it happens.
6427 	 */
6428 	drp->r_pathconf.pc4_xattr_valid = 0;
6429 
6430 	mutex_exit(&drp->r_statelock);
6431 
6432 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6433 
6434 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6435 
6436 	return (0);
6437 }
6438 
6439 /* ARGSUSED */
6440 static int
6441 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6442 	int mode, vnode_t **vpp, cred_t *cr, int flags, caller_context_t *ct,
6443 	vsecattr_t *vsecp)
6444 {
6445 	int error;
6446 	vnode_t *vp = NULL;
6447 	rnode4_t *rp;
6448 	struct vattr vattr;
6449 	rnode4_t *drp;
6450 	vnode_t *tempvp;
6451 	enum createmode4 createmode;
6452 	bool_t must_trunc = FALSE;
6453 	int	truncating = 0;
6454 
6455 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6456 		return (EPERM);
6457 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6458 		return (EINVAL);
6459 	}
6460 
6461 	/* . and .. have special meaning in the protocol, reject them. */
6462 
6463 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6464 		return (EISDIR);
6465 
6466 	drp = VTOR4(dvp);
6467 
6468 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6469 		return (EINTR);
6470 
6471 top:
6472 	/*
6473 	 * We make a copy of the attributes because the caller does not
6474 	 * expect us to change what va points to.
6475 	 */
6476 	vattr = *va;
6477 
6478 	/*
6479 	 * If the pathname is "", then dvp is the root vnode of
6480 	 * a remote file mounted over a local directory.
6481 	 * All that needs to be done is access
6482 	 * checking and truncation.  Note that we avoid doing
6483 	 * open w/ create because the parent directory might
6484 	 * be in pseudo-fs and the open would fail.
6485 	 */
6486 	if (*nm == '\0') {
6487 		error = 0;
6488 		VN_HOLD(dvp);
6489 		vp = dvp;
6490 		must_trunc = TRUE;
6491 	} else {
6492 		/*
6493 		 * We need to go over the wire, just to be sure whether the
6494 		 * file exists or not.  Using the DNLC can be dangerous in
6495 		 * this case when making a decision regarding existence.
6496 		 */
6497 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6498 	}
6499 
6500 	if (exclusive)
6501 		createmode = EXCLUSIVE4;
6502 	else
6503 		createmode = GUARDED4;
6504 
6505 	/*
6506 	 * error would be set if the file does not exist on the
6507 	 * server, so lets go create it.
6508 	 */
6509 	if (error) {
6510 		goto create_otw;
6511 	}
6512 
6513 	/*
6514 	 * File does exist on the server
6515 	 */
6516 	if (exclusive == EXCL)
6517 		error = EEXIST;
6518 	else if (vp->v_type == VDIR && (mode & VWRITE))
6519 		error = EISDIR;
6520 	else {
6521 		/*
6522 		 * If vnode is a device, create special vnode.
6523 		 */
6524 		if (ISVDEV(vp->v_type)) {
6525 			tempvp = vp;
6526 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6527 			VN_RELE(tempvp);
6528 		}
6529 		if (!(error = VOP_ACCESS(vp, mode, 0, cr, ct))) {
6530 			if ((vattr.va_mask & AT_SIZE) &&
6531 			    vp->v_type == VREG) {
6532 				rp = VTOR4(vp);
6533 				/*
6534 				 * Check here for large file handled
6535 				 * by LF-unaware process (as
6536 				 * ufs_create() does)
6537 				 */
6538 				if (!(flags & FOFFMAX)) {
6539 					mutex_enter(&rp->r_statelock);
6540 					if (rp->r_size > MAXOFF32_T)
6541 						error = EOVERFLOW;
6542 					mutex_exit(&rp->r_statelock);
6543 				}
6544 
6545 				/* if error is set then we need to return */
6546 				if (error) {
6547 					nfs_rw_exit(&drp->r_rwlock);
6548 					VN_RELE(vp);
6549 					return (error);
6550 				}
6551 
6552 				if (must_trunc) {
6553 					vattr.va_mask = AT_SIZE;
6554 					error = nfs4setattr(vp, &vattr, 0, cr,
6555 					    NULL);
6556 				} else {
6557 				/*
6558 				 * we know we have a regular file that already
6559 				 * exists and we may end up truncating the file
6560 				 * as a result of the open_otw, so flush out
6561 				 * any dirty pages for this file first.
6562 				 */
6563 					if (nfs4_has_pages(vp) &&
6564 					    ((rp->r_flags & R4DIRTY) ||
6565 					    rp->r_count > 0 ||
6566 					    rp->r_mapcnt > 0)) {
6567 						error = nfs4_putpage(vp,
6568 						    (offset_t)0, 0, 0, cr, ct);
6569 						if (error && (error == ENOSPC ||
6570 						    error == EDQUOT)) {
6571 							mutex_enter(
6572 							    &rp->r_statelock);
6573 							if (!rp->r_error)
6574 								rp->r_error =
6575 								    error;
6576 							mutex_exit(
6577 							    &rp->r_statelock);
6578 						}
6579 					}
6580 					vattr.va_mask = (AT_SIZE |
6581 					    AT_TYPE | AT_MODE);
6582 					vattr.va_type = VREG;
6583 					createmode = UNCHECKED4;
6584 					truncating = 1;
6585 					goto create_otw;
6586 				}
6587 			}
6588 		}
6589 	}
6590 	nfs_rw_exit(&drp->r_rwlock);
6591 	if (error) {
6592 		VN_RELE(vp);
6593 	} else {
6594 		vnode_t *tvp;
6595 		rnode4_t *trp;
6596 		/*
6597 		 * existing file got truncated, notify.
6598 		 */
6599 		tvp = vp;
6600 		if (vp->v_type == VREG) {
6601 			trp = VTOR4(vp);
6602 			if (IS_SHADOW(vp, trp))
6603 				tvp = RTOV4(trp);
6604 		}
6605 		vnevent_create(tvp, ct);
6606 		*vpp = vp;
6607 	}
6608 	return (error);
6609 
6610 create_otw:
6611 	dnlc_remove(dvp, nm);
6612 
6613 	ASSERT(vattr.va_mask & AT_TYPE);
6614 
6615 	/*
6616 	 * If not a regular file let nfs4mknod() handle it.
6617 	 */
6618 	if (vattr.va_type != VREG) {
6619 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6620 		nfs_rw_exit(&drp->r_rwlock);
6621 		return (error);
6622 	}
6623 
6624 	/*
6625 	 * It _is_ a regular file.
6626 	 */
6627 	ASSERT(vattr.va_mask & AT_MODE);
6628 	if (MANDMODE(vattr.va_mode)) {
6629 		nfs_rw_exit(&drp->r_rwlock);
6630 		return (EACCES);
6631 	}
6632 
6633 	/*
6634 	 * If this happens to be a mknod of a regular file, then flags will
6635 	 * have neither FREAD or FWRITE.  However, we must set at least one
6636 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6637 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6638 	 * set (based on openmode specified by app).
6639 	 */
6640 	if ((flags & (FREAD|FWRITE)) == 0)
6641 		flags |= (FREAD|FWRITE);
6642 
6643 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6644 
6645 	if (vp != NULL) {
6646 		/* if create was successful, throw away the file's pages */
6647 		if (!error && (vattr.va_mask & AT_SIZE))
6648 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6649 			    cr);
6650 		/* release the lookup hold */
6651 		VN_RELE(vp);
6652 		vp = NULL;
6653 	}
6654 
6655 	/*
6656 	 * validate that we opened a regular file. This handles a misbehaving
6657 	 * server that returns an incorrect FH.
6658 	 */
6659 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6660 		error = EISDIR;
6661 		VN_RELE(*vpp);
6662 	}
6663 
6664 	/*
6665 	 * If this is not an exclusive create, then the CREATE
6666 	 * request will be made with the GUARDED mode set.  This
6667 	 * means that the server will return EEXIST if the file
6668 	 * exists.  The file could exist because of a retransmitted
6669 	 * request.  In this case, we recover by starting over and
6670 	 * checking to see whether the file exists.  This second
6671 	 * time through it should and a CREATE request will not be
6672 	 * sent.
6673 	 *
6674 	 * This handles the problem of a dangling CREATE request
6675 	 * which contains attributes which indicate that the file
6676 	 * should be truncated.  This retransmitted request could
6677 	 * possibly truncate valid data in the file if not caught
6678 	 * by the duplicate request mechanism on the server or if
6679 	 * not caught by other means.  The scenario is:
6680 	 *
6681 	 * Client transmits CREATE request with size = 0
6682 	 * Client times out, retransmits request.
6683 	 * Response to the first request arrives from the server
6684 	 *  and the client proceeds on.
6685 	 * Client writes data to the file.
6686 	 * The server now processes retransmitted CREATE request
6687 	 *  and truncates file.
6688 	 *
6689 	 * The use of the GUARDED CREATE request prevents this from
6690 	 * happening because the retransmitted CREATE would fail
6691 	 * with EEXIST and would not truncate the file.
6692 	 */
6693 	if (error == EEXIST && exclusive == NONEXCL) {
6694 #ifdef DEBUG
6695 		nfs4_create_misses++;
6696 #endif
6697 		goto top;
6698 	}
6699 	nfs_rw_exit(&drp->r_rwlock);
6700 	if (truncating && !error && *vpp) {
6701 		vnode_t *tvp;
6702 		rnode4_t *trp;
6703 		/*
6704 		 * existing file got truncated, notify.
6705 		 */
6706 		tvp = *vpp;
6707 		trp = VTOR4(tvp);
6708 		if (IS_SHADOW(tvp, trp))
6709 			tvp = RTOV4(trp);
6710 		vnevent_create(tvp, ct);
6711 	}
6712 	return (error);
6713 }
6714 
6715 /*
6716  * Create compound (for mkdir, mknod, symlink):
6717  * { Putfh <dfh>; Create; Getfh; Getattr }
6718  * It's okay if setattr failed to set gid - this is not considered
6719  * an error, but purge attrs in that case.
6720  */
6721 static int
6722 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6723     vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6724 {
6725 	int need_end_op = FALSE;
6726 	COMPOUND4args_clnt args;
6727 	COMPOUND4res_clnt res, *resp = NULL;
6728 	nfs_argop4 *argop;
6729 	nfs_resop4 *resop;
6730 	int doqueue;
6731 	mntinfo4_t *mi;
6732 	rnode4_t *drp = VTOR4(dvp);
6733 	change_info4 *cinfo;
6734 	GETFH4res *gf_res;
6735 	struct vattr vattr;
6736 	vnode_t *vp;
6737 	fattr4 *crattr;
6738 	bool_t needrecov = FALSE;
6739 	nfs4_recov_state_t recov_state;
6740 	nfs4_sharedfh_t *sfhp = NULL;
6741 	hrtime_t t;
6742 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6743 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6744 	dirattr_info_t dinfo, *dinfop;
6745 	servinfo4_t *svp;
6746 	bitmap4 supp_attrs;
6747 
6748 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6749 	    type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6750 
6751 	mi = VTOMI4(dvp);
6752 
6753 	/*
6754 	 * Make sure we properly deal with setting the right gid
6755 	 * on a new directory to reflect the parent's setgid bit
6756 	 */
6757 	setgid_flag = 0;
6758 	if (type == NF4DIR) {
6759 		struct vattr dva;
6760 
6761 		va->va_mode &= ~VSGID;
6762 		dva.va_mask = AT_MODE | AT_GID;
6763 		if (VOP_GETATTR(dvp, &dva, 0, cr, NULL) == 0) {
6764 
6765 			/*
6766 			 * If the parent's directory has the setgid bit set
6767 			 * _and_ the client was able to get a valid mapping
6768 			 * for the parent dir's owner_group, we want to
6769 			 * append NVERIFY(owner_group == dva.va_gid) and
6770 			 * SETTATTR to the CREATE compound.
6771 			 */
6772 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6773 				setgid_flag = 1;
6774 				va->va_mode |= VSGID;
6775 				if (dva.va_gid != GID_NOBODY) {
6776 					va->va_mask |= AT_GID;
6777 					va->va_gid = dva.va_gid;
6778 				}
6779 			}
6780 		}
6781 	}
6782 
6783 	/*
6784 	 * Create ops:
6785 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6786 	 *	5:restorefh(dir) 6:getattr(dir)
6787 	 *
6788 	 * if (setgid)
6789 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6790 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6791 	 *	8:nverify 9:setattr
6792 	 */
6793 	if (setgid_flag) {
6794 		numops = 10;
6795 		idx_create = 1;
6796 		idx_fattr = 3;
6797 	} else {
6798 		numops = 7;
6799 		idx_create = 2;
6800 		idx_fattr = 4;
6801 	}
6802 
6803 	ASSERT(nfs_zone() == mi->mi_zone);
6804 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6805 		return (EINTR);
6806 	}
6807 	recov_state.rs_flags = 0;
6808 	recov_state.rs_num_retry_despite_err = 0;
6809 
6810 	argoplist_size = numops * sizeof (nfs_argop4);
6811 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6812 
6813 recov_retry:
6814 	if (type == NF4LNK)
6815 		args.ctag = TAG_SYMLINK;
6816 	else if (type == NF4DIR)
6817 		args.ctag = TAG_MKDIR;
6818 	else
6819 		args.ctag = TAG_MKNOD;
6820 
6821 	args.array_len = numops;
6822 	args.array = argop;
6823 
6824 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6825 		nfs_rw_exit(&drp->r_rwlock);
6826 		kmem_free(argop, argoplist_size);
6827 		return (e.error);
6828 	}
6829 	need_end_op = TRUE;
6830 
6831 
6832 	/* 0: putfh directory */
6833 	argop[0].argop = OP_CPUTFH;
6834 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6835 
6836 	/* 1/2: Create object */
6837 	argop[idx_create].argop = OP_CCREATE;
6838 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6839 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6840 	if (type == NF4LNK) {
6841 		/*
6842 		 * symlink, treat name as data
6843 		 */
6844 		ASSERT(data != NULL);
6845 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6846 		    (char *)data;
6847 	}
6848 	if (type == NF4BLK || type == NF4CHR) {
6849 		ASSERT(data != NULL);
6850 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6851 		    *((specdata4 *)data);
6852 	}
6853 
6854 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6855 
6856 	svp = drp->r_server;
6857 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6858 	supp_attrs = svp->sv_supp_attrs;
6859 	nfs_rw_exit(&svp->sv_lock);
6860 
6861 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6862 		nfs_rw_exit(&drp->r_rwlock);
6863 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6864 		e.error = EINVAL;
6865 		kmem_free(argop, argoplist_size);
6866 		return (e.error);
6867 	}
6868 
6869 	/* 2/3: getfh fh of created object */
6870 	ASSERT(idx_create + 1 == idx_fattr - 1);
6871 	argop[idx_create + 1].argop = OP_GETFH;
6872 
6873 	/* 3/4: getattr of new object */
6874 	argop[idx_fattr].argop = OP_GETATTR;
6875 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6876 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6877 
6878 	if (setgid_flag) {
6879 		vattr_t	_v;
6880 
6881 		argop[4].argop = OP_SAVEFH;
6882 
6883 		argop[5].argop = OP_CPUTFH;
6884 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6885 
6886 		argop[6].argop = OP_GETATTR;
6887 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6888 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6889 
6890 		argop[7].argop = OP_RESTOREFH;
6891 
6892 		/*
6893 		 * nverify
6894 		 *
6895 		 * XXX - Revisit the last argument to nfs4_end_op()
6896 		 *	 once 5020486 is fixed.
6897 		 */
6898 		_v.va_mask = AT_GID;
6899 		_v.va_gid = va->va_gid;
6900 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6901 		    supp_attrs)) {
6902 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6903 			nfs_rw_exit(&drp->r_rwlock);
6904 			nfs4_fattr4_free(crattr);
6905 			kmem_free(argop, argoplist_size);
6906 			return (e.error);
6907 		}
6908 
6909 		/*
6910 		 * setattr
6911 		 *
6912 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
6913 		 * so no need for stateid or flags. Also we specify NULL
6914 		 * rp since we're only interested in setting owner_group
6915 		 * attributes.
6916 		 */
6917 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
6918 		    &e.error, 0);
6919 
6920 		if (e.error) {
6921 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6922 			nfs_rw_exit(&drp->r_rwlock);
6923 			nfs4_fattr4_free(crattr);
6924 			nfs4args_verify_free(&argop[8]);
6925 			kmem_free(argop, argoplist_size);
6926 			return (e.error);
6927 		}
6928 	} else {
6929 		argop[1].argop = OP_SAVEFH;
6930 
6931 		argop[5].argop = OP_RESTOREFH;
6932 
6933 		argop[6].argop = OP_GETATTR;
6934 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6935 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6936 	}
6937 
6938 	dnlc_remove(dvp, nm);
6939 
6940 	doqueue = 1;
6941 	t = gethrtime();
6942 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
6943 
6944 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
6945 	if (e.error) {
6946 		PURGE_ATTRCACHE4(dvp);
6947 		if (!needrecov)
6948 			goto out;
6949 	}
6950 
6951 	if (needrecov) {
6952 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
6953 		    OP_CREATE, NULL) == FALSE) {
6954 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6955 			    needrecov);
6956 			need_end_op = FALSE;
6957 			nfs4_fattr4_free(crattr);
6958 			if (setgid_flag) {
6959 				nfs4args_verify_free(&argop[8]);
6960 				nfs4args_setattr_free(&argop[9]);
6961 			}
6962 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6963 			goto recov_retry;
6964 		}
6965 	}
6966 
6967 	resp = &res;
6968 
6969 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
6970 
6971 		if (res.status == NFS4ERR_BADOWNER)
6972 			nfs4_log_badowner(mi, OP_CREATE);
6973 
6974 		e.error = geterrno4(res.status);
6975 
6976 		/*
6977 		 * This check is left over from when create was implemented
6978 		 * using a setattr op (instead of createattrs).  If the
6979 		 * putfh/create/getfh failed, the error was returned.  If
6980 		 * setattr/getattr failed, we keep going.
6981 		 *
6982 		 * It might be better to get rid of the GETFH also, and just
6983 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
6984 		 * Then if any of the operations failed, we could return the
6985 		 * error now, and remove much of the error code below.
6986 		 */
6987 		if (res.array_len <= idx_fattr) {
6988 			/*
6989 			 * Either Putfh, Create or Getfh failed.
6990 			 */
6991 			PURGE_ATTRCACHE4(dvp);
6992 			/*
6993 			 * nfs4_purge_stale_fh() may generate otw calls through
6994 			 * nfs4_invalidate_pages. Hence the need to call
6995 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
6996 			 */
6997 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6998 			    needrecov);
6999 			need_end_op = FALSE;
7000 			nfs4_purge_stale_fh(e.error, dvp, cr);
7001 			goto out;
7002 		}
7003 	}
7004 
7005 	resop = &res.array[idx_create];	/* create res */
7006 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
7007 
7008 	resop = &res.array[idx_create + 1]; /* getfh res */
7009 	gf_res = &resop->nfs_resop4_u.opgetfh;
7010 
7011 	sfhp = sfh4_get(&gf_res->object, mi);
7012 	if (e.error) {
7013 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
7014 		    fn_get(VTOSV(dvp)->sv_name, nm));
7015 		if (vp->v_type == VNON) {
7016 			vattr.va_mask = AT_TYPE;
7017 			/*
7018 			 * Need to call nfs4_end_op before nfs4getattr to avoid
7019 			 * potential nfs4_start_op deadlock. See RFE 4777612.
7020 			 */
7021 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7022 			    needrecov);
7023 			need_end_op = FALSE;
7024 			e.error = nfs4getattr(vp, &vattr, cr);
7025 			if (e.error) {
7026 				VN_RELE(vp);
7027 				*vpp = NULL;
7028 				goto out;
7029 			}
7030 			vp->v_type = vattr.va_type;
7031 		}
7032 		e.error = 0;
7033 	} else {
7034 		*vpp = vp = makenfs4node(sfhp,
7035 		    &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
7036 		    dvp->v_vfsp, t, cr,
7037 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
7038 	}
7039 
7040 	/*
7041 	 * If compound succeeded, then update dir attrs
7042 	 */
7043 	if (res.status == NFS4_OK) {
7044 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
7045 		dinfo.di_cred = cr;
7046 		dinfo.di_time_call = t;
7047 		dinfop = &dinfo;
7048 	} else
7049 		dinfop = NULL;
7050 
7051 	/* Update directory cache attribute, readdir and dnlc caches */
7052 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
7053 
7054 out:
7055 	if (sfhp != NULL)
7056 		sfh4_rele(&sfhp);
7057 	nfs_rw_exit(&drp->r_rwlock);
7058 	nfs4_fattr4_free(crattr);
7059 	if (setgid_flag) {
7060 		nfs4args_verify_free(&argop[8]);
7061 		nfs4args_setattr_free(&argop[9]);
7062 	}
7063 	if (resp)
7064 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7065 	if (need_end_op)
7066 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7067 
7068 	kmem_free(argop, argoplist_size);
7069 	return (e.error);
7070 }
7071 
7072 /* ARGSUSED */
7073 static int
7074 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7075     int mode, vnode_t **vpp, cred_t *cr)
7076 {
7077 	int error;
7078 	vnode_t *vp;
7079 	nfs_ftype4 type;
7080 	specdata4 spec, *specp = NULL;
7081 
7082 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7083 
7084 	switch (va->va_type) {
7085 	case VCHR:
7086 	case VBLK:
7087 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7088 		spec.specdata1 = getmajor(va->va_rdev);
7089 		spec.specdata2 = getminor(va->va_rdev);
7090 		specp = &spec;
7091 		break;
7092 
7093 	case VFIFO:
7094 		type = NF4FIFO;
7095 		break;
7096 	case VSOCK:
7097 		type = NF4SOCK;
7098 		break;
7099 
7100 	default:
7101 		return (EINVAL);
7102 	}
7103 
7104 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7105 	if (error) {
7106 		return (error);
7107 	}
7108 
7109 	/*
7110 	 * This might not be needed any more; special case to deal
7111 	 * with problematic v2/v3 servers.  Since create was unable
7112 	 * to set group correctly, not sure what hope setattr has.
7113 	 */
7114 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7115 		va->va_mask = AT_GID;
7116 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7117 	}
7118 
7119 	/*
7120 	 * If vnode is a device create special vnode
7121 	 */
7122 	if (ISVDEV(vp->v_type)) {
7123 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7124 		VN_RELE(vp);
7125 	} else {
7126 		*vpp = vp;
7127 	}
7128 	return (error);
7129 }
7130 
7131 /*
7132  * Remove requires that the current fh be the target directory.
7133  * After the operation, the current fh is unchanged.
7134  * The compound op structure is:
7135  *      PUTFH(targetdir), REMOVE
7136  *
7137  * Weirdness: if the vnode to be removed is open
7138  * we rename it instead of removing it and nfs_inactive
7139  * will remove the new name.
7140  */
7141 /* ARGSUSED */
7142 static int
7143 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr, caller_context_t *ct, int flags)
7144 {
7145 	COMPOUND4args_clnt args;
7146 	COMPOUND4res_clnt res, *resp = NULL;
7147 	REMOVE4res *rm_res;
7148 	nfs_argop4 argop[3];
7149 	nfs_resop4 *resop;
7150 	vnode_t *vp;
7151 	char *tmpname;
7152 	int doqueue;
7153 	mntinfo4_t *mi;
7154 	rnode4_t *rp;
7155 	rnode4_t *drp;
7156 	int needrecov = 0;
7157 	nfs4_recov_state_t recov_state;
7158 	int isopen;
7159 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7160 	dirattr_info_t dinfo;
7161 
7162 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7163 		return (EPERM);
7164 	drp = VTOR4(dvp);
7165 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7166 		return (EINTR);
7167 
7168 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7169 	if (e.error) {
7170 		nfs_rw_exit(&drp->r_rwlock);
7171 		return (e.error);
7172 	}
7173 
7174 	if (vp->v_type == VDIR) {
7175 		VN_RELE(vp);
7176 		nfs_rw_exit(&drp->r_rwlock);
7177 		return (EISDIR);
7178 	}
7179 
7180 	/*
7181 	 * First just remove the entry from the name cache, as it
7182 	 * is most likely the only entry for this vp.
7183 	 */
7184 	dnlc_remove(dvp, nm);
7185 
7186 	rp = VTOR4(vp);
7187 
7188 	/*
7189 	 * For regular file types, check to see if the file is open by looking
7190 	 * at the open streams.
7191 	 * For all other types, check the reference count on the vnode.  Since
7192 	 * they are not opened OTW they never have an open stream.
7193 	 *
7194 	 * If the file is open, rename it to .nfsXXXX.
7195 	 */
7196 	if (vp->v_type != VREG) {
7197 		/*
7198 		 * If the file has a v_count > 1 then there may be more than one
7199 		 * entry in the name cache due multiple links or an open file,
7200 		 * but we don't have the real reference count so flush all
7201 		 * possible entries.
7202 		 */
7203 		if (vp->v_count > 1)
7204 			dnlc_purge_vp(vp);
7205 
7206 		/*
7207 		 * Now we have the real reference count.
7208 		 */
7209 		isopen = vp->v_count > 1;
7210 	} else {
7211 		mutex_enter(&rp->r_os_lock);
7212 		isopen = list_head(&rp->r_open_streams) != NULL;
7213 		mutex_exit(&rp->r_os_lock);
7214 	}
7215 
7216 	mutex_enter(&rp->r_statelock);
7217 	if (isopen &&
7218 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7219 		mutex_exit(&rp->r_statelock);
7220 		tmpname = newname();
7221 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr, ct);
7222 		if (e.error)
7223 			kmem_free(tmpname, MAXNAMELEN);
7224 		else {
7225 			mutex_enter(&rp->r_statelock);
7226 			if (rp->r_unldvp == NULL) {
7227 				VN_HOLD(dvp);
7228 				rp->r_unldvp = dvp;
7229 				if (rp->r_unlcred != NULL)
7230 					crfree(rp->r_unlcred);
7231 				crhold(cr);
7232 				rp->r_unlcred = cr;
7233 				rp->r_unlname = tmpname;
7234 			} else {
7235 				kmem_free(rp->r_unlname, MAXNAMELEN);
7236 				rp->r_unlname = tmpname;
7237 			}
7238 			mutex_exit(&rp->r_statelock);
7239 		}
7240 		VN_RELE(vp);
7241 		nfs_rw_exit(&drp->r_rwlock);
7242 		return (e.error);
7243 	}
7244 	/*
7245 	 * Actually remove the file/dir
7246 	 */
7247 	mutex_exit(&rp->r_statelock);
7248 
7249 	/*
7250 	 * We need to flush any dirty pages which happen to
7251 	 * be hanging around before removing the file.
7252 	 * This shouldn't happen very often since in NFSv4
7253 	 * we should be close to open consistent.
7254 	 */
7255 	if (nfs4_has_pages(vp) &&
7256 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7257 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, ct);
7258 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7259 			mutex_enter(&rp->r_statelock);
7260 			if (!rp->r_error)
7261 				rp->r_error = e.error;
7262 			mutex_exit(&rp->r_statelock);
7263 		}
7264 	}
7265 
7266 	mi = VTOMI4(dvp);
7267 
7268 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7269 	recov_state.rs_flags = 0;
7270 	recov_state.rs_num_retry_despite_err = 0;
7271 
7272 recov_retry:
7273 	/*
7274 	 * Remove ops: putfh dir; remove
7275 	 */
7276 	args.ctag = TAG_REMOVE;
7277 	args.array_len = 3;
7278 	args.array = argop;
7279 
7280 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7281 	if (e.error) {
7282 		nfs_rw_exit(&drp->r_rwlock);
7283 		VN_RELE(vp);
7284 		return (e.error);
7285 	}
7286 
7287 	/* putfh directory */
7288 	argop[0].argop = OP_CPUTFH;
7289 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7290 
7291 	/* remove */
7292 	argop[1].argop = OP_CREMOVE;
7293 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7294 
7295 	/* getattr dir */
7296 	argop[2].argop = OP_GETATTR;
7297 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7298 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7299 
7300 	doqueue = 1;
7301 	dinfo.di_time_call = gethrtime();
7302 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7303 
7304 	PURGE_ATTRCACHE4(vp);
7305 
7306 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7307 	if (e.error)
7308 		PURGE_ATTRCACHE4(dvp);
7309 
7310 	if (needrecov) {
7311 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7312 		    NULL, NULL, NULL, OP_REMOVE, NULL) == FALSE) {
7313 			if (!e.error)
7314 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7315 				    (caddr_t)&res);
7316 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7317 			    needrecov);
7318 			goto recov_retry;
7319 		}
7320 	}
7321 
7322 	/*
7323 	 * Matching nfs4_end_op() for start_op() above.
7324 	 * There is a path in the code below which calls
7325 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7326 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7327 	 * here to avoid nfs4_start_op() deadlock.
7328 	 */
7329 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7330 
7331 	if (!e.error) {
7332 		resp = &res;
7333 
7334 		if (res.status) {
7335 			e.error = geterrno4(res.status);
7336 			PURGE_ATTRCACHE4(dvp);
7337 			nfs4_purge_stale_fh(e.error, dvp, cr);
7338 		} else {
7339 			resop = &res.array[1];	/* remove res */
7340 			rm_res = &resop->nfs_resop4_u.opremove;
7341 
7342 			dinfo.di_garp =
7343 			    &res.array[2].nfs_resop4_u.opgetattr.ga_res;
7344 			dinfo.di_cred = cr;
7345 
7346 			/* Update directory attr, readdir and dnlc caches */
7347 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7348 			    &dinfo);
7349 		}
7350 	}
7351 	nfs_rw_exit(&drp->r_rwlock);
7352 	if (resp)
7353 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7354 
7355 	if (e.error == 0) {
7356 		vnode_t *tvp;
7357 		rnode4_t *trp;
7358 		trp = VTOR4(vp);
7359 		tvp = vp;
7360 		if (IS_SHADOW(vp, trp))
7361 			tvp = RTOV4(trp);
7362 		vnevent_remove(tvp, dvp, nm, ct);
7363 	}
7364 	VN_RELE(vp);
7365 	return (e.error);
7366 }
7367 
7368 /*
7369  * Link requires that the current fh be the target directory and the
7370  * saved fh be the source fh. After the operation, the current fh is unchanged.
7371  * Thus the compound op structure is:
7372  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7373  *	GETATTR(file)
7374  */
7375 /* ARGSUSED */
7376 static int
7377 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr,
7378     caller_context_t *ct, int flags)
7379 {
7380 	COMPOUND4args_clnt args;
7381 	COMPOUND4res_clnt res, *resp = NULL;
7382 	LINK4res *ln_res;
7383 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7384 	nfs_argop4 *argop;
7385 	nfs_resop4 *resop;
7386 	vnode_t *realvp, *nvp;
7387 	int doqueue;
7388 	mntinfo4_t *mi;
7389 	rnode4_t *tdrp;
7390 	bool_t needrecov = FALSE;
7391 	nfs4_recov_state_t recov_state;
7392 	hrtime_t t;
7393 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7394 	dirattr_info_t dinfo;
7395 
7396 	ASSERT(*tnm != '\0');
7397 	ASSERT(tdvp->v_type == VDIR);
7398 	ASSERT(nfs4_consistent_type(tdvp));
7399 	ASSERT(nfs4_consistent_type(svp));
7400 
7401 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7402 		return (EPERM);
7403 	if (VOP_REALVP(svp, &realvp, ct) == 0) {
7404 		svp = realvp;
7405 		ASSERT(nfs4_consistent_type(svp));
7406 	}
7407 
7408 	tdrp = VTOR4(tdvp);
7409 	mi = VTOMI4(svp);
7410 
7411 	if (!(mi->mi_flags & MI4_LINK)) {
7412 		return (EOPNOTSUPP);
7413 	}
7414 	recov_state.rs_flags = 0;
7415 	recov_state.rs_num_retry_despite_err = 0;
7416 
7417 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7418 		return (EINTR);
7419 
7420 recov_retry:
7421 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7422 
7423 	args.ctag = TAG_LINK;
7424 
7425 	/*
7426 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7427 	 * restorefh; getattr(fl)
7428 	 */
7429 	args.array_len = 7;
7430 	args.array = argop;
7431 
7432 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7433 	if (e.error) {
7434 		kmem_free(argop, argoplist_size);
7435 		nfs_rw_exit(&tdrp->r_rwlock);
7436 		return (e.error);
7437 	}
7438 
7439 	/* 0. putfh file */
7440 	argop[0].argop = OP_CPUTFH;
7441 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7442 
7443 	/* 1. save current fh to free up the space for the dir */
7444 	argop[1].argop = OP_SAVEFH;
7445 
7446 	/* 2. putfh targetdir */
7447 	argop[2].argop = OP_CPUTFH;
7448 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7449 
7450 	/* 3. link: current_fh is targetdir, saved_fh is source */
7451 	argop[3].argop = OP_CLINK;
7452 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7453 
7454 	/* 4. Get attributes of dir */
7455 	argop[4].argop = OP_GETATTR;
7456 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7457 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7458 
7459 	/* 5. If link was successful, restore current vp to file */
7460 	argop[5].argop = OP_RESTOREFH;
7461 
7462 	/* 6. Get attributes of linked object */
7463 	argop[6].argop = OP_GETATTR;
7464 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7465 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7466 
7467 	dnlc_remove(tdvp, tnm);
7468 
7469 	doqueue = 1;
7470 	t = gethrtime();
7471 
7472 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7473 
7474 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7475 	if (e.error != 0 && !needrecov) {
7476 		PURGE_ATTRCACHE4(tdvp);
7477 		PURGE_ATTRCACHE4(svp);
7478 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7479 		goto out;
7480 	}
7481 
7482 	if (needrecov) {
7483 		bool_t abort;
7484 
7485 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7486 		    NULL, NULL, OP_LINK, NULL);
7487 		if (abort == FALSE) {
7488 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7489 			    needrecov);
7490 			kmem_free(argop, argoplist_size);
7491 			if (!e.error)
7492 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7493 				    (caddr_t)&res);
7494 			goto recov_retry;
7495 		} else {
7496 			if (e.error != 0) {
7497 				PURGE_ATTRCACHE4(tdvp);
7498 				PURGE_ATTRCACHE4(svp);
7499 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7500 				    &recov_state, needrecov);
7501 				goto out;
7502 			}
7503 			/* fall through for res.status case */
7504 		}
7505 	}
7506 
7507 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7508 
7509 	resp = &res;
7510 	if (res.status) {
7511 		/* If link succeeded, then don't return error */
7512 		e.error = geterrno4(res.status);
7513 		if (res.array_len <= 4) {
7514 			/*
7515 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7516 			 */
7517 			PURGE_ATTRCACHE4(svp);
7518 			PURGE_ATTRCACHE4(tdvp);
7519 			if (e.error == EOPNOTSUPP) {
7520 				mutex_enter(&mi->mi_lock);
7521 				mi->mi_flags &= ~MI4_LINK;
7522 				mutex_exit(&mi->mi_lock);
7523 			}
7524 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7525 			/* XXX-LP */
7526 			if (e.error == EISDIR && crgetuid(cr) != 0)
7527 				e.error = EPERM;
7528 			goto out;
7529 		}
7530 	}
7531 
7532 	/* either no error or one of the postop getattr failed */
7533 
7534 	/*
7535 	 * XXX - if LINK succeeded, but no attrs were returned for link
7536 	 * file, purge its cache.
7537 	 *
7538 	 * XXX Perform a simplified version of wcc checking. Instead of
7539 	 * have another getattr to get pre-op, just purge cache if
7540 	 * any of the ops prior to and including the getattr failed.
7541 	 * If the getattr succeeded then update the attrcache accordingly.
7542 	 */
7543 
7544 	/*
7545 	 * update cache with link file postattrs.
7546 	 * Note: at this point resop points to link res.
7547 	 */
7548 	resop = &res.array[3];	/* link res */
7549 	ln_res = &resop->nfs_resop4_u.oplink;
7550 	if (res.status == NFS4_OK)
7551 		e.error = nfs4_update_attrcache(res.status,
7552 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res,
7553 		    t, svp, cr);
7554 
7555 	/*
7556 	 * Call makenfs4node to create the new shadow vp for tnm.
7557 	 * We pass NULL attrs because we just cached attrs for
7558 	 * the src object.  All we're trying to accomplish is to
7559 	 * to create the new shadow vnode.
7560 	 */
7561 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7562 	    tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm));
7563 
7564 	/* Update target cache attribute, readdir and dnlc caches */
7565 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7566 	dinfo.di_time_call = t;
7567 	dinfo.di_cred = cr;
7568 
7569 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7570 	ASSERT(nfs4_consistent_type(tdvp));
7571 	ASSERT(nfs4_consistent_type(svp));
7572 	ASSERT(nfs4_consistent_type(nvp));
7573 	VN_RELE(nvp);
7574 
7575 	if (!e.error) {
7576 		vnode_t *tvp;
7577 		rnode4_t *trp;
7578 		/*
7579 		 * Notify the source file of this link operation.
7580 		 */
7581 		trp = VTOR4(svp);
7582 		tvp = svp;
7583 		if (IS_SHADOW(svp, trp))
7584 			tvp = RTOV4(trp);
7585 		vnevent_link(tvp, ct);
7586 	}
7587 out:
7588 	kmem_free(argop, argoplist_size);
7589 	if (resp)
7590 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7591 
7592 	nfs_rw_exit(&tdrp->r_rwlock);
7593 
7594 	return (e.error);
7595 }
7596 
7597 /* ARGSUSED */
7598 static int
7599 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7600     caller_context_t *ct, int flags)
7601 {
7602 	vnode_t *realvp;
7603 
7604 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7605 		return (EPERM);
7606 	if (VOP_REALVP(ndvp, &realvp, ct) == 0)
7607 		ndvp = realvp;
7608 
7609 	return (nfs4rename(odvp, onm, ndvp, nnm, cr, ct));
7610 }
7611 
7612 /*
7613  * nfs4rename does the real work of renaming in NFS Version 4.
7614  *
7615  * A file handle is considered volatile for renaming purposes if either
7616  * of the volatile bits are turned on. However, the compound may differ
7617  * based on the likelihood of the filehandle to change during rename.
7618  */
7619 static int
7620 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7621     caller_context_t *ct)
7622 {
7623 	int error;
7624 	mntinfo4_t *mi;
7625 	vnode_t *nvp = NULL;
7626 	vnode_t *ovp = NULL;
7627 	char *tmpname = NULL;
7628 	rnode4_t *rp;
7629 	rnode4_t *odrp;
7630 	rnode4_t *ndrp;
7631 	int did_link = 0;
7632 	int do_link = 1;
7633 	nfsstat4 stat = NFS4_OK;
7634 
7635 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7636 	ASSERT(nfs4_consistent_type(odvp));
7637 	ASSERT(nfs4_consistent_type(ndvp));
7638 
7639 	if (onm[0] == '.' && (onm[1] == '\0' ||
7640 	    (onm[1] == '.' && onm[2] == '\0')))
7641 		return (EINVAL);
7642 
7643 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7644 	    (nnm[1] == '.' && nnm[2] == '\0')))
7645 		return (EINVAL);
7646 
7647 	odrp = VTOR4(odvp);
7648 	ndrp = VTOR4(ndvp);
7649 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7650 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7651 			return (EINTR);
7652 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7653 			nfs_rw_exit(&odrp->r_rwlock);
7654 			return (EINTR);
7655 		}
7656 	} else {
7657 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7658 			return (EINTR);
7659 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7660 			nfs_rw_exit(&ndrp->r_rwlock);
7661 			return (EINTR);
7662 		}
7663 	}
7664 
7665 	/*
7666 	 * Lookup the target file.  If it exists, it needs to be
7667 	 * checked to see whether it is a mount point and whether
7668 	 * it is active (open).
7669 	 */
7670 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7671 	if (!error) {
7672 		int	isactive;
7673 
7674 		ASSERT(nfs4_consistent_type(nvp));
7675 		/*
7676 		 * If this file has been mounted on, then just
7677 		 * return busy because renaming to it would remove
7678 		 * the mounted file system from the name space.
7679 		 */
7680 		if (vn_ismntpt(nvp)) {
7681 			VN_RELE(nvp);
7682 			nfs_rw_exit(&odrp->r_rwlock);
7683 			nfs_rw_exit(&ndrp->r_rwlock);
7684 			return (EBUSY);
7685 		}
7686 
7687 		/*
7688 		 * First just remove the entry from the name cache, as it
7689 		 * is most likely the only entry for this vp.
7690 		 */
7691 		dnlc_remove(ndvp, nnm);
7692 
7693 		rp = VTOR4(nvp);
7694 
7695 		if (nvp->v_type != VREG) {
7696 			/*
7697 			 * Purge the name cache of all references to this vnode
7698 			 * so that we can check the reference count to infer
7699 			 * whether it is active or not.
7700 			 */
7701 			if (nvp->v_count > 1)
7702 				dnlc_purge_vp(nvp);
7703 
7704 			isactive = nvp->v_count > 1;
7705 		} else {
7706 			mutex_enter(&rp->r_os_lock);
7707 			isactive = list_head(&rp->r_open_streams) != NULL;
7708 			mutex_exit(&rp->r_os_lock);
7709 		}
7710 
7711 		/*
7712 		 * If the vnode is active and is not a directory,
7713 		 * arrange to rename it to a
7714 		 * temporary file so that it will continue to be
7715 		 * accessible.  This implements the "unlink-open-file"
7716 		 * semantics for the target of a rename operation.
7717 		 * Before doing this though, make sure that the
7718 		 * source and target files are not already the same.
7719 		 */
7720 		if (isactive && nvp->v_type != VDIR) {
7721 			/*
7722 			 * Lookup the source name.
7723 			 */
7724 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7725 
7726 			/*
7727 			 * The source name *should* already exist.
7728 			 */
7729 			if (error) {
7730 				VN_RELE(nvp);
7731 				nfs_rw_exit(&odrp->r_rwlock);
7732 				nfs_rw_exit(&ndrp->r_rwlock);
7733 				return (error);
7734 			}
7735 
7736 			ASSERT(nfs4_consistent_type(ovp));
7737 
7738 			/*
7739 			 * Compare the two vnodes.  If they are the same,
7740 			 * just release all held vnodes and return success.
7741 			 */
7742 			if (VN_CMP(ovp, nvp)) {
7743 				VN_RELE(ovp);
7744 				VN_RELE(nvp);
7745 				nfs_rw_exit(&odrp->r_rwlock);
7746 				nfs_rw_exit(&ndrp->r_rwlock);
7747 				return (0);
7748 			}
7749 
7750 			/*
7751 			 * Can't mix and match directories and non-
7752 			 * directories in rename operations.  We already
7753 			 * know that the target is not a directory.  If
7754 			 * the source is a directory, return an error.
7755 			 */
7756 			if (ovp->v_type == VDIR) {
7757 				VN_RELE(ovp);
7758 				VN_RELE(nvp);
7759 				nfs_rw_exit(&odrp->r_rwlock);
7760 				nfs_rw_exit(&ndrp->r_rwlock);
7761 				return (ENOTDIR);
7762 			}
7763 link_call:
7764 			/*
7765 			 * The target file exists, is not the same as
7766 			 * the source file, and is active.  We first
7767 			 * try to Link it to a temporary filename to
7768 			 * avoid having the server removing the file
7769 			 * completely (which could cause data loss to
7770 			 * the user's POV in the event the Rename fails
7771 			 * -- see bug 1165874).
7772 			 */
7773 			/*
7774 			 * The do_link and did_link booleans are
7775 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7776 			 * returned for the Rename.  Some servers can
7777 			 * not Rename over an Open file, so they return
7778 			 * this error.  The client needs to Remove the
7779 			 * newly created Link and do two Renames, just
7780 			 * as if the server didn't support LINK.
7781 			 */
7782 			tmpname = newname();
7783 			error = 0;
7784 
7785 			if (do_link) {
7786 				error = nfs4_link(ndvp, nvp, tmpname, cr,
7787 				    NULL, 0);
7788 			}
7789 			if (error == EOPNOTSUPP || !do_link) {
7790 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7791 				    cr, NULL, 0);
7792 				did_link = 0;
7793 			} else {
7794 				did_link = 1;
7795 			}
7796 			if (error) {
7797 				kmem_free(tmpname, MAXNAMELEN);
7798 				VN_RELE(ovp);
7799 				VN_RELE(nvp);
7800 				nfs_rw_exit(&odrp->r_rwlock);
7801 				nfs_rw_exit(&ndrp->r_rwlock);
7802 				return (error);
7803 			}
7804 
7805 			mutex_enter(&rp->r_statelock);
7806 			if (rp->r_unldvp == NULL) {
7807 				VN_HOLD(ndvp);
7808 				rp->r_unldvp = ndvp;
7809 				if (rp->r_unlcred != NULL)
7810 					crfree(rp->r_unlcred);
7811 				crhold(cr);
7812 				rp->r_unlcred = cr;
7813 				rp->r_unlname = tmpname;
7814 			} else {
7815 				if (rp->r_unlname)
7816 					kmem_free(rp->r_unlname, MAXNAMELEN);
7817 				rp->r_unlname = tmpname;
7818 			}
7819 			mutex_exit(&rp->r_statelock);
7820 		}
7821 
7822 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7823 
7824 		ASSERT(nfs4_consistent_type(nvp));
7825 	}
7826 
7827 	if (ovp == NULL) {
7828 		/*
7829 		 * When renaming directories to be a subdirectory of a
7830 		 * different parent, the dnlc entry for ".." will no
7831 		 * longer be valid, so it must be removed.
7832 		 *
7833 		 * We do a lookup here to determine whether we are renaming
7834 		 * a directory and we need to check if we are renaming
7835 		 * an unlinked file.  This might have already been done
7836 		 * in previous code, so we check ovp == NULL to avoid
7837 		 * doing it twice.
7838 		 */
7839 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7840 		/*
7841 		 * The source name *should* already exist.
7842 		 */
7843 		if (error) {
7844 			nfs_rw_exit(&odrp->r_rwlock);
7845 			nfs_rw_exit(&ndrp->r_rwlock);
7846 			if (nvp) {
7847 				VN_RELE(nvp);
7848 			}
7849 			return (error);
7850 		}
7851 		ASSERT(ovp != NULL);
7852 		ASSERT(nfs4_consistent_type(ovp));
7853 	}
7854 
7855 	/*
7856 	 * Is the object being renamed a dir, and if so, is
7857 	 * it being renamed to a child of itself?  The underlying
7858 	 * fs should ultimately return EINVAL for this case;
7859 	 * however, buggy beta non-Solaris NFSv4 servers at
7860 	 * interop testing events have allowed this behavior,
7861 	 * and it caused our client to panic due to a recursive
7862 	 * mutex_enter in fn_move.
7863 	 *
7864 	 * The tedious locking in fn_move could be changed to
7865 	 * deal with this case, and the client could avoid the
7866 	 * panic; however, the client would just confuse itself
7867 	 * later and misbehave.  A better way to handle the broken
7868 	 * server is to detect this condition and return EINVAL
7869 	 * without ever sending the the bogus rename to the server.
7870 	 * We know the rename is invalid -- just fail it now.
7871 	 */
7872 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7873 		VN_RELE(ovp);
7874 		nfs_rw_exit(&odrp->r_rwlock);
7875 		nfs_rw_exit(&ndrp->r_rwlock);
7876 		if (nvp) {
7877 			VN_RELE(nvp);
7878 		}
7879 		return (EINVAL);
7880 	}
7881 
7882 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7883 
7884 	/*
7885 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7886 	 * possible for the filehandle to change due to the rename.
7887 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7888 	 * the fh will not change because of the rename, but we still need
7889 	 * to update its rnode entry with the new name for
7890 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7891 	 * has no effect on these for now, but for future improvements,
7892 	 * we might want to use it too to simplify handling of files
7893 	 * that are open with that flag on. (XXX)
7894 	 */
7895 	mi = VTOMI4(odvp);
7896 	if (NFS4_VOLATILE_FH(mi))
7897 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7898 		    &stat);
7899 	else
7900 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7901 		    &stat);
7902 
7903 	ASSERT(nfs4_consistent_type(odvp));
7904 	ASSERT(nfs4_consistent_type(ndvp));
7905 	ASSERT(nfs4_consistent_type(ovp));
7906 
7907 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
7908 		do_link = 0;
7909 		/*
7910 		 * Before the 'link_call' code, we did a nfs4_lookup
7911 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
7912 		 * call we call VN_RELE to match that hold.  We need
7913 		 * to place an additional VN_HOLD here since we will
7914 		 * be hitting that VN_RELE again.
7915 		 */
7916 		VN_HOLD(nvp);
7917 
7918 		(void) nfs4_remove(ndvp, tmpname, cr, NULL, 0);
7919 
7920 		/* Undo the unlinked file naming stuff we just did */
7921 		mutex_enter(&rp->r_statelock);
7922 		if (rp->r_unldvp) {
7923 			VN_RELE(ndvp);
7924 			rp->r_unldvp = NULL;
7925 			if (rp->r_unlcred != NULL)
7926 				crfree(rp->r_unlcred);
7927 			rp->r_unlcred = NULL;
7928 			/* rp->r_unlanme points to tmpname */
7929 			if (rp->r_unlname)
7930 				kmem_free(rp->r_unlname, MAXNAMELEN);
7931 			rp->r_unlname = NULL;
7932 		}
7933 		mutex_exit(&rp->r_statelock);
7934 
7935 		if (nvp) {
7936 			VN_RELE(nvp);
7937 		}
7938 		goto link_call;
7939 	}
7940 
7941 	if (error) {
7942 		VN_RELE(ovp);
7943 		nfs_rw_exit(&odrp->r_rwlock);
7944 		nfs_rw_exit(&ndrp->r_rwlock);
7945 		if (nvp) {
7946 			VN_RELE(nvp);
7947 		}
7948 		return (error);
7949 	}
7950 
7951 	/*
7952 	 * when renaming directories to be a subdirectory of a
7953 	 * different parent, the dnlc entry for ".." will no
7954 	 * longer be valid, so it must be removed
7955 	 */
7956 	rp = VTOR4(ovp);
7957 	if (ndvp != odvp) {
7958 		if (ovp->v_type == VDIR) {
7959 			dnlc_remove(ovp, "..");
7960 			if (rp->r_dir != NULL)
7961 				nfs4_purge_rddir_cache(ovp);
7962 		}
7963 	}
7964 
7965 	/*
7966 	 * If we are renaming the unlinked file, update the
7967 	 * r_unldvp and r_unlname as needed.
7968 	 */
7969 	mutex_enter(&rp->r_statelock);
7970 	if (rp->r_unldvp != NULL) {
7971 		if (strcmp(rp->r_unlname, onm) == 0) {
7972 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
7973 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
7974 			if (ndvp != rp->r_unldvp) {
7975 				VN_RELE(rp->r_unldvp);
7976 				rp->r_unldvp = ndvp;
7977 				VN_HOLD(ndvp);
7978 			}
7979 		}
7980 	}
7981 	mutex_exit(&rp->r_statelock);
7982 
7983 	/*
7984 	 * Notify the rename vnevents to source vnode, and to the target
7985 	 * vnode if it already existed.
7986 	 */
7987 	if (error == 0) {
7988 		vnode_t *tvp;
7989 		rnode4_t *trp;
7990 		/*
7991 		 * Notify the vnode. Each links is represented by
7992 		 * a different vnode, in nfsv4.
7993 		 */
7994 		if (nvp) {
7995 			trp = VTOR4(nvp);
7996 			tvp = nvp;
7997 			if (IS_SHADOW(nvp, trp))
7998 				tvp = RTOV4(trp);
7999 			vnevent_rename_dest(tvp, ndvp, nnm, ct);
8000 		}
8001 
8002 		/*
8003 		 * if the source and destination directory are not the
8004 		 * same notify the destination directory.
8005 		 */
8006 		if (VTOR4(odvp) != VTOR4(ndvp)) {
8007 			trp = VTOR4(ndvp);
8008 			tvp = ndvp;
8009 			if (IS_SHADOW(ndvp, trp))
8010 				tvp = RTOV4(trp);
8011 			vnevent_rename_dest_dir(tvp, ct);
8012 		}
8013 
8014 		trp = VTOR4(ovp);
8015 		tvp = ovp;
8016 		if (IS_SHADOW(ovp, trp))
8017 			tvp = RTOV4(trp);
8018 		vnevent_rename_src(tvp, odvp, onm, ct);
8019 	}
8020 
8021 	if (nvp) {
8022 		VN_RELE(nvp);
8023 	}
8024 	VN_RELE(ovp);
8025 
8026 	nfs_rw_exit(&odrp->r_rwlock);
8027 	nfs_rw_exit(&ndrp->r_rwlock);
8028 
8029 	return (error);
8030 }
8031 
8032 /*
8033  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
8034  * when it is known that the filehandle is persistent through rename.
8035  *
8036  * Rename requires that the current fh be the target directory and the
8037  * saved fh be the source directory. After the operation, the current fh
8038  * is unchanged.
8039  * The compound op structure for persistent fh rename is:
8040  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
8041  * Rather than bother with the directory postop args, we'll simply
8042  * update that a change occurred in the cache, so no post-op getattrs.
8043  */
8044 static int
8045 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
8046     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8047 {
8048 	COMPOUND4args_clnt args;
8049 	COMPOUND4res_clnt res, *resp = NULL;
8050 	nfs_argop4 *argop;
8051 	nfs_resop4 *resop;
8052 	int doqueue, argoplist_size;
8053 	mntinfo4_t *mi;
8054 	rnode4_t *odrp = VTOR4(odvp);
8055 	rnode4_t *ndrp = VTOR4(ndvp);
8056 	RENAME4res *rn_res;
8057 	bool_t needrecov;
8058 	nfs4_recov_state_t recov_state;
8059 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8060 	dirattr_info_t dinfo, *dinfop;
8061 
8062 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8063 
8064 	recov_state.rs_flags = 0;
8065 	recov_state.rs_num_retry_despite_err = 0;
8066 
8067 	/*
8068 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
8069 	 *
8070 	 * If source/target are different dirs, then append putfh(src); getattr
8071 	 */
8072 	args.array_len = (odvp == ndvp) ? 5 : 7;
8073 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8074 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8075 
8076 recov_retry:
8077 	*statp = NFS4_OK;
8078 
8079 	/* No need to Lookup the file, persistent fh */
8080 	args.ctag = TAG_RENAME;
8081 
8082 	mi = VTOMI4(odvp);
8083 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8084 	if (e.error) {
8085 		kmem_free(argop, argoplist_size);
8086 		return (e.error);
8087 	}
8088 
8089 	/* 0: putfh source directory */
8090 	argop[0].argop = OP_CPUTFH;
8091 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8092 
8093 	/* 1: Save source fh to free up current for target */
8094 	argop[1].argop = OP_SAVEFH;
8095 
8096 	/* 2: putfh targetdir */
8097 	argop[2].argop = OP_CPUTFH;
8098 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8099 
8100 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8101 	argop[3].argop = OP_CRENAME;
8102 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8103 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8104 
8105 	/* 4: getattr (targetdir) */
8106 	argop[4].argop = OP_GETATTR;
8107 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8108 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8109 
8110 	if (ndvp != odvp) {
8111 
8112 		/* 5: putfh (sourcedir) */
8113 		argop[5].argop = OP_CPUTFH;
8114 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8115 
8116 		/* 6: getattr (sourcedir) */
8117 		argop[6].argop = OP_GETATTR;
8118 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8119 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8120 	}
8121 
8122 	dnlc_remove(odvp, onm);
8123 	dnlc_remove(ndvp, nnm);
8124 
8125 	doqueue = 1;
8126 	dinfo.di_time_call = gethrtime();
8127 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8128 
8129 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8130 	if (e.error) {
8131 		PURGE_ATTRCACHE4(odvp);
8132 		PURGE_ATTRCACHE4(ndvp);
8133 	} else {
8134 		*statp = res.status;
8135 	}
8136 
8137 	if (needrecov) {
8138 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8139 		    OP_RENAME, NULL) == FALSE) {
8140 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8141 			if (!e.error)
8142 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8143 				    (caddr_t)&res);
8144 			goto recov_retry;
8145 		}
8146 	}
8147 
8148 	if (!e.error) {
8149 		resp = &res;
8150 		/*
8151 		 * as long as OP_RENAME
8152 		 */
8153 		if (res.status != NFS4_OK && res.array_len <= 4) {
8154 			e.error = geterrno4(res.status);
8155 			PURGE_ATTRCACHE4(odvp);
8156 			PURGE_ATTRCACHE4(ndvp);
8157 			/*
8158 			 * System V defines rename to return EEXIST, not
8159 			 * ENOTEMPTY if the target directory is not empty.
8160 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8161 			 * which geterrno4 maps to ENOTEMPTY.
8162 			 */
8163 			if (e.error == ENOTEMPTY)
8164 				e.error = EEXIST;
8165 		} else {
8166 
8167 			resop = &res.array[3];	/* rename res */
8168 			rn_res = &resop->nfs_resop4_u.oprename;
8169 
8170 			if (res.status == NFS4_OK) {
8171 				/*
8172 				 * Update target attribute, readdir and dnlc
8173 				 * caches.
8174 				 */
8175 				dinfo.di_garp =
8176 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8177 				dinfo.di_cred = cr;
8178 				dinfop = &dinfo;
8179 			} else
8180 				dinfop = NULL;
8181 
8182 			nfs4_update_dircaches(&rn_res->target_cinfo,
8183 			    ndvp, NULL, NULL, dinfop);
8184 
8185 			/*
8186 			 * Update source attribute, readdir and dnlc caches
8187 			 *
8188 			 */
8189 			if (ndvp != odvp) {
8190 				if (dinfop)
8191 					dinfo.di_garp =
8192 					    &(res.array[6].nfs_resop4_u.
8193 					    opgetattr.ga_res);
8194 
8195 				nfs4_update_dircaches(&rn_res->source_cinfo,
8196 				    odvp, NULL, NULL, dinfop);
8197 			}
8198 
8199 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8200 			    nnm);
8201 		}
8202 	}
8203 
8204 	if (resp)
8205 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8206 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8207 	kmem_free(argop, argoplist_size);
8208 
8209 	return (e.error);
8210 }
8211 
8212 /*
8213  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8214  * it is possible for the filehandle to change due to the rename.
8215  *
8216  * The compound req in this case includes a post-rename lookup and getattr
8217  * to ensure that we have the correct fh and attributes for the object.
8218  *
8219  * Rename requires that the current fh be the target directory and the
8220  * saved fh be the source directory. After the operation, the current fh
8221  * is unchanged.
8222  *
8223  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8224  * update the filehandle for the renamed object.  We also get the old
8225  * filehandle for historical reasons; this should be taken out sometime.
8226  * This results in a rather cumbersome compound...
8227  *
8228  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8229  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8230  *
8231  */
8232 static int
8233 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8234     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8235 {
8236 	COMPOUND4args_clnt args;
8237 	COMPOUND4res_clnt res, *resp = NULL;
8238 	int argoplist_size;
8239 	nfs_argop4 *argop;
8240 	nfs_resop4 *resop;
8241 	int doqueue;
8242 	mntinfo4_t *mi;
8243 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8244 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8245 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8246 	RENAME4res *rn_res;
8247 	GETFH4res *ngf_res;
8248 	bool_t needrecov;
8249 	nfs4_recov_state_t recov_state;
8250 	hrtime_t t;
8251 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8252 	dirattr_info_t dinfo, *dinfop = &dinfo;
8253 
8254 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8255 
8256 	recov_state.rs_flags = 0;
8257 	recov_state.rs_num_retry_despite_err = 0;
8258 
8259 recov_retry:
8260 	*statp = NFS4_OK;
8261 
8262 	/*
8263 	 * There is a window between the RPC and updating the path and
8264 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8265 	 * code, so that it doesn't try to use the old path during that
8266 	 * window.
8267 	 */
8268 	mutex_enter(&orp->r_statelock);
8269 	while (orp->r_flags & R4RECEXPFH) {
8270 		klwp_t *lwp = ttolwp(curthread);
8271 
8272 		if (lwp != NULL)
8273 			lwp->lwp_nostop++;
8274 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8275 			mutex_exit(&orp->r_statelock);
8276 			if (lwp != NULL)
8277 				lwp->lwp_nostop--;
8278 			return (EINTR);
8279 		}
8280 		if (lwp != NULL)
8281 			lwp->lwp_nostop--;
8282 	}
8283 	orp->r_flags |= R4RECEXPFH;
8284 	mutex_exit(&orp->r_statelock);
8285 
8286 	mi = VTOMI4(odvp);
8287 
8288 	args.ctag = TAG_RENAME_VFH;
8289 	args.array_len = (odvp == ndvp) ? 10 : 12;
8290 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8291 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8292 
8293 	/*
8294 	 * Rename ops:
8295 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8296 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8297 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8298 	 *
8299 	 *    if (odvp != ndvp)
8300 	 *	add putfh(sourcedir), getattr(sourcedir) }
8301 	 */
8302 	args.array = argop;
8303 
8304 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8305 	    &recov_state, NULL);
8306 	if (e.error) {
8307 		kmem_free(argop, argoplist_size);
8308 		mutex_enter(&orp->r_statelock);
8309 		orp->r_flags &= ~R4RECEXPFH;
8310 		cv_broadcast(&orp->r_cv);
8311 		mutex_exit(&orp->r_statelock);
8312 		return (e.error);
8313 	}
8314 
8315 	/* 0: putfh source directory */
8316 	argop[0].argop = OP_CPUTFH;
8317 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8318 
8319 	/* 1: Save source fh to free up current for target */
8320 	argop[1].argop = OP_SAVEFH;
8321 
8322 	/* 2: Lookup pre-rename fh of renamed object */
8323 	argop[2].argop = OP_CLOOKUP;
8324 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8325 
8326 	/* 3: getfh fh of renamed object (before rename) */
8327 	argop[3].argop = OP_GETFH;
8328 
8329 	/* 4: putfh targetdir */
8330 	argop[4].argop = OP_CPUTFH;
8331 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8332 
8333 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8334 	argop[5].argop = OP_CRENAME;
8335 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8336 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8337 
8338 	/* 6: getattr of target dir (post op attrs) */
8339 	argop[6].argop = OP_GETATTR;
8340 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8341 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8342 
8343 	/* 7: Lookup post-rename fh of renamed object */
8344 	argop[7].argop = OP_CLOOKUP;
8345 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8346 
8347 	/* 8: getfh fh of renamed object (after rename) */
8348 	argop[8].argop = OP_GETFH;
8349 
8350 	/* 9: getattr of renamed object */
8351 	argop[9].argop = OP_GETATTR;
8352 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8353 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8354 
8355 	/*
8356 	 * If source/target dirs are different, then get new post-op
8357 	 * attrs for source dir also.
8358 	 */
8359 	if (ndvp != odvp) {
8360 		/* 10: putfh (sourcedir) */
8361 		argop[10].argop = OP_CPUTFH;
8362 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8363 
8364 		/* 11: getattr (sourcedir) */
8365 		argop[11].argop = OP_GETATTR;
8366 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8367 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8368 	}
8369 
8370 	dnlc_remove(odvp, onm);
8371 	dnlc_remove(ndvp, nnm);
8372 
8373 	doqueue = 1;
8374 	t = gethrtime();
8375 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8376 
8377 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8378 	if (e.error) {
8379 		PURGE_ATTRCACHE4(odvp);
8380 		PURGE_ATTRCACHE4(ndvp);
8381 		if (!needrecov) {
8382 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8383 			    &recov_state, needrecov);
8384 			goto out;
8385 		}
8386 	} else {
8387 		*statp = res.status;
8388 	}
8389 
8390 	if (needrecov) {
8391 		bool_t abort;
8392 
8393 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8394 		    OP_RENAME, NULL);
8395 		if (abort == FALSE) {
8396 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8397 			    &recov_state, needrecov);
8398 			kmem_free(argop, argoplist_size);
8399 			if (!e.error)
8400 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8401 				    (caddr_t)&res);
8402 			mutex_enter(&orp->r_statelock);
8403 			orp->r_flags &= ~R4RECEXPFH;
8404 			cv_broadcast(&orp->r_cv);
8405 			mutex_exit(&orp->r_statelock);
8406 			goto recov_retry;
8407 		} else {
8408 			if (e.error != 0) {
8409 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8410 				    &recov_state, needrecov);
8411 				goto out;
8412 			}
8413 			/* fall through for res.status case */
8414 		}
8415 	}
8416 
8417 	resp = &res;
8418 	/*
8419 	 * If OP_RENAME (or any prev op) failed, then return an error.
8420 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8421 	 */
8422 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8423 		/*
8424 		 * Error in an op other than last Getattr
8425 		 */
8426 		e.error = geterrno4(res.status);
8427 		PURGE_ATTRCACHE4(odvp);
8428 		PURGE_ATTRCACHE4(ndvp);
8429 		/*
8430 		 * System V defines rename to return EEXIST, not
8431 		 * ENOTEMPTY if the target directory is not empty.
8432 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8433 		 * which geterrno4 maps to ENOTEMPTY.
8434 		 */
8435 		if (e.error == ENOTEMPTY)
8436 			e.error = EEXIST;
8437 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8438 		    needrecov);
8439 		goto out;
8440 	}
8441 
8442 	/* rename results */
8443 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8444 
8445 	if (res.status == NFS4_OK) {
8446 		/* Update target attribute, readdir and dnlc caches */
8447 		dinfo.di_garp =
8448 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
8449 		dinfo.di_cred = cr;
8450 		dinfo.di_time_call = t;
8451 	} else
8452 		dinfop = NULL;
8453 
8454 	/* Update source cache attribute, readdir and dnlc caches */
8455 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8456 
8457 	/* Update source cache attribute, readdir and dnlc caches */
8458 	if (ndvp != odvp) {
8459 
8460 		/*
8461 		 * If dinfop is non-NULL, then compound succeded, so
8462 		 * set di_garp to attrs for source dir.  dinfop is only
8463 		 * set to NULL when compound fails.
8464 		 */
8465 		if (dinfop)
8466 			dinfo.di_garp =
8467 			    &res.array[11].nfs_resop4_u.opgetattr.ga_res;
8468 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8469 		    dinfop);
8470 	}
8471 
8472 	/*
8473 	 * Update the rnode with the new component name and args,
8474 	 * and if the file handle changed, also update it with the new fh.
8475 	 * This is only necessary if the target object has an rnode
8476 	 * entry and there is no need to create one for it.
8477 	 */
8478 	resop = &res.array[8];	/* getfh new res */
8479 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8480 
8481 	/*
8482 	 * Update the path and filehandle for the renamed object.
8483 	 */
8484 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8485 
8486 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8487 
8488 	if (res.status == NFS4_OK) {
8489 		resop++;	/* getattr res */
8490 		e.error = nfs4_update_attrcache(res.status,
8491 		    &resop->nfs_resop4_u.opgetattr.ga_res,
8492 		    t, ovp, cr);
8493 	}
8494 
8495 out:
8496 	kmem_free(argop, argoplist_size);
8497 	if (resp)
8498 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8499 	mutex_enter(&orp->r_statelock);
8500 	orp->r_flags &= ~R4RECEXPFH;
8501 	cv_broadcast(&orp->r_cv);
8502 	mutex_exit(&orp->r_statelock);
8503 
8504 	return (e.error);
8505 }
8506 
8507 /* ARGSUSED */
8508 static int
8509 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr,
8510     caller_context_t *ct, int flags, vsecattr_t *vsecp)
8511 {
8512 	int error;
8513 	vnode_t *vp;
8514 
8515 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8516 		return (EPERM);
8517 	/*
8518 	 * As ".." has special meaning and rather than send a mkdir
8519 	 * over the wire to just let the server freak out, we just
8520 	 * short circuit it here and return EEXIST
8521 	 */
8522 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8523 		return (EEXIST);
8524 
8525 	/*
8526 	 * Decision to get the right gid and setgid bit of the
8527 	 * new directory is now made in call_nfs4_create_req.
8528 	 */
8529 	va->va_mask |= AT_MODE;
8530 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8531 	if (error)
8532 		return (error);
8533 
8534 	*vpp = vp;
8535 	return (0);
8536 }
8537 
8538 
8539 /*
8540  * rmdir is using the same remove v4 op as does remove.
8541  * Remove requires that the current fh be the target directory.
8542  * After the operation, the current fh is unchanged.
8543  * The compound op structure is:
8544  *      PUTFH(targetdir), REMOVE
8545  */
8546 /*ARGSUSED4*/
8547 static int
8548 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr,
8549     caller_context_t *ct, int flags)
8550 {
8551 	int need_end_op = FALSE;
8552 	COMPOUND4args_clnt args;
8553 	COMPOUND4res_clnt res, *resp = NULL;
8554 	REMOVE4res *rm_res;
8555 	nfs_argop4 argop[3];
8556 	nfs_resop4 *resop;
8557 	vnode_t *vp;
8558 	int doqueue;
8559 	mntinfo4_t *mi;
8560 	rnode4_t *drp;
8561 	bool_t needrecov = FALSE;
8562 	nfs4_recov_state_t recov_state;
8563 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8564 	dirattr_info_t dinfo, *dinfop;
8565 
8566 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8567 		return (EPERM);
8568 	/*
8569 	 * As ".." has special meaning and rather than send a rmdir
8570 	 * over the wire to just let the server freak out, we just
8571 	 * short circuit it here and return EEXIST
8572 	 */
8573 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8574 		return (EEXIST);
8575 
8576 	drp = VTOR4(dvp);
8577 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8578 		return (EINTR);
8579 
8580 	/*
8581 	 * Attempt to prevent a rmdir(".") from succeeding.
8582 	 */
8583 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8584 	if (e.error) {
8585 		nfs_rw_exit(&drp->r_rwlock);
8586 		return (e.error);
8587 	}
8588 	if (vp == cdir) {
8589 		VN_RELE(vp);
8590 		nfs_rw_exit(&drp->r_rwlock);
8591 		return (EINVAL);
8592 	}
8593 
8594 	/*
8595 	 * Since nfsv4 remove op works on both files and directories,
8596 	 * check that the removed object is indeed a directory.
8597 	 */
8598 	if (vp->v_type != VDIR) {
8599 		VN_RELE(vp);
8600 		nfs_rw_exit(&drp->r_rwlock);
8601 		return (ENOTDIR);
8602 	}
8603 
8604 	/*
8605 	 * First just remove the entry from the name cache, as it
8606 	 * is most likely an entry for this vp.
8607 	 */
8608 	dnlc_remove(dvp, nm);
8609 
8610 	/*
8611 	 * If there vnode reference count is greater than one, then
8612 	 * there may be additional references in the DNLC which will
8613 	 * need to be purged.  First, trying removing the entry for
8614 	 * the parent directory and see if that removes the additional
8615 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8616 	 * to completely remove any references to the directory which
8617 	 * might still exist in the DNLC.
8618 	 */
8619 	if (vp->v_count > 1) {
8620 		dnlc_remove(vp, "..");
8621 		if (vp->v_count > 1)
8622 			dnlc_purge_vp(vp);
8623 	}
8624 
8625 	mi = VTOMI4(dvp);
8626 	recov_state.rs_flags = 0;
8627 	recov_state.rs_num_retry_despite_err = 0;
8628 
8629 recov_retry:
8630 	args.ctag = TAG_RMDIR;
8631 
8632 	/*
8633 	 * Rmdir ops: putfh dir; remove
8634 	 */
8635 	args.array_len = 3;
8636 	args.array = argop;
8637 
8638 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8639 	if (e.error) {
8640 		nfs_rw_exit(&drp->r_rwlock);
8641 		return (e.error);
8642 	}
8643 	need_end_op = TRUE;
8644 
8645 	/* putfh directory */
8646 	argop[0].argop = OP_CPUTFH;
8647 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8648 
8649 	/* remove */
8650 	argop[1].argop = OP_CREMOVE;
8651 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8652 
8653 	/* getattr (postop attrs for dir that contained removed dir) */
8654 	argop[2].argop = OP_GETATTR;
8655 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8656 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8657 
8658 	dinfo.di_time_call = gethrtime();
8659 	doqueue = 1;
8660 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8661 
8662 	PURGE_ATTRCACHE4(vp);
8663 
8664 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8665 	if (e.error) {
8666 		PURGE_ATTRCACHE4(dvp);
8667 	}
8668 
8669 	if (needrecov) {
8670 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8671 		    NULL, OP_REMOVE, NULL) == FALSE) {
8672 			if (!e.error)
8673 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8674 				    (caddr_t)&res);
8675 
8676 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8677 			    needrecov);
8678 			need_end_op = FALSE;
8679 			goto recov_retry;
8680 		}
8681 	}
8682 
8683 	if (!e.error) {
8684 		resp = &res;
8685 
8686 		/*
8687 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8688 		 * failed.
8689 		 */
8690 		if (res.status != NFS4_OK && res.array_len <= 2) {
8691 			e.error = geterrno4(res.status);
8692 			PURGE_ATTRCACHE4(dvp);
8693 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8694 			    &recov_state, needrecov);
8695 			need_end_op = FALSE;
8696 			nfs4_purge_stale_fh(e.error, dvp, cr);
8697 			/*
8698 			 * System V defines rmdir to return EEXIST, not
8699 			 * ENOTEMPTY if the directory is not empty.  Over
8700 			 * the wire, the error is NFSERR_ENOTEMPTY which
8701 			 * geterrno4 maps to ENOTEMPTY.
8702 			 */
8703 			if (e.error == ENOTEMPTY)
8704 				e.error = EEXIST;
8705 		} else {
8706 			resop = &res.array[1];	/* remove res */
8707 			rm_res = &resop->nfs_resop4_u.opremove;
8708 
8709 			if (res.status == NFS4_OK) {
8710 				resop = &res.array[2];	/* dir attrs */
8711 				dinfo.di_garp =
8712 				    &resop->nfs_resop4_u.opgetattr.ga_res;
8713 				dinfo.di_cred = cr;
8714 				dinfop = &dinfo;
8715 			} else
8716 				dinfop = NULL;
8717 
8718 			/* Update dir attribute, readdir and dnlc caches */
8719 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8720 			    dinfop);
8721 
8722 			/* destroy rddir cache for dir that was removed */
8723 			if (VTOR4(vp)->r_dir != NULL)
8724 				nfs4_purge_rddir_cache(vp);
8725 		}
8726 	}
8727 
8728 	if (need_end_op)
8729 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8730 
8731 	nfs_rw_exit(&drp->r_rwlock);
8732 
8733 	if (resp)
8734 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8735 
8736 	if (e.error == 0) {
8737 		vnode_t *tvp;
8738 		rnode4_t *trp;
8739 		trp = VTOR4(vp);
8740 		tvp = vp;
8741 		if (IS_SHADOW(vp, trp))
8742 			tvp = RTOV4(trp);
8743 		vnevent_rmdir(tvp, dvp, nm, ct);
8744 	}
8745 
8746 	VN_RELE(vp);
8747 
8748 	return (e.error);
8749 }
8750 
8751 /* ARGSUSED */
8752 static int
8753 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr,
8754     caller_context_t *ct, int flags)
8755 {
8756 	int error;
8757 	vnode_t *vp;
8758 	rnode4_t *rp;
8759 	char *contents;
8760 	mntinfo4_t *mi = VTOMI4(dvp);
8761 
8762 	if (nfs_zone() != mi->mi_zone)
8763 		return (EPERM);
8764 	if (!(mi->mi_flags & MI4_SYMLINK))
8765 		return (EOPNOTSUPP);
8766 
8767 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8768 	if (error)
8769 		return (error);
8770 
8771 	ASSERT(nfs4_consistent_type(vp));
8772 	rp = VTOR4(vp);
8773 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8774 
8775 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8776 
8777 		if (contents != NULL) {
8778 			mutex_enter(&rp->r_statelock);
8779 			if (rp->r_symlink.contents == NULL) {
8780 				rp->r_symlink.len = strlen(tnm);
8781 				bcopy(tnm, contents, rp->r_symlink.len);
8782 				rp->r_symlink.contents = contents;
8783 				rp->r_symlink.size = MAXPATHLEN;
8784 				mutex_exit(&rp->r_statelock);
8785 			} else {
8786 				mutex_exit(&rp->r_statelock);
8787 				kmem_free((void *)contents, MAXPATHLEN);
8788 			}
8789 		}
8790 	}
8791 	VN_RELE(vp);
8792 
8793 	return (error);
8794 }
8795 
8796 
8797 /*
8798  * Read directory entries.
8799  * There are some weird things to look out for here.  The uio_loffset
8800  * field is either 0 or it is the offset returned from a previous
8801  * readdir.  It is an opaque value used by the server to find the
8802  * correct directory block to read. The count field is the number
8803  * of blocks to read on the server.  This is advisory only, the server
8804  * may return only one block's worth of entries.  Entries may be compressed
8805  * on the server.
8806  */
8807 /* ARGSUSED */
8808 static int
8809 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp,
8810 	caller_context_t *ct, int flags)
8811 {
8812 	int error;
8813 	uint_t count;
8814 	rnode4_t *rp;
8815 	rddir4_cache *rdc;
8816 	rddir4_cache *rrdc;
8817 
8818 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8819 		return (EIO);
8820 	rp = VTOR4(vp);
8821 
8822 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8823 
8824 	/*
8825 	 * Make sure that the directory cache is valid.
8826 	 */
8827 	if (rp->r_dir != NULL) {
8828 		if (nfs_disable_rddir_cache != 0) {
8829 			/*
8830 			 * Setting nfs_disable_rddir_cache in /etc/system
8831 			 * allows interoperability with servers that do not
8832 			 * properly update the attributes of directories.
8833 			 * Any cached information gets purged before an
8834 			 * access is made to it.
8835 			 */
8836 			nfs4_purge_rddir_cache(vp);
8837 		}
8838 
8839 		error = nfs4_validate_caches(vp, cr);
8840 		if (error)
8841 			return (error);
8842 	}
8843 
8844 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8845 
8846 	/*
8847 	 * Short circuit last readdir which always returns 0 bytes.
8848 	 * This can be done after the directory has been read through
8849 	 * completely at least once.  This will set r_direof which
8850 	 * can be used to find the value of the last cookie.
8851 	 */
8852 	mutex_enter(&rp->r_statelock);
8853 	if (rp->r_direof != NULL &&
8854 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8855 		mutex_exit(&rp->r_statelock);
8856 #ifdef DEBUG
8857 		nfs4_readdir_cache_shorts++;
8858 #endif
8859 		if (eofp)
8860 			*eofp = 1;
8861 		return (0);
8862 	}
8863 
8864 	/*
8865 	 * Look for a cache entry.  Cache entries are identified
8866 	 * by the NFS cookie value and the byte count requested.
8867 	 */
8868 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8869 
8870 	/*
8871 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8872 	 */
8873 	if (rdc == NULL) {
8874 		mutex_exit(&rp->r_statelock);
8875 		return (EINTR);
8876 	}
8877 
8878 	/*
8879 	 * Check to see if we need to fill this entry in.
8880 	 */
8881 	if (rdc->flags & RDDIRREQ) {
8882 		rdc->flags &= ~RDDIRREQ;
8883 		rdc->flags |= RDDIR;
8884 		mutex_exit(&rp->r_statelock);
8885 
8886 		/*
8887 		 * Do the readdir.
8888 		 */
8889 		nfs4readdir(vp, rdc, cr);
8890 
8891 		/*
8892 		 * Reacquire the lock, so that we can continue
8893 		 */
8894 		mutex_enter(&rp->r_statelock);
8895 		/*
8896 		 * The entry is now complete
8897 		 */
8898 		rdc->flags &= ~RDDIR;
8899 	}
8900 
8901 	ASSERT(!(rdc->flags & RDDIR));
8902 
8903 	/*
8904 	 * If an error occurred while attempting
8905 	 * to fill the cache entry, mark the entry invalid and
8906 	 * just return the error.
8907 	 */
8908 	if (rdc->error) {
8909 		error = rdc->error;
8910 		rdc->flags |= RDDIRREQ;
8911 		rddir4_cache_rele(rp, rdc);
8912 		mutex_exit(&rp->r_statelock);
8913 		return (error);
8914 	}
8915 
8916 	/*
8917 	 * The cache entry is complete and good,
8918 	 * copyout the dirent structs to the calling
8919 	 * thread.
8920 	 */
8921 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
8922 
8923 	/*
8924 	 * If no error occurred during the copyout,
8925 	 * update the offset in the uio struct to
8926 	 * contain the value of the next NFS 4 cookie
8927 	 * and set the eof value appropriately.
8928 	 */
8929 	if (!error) {
8930 		uiop->uio_loffset = rdc->nfs4_ncookie;
8931 		if (eofp)
8932 			*eofp = rdc->eof;
8933 	}
8934 
8935 	/*
8936 	 * Decide whether to do readahead.  Don't if we
8937 	 * have already read to the end of directory.
8938 	 */
8939 	if (rdc->eof) {
8940 		/*
8941 		 * Make the entry the direof only if it is cached
8942 		 */
8943 		if (rdc->flags & RDDIRCACHED)
8944 			rp->r_direof = rdc;
8945 		rddir4_cache_rele(rp, rdc);
8946 		mutex_exit(&rp->r_statelock);
8947 		return (error);
8948 	}
8949 
8950 	/* Determine if a readdir readahead should be done */
8951 	if (!(rp->r_flags & R4LOOKUP)) {
8952 		rddir4_cache_rele(rp, rdc);
8953 		mutex_exit(&rp->r_statelock);
8954 		return (error);
8955 	}
8956 
8957 	/*
8958 	 * Now look for a readahead entry.
8959 	 *
8960 	 * Check to see whether we found an entry for the readahead.
8961 	 * If so, we don't need to do anything further, so free the new
8962 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
8963 	 * it to the cache, and then initiate an asynchronous readdir
8964 	 * operation to fill it.
8965 	 */
8966 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
8967 
8968 	/*
8969 	 * A readdir cache entry could not be obtained for the readahead.  In
8970 	 * this case we skip the readahead and return.
8971 	 */
8972 	if (rrdc == NULL) {
8973 		rddir4_cache_rele(rp, rdc);
8974 		mutex_exit(&rp->r_statelock);
8975 		return (error);
8976 	}
8977 
8978 	/*
8979 	 * Check to see if we need to fill this entry in.
8980 	 */
8981 	if (rrdc->flags & RDDIRREQ) {
8982 		rrdc->flags &= ~RDDIRREQ;
8983 		rrdc->flags |= RDDIR;
8984 		rddir4_cache_rele(rp, rdc);
8985 		mutex_exit(&rp->r_statelock);
8986 #ifdef DEBUG
8987 		nfs4_readdir_readahead++;
8988 #endif
8989 		/*
8990 		 * Do the readdir.
8991 		 */
8992 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
8993 		return (error);
8994 	}
8995 
8996 	rddir4_cache_rele(rp, rrdc);
8997 	rddir4_cache_rele(rp, rdc);
8998 	mutex_exit(&rp->r_statelock);
8999 	return (error);
9000 }
9001 
9002 static int
9003 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9004 {
9005 	int error;
9006 	rnode4_t *rp;
9007 
9008 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9009 
9010 	rp = VTOR4(vp);
9011 
9012 	/*
9013 	 * Obtain the readdir results for the caller.
9014 	 */
9015 	nfs4readdir(vp, rdc, cr);
9016 
9017 	mutex_enter(&rp->r_statelock);
9018 	/*
9019 	 * The entry is now complete
9020 	 */
9021 	rdc->flags &= ~RDDIR;
9022 
9023 	error = rdc->error;
9024 	if (error)
9025 		rdc->flags |= RDDIRREQ;
9026 	rddir4_cache_rele(rp, rdc);
9027 	mutex_exit(&rp->r_statelock);
9028 
9029 	return (error);
9030 }
9031 
9032 /*
9033  * Read directory entries.
9034  * There are some weird things to look out for here.  The uio_loffset
9035  * field is either 0 or it is the offset returned from a previous
9036  * readdir.  It is an opaque value used by the server to find the
9037  * correct directory block to read. The count field is the number
9038  * of blocks to read on the server.  This is advisory only, the server
9039  * may return only one block's worth of entries.  Entries may be compressed
9040  * on the server.
9041  *
9042  * Generates the following compound request:
9043  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9044  *    must include a Lookupp as well. In this case, send:
9045  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9046  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9047  *
9048  * Get complete attributes and filehandles for entries if this is the
9049  * first read of the directory. Otherwise, just get fileid's.
9050  */
9051 static void
9052 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9053 {
9054 	COMPOUND4args_clnt args;
9055 	COMPOUND4res_clnt res;
9056 	READDIR4args *rargs;
9057 	READDIR4res_clnt *rd_res;
9058 	bitmap4 rd_bitsval;
9059 	nfs_argop4 argop[5];
9060 	nfs_resop4 *resop;
9061 	rnode4_t *rp = VTOR4(vp);
9062 	mntinfo4_t *mi = VTOMI4(vp);
9063 	int doqueue;
9064 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9065 	vnode_t *dvp;
9066 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9067 	int num_ops, res_opcnt;
9068 	bool_t needrecov = FALSE;
9069 	nfs4_recov_state_t recov_state;
9070 	hrtime_t t;
9071 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9072 
9073 	ASSERT(nfs_zone() == mi->mi_zone);
9074 	ASSERT(rdc->flags & RDDIR);
9075 	ASSERT(rdc->entries == NULL);
9076 
9077 	/*
9078 	 * If rp were a stub, it should have triggered and caused
9079 	 * a mount for us to get this far.
9080 	 */
9081 	ASSERT(!RP_ISSTUB(rp));
9082 
9083 	num_ops = 2;
9084 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9085 		/*
9086 		 * Since nfsv4 readdir may not return entries for "." and "..",
9087 		 * the client must recreate them:
9088 		 * To find the correct nodeid, do the following:
9089 		 * For current node, get nodeid from dnlc.
9090 		 * - if current node is rootvp, set pnodeid to nodeid.
9091 		 * - else if parent is in the dnlc, get its nodeid from there.
9092 		 * - else add LOOKUPP+GETATTR to compound.
9093 		 */
9094 		nodeid = rp->r_attr.va_nodeid;
9095 		if (vp->v_flag & VROOT) {
9096 			pnodeid = nodeid;	/* root of mount point */
9097 		} else {
9098 			dvp = dnlc_lookup(vp, "..");
9099 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9100 				/* parent in dnlc cache - no need for otw */
9101 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9102 			} else {
9103 				/*
9104 				 * parent not in dnlc cache,
9105 				 * do lookupp to get its id
9106 				 */
9107 				num_ops = 5;
9108 				pnodeid = 0; /* set later by getattr parent */
9109 			}
9110 			if (dvp)
9111 				VN_RELE(dvp);
9112 		}
9113 	}
9114 	recov_state.rs_flags = 0;
9115 	recov_state.rs_num_retry_despite_err = 0;
9116 
9117 	/* Save the original mount point security flavor */
9118 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9119 
9120 recov_retry:
9121 	args.ctag = TAG_READDIR;
9122 
9123 	args.array = argop;
9124 	args.array_len = num_ops;
9125 
9126 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9127 	    &recov_state, NULL)) {
9128 		/*
9129 		 * If readdir a node that is a stub for a crossed mount point,
9130 		 * keep the original secinfo flavor for the current file
9131 		 * system, not the crossed one.
9132 		 */
9133 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9134 		rdc->error = e.error;
9135 		return;
9136 	}
9137 
9138 	/*
9139 	 * Determine which attrs to request for dirents.  This code
9140 	 * must be protected by nfs4_start/end_fop because of r_server
9141 	 * (which will change during failover recovery).
9142 	 *
9143 	 */
9144 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9145 		/*
9146 		 * Get all vattr attrs plus filehandle and rdattr_error
9147 		 */
9148 		rd_bitsval = NFS4_VATTR_MASK |
9149 		    FATTR4_RDATTR_ERROR_MASK |
9150 		    FATTR4_FILEHANDLE_MASK;
9151 
9152 		if (rp->r_flags & R4READDIRWATTR) {
9153 			mutex_enter(&rp->r_statelock);
9154 			rp->r_flags &= ~R4READDIRWATTR;
9155 			mutex_exit(&rp->r_statelock);
9156 		}
9157 	} else {
9158 		servinfo4_t *svp = rp->r_server;
9159 
9160 		/*
9161 		 * Already read directory. Use readdir with
9162 		 * no attrs (except for mounted_on_fileid) for updates.
9163 		 */
9164 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9165 
9166 		/*
9167 		 * request mounted on fileid if supported, else request
9168 		 * fileid.  maybe we should verify that fileid is supported
9169 		 * and request something else if not.
9170 		 */
9171 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9172 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9173 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9174 		nfs_rw_exit(&svp->sv_lock);
9175 	}
9176 
9177 	/* putfh directory fh */
9178 	argop[0].argop = OP_CPUTFH;
9179 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9180 
9181 	argop[1].argop = OP_READDIR;
9182 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9183 	/*
9184 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9185 	 * cookie 0 should be used over-the-wire to start reading at
9186 	 * the beginning of the directory excluding "." and "..".
9187 	 */
9188 	if (rdc->nfs4_cookie == 0 ||
9189 	    rdc->nfs4_cookie == 1 ||
9190 	    rdc->nfs4_cookie == 2) {
9191 		rargs->cookie = (nfs_cookie4)0;
9192 		rargs->cookieverf = 0;
9193 	} else {
9194 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9195 		mutex_enter(&rp->r_statelock);
9196 		rargs->cookieverf = rp->r_cookieverf4;
9197 		mutex_exit(&rp->r_statelock);
9198 	}
9199 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9200 	rargs->maxcount = mi->mi_tsize;
9201 	rargs->attr_request = rd_bitsval;
9202 	rargs->rdc = rdc;
9203 	rargs->dvp = vp;
9204 	rargs->mi = mi;
9205 	rargs->cr = cr;
9206 
9207 
9208 	/*
9209 	 * If count < than the minimum required, we return no entries
9210 	 * and fail with EINVAL
9211 	 */
9212 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9213 		rdc->error = EINVAL;
9214 		goto out;
9215 	}
9216 
9217 	if (args.array_len == 5) {
9218 		/*
9219 		 * Add lookupp and getattr for parent nodeid.
9220 		 */
9221 		argop[2].argop = OP_LOOKUPP;
9222 
9223 		argop[3].argop = OP_GETFH;
9224 
9225 		/* getattr parent */
9226 		argop[4].argop = OP_GETATTR;
9227 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9228 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9229 	}
9230 
9231 	doqueue = 1;
9232 
9233 	if (mi->mi_io_kstats) {
9234 		mutex_enter(&mi->mi_lock);
9235 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9236 		mutex_exit(&mi->mi_lock);
9237 	}
9238 
9239 	/* capture the time of this call */
9240 	rargs->t = t = gethrtime();
9241 
9242 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9243 
9244 	if (mi->mi_io_kstats) {
9245 		mutex_enter(&mi->mi_lock);
9246 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9247 		mutex_exit(&mi->mi_lock);
9248 	}
9249 
9250 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9251 
9252 	/*
9253 	 * If RPC error occurred and it isn't an error that
9254 	 * triggers recovery, then go ahead and fail now.
9255 	 */
9256 	if (e.error != 0 && !needrecov) {
9257 		rdc->error = e.error;
9258 		goto out;
9259 	}
9260 
9261 	if (needrecov) {
9262 		bool_t abort;
9263 
9264 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9265 		    "nfs4readdir: initiating recovery.\n"));
9266 
9267 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9268 		    NULL, OP_READDIR, NULL);
9269 		if (abort == FALSE) {
9270 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9271 			    &recov_state, needrecov);
9272 			if (!e.error)
9273 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9274 				    (caddr_t)&res);
9275 			if (rdc->entries != NULL) {
9276 				kmem_free(rdc->entries, rdc->entlen);
9277 				rdc->entries = NULL;
9278 			}
9279 			goto recov_retry;
9280 		}
9281 
9282 		if (e.error != 0) {
9283 			rdc->error = e.error;
9284 			goto out;
9285 		}
9286 
9287 		/* fall through for res.status case */
9288 	}
9289 
9290 	res_opcnt = res.array_len;
9291 
9292 	/*
9293 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9294 	 * failure here.  Subsequent ops are for filling out dot-dot
9295 	 * dirent, and if they fail, we still want to give the caller
9296 	 * the dirents returned by (the successful) READDIR op, so we need
9297 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9298 	 *
9299 	 * One example where PUTFH+READDIR ops would succeed but
9300 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9301 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9302 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9303 	 * x perm.  We need to come up with a non-vendor-specific way
9304 	 * for a POSIX server to return d_ino from dotdot's dirent if
9305 	 * client only requests mounted_on_fileid, and just say the
9306 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9307 	 * client requested any mandatory attrs, server would be required
9308 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9309 	 * for dotdot.
9310 	 */
9311 
9312 	if (res.status) {
9313 		if (res_opcnt <= 2) {
9314 			e.error = geterrno4(res.status);
9315 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9316 			    &recov_state, needrecov);
9317 			nfs4_purge_stale_fh(e.error, vp, cr);
9318 			rdc->error = e.error;
9319 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9320 			if (rdc->entries != NULL) {
9321 				kmem_free(rdc->entries, rdc->entlen);
9322 				rdc->entries = NULL;
9323 			}
9324 			/*
9325 			 * If readdir a node that is a stub for a
9326 			 * crossed mount point, keep the original
9327 			 * secinfo flavor for the current file system,
9328 			 * not the crossed one.
9329 			 */
9330 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9331 			return;
9332 		}
9333 	}
9334 
9335 	resop = &res.array[1];	/* readdir res */
9336 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9337 
9338 	mutex_enter(&rp->r_statelock);
9339 	rp->r_cookieverf4 = rd_res->cookieverf;
9340 	mutex_exit(&rp->r_statelock);
9341 
9342 	/*
9343 	 * For "." and ".." entries
9344 	 * e.g.
9345 	 *	seek(cookie=0) -> "." entry with d_off = 1
9346 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9347 	 */
9348 	if (cookie == (nfs_cookie4) 0) {
9349 		if (rd_res->dotp)
9350 			rd_res->dotp->d_ino = nodeid;
9351 		if (rd_res->dotdotp)
9352 			rd_res->dotdotp->d_ino = pnodeid;
9353 	}
9354 	if (cookie == (nfs_cookie4) 1) {
9355 		if (rd_res->dotdotp)
9356 			rd_res->dotdotp->d_ino = pnodeid;
9357 	}
9358 
9359 
9360 	/* LOOKUPP+GETATTR attemped */
9361 	if (args.array_len == 5 && rd_res->dotdotp) {
9362 		if (res.status == NFS4_OK && res_opcnt == 5) {
9363 			nfs_fh4 *fhp;
9364 			nfs4_sharedfh_t *sfhp;
9365 			vnode_t *pvp;
9366 			nfs4_ga_res_t *garp;
9367 
9368 			resop++;	/* lookupp */
9369 			resop++;	/* getfh   */
9370 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9371 
9372 			resop++;	/* getattr of parent */
9373 
9374 			/*
9375 			 * First, take care of finishing the
9376 			 * readdir results.
9377 			 */
9378 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9379 			/*
9380 			 * The d_ino of .. must be the inode number
9381 			 * of the mounted filesystem.
9382 			 */
9383 			if (garp->n4g_va.va_mask & AT_NODEID)
9384 				rd_res->dotdotp->d_ino =
9385 				    garp->n4g_va.va_nodeid;
9386 
9387 
9388 			/*
9389 			 * Next, create the ".." dnlc entry
9390 			 */
9391 			sfhp = sfh4_get(fhp, mi);
9392 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9393 				dnlc_update(vp, "..", pvp);
9394 				VN_RELE(pvp);
9395 			}
9396 			sfh4_rele(&sfhp);
9397 		}
9398 	}
9399 
9400 	if (mi->mi_io_kstats) {
9401 		mutex_enter(&mi->mi_lock);
9402 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9403 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9404 		mutex_exit(&mi->mi_lock);
9405 	}
9406 
9407 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9408 
9409 out:
9410 	/*
9411 	 * If readdir a node that is a stub for a crossed mount point,
9412 	 * keep the original secinfo flavor for the current file system,
9413 	 * not the crossed one.
9414 	 */
9415 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9416 
9417 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9418 }
9419 
9420 
9421 static int
9422 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9423 {
9424 	rnode4_t *rp = VTOR4(bp->b_vp);
9425 	int count;
9426 	int error;
9427 	cred_t *cred_otw = NULL;
9428 	offset_t offset;
9429 	nfs4_open_stream_t *osp = NULL;
9430 	bool_t first_time = TRUE;	/* first time getting otw cred */
9431 	bool_t last_time = FALSE;	/* last time getting otw cred */
9432 
9433 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9434 
9435 	DTRACE_IO1(start, struct buf *, bp);
9436 	offset = ldbtob(bp->b_lblkno);
9437 
9438 	if (bp->b_flags & B_READ) {
9439 	read_again:
9440 		/*
9441 		 * Releases the osp, if it is provided.
9442 		 * Puts a hold on the cred_otw and the new osp (if found).
9443 		 */
9444 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9445 		    &first_time, &last_time);
9446 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9447 		    offset, bp->b_bcount, &bp->b_resid, cred_otw,
9448 		    readahead, NULL);
9449 		crfree(cred_otw);
9450 		if (!error) {
9451 			if (bp->b_resid) {
9452 				/*
9453 				 * Didn't get it all because we hit EOF,
9454 				 * zero all the memory beyond the EOF.
9455 				 */
9456 				/* bzero(rdaddr + */
9457 				bzero(bp->b_un.b_addr +
9458 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9459 			}
9460 			mutex_enter(&rp->r_statelock);
9461 			if (bp->b_resid == bp->b_bcount &&
9462 			    offset >= rp->r_size) {
9463 				/*
9464 				 * We didn't read anything at all as we are
9465 				 * past EOF.  Return an error indicator back
9466 				 * but don't destroy the pages (yet).
9467 				 */
9468 				error = NFS_EOF;
9469 			}
9470 			mutex_exit(&rp->r_statelock);
9471 		} else if (error == EACCES && last_time == FALSE) {
9472 				goto read_again;
9473 		}
9474 	} else {
9475 		if (!(rp->r_flags & R4STALE)) {
9476 write_again:
9477 			/*
9478 			 * Releases the osp, if it is provided.
9479 			 * Puts a hold on the cred_otw and the new
9480 			 * osp (if found).
9481 			 */
9482 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9483 			    &first_time, &last_time);
9484 			mutex_enter(&rp->r_statelock);
9485 			count = MIN(bp->b_bcount, rp->r_size - offset);
9486 			mutex_exit(&rp->r_statelock);
9487 			if (count < 0)
9488 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9489 #ifdef DEBUG
9490 			if (count == 0) {
9491 				zoneid_t zoneid = getzoneid();
9492 
9493 				zcmn_err(zoneid, CE_WARN,
9494 				    "nfs4_bio: zero length write at %lld",
9495 				    offset);
9496 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9497 				    "b_bcount=%ld, file size=%lld",
9498 				    rp->r_flags, (long)bp->b_bcount,
9499 				    rp->r_size);
9500 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9501 				if (nfs4_bio_do_stop)
9502 					debug_enter("nfs4_bio");
9503 			}
9504 #endif
9505 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9506 			    count, cred_otw, stab_comm);
9507 			if (error == EACCES && last_time == FALSE) {
9508 				crfree(cred_otw);
9509 				goto write_again;
9510 			}
9511 			bp->b_error = error;
9512 			if (error && error != EINTR &&
9513 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9514 				/*
9515 				 * Don't print EDQUOT errors on the console.
9516 				 * Don't print asynchronous EACCES errors.
9517 				 * Don't print EFBIG errors.
9518 				 * Print all other write errors.
9519 				 */
9520 				if (error != EDQUOT && error != EFBIG &&
9521 				    (error != EACCES ||
9522 				    !(bp->b_flags & B_ASYNC)))
9523 					nfs4_write_error(bp->b_vp,
9524 					    error, cred_otw);
9525 				/*
9526 				 * Update r_error and r_flags as appropriate.
9527 				 * If the error was ESTALE, then mark the
9528 				 * rnode as not being writeable and save
9529 				 * the error status.  Otherwise, save any
9530 				 * errors which occur from asynchronous
9531 				 * page invalidations.  Any errors occurring
9532 				 * from other operations should be saved
9533 				 * by the caller.
9534 				 */
9535 				mutex_enter(&rp->r_statelock);
9536 				if (error == ESTALE) {
9537 					rp->r_flags |= R4STALE;
9538 					if (!rp->r_error)
9539 						rp->r_error = error;
9540 				} else if (!rp->r_error &&
9541 				    (bp->b_flags &
9542 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9543 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9544 					rp->r_error = error;
9545 				}
9546 				mutex_exit(&rp->r_statelock);
9547 			}
9548 			crfree(cred_otw);
9549 		} else
9550 			error = rp->r_error;
9551 	}
9552 
9553 	if (error != 0 && error != NFS_EOF)
9554 		bp->b_flags |= B_ERROR;
9555 
9556 	if (osp)
9557 		open_stream_rele(osp, rp);
9558 
9559 	DTRACE_IO1(done, struct buf *, bp);
9560 
9561 	return (error);
9562 }
9563 
9564 /* ARGSUSED */
9565 int
9566 nfs4_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
9567 {
9568 	return (EREMOTE);
9569 }
9570 
9571 /* ARGSUSED2 */
9572 int
9573 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9574 {
9575 	rnode4_t *rp = VTOR4(vp);
9576 
9577 	if (!write_lock) {
9578 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9579 		return (V_WRITELOCK_FALSE);
9580 	}
9581 
9582 	if ((rp->r_flags & R4DIRECTIO) ||
9583 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9584 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9585 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9586 			return (V_WRITELOCK_FALSE);
9587 		nfs_rw_exit(&rp->r_rwlock);
9588 	}
9589 
9590 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9591 	return (V_WRITELOCK_TRUE);
9592 }
9593 
9594 /* ARGSUSED */
9595 void
9596 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9597 {
9598 	rnode4_t *rp = VTOR4(vp);
9599 
9600 	nfs_rw_exit(&rp->r_rwlock);
9601 }
9602 
9603 /* ARGSUSED */
9604 static int
9605 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp, caller_context_t *ct)
9606 {
9607 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9608 		return (EIO);
9609 
9610 	/*
9611 	 * Because we stuff the readdir cookie into the offset field
9612 	 * someone may attempt to do an lseek with the cookie which
9613 	 * we want to succeed.
9614 	 */
9615 	if (vp->v_type == VDIR)
9616 		return (0);
9617 	if (*noffp < 0)
9618 		return (EINVAL);
9619 	return (0);
9620 }
9621 
9622 
9623 /*
9624  * Return all the pages from [off..off+len) in file
9625  */
9626 /* ARGSUSED */
9627 static int
9628 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9629     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9630 	enum seg_rw rw, cred_t *cr, caller_context_t *ct)
9631 {
9632 	rnode4_t *rp;
9633 	int error;
9634 	mntinfo4_t *mi;
9635 
9636 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9637 		return (EIO);
9638 	rp = VTOR4(vp);
9639 	if (IS_SHADOW(vp, rp))
9640 		vp = RTOV4(rp);
9641 
9642 	if (vp->v_flag & VNOMAP)
9643 		return (ENOSYS);
9644 
9645 	if (protp != NULL)
9646 		*protp = PROT_ALL;
9647 
9648 	/*
9649 	 * Now validate that the caches are up to date.
9650 	 */
9651 	if (error = nfs4_validate_caches(vp, cr))
9652 		return (error);
9653 
9654 	mi = VTOMI4(vp);
9655 retry:
9656 	mutex_enter(&rp->r_statelock);
9657 
9658 	/*
9659 	 * Don't create dirty pages faster than they
9660 	 * can be cleaned so that the system doesn't
9661 	 * get imbalanced.  If the async queue is
9662 	 * maxed out, then wait for it to drain before
9663 	 * creating more dirty pages.  Also, wait for
9664 	 * any threads doing pagewalks in the vop_getattr
9665 	 * entry points so that they don't block for
9666 	 * long periods.
9667 	 */
9668 	if (rw == S_CREATE) {
9669 		while ((mi->mi_max_threads != 0 &&
9670 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
9671 		    rp->r_gcount > 0)
9672 			cv_wait(&rp->r_cv, &rp->r_statelock);
9673 	}
9674 
9675 	/*
9676 	 * If we are getting called as a side effect of an nfs_write()
9677 	 * operation the local file size might not be extended yet.
9678 	 * In this case we want to be able to return pages of zeroes.
9679 	 */
9680 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9681 		NFS4_DEBUG(nfs4_pageio_debug,
9682 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9683 		    "len=%llu, size=%llu, attrsize =%llu", off,
9684 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9685 		mutex_exit(&rp->r_statelock);
9686 		return (EFAULT);		/* beyond EOF */
9687 	}
9688 
9689 	mutex_exit(&rp->r_statelock);
9690 
9691 	if (len <= PAGESIZE) {
9692 		error = nfs4_getapage(vp, off, len, protp, pl, plsz,
9693 		    seg, addr, rw, cr);
9694 		NFS4_DEBUG(nfs4_pageio_debug && error,
9695 		    (CE_NOTE, "getpage error %d; off=%lld, "
9696 		    "len=%lld", error, off, (u_longlong_t)len));
9697 	} else {
9698 		error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9699 		    pl, plsz, seg, addr, rw, cr);
9700 		NFS4_DEBUG(nfs4_pageio_debug && error,
9701 		    (CE_NOTE, "getpages error %d; off=%lld, "
9702 		    "len=%lld", error, off, (u_longlong_t)len));
9703 	}
9704 
9705 	switch (error) {
9706 	case NFS_EOF:
9707 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9708 		goto retry;
9709 	case ESTALE:
9710 		nfs4_purge_stale_fh(error, vp, cr);
9711 	}
9712 
9713 	return (error);
9714 }
9715 
9716 /*
9717  * Called from pvn_getpages or nfs4_getpage to get a particular page.
9718  */
9719 /* ARGSUSED */
9720 static int
9721 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9722     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9723     enum seg_rw rw, cred_t *cr)
9724 {
9725 	rnode4_t *rp;
9726 	uint_t bsize;
9727 	struct buf *bp;
9728 	page_t *pp;
9729 	u_offset_t lbn;
9730 	u_offset_t io_off;
9731 	u_offset_t blkoff;
9732 	u_offset_t rablkoff;
9733 	size_t io_len;
9734 	uint_t blksize;
9735 	int error;
9736 	int readahead;
9737 	int readahead_issued = 0;
9738 	int ra_window; /* readahead window */
9739 	page_t *pagefound;
9740 	page_t *savepp;
9741 
9742 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9743 		return (EIO);
9744 
9745 	rp = VTOR4(vp);
9746 	ASSERT(!IS_SHADOW(vp, rp));
9747 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9748 
9749 reread:
9750 	bp = NULL;
9751 	pp = NULL;
9752 	pagefound = NULL;
9753 
9754 	if (pl != NULL)
9755 		pl[0] = NULL;
9756 
9757 	error = 0;
9758 	lbn = off / bsize;
9759 	blkoff = lbn * bsize;
9760 
9761 	/*
9762 	 * Queueing up the readahead before doing the synchronous read
9763 	 * results in a significant increase in read throughput because
9764 	 * of the increased parallelism between the async threads and
9765 	 * the process context.
9766 	 */
9767 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9768 	    rw != S_CREATE &&
9769 	    !(vp->v_flag & VNOCACHE)) {
9770 		mutex_enter(&rp->r_statelock);
9771 
9772 		/*
9773 		 * Calculate the number of readaheads to do.
9774 		 * a) No readaheads at offset = 0.
9775 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9776 		 *    window is closed.
9777 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9778 		 *    upon how far the readahead window is open or close.
9779 		 * d) No readaheads if rp->r_nextr is not within the scope
9780 		 *    of the readahead window (random i/o).
9781 		 */
9782 
9783 		if (off == 0)
9784 			readahead = 0;
9785 		else if (blkoff == rp->r_nextr)
9786 			readahead = nfs4_nra;
9787 		else if (rp->r_nextr > blkoff &&
9788 		    ((ra_window = (rp->r_nextr - blkoff) / bsize)
9789 		    <= (nfs4_nra - 1)))
9790 			readahead = nfs4_nra - ra_window;
9791 		else
9792 			readahead = 0;
9793 
9794 		rablkoff = rp->r_nextr;
9795 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9796 			mutex_exit(&rp->r_statelock);
9797 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9798 			    addr + (rablkoff + bsize - off),
9799 			    seg, cr, nfs4_readahead) < 0) {
9800 				mutex_enter(&rp->r_statelock);
9801 				break;
9802 			}
9803 			readahead--;
9804 			rablkoff += bsize;
9805 			/*
9806 			 * Indicate that we did a readahead so
9807 			 * readahead offset is not updated
9808 			 * by the synchronous read below.
9809 			 */
9810 			readahead_issued = 1;
9811 			mutex_enter(&rp->r_statelock);
9812 			/*
9813 			 * set readahead offset to
9814 			 * offset of last async readahead
9815 			 * request.
9816 			 */
9817 			rp->r_nextr = rablkoff;
9818 		}
9819 		mutex_exit(&rp->r_statelock);
9820 	}
9821 
9822 again:
9823 	if ((pagefound = page_exists(vp, off)) == NULL) {
9824 		if (pl == NULL) {
9825 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9826 			    nfs4_readahead);
9827 		} else if (rw == S_CREATE) {
9828 			/*
9829 			 * Block for this page is not allocated, or the offset
9830 			 * is beyond the current allocation size, or we're
9831 			 * allocating a swap slot and the page was not found,
9832 			 * so allocate it and return a zero page.
9833 			 */
9834 			if ((pp = page_create_va(vp, off,
9835 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9836 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9837 			io_len = PAGESIZE;
9838 			mutex_enter(&rp->r_statelock);
9839 			rp->r_nextr = off + PAGESIZE;
9840 			mutex_exit(&rp->r_statelock);
9841 		} else {
9842 			/*
9843 			 * Need to go to server to get a block
9844 			 */
9845 			mutex_enter(&rp->r_statelock);
9846 			if (blkoff < rp->r_size &&
9847 			    blkoff + bsize > rp->r_size) {
9848 				/*
9849 				 * If less than a block left in
9850 				 * file read less than a block.
9851 				 */
9852 				if (rp->r_size <= off) {
9853 					/*
9854 					 * Trying to access beyond EOF,
9855 					 * set up to get at least one page.
9856 					 */
9857 					blksize = off + PAGESIZE - blkoff;
9858 				} else
9859 					blksize = rp->r_size - blkoff;
9860 			} else if ((off == 0) ||
9861 			    (off != rp->r_nextr && !readahead_issued)) {
9862 				blksize = PAGESIZE;
9863 				blkoff = off; /* block = page here */
9864 			} else
9865 				blksize = bsize;
9866 			mutex_exit(&rp->r_statelock);
9867 
9868 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9869 			    &io_len, blkoff, blksize, 0);
9870 
9871 			/*
9872 			 * Some other thread has entered the page,
9873 			 * so just use it.
9874 			 */
9875 			if (pp == NULL)
9876 				goto again;
9877 
9878 			/*
9879 			 * Now round the request size up to page boundaries.
9880 			 * This ensures that the entire page will be
9881 			 * initialized to zeroes if EOF is encountered.
9882 			 */
9883 			io_len = ptob(btopr(io_len));
9884 
9885 			bp = pageio_setup(pp, io_len, vp, B_READ);
9886 			ASSERT(bp != NULL);
9887 
9888 			/*
9889 			 * pageio_setup should have set b_addr to 0.  This
9890 			 * is correct since we want to do I/O on a page
9891 			 * boundary.  bp_mapin will use this addr to calculate
9892 			 * an offset, and then set b_addr to the kernel virtual
9893 			 * address it allocated for us.
9894 			 */
9895 			ASSERT(bp->b_un.b_addr == 0);
9896 
9897 			bp->b_edev = 0;
9898 			bp->b_dev = 0;
9899 			bp->b_lblkno = lbtodb(io_off);
9900 			bp->b_file = vp;
9901 			bp->b_offset = (offset_t)off;
9902 			bp_mapin(bp);
9903 
9904 			/*
9905 			 * If doing a write beyond what we believe is EOF,
9906 			 * don't bother trying to read the pages from the
9907 			 * server, we'll just zero the pages here.  We
9908 			 * don't check that the rw flag is S_WRITE here
9909 			 * because some implementations may attempt a
9910 			 * read access to the buffer before copying data.
9911 			 */
9912 			mutex_enter(&rp->r_statelock);
9913 			if (io_off >= rp->r_size && seg == segkmap) {
9914 				mutex_exit(&rp->r_statelock);
9915 				bzero(bp->b_un.b_addr, io_len);
9916 			} else {
9917 				mutex_exit(&rp->r_statelock);
9918 				error = nfs4_bio(bp, NULL, cr, FALSE);
9919 			}
9920 
9921 			/*
9922 			 * Unmap the buffer before freeing it.
9923 			 */
9924 			bp_mapout(bp);
9925 			pageio_done(bp);
9926 
9927 			savepp = pp;
9928 			do {
9929 				pp->p_fsdata = C_NOCOMMIT;
9930 			} while ((pp = pp->p_next) != savepp);
9931 
9932 			if (error == NFS_EOF) {
9933 				/*
9934 				 * If doing a write system call just return
9935 				 * zeroed pages, else user tried to get pages
9936 				 * beyond EOF, return error.  We don't check
9937 				 * that the rw flag is S_WRITE here because
9938 				 * some implementations may attempt a read
9939 				 * access to the buffer before copying data.
9940 				 */
9941 				if (seg == segkmap)
9942 					error = 0;
9943 				else
9944 					error = EFAULT;
9945 			}
9946 
9947 			if (!readahead_issued && !error) {
9948 				mutex_enter(&rp->r_statelock);
9949 				rp->r_nextr = io_off + io_len;
9950 				mutex_exit(&rp->r_statelock);
9951 			}
9952 		}
9953 	}
9954 
9955 out:
9956 	if (pl == NULL)
9957 		return (error);
9958 
9959 	if (error) {
9960 		if (pp != NULL)
9961 			pvn_read_done(pp, B_ERROR);
9962 		return (error);
9963 	}
9964 
9965 	if (pagefound) {
9966 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
9967 
9968 		/*
9969 		 * Page exists in the cache, acquire the appropriate lock.
9970 		 * If this fails, start all over again.
9971 		 */
9972 		if ((pp = page_lookup(vp, off, se)) == NULL) {
9973 #ifdef DEBUG
9974 			nfs4_lostpage++;
9975 #endif
9976 			goto reread;
9977 		}
9978 		pl[0] = pp;
9979 		pl[1] = NULL;
9980 		return (0);
9981 	}
9982 
9983 	if (pp != NULL)
9984 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
9985 
9986 	return (error);
9987 }
9988 
9989 static void
9990 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
9991     cred_t *cr)
9992 {
9993 	int error;
9994 	page_t *pp;
9995 	u_offset_t io_off;
9996 	size_t io_len;
9997 	struct buf *bp;
9998 	uint_t bsize, blksize;
9999 	rnode4_t *rp = VTOR4(vp);
10000 	page_t *savepp;
10001 
10002 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10003 
10004 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10005 
10006 	mutex_enter(&rp->r_statelock);
10007 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
10008 		/*
10009 		 * If less than a block left in file read less
10010 		 * than a block.
10011 		 */
10012 		blksize = rp->r_size - blkoff;
10013 	} else
10014 		blksize = bsize;
10015 	mutex_exit(&rp->r_statelock);
10016 
10017 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
10018 	    &io_off, &io_len, blkoff, blksize, 1);
10019 	/*
10020 	 * The isra flag passed to the kluster function is 1, we may have
10021 	 * gotten a return value of NULL for a variety of reasons (# of free
10022 	 * pages < minfree, someone entered the page on the vnode etc). In all
10023 	 * cases, we want to punt on the readahead.
10024 	 */
10025 	if (pp == NULL)
10026 		return;
10027 
10028 	/*
10029 	 * Now round the request size up to page boundaries.
10030 	 * This ensures that the entire page will be
10031 	 * initialized to zeroes if EOF is encountered.
10032 	 */
10033 	io_len = ptob(btopr(io_len));
10034 
10035 	bp = pageio_setup(pp, io_len, vp, B_READ);
10036 	ASSERT(bp != NULL);
10037 
10038 	/*
10039 	 * pageio_setup should have set b_addr to 0.  This is correct since
10040 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10041 	 * to calculate an offset, and then set b_addr to the kernel virtual
10042 	 * address it allocated for us.
10043 	 */
10044 	ASSERT(bp->b_un.b_addr == 0);
10045 
10046 	bp->b_edev = 0;
10047 	bp->b_dev = 0;
10048 	bp->b_lblkno = lbtodb(io_off);
10049 	bp->b_file = vp;
10050 	bp->b_offset = (offset_t)blkoff;
10051 	bp_mapin(bp);
10052 
10053 	/*
10054 	 * If doing a write beyond what we believe is EOF, don't bother trying
10055 	 * to read the pages from the server, we'll just zero the pages here.
10056 	 * We don't check that the rw flag is S_WRITE here because some
10057 	 * implementations may attempt a read access to the buffer before
10058 	 * copying data.
10059 	 */
10060 	mutex_enter(&rp->r_statelock);
10061 	if (io_off >= rp->r_size && seg == segkmap) {
10062 		mutex_exit(&rp->r_statelock);
10063 		bzero(bp->b_un.b_addr, io_len);
10064 		error = 0;
10065 	} else {
10066 		mutex_exit(&rp->r_statelock);
10067 		error = nfs4_bio(bp, NULL, cr, TRUE);
10068 		if (error == NFS_EOF)
10069 			error = 0;
10070 	}
10071 
10072 	/*
10073 	 * Unmap the buffer before freeing it.
10074 	 */
10075 	bp_mapout(bp);
10076 	pageio_done(bp);
10077 
10078 	savepp = pp;
10079 	do {
10080 		pp->p_fsdata = C_NOCOMMIT;
10081 	} while ((pp = pp->p_next) != savepp);
10082 
10083 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10084 
10085 	/*
10086 	 * In case of error set readahead offset
10087 	 * to the lowest offset.
10088 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10089 	 */
10090 	if (error && rp->r_nextr > io_off) {
10091 		mutex_enter(&rp->r_statelock);
10092 		if (rp->r_nextr > io_off)
10093 			rp->r_nextr = io_off;
10094 		mutex_exit(&rp->r_statelock);
10095 	}
10096 }
10097 
10098 /*
10099  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10100  * If len == 0, do from off to EOF.
10101  *
10102  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10103  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10104  * (from pageout).
10105  */
10106 /* ARGSUSED */
10107 static int
10108 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
10109 	caller_context_t *ct)
10110 {
10111 	int error;
10112 	rnode4_t *rp;
10113 
10114 	ASSERT(cr != NULL);
10115 
10116 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10117 		return (EIO);
10118 
10119 	rp = VTOR4(vp);
10120 	if (IS_SHADOW(vp, rp))
10121 		vp = RTOV4(rp);
10122 
10123 	/*
10124 	 * XXX - Why should this check be made here?
10125 	 */
10126 	if (vp->v_flag & VNOMAP)
10127 		return (ENOSYS);
10128 
10129 	if (len == 0 && !(flags & B_INVAL) &&
10130 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10131 		return (0);
10132 
10133 	mutex_enter(&rp->r_statelock);
10134 	rp->r_count++;
10135 	mutex_exit(&rp->r_statelock);
10136 	error = nfs4_putpages(vp, off, len, flags, cr);
10137 	mutex_enter(&rp->r_statelock);
10138 	rp->r_count--;
10139 	cv_broadcast(&rp->r_cv);
10140 	mutex_exit(&rp->r_statelock);
10141 
10142 	return (error);
10143 }
10144 
10145 /*
10146  * Write out a single page, possibly klustering adjacent dirty pages.
10147  */
10148 int
10149 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10150     int flags, cred_t *cr)
10151 {
10152 	u_offset_t io_off;
10153 	u_offset_t lbn_off;
10154 	u_offset_t lbn;
10155 	size_t io_len;
10156 	uint_t bsize;
10157 	int error;
10158 	rnode4_t *rp;
10159 
10160 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10161 	ASSERT(pp != NULL);
10162 	ASSERT(cr != NULL);
10163 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10164 
10165 	rp = VTOR4(vp);
10166 	ASSERT(rp->r_count > 0);
10167 	ASSERT(!IS_SHADOW(vp, rp));
10168 
10169 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10170 	lbn = pp->p_offset / bsize;
10171 	lbn_off = lbn * bsize;
10172 
10173 	/*
10174 	 * Find a kluster that fits in one block, or in
10175 	 * one page if pages are bigger than blocks.  If
10176 	 * there is less file space allocated than a whole
10177 	 * page, we'll shorten the i/o request below.
10178 	 */
10179 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10180 	    roundup(bsize, PAGESIZE), flags);
10181 
10182 	/*
10183 	 * pvn_write_kluster shouldn't have returned a page with offset
10184 	 * behind the original page we were given.  Verify that.
10185 	 */
10186 	ASSERT((pp->p_offset / bsize) >= lbn);
10187 
10188 	/*
10189 	 * Now pp will have the list of kept dirty pages marked for
10190 	 * write back.  It will also handle invalidation and freeing
10191 	 * of pages that are not dirty.  Check for page length rounding
10192 	 * problems.
10193 	 */
10194 	if (io_off + io_len > lbn_off + bsize) {
10195 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10196 		io_len = lbn_off + bsize - io_off;
10197 	}
10198 	/*
10199 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10200 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10201 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10202 	 * progress and the r_size has not been made consistent with the
10203 	 * new size of the file. When the uiomove() completes the r_size is
10204 	 * updated and the R4MODINPROGRESS flag is cleared.
10205 	 *
10206 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10207 	 * consistent value of r_size. Without this handshaking, it is
10208 	 * possible that nfs4_bio() picks  up the old value of r_size
10209 	 * before the uiomove() in writerp4() completes. This will result
10210 	 * in the write through nfs4_bio() being dropped.
10211 	 *
10212 	 * More precisely, there is a window between the time the uiomove()
10213 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10214 	 * operation intervenes in this window, the page will be picked up,
10215 	 * because it is dirty (it will be unlocked, unless it was
10216 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10217 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10218 	 * checked. This will still be the old size. Therefore the page will
10219 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10220 	 * the page will be found to be clean and the write will be dropped.
10221 	 */
10222 	if (rp->r_flags & R4MODINPROGRESS) {
10223 		mutex_enter(&rp->r_statelock);
10224 		if ((rp->r_flags & R4MODINPROGRESS) &&
10225 		    rp->r_modaddr + MAXBSIZE > io_off &&
10226 		    rp->r_modaddr < io_off + io_len) {
10227 			page_t *plist;
10228 			/*
10229 			 * A write is in progress for this region of the file.
10230 			 * If we did not detect R4MODINPROGRESS here then this
10231 			 * path through nfs_putapage() would eventually go to
10232 			 * nfs4_bio() and may not write out all of the data
10233 			 * in the pages. We end up losing data. So we decide
10234 			 * to set the modified bit on each page in the page
10235 			 * list and mark the rnode with R4DIRTY. This write
10236 			 * will be restarted at some later time.
10237 			 */
10238 			plist = pp;
10239 			while (plist != NULL) {
10240 				pp = plist;
10241 				page_sub(&plist, pp);
10242 				hat_setmod(pp);
10243 				page_io_unlock(pp);
10244 				page_unlock(pp);
10245 			}
10246 			rp->r_flags |= R4DIRTY;
10247 			mutex_exit(&rp->r_statelock);
10248 			if (offp)
10249 				*offp = io_off;
10250 			if (lenp)
10251 				*lenp = io_len;
10252 			return (0);
10253 		}
10254 		mutex_exit(&rp->r_statelock);
10255 	}
10256 
10257 	if (flags & B_ASYNC) {
10258 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10259 		    nfs4_sync_putapage);
10260 	} else
10261 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10262 
10263 	if (offp)
10264 		*offp = io_off;
10265 	if (lenp)
10266 		*lenp = io_len;
10267 	return (error);
10268 }
10269 
10270 static int
10271 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10272     int flags, cred_t *cr)
10273 {
10274 	int error;
10275 	rnode4_t *rp;
10276 
10277 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10278 
10279 	flags |= B_WRITE;
10280 
10281 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10282 
10283 	rp = VTOR4(vp);
10284 
10285 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10286 	    error == EACCES) &&
10287 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10288 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10289 			mutex_enter(&rp->r_statelock);
10290 			rp->r_flags |= R4OUTOFSPACE;
10291 			mutex_exit(&rp->r_statelock);
10292 		}
10293 		flags |= B_ERROR;
10294 		pvn_write_done(pp, flags);
10295 		/*
10296 		 * If this was not an async thread, then try again to
10297 		 * write out the pages, but this time, also destroy
10298 		 * them whether or not the write is successful.  This
10299 		 * will prevent memory from filling up with these
10300 		 * pages and destroying them is the only alternative
10301 		 * if they can't be written out.
10302 		 *
10303 		 * Don't do this if this is an async thread because
10304 		 * when the pages are unlocked in pvn_write_done,
10305 		 * some other thread could have come along, locked
10306 		 * them, and queued for an async thread.  It would be
10307 		 * possible for all of the async threads to be tied
10308 		 * up waiting to lock the pages again and they would
10309 		 * all already be locked and waiting for an async
10310 		 * thread to handle them.  Deadlock.
10311 		 */
10312 		if (!(flags & B_ASYNC)) {
10313 			error = nfs4_putpage(vp, io_off, io_len,
10314 			    B_INVAL | B_FORCE, cr, NULL);
10315 		}
10316 	} else {
10317 		if (error)
10318 			flags |= B_ERROR;
10319 		else if (rp->r_flags & R4OUTOFSPACE) {
10320 			mutex_enter(&rp->r_statelock);
10321 			rp->r_flags &= ~R4OUTOFSPACE;
10322 			mutex_exit(&rp->r_statelock);
10323 		}
10324 		pvn_write_done(pp, flags);
10325 		if (freemem < desfree)
10326 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10327 			    NFS4_WRITE_NOWAIT);
10328 	}
10329 
10330 	return (error);
10331 }
10332 
10333 #ifdef DEBUG
10334 int nfs4_force_open_before_mmap = 0;
10335 #endif
10336 
10337 /* ARGSUSED */
10338 static int
10339 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10340     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10341     caller_context_t *ct)
10342 {
10343 	struct segvn_crargs vn_a;
10344 	int error = 0;
10345 	rnode4_t *rp = VTOR4(vp);
10346 	mntinfo4_t *mi = VTOMI4(vp);
10347 
10348 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10349 		return (EIO);
10350 
10351 	if (vp->v_flag & VNOMAP)
10352 		return (ENOSYS);
10353 
10354 	if (off < 0 || (off + len) < 0)
10355 		return (ENXIO);
10356 
10357 	if (vp->v_type != VREG)
10358 		return (ENODEV);
10359 
10360 	/*
10361 	 * If the file is delegated to the client don't do anything.
10362 	 * If the file is not delegated, then validate the data cache.
10363 	 */
10364 	mutex_enter(&rp->r_statev4_lock);
10365 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10366 		mutex_exit(&rp->r_statev4_lock);
10367 		error = nfs4_validate_caches(vp, cr);
10368 		if (error)
10369 			return (error);
10370 	} else {
10371 		mutex_exit(&rp->r_statev4_lock);
10372 	}
10373 
10374 	/*
10375 	 * Check to see if the vnode is currently marked as not cachable.
10376 	 * This means portions of the file are locked (through VOP_FRLOCK).
10377 	 * In this case the map request must be refused.  We use
10378 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10379 	 */
10380 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
10381 		return (EINTR);
10382 
10383 	if (vp->v_flag & VNOCACHE) {
10384 		error = EAGAIN;
10385 		goto done;
10386 	}
10387 
10388 	/*
10389 	 * Don't allow concurrent locks and mapping if mandatory locking is
10390 	 * enabled.
10391 	 */
10392 	if (flk_has_remote_locks(vp)) {
10393 		struct vattr va;
10394 		va.va_mask = AT_MODE;
10395 		error = nfs4getattr(vp, &va, cr);
10396 		if (error != 0)
10397 			goto done;
10398 		if (MANDLOCK(vp, va.va_mode)) {
10399 			error = EAGAIN;
10400 			goto done;
10401 		}
10402 	}
10403 
10404 	/*
10405 	 * It is possible that the rnode has a lost lock request that we
10406 	 * are still trying to recover, and that the request conflicts with
10407 	 * this map request.
10408 	 *
10409 	 * An alternative approach would be for nfs4_safemap() to consider
10410 	 * queued lock requests when deciding whether to set or clear
10411 	 * VNOCACHE.  This would require the frlock code path to call
10412 	 * nfs4_safemap() after enqueing a lost request.
10413 	 */
10414 	if (nfs4_map_lost_lock_conflict(vp)) {
10415 		error = EAGAIN;
10416 		goto done;
10417 	}
10418 
10419 	as_rangelock(as);
10420 	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
10421 	if (error != 0) {
10422 		as_rangeunlock(as);
10423 		goto done;
10424 	}
10425 
10426 	if (vp->v_type == VREG) {
10427 		/*
10428 		 * We need to retrieve the open stream
10429 		 */
10430 		nfs4_open_stream_t	*osp = NULL;
10431 		nfs4_open_owner_t	*oop = NULL;
10432 
10433 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10434 		if (oop != NULL) {
10435 			/* returns with 'os_sync_lock' held */
10436 			osp = find_open_stream(oop, rp);
10437 			open_owner_rele(oop);
10438 		}
10439 		if (osp == NULL) {
10440 #ifdef DEBUG
10441 			if (nfs4_force_open_before_mmap) {
10442 				error = EIO;
10443 				goto done;
10444 			}
10445 #endif
10446 			/* returns with 'os_sync_lock' held */
10447 			error = open_and_get_osp(vp, cr, &osp);
10448 			if (osp == NULL) {
10449 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10450 				    "nfs4_map: we tried to OPEN the file "
10451 				    "but again no osp, so fail with EIO"));
10452 				goto done;
10453 			}
10454 		}
10455 
10456 		if (osp->os_failed_reopen) {
10457 			mutex_exit(&osp->os_sync_lock);
10458 			open_stream_rele(osp, rp);
10459 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10460 			    "nfs4_map: os_failed_reopen set on "
10461 			    "osp %p, cr %p, rp %s", (void *)osp,
10462 			    (void *)cr, rnode4info(rp)));
10463 			error = EIO;
10464 			goto done;
10465 		}
10466 		mutex_exit(&osp->os_sync_lock);
10467 		open_stream_rele(osp, rp);
10468 	}
10469 
10470 	vn_a.vp = vp;
10471 	vn_a.offset = off;
10472 	vn_a.type = (flags & MAP_TYPE);
10473 	vn_a.prot = (uchar_t)prot;
10474 	vn_a.maxprot = (uchar_t)maxprot;
10475 	vn_a.flags = (flags & ~MAP_TYPE);
10476 	vn_a.cred = cr;
10477 	vn_a.amp = NULL;
10478 	vn_a.szc = 0;
10479 	vn_a.lgrp_mem_policy_flags = 0;
10480 
10481 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10482 	as_rangeunlock(as);
10483 
10484 done:
10485 	nfs_rw_exit(&rp->r_lkserlock);
10486 	return (error);
10487 }
10488 
10489 /*
10490  * We're most likely dealing with a kernel module that likes to READ
10491  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10492  * officially OPEN the file to create the necessary client state
10493  * for bookkeeping of os_mmap_read/write counts.
10494  *
10495  * Since VOP_MAP only passes in a pointer to the vnode rather than
10496  * a double pointer, we can't handle the case where nfs4open_otw()
10497  * returns a different vnode than the one passed into VOP_MAP (since
10498  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10499  * we return NULL and let nfs4_map() fail.  Note: the only case where
10500  * this should happen is if the file got removed and replaced with the
10501  * same name on the server (in addition to the fact that we're trying
10502  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10503  */
10504 static int
10505 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10506 {
10507 	rnode4_t		*rp, *drp;
10508 	vnode_t			*dvp, *open_vp;
10509 	char			file_name[MAXNAMELEN];
10510 	int			just_created;
10511 	nfs4_open_stream_t	*osp;
10512 	nfs4_open_owner_t	*oop;
10513 	int			error;
10514 
10515 	*ospp = NULL;
10516 	open_vp = map_vp;
10517 
10518 	rp = VTOR4(open_vp);
10519 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10520 		return (error);
10521 	drp = VTOR4(dvp);
10522 
10523 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10524 		VN_RELE(dvp);
10525 		return (EINTR);
10526 	}
10527 
10528 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10529 		nfs_rw_exit(&drp->r_rwlock);
10530 		VN_RELE(dvp);
10531 		return (error);
10532 	}
10533 
10534 	mutex_enter(&rp->r_statev4_lock);
10535 	if (rp->created_v4) {
10536 		rp->created_v4 = 0;
10537 		mutex_exit(&rp->r_statev4_lock);
10538 
10539 		dnlc_update(dvp, file_name, open_vp);
10540 		/* This is needed so we don't bump the open ref count */
10541 		just_created = 1;
10542 	} else {
10543 		mutex_exit(&rp->r_statev4_lock);
10544 		just_created = 0;
10545 	}
10546 
10547 	VN_HOLD(map_vp);
10548 
10549 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10550 	    just_created);
10551 	if (error) {
10552 		nfs_rw_exit(&drp->r_rwlock);
10553 		VN_RELE(dvp);
10554 		VN_RELE(map_vp);
10555 		return (error);
10556 	}
10557 
10558 	nfs_rw_exit(&drp->r_rwlock);
10559 	VN_RELE(dvp);
10560 
10561 	/*
10562 	 * If nfs4open_otw() returned a different vnode then "undo"
10563 	 * the open and return failure to the caller.
10564 	 */
10565 	if (!VN_CMP(open_vp, map_vp)) {
10566 		nfs4_error_t e;
10567 
10568 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10569 		    "open returned a different vnode"));
10570 		/*
10571 		 * If there's an error, ignore it,
10572 		 * and let VOP_INACTIVE handle it.
10573 		 */
10574 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10575 		    CLOSE_NORM, 0, 0, 0);
10576 		VN_RELE(map_vp);
10577 		return (EIO);
10578 	}
10579 
10580 	VN_RELE(map_vp);
10581 
10582 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10583 	if (!oop) {
10584 		nfs4_error_t e;
10585 
10586 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10587 		    "no open owner"));
10588 		/*
10589 		 * If there's an error, ignore it,
10590 		 * and let VOP_INACTIVE handle it.
10591 		 */
10592 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10593 		    CLOSE_NORM, 0, 0, 0);
10594 		return (EIO);
10595 	}
10596 	osp = find_open_stream(oop, rp);
10597 	open_owner_rele(oop);
10598 	*ospp = osp;
10599 	return (0);
10600 }
10601 
10602 /*
10603  * Please be aware that when this function is called, the address space write
10604  * a_lock is held.  Do not put over the wire calls in this function.
10605  */
10606 /* ARGSUSED */
10607 static int
10608 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10609     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10610     caller_context_t *ct)
10611 {
10612 	rnode4_t		*rp;
10613 	int			error = 0;
10614 	mntinfo4_t		*mi;
10615 
10616 	mi = VTOMI4(vp);
10617 	rp = VTOR4(vp);
10618 
10619 	if (nfs_zone() != mi->mi_zone)
10620 		return (EIO);
10621 	if (vp->v_flag & VNOMAP)
10622 		return (ENOSYS);
10623 
10624 	/*
10625 	 * Need to hold rwlock while incrementing the mapcnt so that
10626 	 * mmap'ing can be serialized with writes so that the caching
10627 	 * can be handled correctly.
10628 	 *
10629 	 * Don't need to update the open stream first, since this
10630 	 * mmap can't add any additional share access that isn't
10631 	 * already contained in the open stream (for the case where we
10632 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10633 	 * take into account os_mmap_read[write] counts).
10634 	 */
10635 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR(vp)))
10636 		return (EINTR);
10637 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10638 	nfs_rw_exit(&rp->r_rwlock);
10639 
10640 	if (vp->v_type == VREG) {
10641 		/*
10642 		 * We need to retrieve the open stream and update the counts.
10643 		 * If there is no open stream here, something is wrong.
10644 		 */
10645 		nfs4_open_stream_t	*osp = NULL;
10646 		nfs4_open_owner_t	*oop = NULL;
10647 
10648 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10649 		if (oop != NULL) {
10650 			/* returns with 'os_sync_lock' held */
10651 			osp = find_open_stream(oop, rp);
10652 			open_owner_rele(oop);
10653 		}
10654 		if (osp == NULL) {
10655 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10656 			    "nfs4_addmap: we should have an osp"
10657 			    "but we don't, so fail with EIO"));
10658 			error = EIO;
10659 			goto out;
10660 		}
10661 
10662 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10663 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10664 
10665 		/*
10666 		 * Update the map count in the open stream.
10667 		 * This is necessary in the case where we
10668 		 * open/mmap/close/, then the server reboots, and we
10669 		 * attempt to reopen.  If the mmap doesn't add share
10670 		 * access then we send an invalid reopen with
10671 		 * access = NONE.
10672 		 *
10673 		 * We need to specifically check each PROT_* so a mmap
10674 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10675 		 * read and write access.  A simple comparison of prot
10676 		 * to ~PROT_WRITE to determine read access is insufficient
10677 		 * since prot can be |= with PROT_USER, etc.
10678 		 */
10679 
10680 		/*
10681 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10682 		 */
10683 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10684 			osp->os_mmap_write += btopr(len);
10685 		if (maxprot & PROT_READ)
10686 			osp->os_mmap_read += btopr(len);
10687 		if (maxprot & PROT_EXEC)
10688 			osp->os_mmap_read += btopr(len);
10689 		/*
10690 		 * Ensure that os_mmap_read gets incremented, even if
10691 		 * maxprot were to look like PROT_NONE.
10692 		 */
10693 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10694 		    !(maxprot & PROT_EXEC))
10695 			osp->os_mmap_read += btopr(len);
10696 		osp->os_mapcnt += btopr(len);
10697 		mutex_exit(&osp->os_sync_lock);
10698 		open_stream_rele(osp, rp);
10699 	}
10700 
10701 out:
10702 	/*
10703 	 * If we got an error, then undo our
10704 	 * incrementing of 'r_mapcnt'.
10705 	 */
10706 
10707 	if (error) {
10708 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10709 		ASSERT(rp->r_mapcnt >= 0);
10710 	}
10711 	return (error);
10712 }
10713 
10714 /* ARGSUSED */
10715 static int
10716 nfs4_cmp(vnode_t *vp1, vnode_t *vp2, caller_context_t *ct)
10717 {
10718 
10719 	return (VTOR4(vp1) == VTOR4(vp2));
10720 }
10721 
10722 /* ARGSUSED */
10723 static int
10724 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10725     offset_t offset, struct flk_callback *flk_cbp, cred_t *cr,
10726     caller_context_t *ct)
10727 {
10728 	int rc;
10729 	u_offset_t start, end;
10730 	rnode4_t *rp;
10731 	int error = 0, intr = INTR4(vp);
10732 	nfs4_error_t e;
10733 
10734 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10735 		return (EIO);
10736 
10737 	/* check for valid cmd parameter */
10738 	if (cmd != F_GETLK && cmd != F_SETLK && cmd != F_SETLKW)
10739 		return (EINVAL);
10740 
10741 	/* Verify l_type. */
10742 	switch (bfp->l_type) {
10743 	case F_RDLCK:
10744 		if (cmd != F_GETLK && !(flag & FREAD))
10745 			return (EBADF);
10746 		break;
10747 	case F_WRLCK:
10748 		if (cmd != F_GETLK && !(flag & FWRITE))
10749 			return (EBADF);
10750 		break;
10751 	case F_UNLCK:
10752 		intr = 0;
10753 		break;
10754 
10755 	default:
10756 		return (EINVAL);
10757 	}
10758 
10759 	/* check the validity of the lock range */
10760 	if (rc = flk_convert_lock_data(vp, bfp, &start, &end, offset))
10761 		return (rc);
10762 	if (rc = flk_check_lock_data(start, end, MAXEND))
10763 		return (rc);
10764 
10765 	/*
10766 	 * If the filesystem is mounted using local locking, pass the
10767 	 * request off to the local locking code.
10768 	 */
10769 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10770 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10771 			/*
10772 			 * For complete safety, we should be holding
10773 			 * r_lkserlock.  However, we can't call
10774 			 * nfs4_safelock and then fs_frlock while
10775 			 * holding r_lkserlock, so just invoke
10776 			 * nfs4_safelock and expect that this will
10777 			 * catch enough of the cases.
10778 			 */
10779 			if (!nfs4_safelock(vp, bfp, cr))
10780 				return (EAGAIN);
10781 		}
10782 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
10783 	}
10784 
10785 	rp = VTOR4(vp);
10786 
10787 	/*
10788 	 * Check whether the given lock request can proceed, given the
10789 	 * current file mappings.
10790 	 */
10791 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr))
10792 		return (EINTR);
10793 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10794 		if (!nfs4_safelock(vp, bfp, cr)) {
10795 			rc = EAGAIN;
10796 			goto done;
10797 		}
10798 	}
10799 
10800 	/*
10801 	 * Flush the cache after waiting for async I/O to finish.  For new
10802 	 * locks, this is so that the process gets the latest bits from the
10803 	 * server.  For unlocks, this is so that other clients see the
10804 	 * latest bits once the file has been unlocked.  If currently dirty
10805 	 * pages can't be flushed, then don't allow a lock to be set.  But
10806 	 * allow unlocks to succeed, to avoid having orphan locks on the
10807 	 * server.
10808 	 */
10809 	if (cmd != F_GETLK) {
10810 		mutex_enter(&rp->r_statelock);
10811 		while (rp->r_count > 0) {
10812 			if (intr) {
10813 				klwp_t *lwp = ttolwp(curthread);
10814 
10815 				if (lwp != NULL)
10816 					lwp->lwp_nostop++;
10817 				if (cv_wait_sig(&rp->r_cv,
10818 				    &rp->r_statelock) == 0) {
10819 					if (lwp != NULL)
10820 						lwp->lwp_nostop--;
10821 					rc = EINTR;
10822 					break;
10823 				}
10824 				if (lwp != NULL)
10825 					lwp->lwp_nostop--;
10826 				} else
10827 					cv_wait(&rp->r_cv, &rp->r_statelock);
10828 		}
10829 		mutex_exit(&rp->r_statelock);
10830 		if (rc != 0)
10831 			goto done;
10832 		error = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr, ct);
10833 		if (error) {
10834 			if (error == ENOSPC || error == EDQUOT) {
10835 				mutex_enter(&rp->r_statelock);
10836 				if (!rp->r_error)
10837 					rp->r_error = error;
10838 				mutex_exit(&rp->r_statelock);
10839 			}
10840 			if (bfp->l_type != F_UNLCK) {
10841 				rc = ENOLCK;
10842 				goto done;
10843 			}
10844 		}
10845 	}
10846 
10847 	/*
10848 	 * Call the lock manager to do the real work of contacting
10849 	 * the server and obtaining the lock.
10850 	 */
10851 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, flag, offset,
10852 	    cr, &e, NULL, NULL);
10853 	rc = e.error;
10854 
10855 	if (rc == 0)
10856 		nfs4_lockcompletion(vp, cmd);
10857 
10858 done:
10859 	nfs_rw_exit(&rp->r_lkserlock);
10860 
10861 	return (rc);
10862 }
10863 
10864 /*
10865  * Free storage space associated with the specified vnode.  The portion
10866  * to be freed is specified by bfp->l_start and bfp->l_len (already
10867  * normalized to a "whence" of 0).
10868  *
10869  * This is an experimental facility whose continued existence is not
10870  * guaranteed.  Currently, we only support the special case
10871  * of l_len == 0, meaning free to end of file.
10872  */
10873 /* ARGSUSED */
10874 static int
10875 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10876     offset_t offset, cred_t *cr, caller_context_t *ct)
10877 {
10878 	int error;
10879 
10880 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10881 		return (EIO);
10882 	ASSERT(vp->v_type == VREG);
10883 	if (cmd != F_FREESP)
10884 		return (EINVAL);
10885 
10886 	error = convoff(vp, bfp, 0, offset);
10887 	if (!error) {
10888 		ASSERT(bfp->l_start >= 0);
10889 		if (bfp->l_len == 0) {
10890 			struct vattr va;
10891 
10892 			va.va_mask = AT_SIZE;
10893 			va.va_size = bfp->l_start;
10894 			error = nfs4setattr(vp, &va, 0, cr, NULL);
10895 		} else
10896 			error = EINVAL;
10897 	}
10898 
10899 	return (error);
10900 }
10901 
10902 /* ARGSUSED */
10903 int
10904 nfs4_realvp(vnode_t *vp, vnode_t **vpp, caller_context_t *ct)
10905 {
10906 	rnode4_t *rp;
10907 	rp = VTOR4(vp);
10908 
10909 	if (vp->v_type == VREG && IS_SHADOW(vp, rp)) {
10910 		vp = RTOV4(rp);
10911 	}
10912 	*vpp = vp;
10913 	return (0);
10914 }
10915 
10916 /*
10917  * Setup and add an address space callback to do the work of the delmap call.
10918  * The callback will (and must be) deleted in the actual callback function.
10919  *
10920  * This is done in order to take care of the problem that we have with holding
10921  * the address space's a_lock for a long period of time (e.g. if the NFS server
10922  * is down).  Callbacks will be executed in the address space code while the
10923  * a_lock is not held.  Holding the address space's a_lock causes things such
10924  * as ps and fork to hang because they are trying to acquire this lock as well.
10925  */
10926 /* ARGSUSED */
10927 static int
10928 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10929     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
10930     caller_context_t *ct)
10931 {
10932 	int			caller_found;
10933 	int			error;
10934 	rnode4_t		*rp;
10935 	nfs4_delmap_args_t	*dmapp;
10936 	nfs4_delmapcall_t	*delmap_call;
10937 
10938 	if (vp->v_flag & VNOMAP)
10939 		return (ENOSYS);
10940 
10941 	/*
10942 	 * A process may not change zones if it has NFS pages mmap'ed
10943 	 * in, so we can't legitimately get here from the wrong zone.
10944 	 */
10945 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10946 
10947 	rp = VTOR4(vp);
10948 
10949 	/*
10950 	 * The way that the address space of this process deletes its mapping
10951 	 * of this file is via the following call chains:
10952 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10953 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10954 	 *
10955 	 * With the use of address space callbacks we are allowed to drop the
10956 	 * address space lock, a_lock, while executing the NFS operations that
10957 	 * need to go over the wire.  Returning EAGAIN to the caller of this
10958 	 * function is what drives the execution of the callback that we add
10959 	 * below.  The callback will be executed by the address space code
10960 	 * after dropping the a_lock.  When the callback is finished, since
10961 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
10962 	 * is called again on the same segment to finish the rest of the work
10963 	 * that needs to happen during unmapping.
10964 	 *
10965 	 * This action of calling back into the segment driver causes
10966 	 * nfs4_delmap() to get called again, but since the callback was
10967 	 * already executed at this point, it already did the work and there
10968 	 * is nothing left for us to do.
10969 	 *
10970 	 * To Summarize:
10971 	 * - The first time nfs4_delmap is called by the current thread is when
10972 	 * we add the caller associated with this delmap to the delmap caller
10973 	 * list, add the callback, and return EAGAIN.
10974 	 * - The second time in this call chain when nfs4_delmap is called we
10975 	 * will find this caller in the delmap caller list and realize there
10976 	 * is no more work to do thus removing this caller from the list and
10977 	 * returning the error that was set in the callback execution.
10978 	 */
10979 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
10980 	if (caller_found) {
10981 		/*
10982 		 * 'error' is from the actual delmap operations.  To avoid
10983 		 * hangs, we need to handle the return of EAGAIN differently
10984 		 * since this is what drives the callback execution.
10985 		 * In this case, we don't want to return EAGAIN and do the
10986 		 * callback execution because there are none to execute.
10987 		 */
10988 		if (error == EAGAIN)
10989 			return (0);
10990 		else
10991 			return (error);
10992 	}
10993 
10994 	/* current caller was not in the list */
10995 	delmap_call = nfs4_init_delmapcall();
10996 
10997 	mutex_enter(&rp->r_statelock);
10998 	list_insert_tail(&rp->r_indelmap, delmap_call);
10999 	mutex_exit(&rp->r_statelock);
11000 
11001 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
11002 
11003 	dmapp->vp = vp;
11004 	dmapp->off = off;
11005 	dmapp->addr = addr;
11006 	dmapp->len = len;
11007 	dmapp->prot = prot;
11008 	dmapp->maxprot = maxprot;
11009 	dmapp->flags = flags;
11010 	dmapp->cr = cr;
11011 	dmapp->caller = delmap_call;
11012 
11013 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
11014 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
11015 
11016 	return (error ? error : EAGAIN);
11017 }
11018 
11019 static nfs4_delmapcall_t *
11020 nfs4_init_delmapcall()
11021 {
11022 	nfs4_delmapcall_t	*delmap_call;
11023 
11024 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
11025 	delmap_call->call_id = curthread;
11026 	delmap_call->error = 0;
11027 
11028 	return (delmap_call);
11029 }
11030 
11031 static void
11032 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11033 {
11034 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11035 }
11036 
11037 /*
11038  * Searches for the current delmap caller (based on curthread) in the list of
11039  * callers.  If it is found, we remove it and free the delmap caller.
11040  * Returns:
11041  *      0 if the caller wasn't found
11042  *      1 if the caller was found, removed and freed.  *errp will be set
11043  *	to what the result of the delmap was.
11044  */
11045 static int
11046 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11047 {
11048 	nfs4_delmapcall_t	*delmap_call;
11049 
11050 	/*
11051 	 * If the list doesn't exist yet, we create it and return
11052 	 * that the caller wasn't found.  No list = no callers.
11053 	 */
11054 	mutex_enter(&rp->r_statelock);
11055 	if (!(rp->r_flags & R4DELMAPLIST)) {
11056 		/* The list does not exist */
11057 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11058 		    offsetof(nfs4_delmapcall_t, call_node));
11059 		rp->r_flags |= R4DELMAPLIST;
11060 		mutex_exit(&rp->r_statelock);
11061 		return (0);
11062 	} else {
11063 		/* The list exists so search it */
11064 		for (delmap_call = list_head(&rp->r_indelmap);
11065 		    delmap_call != NULL;
11066 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11067 			if (delmap_call->call_id == curthread) {
11068 				/* current caller is in the list */
11069 				*errp = delmap_call->error;
11070 				list_remove(&rp->r_indelmap, delmap_call);
11071 				mutex_exit(&rp->r_statelock);
11072 				nfs4_free_delmapcall(delmap_call);
11073 				return (1);
11074 			}
11075 		}
11076 	}
11077 	mutex_exit(&rp->r_statelock);
11078 	return (0);
11079 }
11080 
11081 /*
11082  * Remove some pages from an mmap'd vnode.  Just update the
11083  * count of pages.  If doing close-to-open, then flush and
11084  * commit all of the pages associated with this file.
11085  * Otherwise, start an asynchronous page flush to write out
11086  * any dirty pages.  This will also associate a credential
11087  * with the rnode which can be used to write the pages.
11088  */
11089 /* ARGSUSED */
11090 static void
11091 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11092 {
11093 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11094 	rnode4_t		*rp;
11095 	mntinfo4_t		*mi;
11096 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11097 
11098 	rp = VTOR4(dmapp->vp);
11099 	mi = VTOMI4(dmapp->vp);
11100 
11101 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11102 	ASSERT(rp->r_mapcnt >= 0);
11103 
11104 	/*
11105 	 * Initiate a page flush and potential commit if there are
11106 	 * pages, the file system was not mounted readonly, the segment
11107 	 * was mapped shared, and the pages themselves were writeable.
11108 	 */
11109 	if (nfs4_has_pages(dmapp->vp) &&
11110 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11111 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11112 		mutex_enter(&rp->r_statelock);
11113 		rp->r_flags |= R4DIRTY;
11114 		mutex_exit(&rp->r_statelock);
11115 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11116 		    dmapp->len, dmapp->cr);
11117 		if (!e.error) {
11118 			mutex_enter(&rp->r_statelock);
11119 			e.error = rp->r_error;
11120 			rp->r_error = 0;
11121 			mutex_exit(&rp->r_statelock);
11122 		}
11123 	} else
11124 		e.error = 0;
11125 
11126 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11127 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11128 		    B_INVAL, dmapp->cr, NULL);
11129 
11130 	if (e.error) {
11131 		e.stat = puterrno4(e.error);
11132 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11133 		    OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11134 		dmapp->caller->error = e.error;
11135 	}
11136 
11137 	/* Check to see if we need to close the file */
11138 
11139 	if (dmapp->vp->v_type == VREG) {
11140 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11141 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11142 
11143 		if (e.error != 0 || e.stat != NFS4_OK) {
11144 			/*
11145 			 * Since it is possible that e.error == 0 and
11146 			 * e.stat != NFS4_OK (and vice versa),
11147 			 * we do the proper checking in order to get both
11148 			 * e.error and e.stat reporting the correct info.
11149 			 */
11150 			if (e.stat == NFS4_OK)
11151 				e.stat = puterrno4(e.error);
11152 			if (e.error == 0)
11153 				e.error = geterrno4(e.stat);
11154 
11155 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11156 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11157 			dmapp->caller->error = e.error;
11158 		}
11159 	}
11160 
11161 	(void) as_delete_callback(as, arg);
11162 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11163 }
11164 
11165 
11166 static uint_t
11167 fattr4_maxfilesize_to_bits(uint64_t ll)
11168 {
11169 	uint_t l = 1;
11170 
11171 	if (ll == 0) {
11172 		return (0);
11173 	}
11174 
11175 	if (ll & 0xffffffff00000000) {
11176 		l += 32; ll >>= 32;
11177 	}
11178 	if (ll & 0xffff0000) {
11179 		l += 16; ll >>= 16;
11180 	}
11181 	if (ll & 0xff00) {
11182 		l += 8; ll >>= 8;
11183 	}
11184 	if (ll & 0xf0) {
11185 		l += 4; ll >>= 4;
11186 	}
11187 	if (ll & 0xc) {
11188 		l += 2; ll >>= 2;
11189 	}
11190 	if (ll & 0x2) {
11191 		l += 1;
11192 	}
11193 	return (l);
11194 }
11195 
11196 static int
11197 nfs4_have_xattrs(vnode_t *vp, ulong_t *valp, cred_t *cr)
11198 {
11199 	vnode_t *avp = NULL;
11200 	int error;
11201 
11202 	if ((error = nfs4lookup_xattr(vp, "", &avp,
11203 	    LOOKUP_XATTR, cr)) == 0)
11204 		error = do_xattr_exists_check(avp, valp, cr);
11205 	if (avp)
11206 		VN_RELE(avp);
11207 
11208 	return (error);
11209 }
11210 
11211 /* ARGSUSED */
11212 int
11213 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
11214 	caller_context_t *ct)
11215 {
11216 	int error;
11217 	hrtime_t t;
11218 	rnode4_t *rp;
11219 	nfs4_ga_res_t gar;
11220 	nfs4_ga_ext_res_t ger;
11221 
11222 	gar.n4g_ext_res = &ger;
11223 
11224 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11225 		return (EIO);
11226 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11227 		*valp = MAXPATHLEN;
11228 		return (0);
11229 	}
11230 	if (cmd == _PC_ACL_ENABLED) {
11231 		*valp = _ACL_ACE_ENABLED;
11232 		return (0);
11233 	}
11234 
11235 	rp = VTOR4(vp);
11236 	if (cmd == _PC_XATTR_EXISTS) {
11237 		/*
11238 		 * The existence of the xattr directory is not sufficient
11239 		 * for determining whether generic user attributes exists.
11240 		 * The attribute directory could only be a transient directory
11241 		 * used for Solaris sysattr support.  Do a small readdir
11242 		 * to verify if the only entries are sysattrs or not.
11243 		 *
11244 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11245 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11246 		 * and we don't have any way to update the "base" object's
11247 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11248 		 * could help out.
11249 		 */
11250 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11251 		    rp->r_xattr_dir == NULL) {
11252 			return (nfs4_have_xattrs(vp, valp, cr));
11253 		}
11254 	} else {  /* OLD CODE */
11255 		if (ATTRCACHE4_VALID(vp)) {
11256 			mutex_enter(&rp->r_statelock);
11257 			if (rp->r_pathconf.pc4_cache_valid) {
11258 				error = 0;
11259 				switch (cmd) {
11260 				case _PC_FILESIZEBITS:
11261 					*valp =
11262 					    rp->r_pathconf.pc4_filesizebits;
11263 					break;
11264 				case _PC_LINK_MAX:
11265 					*valp =
11266 					    rp->r_pathconf.pc4_link_max;
11267 					break;
11268 				case _PC_NAME_MAX:
11269 					*valp =
11270 					    rp->r_pathconf.pc4_name_max;
11271 					break;
11272 				case _PC_CHOWN_RESTRICTED:
11273 					*valp =
11274 					    rp->r_pathconf.pc4_chown_restricted;
11275 					break;
11276 				case _PC_NO_TRUNC:
11277 					*valp =
11278 					    rp->r_pathconf.pc4_no_trunc;
11279 					break;
11280 				default:
11281 					error = EINVAL;
11282 					break;
11283 				}
11284 				mutex_exit(&rp->r_statelock);
11285 #ifdef DEBUG
11286 				nfs4_pathconf_cache_hits++;
11287 #endif
11288 				return (error);
11289 			}
11290 			mutex_exit(&rp->r_statelock);
11291 		}
11292 	}
11293 #ifdef DEBUG
11294 	nfs4_pathconf_cache_misses++;
11295 #endif
11296 
11297 	t = gethrtime();
11298 
11299 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11300 
11301 	if (error) {
11302 		mutex_enter(&rp->r_statelock);
11303 		rp->r_pathconf.pc4_cache_valid = FALSE;
11304 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11305 		mutex_exit(&rp->r_statelock);
11306 		return (error);
11307 	}
11308 
11309 	/* interpret the max filesize */
11310 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11311 	    fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11312 
11313 	/* Store the attributes we just received */
11314 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11315 
11316 	switch (cmd) {
11317 	case _PC_FILESIZEBITS:
11318 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11319 		break;
11320 	case _PC_LINK_MAX:
11321 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11322 		break;
11323 	case _PC_NAME_MAX:
11324 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11325 		break;
11326 	case _PC_CHOWN_RESTRICTED:
11327 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11328 		break;
11329 	case _PC_NO_TRUNC:
11330 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11331 		break;
11332 	case _PC_XATTR_EXISTS:
11333 		if (gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists) {
11334 			if (error = nfs4_have_xattrs(vp, valp, cr))
11335 				return (error);
11336 		}
11337 		break;
11338 	default:
11339 		return (EINVAL);
11340 	}
11341 
11342 	return (0);
11343 }
11344 
11345 /*
11346  * Called by async thread to do synchronous pageio. Do the i/o, wait
11347  * for it to complete, and cleanup the page list when done.
11348  */
11349 static int
11350 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11351     int flags, cred_t *cr)
11352 {
11353 	int error;
11354 
11355 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11356 
11357 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11358 	if (flags & B_READ)
11359 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11360 	else
11361 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11362 	return (error);
11363 }
11364 
11365 /* ARGSUSED */
11366 static int
11367 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11368 	int flags, cred_t *cr, caller_context_t *ct)
11369 {
11370 	int error;
11371 	rnode4_t *rp;
11372 
11373 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11374 		return (EIO);
11375 
11376 	if (pp == NULL)
11377 		return (EINVAL);
11378 
11379 	rp = VTOR4(vp);
11380 	mutex_enter(&rp->r_statelock);
11381 	rp->r_count++;
11382 	mutex_exit(&rp->r_statelock);
11383 
11384 	if (flags & B_ASYNC) {
11385 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11386 		    nfs4_sync_pageio);
11387 	} else
11388 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11389 	mutex_enter(&rp->r_statelock);
11390 	rp->r_count--;
11391 	cv_broadcast(&rp->r_cv);
11392 	mutex_exit(&rp->r_statelock);
11393 	return (error);
11394 }
11395 
11396 /* ARGSUSED */
11397 static void
11398 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr,
11399 	caller_context_t *ct)
11400 {
11401 	int error;
11402 	rnode4_t *rp;
11403 	page_t *plist;
11404 	page_t *pptr;
11405 	offset3 offset;
11406 	count3 len;
11407 	k_sigset_t smask;
11408 
11409 	/*
11410 	 * We should get called with fl equal to either B_FREE or
11411 	 * B_INVAL.  Any other value is illegal.
11412 	 *
11413 	 * The page that we are either supposed to free or destroy
11414 	 * should be exclusive locked and its io lock should not
11415 	 * be held.
11416 	 */
11417 	ASSERT(fl == B_FREE || fl == B_INVAL);
11418 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11419 
11420 	rp = VTOR4(vp);
11421 
11422 	/*
11423 	 * If the page doesn't need to be committed or we shouldn't
11424 	 * even bother attempting to commit it, then just make sure
11425 	 * that the p_fsdata byte is clear and then either free or
11426 	 * destroy the page as appropriate.
11427 	 */
11428 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11429 		pp->p_fsdata = C_NOCOMMIT;
11430 		if (fl == B_FREE)
11431 			page_free(pp, dn);
11432 		else
11433 			page_destroy(pp, dn);
11434 		return;
11435 	}
11436 
11437 	/*
11438 	 * If there is a page invalidation operation going on, then
11439 	 * if this is one of the pages being destroyed, then just
11440 	 * clear the p_fsdata byte and then either free or destroy
11441 	 * the page as appropriate.
11442 	 */
11443 	mutex_enter(&rp->r_statelock);
11444 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11445 		mutex_exit(&rp->r_statelock);
11446 		pp->p_fsdata = C_NOCOMMIT;
11447 		if (fl == B_FREE)
11448 			page_free(pp, dn);
11449 		else
11450 			page_destroy(pp, dn);
11451 		return;
11452 	}
11453 
11454 	/*
11455 	 * If we are freeing this page and someone else is already
11456 	 * waiting to do a commit, then just unlock the page and
11457 	 * return.  That other thread will take care of commiting
11458 	 * this page.  The page can be freed sometime after the
11459 	 * commit has finished.  Otherwise, if the page is marked
11460 	 * as delay commit, then we may be getting called from
11461 	 * pvn_write_done, one page at a time.   This could result
11462 	 * in one commit per page, so we end up doing lots of small
11463 	 * commits instead of fewer larger commits.  This is bad,
11464 	 * we want do as few commits as possible.
11465 	 */
11466 	if (fl == B_FREE) {
11467 		if (rp->r_flags & R4COMMITWAIT) {
11468 			page_unlock(pp);
11469 			mutex_exit(&rp->r_statelock);
11470 			return;
11471 		}
11472 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11473 			pp->p_fsdata = C_COMMIT;
11474 			page_unlock(pp);
11475 			mutex_exit(&rp->r_statelock);
11476 			return;
11477 		}
11478 	}
11479 
11480 	/*
11481 	 * Check to see if there is a signal which would prevent an
11482 	 * attempt to commit the pages from being successful.  If so,
11483 	 * then don't bother with all of the work to gather pages and
11484 	 * generate the unsuccessful RPC.  Just return from here and
11485 	 * let the page be committed at some later time.
11486 	 */
11487 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11488 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11489 		sigunintr(&smask);
11490 		page_unlock(pp);
11491 		mutex_exit(&rp->r_statelock);
11492 		return;
11493 	}
11494 	sigunintr(&smask);
11495 
11496 	/*
11497 	 * We are starting to need to commit pages, so let's try
11498 	 * to commit as many as possible at once to reduce the
11499 	 * overhead.
11500 	 *
11501 	 * Set the `commit inprogress' state bit.  We must
11502 	 * first wait until any current one finishes.  Then
11503 	 * we initialize the c_pages list with this page.
11504 	 */
11505 	while (rp->r_flags & R4COMMIT) {
11506 		rp->r_flags |= R4COMMITWAIT;
11507 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11508 		rp->r_flags &= ~R4COMMITWAIT;
11509 	}
11510 	rp->r_flags |= R4COMMIT;
11511 	mutex_exit(&rp->r_statelock);
11512 	ASSERT(rp->r_commit.c_pages == NULL);
11513 	rp->r_commit.c_pages = pp;
11514 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11515 	rp->r_commit.c_commlen = PAGESIZE;
11516 
11517 	/*
11518 	 * Gather together all other pages which can be committed.
11519 	 * They will all be chained off r_commit.c_pages.
11520 	 */
11521 	nfs4_get_commit(vp);
11522 
11523 	/*
11524 	 * Clear the `commit inprogress' status and disconnect
11525 	 * the list of pages to be committed from the rnode.
11526 	 * At this same time, we also save the starting offset
11527 	 * and length of data to be committed on the server.
11528 	 */
11529 	plist = rp->r_commit.c_pages;
11530 	rp->r_commit.c_pages = NULL;
11531 	offset = rp->r_commit.c_commbase;
11532 	len = rp->r_commit.c_commlen;
11533 	mutex_enter(&rp->r_statelock);
11534 	rp->r_flags &= ~R4COMMIT;
11535 	cv_broadcast(&rp->r_commit.c_cv);
11536 	mutex_exit(&rp->r_statelock);
11537 
11538 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11539 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11540 		nfs4_async_commit(vp, plist, offset, len,
11541 		    cr, do_nfs4_async_commit);
11542 		return;
11543 	}
11544 
11545 	/*
11546 	 * Actually generate the COMMIT op over the wire operation.
11547 	 */
11548 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11549 
11550 	/*
11551 	 * If we got an error during the commit, just unlock all
11552 	 * of the pages.  The pages will get retransmitted to the
11553 	 * server during a putpage operation.
11554 	 */
11555 	if (error) {
11556 		while (plist != NULL) {
11557 			pptr = plist;
11558 			page_sub(&plist, pptr);
11559 			page_unlock(pptr);
11560 		}
11561 		return;
11562 	}
11563 
11564 	/*
11565 	 * We've tried as hard as we can to commit the data to stable
11566 	 * storage on the server.  We just unlock the rest of the pages
11567 	 * and clear the commit required state.  They will be put
11568 	 * onto the tail of the cachelist if they are nolonger
11569 	 * mapped.
11570 	 */
11571 	while (plist != pp) {
11572 		pptr = plist;
11573 		page_sub(&plist, pptr);
11574 		pptr->p_fsdata = C_NOCOMMIT;
11575 		page_unlock(pptr);
11576 	}
11577 
11578 	/*
11579 	 * It is possible that nfs4_commit didn't return error but
11580 	 * some other thread has modified the page we are going
11581 	 * to free/destroy.
11582 	 *    In this case we need to rewrite the page. Do an explicit check
11583 	 * before attempting to free/destroy the page. If modified, needs to
11584 	 * be rewritten so unlock the page and return.
11585 	 */
11586 	if (hat_ismod(pp)) {
11587 		pp->p_fsdata = C_NOCOMMIT;
11588 		page_unlock(pp);
11589 		return;
11590 	}
11591 
11592 	/*
11593 	 * Now, as appropriate, either free or destroy the page
11594 	 * that we were called with.
11595 	 */
11596 	pp->p_fsdata = C_NOCOMMIT;
11597 	if (fl == B_FREE)
11598 		page_free(pp, dn);
11599 	else
11600 		page_destroy(pp, dn);
11601 }
11602 
11603 /*
11604  * Commit requires that the current fh be the file written to.
11605  * The compound op structure is:
11606  *      PUTFH(file), COMMIT
11607  */
11608 static int
11609 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11610 {
11611 	COMPOUND4args_clnt args;
11612 	COMPOUND4res_clnt res;
11613 	COMMIT4res *cm_res;
11614 	nfs_argop4 argop[2];
11615 	nfs_resop4 *resop;
11616 	int doqueue;
11617 	mntinfo4_t *mi;
11618 	rnode4_t *rp;
11619 	cred_t *cred_otw = NULL;
11620 	bool_t needrecov = FALSE;
11621 	nfs4_recov_state_t recov_state;
11622 	nfs4_open_stream_t *osp = NULL;
11623 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11624 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11625 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11626 
11627 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11628 
11629 	rp = VTOR4(vp);
11630 
11631 	mi = VTOMI4(vp);
11632 	recov_state.rs_flags = 0;
11633 	recov_state.rs_num_retry_despite_err = 0;
11634 get_commit_cred:
11635 	/*
11636 	 * Releases the osp, if a valid open stream is provided.
11637 	 * Puts a hold on the cred_otw and the new osp (if found).
11638 	 */
11639 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11640 	    &first_time, &last_time);
11641 	args.ctag = TAG_COMMIT;
11642 recov_retry:
11643 	/*
11644 	 * Commit ops: putfh file; commit
11645 	 */
11646 	args.array_len = 2;
11647 	args.array = argop;
11648 
11649 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11650 	    &recov_state, NULL);
11651 	if (e.error) {
11652 		crfree(cred_otw);
11653 		if (osp != NULL)
11654 			open_stream_rele(osp, rp);
11655 		return (e.error);
11656 	}
11657 
11658 	/* putfh directory */
11659 	argop[0].argop = OP_CPUTFH;
11660 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11661 
11662 	/* commit */
11663 	argop[1].argop = OP_COMMIT;
11664 	argop[1].nfs_argop4_u.opcommit.offset = offset;
11665 	argop[1].nfs_argop4_u.opcommit.count = count;
11666 
11667 	doqueue = 1;
11668 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
11669 
11670 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
11671 	if (!needrecov && e.error) {
11672 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
11673 		    needrecov);
11674 		crfree(cred_otw);
11675 		if (e.error == EACCES && last_time == FALSE)
11676 			goto get_commit_cred;
11677 		if (osp != NULL)
11678 			open_stream_rele(osp, rp);
11679 		return (e.error);
11680 	}
11681 
11682 	if (needrecov) {
11683 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
11684 		    NULL, OP_COMMIT, NULL) == FALSE) {
11685 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11686 			    &recov_state, needrecov);
11687 			if (!e.error)
11688 				(void) xdr_free(xdr_COMPOUND4res_clnt,
11689 				    (caddr_t)&res);
11690 			goto recov_retry;
11691 		}
11692 		if (e.error) {
11693 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11694 			    &recov_state, needrecov);
11695 			crfree(cred_otw);
11696 			if (osp != NULL)
11697 				open_stream_rele(osp, rp);
11698 			return (e.error);
11699 		}
11700 		/* fall through for res.status case */
11701 	}
11702 
11703 	if (res.status) {
11704 		e.error = geterrno4(res.status);
11705 		if (e.error == EACCES && last_time == FALSE) {
11706 			crfree(cred_otw);
11707 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11708 			    &recov_state, needrecov);
11709 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11710 			goto get_commit_cred;
11711 		}
11712 		/*
11713 		 * Can't do a nfs4_purge_stale_fh here because this
11714 		 * can cause a deadlock.  nfs4_commit can
11715 		 * be called from nfs4_dispose which can be called
11716 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
11717 		 * can call back to pvn_vplist_dirty.
11718 		 */
11719 		if (e.error == ESTALE) {
11720 			mutex_enter(&rp->r_statelock);
11721 			rp->r_flags |= R4STALE;
11722 			if (!rp->r_error)
11723 				rp->r_error = e.error;
11724 			mutex_exit(&rp->r_statelock);
11725 			PURGE_ATTRCACHE4(vp);
11726 		} else {
11727 			mutex_enter(&rp->r_statelock);
11728 			if (!rp->r_error)
11729 				rp->r_error = e.error;
11730 			mutex_exit(&rp->r_statelock);
11731 		}
11732 	} else {
11733 		ASSERT(rp->r_flags & R4HAVEVERF);
11734 		resop = &res.array[1];	/* commit res */
11735 		cm_res = &resop->nfs_resop4_u.opcommit;
11736 		mutex_enter(&rp->r_statelock);
11737 		if (cm_res->writeverf == rp->r_writeverf) {
11738 			mutex_exit(&rp->r_statelock);
11739 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11740 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11741 			    &recov_state, needrecov);
11742 			crfree(cred_otw);
11743 			if (osp != NULL)
11744 				open_stream_rele(osp, rp);
11745 			return (0);
11746 		}
11747 		nfs4_set_mod(vp);
11748 		rp->r_writeverf = cm_res->writeverf;
11749 		mutex_exit(&rp->r_statelock);
11750 		e.error = NFS_VERF_MISMATCH;
11751 	}
11752 
11753 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11754 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
11755 	crfree(cred_otw);
11756 	if (osp != NULL)
11757 		open_stream_rele(osp, rp);
11758 
11759 	return (e.error);
11760 }
11761 
11762 static void
11763 nfs4_set_mod(vnode_t *vp)
11764 {
11765 	page_t *pp;
11766 	kmutex_t *vphm;
11767 	rnode4_t *rp;
11768 
11769 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11770 
11771 	/* make sure we're looking at the master vnode, not a shadow */
11772 
11773 	rp = VTOR4(vp);
11774 	if (IS_SHADOW(vp, rp))
11775 		vp = RTOV4(rp);
11776 
11777 	vphm = page_vnode_mutex(vp);
11778 	mutex_enter(vphm);
11779 	/*
11780 	 * If there are no pages associated with this vnode, then
11781 	 * just return.
11782 	 */
11783 	if ((pp = vp->v_pages) == NULL) {
11784 		mutex_exit(vphm);
11785 		return;
11786 	}
11787 
11788 	do {
11789 		if (pp->p_fsdata != C_NOCOMMIT) {
11790 			hat_setmod(pp);
11791 			pp->p_fsdata = C_NOCOMMIT;
11792 		}
11793 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11794 	mutex_exit(vphm);
11795 }
11796 
11797 /*
11798  * This function is used to gather a page list of the pages which
11799  * can be committed on the server.
11800  *
11801  * The calling thread must have set R4COMMIT.  This bit is used to
11802  * serialize access to the commit structure in the rnode.  As long
11803  * as the thread has set R4COMMIT, then it can manipulate the commit
11804  * structure without requiring any other locks.
11805  *
11806  * When this function is called from nfs4_dispose() the page passed
11807  * into nfs4_dispose() will be SE_EXCL locked, and so this function
11808  * will skip it. This is not a problem since we initially add the
11809  * page to the r_commit page list.
11810  *
11811  */
11812 static void
11813 nfs4_get_commit(vnode_t *vp)
11814 {
11815 	rnode4_t *rp;
11816 	page_t *pp;
11817 	kmutex_t *vphm;
11818 
11819 	rp = VTOR4(vp);
11820 
11821 	ASSERT(rp->r_flags & R4COMMIT);
11822 
11823 	/* make sure we're looking at the master vnode, not a shadow */
11824 
11825 	if (IS_SHADOW(vp, rp))
11826 		vp = RTOV4(rp);
11827 
11828 	vphm = page_vnode_mutex(vp);
11829 	mutex_enter(vphm);
11830 
11831 	/*
11832 	 * If there are no pages associated with this vnode, then
11833 	 * just return.
11834 	 */
11835 	if ((pp = vp->v_pages) == NULL) {
11836 		mutex_exit(vphm);
11837 		return;
11838 	}
11839 
11840 	/*
11841 	 * Step through all of the pages associated with this vnode
11842 	 * looking for pages which need to be committed.
11843 	 */
11844 	do {
11845 		/*
11846 		 * First short-cut everything (without the page_lock)
11847 		 * and see if this page does not need to be committed
11848 		 * or is modified if so then we'll just skip it.
11849 		 */
11850 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
11851 			continue;
11852 
11853 		/*
11854 		 * Attempt to lock the page.  If we can't, then
11855 		 * someone else is messing with it or we have been
11856 		 * called from nfs4_dispose and this is the page that
11857 		 * nfs4_dispose was called with.. anyway just skip it.
11858 		 */
11859 		if (!page_trylock(pp, SE_EXCL))
11860 			continue;
11861 
11862 		/*
11863 		 * Lets check again now that we have the page lock.
11864 		 */
11865 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11866 			page_unlock(pp);
11867 			continue;
11868 		}
11869 
11870 		/* this had better not be a free page */
11871 		ASSERT(PP_ISFREE(pp) == 0);
11872 
11873 		/*
11874 		 * The page needs to be committed and we locked it.
11875 		 * Update the base and length parameters and add it
11876 		 * to r_pages.
11877 		 */
11878 		if (rp->r_commit.c_pages == NULL) {
11879 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11880 			rp->r_commit.c_commlen = PAGESIZE;
11881 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
11882 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
11883 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
11884 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11885 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
11886 		    <= pp->p_offset) {
11887 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11888 			    rp->r_commit.c_commbase + PAGESIZE;
11889 		}
11890 		page_add(&rp->r_commit.c_pages, pp);
11891 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11892 
11893 	mutex_exit(vphm);
11894 }
11895 
11896 /*
11897  * This routine is used to gather together a page list of the pages
11898  * which are to be committed on the server.  This routine must not
11899  * be called if the calling thread holds any locked pages.
11900  *
11901  * The calling thread must have set R4COMMIT.  This bit is used to
11902  * serialize access to the commit structure in the rnode.  As long
11903  * as the thread has set R4COMMIT, then it can manipulate the commit
11904  * structure without requiring any other locks.
11905  */
11906 static void
11907 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
11908 {
11909 
11910 	rnode4_t *rp;
11911 	page_t *pp;
11912 	u_offset_t end;
11913 	u_offset_t off;
11914 	ASSERT(len != 0);
11915 	rp = VTOR4(vp);
11916 	ASSERT(rp->r_flags & R4COMMIT);
11917 
11918 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11919 
11920 	/* make sure we're looking at the master vnode, not a shadow */
11921 
11922 	if (IS_SHADOW(vp, rp))
11923 		vp = RTOV4(rp);
11924 
11925 	/*
11926 	 * If there are no pages associated with this vnode, then
11927 	 * just return.
11928 	 */
11929 	if ((pp = vp->v_pages) == NULL)
11930 		return;
11931 	/*
11932 	 * Calculate the ending offset.
11933 	 */
11934 	end = soff + len;
11935 	for (off = soff; off < end; off += PAGESIZE) {
11936 		/*
11937 		 * Lookup each page by vp, offset.
11938 		 */
11939 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
11940 			continue;
11941 		/*
11942 		 * If this page does not need to be committed or is
11943 		 * modified, then just skip it.
11944 		 */
11945 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11946 			page_unlock(pp);
11947 			continue;
11948 		}
11949 
11950 		ASSERT(PP_ISFREE(pp) == 0);
11951 		/*
11952 		 * The page needs to be committed and we locked it.
11953 		 * Update the base and length parameters and add it
11954 		 * to r_pages.
11955 		 */
11956 		if (rp->r_commit.c_pages == NULL) {
11957 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11958 			rp->r_commit.c_commlen = PAGESIZE;
11959 		} else {
11960 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11961 			    rp->r_commit.c_commbase + PAGESIZE;
11962 		}
11963 		page_add(&rp->r_commit.c_pages, pp);
11964 	}
11965 }
11966 
11967 /*
11968  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
11969  * Flushes and commits data to the server.
11970  */
11971 static int
11972 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
11973 {
11974 	int error;
11975 	verifier4 write_verf;
11976 	rnode4_t *rp = VTOR4(vp);
11977 
11978 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11979 
11980 	/*
11981 	 * Flush the data portion of the file and then commit any
11982 	 * portions which need to be committed.  This may need to
11983 	 * be done twice if the server has changed state since
11984 	 * data was last written.  The data will need to be
11985 	 * rewritten to the server and then a new commit done.
11986 	 *
11987 	 * In fact, this may need to be done several times if the
11988 	 * server is having problems and crashing while we are
11989 	 * attempting to do this.
11990 	 */
11991 
11992 top:
11993 	/*
11994 	 * Do a flush based on the poff and plen arguments.  This
11995 	 * will synchronously write out any modified pages in the
11996 	 * range specified by (poff, plen). This starts all of the
11997 	 * i/o operations which will be waited for in the next
11998 	 * call to nfs4_putpage
11999 	 */
12000 
12001 	mutex_enter(&rp->r_statelock);
12002 	write_verf = rp->r_writeverf;
12003 	mutex_exit(&rp->r_statelock);
12004 
12005 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr, NULL);
12006 	if (error == EAGAIN)
12007 		error = 0;
12008 
12009 	/*
12010 	 * Do a flush based on the poff and plen arguments.  This
12011 	 * will synchronously write out any modified pages in the
12012 	 * range specified by (poff, plen) and wait until all of
12013 	 * the asynchronous i/o's in that range are done as well.
12014 	 */
12015 	if (!error)
12016 		error = nfs4_putpage(vp, poff, plen, 0, cr, NULL);
12017 
12018 	if (error)
12019 		return (error);
12020 
12021 	mutex_enter(&rp->r_statelock);
12022 	if (rp->r_writeverf != write_verf) {
12023 		mutex_exit(&rp->r_statelock);
12024 		goto top;
12025 	}
12026 	mutex_exit(&rp->r_statelock);
12027 
12028 	/*
12029 	 * Now commit any pages which might need to be committed.
12030 	 * If the error, NFS_VERF_MISMATCH, is returned, then
12031 	 * start over with the flush operation.
12032 	 */
12033 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
12034 
12035 	if (error == NFS_VERF_MISMATCH)
12036 		goto top;
12037 
12038 	return (error);
12039 }
12040 
12041 /*
12042  * nfs4_commit_vp()  will wait for other pending commits and
12043  * will either commit the whole file or a range, plen dictates
12044  * if we commit whole file. a value of zero indicates the whole
12045  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
12046  */
12047 static int
12048 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12049     cred_t *cr, int wait_on_writes)
12050 {
12051 	rnode4_t *rp;
12052 	page_t *plist;
12053 	offset3 offset;
12054 	count3 len;
12055 
12056 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12057 
12058 	rp = VTOR4(vp);
12059 
12060 	/*
12061 	 *  before we gather commitable pages make
12062 	 *  sure there are no outstanding async writes
12063 	 */
12064 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12065 		mutex_enter(&rp->r_statelock);
12066 		while (rp->r_count > 0) {
12067 			cv_wait(&rp->r_cv, &rp->r_statelock);
12068 		}
12069 		mutex_exit(&rp->r_statelock);
12070 	}
12071 
12072 	/*
12073 	 * Set the `commit inprogress' state bit.  We must
12074 	 * first wait until any current one finishes.
12075 	 */
12076 	mutex_enter(&rp->r_statelock);
12077 	while (rp->r_flags & R4COMMIT) {
12078 		rp->r_flags |= R4COMMITWAIT;
12079 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12080 		rp->r_flags &= ~R4COMMITWAIT;
12081 	}
12082 	rp->r_flags |= R4COMMIT;
12083 	mutex_exit(&rp->r_statelock);
12084 
12085 	/*
12086 	 * Gather all of the pages which need to be
12087 	 * committed.
12088 	 */
12089 	if (plen == 0)
12090 		nfs4_get_commit(vp);
12091 	else
12092 		nfs4_get_commit_range(vp, poff, plen);
12093 
12094 	/*
12095 	 * Clear the `commit inprogress' bit and disconnect the
12096 	 * page list which was gathered by nfs4_get_commit.
12097 	 */
12098 	plist = rp->r_commit.c_pages;
12099 	rp->r_commit.c_pages = NULL;
12100 	offset = rp->r_commit.c_commbase;
12101 	len = rp->r_commit.c_commlen;
12102 	mutex_enter(&rp->r_statelock);
12103 	rp->r_flags &= ~R4COMMIT;
12104 	cv_broadcast(&rp->r_commit.c_cv);
12105 	mutex_exit(&rp->r_statelock);
12106 
12107 	/*
12108 	 * If any pages need to be committed, commit them and
12109 	 * then unlock them so that they can be freed some
12110 	 * time later.
12111 	 */
12112 	if (plist == NULL)
12113 		return (0);
12114 
12115 	/*
12116 	 * No error occurred during the flush portion
12117 	 * of this operation, so now attempt to commit
12118 	 * the data to stable storage on the server.
12119 	 *
12120 	 * This will unlock all of the pages on the list.
12121 	 */
12122 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12123 }
12124 
12125 static int
12126 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12127     cred_t *cr)
12128 {
12129 	int error;
12130 	page_t *pp;
12131 
12132 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12133 
12134 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12135 
12136 	/*
12137 	 * If we got an error, then just unlock all of the pages
12138 	 * on the list.
12139 	 */
12140 	if (error) {
12141 		while (plist != NULL) {
12142 			pp = plist;
12143 			page_sub(&plist, pp);
12144 			page_unlock(pp);
12145 		}
12146 		return (error);
12147 	}
12148 	/*
12149 	 * We've tried as hard as we can to commit the data to stable
12150 	 * storage on the server.  We just unlock the pages and clear
12151 	 * the commit required state.  They will get freed later.
12152 	 */
12153 	while (plist != NULL) {
12154 		pp = plist;
12155 		page_sub(&plist, pp);
12156 		pp->p_fsdata = C_NOCOMMIT;
12157 		page_unlock(pp);
12158 	}
12159 
12160 	return (error);
12161 }
12162 
12163 static void
12164 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12165     cred_t *cr)
12166 {
12167 
12168 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12169 }
12170 
12171 /*ARGSUSED*/
12172 static int
12173 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12174 	caller_context_t *ct)
12175 {
12176 	int		error = 0;
12177 	mntinfo4_t	*mi;
12178 	vattr_t		va;
12179 	vsecattr_t	nfsace4_vsap;
12180 
12181 	mi = VTOMI4(vp);
12182 	if (nfs_zone() != mi->mi_zone)
12183 		return (EIO);
12184 	if (mi->mi_flags & MI4_ACL) {
12185 		/* if we have a delegation, return it */
12186 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12187 			(void) nfs4delegreturn(VTOR4(vp),
12188 			    NFS4_DR_REOPEN|NFS4_DR_PUSH);
12189 
12190 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12191 		    NFS4_ACL_SET);
12192 		if (error) /* EINVAL */
12193 			return (error);
12194 
12195 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12196 			/*
12197 			 * These are aclent_t type entries.
12198 			 */
12199 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12200 			    vp->v_type == VDIR, FALSE);
12201 			if (error)
12202 				return (error);
12203 		} else {
12204 			/*
12205 			 * These are ace_t type entries.
12206 			 */
12207 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12208 			    FALSE);
12209 			if (error)
12210 				return (error);
12211 		}
12212 		bzero(&va, sizeof (va));
12213 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12214 		vs_ace4_destroy(&nfsace4_vsap);
12215 		return (error);
12216 	}
12217 	return (ENOSYS);
12218 }
12219 
12220 /* ARGSUSED */
12221 int
12222 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12223 	caller_context_t *ct)
12224 {
12225 	int		error;
12226 	mntinfo4_t	*mi;
12227 	nfs4_ga_res_t	gar;
12228 	rnode4_t	*rp = VTOR4(vp);
12229 
12230 	mi = VTOMI4(vp);
12231 	if (nfs_zone() != mi->mi_zone)
12232 		return (EIO);
12233 
12234 	bzero(&gar, sizeof (gar));
12235 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12236 
12237 	/*
12238 	 * vsecattr->vsa_mask holds the original acl request mask.
12239 	 * This is needed when determining what to return.
12240 	 * (See: nfs4_create_getsecattr_return())
12241 	 */
12242 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12243 	if (error) /* EINVAL */
12244 		return (error);
12245 
12246 	if (mi->mi_flags & MI4_ACL) {
12247 		/*
12248 		 * Check if the data is cached and the cache is valid.  If it
12249 		 * is we don't go over the wire.
12250 		 */
12251 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12252 			mutex_enter(&rp->r_statelock);
12253 			if (rp->r_secattr != NULL) {
12254 				error = nfs4_create_getsecattr_return(
12255 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12256 				    rp->r_attr.va_gid,
12257 				    vp->v_type == VDIR);
12258 				if (!error) { /* error == 0 - Success! */
12259 					mutex_exit(&rp->r_statelock);
12260 					return (error);
12261 				}
12262 			}
12263 			mutex_exit(&rp->r_statelock);
12264 		}
12265 
12266 		/*
12267 		 * The getattr otw call will always get both the acl, in
12268 		 * the form of a list of nfsace4's, and the number of acl
12269 		 * entries; independent of the value of gar.n4g_vsa.vsa_mask.
12270 		 */
12271 		gar.n4g_va.va_mask = AT_ALL;
12272 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12273 		if (error) {
12274 			vs_ace4_destroy(&gar.n4g_vsa);
12275 			if (error == ENOTSUP || error == EOPNOTSUPP)
12276 				error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12277 			return (error);
12278 		}
12279 
12280 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12281 			/*
12282 			 * No error was returned, but according to the response
12283 			 * bitmap, neither was an acl.
12284 			 */
12285 			vs_ace4_destroy(&gar.n4g_vsa);
12286 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12287 			return (error);
12288 		}
12289 
12290 		/*
12291 		 * Update the cache with the ACL.
12292 		 */
12293 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12294 
12295 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12296 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12297 		    vp->v_type == VDIR);
12298 		vs_ace4_destroy(&gar.n4g_vsa);
12299 		if ((error) && (vsecattr->vsa_mask &
12300 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12301 		    (error != EACCES)) {
12302 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12303 		}
12304 		return (error);
12305 	}
12306 	error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12307 	return (error);
12308 }
12309 
12310 /*
12311  * The function returns:
12312  * 	- 0 (zero) if the passed in "acl_mask" is a valid request.
12313  * 	- EINVAL if the passed in "acl_mask" is an invalid request.
12314  *
12315  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12316  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12317  *
12318  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12319  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12320  * - We have a count field set without the corresponding acl field set. (e.g. -
12321  * VSA_ACECNT is set, but VSA_ACE is not)
12322  */
12323 static int
12324 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12325 {
12326 	/* Shortcut the masks that are always valid. */
12327 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12328 		return (0);
12329 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12330 		return (0);
12331 
12332 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12333 		/*
12334 		 * We can't have any VSA_ACL type stuff in the mask now.
12335 		 */
12336 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12337 		    VSA_DFACLCNT))
12338 			return (EINVAL);
12339 
12340 		if (op == NFS4_ACL_SET) {
12341 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12342 				return (EINVAL);
12343 		}
12344 	}
12345 
12346 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12347 		/*
12348 		 * We can't have any VSA_ACE type stuff in the mask now.
12349 		 */
12350 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12351 			return (EINVAL);
12352 
12353 		if (op == NFS4_ACL_SET) {
12354 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12355 				return (EINVAL);
12356 
12357 			if ((acl_mask & VSA_DFACLCNT) &&
12358 			    !(acl_mask & VSA_DFACL))
12359 				return (EINVAL);
12360 		}
12361 	}
12362 	return (0);
12363 }
12364 
12365 /*
12366  * The theory behind creating the correct getsecattr return is simply this:
12367  * "Don't return anything that the caller is not expecting to have to free."
12368  */
12369 static int
12370 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12371     uid_t uid, gid_t gid, int isdir)
12372 {
12373 	int error = 0;
12374 	/* Save the mask since the translators modify it. */
12375 	uint_t	orig_mask = vsap->vsa_mask;
12376 
12377 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12378 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid,
12379 		    FALSE, ((orig_mask & VSA_ACE) ? FALSE : TRUE));
12380 
12381 		if (error)
12382 			return (error);
12383 
12384 		/*
12385 		 * If the caller only asked for the ace count (VSA_ACECNT)
12386 		 * don't give them the full acl (VSA_ACE), free it.
12387 		 */
12388 		if (!orig_mask & VSA_ACE) {
12389 			if (vsap->vsa_aclentp != NULL) {
12390 				kmem_free(vsap->vsa_aclentp,
12391 				    vsap->vsa_aclcnt * sizeof (ace_t));
12392 				vsap->vsa_aclentp = NULL;
12393 			}
12394 		}
12395 		vsap->vsa_mask = orig_mask;
12396 
12397 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12398 	    VSA_DFACLCNT)) {
12399 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12400 		    isdir, FALSE,
12401 		    ((orig_mask & (VSA_ACL | VSA_DFACL)) ? FALSE : TRUE));
12402 
12403 		if (error)
12404 			return (error);
12405 
12406 		/*
12407 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12408 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12409 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12410 		 */
12411 		if (!orig_mask & VSA_ACL) {
12412 			if (vsap->vsa_aclentp != NULL) {
12413 				kmem_free(vsap->vsa_aclentp,
12414 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12415 				vsap->vsa_aclentp = NULL;
12416 			}
12417 		}
12418 
12419 		if (!orig_mask & VSA_DFACL) {
12420 			if (vsap->vsa_dfaclentp != NULL) {
12421 				kmem_free(vsap->vsa_dfaclentp,
12422 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12423 				vsap->vsa_dfaclentp = NULL;
12424 			}
12425 		}
12426 		vsap->vsa_mask = orig_mask;
12427 	}
12428 	return (0);
12429 }
12430 
12431 /* ARGSUSED */
12432 int
12433 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr,
12434     caller_context_t *ct)
12435 {
12436 	int error;
12437 
12438 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12439 		return (EIO);
12440 	/*
12441 	 * check for valid cmd parameter
12442 	 */
12443 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12444 		return (EINVAL);
12445 
12446 	/*
12447 	 * Check access permissions
12448 	 */
12449 	if ((cmd & F_SHARE) &&
12450 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12451 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12452 		return (EBADF);
12453 
12454 	/*
12455 	 * If the filesystem is mounted using local locking, pass the
12456 	 * request off to the local share code.
12457 	 */
12458 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12459 		return (fs_shrlock(vp, cmd, shr, flag, cr, ct));
12460 
12461 	switch (cmd) {
12462 	case F_SHARE:
12463 	case F_UNSHARE:
12464 		/*
12465 		 * This will be properly implemented later,
12466 		 * see RFE: 4823948 .
12467 		 */
12468 		error = EAGAIN;
12469 		break;
12470 
12471 	case F_HASREMOTELOCKS:
12472 		/*
12473 		 * NFS client can't store remote locks itself
12474 		 */
12475 		shr->s_access = 0;
12476 		error = 0;
12477 		break;
12478 
12479 	default:
12480 		error = EINVAL;
12481 		break;
12482 	}
12483 
12484 	return (error);
12485 }
12486 
12487 /*
12488  * Common code called by directory ops to update the attrcache
12489  */
12490 static int
12491 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12492     hrtime_t t, vnode_t *vp, cred_t *cr)
12493 {
12494 	int error = 0;
12495 
12496 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12497 
12498 	if (status != NFS4_OK) {
12499 		/* getattr not done or failed */
12500 		PURGE_ATTRCACHE4(vp);
12501 		return (error);
12502 	}
12503 
12504 	if (garp) {
12505 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12506 	} else {
12507 		PURGE_ATTRCACHE4(vp);
12508 	}
12509 	return (error);
12510 }
12511 
12512 /*
12513  * Update directory caches for directory modification ops (link, rename, etc.)
12514  * When dinfo is NULL, manage dircaches in the old way.
12515  */
12516 static void
12517 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12518     dirattr_info_t *dinfo)
12519 {
12520 	rnode4_t	*drp = VTOR4(dvp);
12521 
12522 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12523 
12524 	/* Purge rddir cache for dir since it changed */
12525 	if (drp->r_dir != NULL)
12526 		nfs4_purge_rddir_cache(dvp);
12527 
12528 	/*
12529 	 * If caller provided dinfo, then use it to manage dir caches.
12530 	 */
12531 	if (dinfo != NULL) {
12532 		if (vp != NULL) {
12533 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12534 			if (!VTOR4(vp)->created_v4) {
12535 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12536 				dnlc_update(dvp, nm, vp);
12537 			} else {
12538 				/*
12539 				 * XXX don't update if the created_v4 flag is
12540 				 * set
12541 				 */
12542 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12543 				NFS4_DEBUG(nfs4_client_state_debug,
12544 				    (CE_NOTE, "nfs4_update_dircaches: "
12545 				    "don't update dnlc: created_v4 flag"));
12546 			}
12547 		}
12548 
12549 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12550 		    dinfo->di_cred, FALSE, cinfo);
12551 
12552 		return;
12553 	}
12554 
12555 	/*
12556 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12557 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12558 	 * attrs, the dir's attrs must be purged.
12559 	 *
12560 	 * XXX this check and dnlc update/purge should really be atomic,
12561 	 * XXX but can't use rnode statelock because it'll deadlock in
12562 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12563 	 * XXX does occur.
12564 	 *
12565 	 * XXX We also may want to check that atomic is true in the
12566 	 * XXX change_info struct. If it is not, the change_info may
12567 	 * XXX reflect changes by more than one clients which means that
12568 	 * XXX our cache may not be valid.
12569 	 */
12570 	PURGE_ATTRCACHE4(dvp);
12571 	if (drp->r_change == cinfo->before) {
12572 		/* no changes took place in the directory prior to our link */
12573 		if (vp != NULL) {
12574 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12575 			if (!VTOR4(vp)->created_v4) {
12576 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12577 				dnlc_update(dvp, nm, vp);
12578 			} else {
12579 				/*
12580 				 * XXX dont' update if the created_v4 flag
12581 				 * is set
12582 				 */
12583 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12584 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12585 				    "nfs4_update_dircaches: don't"
12586 				    " update dnlc: created_v4 flag"));
12587 			}
12588 		}
12589 	} else {
12590 		/* Another client modified directory - purge its dnlc cache */
12591 		dnlc_purge_vp(dvp);
12592 	}
12593 }
12594 
12595 /*
12596  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12597  * file.
12598  *
12599  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12600  * file (ie: client recovery) and otherwise set to FALSE.
12601  *
12602  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12603  * initiated) calling functions.
12604  *
12605  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12606  * of resending a 'lost' open request.
12607  *
12608  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12609  * server that hands out BAD_SEQID on open confirm.
12610  *
12611  * Errors are returned via the nfs4_error_t parameter.
12612  */
12613 void
12614 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12615     bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12616     bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12617 {
12618 	COMPOUND4args_clnt args;
12619 	COMPOUND4res_clnt res;
12620 	nfs_argop4 argop[2];
12621 	nfs_resop4 *resop;
12622 	int doqueue = 1;
12623 	mntinfo4_t *mi;
12624 	OPEN_CONFIRM4args *open_confirm_args;
12625 	int needrecov;
12626 
12627 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12628 #if DEBUG
12629 	mutex_enter(&oop->oo_lock);
12630 	ASSERT(oop->oo_seqid_inuse);
12631 	mutex_exit(&oop->oo_lock);
12632 #endif
12633 
12634 recov_retry_confirm:
12635 	nfs4_error_zinit(ep);
12636 	*retry_open = FALSE;
12637 
12638 	if (resend)
12639 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12640 	else
12641 		args.ctag = TAG_OPEN_CONFIRM;
12642 
12643 	args.array_len = 2;
12644 	args.array = argop;
12645 
12646 	/* putfh target fh */
12647 	argop[0].argop = OP_CPUTFH;
12648 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12649 
12650 	argop[1].argop = OP_OPEN_CONFIRM;
12651 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12652 
12653 	(*seqid) += 1;
12654 	open_confirm_args->seqid = *seqid;
12655 	open_confirm_args->open_stateid = *stateid;
12656 
12657 	mi = VTOMI4(vp);
12658 
12659 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12660 
12661 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12662 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12663 	}
12664 
12665 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12666 	if (!needrecov && ep->error)
12667 		return;
12668 
12669 	if (needrecov) {
12670 		bool_t abort = FALSE;
12671 
12672 		if (reopening_file == FALSE) {
12673 			nfs4_bseqid_entry_t *bsep = NULL;
12674 
12675 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12676 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12677 				    vp, 0, args.ctag,
12678 				    open_confirm_args->seqid);
12679 
12680 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp,
12681 			    NULL, NULL, NULL, OP_OPEN_CONFIRM, bsep);
12682 			if (bsep) {
12683 				kmem_free(bsep, sizeof (*bsep));
12684 				if (num_bseqid_retryp &&
12685 				    --(*num_bseqid_retryp) == 0)
12686 					abort = TRUE;
12687 			}
12688 		}
12689 		if ((ep->error == ETIMEDOUT ||
12690 		    res.status == NFS4ERR_RESOURCE) &&
12691 		    abort == FALSE && resend == FALSE) {
12692 			if (!ep->error)
12693 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12694 				    (caddr_t)&res);
12695 
12696 			delay(SEC_TO_TICK(confirm_retry_sec));
12697 			goto recov_retry_confirm;
12698 		}
12699 		/* State may have changed so retry the entire OPEN op */
12700 		if (abort == FALSE)
12701 			*retry_open = TRUE;
12702 		else
12703 			*retry_open = FALSE;
12704 		if (!ep->error)
12705 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12706 		return;
12707 	}
12708 
12709 	if (res.status) {
12710 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12711 		return;
12712 	}
12713 
12714 	resop = &res.array[1];  /* open confirm res */
12715 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
12716 	    stateid, sizeof (*stateid));
12717 
12718 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12719 }
12720 
12721 /*
12722  * Return the credentials associated with a client state object.  The
12723  * caller is responsible for freeing the credentials.
12724  */
12725 
12726 static cred_t *
12727 state_to_cred(nfs4_open_stream_t *osp)
12728 {
12729 	cred_t *cr;
12730 
12731 	/*
12732 	 * It's ok to not lock the open stream and open owner to get
12733 	 * the oo_cred since this is only written once (upon creation)
12734 	 * and will not change.
12735 	 */
12736 	cr = osp->os_open_owner->oo_cred;
12737 	crhold(cr);
12738 
12739 	return (cr);
12740 }
12741 
12742 /*
12743  * nfs4_find_sysid
12744  *
12745  * Find the sysid for the knetconfig associated with the given mi.
12746  */
12747 static struct lm_sysid *
12748 nfs4_find_sysid(mntinfo4_t *mi)
12749 {
12750 	ASSERT(nfs_zone() == mi->mi_zone);
12751 
12752 	/*
12753 	 * Switch from RDMA knconf to original mount knconf
12754 	 */
12755 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
12756 	    mi->mi_curr_serv->sv_hostname, NULL));
12757 }
12758 
12759 #ifdef DEBUG
12760 /*
12761  * Return a string version of the call type for easy reading.
12762  */
12763 static char *
12764 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
12765 {
12766 	switch (ctype) {
12767 	case NFS4_LCK_CTYPE_NORM:
12768 		return ("NORMAL");
12769 	case NFS4_LCK_CTYPE_RECLAIM:
12770 		return ("RECLAIM");
12771 	case NFS4_LCK_CTYPE_RESEND:
12772 		return ("RESEND");
12773 	case NFS4_LCK_CTYPE_REINSTATE:
12774 		return ("REINSTATE");
12775 	default:
12776 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
12777 		    "type %d", ctype);
12778 		return ("");
12779 	}
12780 }
12781 #endif
12782 
12783 /*
12784  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
12785  * Unlock requests don't have an over-the-wire locktype, so we just return
12786  * something non-threatening.
12787  */
12788 
12789 static nfs_lock_type4
12790 flk_to_locktype(int cmd, int l_type)
12791 {
12792 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
12793 
12794 	switch (l_type) {
12795 	case F_UNLCK:
12796 		return (READ_LT);
12797 	case F_RDLCK:
12798 		if (cmd == F_SETLK)
12799 			return (READ_LT);
12800 		else
12801 			return (READW_LT);
12802 	case F_WRLCK:
12803 		if (cmd == F_SETLK)
12804 			return (WRITE_LT);
12805 		else
12806 			return (WRITEW_LT);
12807 	}
12808 	panic("flk_to_locktype");
12809 	/*NOTREACHED*/
12810 }
12811 
12812 /*
12813  * Do some preliminary checks for nfs4frlock.
12814  */
12815 static int
12816 nfs4frlock_validate_args(int cmd, flock64_t *flk, int flag, vnode_t *vp,
12817     u_offset_t offset)
12818 {
12819 	int error = 0;
12820 
12821 	/*
12822 	 * If we are setting a lock, check that the file is opened
12823 	 * with the correct mode.
12824 	 */
12825 	if (cmd == F_SETLK || cmd == F_SETLKW) {
12826 		if ((flk->l_type == F_RDLCK && (flag & FREAD) == 0) ||
12827 		    (flk->l_type == F_WRLCK && (flag & FWRITE) == 0)) {
12828 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12829 			    "nfs4frlock_validate_args: file was opened with "
12830 			    "incorrect mode"));
12831 			return (EBADF);
12832 		}
12833 	}
12834 
12835 	/* Convert the offset. It may need to be restored before returning. */
12836 	if (error = convoff(vp, flk, 0, offset)) {
12837 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12838 		    "nfs4frlock_validate_args: convoff  =>  error= %d\n",
12839 		    error));
12840 		return (error);
12841 	}
12842 
12843 	return (error);
12844 }
12845 
12846 /*
12847  * Set the flock64's lm_sysid for nfs4frlock.
12848  */
12849 static int
12850 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
12851 {
12852 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12853 
12854 	/* Find the lm_sysid */
12855 	*lspp = nfs4_find_sysid(VTOMI4(vp));
12856 
12857 	if (*lspp == NULL) {
12858 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12859 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
12860 		return (ENOLCK);
12861 	}
12862 
12863 	flk->l_sysid = lm_sysidt(*lspp);
12864 
12865 	return (0);
12866 }
12867 
12868 /*
12869  * Do the remaining preliminary setup for nfs4frlock.
12870  */
12871 static void
12872 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
12873     flock64_t *flk, short *whencep, vnode_t *vp, cred_t *search_cr,
12874     cred_t **cred_otw)
12875 {
12876 	/*
12877 	 * set tick_delay to the base delay time.
12878 	 * (NFS4_BASE_WAIT_TIME is in secs)
12879 	 */
12880 
12881 	*tick_delayp = drv_usectohz(NFS4_BASE_WAIT_TIME * 1000 * 1000);
12882 
12883 	/*
12884 	 * If lock is relative to EOF, we need the newest length of the
12885 	 * file. Therefore invalidate the ATTR_CACHE.
12886 	 */
12887 
12888 	*whencep = flk->l_whence;
12889 
12890 	if (*whencep == 2)		/* SEEK_END */
12891 		PURGE_ATTRCACHE4(vp);
12892 
12893 	recov_statep->rs_flags = 0;
12894 	recov_statep->rs_num_retry_despite_err = 0;
12895 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
12896 }
12897 
12898 /*
12899  * Initialize and allocate the data structures necessary for
12900  * the nfs4frlock call.
12901  * Allocates argsp's op array, frees up the saved_rqstpp if there is one.
12902  */
12903 static void
12904 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
12905     nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
12906     bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
12907     bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
12908 {
12909 	int		argoplist_size;
12910 	int		num_ops = 2;
12911 
12912 	*retry = FALSE;
12913 	*did_start_fop = FALSE;
12914 	*skip_get_err = FALSE;
12915 	lost_rqstp->lr_op = 0;
12916 	argoplist_size  = num_ops * sizeof (nfs_argop4);
12917 	/* fill array with zero */
12918 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
12919 
12920 	*argspp = argsp;
12921 	*respp = NULL;
12922 
12923 	argsp->array_len = num_ops;
12924 	argsp->array = *argopp;
12925 
12926 	/* initialize in case of error; will get real value down below */
12927 	argsp->ctag = TAG_NONE;
12928 
12929 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
12930 		*op_hintp = OH_LOCKU;
12931 	else
12932 		*op_hintp = OH_OTHER;
12933 }
12934 
12935 /*
12936  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
12937  * the proper nfs4_server_t for this instance of nfs4frlock.
12938  * Returns 0 (success) or an errno value.
12939  */
12940 static int
12941 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
12942     nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
12943     bool_t *did_start_fop, bool_t *startrecovp)
12944 {
12945 	int error = 0;
12946 	rnode4_t *rp;
12947 
12948 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12949 
12950 	if (ctype == NFS4_LCK_CTYPE_NORM) {
12951 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
12952 		    recov_statep, startrecovp);
12953 		if (error)
12954 			return (error);
12955 		*did_start_fop = TRUE;
12956 	} else {
12957 		*did_start_fop = FALSE;
12958 		*startrecovp = FALSE;
12959 	}
12960 
12961 	if (!error) {
12962 		rp = VTOR4(vp);
12963 
12964 		/* If the file failed recovery, just quit. */
12965 		mutex_enter(&rp->r_statelock);
12966 		if (rp->r_flags & R4RECOVERR) {
12967 			error = EIO;
12968 		}
12969 		mutex_exit(&rp->r_statelock);
12970 	}
12971 
12972 	return (error);
12973 }
12974 
12975 /*
12976  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
12977  * resend nfs4frlock call is initiated by the recovery framework.
12978  * Acquires the lop and oop seqid synchronization.
12979  */
12980 static void
12981 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
12982     COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
12983     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
12984     LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
12985 {
12986 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
12987 	int error;
12988 
12989 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
12990 	    (CE_NOTE,
12991 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
12992 	ASSERT(resend_rqstp != NULL);
12993 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
12994 	    resend_rqstp->lr_op == OP_LOCKU);
12995 
12996 	*oopp = resend_rqstp->lr_oop;
12997 	if (resend_rqstp->lr_oop) {
12998 		open_owner_hold(resend_rqstp->lr_oop);
12999 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
13000 		ASSERT(error == 0);	/* recov thread always succeeds */
13001 	}
13002 
13003 	/* Must resend this lost lock/locku request. */
13004 	ASSERT(resend_rqstp->lr_lop != NULL);
13005 	*lopp = resend_rqstp->lr_lop;
13006 	lock_owner_hold(resend_rqstp->lr_lop);
13007 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
13008 	ASSERT(error == 0);	/* recov thread always succeeds */
13009 
13010 	*ospp = resend_rqstp->lr_osp;
13011 	if (*ospp)
13012 		open_stream_hold(resend_rqstp->lr_osp);
13013 
13014 	if (resend_rqstp->lr_op == OP_LOCK) {
13015 		LOCK4args *lock_args;
13016 
13017 		argop->argop = OP_LOCK;
13018 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
13019 		lock_args->locktype = resend_rqstp->lr_locktype;
13020 		lock_args->reclaim =
13021 		    (resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
13022 		lock_args->offset = resend_rqstp->lr_flk->l_start;
13023 		lock_args->length = resend_rqstp->lr_flk->l_len;
13024 		if (lock_args->length == 0)
13025 			lock_args->length = ~lock_args->length;
13026 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
13027 		    mi2clientid(mi), &lock_args->locker);
13028 
13029 		switch (resend_rqstp->lr_ctype) {
13030 		case NFS4_LCK_CTYPE_RESEND:
13031 			argsp->ctag = TAG_LOCK_RESEND;
13032 			break;
13033 		case NFS4_LCK_CTYPE_REINSTATE:
13034 			argsp->ctag = TAG_LOCK_REINSTATE;
13035 			break;
13036 		case NFS4_LCK_CTYPE_RECLAIM:
13037 			argsp->ctag = TAG_LOCK_RECLAIM;
13038 			break;
13039 		default:
13040 			argsp->ctag = TAG_LOCK_UNKNOWN;
13041 			break;
13042 		}
13043 	} else {
13044 		LOCKU4args *locku_args;
13045 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
13046 
13047 		argop->argop = OP_LOCKU;
13048 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
13049 		locku_args->locktype = READ_LT;
13050 		locku_args->seqid = lop->lock_seqid + 1;
13051 		mutex_enter(&lop->lo_lock);
13052 		locku_args->lock_stateid = lop->lock_stateid;
13053 		mutex_exit(&lop->lo_lock);
13054 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13055 		locku_args->length = resend_rqstp->lr_flk->l_len;
13056 		if (locku_args->length == 0)
13057 			locku_args->length = ~locku_args->length;
13058 
13059 		switch (resend_rqstp->lr_ctype) {
13060 		case NFS4_LCK_CTYPE_RESEND:
13061 			argsp->ctag = TAG_LOCKU_RESEND;
13062 			break;
13063 		case NFS4_LCK_CTYPE_REINSTATE:
13064 			argsp->ctag = TAG_LOCKU_REINSTATE;
13065 			break;
13066 		default:
13067 			argsp->ctag = TAG_LOCK_UNKNOWN;
13068 			break;
13069 		}
13070 	}
13071 }
13072 
13073 /*
13074  * Setup the LOCKT4 arguments.
13075  */
13076 static void
13077 nfs4frlock_setup_lockt_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13078     LOCKT4args **lockt_argsp, COMPOUND4args_clnt *argsp, flock64_t *flk,
13079     rnode4_t *rp)
13080 {
13081 	LOCKT4args *lockt_args;
13082 
13083 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13084 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13085 	argop->argop = OP_LOCKT;
13086 	argsp->ctag = TAG_LOCKT;
13087 	lockt_args = &argop->nfs_argop4_u.oplockt;
13088 
13089 	/*
13090 	 * The locktype will be READ_LT unless it's
13091 	 * a write lock. We do this because the Solaris
13092 	 * system call allows the combination of
13093 	 * F_UNLCK and F_GETLK* and so in that case the
13094 	 * unlock is mapped to a read.
13095 	 */
13096 	if (flk->l_type == F_WRLCK)
13097 		lockt_args->locktype = WRITE_LT;
13098 	else
13099 		lockt_args->locktype = READ_LT;
13100 
13101 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13102 	/* set the lock owner4 args */
13103 	nfs4_setlockowner_args(&lockt_args->owner, rp,
13104 	    ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13105 	    flk->l_pid);
13106 	lockt_args->offset = flk->l_start;
13107 	lockt_args->length = flk->l_len;
13108 	if (flk->l_len == 0)
13109 		lockt_args->length = ~lockt_args->length;
13110 
13111 	*lockt_argsp = lockt_args;
13112 }
13113 
13114 /*
13115  * If the client is holding a delegation, and the open stream to be used
13116  * with this lock request is a delegation open stream, then re-open the stream.
13117  * Sets the nfs4_error_t to all zeros unless the open stream has already
13118  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13119  * means the caller should retry (like a recovery retry).
13120  */
13121 static void
13122 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13123 {
13124 	open_delegation_type4	dt;
13125 	bool_t			reopen_needed, force;
13126 	nfs4_open_stream_t	*osp;
13127 	open_claim_type4 	oclaim;
13128 	rnode4_t		*rp = VTOR4(vp);
13129 	mntinfo4_t		*mi = VTOMI4(vp);
13130 
13131 	ASSERT(nfs_zone() == mi->mi_zone);
13132 
13133 	nfs4_error_zinit(ep);
13134 
13135 	mutex_enter(&rp->r_statev4_lock);
13136 	dt = rp->r_deleg_type;
13137 	mutex_exit(&rp->r_statev4_lock);
13138 
13139 	if (dt != OPEN_DELEGATE_NONE) {
13140 		nfs4_open_owner_t	*oop;
13141 
13142 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13143 		if (!oop) {
13144 			ep->stat = NFS4ERR_IO;
13145 			return;
13146 		}
13147 		/* returns with 'os_sync_lock' held */
13148 		osp = find_open_stream(oop, rp);
13149 		if (!osp) {
13150 			open_owner_rele(oop);
13151 			ep->stat = NFS4ERR_IO;
13152 			return;
13153 		}
13154 
13155 		if (osp->os_failed_reopen) {
13156 			NFS4_DEBUG((nfs4_open_stream_debug ||
13157 			    nfs4_client_lock_debug), (CE_NOTE,
13158 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13159 			    "for osp %p, cr %p, rp %s", (void *)osp,
13160 			    (void *)cr, rnode4info(rp)));
13161 			mutex_exit(&osp->os_sync_lock);
13162 			open_stream_rele(osp, rp);
13163 			open_owner_rele(oop);
13164 			ep->stat = NFS4ERR_IO;
13165 			return;
13166 		}
13167 
13168 		/*
13169 		 * Determine whether a reopen is needed.  If this
13170 		 * is a delegation open stream, then send the open
13171 		 * to the server to give visibility to the open owner.
13172 		 * Even if it isn't a delegation open stream, we need
13173 		 * to check if the previous open CLAIM_DELEGATE_CUR
13174 		 * was sufficient.
13175 		 */
13176 
13177 		reopen_needed = osp->os_delegation ||
13178 		    ((lt == F_RDLCK &&
13179 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13180 		    (lt == F_WRLCK &&
13181 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13182 
13183 		mutex_exit(&osp->os_sync_lock);
13184 		open_owner_rele(oop);
13185 
13186 		if (reopen_needed) {
13187 			/*
13188 			 * Always use CLAIM_PREVIOUS after server reboot.
13189 			 * The server will reject CLAIM_DELEGATE_CUR if
13190 			 * it is used during the grace period.
13191 			 */
13192 			mutex_enter(&mi->mi_lock);
13193 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13194 				oclaim = CLAIM_PREVIOUS;
13195 				force = TRUE;
13196 			} else {
13197 				oclaim = CLAIM_DELEGATE_CUR;
13198 				force = FALSE;
13199 			}
13200 			mutex_exit(&mi->mi_lock);
13201 
13202 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13203 			if (ep->error == EAGAIN) {
13204 				nfs4_error_zinit(ep);
13205 				ep->stat = NFS4ERR_DELAY;
13206 			}
13207 		}
13208 		open_stream_rele(osp, rp);
13209 		osp = NULL;
13210 	}
13211 }
13212 
13213 /*
13214  * Setup the LOCKU4 arguments.
13215  * Returns errors via the nfs4_error_t.
13216  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13217  *			over-the-wire.  The caller must release the
13218  *			reference on *lopp.
13219  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13220  * (other)		unrecoverable error.
13221  */
13222 static void
13223 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13224     LOCKU4args **locku_argsp, flock64_t *flk,
13225     nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13226     vnode_t *vp, int flag, u_offset_t offset, cred_t *cr,
13227     bool_t *skip_get_err, bool_t *go_otwp)
13228 {
13229 	nfs4_lock_owner_t	*lop = NULL;
13230 	LOCKU4args		*locku_args;
13231 	pid_t			pid;
13232 	bool_t			is_spec = FALSE;
13233 	rnode4_t		*rp = VTOR4(vp);
13234 
13235 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13236 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13237 
13238 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13239 	if (ep->error || ep->stat)
13240 		return;
13241 
13242 	argop->argop = OP_LOCKU;
13243 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13244 		argsp->ctag = TAG_LOCKU_REINSTATE;
13245 	else
13246 		argsp->ctag = TAG_LOCKU;
13247 	locku_args = &argop->nfs_argop4_u.oplocku;
13248 	*locku_argsp = locku_args;
13249 
13250 	/*
13251 	 * XXX what should locku_args->locktype be?
13252 	 * setting to ALWAYS be READ_LT so at least
13253 	 * it is a valid locktype.
13254 	 */
13255 
13256 	locku_args->locktype = READ_LT;
13257 
13258 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13259 	    flk->l_pid;
13260 
13261 	/*
13262 	 * Get the lock owner stateid.  If no lock owner
13263 	 * exists, return success.
13264 	 */
13265 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13266 	*lopp = lop;
13267 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13268 		is_spec = TRUE;
13269 	if (!lop || is_spec) {
13270 		/*
13271 		 * No lock owner so no locks to unlock.
13272 		 * Return success.  If there was a failed
13273 		 * reclaim earlier, the lock might still be
13274 		 * registered with the local locking code,
13275 		 * so notify it of the unlock.
13276 		 *
13277 		 * If the lockowner is using a special stateid,
13278 		 * then the original lock request (that created
13279 		 * this lockowner) was never successful, so we
13280 		 * have no lock to undo OTW.
13281 		 */
13282 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13283 		    "nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13284 		    "(%ld) so return success", (long)pid));
13285 
13286 		if (ctype == NFS4_LCK_CTYPE_NORM)
13287 			flk->l_pid = curproc->p_pid;
13288 		nfs4_register_lock_locally(vp, flk, flag, offset);
13289 		/*
13290 		 * Release our hold and NULL out so final_cleanup
13291 		 * doesn't try to end a lock seqid sync we
13292 		 * never started.
13293 		 */
13294 		if (is_spec) {
13295 			lock_owner_rele(lop);
13296 			*lopp = NULL;
13297 		}
13298 		*skip_get_err = TRUE;
13299 		*go_otwp = FALSE;
13300 		return;
13301 	}
13302 
13303 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13304 	if (ep->error == EAGAIN) {
13305 		lock_owner_rele(lop);
13306 		*lopp = NULL;
13307 		return;
13308 	}
13309 
13310 	mutex_enter(&lop->lo_lock);
13311 	locku_args->lock_stateid = lop->lock_stateid;
13312 	mutex_exit(&lop->lo_lock);
13313 	locku_args->seqid = lop->lock_seqid + 1;
13314 
13315 	/* leave the ref count on lop, rele after RPC call */
13316 
13317 	locku_args->offset = flk->l_start;
13318 	locku_args->length = flk->l_len;
13319 	if (flk->l_len == 0)
13320 		locku_args->length = ~locku_args->length;
13321 
13322 	*go_otwp = TRUE;
13323 }
13324 
13325 /*
13326  * Setup the LOCK4 arguments.
13327  *
13328  * Returns errors via the nfs4_error_t.
13329  * NFS4_OK		no problems
13330  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13331  * (other)		unrecoverable error
13332  */
13333 static void
13334 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13335     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13336     nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13337     flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13338 {
13339 	LOCK4args		*lock_args;
13340 	nfs4_open_owner_t	*oop = NULL;
13341 	nfs4_open_stream_t	*osp = NULL;
13342 	nfs4_lock_owner_t	*lop = NULL;
13343 	pid_t			pid;
13344 	rnode4_t		*rp = VTOR4(vp);
13345 
13346 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13347 
13348 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13349 	if (ep->error || ep->stat != NFS4_OK)
13350 		return;
13351 
13352 	argop->argop = OP_LOCK;
13353 	if (ctype == NFS4_LCK_CTYPE_NORM)
13354 		argsp->ctag = TAG_LOCK;
13355 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13356 		argsp->ctag = TAG_RELOCK;
13357 	else
13358 		argsp->ctag = TAG_LOCK_REINSTATE;
13359 	lock_args = &argop->nfs_argop4_u.oplock;
13360 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13361 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13362 	/*
13363 	 * Get the lock owner.  If no lock owner exists,
13364 	 * create a 'temporary' one and grab the open seqid
13365 	 * synchronization (which puts a hold on the open
13366 	 * owner and open stream).
13367 	 * This also grabs the lock seqid synchronization.
13368 	 */
13369 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid : flk->l_pid;
13370 	ep->stat =
13371 	    nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13372 
13373 	if (ep->stat != NFS4_OK)
13374 		goto out;
13375 
13376 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13377 	    &lock_args->locker);
13378 
13379 	lock_args->offset = flk->l_start;
13380 	lock_args->length = flk->l_len;
13381 	if (flk->l_len == 0)
13382 		lock_args->length = ~lock_args->length;
13383 	*lock_argsp = lock_args;
13384 out:
13385 	*oopp = oop;
13386 	*ospp = osp;
13387 	*lopp = lop;
13388 }
13389 
13390 /*
13391  * After we get the reply from the server, record the proper information
13392  * for possible resend lock requests.
13393  *
13394  * Allocates memory for the saved_rqstp if we have a lost lock to save.
13395  */
13396 static void
13397 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13398     nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13399     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13400     nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13401 {
13402 	bool_t unlock = (flk->l_type == F_UNLCK);
13403 
13404 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13405 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13406 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13407 
13408 	if (error != 0 && !unlock) {
13409 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13410 		    nfs4_client_lock_debug), (CE_NOTE,
13411 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13412 		    " for lop %p", (void *)lop));
13413 		ASSERT(lop != NULL);
13414 		mutex_enter(&lop->lo_lock);
13415 		lop->lo_pending_rqsts = 1;
13416 		mutex_exit(&lop->lo_lock);
13417 	}
13418 
13419 	lost_rqstp->lr_putfirst = FALSE;
13420 	lost_rqstp->lr_op = 0;
13421 
13422 	/*
13423 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13424 	 * recovery purposes so that the lock request that was sent
13425 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13426 	 * unmount.  This is done to have the client's local locking state
13427 	 * match the v4 server's state; that is, the request was
13428 	 * potentially received and accepted by the server but the client
13429 	 * thinks it was not.
13430 	 */
13431 	if (error == ETIMEDOUT || error == EINTR ||
13432 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13433 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13434 		    nfs4_client_lock_debug), (CE_NOTE,
13435 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13436 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13437 		    (void *)lop, (void *)oop, (void *)osp));
13438 		if (unlock)
13439 			lost_rqstp->lr_op = OP_LOCKU;
13440 		else {
13441 			lost_rqstp->lr_op = OP_LOCK;
13442 			lost_rqstp->lr_locktype = locktype;
13443 		}
13444 		/*
13445 		 * Objects are held and rele'd via the recovery code.
13446 		 * See nfs4_save_lost_rqst.
13447 		 */
13448 		lost_rqstp->lr_vp = vp;
13449 		lost_rqstp->lr_dvp = NULL;
13450 		lost_rqstp->lr_oop = oop;
13451 		lost_rqstp->lr_osp = osp;
13452 		lost_rqstp->lr_lop = lop;
13453 		lost_rqstp->lr_cr = cr;
13454 		switch (ctype) {
13455 		case NFS4_LCK_CTYPE_NORM:
13456 			flk->l_pid = ttoproc(curthread)->p_pid;
13457 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13458 			break;
13459 		case NFS4_LCK_CTYPE_REINSTATE:
13460 			lost_rqstp->lr_putfirst = TRUE;
13461 			lost_rqstp->lr_ctype = ctype;
13462 			break;
13463 		default:
13464 			break;
13465 		}
13466 		lost_rqstp->lr_flk = flk;
13467 	}
13468 }
13469 
13470 /*
13471  * Update lop's seqid.  Also update the seqid stored in a resend request,
13472  * if any.  (Some recovery errors increment the seqid, and we may have to
13473  * send the resend request again.)
13474  */
13475 
13476 static void
13477 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13478     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13479 {
13480 	if (lock_args) {
13481 		if (lock_args->locker.new_lock_owner == TRUE)
13482 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13483 		else {
13484 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13485 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13486 		}
13487 	} else if (locku_args) {
13488 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13489 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13490 	}
13491 }
13492 
13493 /*
13494  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13495  * COMPOUND4 args/res for calls that need to retry.
13496  * Switches the *cred_otwp to base_cr.
13497  */
13498 static void
13499 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13500     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13501     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13502     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13503     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13504 {
13505 	nfs4_open_owner_t	*oop = *oopp;
13506 	nfs4_open_stream_t	*osp = *ospp;
13507 	nfs4_lock_owner_t	*lop = *lopp;
13508 	nfs_argop4		*argop = (*argspp)->array;
13509 
13510 	if (*did_start_fop) {
13511 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13512 		    needrecov);
13513 		*did_start_fop = FALSE;
13514 	}
13515 	ASSERT((*argspp)->array_len == 2);
13516 	if (argop[1].argop == OP_LOCK)
13517 		nfs4args_lock_free(&argop[1]);
13518 	else if (argop[1].argop == OP_LOCKT)
13519 		nfs4args_lockt_free(&argop[1]);
13520 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13521 	if (!error)
13522 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13523 	*argspp = NULL;
13524 	*respp = NULL;
13525 
13526 	if (lop) {
13527 		nfs4_end_lock_seqid_sync(lop);
13528 		lock_owner_rele(lop);
13529 		*lopp = NULL;
13530 	}
13531 
13532 	/* need to free up the reference on osp for lock args */
13533 	if (osp != NULL) {
13534 		open_stream_rele(osp, VTOR4(vp));
13535 		*ospp = NULL;
13536 	}
13537 
13538 	/* need to free up the reference on oop for lock args */
13539 	if (oop != NULL) {
13540 		nfs4_end_open_seqid_sync(oop);
13541 		open_owner_rele(oop);
13542 		*oopp = NULL;
13543 	}
13544 
13545 	crfree(*cred_otwp);
13546 	*cred_otwp = base_cr;
13547 	crhold(*cred_otwp);
13548 }
13549 
13550 /*
13551  * Function to process the client's recovery for nfs4frlock.
13552  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13553  *
13554  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13555  * COMPOUND4 args/res for calls that need to retry.
13556  *
13557  * Note: the rp's r_lkserlock is *not* dropped during this path.
13558  */
13559 static bool_t
13560 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13561     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13562     LOCK4args *lock_args, LOCKU4args *locku_args,
13563     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13564     nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13565     nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13566     bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13567 {
13568 	nfs4_open_owner_t	*oop = *oopp;
13569 	nfs4_open_stream_t	*osp = *ospp;
13570 	nfs4_lock_owner_t	*lop = *lopp;
13571 
13572 	bool_t abort, retry;
13573 
13574 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13575 	ASSERT((*argspp) != NULL);
13576 	ASSERT((*respp) != NULL);
13577 	if (lock_args || locku_args)
13578 		ASSERT(lop != NULL);
13579 
13580 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13581 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13582 
13583 	retry = TRUE;
13584 	abort = FALSE;
13585 	if (needrecov) {
13586 		nfs4_bseqid_entry_t *bsep = NULL;
13587 		nfs_opnum4 op;
13588 
13589 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13590 
13591 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13592 			seqid4 seqid;
13593 
13594 			if (lock_args) {
13595 				if (lock_args->locker.new_lock_owner == TRUE)
13596 					seqid = lock_args->locker.locker4_u.
13597 					    open_owner.open_seqid;
13598 				else
13599 					seqid = lock_args->locker.locker4_u.
13600 					    lock_owner.lock_seqid;
13601 			} else if (locku_args) {
13602 				seqid = locku_args->seqid;
13603 			} else {
13604 				seqid = 0;
13605 			}
13606 
13607 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13608 			    flk->l_pid, (*argspp)->ctag, seqid);
13609 		}
13610 
13611 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13612 		    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13613 		    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13614 		    NULL, op, bsep);
13615 
13616 		if (bsep)
13617 			kmem_free(bsep, sizeof (*bsep));
13618 	}
13619 
13620 	/*
13621 	 * Return that we do not want to retry the request for 3 cases:
13622 	 * 1. If we received EINTR or are bailing out because of a forced
13623 	 *    unmount, we came into this code path just for the sake of
13624 	 *    initiating recovery, we now need to return the error.
13625 	 * 2. If we have aborted recovery.
13626 	 * 3. We received NFS4ERR_BAD_SEQID.
13627 	 */
13628 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13629 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13630 		retry = FALSE;
13631 
13632 	if (*did_start_fop == TRUE) {
13633 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13634 		    needrecov);
13635 		*did_start_fop = FALSE;
13636 	}
13637 
13638 	if (retry == TRUE) {
13639 		nfs_argop4	*argop;
13640 
13641 		argop = (*argspp)->array;
13642 		ASSERT((*argspp)->array_len == 2);
13643 
13644 		if (argop[1].argop == OP_LOCK)
13645 			nfs4args_lock_free(&argop[1]);
13646 		else if (argop[1].argop == OP_LOCKT)
13647 			nfs4args_lockt_free(&argop[1]);
13648 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13649 		if (!ep->error)
13650 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13651 		*respp = NULL;
13652 		*argspp = NULL;
13653 	}
13654 
13655 	if (lop != NULL) {
13656 		nfs4_end_lock_seqid_sync(lop);
13657 		lock_owner_rele(lop);
13658 	}
13659 
13660 	*lopp = NULL;
13661 
13662 	/* need to free up the reference on osp for lock args */
13663 	if (osp != NULL) {
13664 		open_stream_rele(osp, rp);
13665 		*ospp = NULL;
13666 	}
13667 
13668 	/* need to free up the reference on oop for lock args */
13669 	if (oop != NULL) {
13670 		nfs4_end_open_seqid_sync(oop);
13671 		open_owner_rele(oop);
13672 		*oopp = NULL;
13673 	}
13674 
13675 	return (retry);
13676 }
13677 
13678 /*
13679  * Handles the successful reply from the server for nfs4frlock.
13680  */
13681 static void
13682 nfs4frlock_results_ok(nfs4_lock_call_type_t ctype, int cmd, flock64_t *flk,
13683     vnode_t *vp, int flag, u_offset_t offset,
13684     nfs4_lost_rqst_t *resend_rqstp)
13685 {
13686 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13687 	if ((cmd == F_SETLK || cmd == F_SETLKW) &&
13688 	    (flk->l_type == F_RDLCK || flk->l_type == F_WRLCK)) {
13689 		if (ctype == NFS4_LCK_CTYPE_NORM) {
13690 			flk->l_pid = ttoproc(curthread)->p_pid;
13691 			/*
13692 			 * We do not register lost locks locally in
13693 			 * the 'resend' case since the user/application
13694 			 * doesn't think we have the lock.
13695 			 */
13696 			ASSERT(!resend_rqstp);
13697 			nfs4_register_lock_locally(vp, flk, flag, offset);
13698 		}
13699 	}
13700 }
13701 
13702 /*
13703  * Handle the DENIED reply from the server for nfs4frlock.
13704  * Returns TRUE if we should retry the request; FALSE otherwise.
13705  *
13706  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13707  * COMPOUND4 args/res for calls that need to retry.  Can also
13708  * drop and regrab the r_lkserlock.
13709  */
13710 static bool_t
13711 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13712     LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13713     nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13714     vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13715     nfs4_recov_state_t *recov_statep, int needrecov,
13716     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13717     clock_t *tick_delayp, short *whencep, int *errorp,
13718     nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13719     bool_t *skip_get_err)
13720 {
13721 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13722 
13723 	if (lock_args) {
13724 		nfs4_open_owner_t	*oop = *oopp;
13725 		nfs4_open_stream_t	*osp = *ospp;
13726 		nfs4_lock_owner_t	*lop = *lopp;
13727 		int			intr;
13728 
13729 		/*
13730 		 * Blocking lock needs to sleep and retry from the request.
13731 		 *
13732 		 * Do not block and wait for 'resend' or 'reinstate'
13733 		 * lock requests, just return the error.
13734 		 *
13735 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13736 		 */
13737 		if (cmd == F_SETLKW) {
13738 			rnode4_t *rp = VTOR4(vp);
13739 			nfs_argop4 *argop = (*argspp)->array;
13740 
13741 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13742 
13743 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13744 			    recov_statep, needrecov);
13745 			*did_start_fop = FALSE;
13746 			ASSERT((*argspp)->array_len == 2);
13747 			if (argop[1].argop == OP_LOCK)
13748 				nfs4args_lock_free(&argop[1]);
13749 			else if (argop[1].argop == OP_LOCKT)
13750 				nfs4args_lockt_free(&argop[1]);
13751 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13752 			if (*respp)
13753 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13754 				    (caddr_t)*respp);
13755 			*argspp = NULL;
13756 			*respp = NULL;
13757 			nfs4_end_lock_seqid_sync(lop);
13758 			lock_owner_rele(lop);
13759 			*lopp = NULL;
13760 			if (osp != NULL) {
13761 				open_stream_rele(osp, rp);
13762 				*ospp = NULL;
13763 			}
13764 			if (oop != NULL) {
13765 				nfs4_end_open_seqid_sync(oop);
13766 				open_owner_rele(oop);
13767 				*oopp = NULL;
13768 			}
13769 
13770 			nfs_rw_exit(&rp->r_lkserlock);
13771 
13772 			intr = nfs4_block_and_wait(tick_delayp, rp);
13773 
13774 			if (intr) {
13775 				(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13776 				    RW_WRITER, FALSE);
13777 				*errorp = EINTR;
13778 				return (FALSE);
13779 			}
13780 
13781 			(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13782 			    RW_WRITER, FALSE);
13783 
13784 			/*
13785 			 * Make sure we are still safe to lock with
13786 			 * regards to mmapping.
13787 			 */
13788 			if (!nfs4_safelock(vp, flk, cr)) {
13789 				*errorp = EAGAIN;
13790 				return (FALSE);
13791 			}
13792 
13793 			return (TRUE);
13794 		}
13795 		if (ctype == NFS4_LCK_CTYPE_NORM)
13796 			*errorp = EAGAIN;
13797 		*skip_get_err = TRUE;
13798 		flk->l_whence = 0;
13799 		*whencep = 0;
13800 		return (FALSE);
13801 	} else if (lockt_args) {
13802 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13803 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
13804 
13805 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
13806 		    flk, lockt_args);
13807 
13808 		/* according to NLM code */
13809 		*errorp = 0;
13810 		*whencep = 0;
13811 		*skip_get_err = TRUE;
13812 		return (FALSE);
13813 	}
13814 	return (FALSE);
13815 }
13816 
13817 /*
13818  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
13819  */
13820 static void
13821 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
13822 {
13823 	switch (resp->status) {
13824 	case NFS4ERR_ACCESS:
13825 	case NFS4ERR_ADMIN_REVOKED:
13826 	case NFS4ERR_BADHANDLE:
13827 	case NFS4ERR_BAD_RANGE:
13828 	case NFS4ERR_BAD_SEQID:
13829 	case NFS4ERR_BAD_STATEID:
13830 	case NFS4ERR_BADXDR:
13831 	case NFS4ERR_DEADLOCK:
13832 	case NFS4ERR_DELAY:
13833 	case NFS4ERR_EXPIRED:
13834 	case NFS4ERR_FHEXPIRED:
13835 	case NFS4ERR_GRACE:
13836 	case NFS4ERR_INVAL:
13837 	case NFS4ERR_ISDIR:
13838 	case NFS4ERR_LEASE_MOVED:
13839 	case NFS4ERR_LOCK_NOTSUPP:
13840 	case NFS4ERR_LOCK_RANGE:
13841 	case NFS4ERR_MOVED:
13842 	case NFS4ERR_NOFILEHANDLE:
13843 	case NFS4ERR_NO_GRACE:
13844 	case NFS4ERR_OLD_STATEID:
13845 	case NFS4ERR_OPENMODE:
13846 	case NFS4ERR_RECLAIM_BAD:
13847 	case NFS4ERR_RECLAIM_CONFLICT:
13848 	case NFS4ERR_RESOURCE:
13849 	case NFS4ERR_SERVERFAULT:
13850 	case NFS4ERR_STALE:
13851 	case NFS4ERR_STALE_CLIENTID:
13852 	case NFS4ERR_STALE_STATEID:
13853 		return;
13854 	default:
13855 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13856 		    "nfs4frlock_results_default: got unrecognizable "
13857 		    "res.status %d", resp->status));
13858 		*errorp = NFS4ERR_INVAL;
13859 	}
13860 }
13861 
13862 /*
13863  * The lock request was successful, so update the client's state.
13864  */
13865 static void
13866 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
13867     LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
13868     vnode_t *vp, flock64_t *flk, cred_t *cr,
13869     nfs4_lost_rqst_t *resend_rqstp)
13870 {
13871 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13872 
13873 	if (lock_args) {
13874 		LOCK4res *lock_res;
13875 
13876 		lock_res = &resop->nfs_resop4_u.oplock;
13877 		/* update the stateid with server's response */
13878 
13879 		if (lock_args->locker.new_lock_owner == TRUE) {
13880 			mutex_enter(&lop->lo_lock);
13881 			lop->lo_just_created = NFS4_PERM_CREATED;
13882 			mutex_exit(&lop->lo_lock);
13883 		}
13884 
13885 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
13886 
13887 		/*
13888 		 * If the lock was the result of a resending a lost
13889 		 * request, we've synched up the stateid and seqid
13890 		 * with the server, but now the server might be out of sync
13891 		 * with what the application thinks it has for locks.
13892 		 * Clean that up here.  It's unclear whether we should do
13893 		 * this even if the filesystem has been forcibly unmounted.
13894 		 * For most servers, it's probably wasted effort, but
13895 		 * RFC3530 lets servers require that unlocks exactly match
13896 		 * the locks that are held.
13897 		 */
13898 		if (resend_rqstp != NULL &&
13899 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
13900 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
13901 		} else {
13902 			flk->l_whence = 0;
13903 		}
13904 	} else if (locku_args) {
13905 		LOCKU4res *locku_res;
13906 
13907 		locku_res = &resop->nfs_resop4_u.oplocku;
13908 
13909 		/* Update the stateid with the server's response */
13910 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
13911 	} else if (lockt_args) {
13912 		/* Switch the lock type to express success, see fcntl */
13913 		flk->l_type = F_UNLCK;
13914 		flk->l_whence = 0;
13915 	}
13916 }
13917 
13918 /*
13919  * Do final cleanup before exiting nfs4frlock.
13920  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13921  * COMPOUND4 args/res for calls that haven't already.
13922  */
13923 static void
13924 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
13925     COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
13926     nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
13927     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13928     short whence, u_offset_t offset, struct lm_sysid *ls,
13929     int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
13930     bool_t did_start_fop, bool_t skip_get_err,
13931     cred_t *cred_otw, cred_t *cred)
13932 {
13933 	mntinfo4_t	*mi = VTOMI4(vp);
13934 	rnode4_t	*rp = VTOR4(vp);
13935 	int		error = *errorp;
13936 	nfs_argop4	*argop;
13937 
13938 	ASSERT(nfs_zone() == mi->mi_zone);
13939 	/*
13940 	 * The client recovery code wants the raw status information,
13941 	 * so don't map the NFS status code to an errno value for
13942 	 * non-normal call types.
13943 	 */
13944 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13945 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
13946 			*errorp = geterrno4(resp->status);
13947 		if (did_start_fop == TRUE)
13948 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
13949 			    needrecov);
13950 
13951 		/*
13952 		 * We've established a new lock on the server, so invalidate
13953 		 * the pages associated with the vnode to get the most up to
13954 		 * date pages from the server after acquiring the lock. We
13955 		 * want to be sure that the read operation gets the newest data.
13956 		 * N.B.
13957 		 * We used to do this in nfs4frlock_results_ok but that doesn't
13958 		 * work since VOP_PUTPAGE can call nfs4_commit which calls
13959 		 * nfs4_start_fop. We flush the pages below after calling
13960 		 * nfs4_end_fop above
13961 		 */
13962 		if (!error && resp && resp->status == NFS4_OK) {
13963 			int error;
13964 
13965 			error = VOP_PUTPAGE(vp, (u_offset_t)0,
13966 			    0, B_INVAL, cred, NULL);
13967 
13968 			if (error && (error == ENOSPC || error == EDQUOT)) {
13969 				rnode4_t *rp = VTOR4(vp);
13970 
13971 				mutex_enter(&rp->r_statelock);
13972 				if (!rp->r_error)
13973 					rp->r_error = error;
13974 				mutex_exit(&rp->r_statelock);
13975 			}
13976 		}
13977 	}
13978 	if (argsp) {
13979 		ASSERT(argsp->array_len == 2);
13980 		argop = argsp->array;
13981 		if (argop[1].argop == OP_LOCK)
13982 			nfs4args_lock_free(&argop[1]);
13983 		else if (argop[1].argop == OP_LOCKT)
13984 			nfs4args_lockt_free(&argop[1]);
13985 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13986 		if (resp)
13987 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
13988 	}
13989 
13990 	/* free the reference on the lock owner */
13991 	if (lop != NULL) {
13992 		nfs4_end_lock_seqid_sync(lop);
13993 		lock_owner_rele(lop);
13994 	}
13995 
13996 	/* need to free up the reference on osp for lock args */
13997 	if (osp != NULL)
13998 		open_stream_rele(osp, rp);
13999 
14000 	/* need to free up the reference on oop for lock args */
14001 	if (oop != NULL) {
14002 		nfs4_end_open_seqid_sync(oop);
14003 		open_owner_rele(oop);
14004 	}
14005 
14006 	(void) convoff(vp, flk, whence, offset);
14007 
14008 	lm_rel_sysid(ls);
14009 
14010 	/*
14011 	 * Record debug information in the event we get EINVAL.
14012 	 */
14013 	mutex_enter(&mi->mi_lock);
14014 	if (*errorp == EINVAL && (lock_args || locku_args) &&
14015 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
14016 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
14017 			zcmn_err(getzoneid(), CE_NOTE,
14018 			    "%s operation failed with "
14019 			    "EINVAL probably since the server, %s,"
14020 			    " doesn't support POSIX style locking",
14021 			    lock_args ? "LOCK" : "LOCKU",
14022 			    mi->mi_curr_serv->sv_hostname);
14023 			mi->mi_flags |= MI4_LOCK_DEBUG;
14024 		}
14025 	}
14026 	mutex_exit(&mi->mi_lock);
14027 
14028 	if (cred_otw)
14029 		crfree(cred_otw);
14030 }
14031 
14032 /*
14033  * This calls the server and the local locking code.
14034  *
14035  * Client locks are registerred locally by oring the sysid with
14036  * LM_SYSID_CLIENT. The server registers locks locally using just the sysid.
14037  * We need to distinguish between the two to avoid collision in case one
14038  * machine is used as both client and server.
14039  *
14040  * Blocking lock requests will continually retry to acquire the lock
14041  * forever.
14042  *
14043  * The ctype is defined as follows:
14044  * NFS4_LCK_CTYPE_NORM: normal lock request.
14045  *
14046  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
14047  * recovery, get the pid from flk instead of curproc, and don't reregister
14048  * the lock locally.
14049  *
14050  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
14051  * that we will use the information passed in via resend_rqstp to setup the
14052  * lock/locku request.  This resend is the exact same request as the 'lost
14053  * lock', and is initiated by the recovery framework. A successful resend
14054  * request can initiate one or more reinstate requests.
14055  *
14056  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14057  * does not trigger additional reinstate requests.  This lock call type is
14058  * set for setting the v4 server's locking state back to match what the
14059  * client's local locking state is in the event of a received 'lost lock'.
14060  *
14061  * Errors are returned via the nfs4_error_t parameter.
14062  */
14063 void
14064 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14065     int flag, u_offset_t offset, cred_t *cr, nfs4_error_t *ep,
14066     nfs4_lost_rqst_t *resend_rqstp, int *did_reclaimp)
14067 {
14068 	COMPOUND4args_clnt	args, *argsp = NULL;
14069 	COMPOUND4res_clnt	res, *resp = NULL;
14070 	nfs_argop4	*argop;
14071 	nfs_resop4	*resop;
14072 	rnode4_t	*rp;
14073 	int		doqueue = 1;
14074 	clock_t		tick_delay;  /* delay in clock ticks */
14075 	struct lm_sysid	*ls;
14076 	LOCK4args	*lock_args = NULL;
14077 	LOCKU4args	*locku_args = NULL;
14078 	LOCKT4args	*lockt_args = NULL;
14079 	nfs4_open_owner_t *oop = NULL;
14080 	nfs4_open_stream_t *osp = NULL;
14081 	nfs4_lock_owner_t *lop = NULL;
14082 	bool_t		needrecov = FALSE;
14083 	nfs4_recov_state_t recov_state;
14084 	short		whence;
14085 	nfs4_op_hint_t	op_hint;
14086 	nfs4_lost_rqst_t lost_rqst;
14087 	bool_t		retry = FALSE;
14088 	bool_t		did_start_fop = FALSE;
14089 	bool_t		skip_get_err = FALSE;
14090 	cred_t		*cred_otw = NULL;
14091 	bool_t		recovonly;	/* just queue request */
14092 	int		frc_no_reclaim = 0;
14093 #ifdef DEBUG
14094 	char *name;
14095 #endif
14096 
14097 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14098 
14099 #ifdef DEBUG
14100 	name = fn_name(VTOSV(vp)->sv_name);
14101 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14102 	    "%s: cmd %d, type %d, offset %llu, start %"PRIx64", "
14103 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14104 	    "resend request %s", name, cmd, flk->l_type, offset, flk->l_start,
14105 	    flk->l_len, ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid :
14106 	    flk->l_pid, flk->l_sysid, nfs4frlock_get_call_type(ctype),
14107 	    resend_rqstp ? "TRUE" : "FALSE"));
14108 	kmem_free(name, MAXNAMELEN);
14109 #endif
14110 
14111 	nfs4_error_zinit(ep);
14112 	ep->error = nfs4frlock_validate_args(cmd, flk, flag, vp, offset);
14113 	if (ep->error)
14114 		return;
14115 	ep->error = nfs4frlock_get_sysid(&ls, vp, flk);
14116 	if (ep->error)
14117 		return;
14118 	nfs4frlock_pre_setup(&tick_delay, &recov_state, flk, &whence,
14119 	    vp, cr, &cred_otw);
14120 
14121 recov_retry:
14122 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14123 	    &retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14124 	rp = VTOR4(vp);
14125 
14126 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14127 	    &did_start_fop, &recovonly);
14128 
14129 	if (ep->error)
14130 		goto out;
14131 
14132 	if (recovonly) {
14133 		/*
14134 		 * Leave the request for the recovery system to deal with.
14135 		 */
14136 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14137 		ASSERT(cmd != F_GETLK);
14138 		ASSERT(flk->l_type == F_UNLCK);
14139 
14140 		nfs4_error_init(ep, EINTR);
14141 		needrecov = TRUE;
14142 		lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14143 		if (lop != NULL) {
14144 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14145 			    NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14146 			(void) nfs4_start_recovery(ep,
14147 			    VTOMI4(vp), vp, NULL, NULL,
14148 			    (lost_rqst.lr_op == OP_LOCK ||
14149 			    lost_rqst.lr_op == OP_LOCKU) ?
14150 			    &lost_rqst : NULL, OP_LOCKU, NULL);
14151 			lock_owner_rele(lop);
14152 			lop = NULL;
14153 		}
14154 		flk->l_pid = curproc->p_pid;
14155 		nfs4_register_lock_locally(vp, flk, flag, offset);
14156 		goto out;
14157 	}
14158 
14159 	/* putfh directory fh */
14160 	argop[0].argop = OP_CPUTFH;
14161 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14162 
14163 	/*
14164 	 * Set up the over-the-wire arguments and get references to the
14165 	 * open owner, etc.
14166 	 */
14167 
14168 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14169 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14170 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14171 		    &argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14172 	} else {
14173 		bool_t go_otw = TRUE;
14174 
14175 		ASSERT(resend_rqstp == NULL);
14176 
14177 		switch (cmd) {
14178 		case F_GETLK:
14179 		case F_O_GETLK:
14180 			nfs4frlock_setup_lockt_args(ctype, &argop[1],
14181 			    &lockt_args, argsp, flk, rp);
14182 			break;
14183 		case F_SETLKW:
14184 		case F_SETLK:
14185 			if (flk->l_type == F_UNLCK)
14186 				nfs4frlock_setup_locku_args(ctype,
14187 				    &argop[1], &locku_args, flk,
14188 				    &lop, ep, argsp,
14189 				    vp, flag, offset, cr,
14190 				    &skip_get_err, &go_otw);
14191 			else
14192 				nfs4frlock_setup_lock_args(ctype,
14193 				    &lock_args, &oop, &osp, &lop, &argop[1],
14194 				    argsp, flk, cmd, vp, cr, ep);
14195 
14196 			if (ep->error)
14197 				goto out;
14198 
14199 			switch (ep->stat) {
14200 			case NFS4_OK:
14201 				break;
14202 			case NFS4ERR_DELAY:
14203 				/* recov thread never gets this error */
14204 				ASSERT(resend_rqstp == NULL);
14205 				ASSERT(did_start_fop);
14206 
14207 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14208 				    &recov_state, TRUE);
14209 				did_start_fop = FALSE;
14210 				if (argop[1].argop == OP_LOCK)
14211 					nfs4args_lock_free(&argop[1]);
14212 				else if (argop[1].argop == OP_LOCKT)
14213 					nfs4args_lockt_free(&argop[1]);
14214 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14215 				argsp = NULL;
14216 				goto recov_retry;
14217 			default:
14218 				ep->error = EIO;
14219 				goto out;
14220 			}
14221 			break;
14222 		default:
14223 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14224 			    "nfs4_frlock: invalid cmd %d", cmd));
14225 			ep->error = EINVAL;
14226 			goto out;
14227 		}
14228 
14229 		if (!go_otw)
14230 			goto out;
14231 	}
14232 
14233 	/* XXX should we use the local reclock as a cache ? */
14234 	/*
14235 	 * Unregister the lock with the local locking code before
14236 	 * contacting the server.  This avoids a potential race where
14237 	 * another process gets notified that it has been granted a lock
14238 	 * before we can unregister ourselves locally.
14239 	 */
14240 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK) {
14241 		if (ctype == NFS4_LCK_CTYPE_NORM)
14242 			flk->l_pid = ttoproc(curthread)->p_pid;
14243 		nfs4_register_lock_locally(vp, flk, flag, offset);
14244 	}
14245 
14246 	/*
14247 	 * Send the server the lock request.  Continually loop with a delay
14248 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14249 	 */
14250 	resp = &res;
14251 
14252 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14253 	    (CE_NOTE,
14254 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14255 	    rnode4info(rp)));
14256 
14257 	if (lock_args && frc_no_reclaim) {
14258 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14259 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14260 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14261 		lock_args->reclaim = FALSE;
14262 		if (did_reclaimp)
14263 			*did_reclaimp = 0;
14264 	}
14265 
14266 	/*
14267 	 * Do the OTW call.
14268 	 */
14269 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14270 
14271 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14272 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14273 
14274 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14275 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14276 	    "nfs4frlock: needrecov %d", needrecov));
14277 
14278 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14279 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14280 		    args.ctag);
14281 
14282 	/*
14283 	 * Check if one of these mutually exclusive error cases has
14284 	 * happened:
14285 	 *   need to swap credentials due to access error
14286 	 *   recovery is needed
14287 	 *   different error (only known case is missing Kerberos ticket)
14288 	 */
14289 
14290 	if ((ep->error == EACCES ||
14291 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14292 	    cred_otw != cr) {
14293 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14294 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14295 		    cr, &cred_otw);
14296 		goto recov_retry;
14297 	}
14298 
14299 	if (needrecov) {
14300 		/*
14301 		 * LOCKT requests don't need to recover from lost
14302 		 * requests since they don't create/modify state.
14303 		 */
14304 		if ((ep->error == EINTR ||
14305 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14306 		    lockt_args)
14307 			goto out;
14308 		/*
14309 		 * Do not attempt recovery for requests initiated by
14310 		 * the recovery framework.  Let the framework redrive them.
14311 		 */
14312 		if (ctype != NFS4_LCK_CTYPE_NORM)
14313 			goto out;
14314 		else {
14315 			ASSERT(resend_rqstp == NULL);
14316 		}
14317 
14318 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14319 		    flk_to_locktype(cmd, flk->l_type),
14320 		    oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14321 
14322 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14323 		    &resp, lock_args, locku_args, &oop, &osp, &lop,
14324 		    rp, vp, &recov_state, op_hint, &did_start_fop,
14325 		    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14326 
14327 		if (retry) {
14328 			ASSERT(oop == NULL);
14329 			ASSERT(osp == NULL);
14330 			ASSERT(lop == NULL);
14331 			goto recov_retry;
14332 		}
14333 		goto out;
14334 	}
14335 
14336 	/*
14337 	 * Bail out if have reached this point with ep->error set. Can
14338 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14339 	 * This happens if Kerberos ticket has expired or has been
14340 	 * destroyed.
14341 	 */
14342 	if (ep->error != 0)
14343 		goto out;
14344 
14345 	/*
14346 	 * Process the reply.
14347 	 */
14348 	switch (resp->status) {
14349 	case NFS4_OK:
14350 		resop = &resp->array[1];
14351 		nfs4frlock_results_ok(ctype, cmd, flk, vp, flag, offset,
14352 		    resend_rqstp);
14353 		/*
14354 		 * Have a successful lock operation, now update state.
14355 		 */
14356 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14357 		    resop, lop, vp, flk, cr, resend_rqstp);
14358 		break;
14359 
14360 	case NFS4ERR_DENIED:
14361 		resop = &resp->array[1];
14362 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14363 		    &oop, &osp, &lop, cmd, vp, flk, op_hint,
14364 		    &recov_state, needrecov, &argsp, &resp,
14365 		    &tick_delay, &whence, &ep->error, resop, cr,
14366 		    &did_start_fop, &skip_get_err);
14367 
14368 		if (retry) {
14369 			ASSERT(oop == NULL);
14370 			ASSERT(osp == NULL);
14371 			ASSERT(lop == NULL);
14372 			goto recov_retry;
14373 		}
14374 		break;
14375 	/*
14376 	 * If the server won't let us reclaim, fall-back to trying to lock
14377 	 * the file from scratch. Code elsewhere will check the changeinfo
14378 	 * to ensure the file hasn't been changed.
14379 	 */
14380 	case NFS4ERR_NO_GRACE:
14381 		if (lock_args && lock_args->reclaim == TRUE) {
14382 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14383 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14384 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14385 			frc_no_reclaim = 1;
14386 			/* clean up before retrying */
14387 			needrecov = 0;
14388 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14389 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14390 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14391 			goto recov_retry;
14392 		}
14393 		/* FALLTHROUGH */
14394 
14395 	default:
14396 		nfs4frlock_results_default(resp, &ep->error);
14397 		break;
14398 	}
14399 out:
14400 	/*
14401 	 * Process and cleanup from error.  Make interrupted unlock
14402 	 * requests look successful, since they will be handled by the
14403 	 * client recovery code.
14404 	 */
14405 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14406 	    needrecov, oop, osp, lop, flk, whence, offset, ls, &ep->error,
14407 	    lock_args, locku_args, did_start_fop,
14408 	    skip_get_err, cred_otw, cr);
14409 
14410 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14411 	    (cmd == F_SETLK || cmd == F_SETLKW))
14412 		ep->error = 0;
14413 }
14414 
14415 /*
14416  * nfs4_safelock:
14417  *
14418  * Return non-zero if the given lock request can be handled without
14419  * violating the constraints on concurrent mapping and locking.
14420  */
14421 
14422 static int
14423 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14424 {
14425 	rnode4_t *rp = VTOR4(vp);
14426 	struct vattr va;
14427 	int error;
14428 
14429 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14430 	ASSERT(rp->r_mapcnt >= 0);
14431 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14432 	    "(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14433 	    "write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14434 	    bfp->l_start, bfp->l_len, rp->r_mapcnt));
14435 
14436 	if (rp->r_mapcnt == 0)
14437 		return (1);		/* always safe if not mapped */
14438 
14439 	/*
14440 	 * If the file is already mapped and there are locks, then they
14441 	 * should be all safe locks.  So adding or removing a lock is safe
14442 	 * as long as the new request is safe (i.e., whole-file, meaning
14443 	 * length and starting offset are both zero).
14444 	 */
14445 
14446 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14447 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14448 		    "cannot lock a memory mapped file unless locking the "
14449 		    "entire file: start %"PRIx64", len %"PRIx64,
14450 		    bfp->l_start, bfp->l_len));
14451 		return (0);
14452 	}
14453 
14454 	/* mandatory locking and mapping don't mix */
14455 	va.va_mask = AT_MODE;
14456 	error = VOP_GETATTR(vp, &va, 0, cr, NULL);
14457 	if (error != 0) {
14458 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14459 		    "getattr error %d", error));
14460 		return (0);		/* treat errors conservatively */
14461 	}
14462 	if (MANDLOCK(vp, va.va_mode)) {
14463 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14464 		    "cannot mandatory lock and mmap a file"));
14465 		return (0);
14466 	}
14467 
14468 	return (1);
14469 }
14470 
14471 
14472 /*
14473  * Register the lock locally within Solaris.
14474  * As the client, we "or" the sysid with LM_SYSID_CLIENT when
14475  * recording locks locally.
14476  *
14477  * This should handle conflicts/cooperation with NFS v2/v3 since all locks
14478  * are registered locally.
14479  */
14480 void
14481 nfs4_register_lock_locally(vnode_t *vp, struct flock64 *flk, int flag,
14482     u_offset_t offset)
14483 {
14484 	int oldsysid;
14485 	int error;
14486 #ifdef DEBUG
14487 	char *name;
14488 #endif
14489 
14490 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14491 
14492 #ifdef DEBUG
14493 	name = fn_name(VTOSV(vp)->sv_name);
14494 	NFS4_DEBUG(nfs4_client_lock_debug,
14495 	    (CE_NOTE, "nfs4_register_lock_locally: %s: type %d, "
14496 	    "start %"PRIx64", length %"PRIx64", pid %ld, sysid %d",
14497 	    name, flk->l_type, flk->l_start, flk->l_len, (long)flk->l_pid,
14498 	    flk->l_sysid));
14499 	kmem_free(name, MAXNAMELEN);
14500 #endif
14501 
14502 	/* register the lock with local locking */
14503 	oldsysid = flk->l_sysid;
14504 	flk->l_sysid |= LM_SYSID_CLIENT;
14505 	error = reclock(vp, flk, SETFLCK, flag, offset, NULL);
14506 #ifdef DEBUG
14507 	if (error != 0) {
14508 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14509 		    "nfs4_register_lock_locally: could not register with"
14510 		    " local locking"));
14511 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14512 		    "error %d, vp 0x%p, pid %d, sysid 0x%x",
14513 		    error, (void *)vp, flk->l_pid, flk->l_sysid));
14514 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14515 		    "type %d off 0x%" PRIx64 " len 0x%" PRIx64,
14516 		    flk->l_type, flk->l_start, flk->l_len));
14517 		(void) reclock(vp, flk, 0, flag, offset, NULL);
14518 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14519 		    "blocked by pid %d sysid 0x%x type %d "
14520 		    "off 0x%" PRIx64 " len 0x%" PRIx64,
14521 		    flk->l_pid, flk->l_sysid, flk->l_type, flk->l_start,
14522 		    flk->l_len));
14523 	}
14524 #endif
14525 	flk->l_sysid = oldsysid;
14526 }
14527 
14528 /*
14529  * nfs4_lockrelease:
14530  *
14531  * Release any locks on the given vnode that are held by the current
14532  * process.  Also removes the lock owner (if one exists) from the rnode's
14533  * list.
14534  */
14535 static int
14536 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14537 {
14538 	flock64_t ld;
14539 	int ret, error;
14540 	rnode4_t *rp;
14541 	nfs4_lock_owner_t *lop;
14542 	nfs4_recov_state_t recov_state;
14543 	mntinfo4_t *mi;
14544 	bool_t possible_orphan = FALSE;
14545 	bool_t recovonly;
14546 
14547 	ASSERT((uintptr_t)vp > KERNELBASE);
14548 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14549 
14550 	rp = VTOR4(vp);
14551 	mi = VTOMI4(vp);
14552 
14553 	/*
14554 	 * If we have not locked anything then we can
14555 	 * just return since we have no work to do.
14556 	 */
14557 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14558 		return (0);
14559 	}
14560 
14561 	/*
14562 	 * We need to comprehend that another thread may
14563 	 * kick off recovery and the lock_owner we have stashed
14564 	 * in lop might be invalid so we should NOT cache it
14565 	 * locally!
14566 	 */
14567 	recov_state.rs_flags = 0;
14568 	recov_state.rs_num_retry_despite_err = 0;
14569 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14570 	    &recovonly);
14571 	if (error) {
14572 		mutex_enter(&rp->r_statelock);
14573 		rp->r_flags |= R4LODANGLERS;
14574 		mutex_exit(&rp->r_statelock);
14575 		return (error);
14576 	}
14577 
14578 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14579 
14580 	/*
14581 	 * Check if the lock owner might have a lock (request was sent but
14582 	 * no response was received).  Also check if there are any remote
14583 	 * locks on the file.  (In theory we shouldn't have to make this
14584 	 * second check if there's no lock owner, but for now we'll be
14585 	 * conservative and do it anyway.)  If either condition is true,
14586 	 * send an unlock for the entire file to the server.
14587 	 *
14588 	 * Note that no explicit synchronization is needed here.  At worst,
14589 	 * flk_has_remote_locks() will return a false positive, in which case
14590 	 * the unlock call wastes time but doesn't harm correctness.
14591 	 */
14592 
14593 	if (lop) {
14594 		mutex_enter(&lop->lo_lock);
14595 		possible_orphan = lop->lo_pending_rqsts;
14596 		mutex_exit(&lop->lo_lock);
14597 		lock_owner_rele(lop);
14598 	}
14599 
14600 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14601 
14602 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14603 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14604 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14605 	    (void *)lop));
14606 
14607 	if (possible_orphan || flk_has_remote_locks(vp)) {
14608 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14609 		ld.l_whence = 0;	/* unlock from start of file */
14610 		ld.l_start = 0;
14611 		ld.l_len = 0;		/* do entire file */
14612 
14613 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL,
14614 		    cr, NULL);
14615 
14616 		if (ret != 0) {
14617 			/*
14618 			 * If VOP_FRLOCK fails, make sure we unregister
14619 			 * local locks before we continue.
14620 			 */
14621 			ld.l_pid = ttoproc(curthread)->p_pid;
14622 			nfs4_register_lock_locally(vp, &ld, flag, offset);
14623 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14624 			    "nfs4_lockrelease: lock release error on vp"
14625 			    " %p: error %d.\n", (void *)vp, ret));
14626 		}
14627 	}
14628 
14629 	recov_state.rs_flags = 0;
14630 	recov_state.rs_num_retry_despite_err = 0;
14631 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14632 	    &recovonly);
14633 	if (error) {
14634 		mutex_enter(&rp->r_statelock);
14635 		rp->r_flags |= R4LODANGLERS;
14636 		mutex_exit(&rp->r_statelock);
14637 		return (error);
14638 	}
14639 
14640 	/*
14641 	 * So, here we're going to need to retrieve the lock-owner
14642 	 * again (in case recovery has done a switch-a-roo) and
14643 	 * remove it because we can.
14644 	 */
14645 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14646 
14647 	if (lop) {
14648 		nfs4_rnode_remove_lock_owner(rp, lop);
14649 		lock_owner_rele(lop);
14650 	}
14651 
14652 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14653 	return (0);
14654 }
14655 
14656 /*
14657  * Wait for 'tick_delay' clock ticks.
14658  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14659  * NOTE: lock_lease_time is in seconds.
14660  *
14661  * XXX For future improvements, should implement a waiting queue scheme.
14662  */
14663 static int
14664 nfs4_block_and_wait(clock_t *tick_delay, rnode4_t *rp)
14665 {
14666 	long milliseconds_delay;
14667 	time_t lock_lease_time;
14668 
14669 	/* wait tick_delay clock ticks or siginteruptus */
14670 	if (delay_sig(*tick_delay)) {
14671 		return (EINTR);
14672 	}
14673 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14674 	    "reissue the lock request: blocked for %ld clock ticks: %ld "
14675 	    "milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14676 
14677 	/* get the lease time */
14678 	lock_lease_time = r2lease_time(rp);
14679 
14680 	/* drv_hztousec converts ticks to microseconds */
14681 	milliseconds_delay = drv_hztousec(*tick_delay) / 1000;
14682 	if (milliseconds_delay < lock_lease_time * 1000) {
14683 		*tick_delay = 2 * *tick_delay;
14684 		if (drv_hztousec(*tick_delay) > lock_lease_time * 1000 * 1000)
14685 			*tick_delay = drv_usectohz(lock_lease_time*1000*1000);
14686 	}
14687 	return (0);
14688 }
14689 
14690 
14691 void
14692 nfs4_vnops_init(void)
14693 {
14694 }
14695 
14696 void
14697 nfs4_vnops_fini(void)
14698 {
14699 }
14700 
14701 /*
14702  * Return a reference to the directory (parent) vnode for a given vnode,
14703  * using the saved pathname information and the directory file handle.  The
14704  * caller is responsible for disposing of the reference.
14705  * Returns zero or an errno value.
14706  *
14707  * Caller should set need_start_op to FALSE if it is the recovery
14708  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14709  */
14710 int
14711 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14712 {
14713 	svnode_t *svnp;
14714 	vnode_t *dvp = NULL;
14715 	servinfo4_t *svp;
14716 	nfs4_fname_t *mfname;
14717 	int error;
14718 
14719 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14720 
14721 	if (vp->v_flag & VROOT) {
14722 		nfs4_sharedfh_t *sfh;
14723 		nfs_fh4 fh;
14724 		mntinfo4_t *mi;
14725 
14726 		ASSERT(vp->v_type == VREG);
14727 
14728 		mi = VTOMI4(vp);
14729 		svp = mi->mi_curr_serv;
14730 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14731 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14732 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14733 		sfh = sfh4_get(&fh, VTOMI4(vp));
14734 		nfs_rw_exit(&svp->sv_lock);
14735 		mfname = mi->mi_fname;
14736 		fn_hold(mfname);
14737 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14738 		sfh4_rele(&sfh);
14739 
14740 		if (dvp->v_type == VNON)
14741 			dvp->v_type = VDIR;
14742 		*dvpp = dvp;
14743 		return (0);
14744 	}
14745 
14746 	svnp = VTOSV(vp);
14747 
14748 	if (svnp == NULL) {
14749 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14750 		    "shadow node is NULL"));
14751 		return (EINVAL);
14752 	}
14753 
14754 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14755 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14756 		    "shadow node name or dfh val == NULL"));
14757 		return (EINVAL);
14758 	}
14759 
14760 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14761 	    (int)need_start_op);
14762 	if (error != 0) {
14763 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14764 		    "nfs4_make_dotdot returned %d", error));
14765 		return (error);
14766 	}
14767 	if (!dvp) {
14768 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14769 		    "nfs4_make_dotdot returned a NULL dvp"));
14770 		return (EIO);
14771 	}
14772 	if (dvp->v_type == VNON)
14773 		dvp->v_type = VDIR;
14774 	ASSERT(dvp->v_type == VDIR);
14775 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14776 		mutex_enter(&dvp->v_lock);
14777 		dvp->v_flag |= V_XATTRDIR;
14778 		mutex_exit(&dvp->v_lock);
14779 	}
14780 	*dvpp = dvp;
14781 	return (0);
14782 }
14783 
14784 /*
14785  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14786  * length that fnamep can accept, including the trailing null.
14787  * Returns 0 if okay, returns an errno value if there was a problem.
14788  */
14789 
14790 int
14791 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14792 {
14793 	char *fn;
14794 	int err = 0;
14795 	servinfo4_t *svp;
14796 	svnode_t *shvp;
14797 
14798 	/*
14799 	 * If the file being opened has VROOT set, then this is
14800 	 * a "file" mount.  sv_name will not be interesting, so
14801 	 * go back to the servinfo4 to get the original mount
14802 	 * path and strip off all but the final edge.  Otherwise
14803 	 * just return the name from the shadow vnode.
14804 	 */
14805 
14806 	if (vp->v_flag & VROOT) {
14807 
14808 		svp = VTOMI4(vp)->mi_curr_serv;
14809 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14810 
14811 		fn = strrchr(svp->sv_path, '/');
14812 		if (fn == NULL)
14813 			err = EINVAL;
14814 		else
14815 			fn++;
14816 	} else {
14817 		shvp = VTOSV(vp);
14818 		fn = fn_name(shvp->sv_name);
14819 	}
14820 
14821 	if (err == 0)
14822 		if (strlen(fn) < maxlen)
14823 			(void) strcpy(fnamep, fn);
14824 		else
14825 			err = ENAMETOOLONG;
14826 
14827 	if (vp->v_flag & VROOT)
14828 		nfs_rw_exit(&svp->sv_lock);
14829 	else
14830 		kmem_free(fn, MAXNAMELEN);
14831 
14832 	return (err);
14833 }
14834 
14835 /*
14836  * Bookkeeping for a close that doesn't need to go over the wire.
14837  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14838  * it is left at 1.
14839  */
14840 void
14841 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14842 {
14843 	rnode4_t		*rp;
14844 	mntinfo4_t		*mi;
14845 
14846 	mi = VTOMI4(vp);
14847 	rp = VTOR4(vp);
14848 
14849 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14850 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14851 	ASSERT(nfs_zone() == mi->mi_zone);
14852 	ASSERT(mutex_owned(&osp->os_sync_lock));
14853 	ASSERT(*have_lockp);
14854 
14855 	if (!osp->os_valid ||
14856 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14857 		return;
14858 	}
14859 
14860 	/*
14861 	 * This removes the reference obtained at OPEN; ie,
14862 	 * when the open stream structure was created.
14863 	 *
14864 	 * We don't have to worry about calling 'open_stream_rele'
14865 	 * since we our currently holding a reference to this
14866 	 * open stream which means the count can not go to 0 with
14867 	 * this decrement.
14868 	 */
14869 	ASSERT(osp->os_ref_count >= 2);
14870 	osp->os_ref_count--;
14871 	osp->os_valid = 0;
14872 	mutex_exit(&osp->os_sync_lock);
14873 	*have_lockp = 0;
14874 
14875 	nfs4_dec_state_ref_count(mi);
14876 }
14877 
14878 /*
14879  * Close all remaining open streams on the rnode.  These open streams
14880  * could be here because:
14881  * - The close attempted at either close or delmap failed
14882  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
14883  * - Someone did mknod on a regular file but never opened it
14884  */
14885 int
14886 nfs4close_all(vnode_t *vp, cred_t *cr)
14887 {
14888 	nfs4_open_stream_t *osp;
14889 	int error;
14890 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
14891 	rnode4_t *rp;
14892 
14893 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14894 
14895 	error = 0;
14896 	rp = VTOR4(vp);
14897 
14898 	/*
14899 	 * At this point, all we know is that the last time
14900 	 * someone called vn_rele, the count was 1.  Since then,
14901 	 * the vnode could have been re-activated.  We want to
14902 	 * loop through the open streams and close each one, but
14903 	 * we have to be careful since once we release the rnode
14904 	 * hash bucket lock, someone else is free to come in and
14905 	 * re-activate the rnode and add new open streams.  The
14906 	 * strategy is take the rnode hash bucket lock, verify that
14907 	 * the count is still 1, grab the open stream off the
14908 	 * head of the list and mark it invalid, then release the
14909 	 * rnode hash bucket lock and proceed with that open stream.
14910 	 * This is ok because nfs4close_one() will acquire the proper
14911 	 * open/create to close/destroy synchronization for open
14912 	 * streams, and will ensure that if someone has reopened
14913 	 * the open stream after we've dropped the hash bucket lock
14914 	 * then we'll just simply return without destroying the
14915 	 * open stream.
14916 	 * Repeat until the list is empty.
14917 	 */
14918 
14919 	for (;;) {
14920 
14921 		/* make sure vnode hasn't been reactivated */
14922 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
14923 		mutex_enter(&vp->v_lock);
14924 		if (vp->v_count > 1) {
14925 			mutex_exit(&vp->v_lock);
14926 			rw_exit(&rp->r_hashq->r_lock);
14927 			break;
14928 		}
14929 		/*
14930 		 * Grabbing r_os_lock before releasing v_lock prevents
14931 		 * a window where the rnode/open stream could get
14932 		 * reactivated (and os_force_close set to 0) before we
14933 		 * had a chance to set os_force_close to 1.
14934 		 */
14935 		mutex_enter(&rp->r_os_lock);
14936 		mutex_exit(&vp->v_lock);
14937 
14938 		osp = list_head(&rp->r_open_streams);
14939 		if (!osp) {
14940 			/* nothing left to CLOSE OTW, so return */
14941 			mutex_exit(&rp->r_os_lock);
14942 			rw_exit(&rp->r_hashq->r_lock);
14943 			break;
14944 		}
14945 
14946 		mutex_enter(&rp->r_statev4_lock);
14947 		/* the file can't still be mem mapped */
14948 		ASSERT(rp->r_mapcnt == 0);
14949 		if (rp->created_v4)
14950 			rp->created_v4 = 0;
14951 		mutex_exit(&rp->r_statev4_lock);
14952 
14953 		/*
14954 		 * Grab a ref on this open stream; nfs4close_one
14955 		 * will mark it as invalid
14956 		 */
14957 		mutex_enter(&osp->os_sync_lock);
14958 		osp->os_ref_count++;
14959 		osp->os_force_close = 1;
14960 		mutex_exit(&osp->os_sync_lock);
14961 		mutex_exit(&rp->r_os_lock);
14962 		rw_exit(&rp->r_hashq->r_lock);
14963 
14964 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
14965 
14966 		/* Update error if it isn't already non-zero */
14967 		if (error == 0) {
14968 			if (e.error)
14969 				error = e.error;
14970 			else if (e.stat)
14971 				error = geterrno4(e.stat);
14972 		}
14973 
14974 #ifdef	DEBUG
14975 		nfs4close_all_cnt++;
14976 #endif
14977 		/* Release the ref on osp acquired above. */
14978 		open_stream_rele(osp, rp);
14979 
14980 		/* Proceed to the next open stream, if any */
14981 	}
14982 	return (error);
14983 }
14984 
14985 /*
14986  * nfs4close_one - close one open stream for a file if needed.
14987  *
14988  * "close_type" indicates which close path this is:
14989  * CLOSE_NORM: close initiated via VOP_CLOSE.
14990  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
14991  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
14992  *	the close and release of client state for this open stream
14993  *	(unless someone else has the open stream open).
14994  * CLOSE_RESEND: indicates the request is a replay of an earlier request
14995  *	(e.g., due to abort because of a signal).
14996  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
14997  *
14998  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
14999  * recovery.  Instead, the caller is expected to deal with retries.
15000  *
15001  * The caller can either pass in the osp ('provided_osp') or not.
15002  *
15003  * 'access_bits' represents the access we are closing/downgrading.
15004  *
15005  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
15006  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
15007  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
15008  *
15009  * Errors are returned via the nfs4_error_t.
15010  */
15011 void
15012 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
15013     int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
15014     nfs4_close_type_t close_type, size_t len, uint_t maxprot,
15015     uint_t mmap_flags)
15016 {
15017 	nfs4_open_owner_t *oop;
15018 	nfs4_open_stream_t *osp = NULL;
15019 	int retry = 0;
15020 	int num_retries = NFS4_NUM_RECOV_RETRIES;
15021 	rnode4_t *rp;
15022 	mntinfo4_t *mi;
15023 	nfs4_recov_state_t recov_state;
15024 	cred_t *cred_otw = NULL;
15025 	bool_t recovonly = FALSE;
15026 	int isrecov;
15027 	int force_close;
15028 	int close_failed = 0;
15029 	int did_dec_count = 0;
15030 	int did_start_op = 0;
15031 	int did_force_recovlock = 0;
15032 	int did_start_seqid_sync = 0;
15033 	int have_sync_lock = 0;
15034 
15035 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15036 
15037 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
15038 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
15039 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
15040 	    len, maxprot, mmap_flags, access_bits));
15041 
15042 	nfs4_error_zinit(ep);
15043 	rp = VTOR4(vp);
15044 	mi = VTOMI4(vp);
15045 	isrecov = (close_type == CLOSE_RESEND ||
15046 	    close_type == CLOSE_AFTER_RESEND);
15047 
15048 	/*
15049 	 * First get the open owner.
15050 	 */
15051 	if (!provided_osp) {
15052 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
15053 	} else {
15054 		oop = provided_osp->os_open_owner;
15055 		ASSERT(oop != NULL);
15056 		open_owner_hold(oop);
15057 	}
15058 
15059 	if (!oop) {
15060 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15061 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15062 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15063 		    (void *)provided_osp, close_type));
15064 		ep->error = EIO;
15065 		goto out;
15066 	}
15067 
15068 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15069 recov_retry:
15070 	osp = NULL;
15071 	close_failed = 0;
15072 	force_close = (close_type == CLOSE_FORCE);
15073 	retry = 0;
15074 	did_start_op = 0;
15075 	did_force_recovlock = 0;
15076 	did_start_seqid_sync = 0;
15077 	have_sync_lock = 0;
15078 	recovonly = FALSE;
15079 	recov_state.rs_flags = 0;
15080 	recov_state.rs_num_retry_despite_err = 0;
15081 
15082 	/*
15083 	 * Second synchronize with recovery.
15084 	 */
15085 	if (!isrecov) {
15086 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15087 		    &recov_state, &recovonly);
15088 		if (!ep->error) {
15089 			did_start_op = 1;
15090 		} else {
15091 			close_failed = 1;
15092 			/*
15093 			 * If we couldn't get start_fop, but have to
15094 			 * cleanup state, then at least acquire the
15095 			 * mi_recovlock so we can synchronize with
15096 			 * recovery.
15097 			 */
15098 			if (close_type == CLOSE_FORCE) {
15099 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15100 				    RW_READER, FALSE);
15101 				did_force_recovlock = 1;
15102 			} else
15103 				goto out;
15104 		}
15105 	}
15106 
15107 	/*
15108 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15109 	 * set 'recovonly' to TRUE since most likely this is due to
15110 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15111 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15112 	 * to retry, causing us to loop until recovery finishes.  Plus we
15113 	 * don't need protection over the open seqid since we're not going
15114 	 * OTW, hence don't need to use the seqid.
15115 	 */
15116 	if (recovonly == FALSE) {
15117 		/* need to grab the open owner sync before 'os_sync_lock' */
15118 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15119 		if (ep->error == EAGAIN) {
15120 			ASSERT(!isrecov);
15121 			if (did_start_op)
15122 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15123 				    &recov_state, TRUE);
15124 			if (did_force_recovlock)
15125 				nfs_rw_exit(&mi->mi_recovlock);
15126 			goto recov_retry;
15127 		}
15128 		did_start_seqid_sync = 1;
15129 	}
15130 
15131 	/*
15132 	 * Third get an open stream and acquire 'os_sync_lock' to
15133 	 * sychronize the opening/creating of an open stream with the
15134 	 * closing/destroying of an open stream.
15135 	 */
15136 	if (!provided_osp) {
15137 		/* returns with 'os_sync_lock' held */
15138 		osp = find_open_stream(oop, rp);
15139 		if (!osp) {
15140 			ep->error = EIO;
15141 			goto out;
15142 		}
15143 	} else {
15144 		osp = provided_osp;
15145 		open_stream_hold(osp);
15146 		mutex_enter(&osp->os_sync_lock);
15147 	}
15148 	have_sync_lock = 1;
15149 
15150 	ASSERT(oop == osp->os_open_owner);
15151 
15152 	/*
15153 	 * Fourth, do any special pre-OTW CLOSE processing
15154 	 * based on the specific close type.
15155 	 */
15156 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15157 	    !did_dec_count) {
15158 		ASSERT(osp->os_open_ref_count > 0);
15159 		osp->os_open_ref_count--;
15160 		did_dec_count = 1;
15161 		if (osp->os_open_ref_count == 0)
15162 			osp->os_final_close = 1;
15163 	}
15164 
15165 	if (close_type == CLOSE_FORCE) {
15166 		/* see if somebody reopened the open stream. */
15167 		if (!osp->os_force_close) {
15168 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15169 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15170 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15171 			ep->error = 0;
15172 			ep->stat = NFS4_OK;
15173 			goto out;
15174 		}
15175 
15176 		if (!osp->os_final_close && !did_dec_count) {
15177 			osp->os_open_ref_count--;
15178 			did_dec_count = 1;
15179 		}
15180 
15181 		/*
15182 		 * We can't depend on os_open_ref_count being 0 due to the
15183 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15184 		 */
15185 #ifdef	NOTYET
15186 		ASSERT(osp->os_open_ref_count == 0);
15187 #endif
15188 		if (osp->os_open_ref_count != 0) {
15189 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15190 			    "nfs4close_one: should panic here on an "
15191 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15192 			    "since this is probably the exec problem."));
15193 
15194 			osp->os_open_ref_count = 0;
15195 		}
15196 
15197 		/*
15198 		 * There is the possibility that nfs4close_one()
15199 		 * for close_type == CLOSE_DELMAP couldn't find the
15200 		 * open stream, thus couldn't decrement its os_mapcnt;
15201 		 * therefore we can't use this ASSERT yet.
15202 		 */
15203 #ifdef	NOTYET
15204 		ASSERT(osp->os_mapcnt == 0);
15205 #endif
15206 		osp->os_mapcnt = 0;
15207 	}
15208 
15209 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15210 		ASSERT(osp->os_mapcnt >= btopr(len));
15211 
15212 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15213 			osp->os_mmap_write -= btopr(len);
15214 		if (maxprot & PROT_READ)
15215 			osp->os_mmap_read -= btopr(len);
15216 		if (maxprot & PROT_EXEC)
15217 			osp->os_mmap_read -= btopr(len);
15218 		/* mirror the PROT_NONE check in nfs4_addmap() */
15219 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15220 		    !(maxprot & PROT_EXEC))
15221 			osp->os_mmap_read -= btopr(len);
15222 		osp->os_mapcnt -= btopr(len);
15223 		did_dec_count = 1;
15224 	}
15225 
15226 	if (recovonly) {
15227 		nfs4_lost_rqst_t lost_rqst;
15228 
15229 		/* request should not already be in recovery queue */
15230 		ASSERT(lrp == NULL);
15231 		nfs4_error_init(ep, EINTR);
15232 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15233 		    osp, cred_otw, vp);
15234 		mutex_exit(&osp->os_sync_lock);
15235 		have_sync_lock = 0;
15236 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15237 		    lost_rqst.lr_op == OP_CLOSE ?
15238 		    &lost_rqst : NULL, OP_CLOSE, NULL);
15239 		close_failed = 1;
15240 		force_close = 0;
15241 		goto close_cleanup;
15242 	}
15243 
15244 	/*
15245 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15246 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15247 	 * space, which means we stopped operating on the open stream
15248 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15249 	 * stateid could be stale, potentially triggering a false
15250 	 * setclientid), and just clean up the client's internal state.
15251 	 */
15252 	if (osp->os_orig_oo_name != oop->oo_name) {
15253 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15254 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15255 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15256 		    "oo_name %" PRIx64")",
15257 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15258 		    oop->oo_name));
15259 		close_failed = 1;
15260 	}
15261 
15262 	/* If the file failed recovery, just quit. */
15263 	mutex_enter(&rp->r_statelock);
15264 	if (rp->r_flags & R4RECOVERR) {
15265 		close_failed = 1;
15266 	}
15267 	mutex_exit(&rp->r_statelock);
15268 
15269 	/*
15270 	 * If the force close path failed to obtain start_fop
15271 	 * then skip the OTW close and just remove the state.
15272 	 */
15273 	if (close_failed)
15274 		goto close_cleanup;
15275 
15276 	/*
15277 	 * Fifth, check to see if there are still mapped pages or other
15278 	 * opens using this open stream.  If there are then we can't
15279 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15280 	 */
15281 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15282 		nfs4_lost_rqst_t	new_lost_rqst;
15283 		bool_t			needrecov = FALSE;
15284 		cred_t			*odg_cred_otw = NULL;
15285 		seqid4			open_dg_seqid = 0;
15286 
15287 		if (osp->os_delegation) {
15288 			/*
15289 			 * If this open stream was never OPENed OTW then we
15290 			 * surely can't DOWNGRADE it (especially since the
15291 			 * osp->open_stateid is really a delegation stateid
15292 			 * when os_delegation is 1).
15293 			 */
15294 			if (access_bits & FREAD)
15295 				osp->os_share_acc_read--;
15296 			if (access_bits & FWRITE)
15297 				osp->os_share_acc_write--;
15298 			osp->os_share_deny_none--;
15299 			nfs4_error_zinit(ep);
15300 			goto out;
15301 		}
15302 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15303 		    lrp, ep, &odg_cred_otw, &open_dg_seqid);
15304 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15305 		if (needrecov && !isrecov) {
15306 			bool_t abort;
15307 			nfs4_bseqid_entry_t *bsep = NULL;
15308 
15309 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15310 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15311 				    vp, 0,
15312 				    lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15313 				    open_dg_seqid);
15314 
15315 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15316 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15317 			mutex_exit(&osp->os_sync_lock);
15318 			have_sync_lock = 0;
15319 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15320 			    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15321 			    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15322 			    bsep);
15323 			if (odg_cred_otw)
15324 				crfree(odg_cred_otw);
15325 			if (bsep)
15326 				kmem_free(bsep, sizeof (*bsep));
15327 
15328 			if (abort == TRUE)
15329 				goto out;
15330 
15331 			if (did_start_seqid_sync) {
15332 				nfs4_end_open_seqid_sync(oop);
15333 				did_start_seqid_sync = 0;
15334 			}
15335 			open_stream_rele(osp, rp);
15336 
15337 			if (did_start_op)
15338 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15339 				    &recov_state, FALSE);
15340 			if (did_force_recovlock)
15341 				nfs_rw_exit(&mi->mi_recovlock);
15342 
15343 			goto recov_retry;
15344 		} else {
15345 			if (odg_cred_otw)
15346 				crfree(odg_cred_otw);
15347 		}
15348 		goto out;
15349 	}
15350 
15351 	/*
15352 	 * If this open stream was created as the results of an open
15353 	 * while holding a delegation, then just release it; no need
15354 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15355 	 */
15356 	if (osp->os_delegation) {
15357 		nfs4close_notw(vp, osp, &have_sync_lock);
15358 		nfs4_error_zinit(ep);
15359 		goto out;
15360 	}
15361 
15362 	/*
15363 	 * If this stream is not valid, we're done.
15364 	 */
15365 	if (!osp->os_valid) {
15366 		nfs4_error_zinit(ep);
15367 		goto out;
15368 	}
15369 
15370 	/*
15371 	 * Last open or mmap ref has vanished, need to do an OTW close.
15372 	 * First check to see if a close is still necessary.
15373 	 */
15374 	if (osp->os_failed_reopen) {
15375 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15376 		    "don't close OTW osp %p since reopen failed.",
15377 		    (void *)osp));
15378 		/*
15379 		 * Reopen of the open stream failed, hence the
15380 		 * stateid of the open stream is invalid/stale, and
15381 		 * sending this OTW would incorrectly cause another
15382 		 * round of recovery.  In this case, we need to set
15383 		 * the 'os_valid' bit to 0 so another thread doesn't
15384 		 * come in and re-open this open stream before
15385 		 * this "closing" thread cleans up state (decrementing
15386 		 * the nfs4_server_t's state_ref_count and decrementing
15387 		 * the os_ref_count).
15388 		 */
15389 		osp->os_valid = 0;
15390 		/*
15391 		 * This removes the reference obtained at OPEN; ie,
15392 		 * when the open stream structure was created.
15393 		 *
15394 		 * We don't have to worry about calling 'open_stream_rele'
15395 		 * since we our currently holding a reference to this
15396 		 * open stream which means the count can not go to 0 with
15397 		 * this decrement.
15398 		 */
15399 		ASSERT(osp->os_ref_count >= 2);
15400 		osp->os_ref_count--;
15401 		nfs4_error_zinit(ep);
15402 		close_failed = 0;
15403 		goto close_cleanup;
15404 	}
15405 
15406 	ASSERT(osp->os_ref_count > 1);
15407 
15408 	/*
15409 	 * Sixth, try the CLOSE OTW.
15410 	 */
15411 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15412 	    close_type, ep, &have_sync_lock);
15413 
15414 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15415 		/*
15416 		 * Let the recovery thread be responsible for
15417 		 * removing the state for CLOSE.
15418 		 */
15419 		close_failed = 1;
15420 		force_close = 0;
15421 		retry = 0;
15422 	}
15423 
15424 	/* See if we need to retry with a different cred */
15425 	if ((ep->error == EACCES ||
15426 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15427 	    cred_otw != cr) {
15428 		crfree(cred_otw);
15429 		cred_otw = cr;
15430 		crhold(cred_otw);
15431 		retry = 1;
15432 	}
15433 
15434 	if (ep->error || ep->stat)
15435 		close_failed = 1;
15436 
15437 	if (retry && !isrecov && num_retries-- > 0) {
15438 		if (have_sync_lock) {
15439 			mutex_exit(&osp->os_sync_lock);
15440 			have_sync_lock = 0;
15441 		}
15442 		if (did_start_seqid_sync) {
15443 			nfs4_end_open_seqid_sync(oop);
15444 			did_start_seqid_sync = 0;
15445 		}
15446 		open_stream_rele(osp, rp);
15447 
15448 		if (did_start_op)
15449 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15450 			    &recov_state, FALSE);
15451 		if (did_force_recovlock)
15452 			nfs_rw_exit(&mi->mi_recovlock);
15453 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15454 		    "nfs4close_one: need to retry the close "
15455 		    "operation"));
15456 		goto recov_retry;
15457 	}
15458 close_cleanup:
15459 	/*
15460 	 * Seventh and lastly, process our results.
15461 	 */
15462 	if (close_failed && force_close) {
15463 		/*
15464 		 * It's ok to drop and regrab the 'os_sync_lock' since
15465 		 * nfs4close_notw() will recheck to make sure the
15466 		 * "close"/removal of state should happen.
15467 		 */
15468 		if (!have_sync_lock) {
15469 			mutex_enter(&osp->os_sync_lock);
15470 			have_sync_lock = 1;
15471 		}
15472 		/*
15473 		 * This is last call, remove the ref on the open
15474 		 * stream created by open and clean everything up.
15475 		 */
15476 		osp->os_pending_close = 0;
15477 		nfs4close_notw(vp, osp, &have_sync_lock);
15478 		nfs4_error_zinit(ep);
15479 	}
15480 
15481 	if (!close_failed) {
15482 		if (have_sync_lock) {
15483 			osp->os_pending_close = 0;
15484 			mutex_exit(&osp->os_sync_lock);
15485 			have_sync_lock = 0;
15486 		} else {
15487 			mutex_enter(&osp->os_sync_lock);
15488 			osp->os_pending_close = 0;
15489 			mutex_exit(&osp->os_sync_lock);
15490 		}
15491 		if (did_start_op && recov_state.rs_sp != NULL) {
15492 			mutex_enter(&recov_state.rs_sp->s_lock);
15493 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15494 			mutex_exit(&recov_state.rs_sp->s_lock);
15495 		} else {
15496 			nfs4_dec_state_ref_count(mi);
15497 		}
15498 		nfs4_error_zinit(ep);
15499 	}
15500 
15501 out:
15502 	if (have_sync_lock)
15503 		mutex_exit(&osp->os_sync_lock);
15504 	if (did_start_op)
15505 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15506 		    recovonly ? TRUE : FALSE);
15507 	if (did_force_recovlock)
15508 		nfs_rw_exit(&mi->mi_recovlock);
15509 	if (cred_otw)
15510 		crfree(cred_otw);
15511 	if (osp)
15512 		open_stream_rele(osp, rp);
15513 	if (oop) {
15514 		if (did_start_seqid_sync)
15515 			nfs4_end_open_seqid_sync(oop);
15516 		open_owner_rele(oop);
15517 	}
15518 }
15519 
15520 /*
15521  * Convert information returned by the server in the LOCK4denied
15522  * structure to the form required by fcntl.
15523  */
15524 static void
15525 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15526 {
15527 	nfs4_lo_name_t *lo;
15528 
15529 #ifdef	DEBUG
15530 	if (denied_to_flk_debug) {
15531 		lockt_denied_debug = lockt_denied;
15532 		debug_enter("lockt_denied");
15533 	}
15534 #endif
15535 
15536 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15537 	flk->l_whence = 0;	/* aka SEEK_SET */
15538 	flk->l_start = lockt_denied->offset;
15539 	flk->l_len = lockt_denied->length;
15540 
15541 	/*
15542 	 * If the blocking clientid matches our client id, then we can
15543 	 * interpret the lockowner (since we built it).  If not, then
15544 	 * fabricate a sysid and pid.  Note that the l_sysid field
15545 	 * in *flk already has the local sysid.
15546 	 */
15547 
15548 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15549 
15550 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15551 			lo = (nfs4_lo_name_t *)
15552 			    lockt_denied->owner.owner_val;
15553 
15554 			flk->l_pid = lo->ln_pid;
15555 		} else {
15556 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15557 			    "denied_to_flk: bad lock owner length\n"));
15558 
15559 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15560 		}
15561 	} else {
15562 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15563 		"denied_to_flk: foreign clientid\n"));
15564 
15565 		/*
15566 		 * Construct a new sysid which should be different from
15567 		 * sysids of other systems.
15568 		 */
15569 
15570 		flk->l_sysid++;
15571 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15572 	}
15573 }
15574 
15575 static pid_t
15576 lo_to_pid(lock_owner4 *lop)
15577 {
15578 	pid_t pid = 0;
15579 	uchar_t *cp;
15580 	int i;
15581 
15582 	cp = (uchar_t *)&lop->clientid;
15583 
15584 	for (i = 0; i < sizeof (lop->clientid); i++)
15585 		pid += (pid_t)*cp++;
15586 
15587 	cp = (uchar_t *)lop->owner_val;
15588 
15589 	for (i = 0; i < lop->owner_len; i++)
15590 		pid += (pid_t)*cp++;
15591 
15592 	return (pid);
15593 }
15594 
15595 /*
15596  * Given a lock pointer, returns the length of that lock.
15597  * "end" is the last locked offset the "l_len" covers from
15598  * the start of the lock.
15599  */
15600 static off64_t
15601 lock_to_end(flock64_t *lock)
15602 {
15603 	off64_t lock_end;
15604 
15605 	if (lock->l_len == 0)
15606 		lock_end = (off64_t)MAXEND;
15607 	else
15608 		lock_end = lock->l_start + lock->l_len - 1;
15609 
15610 	return (lock_end);
15611 }
15612 
15613 /*
15614  * Given the end of a lock, it will return you the length "l_len" for that lock.
15615  */
15616 static off64_t
15617 end_to_len(off64_t start, off64_t end)
15618 {
15619 	off64_t lock_len;
15620 
15621 	ASSERT(end >= start);
15622 	if (end == MAXEND)
15623 		lock_len = 0;
15624 	else
15625 		lock_len = end - start + 1;
15626 
15627 	return (lock_len);
15628 }
15629 
15630 /*
15631  * On given end for a lock it determines if it is the last locked offset
15632  * or not, if so keeps it as is, else adds one to return the length for
15633  * valid start.
15634  */
15635 static off64_t
15636 start_check(off64_t x)
15637 {
15638 	if (x == MAXEND)
15639 		return (x);
15640 	else
15641 		return (x + 1);
15642 }
15643 
15644 /*
15645  * See if these two locks overlap, and if so return 1;
15646  * otherwise, return 0.
15647  */
15648 static int
15649 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15650 {
15651 	off64_t llfp_end, curfp_end;
15652 
15653 	llfp_end = lock_to_end(llfp);
15654 	curfp_end = lock_to_end(curfp);
15655 
15656 	if (((llfp_end >= curfp->l_start) &&
15657 	    (llfp->l_start <= curfp->l_start)) ||
15658 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15659 		return (1);
15660 	return (0);
15661 }
15662 
15663 /*
15664  * Determine what the intersecting lock region is, and add that to the
15665  * 'nl_llpp' locklist in increasing order (by l_start).
15666  */
15667 static void
15668 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15669     locklist_t **nl_llpp, vnode_t *vp)
15670 {
15671 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15672 	off64_t lost_flp_end, local_flp_end, len, start;
15673 
15674 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15675 
15676 	if (!locks_intersect(lost_flp, local_flp))
15677 		return;
15678 
15679 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15680 	    "locks intersect"));
15681 
15682 	lost_flp_end = lock_to_end(lost_flp);
15683 	local_flp_end = lock_to_end(local_flp);
15684 
15685 	/* Find the starting point of the intersecting region */
15686 	if (local_flp->l_start > lost_flp->l_start)
15687 		start = local_flp->l_start;
15688 	else
15689 		start = lost_flp->l_start;
15690 
15691 	/* Find the lenght of the intersecting region */
15692 	if (lost_flp_end < local_flp_end)
15693 		len = end_to_len(start, lost_flp_end);
15694 	else
15695 		len = end_to_len(start, local_flp_end);
15696 
15697 	/*
15698 	 * Prepare the flock structure for the intersection found and insert
15699 	 * it into the new list in increasing l_start order. This list contains
15700 	 * intersections of locks registered by the client with the local host
15701 	 * and the lost lock.
15702 	 * The lock type of this lock is the same as that of the local_flp.
15703 	 */
15704 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15705 	intersect_llp->ll_flock.l_start = start;
15706 	intersect_llp->ll_flock.l_len = len;
15707 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15708 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15709 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15710 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15711 	intersect_llp->ll_vp = vp;
15712 
15713 	tmp_fllp = *nl_llpp;
15714 	cur_fllp = NULL;
15715 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15716 	    intersect_llp->ll_flock.l_start) {
15717 			cur_fllp = tmp_fllp;
15718 			tmp_fllp = tmp_fllp->ll_next;
15719 	}
15720 	if (cur_fllp == NULL) {
15721 		/* first on the list */
15722 		intersect_llp->ll_next = *nl_llpp;
15723 		*nl_llpp = intersect_llp;
15724 	} else {
15725 		intersect_llp->ll_next = cur_fllp->ll_next;
15726 		cur_fllp->ll_next = intersect_llp;
15727 	}
15728 
15729 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15730 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15731 	    intersect_llp->ll_flock.l_start,
15732 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15733 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15734 }
15735 
15736 /*
15737  * Our local locking current state is potentially different than
15738  * what the NFSv4 server thinks we have due to a lost lock that was
15739  * resent and then received.  We need to reset our "NFSv4" locking
15740  * state to match the current local locking state for this pid since
15741  * that is what the user/application sees as what the world is.
15742  *
15743  * We cannot afford to drop the open/lock seqid sync since then we can
15744  * get confused about what the current local locking state "is" versus
15745  * "was".
15746  *
15747  * If we are unable to fix up the locks, we send SIGLOST to the affected
15748  * process.  This is not done if the filesystem has been forcibly
15749  * unmounted, in case the process has already exited and a new process
15750  * exists with the same pid.
15751  */
15752 static void
15753 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15754     nfs4_lock_owner_t *lop)
15755 {
15756 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15757 	mntinfo4_t *mi = VTOMI4(vp);
15758 	const int cmd = F_SETLK;
15759 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15760 	flock64_t ul_fl;
15761 
15762 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15763 	    "nfs4_reinstitute_local_lock_state"));
15764 
15765 	/*
15766 	 * Find active locks for this vp from the local locking code.
15767 	 * Scan through this list and find out the locks that intersect with
15768 	 * the lost lock. Once we find the lock that intersects, add the
15769 	 * intersection area as a new lock to a new list "ri_llp". The lock
15770 	 * type of the intersection region lock added to ri_llp is the same
15771 	 * as that found in the active lock list, "list". The intersecting
15772 	 * region locks are added to ri_llp in increasing l_start order.
15773 	 */
15774 	ASSERT(nfs_zone() == mi->mi_zone);
15775 
15776 	locks = flk_active_locks_for_vp(vp);
15777 	ri_llp = NULL;
15778 
15779 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15780 		ASSERT(llp->ll_vp == vp);
15781 		/*
15782 		 * Pick locks that belong to this pid/lockowner
15783 		 */
15784 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15785 			continue;
15786 
15787 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15788 	}
15789 
15790 	/*
15791 	 * Now we have the list of intersections with the lost lock. These are
15792 	 * the locks that were/are active before the server replied to the
15793 	 * last/lost lock. Issue these locks to the server here. Playing these
15794 	 * locks to the server will re-establish aur current local locking state
15795 	 * with the v4 server.
15796 	 * If we get an error, send SIGLOST to the application for that lock.
15797 	 */
15798 
15799 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15800 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15801 		    "nfs4_reinstitute_local_lock_state: need to issue "
15802 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15803 		    llp->ll_flock.l_start,
15804 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15805 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15806 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15807 		/*
15808 		 * No need to relock what we already have
15809 		 */
15810 		if (llp->ll_flock.l_type == lost_flp->l_type)
15811 			continue;
15812 
15813 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15814 	}
15815 
15816 	/*
15817 	 * Now keeping the start of the lost lock as our reference parse the
15818 	 * newly created ri_llp locklist to find the ranges that we have locked
15819 	 * with the v4 server but not in the current local locking. We need
15820 	 * to unlock these ranges.
15821 	 * These ranges can also be reffered to as those ranges, where the lost
15822 	 * lock does not overlap with the locks in the ri_llp but are locked
15823 	 * since the server replied to the lost lock.
15824 	 */
15825 	cur_start = lost_flp->l_start;
15826 	lost_flp_end = lock_to_end(lost_flp);
15827 
15828 	ul_fl.l_type = F_UNLCK;
15829 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15830 	ul_fl.l_sysid = lost_flp->l_sysid;
15831 	ul_fl.l_pid = lost_flp->l_pid;
15832 
15833 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15834 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15835 
15836 		if (llp->ll_flock.l_start <= cur_start) {
15837 			cur_start = start_check(llp_ll_flock_end);
15838 			continue;
15839 		}
15840 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15841 		    "nfs4_reinstitute_local_lock_state: "
15842 		    "UNLOCK [%"PRIx64" - %"PRIx64"]",
15843 		    cur_start, llp->ll_flock.l_start));
15844 
15845 		ul_fl.l_start = cur_start;
15846 		ul_fl.l_len = end_to_len(cur_start,
15847 		    (llp->ll_flock.l_start - 1));
15848 
15849 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15850 		cur_start = start_check(llp_ll_flock_end);
15851 	}
15852 
15853 	/*
15854 	 * In the case where the lost lock ends after all intersecting locks,
15855 	 * unlock the last part of the lost lock range.
15856 	 */
15857 	if (cur_start != start_check(lost_flp_end)) {
15858 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15859 		    "nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15860 		    "lost lock region [%"PRIx64" - %"PRIx64"]",
15861 		    cur_start, lost_flp->l_start + lost_flp->l_len));
15862 
15863 		ul_fl.l_start = cur_start;
15864 		/*
15865 		 * Is it an to-EOF lock? if so unlock till the end
15866 		 */
15867 		if (lost_flp->l_len == 0)
15868 			ul_fl.l_len = 0;
15869 		else
15870 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15871 
15872 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15873 	}
15874 
15875 	if (locks != NULL)
15876 		flk_free_locklist(locks);
15877 
15878 	/* Free up our newly created locklist */
15879 	for (llp = ri_llp; llp != NULL; ) {
15880 		tmp_llp = llp->ll_next;
15881 		kmem_free(llp, sizeof (locklist_t));
15882 		llp = tmp_llp;
15883 	}
15884 
15885 	/*
15886 	 * Now return back to the original calling nfs4frlock()
15887 	 * and let us naturally drop our seqid syncs.
15888 	 */
15889 }
15890 
15891 /*
15892  * Create a lost state record for the given lock reinstantiation request
15893  * and push it onto the lost state queue.
15894  */
15895 static void
15896 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
15897     nfs4_lock_owner_t *lop)
15898 {
15899 	nfs4_lost_rqst_t req;
15900 	nfs_lock_type4 locktype;
15901 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
15902 
15903 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15904 
15905 	locktype = flk_to_locktype(cmd, flk->l_type);
15906 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
15907 	    NULL, NULL, lop, flk, &req, cr, vp);
15908 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
15909 	    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
15910 	    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
15911 	    NULL);
15912 }
15913