xref: /illumos-gate/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision c85864d8472aaccb47ceb468ebd9b3a85b66d161)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  *	Copyright 1983,1984,1985,1986,1987,1988,1989 AT&T.
28  *	All Rights Reserved
29  */
30 
31 #include <sys/param.h>
32 #include <sys/types.h>
33 #include <sys/systm.h>
34 #include <sys/cred.h>
35 #include <sys/time.h>
36 #include <sys/vnode.h>
37 #include <sys/vfs.h>
38 #include <sys/vfs_opreg.h>
39 #include <sys/file.h>
40 #include <sys/filio.h>
41 #include <sys/uio.h>
42 #include <sys/buf.h>
43 #include <sys/mman.h>
44 #include <sys/pathname.h>
45 #include <sys/dirent.h>
46 #include <sys/debug.h>
47 #include <sys/vmsystm.h>
48 #include <sys/fcntl.h>
49 #include <sys/flock.h>
50 #include <sys/swap.h>
51 #include <sys/errno.h>
52 #include <sys/strsubr.h>
53 #include <sys/sysmacros.h>
54 #include <sys/kmem.h>
55 #include <sys/cmn_err.h>
56 #include <sys/pathconf.h>
57 #include <sys/utsname.h>
58 #include <sys/dnlc.h>
59 #include <sys/acl.h>
60 #include <sys/systeminfo.h>
61 #include <sys/policy.h>
62 #include <sys/sdt.h>
63 #include <sys/list.h>
64 #include <sys/stat.h>
65 #include <sys/zone.h>
66 
67 #include <rpc/types.h>
68 #include <rpc/auth.h>
69 #include <rpc/clnt.h>
70 
71 #include <nfs/nfs.h>
72 #include <nfs/nfs_clnt.h>
73 #include <nfs/nfs_acl.h>
74 #include <nfs/lm.h>
75 #include <nfs/nfs4.h>
76 #include <nfs/nfs4_kprot.h>
77 #include <nfs/rnode4.h>
78 #include <nfs/nfs4_clnt.h>
79 
80 #include <vm/hat.h>
81 #include <vm/as.h>
82 #include <vm/page.h>
83 #include <vm/pvn.h>
84 #include <vm/seg.h>
85 #include <vm/seg_map.h>
86 #include <vm/seg_kpm.h>
87 #include <vm/seg_vn.h>
88 
89 #include <fs/fs_subr.h>
90 
91 #include <sys/ddi.h>
92 #include <sys/int_fmtio.h>
93 
94 typedef struct {
95 	nfs4_ga_res_t	*di_garp;
96 	cred_t		*di_cred;
97 	hrtime_t	di_time_call;
98 } dirattr_info_t;
99 
100 typedef enum nfs4_acl_op {
101 	NFS4_ACL_GET,
102 	NFS4_ACL_SET
103 } nfs4_acl_op_t;
104 
105 static struct lm_sysid *nfs4_find_sysid(mntinfo4_t *mi);
106 
107 static void	nfs4_update_dircaches(change_info4 *, vnode_t *, vnode_t *,
108 			char *, dirattr_info_t *);
109 
110 static void	nfs4close_otw(rnode4_t *, cred_t *, nfs4_open_owner_t *,
111 		    nfs4_open_stream_t *, int *, int *, nfs4_close_type_t,
112 		    nfs4_error_t *, int *);
113 static int	nfs4_rdwrlbn(vnode_t *, page_t *, u_offset_t, size_t, int,
114 			cred_t *);
115 static int	nfs4write(vnode_t *, caddr_t, u_offset_t, int, cred_t *,
116 			stable_how4 *);
117 static int	nfs4read(vnode_t *, caddr_t, offset_t, int, size_t *,
118 			cred_t *, bool_t, struct uio *);
119 static int	nfs4setattr(vnode_t *, struct vattr *, int, cred_t *,
120 			vsecattr_t *);
121 static int	nfs4openattr(vnode_t *, vnode_t **, int, cred_t *);
122 static int	nfs4lookup(vnode_t *, char *, vnode_t **, cred_t *, int);
123 static int	nfs4lookup_xattr(vnode_t *, char *, vnode_t **, int, cred_t *);
124 static int	nfs4lookupvalidate_otw(vnode_t *, char *, vnode_t **, cred_t *);
125 static int	nfs4lookupnew_otw(vnode_t *, char *, vnode_t **, cred_t *);
126 static int	nfs4mknod(vnode_t *, char *, struct vattr *, enum vcexcl,
127 			int, vnode_t **, cred_t *);
128 static int	nfs4open_otw(vnode_t *, char *, struct vattr *, vnode_t **,
129 			cred_t *, int, int, enum createmode4, int);
130 static int	nfs4rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
131 			caller_context_t *);
132 static int	nfs4rename_persistent_fh(vnode_t *, char *, vnode_t *,
133 			vnode_t *, char *, cred_t *, nfsstat4 *);
134 static int	nfs4rename_volatile_fh(vnode_t *, char *, vnode_t *,
135 			vnode_t *, char *, cred_t *, nfsstat4 *);
136 static int	do_nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
137 static void	nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
138 static int	nfs4_bio(struct buf *, stable_how4 *, cred_t *, bool_t);
139 static int	nfs4_getapage(vnode_t *, u_offset_t, size_t, uint_t *,
140 			page_t *[], size_t, struct seg *, caddr_t,
141 			enum seg_rw, cred_t *);
142 static void	nfs4_readahead(vnode_t *, u_offset_t, caddr_t, struct seg *,
143 			cred_t *);
144 static int	nfs4_sync_putapage(vnode_t *, page_t *, u_offset_t, size_t,
145 			int, cred_t *);
146 static int	nfs4_sync_pageio(vnode_t *, page_t *, u_offset_t, size_t,
147 			int, cred_t *);
148 static int	nfs4_commit(vnode_t *, offset4, count4, cred_t *);
149 static void	nfs4_set_mod(vnode_t *);
150 static void	nfs4_get_commit(vnode_t *);
151 static void	nfs4_get_commit_range(vnode_t *, u_offset_t, size_t);
152 static int	nfs4_putpage_commit(vnode_t *, offset_t, size_t, cred_t *);
153 static int	nfs4_commit_vp(vnode_t *, u_offset_t, size_t, cred_t *, int);
154 static int	nfs4_sync_commit(vnode_t *, page_t *, offset3, count3,
155 			cred_t *);
156 static void	do_nfs4_async_commit(vnode_t *, page_t *, offset3, count3,
157 			cred_t *);
158 static int	nfs4_update_attrcache(nfsstat4, nfs4_ga_res_t *,
159 			hrtime_t, vnode_t *, cred_t *);
160 static int	nfs4_open_non_reg_file(vnode_t **, int, cred_t *);
161 static int	nfs4_safelock(vnode_t *, const struct flock64 *, cred_t *);
162 static void	nfs4_register_lock_locally(vnode_t *, struct flock64 *, int,
163 			u_offset_t);
164 static int 	nfs4_lockrelease(vnode_t *, int, offset_t, cred_t *);
165 static int	nfs4_block_and_wait(clock_t *, rnode4_t *);
166 static cred_t  *state_to_cred(nfs4_open_stream_t *);
167 static int	vtoname(vnode_t *, char *, ssize_t);
168 static void	denied_to_flk(LOCK4denied *, flock64_t *, LOCKT4args *);
169 static pid_t	lo_to_pid(lock_owner4 *);
170 static void	nfs4_reinstitute_local_lock_state(vnode_t *, flock64_t *,
171 			cred_t *, nfs4_lock_owner_t *);
172 static void	push_reinstate(vnode_t *, int, flock64_t *, cred_t *,
173 			nfs4_lock_owner_t *);
174 static int 	open_and_get_osp(vnode_t *, cred_t *, nfs4_open_stream_t **);
175 static void	nfs4_delmap_callback(struct as *, void *, uint_t);
176 static void	nfs4_free_delmapcall(nfs4_delmapcall_t *);
177 static nfs4_delmapcall_t	*nfs4_init_delmapcall();
178 static int	nfs4_find_and_delete_delmapcall(rnode4_t *, int *);
179 static int	nfs4_is_acl_mask_valid(uint_t, nfs4_acl_op_t);
180 static int	nfs4_create_getsecattr_return(vsecattr_t *, vsecattr_t *,
181 			uid_t, gid_t, int);
182 
183 /*
184  * Routines that implement the setting of v4 args for the misc. ops
185  */
186 static void	nfs4args_lock_free(nfs_argop4 *);
187 static void	nfs4args_lockt_free(nfs_argop4 *);
188 static void	nfs4args_setattr(nfs_argop4 *, vattr_t *, vsecattr_t *,
189 			int, rnode4_t *, cred_t *, bitmap4, int *,
190 			nfs4_stateid_types_t *);
191 static void	nfs4args_setattr_free(nfs_argop4 *);
192 static int	nfs4args_verify(nfs_argop4 *, vattr_t *, enum nfs_opnum4,
193 			bitmap4);
194 static void	nfs4args_verify_free(nfs_argop4 *);
195 static void	nfs4args_write(nfs_argop4 *, stable_how4, rnode4_t *, cred_t *,
196 			WRITE4args **, nfs4_stateid_types_t *);
197 
198 /*
199  * These are the vnode ops functions that implement the vnode interface to
200  * the networked file system.  See more comments below at nfs4_vnodeops.
201  */
202 static int	nfs4_open(vnode_t **, int, cred_t *, caller_context_t *);
203 static int	nfs4_close(vnode_t *, int, int, offset_t, cred_t *,
204 			caller_context_t *);
205 static int	nfs4_read(vnode_t *, struct uio *, int, cred_t *,
206 			caller_context_t *);
207 static int	nfs4_write(vnode_t *, struct uio *, int, cred_t *,
208 			caller_context_t *);
209 static int	nfs4_ioctl(vnode_t *, int, intptr_t, int, cred_t *, int *,
210 			caller_context_t *);
211 static int	nfs4_setattr(vnode_t *, struct vattr *, int, cred_t *,
212 			caller_context_t *);
213 static int	nfs4_access(vnode_t *, int, int, cred_t *, caller_context_t *);
214 static int	nfs4_readlink(vnode_t *, struct uio *, cred_t *,
215 			caller_context_t *);
216 static int	nfs4_fsync(vnode_t *, int, cred_t *, caller_context_t *);
217 static int	nfs4_create(vnode_t *, char *, struct vattr *, enum vcexcl,
218 			int, vnode_t **, cred_t *, int, caller_context_t *,
219 			vsecattr_t *);
220 static int	nfs4_remove(vnode_t *, char *, cred_t *, caller_context_t *,
221 			int);
222 static int	nfs4_link(vnode_t *, vnode_t *, char *, cred_t *,
223 			caller_context_t *, int);
224 static int	nfs4_rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
225 			caller_context_t *, int);
226 static int	nfs4_mkdir(vnode_t *, char *, struct vattr *, vnode_t **,
227 			cred_t *, caller_context_t *, int, vsecattr_t *);
228 static int	nfs4_rmdir(vnode_t *, char *, vnode_t *, cred_t *,
229 			caller_context_t *, int);
230 static int	nfs4_symlink(vnode_t *, char *, struct vattr *, char *,
231 			cred_t *, caller_context_t *, int);
232 static int	nfs4_readdir(vnode_t *, struct uio *, cred_t *, int *,
233 			caller_context_t *, int);
234 static int	nfs4_seek(vnode_t *, offset_t, offset_t *, caller_context_t *);
235 static int	nfs4_getpage(vnode_t *, offset_t, size_t, uint_t *,
236 			page_t *[], size_t, struct seg *, caddr_t,
237 			enum seg_rw, cred_t *, caller_context_t *);
238 static int	nfs4_putpage(vnode_t *, offset_t, size_t, int, cred_t *,
239 			caller_context_t *);
240 static int	nfs4_map(vnode_t *, offset_t, struct as *, caddr_t *, size_t,
241 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
242 static int	nfs4_addmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
243 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
244 static int	nfs4_cmp(vnode_t *, vnode_t *, caller_context_t *);
245 static int	nfs4_frlock(vnode_t *, int, struct flock64 *, int, offset_t,
246 			struct flk_callback *, cred_t *, caller_context_t *);
247 static int	nfs4_space(vnode_t *, int, struct flock64 *, int, offset_t,
248 			cred_t *, caller_context_t *);
249 static int	nfs4_delmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
250 			uint_t, uint_t, uint_t, cred_t *, caller_context_t *);
251 static int	nfs4_pageio(vnode_t *, page_t *, u_offset_t, size_t, int,
252 			cred_t *, caller_context_t *);
253 static void	nfs4_dispose(vnode_t *, page_t *, int, int, cred_t *,
254 			caller_context_t *);
255 static int	nfs4_setsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
256 			caller_context_t *);
257 /*
258  * These vnode ops are required to be called from outside this source file,
259  * e.g. by ephemeral mount stub vnode ops, and so may not be declared
260  * as static.
261  */
262 int	nfs4_getattr(vnode_t *, struct vattr *, int, cred_t *,
263 	    caller_context_t *);
264 void	nfs4_inactive(vnode_t *, cred_t *, caller_context_t *);
265 int	nfs4_lookup(vnode_t *, char *, vnode_t **,
266 	    struct pathname *, int, vnode_t *, cred_t *,
267 	    caller_context_t *, int *, pathname_t *);
268 int	nfs4_fid(vnode_t *, fid_t *, caller_context_t *);
269 int	nfs4_rwlock(vnode_t *, int, caller_context_t *);
270 void	nfs4_rwunlock(vnode_t *, int, caller_context_t *);
271 int	nfs4_realvp(vnode_t *, vnode_t **, caller_context_t *);
272 int	nfs4_pathconf(vnode_t *, int, ulong_t *, cred_t *,
273 	    caller_context_t *);
274 int	nfs4_getsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
275 	    caller_context_t *);
276 int	nfs4_shrlock(vnode_t *, int, struct shrlock *, int, cred_t *,
277 	    caller_context_t *);
278 
279 /*
280  * Used for nfs4_commit_vp() to indicate if we should
281  * wait on pending writes.
282  */
283 #define	NFS4_WRITE_NOWAIT	0
284 #define	NFS4_WRITE_WAIT		1
285 
286 #define	NFS4_BASE_WAIT_TIME 1	/* 1 second */
287 
288 /*
289  * Error flags used to pass information about certain special errors
290  * which need to be handled specially.
291  */
292 #define	NFS_EOF			-98
293 #define	NFS_VERF_MISMATCH	-97
294 
295 /*
296  * Flags used to differentiate between which operation drove the
297  * potential CLOSE OTW. (see nfs4_close_otw_if_necessary)
298  */
299 #define	NFS4_CLOSE_OP		0x1
300 #define	NFS4_DELMAP_OP		0x2
301 #define	NFS4_INACTIVE_OP	0x3
302 
303 #define	ISVDEV(t) ((t == VBLK) || (t == VCHR) || (t == VFIFO))
304 
305 /* ALIGN64 aligns the given buffer and adjust buffer size to 64 bit */
306 #define	ALIGN64(x, ptr, sz)						\
307 	x = ((uintptr_t)(ptr)) & (sizeof (uint64_t) - 1);		\
308 	if (x) {							\
309 		x = sizeof (uint64_t) - (x);				\
310 		sz -= (x);						\
311 		ptr += (x);						\
312 	}
313 
314 #ifdef DEBUG
315 int nfs4_client_attr_debug = 0;
316 int nfs4_client_state_debug = 0;
317 int nfs4_client_shadow_debug = 0;
318 int nfs4_client_lock_debug = 0;
319 int nfs4_seqid_sync = 0;
320 int nfs4_client_map_debug = 0;
321 static int nfs4_pageio_debug = 0;
322 int nfs4_client_inactive_debug = 0;
323 int nfs4_client_recov_debug = 0;
324 int nfs4_client_failover_debug = 0;
325 int nfs4_client_call_debug = 0;
326 int nfs4_client_lookup_debug = 0;
327 int nfs4_client_zone_debug = 0;
328 int nfs4_lost_rqst_debug = 0;
329 int nfs4_rdattrerr_debug = 0;
330 int nfs4_open_stream_debug = 0;
331 
332 int nfs4read_error_inject;
333 
334 static int nfs4_create_misses = 0;
335 
336 static int nfs4_readdir_cache_shorts = 0;
337 static int nfs4_readdir_readahead = 0;
338 
339 static int nfs4_bio_do_stop = 0;
340 
341 static int nfs4_lostpage = 0;	/* number of times we lost original page */
342 
343 int nfs4_mmap_debug = 0;
344 
345 static int nfs4_pathconf_cache_hits = 0;
346 static int nfs4_pathconf_cache_misses = 0;
347 
348 int nfs4close_all_cnt;
349 int nfs4close_one_debug = 0;
350 int nfs4close_notw_debug = 0;
351 
352 int denied_to_flk_debug = 0;
353 void *lockt_denied_debug;
354 
355 #endif
356 
357 /*
358  * How long to wait before trying again if OPEN_CONFIRM gets ETIMEDOUT
359  * or NFS4ERR_RESOURCE.
360  */
361 static int confirm_retry_sec = 30;
362 
363 static int nfs4_lookup_neg_cache = 1;
364 
365 /*
366  * number of pages to read ahead
367  * optimized for 100 base-T.
368  */
369 static int nfs4_nra = 4;
370 
371 static int nfs4_do_symlink_cache = 1;
372 
373 static int nfs4_pathconf_disable_cache = 0;
374 
375 /*
376  * These are the vnode ops routines which implement the vnode interface to
377  * the networked file system.  These routines just take their parameters,
378  * make them look networkish by putting the right info into interface structs,
379  * and then calling the appropriate remote routine(s) to do the work.
380  *
381  * Note on directory name lookup cacheing:  If we detect a stale fhandle,
382  * we purge the directory cache relative to that vnode.  This way, the
383  * user won't get burned by the cache repeatedly.  See <nfs/rnode4.h> for
384  * more details on rnode locking.
385  */
386 
387 struct vnodeops *nfs4_vnodeops;
388 
389 const fs_operation_def_t nfs4_vnodeops_template[] = {
390 	VOPNAME_OPEN,		{ .vop_open = nfs4_open },
391 	VOPNAME_CLOSE,		{ .vop_close = nfs4_close },
392 	VOPNAME_READ,		{ .vop_read = nfs4_read },
393 	VOPNAME_WRITE,		{ .vop_write = nfs4_write },
394 	VOPNAME_IOCTL,		{ .vop_ioctl = nfs4_ioctl },
395 	VOPNAME_GETATTR,	{ .vop_getattr = nfs4_getattr },
396 	VOPNAME_SETATTR,	{ .vop_setattr = nfs4_setattr },
397 	VOPNAME_ACCESS,		{ .vop_access = nfs4_access },
398 	VOPNAME_LOOKUP,		{ .vop_lookup = nfs4_lookup },
399 	VOPNAME_CREATE,		{ .vop_create = nfs4_create },
400 	VOPNAME_REMOVE,		{ .vop_remove = nfs4_remove },
401 	VOPNAME_LINK,		{ .vop_link = nfs4_link },
402 	VOPNAME_RENAME,		{ .vop_rename = nfs4_rename },
403 	VOPNAME_MKDIR,		{ .vop_mkdir = nfs4_mkdir },
404 	VOPNAME_RMDIR,		{ .vop_rmdir = nfs4_rmdir },
405 	VOPNAME_READDIR,	{ .vop_readdir = nfs4_readdir },
406 	VOPNAME_SYMLINK,	{ .vop_symlink = nfs4_symlink },
407 	VOPNAME_READLINK,	{ .vop_readlink = nfs4_readlink },
408 	VOPNAME_FSYNC,		{ .vop_fsync = nfs4_fsync },
409 	VOPNAME_INACTIVE,	{ .vop_inactive = nfs4_inactive },
410 	VOPNAME_FID,		{ .vop_fid = nfs4_fid },
411 	VOPNAME_RWLOCK,		{ .vop_rwlock = nfs4_rwlock },
412 	VOPNAME_RWUNLOCK,	{ .vop_rwunlock = nfs4_rwunlock },
413 	VOPNAME_SEEK,		{ .vop_seek = nfs4_seek },
414 	VOPNAME_FRLOCK,		{ .vop_frlock = nfs4_frlock },
415 	VOPNAME_SPACE,		{ .vop_space = nfs4_space },
416 	VOPNAME_REALVP,		{ .vop_realvp = nfs4_realvp },
417 	VOPNAME_GETPAGE,	{ .vop_getpage = nfs4_getpage },
418 	VOPNAME_PUTPAGE,	{ .vop_putpage = nfs4_putpage },
419 	VOPNAME_MAP,		{ .vop_map = nfs4_map },
420 	VOPNAME_ADDMAP,		{ .vop_addmap = nfs4_addmap },
421 	VOPNAME_DELMAP,		{ .vop_delmap = nfs4_delmap },
422 	/* no separate nfs4_dump */
423 	VOPNAME_DUMP,		{ .vop_dump = nfs_dump },
424 	VOPNAME_PATHCONF,	{ .vop_pathconf = nfs4_pathconf },
425 	VOPNAME_PAGEIO,		{ .vop_pageio = nfs4_pageio },
426 	VOPNAME_DISPOSE,	{ .vop_dispose = nfs4_dispose },
427 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = nfs4_setsecattr },
428 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = nfs4_getsecattr },
429 	VOPNAME_SHRLOCK,	{ .vop_shrlock = nfs4_shrlock },
430 	VOPNAME_VNEVENT, 	{ .vop_vnevent = fs_vnevent_support },
431 	NULL,			NULL
432 };
433 
434 /*
435  * The following are subroutines and definitions to set args or get res
436  * for the different nfsv4 ops
437  */
438 
439 void
440 nfs4args_lookup_free(nfs_argop4 *argop, int arglen)
441 {
442 	int		i;
443 
444 	for (i = 0; i < arglen; i++) {
445 		if (argop[i].argop == OP_LOOKUP) {
446 			kmem_free(
447 			    argop[i].nfs_argop4_u.oplookup.
448 			    objname.utf8string_val,
449 			    argop[i].nfs_argop4_u.oplookup.
450 			    objname.utf8string_len);
451 		}
452 	}
453 }
454 
455 static void
456 nfs4args_lock_free(nfs_argop4 *argop)
457 {
458 	locker4 *locker = &argop->nfs_argop4_u.oplock.locker;
459 
460 	if (locker->new_lock_owner == TRUE) {
461 		open_to_lock_owner4 *open_owner;
462 
463 		open_owner = &locker->locker4_u.open_owner;
464 		if (open_owner->lock_owner.owner_val != NULL) {
465 			kmem_free(open_owner->lock_owner.owner_val,
466 			    open_owner->lock_owner.owner_len);
467 		}
468 	}
469 }
470 
471 static void
472 nfs4args_lockt_free(nfs_argop4 *argop)
473 {
474 	lock_owner4 *lowner = &argop->nfs_argop4_u.oplockt.owner;
475 
476 	if (lowner->owner_val != NULL) {
477 		kmem_free(lowner->owner_val, lowner->owner_len);
478 	}
479 }
480 
481 static void
482 nfs4args_setattr(nfs_argop4 *argop, vattr_t *vap, vsecattr_t *vsap, int flags,
483     rnode4_t *rp, cred_t *cr, bitmap4 supp, int *error,
484     nfs4_stateid_types_t *sid_types)
485 {
486 	fattr4		*attr = &argop->nfs_argop4_u.opsetattr.obj_attributes;
487 	mntinfo4_t	*mi;
488 
489 	argop->argop = OP_SETATTR;
490 	/*
491 	 * The stateid is set to 0 if client is not modifying the size
492 	 * and otherwise to whatever nfs4_get_stateid() returns.
493 	 *
494 	 * XXX Note: nfs4_get_stateid() returns 0 if no lockowner and/or no
495 	 * state struct could be found for the process/file pair.  We may
496 	 * want to change this in the future (by OPENing the file).  See
497 	 * bug # 4474852.
498 	 */
499 	if (vap->va_mask & AT_SIZE) {
500 
501 		ASSERT(rp != NULL);
502 		mi = VTOMI4(RTOV4(rp));
503 
504 		argop->nfs_argop4_u.opsetattr.stateid =
505 		    nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
506 		    OP_SETATTR, sid_types, FALSE);
507 	} else {
508 		bzero(&argop->nfs_argop4_u.opsetattr.stateid,
509 		    sizeof (stateid4));
510 	}
511 
512 	*error = vattr_to_fattr4(vap, vsap, attr, flags, OP_SETATTR, supp);
513 	if (*error)
514 		bzero(attr, sizeof (*attr));
515 }
516 
517 static void
518 nfs4args_setattr_free(nfs_argop4 *argop)
519 {
520 	nfs4_fattr4_free(&argop->nfs_argop4_u.opsetattr.obj_attributes);
521 }
522 
523 static int
524 nfs4args_verify(nfs_argop4 *argop, vattr_t *vap, enum nfs_opnum4 op,
525     bitmap4 supp)
526 {
527 	fattr4 *attr;
528 	int error = 0;
529 
530 	argop->argop = op;
531 	switch (op) {
532 	case OP_VERIFY:
533 		attr = &argop->nfs_argop4_u.opverify.obj_attributes;
534 		break;
535 	case OP_NVERIFY:
536 		attr = &argop->nfs_argop4_u.opnverify.obj_attributes;
537 		break;
538 	default:
539 		return (EINVAL);
540 	}
541 	if (!error)
542 		error = vattr_to_fattr4(vap, NULL, attr, 0, op, supp);
543 	if (error)
544 		bzero(attr, sizeof (*attr));
545 	return (error);
546 }
547 
548 static void
549 nfs4args_verify_free(nfs_argop4 *argop)
550 {
551 	switch (argop->argop) {
552 	case OP_VERIFY:
553 		nfs4_fattr4_free(&argop->nfs_argop4_u.opverify.obj_attributes);
554 		break;
555 	case OP_NVERIFY:
556 		nfs4_fattr4_free(&argop->nfs_argop4_u.opnverify.obj_attributes);
557 		break;
558 	default:
559 		break;
560 	}
561 }
562 
563 static void
564 nfs4args_write(nfs_argop4 *argop, stable_how4 stable, rnode4_t *rp, cred_t *cr,
565     WRITE4args **wargs_pp, nfs4_stateid_types_t *sid_tp)
566 {
567 	WRITE4args *wargs = &argop->nfs_argop4_u.opwrite;
568 	mntinfo4_t *mi = VTOMI4(RTOV4(rp));
569 
570 	argop->argop = OP_WRITE;
571 	wargs->stable = stable;
572 	wargs->stateid = nfs4_get_w_stateid(cr, rp, curproc->p_pidp->pid_id,
573 	    mi, OP_WRITE, sid_tp);
574 	wargs->mblk = NULL;
575 	*wargs_pp = wargs;
576 }
577 
578 void
579 nfs4args_copen_free(OPEN4cargs *open_args)
580 {
581 	if (open_args->owner.owner_val) {
582 		kmem_free(open_args->owner.owner_val,
583 		    open_args->owner.owner_len);
584 	}
585 	if ((open_args->opentype == OPEN4_CREATE) &&
586 	    (open_args->mode != EXCLUSIVE4)) {
587 		nfs4_fattr4_free(&open_args->createhow4_u.createattrs);
588 	}
589 }
590 
591 /*
592  * XXX:  This is referenced in modstubs.s
593  */
594 struct vnodeops *
595 nfs4_getvnodeops(void)
596 {
597 	return (nfs4_vnodeops);
598 }
599 
600 /*
601  * The OPEN operation opens a regular file.
602  */
603 /*ARGSUSED3*/
604 static int
605 nfs4_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
606 {
607 	vnode_t *dvp = NULL;
608 	rnode4_t *rp, *drp;
609 	int error;
610 	int just_been_created;
611 	char fn[MAXNAMELEN];
612 
613 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4_open: "));
614 	if (nfs_zone() != VTOMI4(*vpp)->mi_zone)
615 		return (EIO);
616 	rp = VTOR4(*vpp);
617 
618 	/*
619 	 * Check to see if opening something besides a regular file;
620 	 * if so skip the OTW call
621 	 */
622 	if ((*vpp)->v_type != VREG) {
623 		error = nfs4_open_non_reg_file(vpp, flag, cr);
624 		return (error);
625 	}
626 
627 	/*
628 	 * XXX - would like a check right here to know if the file is
629 	 * executable or not, so as to skip OTW
630 	 */
631 
632 	if ((error = vtodv(*vpp, &dvp, cr, TRUE)) != 0)
633 		return (error);
634 
635 	drp = VTOR4(dvp);
636 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
637 		return (EINTR);
638 
639 	if ((error = vtoname(*vpp, fn, MAXNAMELEN)) != 0) {
640 		nfs_rw_exit(&drp->r_rwlock);
641 		return (error);
642 	}
643 
644 	/*
645 	 * See if this file has just been CREATEd.
646 	 * If so, clear the flag and update the dnlc, which was previously
647 	 * skipped in nfs4_create.
648 	 * XXX need better serilization on this.
649 	 * XXX move this into the nf4open_otw call, after we have
650 	 * XXX acquired the open owner seqid sync.
651 	 */
652 	mutex_enter(&rp->r_statev4_lock);
653 	if (rp->created_v4) {
654 		rp->created_v4 = 0;
655 		mutex_exit(&rp->r_statev4_lock);
656 
657 		dnlc_update(dvp, fn, *vpp);
658 		/* This is needed so we don't bump the open ref count */
659 		just_been_created = 1;
660 	} else {
661 		mutex_exit(&rp->r_statev4_lock);
662 		just_been_created = 0;
663 	}
664 
665 	/*
666 	 * If caller specified O_TRUNC/FTRUNC, then be sure to set
667 	 * FWRITE (to drive successful setattr(size=0) after open)
668 	 */
669 	if (flag & FTRUNC)
670 		flag |= FWRITE;
671 
672 	error = nfs4open_otw(dvp, fn, NULL, vpp, cr, 0, flag, 0,
673 	    just_been_created);
674 
675 	if (!error && !((*vpp)->v_flag & VROOT))
676 		dnlc_update(dvp, fn, *vpp);
677 
678 	nfs_rw_exit(&drp->r_rwlock);
679 
680 	/* release the hold from vtodv */
681 	VN_RELE(dvp);
682 
683 	/* exchange the shadow for the master vnode, if needed */
684 
685 	if (error == 0 && IS_SHADOW(*vpp, rp))
686 		sv_exchange(vpp);
687 
688 	return (error);
689 }
690 
691 /*
692  * See if there's a "lost open" request to be saved and recovered.
693  */
694 static void
695 nfs4open_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
696     nfs4_open_owner_t *oop, cred_t *cr, vnode_t *vp,
697     vnode_t *dvp, OPEN4cargs *open_args)
698 {
699 	vfs_t *vfsp;
700 	char *srccfp;
701 
702 	vfsp = (dvp ? dvp->v_vfsp : vp->v_vfsp);
703 
704 	if (error != ETIMEDOUT && error != EINTR &&
705 	    !NFS4_FRC_UNMT_ERR(error, vfsp)) {
706 		lost_rqstp->lr_op = 0;
707 		return;
708 	}
709 
710 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
711 	    "nfs4open_save_lost_rqst: error %d", error));
712 
713 	lost_rqstp->lr_op = OP_OPEN;
714 
715 	/*
716 	 * The vp (if it is not NULL) and dvp are held and rele'd via
717 	 * the recovery code.  See nfs4_save_lost_rqst.
718 	 */
719 	lost_rqstp->lr_vp = vp;
720 	lost_rqstp->lr_dvp = dvp;
721 	lost_rqstp->lr_oop = oop;
722 	lost_rqstp->lr_osp = NULL;
723 	lost_rqstp->lr_lop = NULL;
724 	lost_rqstp->lr_cr = cr;
725 	lost_rqstp->lr_flk = NULL;
726 	lost_rqstp->lr_oacc = open_args->share_access;
727 	lost_rqstp->lr_odeny = open_args->share_deny;
728 	lost_rqstp->lr_oclaim = open_args->claim;
729 	if (open_args->claim == CLAIM_DELEGATE_CUR) {
730 		lost_rqstp->lr_ostateid =
731 		    open_args->open_claim4_u.delegate_cur_info.delegate_stateid;
732 		srccfp = open_args->open_claim4_u.delegate_cur_info.cfile;
733 	} else {
734 		srccfp = open_args->open_claim4_u.cfile;
735 	}
736 	lost_rqstp->lr_ofile.utf8string_len = 0;
737 	lost_rqstp->lr_ofile.utf8string_val = NULL;
738 	(void) str_to_utf8(srccfp, &lost_rqstp->lr_ofile);
739 	lost_rqstp->lr_putfirst = FALSE;
740 }
741 
742 struct nfs4_excl_time {
743 	uint32 seconds;
744 	uint32 nseconds;
745 };
746 
747 /*
748  * The OPEN operation creates and/or opens a regular file
749  *
750  * ARGSUSED
751  */
752 static int
753 nfs4open_otw(vnode_t *dvp, char *file_name, struct vattr *in_va,
754     vnode_t **vpp, cred_t *cr, int create_flag, int open_flag,
755     enum createmode4 createmode, int file_just_been_created)
756 {
757 	rnode4_t *rp;
758 	rnode4_t *drp = VTOR4(dvp);
759 	vnode_t *vp = NULL;
760 	vnode_t *vpi = *vpp;
761 	bool_t needrecov = FALSE;
762 
763 	int doqueue = 1;
764 
765 	COMPOUND4args_clnt args;
766 	COMPOUND4res_clnt res;
767 	nfs_argop4 *argop;
768 	nfs_resop4 *resop;
769 	int argoplist_size;
770 	int idx_open, idx_fattr;
771 
772 	GETFH4res *gf_res = NULL;
773 	OPEN4res *op_res = NULL;
774 	nfs4_ga_res_t *garp;
775 	fattr4 *attr = NULL;
776 	struct nfs4_excl_time verf;
777 	bool_t did_excl_setup = FALSE;
778 	int created_osp;
779 
780 	OPEN4cargs *open_args;
781 	nfs4_open_owner_t	*oop = NULL;
782 	nfs4_open_stream_t	*osp = NULL;
783 	seqid4 seqid = 0;
784 	bool_t retry_open = FALSE;
785 	nfs4_recov_state_t recov_state;
786 	nfs4_lost_rqst_t lost_rqst;
787 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
788 	hrtime_t t;
789 	int acc = 0;
790 	cred_t *cred_otw = NULL;	/* cred used to do the RPC call */
791 	cred_t *ncr = NULL;
792 
793 	nfs4_sharedfh_t *otw_sfh;
794 	nfs4_sharedfh_t *orig_sfh;
795 	int fh_differs = 0;
796 	int numops, setgid_flag;
797 	int num_bseqid_retry = NFS4_NUM_RETRY_BAD_SEQID + 1;
798 
799 	/*
800 	 * Make sure we properly deal with setting the right gid on
801 	 * a newly created file to reflect the parent's setgid bit
802 	 */
803 	setgid_flag = 0;
804 	if (create_flag && in_va) {
805 
806 		/*
807 		 * If the parent's directory has the setgid bit set
808 		 * _and_ the client was able to get a valid mapping
809 		 * for the parent dir's owner_group, we want to
810 		 * append NVERIFY(owner_group == dva.va_gid) and
811 		 * SETATTR to the CREATE compound.
812 		 */
813 		mutex_enter(&drp->r_statelock);
814 		if (drp->r_attr.va_mode & VSGID &&
815 		    drp->r_attr.va_gid != GID_NOBODY) {
816 			in_va->va_gid = drp->r_attr.va_gid;
817 			setgid_flag = 1;
818 		}
819 		mutex_exit(&drp->r_statelock);
820 	}
821 
822 	/*
823 	 * Normal/non-create compound:
824 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new)
825 	 *
826 	 * Open(create) compound no setgid:
827 	 * PUTFH(dfh) + SAVEFH + OPEN(create) + GETFH + GETATTR(new) +
828 	 * RESTOREFH + GETATTR
829 	 *
830 	 * Open(create) setgid:
831 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new) +
832 	 * SAVEFH + PUTFH(dfh) + GETATTR(dvp) + RESTOREFH +
833 	 * NVERIFY(grp) + SETATTR
834 	 */
835 	if (setgid_flag) {
836 		numops = 10;
837 		idx_open = 1;
838 		idx_fattr = 3;
839 	} else if (create_flag) {
840 		numops = 7;
841 		idx_open = 2;
842 		idx_fattr = 4;
843 	} else {
844 		numops = 4;
845 		idx_open = 1;
846 		idx_fattr = 3;
847 	}
848 
849 	args.array_len = numops;
850 	argoplist_size = numops * sizeof (nfs_argop4);
851 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
852 
853 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw: "
854 	    "open %s open flag 0x%x cred %p", file_name, open_flag,
855 	    (void *)cr));
856 
857 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
858 	if (create_flag) {
859 		/*
860 		 * We are to create a file.  Initialize the passed in vnode
861 		 * pointer.
862 		 */
863 		vpi = NULL;
864 	} else {
865 		/*
866 		 * Check to see if the client owns a read delegation and is
867 		 * trying to open for write.  If so, then return the delegation
868 		 * to avoid the server doing a cb_recall and returning DELAY.
869 		 * NB - we don't use the statev4_lock here because we'd have
870 		 * to drop the lock anyway and the result would be stale.
871 		 */
872 		if ((open_flag & FWRITE) &&
873 		    VTOR4(vpi)->r_deleg_type == OPEN_DELEGATE_READ)
874 			(void) nfs4delegreturn(VTOR4(vpi), NFS4_DR_REOPEN);
875 
876 		/*
877 		 * If the file has a delegation, then do an access check up
878 		 * front.  This avoids having to an access check later after
879 		 * we've already done start_op, which could deadlock.
880 		 */
881 		if (VTOR4(vpi)->r_deleg_type != OPEN_DELEGATE_NONE) {
882 			if (open_flag & FREAD &&
883 			    nfs4_access(vpi, VREAD, 0, cr, NULL) == 0)
884 				acc |= VREAD;
885 			if (open_flag & FWRITE &&
886 			    nfs4_access(vpi, VWRITE, 0, cr, NULL) == 0)
887 				acc |= VWRITE;
888 		}
889 	}
890 
891 	drp = VTOR4(dvp);
892 
893 	recov_state.rs_flags = 0;
894 	recov_state.rs_num_retry_despite_err = 0;
895 	cred_otw = cr;
896 
897 recov_retry:
898 	fh_differs = 0;
899 	nfs4_error_zinit(&e);
900 
901 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, vpi, &recov_state);
902 	if (e.error) {
903 		if (ncr != NULL)
904 			crfree(ncr);
905 		kmem_free(argop, argoplist_size);
906 		return (e.error);
907 	}
908 
909 	args.ctag = TAG_OPEN;
910 	args.array_len = numops;
911 	args.array = argop;
912 
913 	/* putfh directory fh */
914 	argop[0].argop = OP_CPUTFH;
915 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
916 
917 	/* OPEN: either op 1 or op 2 depending upon create/setgid flags */
918 	argop[idx_open].argop = OP_COPEN;
919 	open_args = &argop[idx_open].nfs_argop4_u.opcopen;
920 	open_args->claim = CLAIM_NULL;
921 
922 	/* name of file */
923 	open_args->open_claim4_u.cfile = file_name;
924 	open_args->owner.owner_len = 0;
925 	open_args->owner.owner_val = NULL;
926 
927 	if (create_flag) {
928 		/* CREATE a file */
929 		open_args->opentype = OPEN4_CREATE;
930 		open_args->mode = createmode;
931 		if (createmode == EXCLUSIVE4) {
932 			if (did_excl_setup == FALSE) {
933 				verf.seconds = zone_get_hostid(NULL);
934 				if (verf.seconds != 0)
935 					verf.nseconds = newnum();
936 				else {
937 					timestruc_t now;
938 
939 					gethrestime(&now);
940 					verf.seconds = now.tv_sec;
941 					verf.nseconds = now.tv_nsec;
942 				}
943 				/*
944 				 * Since the server will use this value for the
945 				 * mtime, make sure that it can't overflow. Zero
946 				 * out the MSB. The actual value does not matter
947 				 * here, only its uniqeness.
948 				 */
949 				verf.seconds &= INT32_MAX;
950 				did_excl_setup = TRUE;
951 			}
952 
953 			/* Now copy over verifier to OPEN4args. */
954 			open_args->createhow4_u.createverf = *(uint64_t *)&verf;
955 		} else {
956 			int v_error;
957 			bitmap4 supp_attrs;
958 			servinfo4_t *svp;
959 
960 			attr = &open_args->createhow4_u.createattrs;
961 
962 			svp = drp->r_server;
963 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
964 			supp_attrs = svp->sv_supp_attrs;
965 			nfs_rw_exit(&svp->sv_lock);
966 
967 			/* GUARDED4 or UNCHECKED4 */
968 			v_error = vattr_to_fattr4(in_va, NULL, attr, 0, OP_OPEN,
969 			    supp_attrs);
970 			if (v_error) {
971 				bzero(attr, sizeof (*attr));
972 				nfs4args_copen_free(open_args);
973 				nfs4_end_op(VTOMI4(dvp), dvp, vpi,
974 				    &recov_state, FALSE);
975 				if (ncr != NULL)
976 					crfree(ncr);
977 				kmem_free(argop, argoplist_size);
978 				return (v_error);
979 			}
980 		}
981 	} else {
982 		/* NO CREATE */
983 		open_args->opentype = OPEN4_NOCREATE;
984 	}
985 
986 	if (recov_state.rs_sp != NULL) {
987 		mutex_enter(&recov_state.rs_sp->s_lock);
988 		open_args->owner.clientid = recov_state.rs_sp->clientid;
989 		mutex_exit(&recov_state.rs_sp->s_lock);
990 	} else {
991 		/* XXX should we just fail here? */
992 		open_args->owner.clientid = 0;
993 	}
994 
995 	/*
996 	 * This increments oop's ref count or creates a temporary 'just_created'
997 	 * open owner that will become valid when this OPEN/OPEN_CONFIRM call
998 	 * completes.
999 	 */
1000 	mutex_enter(&VTOMI4(dvp)->mi_lock);
1001 
1002 	/* See if a permanent or just created open owner exists */
1003 	oop = find_open_owner_nolock(cr, NFS4_JUST_CREATED, VTOMI4(dvp));
1004 	if (!oop) {
1005 		/*
1006 		 * This open owner does not exist so create a temporary
1007 		 * just created one.
1008 		 */
1009 		oop = create_open_owner(cr, VTOMI4(dvp));
1010 		ASSERT(oop != NULL);
1011 	}
1012 	mutex_exit(&VTOMI4(dvp)->mi_lock);
1013 
1014 	/* this length never changes, do alloc before seqid sync */
1015 	open_args->owner.owner_len = sizeof (oop->oo_name);
1016 	open_args->owner.owner_val =
1017 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1018 
1019 	e.error = nfs4_start_open_seqid_sync(oop, VTOMI4(dvp));
1020 	if (e.error == EAGAIN) {
1021 		open_owner_rele(oop);
1022 		nfs4args_copen_free(open_args);
1023 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1024 		if (ncr != NULL) {
1025 			crfree(ncr);
1026 			ncr = NULL;
1027 		}
1028 		goto recov_retry;
1029 	}
1030 
1031 	/* Check to see if we need to do the OTW call */
1032 	if (!create_flag) {
1033 		if (!nfs4_is_otw_open_necessary(oop, open_flag, vpi,
1034 		    file_just_been_created, &e.error, acc, &recov_state)) {
1035 
1036 			/*
1037 			 * The OTW open is not necessary.  Either
1038 			 * the open can succeed without it (eg.
1039 			 * delegation, error == 0) or the open
1040 			 * must fail due to an access failure
1041 			 * (error != 0).  In either case, tidy
1042 			 * up and return.
1043 			 */
1044 
1045 			nfs4_end_open_seqid_sync(oop);
1046 			open_owner_rele(oop);
1047 			nfs4args_copen_free(open_args);
1048 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, FALSE);
1049 			if (ncr != NULL)
1050 				crfree(ncr);
1051 			kmem_free(argop, argoplist_size);
1052 			return (e.error);
1053 		}
1054 	}
1055 
1056 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1057 	    open_args->owner.owner_len);
1058 
1059 	seqid = nfs4_get_open_seqid(oop) + 1;
1060 	open_args->seqid = seqid;
1061 	open_args->share_access = 0;
1062 	if (open_flag & FREAD)
1063 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1064 	if (open_flag & FWRITE)
1065 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1066 	open_args->share_deny = OPEN4_SHARE_DENY_NONE;
1067 
1068 
1069 
1070 	/*
1071 	 * getfh w/sanity check for idx_open/idx_fattr
1072 	 */
1073 	ASSERT((idx_open + 1) == (idx_fattr - 1));
1074 	argop[idx_open + 1].argop = OP_GETFH;
1075 
1076 	/* getattr */
1077 	argop[idx_fattr].argop = OP_GETATTR;
1078 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1079 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1080 
1081 	if (setgid_flag) {
1082 		vattr_t	_v;
1083 		servinfo4_t *svp;
1084 		bitmap4	supp_attrs;
1085 
1086 		svp = drp->r_server;
1087 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1088 		supp_attrs = svp->sv_supp_attrs;
1089 		nfs_rw_exit(&svp->sv_lock);
1090 
1091 		/*
1092 		 * For setgid case, we need to:
1093 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1094 		 */
1095 		argop[4].argop = OP_SAVEFH;
1096 
1097 		argop[5].argop = OP_CPUTFH;
1098 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
1099 
1100 		argop[6].argop = OP_GETATTR;
1101 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1102 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1103 
1104 		argop[7].argop = OP_RESTOREFH;
1105 
1106 		/*
1107 		 * nverify
1108 		 */
1109 		_v.va_mask = AT_GID;
1110 		_v.va_gid = in_va->va_gid;
1111 		if (!(e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
1112 		    supp_attrs))) {
1113 
1114 			/*
1115 			 * setattr
1116 			 *
1117 			 * We _know_ we're not messing with AT_SIZE or
1118 			 * AT_XTIME, so no need for stateid or flags.
1119 			 * Also we specify NULL rp since we're only
1120 			 * interested in setting owner_group attributes.
1121 			 */
1122 			nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr,
1123 			    supp_attrs, &e.error, 0);
1124 			if (e.error)
1125 				nfs4args_verify_free(&argop[8]);
1126 		}
1127 
1128 		if (e.error) {
1129 			/*
1130 			 * XXX - Revisit the last argument to nfs4_end_op()
1131 			 *	 once 5020486 is fixed.
1132 			 */
1133 			nfs4_end_open_seqid_sync(oop);
1134 			open_owner_rele(oop);
1135 			nfs4args_copen_free(open_args);
1136 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1137 			if (ncr != NULL)
1138 				crfree(ncr);
1139 			kmem_free(argop, argoplist_size);
1140 			return (e.error);
1141 		}
1142 	} else if (create_flag) {
1143 		/*
1144 		 * For setgid case, we need to:
1145 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1146 		 */
1147 		argop[1].argop = OP_SAVEFH;
1148 
1149 		argop[5].argop = OP_RESTOREFH;
1150 
1151 		argop[6].argop = OP_GETATTR;
1152 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1153 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1154 	}
1155 
1156 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1157 	    "nfs4open_otw: %s call, nm %s, rp %s",
1158 	    needrecov ? "recov" : "first", file_name,
1159 	    rnode4info(VTOR4(dvp))));
1160 
1161 	t = gethrtime();
1162 
1163 	rfs4call(VTOMI4(dvp), &args, &res, cred_otw, &doqueue, 0, &e);
1164 
1165 	if (!e.error && nfs4_need_to_bump_seqid(&res))
1166 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1167 
1168 	needrecov = nfs4_needs_recovery(&e, TRUE, dvp->v_vfsp);
1169 
1170 	if (e.error || needrecov) {
1171 		bool_t abort = FALSE;
1172 
1173 		if (needrecov) {
1174 			nfs4_bseqid_entry_t *bsep = NULL;
1175 
1176 			nfs4open_save_lost_rqst(e.error, &lost_rqst, oop,
1177 			    cred_otw, vpi, dvp, open_args);
1178 
1179 			if (!e.error && res.status == NFS4ERR_BAD_SEQID) {
1180 				bsep = nfs4_create_bseqid_entry(oop, NULL,
1181 				    vpi, 0, args.ctag, open_args->seqid);
1182 				num_bseqid_retry--;
1183 			}
1184 
1185 			abort = nfs4_start_recovery(&e, VTOMI4(dvp), dvp, vpi,
1186 			    NULL, lost_rqst.lr_op == OP_OPEN ?
1187 			    &lost_rqst : NULL, OP_OPEN, bsep);
1188 
1189 			if (bsep)
1190 				kmem_free(bsep, sizeof (*bsep));
1191 			/* give up if we keep getting BAD_SEQID */
1192 			if (num_bseqid_retry == 0)
1193 				abort = TRUE;
1194 			if (abort == TRUE && e.error == 0)
1195 				e.error = geterrno4(res.status);
1196 		}
1197 		nfs4_end_open_seqid_sync(oop);
1198 		open_owner_rele(oop);
1199 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1200 		nfs4args_copen_free(open_args);
1201 		if (setgid_flag) {
1202 			nfs4args_verify_free(&argop[8]);
1203 			nfs4args_setattr_free(&argop[9]);
1204 		}
1205 		if (!e.error)
1206 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1207 		if (ncr != NULL) {
1208 			crfree(ncr);
1209 			ncr = NULL;
1210 		}
1211 		if (!needrecov || abort == TRUE || e.error == EINTR ||
1212 		    NFS4_FRC_UNMT_ERR(e.error, dvp->v_vfsp)) {
1213 			kmem_free(argop, argoplist_size);
1214 			return (e.error);
1215 		}
1216 		goto recov_retry;
1217 	}
1218 
1219 	/*
1220 	 * Will check and update lease after checking the rflag for
1221 	 * OPEN_CONFIRM in the successful OPEN call.
1222 	 */
1223 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
1224 
1225 		/*
1226 		 * XXX what if we're crossing mount points from server1:/drp
1227 		 * to server2:/drp/rp.
1228 		 */
1229 
1230 		/* Signal our end of use of the open seqid */
1231 		nfs4_end_open_seqid_sync(oop);
1232 
1233 		/*
1234 		 * This will destroy the open owner if it was just created,
1235 		 * and no one else has put a reference on it.
1236 		 */
1237 		open_owner_rele(oop);
1238 		if (create_flag && (createmode != EXCLUSIVE4) &&
1239 		    res.status == NFS4ERR_BADOWNER)
1240 			nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1241 
1242 		e.error = geterrno4(res.status);
1243 		nfs4args_copen_free(open_args);
1244 		if (setgid_flag) {
1245 			nfs4args_verify_free(&argop[8]);
1246 			nfs4args_setattr_free(&argop[9]);
1247 		}
1248 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1249 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1250 		/*
1251 		 * If the reply is NFS4ERR_ACCESS, it may be because
1252 		 * we are root (no root net access).  If the real uid
1253 		 * is not root, then retry with the real uid instead.
1254 		 */
1255 		if (ncr != NULL) {
1256 			crfree(ncr);
1257 			ncr = NULL;
1258 		}
1259 		if (res.status == NFS4ERR_ACCESS &&
1260 		    (ncr = crnetadjust(cred_otw)) != NULL) {
1261 			cred_otw = ncr;
1262 			goto recov_retry;
1263 		}
1264 		kmem_free(argop, argoplist_size);
1265 		return (e.error);
1266 	}
1267 
1268 	resop = &res.array[idx_open];  /* open res */
1269 	op_res = &resop->nfs_resop4_u.opopen;
1270 
1271 #ifdef DEBUG
1272 	/*
1273 	 * verify attrset bitmap
1274 	 */
1275 	if (create_flag &&
1276 	    (createmode == UNCHECKED4 || createmode == GUARDED4)) {
1277 		/* make sure attrset returned is what we asked for */
1278 		/* XXX Ignore this 'error' for now */
1279 		if (attr->attrmask != op_res->attrset)
1280 			/* EMPTY */;
1281 	}
1282 #endif
1283 
1284 	if (op_res->rflags & OPEN4_RESULT_LOCKTYPE_POSIX) {
1285 		mutex_enter(&VTOMI4(dvp)->mi_lock);
1286 		VTOMI4(dvp)->mi_flags |= MI4_POSIX_LOCK;
1287 		mutex_exit(&VTOMI4(dvp)->mi_lock);
1288 	}
1289 
1290 	resop = &res.array[idx_open + 1];  /* getfh res */
1291 	gf_res = &resop->nfs_resop4_u.opgetfh;
1292 
1293 	otw_sfh = sfh4_get(&gf_res->object, VTOMI4(dvp));
1294 
1295 	/*
1296 	 * The open stateid has been updated on the server but not
1297 	 * on the client yet.  There is a path: makenfs4node->nfs4_attr_cache->
1298 	 * flush_pages->VOP_PUTPAGE->...->nfs4write where we will issue an OTW
1299 	 * WRITE call.  That, however, will use the old stateid, so go ahead
1300 	 * and upate the open stateid now, before any call to makenfs4node.
1301 	 */
1302 	if (vpi) {
1303 		nfs4_open_stream_t	*tmp_osp;
1304 		rnode4_t		*tmp_rp = VTOR4(vpi);
1305 
1306 		tmp_osp = find_open_stream(oop, tmp_rp);
1307 		if (tmp_osp) {
1308 			tmp_osp->open_stateid = op_res->stateid;
1309 			mutex_exit(&tmp_osp->os_sync_lock);
1310 			open_stream_rele(tmp_osp, tmp_rp);
1311 		}
1312 
1313 		/*
1314 		 * We must determine if the file handle given by the otw open
1315 		 * is the same as the file handle which was passed in with
1316 		 * *vpp.  This case can be reached if the file we are trying
1317 		 * to open has been removed and another file has been created
1318 		 * having the same file name.  The passed in vnode is released
1319 		 * later.
1320 		 */
1321 		orig_sfh = VTOR4(vpi)->r_fh;
1322 		fh_differs = nfs4cmpfh(&orig_sfh->sfh_fh, &otw_sfh->sfh_fh);
1323 	}
1324 
1325 	garp = &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res;
1326 
1327 	if (create_flag || fh_differs) {
1328 		int rnode_err = 0;
1329 
1330 		vp = makenfs4node(otw_sfh, garp, dvp->v_vfsp, t, cr,
1331 		    dvp, fn_get(VTOSV(dvp)->sv_name, file_name, otw_sfh));
1332 
1333 		if (e.error)
1334 			PURGE_ATTRCACHE4(vp);
1335 		/*
1336 		 * For the newly created vp case, make sure the rnode
1337 		 * isn't bad before using it.
1338 		 */
1339 		mutex_enter(&(VTOR4(vp))->r_statelock);
1340 		if (VTOR4(vp)->r_flags & R4RECOVERR)
1341 			rnode_err = EIO;
1342 		mutex_exit(&(VTOR4(vp))->r_statelock);
1343 
1344 		if (rnode_err) {
1345 			nfs4_end_open_seqid_sync(oop);
1346 			nfs4args_copen_free(open_args);
1347 			if (setgid_flag) {
1348 				nfs4args_verify_free(&argop[8]);
1349 				nfs4args_setattr_free(&argop[9]);
1350 			}
1351 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1352 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1353 			    needrecov);
1354 			open_owner_rele(oop);
1355 			VN_RELE(vp);
1356 			if (ncr != NULL)
1357 				crfree(ncr);
1358 			sfh4_rele(&otw_sfh);
1359 			kmem_free(argop, argoplist_size);
1360 			return (EIO);
1361 		}
1362 	} else {
1363 		vp = vpi;
1364 	}
1365 	sfh4_rele(&otw_sfh);
1366 
1367 	/*
1368 	 * It seems odd to get a full set of attrs and then not update
1369 	 * the object's attrcache in the non-create case.  Create case uses
1370 	 * the attrs since makenfs4node checks to see if the attrs need to
1371 	 * be updated (and then updates them).  The non-create case should
1372 	 * update attrs also.
1373 	 */
1374 	if (! create_flag && ! fh_differs && !e.error) {
1375 		nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
1376 	}
1377 
1378 	nfs4_error_zinit(&e);
1379 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
1380 		/* This does not do recovery for vp explicitly. */
1381 		nfs4open_confirm(vp, &seqid, &op_res->stateid, cred_otw, FALSE,
1382 		    &retry_open, oop, FALSE, &e, &num_bseqid_retry);
1383 
1384 		if (e.error || e.stat) {
1385 			nfs4_end_open_seqid_sync(oop);
1386 			nfs4args_copen_free(open_args);
1387 			if (setgid_flag) {
1388 				nfs4args_verify_free(&argop[8]);
1389 				nfs4args_setattr_free(&argop[9]);
1390 			}
1391 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1392 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1393 			    needrecov);
1394 			open_owner_rele(oop);
1395 			if (create_flag || fh_differs) {
1396 				/* rele the makenfs4node */
1397 				VN_RELE(vp);
1398 			}
1399 			if (ncr != NULL) {
1400 				crfree(ncr);
1401 				ncr = NULL;
1402 			}
1403 			if (retry_open == TRUE) {
1404 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1405 				    "nfs4open_otw: retry the open since OPEN "
1406 				    "CONFIRM failed with error %d stat %d",
1407 				    e.error, e.stat));
1408 				if (create_flag && createmode == GUARDED4) {
1409 					NFS4_DEBUG(nfs4_client_recov_debug,
1410 					    (CE_NOTE, "nfs4open_otw: switch "
1411 					    "createmode from GUARDED4 to "
1412 					    "UNCHECKED4"));
1413 					createmode = UNCHECKED4;
1414 				}
1415 				goto recov_retry;
1416 			}
1417 			if (!e.error) {
1418 				if (create_flag && (createmode != EXCLUSIVE4) &&
1419 				    e.stat == NFS4ERR_BADOWNER)
1420 					nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1421 
1422 				e.error = geterrno4(e.stat);
1423 			}
1424 			kmem_free(argop, argoplist_size);
1425 			return (e.error);
1426 		}
1427 	}
1428 
1429 	rp = VTOR4(vp);
1430 
1431 	mutex_enter(&rp->r_statev4_lock);
1432 	if (create_flag)
1433 		rp->created_v4 = 1;
1434 	mutex_exit(&rp->r_statev4_lock);
1435 
1436 	mutex_enter(&oop->oo_lock);
1437 	/* Doesn't matter if 'oo_just_created' already was set as this */
1438 	oop->oo_just_created = NFS4_PERM_CREATED;
1439 	if (oop->oo_cred_otw)
1440 		crfree(oop->oo_cred_otw);
1441 	oop->oo_cred_otw = cred_otw;
1442 	crhold(oop->oo_cred_otw);
1443 	mutex_exit(&oop->oo_lock);
1444 
1445 	/* returns with 'os_sync_lock' held */
1446 	osp = find_or_create_open_stream(oop, rp, &created_osp);
1447 	if (!osp) {
1448 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1449 		    "nfs4open_otw: failed to create an open stream"));
1450 		NFS4_DEBUG(nfs4_seqid_sync, (CE_NOTE, "nfs4open_otw: "
1451 		    "signal our end of use of the open seqid"));
1452 
1453 		nfs4_end_open_seqid_sync(oop);
1454 		open_owner_rele(oop);
1455 		nfs4args_copen_free(open_args);
1456 		if (setgid_flag) {
1457 			nfs4args_verify_free(&argop[8]);
1458 			nfs4args_setattr_free(&argop[9]);
1459 		}
1460 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1461 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1462 		if (create_flag || fh_differs)
1463 			VN_RELE(vp);
1464 		if (ncr != NULL)
1465 			crfree(ncr);
1466 
1467 		kmem_free(argop, argoplist_size);
1468 		return (EINVAL);
1469 
1470 	}
1471 
1472 	osp->open_stateid = op_res->stateid;
1473 
1474 	if (open_flag & FREAD)
1475 		osp->os_share_acc_read++;
1476 	if (open_flag & FWRITE)
1477 		osp->os_share_acc_write++;
1478 	osp->os_share_deny_none++;
1479 
1480 	/*
1481 	 * Need to reset this bitfield for the possible case where we were
1482 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
1483 	 * we could retry the CLOSE, OPENed the file again.
1484 	 */
1485 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
1486 	osp->os_final_close = 0;
1487 	osp->os_force_close = 0;
1488 #ifdef DEBUG
1489 	if (osp->os_failed_reopen)
1490 		NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE, "nfs4open_otw:"
1491 		    " clearing os_failed_reopen for osp %p, cr %p, rp %s",
1492 		    (void *)osp, (void *)cr, rnode4info(rp)));
1493 #endif
1494 	osp->os_failed_reopen = 0;
1495 
1496 	mutex_exit(&osp->os_sync_lock);
1497 
1498 	nfs4_end_open_seqid_sync(oop);
1499 
1500 	if (created_osp && recov_state.rs_sp != NULL) {
1501 		mutex_enter(&recov_state.rs_sp->s_lock);
1502 		nfs4_inc_state_ref_count_nolock(recov_state.rs_sp, VTOMI4(dvp));
1503 		mutex_exit(&recov_state.rs_sp->s_lock);
1504 	}
1505 
1506 	/* get rid of our reference to find oop */
1507 	open_owner_rele(oop);
1508 
1509 	open_stream_rele(osp, rp);
1510 
1511 	/* accept delegation, if any */
1512 	nfs4_delegation_accept(rp, CLAIM_NULL, op_res, garp, cred_otw);
1513 
1514 	nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1515 
1516 	if (createmode == EXCLUSIVE4 &&
1517 	    (in_va->va_mask & ~(AT_GID | AT_SIZE))) {
1518 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw:"
1519 		    " EXCLUSIVE4: sending a SETATTR"));
1520 		/*
1521 		 * If doing an exclusive create, then generate
1522 		 * a SETATTR to set the initial attributes.
1523 		 * Try to set the mtime and the atime to the
1524 		 * server's current time.  It is somewhat
1525 		 * expected that these fields will be used to
1526 		 * store the exclusive create cookie.  If not,
1527 		 * server implementors will need to know that
1528 		 * a SETATTR will follow an exclusive create
1529 		 * and the cookie should be destroyed if
1530 		 * appropriate.
1531 		 *
1532 		 * The AT_GID and AT_SIZE bits are turned off
1533 		 * so that the SETATTR request will not attempt
1534 		 * to process these.  The gid will be set
1535 		 * separately if appropriate.  The size is turned
1536 		 * off because it is assumed that a new file will
1537 		 * be created empty and if the file wasn't empty,
1538 		 * then the exclusive create will have failed
1539 		 * because the file must have existed already.
1540 		 * Therefore, no truncate operation is needed.
1541 		 */
1542 		in_va->va_mask &= ~(AT_GID | AT_SIZE);
1543 		in_va->va_mask |= (AT_MTIME | AT_ATIME);
1544 
1545 		e.error = nfs4setattr(vp, in_va, 0, cr, NULL);
1546 		if (e.error) {
1547 			/*
1548 			 * Couldn't correct the attributes of
1549 			 * the newly created file and the
1550 			 * attributes are wrong.  Remove the
1551 			 * file and return an error to the
1552 			 * application.
1553 			 */
1554 			/* XXX will this take care of client state ? */
1555 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1556 			    "nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1557 			    " remove file", e.error));
1558 			VN_RELE(vp);
1559 			(void) nfs4_remove(dvp, file_name, cr, NULL, 0);
1560 			/*
1561 			 * Since we've reled the vnode and removed
1562 			 * the file we now need to return the error.
1563 			 * At this point we don't want to update the
1564 			 * dircaches, call nfs4_waitfor_purge_complete
1565 			 * or set vpp to vp so we need to skip these
1566 			 * as well.
1567 			 */
1568 			goto skip_update_dircaches;
1569 		}
1570 	}
1571 
1572 	/*
1573 	 * If we created or found the correct vnode, due to create_flag or
1574 	 * fh_differs being set, then update directory cache attribute, readdir
1575 	 * and dnlc caches.
1576 	 */
1577 	if (create_flag || fh_differs) {
1578 		dirattr_info_t dinfo, *dinfop;
1579 
1580 		/*
1581 		 * Make sure getattr succeeded before using results.
1582 		 * note: op 7 is getattr(dir) for both flavors of
1583 		 * open(create).
1584 		 */
1585 		if (create_flag && res.status == NFS4_OK) {
1586 			dinfo.di_time_call = t;
1587 			dinfo.di_cred = cr;
1588 			dinfo.di_garp =
1589 			    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
1590 			dinfop = &dinfo;
1591 		} else {
1592 			dinfop = NULL;
1593 		}
1594 
1595 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1596 		    dinfop);
1597 	}
1598 
1599 	/*
1600 	 * If the page cache for this file was flushed from actions
1601 	 * above, it was done asynchronously and if that is true,
1602 	 * there is a need to wait here for it to complete.  This must
1603 	 * be done outside of start_fop/end_fop.
1604 	 */
1605 	(void) nfs4_waitfor_purge_complete(vp);
1606 
1607 	/*
1608 	 * It is implicit that we are in the open case (create_flag == 0) since
1609 	 * fh_differs can only be set to a non-zero value in the open case.
1610 	 */
1611 	if (fh_differs != 0 && vpi != NULL)
1612 		VN_RELE(vpi);
1613 
1614 	/*
1615 	 * Be sure to set *vpp to the correct value before returning.
1616 	 */
1617 	*vpp = vp;
1618 
1619 skip_update_dircaches:
1620 
1621 	nfs4args_copen_free(open_args);
1622 	if (setgid_flag) {
1623 		nfs4args_verify_free(&argop[8]);
1624 		nfs4args_setattr_free(&argop[9]);
1625 	}
1626 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1627 
1628 	if (ncr)
1629 		crfree(ncr);
1630 	kmem_free(argop, argoplist_size);
1631 	return (e.error);
1632 }
1633 
1634 /*
1635  * Reopen an open instance.  cf. nfs4open_otw().
1636  *
1637  * Errors are returned by the nfs4_error_t parameter.
1638  * - ep->error contains an errno value or zero.
1639  * - if it is zero, ep->stat is set to an NFS status code, if any.
1640  *   If the file could not be reopened, but the caller should continue, the
1641  *   file is marked dead and no error values are returned.  If the caller
1642  *   should stop recovering open files and start over, either the ep->error
1643  *   value or ep->stat will indicate an error (either something that requires
1644  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1645  *   filehandles) may be handled silently by this routine.
1646  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1647  *   will be started, so the caller should not do it.
1648  *
1649  * Gotos:
1650  * - kill_file : reopen failed in such a fashion to constitute marking the
1651  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1652  *   is for cases where recovery is not possible.
1653  * - failed_reopen : same as above, except that the file has already been
1654  *   marked dead, so no need to do it again.
1655  * - bailout : reopen failed but we are able to recover and retry the reopen -
1656  *   either within this function immediately or via the calling function.
1657  */
1658 
1659 void
1660 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1661     open_claim_type4 claim, bool_t frc_use_claim_previous,
1662     bool_t is_recov)
1663 {
1664 	COMPOUND4args_clnt args;
1665 	COMPOUND4res_clnt res;
1666 	nfs_argop4 argop[4];
1667 	nfs_resop4 *resop;
1668 	OPEN4res *op_res = NULL;
1669 	OPEN4cargs *open_args;
1670 	GETFH4res *gf_res;
1671 	rnode4_t *rp = VTOR4(vp);
1672 	int doqueue = 1;
1673 	cred_t *cr = NULL, *cred_otw = NULL;
1674 	nfs4_open_owner_t *oop = NULL;
1675 	seqid4 seqid;
1676 	nfs4_ga_res_t *garp;
1677 	char fn[MAXNAMELEN];
1678 	nfs4_recov_state_t recov = {NULL, 0};
1679 	nfs4_lost_rqst_t lost_rqst;
1680 	mntinfo4_t *mi = VTOMI4(vp);
1681 	bool_t abort;
1682 	char *failed_msg = "";
1683 	int fh_different;
1684 	hrtime_t t;
1685 	nfs4_bseqid_entry_t *bsep = NULL;
1686 
1687 	ASSERT(nfs4_consistent_type(vp));
1688 	ASSERT(nfs_zone() == mi->mi_zone);
1689 
1690 	nfs4_error_zinit(ep);
1691 
1692 	/* this is the cred used to find the open owner */
1693 	cr = state_to_cred(osp);
1694 	if (cr == NULL) {
1695 		failed_msg = "Couldn't reopen: no cred";
1696 		goto kill_file;
1697 	}
1698 	/* use this cred for OTW operations */
1699 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1700 
1701 top:
1702 	nfs4_error_zinit(ep);
1703 
1704 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1705 		/* File system has been unmounted, quit */
1706 		ep->error = EIO;
1707 		failed_msg = "Couldn't reopen: file system has been unmounted";
1708 		goto kill_file;
1709 	}
1710 
1711 	oop = osp->os_open_owner;
1712 
1713 	ASSERT(oop != NULL);
1714 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1715 		failed_msg = "can't reopen: no open owner";
1716 		goto kill_file;
1717 	}
1718 	open_owner_hold(oop);
1719 
1720 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1721 	if (ep->error) {
1722 		open_owner_rele(oop);
1723 		oop = NULL;
1724 		goto bailout;
1725 	}
1726 
1727 	/*
1728 	 * If the rnode has a delegation and the delegation has been
1729 	 * recovered and the server didn't request a recall and the caller
1730 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1731 	 * recovery) and the rnode hasn't been marked dead, then install
1732 	 * the delegation stateid in the open stream.  Otherwise, proceed
1733 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1734 	 */
1735 	mutex_enter(&rp->r_statev4_lock);
1736 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1737 	    !rp->r_deleg_return_pending &&
1738 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1739 	    !rp->r_deleg_needs_recall &&
1740 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1741 	    !(rp->r_flags & R4RECOVERR)) {
1742 		mutex_enter(&osp->os_sync_lock);
1743 		osp->os_delegation = 1;
1744 		osp->open_stateid = rp->r_deleg_stateid;
1745 		mutex_exit(&osp->os_sync_lock);
1746 		mutex_exit(&rp->r_statev4_lock);
1747 		goto bailout;
1748 	}
1749 	mutex_exit(&rp->r_statev4_lock);
1750 
1751 	/*
1752 	 * If the file failed recovery, just quit.  This failure need not
1753 	 * affect other reopens, so don't return an error.
1754 	 */
1755 	mutex_enter(&rp->r_statelock);
1756 	if (rp->r_flags & R4RECOVERR) {
1757 		mutex_exit(&rp->r_statelock);
1758 		ep->error = 0;
1759 		goto failed_reopen;
1760 	}
1761 	mutex_exit(&rp->r_statelock);
1762 
1763 	/*
1764 	 * argop is empty here
1765 	 *
1766 	 * PUTFH, OPEN, GETATTR
1767 	 */
1768 	args.ctag = TAG_REOPEN;
1769 	args.array_len = 4;
1770 	args.array = argop;
1771 
1772 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1773 	    "nfs4_reopen: file is type %d, id %s",
1774 	    vp->v_type, rnode4info(VTOR4(vp))));
1775 
1776 	argop[0].argop = OP_CPUTFH;
1777 
1778 	if (claim != CLAIM_PREVIOUS) {
1779 		/*
1780 		 * if this is a file mount then
1781 		 * use the mntinfo parentfh
1782 		 */
1783 		argop[0].nfs_argop4_u.opcputfh.sfh =
1784 		    (vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1785 		    VTOSV(vp)->sv_dfh;
1786 	} else {
1787 		/* putfh fh to reopen */
1788 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1789 	}
1790 
1791 	argop[1].argop = OP_COPEN;
1792 	open_args = &argop[1].nfs_argop4_u.opcopen;
1793 	open_args->claim = claim;
1794 
1795 	if (claim == CLAIM_NULL) {
1796 
1797 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1798 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1799 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1800 			    (void *)vp);
1801 			failed_msg = "Couldn't reopen: vtoname failed for "
1802 			    "CLAIM_NULL";
1803 			/* nothing allocated yet */
1804 			goto kill_file;
1805 		}
1806 
1807 		open_args->open_claim4_u.cfile = fn;
1808 	} else if (claim == CLAIM_PREVIOUS) {
1809 
1810 		/*
1811 		 * We have two cases to deal with here:
1812 		 * 1) We're being called to reopen files in order to satisfy
1813 		 *    a lock operation request which requires us to explicitly
1814 		 *    reopen files which were opened under a delegation.  If
1815 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1816 		 *    that case, frc_use_claim_previous is TRUE and we must
1817 		 *    use the rnode's current delegation type (r_deleg_type).
1818 		 * 2) We're reopening files during some form of recovery.
1819 		 *    In this case, frc_use_claim_previous is FALSE and we
1820 		 *    use the delegation type appropriate for recovery
1821 		 *    (r_deleg_needs_recovery).
1822 		 */
1823 		mutex_enter(&rp->r_statev4_lock);
1824 		open_args->open_claim4_u.delegate_type =
1825 		    frc_use_claim_previous ?
1826 		    rp->r_deleg_type :
1827 		    rp->r_deleg_needs_recovery;
1828 		mutex_exit(&rp->r_statev4_lock);
1829 
1830 	} else if (claim == CLAIM_DELEGATE_CUR) {
1831 
1832 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1833 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1834 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1835 			    "with %m", (void *)vp);
1836 			failed_msg = "Couldn't reopen: vtoname failed for "
1837 			    "CLAIM_DELEGATE_CUR";
1838 			/* nothing allocated yet */
1839 			goto kill_file;
1840 		}
1841 
1842 		mutex_enter(&rp->r_statev4_lock);
1843 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1844 		    rp->r_deleg_stateid;
1845 		mutex_exit(&rp->r_statev4_lock);
1846 
1847 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1848 	}
1849 	open_args->opentype = OPEN4_NOCREATE;
1850 	open_args->owner.clientid = mi2clientid(mi);
1851 	open_args->owner.owner_len = sizeof (oop->oo_name);
1852 	open_args->owner.owner_val =
1853 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1854 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1855 	    open_args->owner.owner_len);
1856 	open_args->share_access = 0;
1857 	open_args->share_deny = 0;
1858 
1859 	mutex_enter(&osp->os_sync_lock);
1860 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1861 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1862 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1863 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1864 	    osp->os_share_acc_write, osp->os_open_ref_count,
1865 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1866 
1867 	if (osp->os_share_acc_read || osp->os_mmap_read)
1868 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1869 	if (osp->os_share_acc_write || osp->os_mmap_write)
1870 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1871 	if (osp->os_share_deny_read)
1872 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1873 	if (osp->os_share_deny_write)
1874 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1875 	mutex_exit(&osp->os_sync_lock);
1876 
1877 	seqid = nfs4_get_open_seqid(oop) + 1;
1878 	open_args->seqid = seqid;
1879 
1880 	/* Construct the getfh part of the compound */
1881 	argop[2].argop = OP_GETFH;
1882 
1883 	/* Construct the getattr part of the compound */
1884 	argop[3].argop = OP_GETATTR;
1885 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1886 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1887 
1888 	t = gethrtime();
1889 
1890 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1891 
1892 	if (ep->error) {
1893 		if (!is_recov && !frc_use_claim_previous &&
1894 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1895 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1896 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1897 			    cred_otw, vp, NULL, open_args);
1898 			abort = nfs4_start_recovery(ep,
1899 			    VTOMI4(vp), vp, NULL, NULL,
1900 			    lost_rqst.lr_op == OP_OPEN ?
1901 			    &lost_rqst : NULL, OP_OPEN, NULL);
1902 			nfs4args_copen_free(open_args);
1903 			goto bailout;
1904 		}
1905 
1906 		nfs4args_copen_free(open_args);
1907 
1908 		if (ep->error == EACCES && cred_otw != cr) {
1909 			crfree(cred_otw);
1910 			cred_otw = cr;
1911 			crhold(cred_otw);
1912 			nfs4_end_open_seqid_sync(oop);
1913 			open_owner_rele(oop);
1914 			oop = NULL;
1915 			goto top;
1916 		}
1917 		if (ep->error == ETIMEDOUT)
1918 			goto bailout;
1919 		failed_msg = "Couldn't reopen: rpc error";
1920 		goto kill_file;
1921 	}
1922 
1923 	if (nfs4_need_to_bump_seqid(&res))
1924 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1925 
1926 	switch (res.status) {
1927 	case NFS4_OK:
1928 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1929 			mutex_enter(&rp->r_statelock);
1930 			rp->r_delay_interval = 0;
1931 			mutex_exit(&rp->r_statelock);
1932 		}
1933 		break;
1934 	case NFS4ERR_BAD_SEQID:
1935 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1936 		    args.ctag, open_args->seqid);
1937 
1938 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1939 		    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1940 		    NULL, OP_OPEN, bsep);
1941 
1942 		nfs4args_copen_free(open_args);
1943 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1944 		nfs4_end_open_seqid_sync(oop);
1945 		open_owner_rele(oop);
1946 		oop = NULL;
1947 		kmem_free(bsep, sizeof (*bsep));
1948 
1949 		goto kill_file;
1950 	case NFS4ERR_NO_GRACE:
1951 		nfs4args_copen_free(open_args);
1952 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1953 		nfs4_end_open_seqid_sync(oop);
1954 		open_owner_rele(oop);
1955 		oop = NULL;
1956 		if (claim == CLAIM_PREVIOUS) {
1957 			/*
1958 			 * Retry as a plain open. We don't need to worry about
1959 			 * checking the changeinfo: it is acceptable for a
1960 			 * client to re-open a file and continue processing
1961 			 * (in the absence of locks).
1962 			 */
1963 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1964 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1965 			    "will retry as CLAIM_NULL"));
1966 			claim = CLAIM_NULL;
1967 			nfs4_mi_kstat_inc_no_grace(mi);
1968 			goto top;
1969 		}
1970 		failed_msg =
1971 		    "Couldn't reopen: tried reclaim outside grace period. ";
1972 		goto kill_file;
1973 	case NFS4ERR_GRACE:
1974 		nfs4_set_grace_wait(mi);
1975 		nfs4args_copen_free(open_args);
1976 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1977 		nfs4_end_open_seqid_sync(oop);
1978 		open_owner_rele(oop);
1979 		oop = NULL;
1980 		ep->error = nfs4_wait_for_grace(mi, &recov);
1981 		if (ep->error != 0)
1982 			goto bailout;
1983 		goto top;
1984 	case NFS4ERR_DELAY:
1985 		nfs4_set_delay_wait(vp);
1986 		nfs4args_copen_free(open_args);
1987 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1988 		nfs4_end_open_seqid_sync(oop);
1989 		open_owner_rele(oop);
1990 		oop = NULL;
1991 		ep->error = nfs4_wait_for_delay(vp, &recov);
1992 		nfs4_mi_kstat_inc_delay(mi);
1993 		if (ep->error != 0)
1994 			goto bailout;
1995 		goto top;
1996 	case NFS4ERR_FHEXPIRED:
1997 		/* recover filehandle and retry */
1998 		abort = nfs4_start_recovery(ep,
1999 		    mi, vp, NULL, NULL, NULL, OP_OPEN, NULL);
2000 		nfs4args_copen_free(open_args);
2001 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2002 		nfs4_end_open_seqid_sync(oop);
2003 		open_owner_rele(oop);
2004 		oop = NULL;
2005 		if (abort == FALSE)
2006 			goto top;
2007 		failed_msg = "Couldn't reopen: recovery aborted";
2008 		goto kill_file;
2009 	case NFS4ERR_RESOURCE:
2010 	case NFS4ERR_STALE_CLIENTID:
2011 	case NFS4ERR_WRONGSEC:
2012 	case NFS4ERR_EXPIRED:
2013 		/*
2014 		 * Do not mark the file dead and let the calling
2015 		 * function initiate recovery.
2016 		 */
2017 		nfs4args_copen_free(open_args);
2018 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2019 		nfs4_end_open_seqid_sync(oop);
2020 		open_owner_rele(oop);
2021 		oop = NULL;
2022 		goto bailout;
2023 	case NFS4ERR_ACCESS:
2024 		if (cred_otw != cr) {
2025 			crfree(cred_otw);
2026 			cred_otw = cr;
2027 			crhold(cred_otw);
2028 			nfs4args_copen_free(open_args);
2029 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2030 			nfs4_end_open_seqid_sync(oop);
2031 			open_owner_rele(oop);
2032 			oop = NULL;
2033 			goto top;
2034 		}
2035 		/* fall through */
2036 	default:
2037 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2038 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2039 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2040 		    rnode4info(VTOR4(vp))));
2041 		failed_msg = "Couldn't reopen: NFSv4 error";
2042 		nfs4args_copen_free(open_args);
2043 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2044 		goto kill_file;
2045 	}
2046 
2047 	resop = &res.array[1];  /* open res */
2048 	op_res = &resop->nfs_resop4_u.opopen;
2049 
2050 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2051 
2052 	/*
2053 	 * Check if the path we reopened really is the same
2054 	 * file. We could end up in a situation where the file
2055 	 * was removed and a new file created with the same name.
2056 	 */
2057 	resop = &res.array[2];
2058 	gf_res = &resop->nfs_resop4_u.opgetfh;
2059 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2060 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2061 	if (fh_different) {
2062 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2063 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2064 			/* Oops, we don't have the same file */
2065 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2066 				failed_msg = "Couldn't reopen: Persistent "
2067 				    "file handle changed";
2068 			else
2069 				failed_msg = "Couldn't reopen: Volatile "
2070 				    "(no expire on open) file handle changed";
2071 
2072 			nfs4args_copen_free(open_args);
2073 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2074 			nfs_rw_exit(&mi->mi_fh_lock);
2075 			goto kill_file;
2076 
2077 		} else {
2078 			/*
2079 			 * We have volatile file handles that don't compare.
2080 			 * If the fids are the same then we assume that the
2081 			 * file handle expired but the rnode still refers to
2082 			 * the same file object.
2083 			 *
2084 			 * First check that we have fids or not.
2085 			 * If we don't we have a dumb server so we will
2086 			 * just assume every thing is ok for now.
2087 			 */
2088 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2089 			    rp->r_attr.va_mask & AT_NODEID &&
2090 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2091 				/*
2092 				 * We have fids, but they don't
2093 				 * compare. So kill the file.
2094 				 */
2095 				failed_msg =
2096 				    "Couldn't reopen: file handle changed"
2097 				    " due to mismatched fids";
2098 				nfs4args_copen_free(open_args);
2099 				(void) xdr_free(xdr_COMPOUND4res_clnt,
2100 				    (caddr_t)&res);
2101 				nfs_rw_exit(&mi->mi_fh_lock);
2102 				goto kill_file;
2103 			} else {
2104 				/*
2105 				 * We have volatile file handles that refers
2106 				 * to the same file (at least they have the
2107 				 * same fid) or we don't have fids so we
2108 				 * can't tell. :(. We'll be a kind and accepting
2109 				 * client so we'll update the rnode's file
2110 				 * handle with the otw handle.
2111 				 *
2112 				 * We need to drop mi->mi_fh_lock since
2113 				 * sh4_update acquires it. Since there is
2114 				 * only one recovery thread there is no
2115 				 * race.
2116 				 */
2117 				nfs_rw_exit(&mi->mi_fh_lock);
2118 				sfh4_update(rp->r_fh, &gf_res->object);
2119 			}
2120 		}
2121 	} else {
2122 		nfs_rw_exit(&mi->mi_fh_lock);
2123 	}
2124 
2125 	ASSERT(nfs4_consistent_type(vp));
2126 
2127 	/*
2128 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2129 	 * over.  Presumably if there is a persistent error it will show up
2130 	 * when we resend the OPEN.
2131 	 */
2132 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2133 		bool_t retry_open = FALSE;
2134 
2135 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2136 		    cred_otw, is_recov, &retry_open,
2137 		    oop, FALSE, ep, NULL);
2138 		if (ep->error || ep->stat) {
2139 			nfs4args_copen_free(open_args);
2140 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2141 			nfs4_end_open_seqid_sync(oop);
2142 			open_owner_rele(oop);
2143 			oop = NULL;
2144 			goto top;
2145 		}
2146 	}
2147 
2148 	mutex_enter(&osp->os_sync_lock);
2149 	osp->open_stateid = op_res->stateid;
2150 	osp->os_delegation = 0;
2151 	/*
2152 	 * Need to reset this bitfield for the possible case where we were
2153 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2154 	 * we could retry the CLOSE, OPENed the file again.
2155 	 */
2156 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2157 	osp->os_final_close = 0;
2158 	osp->os_force_close = 0;
2159 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2160 		osp->os_dc_openacc = open_args->share_access;
2161 	mutex_exit(&osp->os_sync_lock);
2162 
2163 	nfs4_end_open_seqid_sync(oop);
2164 
2165 	/* accept delegation, if any */
2166 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2167 
2168 	nfs4args_copen_free(open_args);
2169 
2170 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2171 
2172 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2173 
2174 	ASSERT(nfs4_consistent_type(vp));
2175 
2176 	open_owner_rele(oop);
2177 	crfree(cr);
2178 	crfree(cred_otw);
2179 	return;
2180 
2181 kill_file:
2182 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2183 failed_reopen:
2184 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2185 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2186 	    (void *)osp, (void *)cr, rnode4info(rp)));
2187 	mutex_enter(&osp->os_sync_lock);
2188 	osp->os_failed_reopen = 1;
2189 	mutex_exit(&osp->os_sync_lock);
2190 bailout:
2191 	if (oop != NULL) {
2192 		nfs4_end_open_seqid_sync(oop);
2193 		open_owner_rele(oop);
2194 	}
2195 	if (cr != NULL)
2196 		crfree(cr);
2197 	if (cred_otw != NULL)
2198 		crfree(cred_otw);
2199 }
2200 
2201 /* for . and .. OPENs */
2202 /* ARGSUSED */
2203 static int
2204 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2205 {
2206 	rnode4_t *rp;
2207 	nfs4_ga_res_t gar;
2208 
2209 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2210 
2211 	/*
2212 	 * If close-to-open consistency checking is turned off or
2213 	 * if there is no cached data, we can avoid
2214 	 * the over the wire getattr.  Otherwise, force a
2215 	 * call to the server to get fresh attributes and to
2216 	 * check caches. This is required for close-to-open
2217 	 * consistency.
2218 	 */
2219 	rp = VTOR4(*vpp);
2220 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2221 	    (rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2222 		return (0);
2223 
2224 	gar.n4g_va.va_mask = AT_ALL;
2225 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2226 }
2227 
2228 /*
2229  * CLOSE a file
2230  */
2231 /* ARGSUSED */
2232 static int
2233 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
2234 	caller_context_t *ct)
2235 {
2236 	rnode4_t	*rp;
2237 	int		 error = 0;
2238 	int		 r_error = 0;
2239 	int		 n4error = 0;
2240 	nfs4_error_t	 e = { 0, NFS4_OK, RPC_SUCCESS };
2241 
2242 	/*
2243 	 * Remove client state for this (lockowner, file) pair.
2244 	 * Issue otw v4 call to have the server do the same.
2245 	 */
2246 
2247 	rp = VTOR4(vp);
2248 
2249 	/*
2250 	 * zone_enter(2) prevents processes from changing zones with NFS files
2251 	 * open; if we happen to get here from the wrong zone we can't do
2252 	 * anything over the wire.
2253 	 */
2254 	if (VTOMI4(vp)->mi_zone != nfs_zone()) {
2255 		/*
2256 		 * We could attempt to clean up locks, except we're sure
2257 		 * that the current process didn't acquire any locks on
2258 		 * the file: any attempt to lock a file belong to another zone
2259 		 * will fail, and one can't lock an NFS file and then change
2260 		 * zones, as that fails too.
2261 		 *
2262 		 * Returning an error here is the sane thing to do.  A
2263 		 * subsequent call to VN_RELE() which translates to a
2264 		 * nfs4_inactive() will clean up state: if the zone of the
2265 		 * vnode's origin is still alive and kicking, the inactive
2266 		 * thread will handle the request (from the correct zone), and
2267 		 * everything (minus the OTW close call) should be OK.  If the
2268 		 * zone is going away nfs4_async_inactive() will throw away
2269 		 * delegations, open streams and cached pages inline.
2270 		 */
2271 		return (EIO);
2272 	}
2273 
2274 	/*
2275 	 * If we are using local locking for this filesystem, then
2276 	 * release all of the SYSV style record locks.  Otherwise,
2277 	 * we are doing network locking and we need to release all
2278 	 * of the network locks.  All of the locks held by this
2279 	 * process on this file are released no matter what the
2280 	 * incoming reference count is.
2281 	 */
2282 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK) {
2283 		cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
2284 		cleanshares(vp, ttoproc(curthread)->p_pid);
2285 	} else
2286 		e.error = nfs4_lockrelease(vp, flag, offset, cr);
2287 
2288 	if (e.error) {
2289 		struct lm_sysid *lmsid;
2290 		lmsid = nfs4_find_sysid(VTOMI4(vp));
2291 		if (lmsid == NULL) {
2292 			DTRACE_PROBE2(unknown__sysid, int, e.error,
2293 			    vnode_t *, vp);
2294 		} else {
2295 			cleanlocks(vp, ttoproc(curthread)->p_pid,
2296 			    (lm_sysidt(lmsid) | LM_SYSID_CLIENT));
2297 		}
2298 		return (e.error);
2299 	}
2300 
2301 	if (count > 1)
2302 		return (0);
2303 
2304 	/*
2305 	 * If the file has been `unlinked', then purge the
2306 	 * DNLC so that this vnode will get reycled quicker
2307 	 * and the .nfs* file on the server will get removed.
2308 	 */
2309 	if (rp->r_unldvp != NULL)
2310 		dnlc_purge_vp(vp);
2311 
2312 	/*
2313 	 * If the file was open for write and there are pages,
2314 	 * do a synchronous flush and commit of all of the
2315 	 * dirty and uncommitted pages.
2316 	 */
2317 	ASSERT(!e.error);
2318 	if ((flag & FWRITE) && nfs4_has_pages(vp))
2319 		error = nfs4_putpage_commit(vp, 0, 0, cr);
2320 
2321 	mutex_enter(&rp->r_statelock);
2322 	r_error = rp->r_error;
2323 	rp->r_error = 0;
2324 	mutex_exit(&rp->r_statelock);
2325 
2326 	/*
2327 	 * If this file type is one for which no explicit 'open' was
2328 	 * done, then bail now (ie. no need for protocol 'close'). If
2329 	 * there was an error w/the vm subsystem, return _that_ error,
2330 	 * otherwise, return any errors that may've been reported via
2331 	 * the rnode.
2332 	 */
2333 	if (vp->v_type != VREG)
2334 		return (error ? error : r_error);
2335 
2336 	/*
2337 	 * The sync putpage commit may have failed above, but since
2338 	 * we're working w/a regular file, we need to do the protocol
2339 	 * 'close' (nfs4close_one will figure out if an otw close is
2340 	 * needed or not). Report any errors _after_ doing the protocol
2341 	 * 'close'.
2342 	 */
2343 	nfs4close_one(vp, NULL, cr, flag, NULL, &e, CLOSE_NORM, 0, 0, 0);
2344 	n4error = e.error ? e.error : geterrno4(e.stat);
2345 
2346 	/*
2347 	 * Error reporting prio (Hi -> Lo)
2348 	 *
2349 	 *   i) nfs4_putpage_commit (error)
2350 	 *  ii) rnode's (r_error)
2351 	 * iii) nfs4close_one (n4error)
2352 	 */
2353 	return (error ? error : (r_error ? r_error : n4error));
2354 }
2355 
2356 /*
2357  * Initialize *lost_rqstp.
2358  */
2359 
2360 static void
2361 nfs4close_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
2362     nfs4_open_owner_t *oop, nfs4_open_stream_t *osp, cred_t *cr,
2363     vnode_t *vp)
2364 {
2365 	if (error != ETIMEDOUT && error != EINTR &&
2366 	    !NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
2367 		lost_rqstp->lr_op = 0;
2368 		return;
2369 	}
2370 
2371 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
2372 	    "nfs4close_save_lost_rqst: error %d", error));
2373 
2374 	lost_rqstp->lr_op = OP_CLOSE;
2375 	/*
2376 	 * The vp is held and rele'd via the recovery code.
2377 	 * See nfs4_save_lost_rqst.
2378 	 */
2379 	lost_rqstp->lr_vp = vp;
2380 	lost_rqstp->lr_dvp = NULL;
2381 	lost_rqstp->lr_oop = oop;
2382 	lost_rqstp->lr_osp = osp;
2383 	ASSERT(osp != NULL);
2384 	ASSERT(mutex_owned(&osp->os_sync_lock));
2385 	osp->os_pending_close = 1;
2386 	lost_rqstp->lr_lop = NULL;
2387 	lost_rqstp->lr_cr = cr;
2388 	lost_rqstp->lr_flk = NULL;
2389 	lost_rqstp->lr_putfirst = FALSE;
2390 }
2391 
2392 /*
2393  * Assumes you already have the open seqid sync grabbed as well as the
2394  * 'os_sync_lock'.  Note: this will release the open seqid sync and
2395  * 'os_sync_lock' if client recovery starts.  Calling functions have to
2396  * be prepared to handle this.
2397  *
2398  * 'recov' is returned as 1 if the CLOSE operation detected client recovery
2399  * was needed and was started, and that the calling function should retry
2400  * this function; otherwise it is returned as 0.
2401  *
2402  * Errors are returned via the nfs4_error_t parameter.
2403  */
2404 static void
2405 nfs4close_otw(rnode4_t *rp, cred_t *cred_otw, nfs4_open_owner_t *oop,
2406     nfs4_open_stream_t *osp, int *recov, int *did_start_seqid_syncp,
2407     nfs4_close_type_t close_type, nfs4_error_t *ep, int *have_sync_lockp)
2408 {
2409 	COMPOUND4args_clnt args;
2410 	COMPOUND4res_clnt res;
2411 	CLOSE4args *close_args;
2412 	nfs_resop4 *resop;
2413 	nfs_argop4 argop[3];
2414 	int doqueue = 1;
2415 	mntinfo4_t *mi;
2416 	seqid4 seqid;
2417 	vnode_t *vp;
2418 	bool_t needrecov = FALSE;
2419 	nfs4_lost_rqst_t lost_rqst;
2420 	hrtime_t t;
2421 
2422 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
2423 
2424 	ASSERT(MUTEX_HELD(&osp->os_sync_lock));
2425 
2426 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw"));
2427 
2428 	/* Only set this to 1 if recovery is started */
2429 	*recov = 0;
2430 
2431 	/* do the OTW call to close the file */
2432 
2433 	if (close_type == CLOSE_RESEND)
2434 		args.ctag = TAG_CLOSE_LOST;
2435 	else if (close_type == CLOSE_AFTER_RESEND)
2436 		args.ctag = TAG_CLOSE_UNDO;
2437 	else
2438 		args.ctag = TAG_CLOSE;
2439 
2440 	args.array_len = 3;
2441 	args.array = argop;
2442 
2443 	vp = RTOV4(rp);
2444 
2445 	mi = VTOMI4(vp);
2446 
2447 	/* putfh target fh */
2448 	argop[0].argop = OP_CPUTFH;
2449 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
2450 
2451 	argop[1].argop = OP_GETATTR;
2452 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
2453 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
2454 
2455 	argop[2].argop = OP_CLOSE;
2456 	close_args = &argop[2].nfs_argop4_u.opclose;
2457 
2458 	seqid = nfs4_get_open_seqid(oop) + 1;
2459 
2460 	close_args->seqid = seqid;
2461 	close_args->open_stateid = osp->open_stateid;
2462 
2463 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
2464 	    "nfs4close_otw: %s call, rp %s", needrecov ? "recov" : "first",
2465 	    rnode4info(rp)));
2466 
2467 	t = gethrtime();
2468 
2469 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
2470 
2471 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
2472 		nfs4_set_open_seqid(seqid, oop, args.ctag);
2473 	}
2474 
2475 	needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
2476 	if (ep->error && !needrecov) {
2477 		/*
2478 		 * if there was an error and no recovery is to be done
2479 		 * then then set up the file to flush its cache if
2480 		 * needed for the next caller.
2481 		 */
2482 		mutex_enter(&rp->r_statelock);
2483 		PURGE_ATTRCACHE4_LOCKED(rp);
2484 		rp->r_flags &= ~R4WRITEMODIFIED;
2485 		mutex_exit(&rp->r_statelock);
2486 		return;
2487 	}
2488 
2489 	if (needrecov) {
2490 		bool_t abort;
2491 		nfs4_bseqid_entry_t *bsep = NULL;
2492 
2493 		if (close_type != CLOSE_RESEND)
2494 			nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
2495 			    osp, cred_otw, vp);
2496 
2497 		if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
2498 			bsep = nfs4_create_bseqid_entry(oop, NULL, vp,
2499 			    0, args.ctag, close_args->seqid);
2500 
2501 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
2502 		    "nfs4close_otw: initiating recovery. error %d "
2503 		    "res.status %d", ep->error, res.status));
2504 
2505 		/*
2506 		 * Drop the 'os_sync_lock' here so we don't hit
2507 		 * a potential recursive mutex_enter via an
2508 		 * 'open_stream_hold()'.
2509 		 */
2510 		mutex_exit(&osp->os_sync_lock);
2511 		*have_sync_lockp = 0;
2512 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
2513 		    (close_type != CLOSE_RESEND &&
2514 		    lost_rqst.lr_op == OP_CLOSE) ? &lost_rqst : NULL,
2515 		    OP_CLOSE, bsep);
2516 
2517 		/* drop open seq sync, and let the calling function regrab it */
2518 		nfs4_end_open_seqid_sync(oop);
2519 		*did_start_seqid_syncp = 0;
2520 
2521 		if (bsep)
2522 			kmem_free(bsep, sizeof (*bsep));
2523 		/*
2524 		 * For signals, the caller wants to quit, so don't say to
2525 		 * retry.  For forced unmount, if it's a user thread, it
2526 		 * wants to quit.  If it's a recovery thread, the retry
2527 		 * will happen higher-up on the call stack.  Either way,
2528 		 * don't say to retry.
2529 		 */
2530 		if (abort == FALSE && ep->error != EINTR &&
2531 		    !NFS4_FRC_UNMT_ERR(ep->error, mi->mi_vfsp) &&
2532 		    close_type != CLOSE_RESEND &&
2533 		    close_type != CLOSE_AFTER_RESEND)
2534 			*recov = 1;
2535 		else
2536 			*recov = 0;
2537 
2538 		if (!ep->error)
2539 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2540 		return;
2541 	}
2542 
2543 	if (res.status) {
2544 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2545 		return;
2546 	}
2547 
2548 	mutex_enter(&rp->r_statev4_lock);
2549 	rp->created_v4 = 0;
2550 	mutex_exit(&rp->r_statev4_lock);
2551 
2552 	resop = &res.array[2];
2553 	osp->open_stateid = resop->nfs_resop4_u.opclose.open_stateid;
2554 	osp->os_valid = 0;
2555 
2556 	/*
2557 	 * This removes the reference obtained at OPEN; ie, when the
2558 	 * open stream structure was created.
2559 	 *
2560 	 * We don't have to worry about calling 'open_stream_rele'
2561 	 * since we our currently holding a reference to the open
2562 	 * stream which means the count cannot go to 0 with this
2563 	 * decrement.
2564 	 */
2565 	ASSERT(osp->os_ref_count >= 2);
2566 	osp->os_ref_count--;
2567 
2568 	if (!ep->error)
2569 		nfs4_attr_cache(vp,
2570 		    &res.array[1].nfs_resop4_u.opgetattr.ga_res,
2571 		    t, cred_otw, TRUE, NULL);
2572 
2573 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw:"
2574 	    " returning %d", ep->error));
2575 
2576 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2577 }
2578 
2579 /* ARGSUSED */
2580 static int
2581 nfs4_read(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2582     caller_context_t *ct)
2583 {
2584 	rnode4_t *rp;
2585 	u_offset_t off;
2586 	offset_t diff;
2587 	uint_t on;
2588 	uint_t n;
2589 	caddr_t base;
2590 	uint_t flags;
2591 	int error;
2592 	mntinfo4_t *mi;
2593 
2594 	rp = VTOR4(vp);
2595 
2596 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2597 
2598 	if (IS_SHADOW(vp, rp))
2599 		vp = RTOV4(rp);
2600 
2601 	if (vp->v_type != VREG)
2602 		return (EISDIR);
2603 
2604 	mi = VTOMI4(vp);
2605 
2606 	if (nfs_zone() != mi->mi_zone)
2607 		return (EIO);
2608 
2609 	if (uiop->uio_resid == 0)
2610 		return (0);
2611 
2612 	if (uiop->uio_loffset < 0 || uiop->uio_loffset + uiop->uio_resid < 0)
2613 		return (EINVAL);
2614 
2615 	mutex_enter(&rp->r_statelock);
2616 	if (rp->r_flags & R4RECOVERRP)
2617 		error = (rp->r_error ? rp->r_error : EIO);
2618 	else
2619 		error = 0;
2620 	mutex_exit(&rp->r_statelock);
2621 	if (error)
2622 		return (error);
2623 
2624 	/*
2625 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2626 	 * using client-side direct I/O and the file is not mmap'd and
2627 	 * there are no cached pages.
2628 	 */
2629 	if ((vp->v_flag & VNOCACHE) ||
2630 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2631 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2632 		size_t resid = 0;
2633 
2634 		return (nfs4read(vp, NULL, uiop->uio_loffset,
2635 		    uiop->uio_resid, &resid, cr, FALSE, uiop));
2636 	}
2637 
2638 	error = 0;
2639 
2640 	do {
2641 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2642 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2643 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2644 
2645 		if (error = nfs4_validate_caches(vp, cr))
2646 			break;
2647 
2648 		mutex_enter(&rp->r_statelock);
2649 		while (rp->r_flags & R4INCACHEPURGE) {
2650 			if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2651 				mutex_exit(&rp->r_statelock);
2652 				return (EINTR);
2653 			}
2654 		}
2655 		diff = rp->r_size - uiop->uio_loffset;
2656 		mutex_exit(&rp->r_statelock);
2657 		if (diff <= 0)
2658 			break;
2659 		if (diff < n)
2660 			n = (uint_t)diff;
2661 
2662 		if (vpm_enable) {
2663 			/*
2664 			 * Copy data.
2665 			 */
2666 			error = vpm_data_copy(vp, off + on, n, uiop,
2667 			    1, NULL, 0, S_READ);
2668 		} else {
2669 			base = segmap_getmapflt(segkmap, vp, off + on, n, 1,
2670 			    S_READ);
2671 
2672 			error = uiomove(base + on, n, UIO_READ, uiop);
2673 		}
2674 
2675 		if (!error) {
2676 			/*
2677 			 * If read a whole block or read to eof,
2678 			 * won't need this buffer again soon.
2679 			 */
2680 			mutex_enter(&rp->r_statelock);
2681 			if (n + on == MAXBSIZE ||
2682 			    uiop->uio_loffset == rp->r_size)
2683 				flags = SM_DONTNEED;
2684 			else
2685 				flags = 0;
2686 			mutex_exit(&rp->r_statelock);
2687 			if (vpm_enable) {
2688 				error = vpm_sync_pages(vp, off, n, flags);
2689 			} else {
2690 				error = segmap_release(segkmap, base, flags);
2691 			}
2692 		} else {
2693 			if (vpm_enable) {
2694 				(void) vpm_sync_pages(vp, off, n, 0);
2695 			} else {
2696 				(void) segmap_release(segkmap, base, 0);
2697 			}
2698 		}
2699 	} while (!error && uiop->uio_resid > 0);
2700 
2701 	return (error);
2702 }
2703 
2704 /* ARGSUSED */
2705 static int
2706 nfs4_write(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2707     caller_context_t *ct)
2708 {
2709 	rlim64_t limit = uiop->uio_llimit;
2710 	rnode4_t *rp;
2711 	u_offset_t off;
2712 	caddr_t base;
2713 	uint_t flags;
2714 	int remainder;
2715 	size_t n;
2716 	int on;
2717 	int error;
2718 	int resid;
2719 	u_offset_t offset;
2720 	mntinfo4_t *mi;
2721 	uint_t bsize;
2722 
2723 	rp = VTOR4(vp);
2724 
2725 	if (IS_SHADOW(vp, rp))
2726 		vp = RTOV4(rp);
2727 
2728 	if (vp->v_type != VREG)
2729 		return (EISDIR);
2730 
2731 	mi = VTOMI4(vp);
2732 
2733 	if (nfs_zone() != mi->mi_zone)
2734 		return (EIO);
2735 
2736 	if (uiop->uio_resid == 0)
2737 		return (0);
2738 
2739 	mutex_enter(&rp->r_statelock);
2740 	if (rp->r_flags & R4RECOVERRP)
2741 		error = (rp->r_error ? rp->r_error : EIO);
2742 	else
2743 		error = 0;
2744 	mutex_exit(&rp->r_statelock);
2745 	if (error)
2746 		return (error);
2747 
2748 	if (ioflag & FAPPEND) {
2749 		struct vattr va;
2750 
2751 		/*
2752 		 * Must serialize if appending.
2753 		 */
2754 		if (nfs_rw_lock_held(&rp->r_rwlock, RW_READER)) {
2755 			nfs_rw_exit(&rp->r_rwlock);
2756 			if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER,
2757 			    INTR(vp)))
2758 				return (EINTR);
2759 		}
2760 
2761 		va.va_mask = AT_SIZE;
2762 		error = nfs4getattr(vp, &va, cr);
2763 		if (error)
2764 			return (error);
2765 		uiop->uio_loffset = va.va_size;
2766 	}
2767 
2768 	offset = uiop->uio_loffset + uiop->uio_resid;
2769 
2770 	if (uiop->uio_loffset < (offset_t)0 || offset < 0)
2771 		return (EINVAL);
2772 
2773 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
2774 		limit = MAXOFFSET_T;
2775 
2776 	/*
2777 	 * Check to make sure that the process will not exceed
2778 	 * its limit on file size.  It is okay to write up to
2779 	 * the limit, but not beyond.  Thus, the write which
2780 	 * reaches the limit will be short and the next write
2781 	 * will return an error.
2782 	 */
2783 	remainder = 0;
2784 	if (offset > uiop->uio_llimit) {
2785 		remainder = offset - uiop->uio_llimit;
2786 		uiop->uio_resid = uiop->uio_llimit - uiop->uio_loffset;
2787 		if (uiop->uio_resid <= 0) {
2788 			proc_t *p = ttoproc(curthread);
2789 
2790 			uiop->uio_resid += remainder;
2791 			mutex_enter(&p->p_lock);
2792 			(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE],
2793 			    p->p_rctls, p, RCA_UNSAFE_SIGINFO);
2794 			mutex_exit(&p->p_lock);
2795 			return (EFBIG);
2796 		}
2797 	}
2798 
2799 	/* update the change attribute, if we have a write delegation */
2800 
2801 	mutex_enter(&rp->r_statev4_lock);
2802 	if (rp->r_deleg_type == OPEN_DELEGATE_WRITE)
2803 		rp->r_deleg_change++;
2804 
2805 	mutex_exit(&rp->r_statev4_lock);
2806 
2807 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
2808 		return (EINTR);
2809 
2810 	/*
2811 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2812 	 * using client-side direct I/O and the file is not mmap'd and
2813 	 * there are no cached pages.
2814 	 */
2815 	if ((vp->v_flag & VNOCACHE) ||
2816 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2817 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2818 		size_t bufsize;
2819 		int count;
2820 		u_offset_t org_offset;
2821 		stable_how4 stab_comm;
2822 nfs4_fwrite:
2823 		if (rp->r_flags & R4STALE) {
2824 			resid = uiop->uio_resid;
2825 			offset = uiop->uio_loffset;
2826 			error = rp->r_error;
2827 			/*
2828 			 * A close may have cleared r_error, if so,
2829 			 * propagate ESTALE error return properly
2830 			 */
2831 			if (error == 0)
2832 				error = ESTALE;
2833 			goto bottom;
2834 		}
2835 
2836 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2837 		base = kmem_alloc(bufsize, KM_SLEEP);
2838 		do {
2839 			if (ioflag & FDSYNC)
2840 				stab_comm = DATA_SYNC4;
2841 			else
2842 				stab_comm = FILE_SYNC4;
2843 			resid = uiop->uio_resid;
2844 			offset = uiop->uio_loffset;
2845 			count = MIN(uiop->uio_resid, bufsize);
2846 			org_offset = uiop->uio_loffset;
2847 			error = uiomove(base, count, UIO_WRITE, uiop);
2848 			if (!error) {
2849 				error = nfs4write(vp, base, org_offset,
2850 				    count, cr, &stab_comm);
2851 				if (!error) {
2852 					mutex_enter(&rp->r_statelock);
2853 					if (rp->r_size < uiop->uio_loffset)
2854 						rp->r_size = uiop->uio_loffset;
2855 					mutex_exit(&rp->r_statelock);
2856 				}
2857 			}
2858 		} while (!error && uiop->uio_resid > 0);
2859 		kmem_free(base, bufsize);
2860 		goto bottom;
2861 	}
2862 
2863 	bsize = vp->v_vfsp->vfs_bsize;
2864 
2865 	do {
2866 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2867 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2868 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2869 
2870 		resid = uiop->uio_resid;
2871 		offset = uiop->uio_loffset;
2872 
2873 		if (rp->r_flags & R4STALE) {
2874 			error = rp->r_error;
2875 			/*
2876 			 * A close may have cleared r_error, if so,
2877 			 * propagate ESTALE error return properly
2878 			 */
2879 			if (error == 0)
2880 				error = ESTALE;
2881 			break;
2882 		}
2883 
2884 		/*
2885 		 * Don't create dirty pages faster than they
2886 		 * can be cleaned so that the system doesn't
2887 		 * get imbalanced.  If the async queue is
2888 		 * maxed out, then wait for it to drain before
2889 		 * creating more dirty pages.  Also, wait for
2890 		 * any threads doing pagewalks in the vop_getattr
2891 		 * entry points so that they don't block for
2892 		 * long periods.
2893 		 */
2894 		mutex_enter(&rp->r_statelock);
2895 		while ((mi->mi_max_threads != 0 &&
2896 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2897 		    rp->r_gcount > 0)
2898 			cv_wait(&rp->r_cv, &rp->r_statelock);
2899 		mutex_exit(&rp->r_statelock);
2900 
2901 		/*
2902 		 * Touch the page and fault it in if it is not in core
2903 		 * before segmap_getmapflt or vpm_data_copy can lock it.
2904 		 * This is to avoid the deadlock if the buffer is mapped
2905 		 * to the same file through mmap which we want to write.
2906 		 */
2907 		uio_prefaultpages((long)n, uiop);
2908 
2909 		if (vpm_enable) {
2910 			/*
2911 			 * It will use kpm mappings, so no need to
2912 			 * pass an address.
2913 			 */
2914 			error = writerp4(rp, NULL, n, uiop, 0);
2915 		} else  {
2916 			if (segmap_kpm) {
2917 				int pon = uiop->uio_loffset & PAGEOFFSET;
2918 				size_t pn = MIN(PAGESIZE - pon,
2919 				    uiop->uio_resid);
2920 				int pagecreate;
2921 
2922 				mutex_enter(&rp->r_statelock);
2923 				pagecreate = (pon == 0) && (pn == PAGESIZE ||
2924 				    uiop->uio_loffset + pn >= rp->r_size);
2925 				mutex_exit(&rp->r_statelock);
2926 
2927 				base = segmap_getmapflt(segkmap, vp, off + on,
2928 				    pn, !pagecreate, S_WRITE);
2929 
2930 				error = writerp4(rp, base + pon, n, uiop,
2931 				    pagecreate);
2932 
2933 			} else {
2934 				base = segmap_getmapflt(segkmap, vp, off + on,
2935 				    n, 0, S_READ);
2936 				error = writerp4(rp, base + on, n, uiop, 0);
2937 			}
2938 		}
2939 
2940 		if (!error) {
2941 			if (mi->mi_flags & MI4_NOAC)
2942 				flags = SM_WRITE;
2943 			else if ((uiop->uio_loffset % bsize) == 0 ||
2944 			    IS_SWAPVP(vp)) {
2945 				/*
2946 				 * Have written a whole block.
2947 				 * Start an asynchronous write
2948 				 * and mark the buffer to
2949 				 * indicate that it won't be
2950 				 * needed again soon.
2951 				 */
2952 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
2953 			} else
2954 				flags = 0;
2955 			if ((ioflag & (FSYNC|FDSYNC)) ||
2956 			    (rp->r_flags & R4OUTOFSPACE)) {
2957 				flags &= ~SM_ASYNC;
2958 				flags |= SM_WRITE;
2959 			}
2960 			if (vpm_enable) {
2961 				error = vpm_sync_pages(vp, off, n, flags);
2962 			} else {
2963 				error = segmap_release(segkmap, base, flags);
2964 			}
2965 		} else {
2966 			if (vpm_enable) {
2967 				(void) vpm_sync_pages(vp, off, n, 0);
2968 			} else {
2969 				(void) segmap_release(segkmap, base, 0);
2970 			}
2971 			/*
2972 			 * In the event that we got an access error while
2973 			 * faulting in a page for a write-only file just
2974 			 * force a write.
2975 			 */
2976 			if (error == EACCES)
2977 				goto nfs4_fwrite;
2978 		}
2979 	} while (!error && uiop->uio_resid > 0);
2980 
2981 bottom:
2982 	if (error) {
2983 		uiop->uio_resid = resid + remainder;
2984 		uiop->uio_loffset = offset;
2985 	} else {
2986 		uiop->uio_resid += remainder;
2987 
2988 		mutex_enter(&rp->r_statev4_lock);
2989 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
2990 			gethrestime(&rp->r_attr.va_mtime);
2991 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
2992 		}
2993 		mutex_exit(&rp->r_statev4_lock);
2994 	}
2995 
2996 	nfs_rw_exit(&rp->r_lkserlock);
2997 
2998 	return (error);
2999 }
3000 
3001 /*
3002  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
3003  */
3004 static int
3005 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
3006     int flags, cred_t *cr)
3007 {
3008 	struct buf *bp;
3009 	int error;
3010 	page_t *savepp;
3011 	uchar_t fsdata;
3012 	stable_how4 stab_comm;
3013 
3014 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3015 	bp = pageio_setup(pp, len, vp, flags);
3016 	ASSERT(bp != NULL);
3017 
3018 	/*
3019 	 * pageio_setup should have set b_addr to 0.  This
3020 	 * is correct since we want to do I/O on a page
3021 	 * boundary.  bp_mapin will use this addr to calculate
3022 	 * an offset, and then set b_addr to the kernel virtual
3023 	 * address it allocated for us.
3024 	 */
3025 	ASSERT(bp->b_un.b_addr == 0);
3026 
3027 	bp->b_edev = 0;
3028 	bp->b_dev = 0;
3029 	bp->b_lblkno = lbtodb(off);
3030 	bp->b_file = vp;
3031 	bp->b_offset = (offset_t)off;
3032 	bp_mapin(bp);
3033 
3034 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
3035 	    freemem > desfree)
3036 		stab_comm = UNSTABLE4;
3037 	else
3038 		stab_comm = FILE_SYNC4;
3039 
3040 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
3041 
3042 	bp_mapout(bp);
3043 	pageio_done(bp);
3044 
3045 	if (stab_comm == UNSTABLE4)
3046 		fsdata = C_DELAYCOMMIT;
3047 	else
3048 		fsdata = C_NOCOMMIT;
3049 
3050 	savepp = pp;
3051 	do {
3052 		pp->p_fsdata = fsdata;
3053 	} while ((pp = pp->p_next) != savepp);
3054 
3055 	return (error);
3056 }
3057 
3058 /*
3059  */
3060 static int
3061 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
3062 {
3063 	nfs4_open_owner_t	*oop;
3064 	nfs4_open_stream_t	*osp;
3065 	rnode4_t		*rp = VTOR4(vp);
3066 	mntinfo4_t 		*mi = VTOMI4(vp);
3067 	int 			reopen_needed;
3068 
3069 	ASSERT(nfs_zone() == mi->mi_zone);
3070 
3071 
3072 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
3073 	if (!oop)
3074 		return (EIO);
3075 
3076 	/* returns with 'os_sync_lock' held */
3077 	osp = find_open_stream(oop, rp);
3078 	if (!osp) {
3079 		open_owner_rele(oop);
3080 		return (EIO);
3081 	}
3082 
3083 	if (osp->os_failed_reopen) {
3084 		mutex_exit(&osp->os_sync_lock);
3085 		open_stream_rele(osp, rp);
3086 		open_owner_rele(oop);
3087 		return (EIO);
3088 	}
3089 
3090 	/*
3091 	 * Determine whether a reopen is needed.  If this
3092 	 * is a delegation open stream, then the os_delegation bit
3093 	 * should be set.
3094 	 */
3095 
3096 	reopen_needed = osp->os_delegation;
3097 
3098 	mutex_exit(&osp->os_sync_lock);
3099 	open_owner_rele(oop);
3100 
3101 	if (reopen_needed) {
3102 		nfs4_error_zinit(ep);
3103 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
3104 		mutex_enter(&osp->os_sync_lock);
3105 		if (ep->error || ep->stat || osp->os_failed_reopen) {
3106 			mutex_exit(&osp->os_sync_lock);
3107 			open_stream_rele(osp, rp);
3108 			return (EIO);
3109 		}
3110 		mutex_exit(&osp->os_sync_lock);
3111 	}
3112 	open_stream_rele(osp, rp);
3113 
3114 	return (0);
3115 }
3116 
3117 /*
3118  * Write to file.  Writes to remote server in largest size
3119  * chunks that the server can handle.  Write is synchronous.
3120  */
3121 static int
3122 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3123     stable_how4 *stab_comm)
3124 {
3125 	mntinfo4_t *mi;
3126 	COMPOUND4args_clnt args;
3127 	COMPOUND4res_clnt res;
3128 	WRITE4args *wargs;
3129 	WRITE4res *wres;
3130 	nfs_argop4 argop[2];
3131 	nfs_resop4 *resop;
3132 	int tsize;
3133 	stable_how4 stable;
3134 	rnode4_t *rp;
3135 	int doqueue = 1;
3136 	bool_t needrecov;
3137 	nfs4_recov_state_t recov_state;
3138 	nfs4_stateid_types_t sid_types;
3139 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3140 	int recov;
3141 
3142 	rp = VTOR4(vp);
3143 	mi = VTOMI4(vp);
3144 
3145 	ASSERT(nfs_zone() == mi->mi_zone);
3146 
3147 	stable = *stab_comm;
3148 	*stab_comm = FILE_SYNC4;
3149 
3150 	needrecov = FALSE;
3151 	recov_state.rs_flags = 0;
3152 	recov_state.rs_num_retry_despite_err = 0;
3153 	nfs4_init_stateid_types(&sid_types);
3154 
3155 	/* Is curthread the recovery thread? */
3156 	mutex_enter(&mi->mi_lock);
3157 	recov = (mi->mi_recovthread == curthread);
3158 	mutex_exit(&mi->mi_lock);
3159 
3160 recov_retry:
3161 	args.ctag = TAG_WRITE;
3162 	args.array_len = 2;
3163 	args.array = argop;
3164 
3165 	if (!recov) {
3166 		e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3167 		    &recov_state, NULL);
3168 		if (e.error)
3169 			return (e.error);
3170 	}
3171 
3172 	/* 0. putfh target fh */
3173 	argop[0].argop = OP_CPUTFH;
3174 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3175 
3176 	/* 1. write */
3177 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3178 
3179 	do {
3180 
3181 		wargs->offset = (offset4)offset;
3182 		wargs->data_val = base;
3183 
3184 		if (mi->mi_io_kstats) {
3185 			mutex_enter(&mi->mi_lock);
3186 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3187 			mutex_exit(&mi->mi_lock);
3188 		}
3189 
3190 		if ((vp->v_flag & VNOCACHE) ||
3191 		    (rp->r_flags & R4DIRECTIO) ||
3192 		    (mi->mi_flags & MI4_DIRECTIO))
3193 			tsize = MIN(mi->mi_stsize, count);
3194 		else
3195 			tsize = MIN(mi->mi_curwrite, count);
3196 		wargs->data_len = (uint_t)tsize;
3197 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3198 
3199 		if (mi->mi_io_kstats) {
3200 			mutex_enter(&mi->mi_lock);
3201 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3202 			mutex_exit(&mi->mi_lock);
3203 		}
3204 
3205 		if (!recov) {
3206 			needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3207 			if (e.error && !needrecov) {
3208 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3209 				    &recov_state, needrecov);
3210 				return (e.error);
3211 			}
3212 		} else {
3213 			if (e.error)
3214 				return (e.error);
3215 		}
3216 
3217 		/*
3218 		 * Do handling of OLD_STATEID outside
3219 		 * of the normal recovery framework.
3220 		 *
3221 		 * If write receives a BAD stateid error while using a
3222 		 * delegation stateid, retry using the open stateid (if it
3223 		 * exists).  If it doesn't have an open stateid, reopen the
3224 		 * file first, then retry.
3225 		 */
3226 		if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3227 		    sid_types.cur_sid_type != SPEC_SID) {
3228 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3229 			if (!recov)
3230 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3231 				    &recov_state, needrecov);
3232 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3233 			goto recov_retry;
3234 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3235 		    sid_types.cur_sid_type == DEL_SID) {
3236 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3237 			mutex_enter(&rp->r_statev4_lock);
3238 			rp->r_deleg_return_pending = TRUE;
3239 			mutex_exit(&rp->r_statev4_lock);
3240 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3241 				if (!recov)
3242 					nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3243 					    &recov_state, needrecov);
3244 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3245 				    (caddr_t)&res);
3246 				return (EIO);
3247 			}
3248 			if (!recov)
3249 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3250 				    &recov_state, needrecov);
3251 			/* hold needed for nfs4delegreturn_thread */
3252 			VN_HOLD(vp);
3253 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3254 			    NFS4_DR_DISCARD), FALSE);
3255 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3256 			goto recov_retry;
3257 		}
3258 
3259 		if (needrecov) {
3260 			bool_t abort;
3261 
3262 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3263 			    "nfs4write: client got error %d, res.status %d"
3264 			    ", so start recovery", e.error, res.status));
3265 
3266 			abort = nfs4_start_recovery(&e,
3267 			    VTOMI4(vp), vp, NULL, &wargs->stateid,
3268 			    NULL, OP_WRITE, NULL);
3269 			if (!e.error) {
3270 				e.error = geterrno4(res.status);
3271 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3272 				    (caddr_t)&res);
3273 			}
3274 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3275 			    &recov_state, needrecov);
3276 			if (abort == FALSE)
3277 				goto recov_retry;
3278 			return (e.error);
3279 		}
3280 
3281 		if (res.status) {
3282 			e.error = geterrno4(res.status);
3283 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3284 			if (!recov)
3285 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3286 				    &recov_state, needrecov);
3287 			return (e.error);
3288 		}
3289 
3290 		resop = &res.array[1];	/* write res */
3291 		wres = &resop->nfs_resop4_u.opwrite;
3292 
3293 		if ((int)wres->count > tsize) {
3294 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3295 
3296 			zcmn_err(getzoneid(), CE_WARN,
3297 			    "nfs4write: server wrote %u, requested was %u",
3298 			    (int)wres->count, tsize);
3299 			if (!recov)
3300 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3301 				    &recov_state, needrecov);
3302 			return (EIO);
3303 		}
3304 		if (wres->committed == UNSTABLE4) {
3305 			*stab_comm = UNSTABLE4;
3306 			if (wargs->stable == DATA_SYNC4 ||
3307 			    wargs->stable == FILE_SYNC4) {
3308 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3309 				    (caddr_t)&res);
3310 				zcmn_err(getzoneid(), CE_WARN,
3311 				    "nfs4write: server %s did not commit "
3312 				    "to stable storage",
3313 				    rp->r_server->sv_hostname);
3314 				if (!recov)
3315 					nfs4_end_fop(VTOMI4(vp), vp, NULL,
3316 					    OH_WRITE, &recov_state, needrecov);
3317 				return (EIO);
3318 			}
3319 		}
3320 
3321 		tsize = (int)wres->count;
3322 		count -= tsize;
3323 		base += tsize;
3324 		offset += tsize;
3325 		if (mi->mi_io_kstats) {
3326 			mutex_enter(&mi->mi_lock);
3327 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3328 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3329 			    tsize;
3330 			mutex_exit(&mi->mi_lock);
3331 		}
3332 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3333 		mutex_enter(&rp->r_statelock);
3334 		if (rp->r_flags & R4HAVEVERF) {
3335 			if (rp->r_writeverf != wres->writeverf) {
3336 				nfs4_set_mod(vp);
3337 				rp->r_writeverf = wres->writeverf;
3338 			}
3339 		} else {
3340 			rp->r_writeverf = wres->writeverf;
3341 			rp->r_flags |= R4HAVEVERF;
3342 		}
3343 		PURGE_ATTRCACHE4_LOCKED(rp);
3344 		rp->r_flags |= R4WRITEMODIFIED;
3345 		gethrestime(&rp->r_attr.va_mtime);
3346 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3347 		mutex_exit(&rp->r_statelock);
3348 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3349 	} while (count);
3350 
3351 	if (!recov)
3352 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state,
3353 		    needrecov);
3354 
3355 	return (e.error);
3356 }
3357 
3358 /*
3359  * Read from a file.  Reads data in largest chunks our interface can handle.
3360  */
3361 static int
3362 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3363     size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3364 {
3365 	mntinfo4_t *mi;
3366 	COMPOUND4args_clnt args;
3367 	COMPOUND4res_clnt res;
3368 	READ4args *rargs;
3369 	nfs_argop4 argop[2];
3370 	int tsize;
3371 	int doqueue;
3372 	rnode4_t *rp;
3373 	int data_len;
3374 	bool_t is_eof;
3375 	bool_t needrecov = FALSE;
3376 	nfs4_recov_state_t recov_state;
3377 	nfs4_stateid_types_t sid_types;
3378 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3379 
3380 	rp = VTOR4(vp);
3381 	mi = VTOMI4(vp);
3382 	doqueue = 1;
3383 
3384 	ASSERT(nfs_zone() == mi->mi_zone);
3385 
3386 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3387 
3388 	args.array_len = 2;
3389 	args.array = argop;
3390 
3391 	nfs4_init_stateid_types(&sid_types);
3392 
3393 	recov_state.rs_flags = 0;
3394 	recov_state.rs_num_retry_despite_err = 0;
3395 
3396 recov_retry:
3397 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3398 	    &recov_state, NULL);
3399 	if (e.error)
3400 		return (e.error);
3401 
3402 	/* putfh target fh */
3403 	argop[0].argop = OP_CPUTFH;
3404 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3405 
3406 	/* read */
3407 	argop[1].argop = OP_READ;
3408 	rargs = &argop[1].nfs_argop4_u.opread;
3409 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3410 	    OP_READ, &sid_types, async);
3411 
3412 	do {
3413 		if (mi->mi_io_kstats) {
3414 			mutex_enter(&mi->mi_lock);
3415 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3416 			mutex_exit(&mi->mi_lock);
3417 		}
3418 
3419 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3420 		    "nfs4read: %s call, rp %s",
3421 		    needrecov ? "recov" : "first",
3422 		    rnode4info(rp)));
3423 
3424 		if ((vp->v_flag & VNOCACHE) ||
3425 		    (rp->r_flags & R4DIRECTIO) ||
3426 		    (mi->mi_flags & MI4_DIRECTIO))
3427 			tsize = MIN(mi->mi_tsize, count);
3428 		else
3429 			tsize = MIN(mi->mi_curread, count);
3430 
3431 		rargs->offset = (offset4)offset;
3432 		rargs->count = (count4)tsize;
3433 		rargs->res_data_val_alt = NULL;
3434 		rargs->res_mblk = NULL;
3435 		rargs->res_uiop = NULL;
3436 		rargs->res_maxsize = 0;
3437 		rargs->wlist = NULL;
3438 
3439 		if (uiop)
3440 			rargs->res_uiop = uiop;
3441 		else
3442 			rargs->res_data_val_alt = base;
3443 		rargs->res_maxsize = tsize;
3444 
3445 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3446 #ifdef	DEBUG
3447 		if (nfs4read_error_inject) {
3448 			res.status = nfs4read_error_inject;
3449 			nfs4read_error_inject = 0;
3450 		}
3451 #endif
3452 
3453 		if (mi->mi_io_kstats) {
3454 			mutex_enter(&mi->mi_lock);
3455 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3456 			mutex_exit(&mi->mi_lock);
3457 		}
3458 
3459 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3460 		if (e.error != 0 && !needrecov) {
3461 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3462 			    &recov_state, needrecov);
3463 			return (e.error);
3464 		}
3465 
3466 		/*
3467 		 * Do proper retry for OLD and BAD stateid errors outside
3468 		 * of the normal recovery framework.  There are two differences
3469 		 * between async and sync reads.  The first is that we allow
3470 		 * retry on BAD_STATEID for async reads, but not sync reads.
3471 		 * The second is that we mark the file dead for a failed
3472 		 * attempt with a special stateid for sync reads, but just
3473 		 * return EIO for async reads.
3474 		 *
3475 		 * If a sync read receives a BAD stateid error while using a
3476 		 * delegation stateid, retry using the open stateid (if it
3477 		 * exists).  If it doesn't have an open stateid, reopen the
3478 		 * file first, then retry.
3479 		 */
3480 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3481 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3482 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3483 			    &recov_state, needrecov);
3484 			if (sid_types.cur_sid_type == SPEC_SID) {
3485 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3486 				    (caddr_t)&res);
3487 				return (EIO);
3488 			}
3489 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3490 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3491 			goto recov_retry;
3492 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3493 		    !async && sid_types.cur_sid_type != SPEC_SID) {
3494 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3495 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3496 			    &recov_state, needrecov);
3497 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3498 			goto recov_retry;
3499 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3500 		    sid_types.cur_sid_type == DEL_SID) {
3501 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3502 			mutex_enter(&rp->r_statev4_lock);
3503 			rp->r_deleg_return_pending = TRUE;
3504 			mutex_exit(&rp->r_statev4_lock);
3505 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3506 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3507 				    &recov_state, needrecov);
3508 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3509 				    (caddr_t)&res);
3510 				return (EIO);
3511 			}
3512 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3513 			    &recov_state, needrecov);
3514 			/* hold needed for nfs4delegreturn_thread */
3515 			VN_HOLD(vp);
3516 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3517 			    NFS4_DR_DISCARD), FALSE);
3518 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3519 			goto recov_retry;
3520 		}
3521 		if (needrecov) {
3522 			bool_t abort;
3523 
3524 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3525 			    "nfs4read: initiating recovery\n"));
3526 			abort = nfs4_start_recovery(&e,
3527 			    mi, vp, NULL, &rargs->stateid,
3528 			    NULL, OP_READ, NULL);
3529 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3530 			    &recov_state, needrecov);
3531 			/*
3532 			 * Do not retry if we got OLD_STATEID using a special
3533 			 * stateid.  This avoids looping with a broken server.
3534 			 */
3535 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3536 			    sid_types.cur_sid_type == SPEC_SID)
3537 				abort = TRUE;
3538 
3539 			if (abort == FALSE) {
3540 				/*
3541 				 * Need to retry all possible stateids in
3542 				 * case the recovery error wasn't stateid
3543 				 * related or the stateids have become
3544 				 * stale (server reboot).
3545 				 */
3546 				nfs4_init_stateid_types(&sid_types);
3547 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3548 				    (caddr_t)&res);
3549 				goto recov_retry;
3550 			}
3551 
3552 			if (!e.error) {
3553 				e.error = geterrno4(res.status);
3554 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3555 				    (caddr_t)&res);
3556 			}
3557 			return (e.error);
3558 		}
3559 
3560 		if (res.status) {
3561 			e.error = geterrno4(res.status);
3562 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3563 			    &recov_state, needrecov);
3564 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3565 			return (e.error);
3566 		}
3567 
3568 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3569 		count -= data_len;
3570 		if (base)
3571 			base += data_len;
3572 		offset += data_len;
3573 		if (mi->mi_io_kstats) {
3574 			mutex_enter(&mi->mi_lock);
3575 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3576 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3577 			mutex_exit(&mi->mi_lock);
3578 		}
3579 		lwp_stat_update(LWP_STAT_INBLK, 1);
3580 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3581 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3582 
3583 	} while (count && !is_eof);
3584 
3585 	*residp = count;
3586 
3587 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3588 
3589 	return (e.error);
3590 }
3591 
3592 /* ARGSUSED */
3593 static int
3594 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp,
3595 	caller_context_t *ct)
3596 {
3597 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3598 		return (EIO);
3599 	switch (cmd) {
3600 		case _FIODIRECTIO:
3601 			return (nfs4_directio(vp, (int)arg, cr));
3602 		default:
3603 			return (ENOTTY);
3604 	}
3605 }
3606 
3607 /* ARGSUSED */
3608 int
3609 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3610     caller_context_t *ct)
3611 {
3612 	int error;
3613 	rnode4_t *rp = VTOR4(vp);
3614 
3615 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3616 		return (EIO);
3617 	/*
3618 	 * If it has been specified that the return value will
3619 	 * just be used as a hint, and we are only being asked
3620 	 * for size, fsid or rdevid, then return the client's
3621 	 * notion of these values without checking to make sure
3622 	 * that the attribute cache is up to date.
3623 	 * The whole point is to avoid an over the wire GETATTR
3624 	 * call.
3625 	 */
3626 	if (flags & ATTR_HINT) {
3627 		if (vap->va_mask ==
3628 		    (vap->va_mask & (AT_SIZE | AT_FSID | AT_RDEV))) {
3629 			mutex_enter(&rp->r_statelock);
3630 			if (vap->va_mask | AT_SIZE)
3631 				vap->va_size = rp->r_size;
3632 			if (vap->va_mask | AT_FSID)
3633 				vap->va_fsid = rp->r_attr.va_fsid;
3634 			if (vap->va_mask | AT_RDEV)
3635 				vap->va_rdev = rp->r_attr.va_rdev;
3636 			mutex_exit(&rp->r_statelock);
3637 			return (0);
3638 		}
3639 	}
3640 
3641 	/*
3642 	 * Only need to flush pages if asking for the mtime
3643 	 * and if there any dirty pages or any outstanding
3644 	 * asynchronous (write) requests for this file.
3645 	 */
3646 	if (vap->va_mask & AT_MTIME) {
3647 		rp = VTOR4(vp);
3648 		if (nfs4_has_pages(vp)) {
3649 			mutex_enter(&rp->r_statev4_lock);
3650 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3651 				mutex_exit(&rp->r_statev4_lock);
3652 				if (rp->r_flags & R4DIRTY ||
3653 				    rp->r_awcount > 0) {
3654 					mutex_enter(&rp->r_statelock);
3655 					rp->r_gcount++;
3656 					mutex_exit(&rp->r_statelock);
3657 					error =
3658 					    nfs4_putpage(vp, (u_offset_t)0,
3659 					    0, 0, cr, NULL);
3660 					mutex_enter(&rp->r_statelock);
3661 					if (error && (error == ENOSPC ||
3662 					    error == EDQUOT)) {
3663 						if (!rp->r_error)
3664 							rp->r_error = error;
3665 					}
3666 					if (--rp->r_gcount == 0)
3667 						cv_broadcast(&rp->r_cv);
3668 					mutex_exit(&rp->r_statelock);
3669 				}
3670 			} else {
3671 				mutex_exit(&rp->r_statev4_lock);
3672 			}
3673 		}
3674 	}
3675 	return (nfs4getattr(vp, vap, cr));
3676 }
3677 
3678 int
3679 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3680 {
3681 	/*
3682 	 * If these are the only two bits cleared
3683 	 * on the server then return 0 (OK) else
3684 	 * return 1 (BAD).
3685 	 */
3686 	on_client &= ~(S_ISUID|S_ISGID);
3687 	if (on_client == from_server)
3688 		return (0);
3689 	else
3690 		return (1);
3691 }
3692 
3693 /*ARGSUSED4*/
3694 static int
3695 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3696     caller_context_t *ct)
3697 {
3698 	if (vap->va_mask & AT_NOSET)
3699 		return (EINVAL);
3700 
3701 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3702 		return (EIO);
3703 
3704 	/*
3705 	 * Don't call secpolicy_vnode_setattr, the client cannot
3706 	 * use its cached attributes to make security decisions
3707 	 * as the server may be faking mode bits or mapping uid/gid.
3708 	 * Always just let the server to the checking.
3709 	 * If we provide the ability to remove basic priviledges
3710 	 * to setattr (e.g. basic without chmod) then we will
3711 	 * need to add a check here before calling the server.
3712 	 */
3713 
3714 	return (nfs4setattr(vp, vap, flags, cr, NULL));
3715 }
3716 
3717 /*
3718  * To replace the "guarded" version 3 setattr, we use two types of compound
3719  * setattr requests:
3720  * 1. The "normal" setattr, used when the size of the file isn't being
3721  *    changed - { Putfh <fh>; Setattr; Getattr }/
3722  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3723  *    with only ctime as the argument. If the server ctime differs from
3724  *    what is cached on the client, the verify will fail, but we would
3725  *    already have the ctime from the preceding getattr, so just set it
3726  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3727  *	Setattr; Getattr }.
3728  *
3729  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3730  * this setattr and NULL if they are not.
3731  */
3732 static int
3733 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3734     vsecattr_t *vsap)
3735 {
3736 	COMPOUND4args_clnt args;
3737 	COMPOUND4res_clnt res, *resp = NULL;
3738 	nfs4_ga_res_t *garp = NULL;
3739 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3740 	nfs_argop4 argop[5];
3741 	int verify_argop = -1;
3742 	int setattr_argop = 1;
3743 	nfs_resop4 *resop;
3744 	vattr_t va;
3745 	rnode4_t *rp;
3746 	int doqueue = 1;
3747 	uint_t mask = vap->va_mask;
3748 	mode_t omode;
3749 	vsecattr_t *vsp;
3750 	timestruc_t ctime;
3751 	bool_t needrecov = FALSE;
3752 	nfs4_recov_state_t recov_state;
3753 	nfs4_stateid_types_t sid_types;
3754 	stateid4 stateid;
3755 	hrtime_t t;
3756 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3757 	servinfo4_t *svp;
3758 	bitmap4 supp_attrs;
3759 
3760 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3761 	rp = VTOR4(vp);
3762 	nfs4_init_stateid_types(&sid_types);
3763 
3764 	/*
3765 	 * Only need to flush pages if there are any pages and
3766 	 * if the file is marked as dirty in some fashion.  The
3767 	 * file must be flushed so that we can accurately
3768 	 * determine the size of the file and the cached data
3769 	 * after the SETATTR returns.  A file is considered to
3770 	 * be dirty if it is either marked with R4DIRTY, has
3771 	 * outstanding i/o's active, or is mmap'd.  In this
3772 	 * last case, we can't tell whether there are dirty
3773 	 * pages, so we flush just to be sure.
3774 	 */
3775 	if (nfs4_has_pages(vp) &&
3776 	    ((rp->r_flags & R4DIRTY) ||
3777 	    rp->r_count > 0 ||
3778 	    rp->r_mapcnt > 0)) {
3779 		ASSERT(vp->v_type != VCHR);
3780 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr, NULL);
3781 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3782 			mutex_enter(&rp->r_statelock);
3783 			if (!rp->r_error)
3784 				rp->r_error = e.error;
3785 			mutex_exit(&rp->r_statelock);
3786 		}
3787 	}
3788 
3789 	if (mask & AT_SIZE) {
3790 		/*
3791 		 * Verification setattr compound for non-deleg AT_SIZE:
3792 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3793 		 * Set ctime local here (outside the do_again label)
3794 		 * so that subsequent retries (after failed VERIFY)
3795 		 * will use ctime from GETATTR results (from failed
3796 		 * verify compound) as VERIFY arg.
3797 		 * If file has delegation, then VERIFY(time_metadata)
3798 		 * is of little added value, so don't bother.
3799 		 */
3800 		mutex_enter(&rp->r_statev4_lock);
3801 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3802 		    rp->r_deleg_return_pending) {
3803 			numops = 5;
3804 			ctime = rp->r_attr.va_ctime;
3805 		}
3806 		mutex_exit(&rp->r_statev4_lock);
3807 	}
3808 
3809 	recov_state.rs_flags = 0;
3810 	recov_state.rs_num_retry_despite_err = 0;
3811 
3812 	args.ctag = TAG_SETATTR;
3813 do_again:
3814 recov_retry:
3815 	setattr_argop = numops - 2;
3816 
3817 	args.array = argop;
3818 	args.array_len = numops;
3819 
3820 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3821 	if (e.error)
3822 		return (e.error);
3823 
3824 
3825 	/* putfh target fh */
3826 	argop[0].argop = OP_CPUTFH;
3827 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3828 
3829 	if (numops == 5) {
3830 		/*
3831 		 * We only care about the ctime, but need to get mtime
3832 		 * and size for proper cache update.
3833 		 */
3834 		/* getattr */
3835 		argop[1].argop = OP_GETATTR;
3836 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3837 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3838 
3839 		/* verify - set later in loop */
3840 		verify_argop = 2;
3841 	}
3842 
3843 	/* setattr */
3844 	svp = rp->r_server;
3845 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3846 	supp_attrs = svp->sv_supp_attrs;
3847 	nfs_rw_exit(&svp->sv_lock);
3848 
3849 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3850 	    supp_attrs, &e.error, &sid_types);
3851 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3852 	if (e.error) {
3853 		/* req time field(s) overflow - return immediately */
3854 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3855 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3856 		    opsetattr.obj_attributes);
3857 		return (e.error);
3858 	}
3859 	omode = rp->r_attr.va_mode;
3860 
3861 	/* getattr */
3862 	argop[numops-1].argop = OP_GETATTR;
3863 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3864 	/*
3865 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3866 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3867 	 * used in updating the ACL cache.
3868 	 */
3869 	if (vsap != NULL)
3870 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3871 		    FATTR4_ACL_MASK;
3872 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3873 
3874 	/*
3875 	 * setattr iterates if the object size is set and the cached ctime
3876 	 * does not match the file ctime. In that case, verify the ctime first.
3877 	 */
3878 
3879 	do {
3880 		if (verify_argop != -1) {
3881 			/*
3882 			 * Verify that the ctime match before doing setattr.
3883 			 */
3884 			va.va_mask = AT_CTIME;
3885 			va.va_ctime = ctime;
3886 			svp = rp->r_server;
3887 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3888 			supp_attrs = svp->sv_supp_attrs;
3889 			nfs_rw_exit(&svp->sv_lock);
3890 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3891 			    OP_VERIFY, supp_attrs);
3892 			if (e.error) {
3893 				/* req time field(s) overflow - return */
3894 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3895 				    needrecov);
3896 				break;
3897 			}
3898 		}
3899 
3900 		doqueue = 1;
3901 
3902 		t = gethrtime();
3903 
3904 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3905 
3906 		/*
3907 		 * Purge the access cache and ACL cache if changing either the
3908 		 * owner of the file, the group owner, or the mode.  These may
3909 		 * change the access permissions of the file, so purge old
3910 		 * information and start over again.
3911 		 */
3912 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3913 			(void) nfs4_access_purge_rp(rp);
3914 			if (rp->r_secattr != NULL) {
3915 				mutex_enter(&rp->r_statelock);
3916 				vsp = rp->r_secattr;
3917 				rp->r_secattr = NULL;
3918 				mutex_exit(&rp->r_statelock);
3919 				if (vsp != NULL)
3920 					nfs4_acl_free_cache(vsp);
3921 			}
3922 		}
3923 
3924 		/*
3925 		 * If res.array_len == numops, then everything succeeded,
3926 		 * except for possibly the final getattr.  If only the
3927 		 * last getattr failed, give up, and don't try recovery.
3928 		 */
3929 		if (res.array_len == numops) {
3930 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3931 			    needrecov);
3932 			if (! e.error)
3933 				resp = &res;
3934 			break;
3935 		}
3936 
3937 		/*
3938 		 * if either rpc call failed or completely succeeded - done
3939 		 */
3940 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
3941 		if (e.error) {
3942 			PURGE_ATTRCACHE4(vp);
3943 			if (!needrecov) {
3944 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3945 				    needrecov);
3946 				break;
3947 			}
3948 		}
3949 
3950 		/*
3951 		 * Do proper retry for OLD_STATEID outside of the normal
3952 		 * recovery framework.
3953 		 */
3954 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3955 		    sid_types.cur_sid_type != SPEC_SID &&
3956 		    sid_types.cur_sid_type != NO_SID) {
3957 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3958 			    needrecov);
3959 			nfs4_save_stateid(&stateid, &sid_types);
3960 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3961 			    opsetattr.obj_attributes);
3962 			if (verify_argop != -1) {
3963 				nfs4args_verify_free(&argop[verify_argop]);
3964 				verify_argop = -1;
3965 			}
3966 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3967 			goto recov_retry;
3968 		}
3969 
3970 		if (needrecov) {
3971 			bool_t abort;
3972 
3973 			abort = nfs4_start_recovery(&e,
3974 			    VTOMI4(vp), vp, NULL, NULL, NULL,
3975 			    OP_SETATTR, NULL);
3976 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3977 			    needrecov);
3978 			/*
3979 			 * Do not retry if we failed with OLD_STATEID using
3980 			 * a special stateid.  This is done to avoid looping
3981 			 * with a broken server.
3982 			 */
3983 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3984 			    (sid_types.cur_sid_type == SPEC_SID ||
3985 			    sid_types.cur_sid_type == NO_SID))
3986 				abort = TRUE;
3987 			if (!e.error) {
3988 				if (res.status == NFS4ERR_BADOWNER)
3989 					nfs4_log_badowner(VTOMI4(vp),
3990 					    OP_SETATTR);
3991 
3992 				e.error = geterrno4(res.status);
3993 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3994 				    (caddr_t)&res);
3995 			}
3996 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3997 			    opsetattr.obj_attributes);
3998 			if (verify_argop != -1) {
3999 				nfs4args_verify_free(&argop[verify_argop]);
4000 				verify_argop = -1;
4001 			}
4002 			if (abort == FALSE) {
4003 				/*
4004 				 * Need to retry all possible stateids in
4005 				 * case the recovery error wasn't stateid
4006 				 * related or the stateids have become
4007 				 * stale (server reboot).
4008 				 */
4009 				nfs4_init_stateid_types(&sid_types);
4010 				goto recov_retry;
4011 			}
4012 			return (e.error);
4013 		}
4014 
4015 		/*
4016 		 * Need to call nfs4_end_op before nfs4getattr to
4017 		 * avoid potential nfs4_start_op deadlock. See RFE
4018 		 * 4777612.  Calls to nfs4_invalidate_pages() and
4019 		 * nfs4_purge_stale_fh() might also generate over the
4020 		 * wire calls which my cause nfs4_start_op() deadlock.
4021 		 */
4022 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4023 
4024 		/*
4025 		 * Check to update lease.
4026 		 */
4027 		resp = &res;
4028 		if (res.status == NFS4_OK) {
4029 			break;
4030 		}
4031 
4032 		/*
4033 		 * Check if verify failed to see if try again
4034 		 */
4035 		if ((verify_argop == -1) || (res.array_len != 3)) {
4036 			/*
4037 			 * can't continue...
4038 			 */
4039 			if (res.status == NFS4ERR_BADOWNER)
4040 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
4041 
4042 			e.error = geterrno4(res.status);
4043 		} else {
4044 			/*
4045 			 * When the verify request fails, the client ctime is
4046 			 * not in sync with the server. This is the same as
4047 			 * the version 3 "not synchronized" error, and we
4048 			 * handle it in a similar manner (XXX do we need to???).
4049 			 * Use the ctime returned in the first getattr for
4050 			 * the input to the next verify.
4051 			 * If we couldn't get the attributes, then we give up
4052 			 * because we can't complete the operation as required.
4053 			 */
4054 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
4055 		}
4056 		if (e.error) {
4057 			PURGE_ATTRCACHE4(vp);
4058 			nfs4_purge_stale_fh(e.error, vp, cr);
4059 		} else {
4060 			/*
4061 			 * retry with a new verify value
4062 			 */
4063 			ctime = garp->n4g_va.va_ctime;
4064 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4065 			resp = NULL;
4066 		}
4067 		if (!e.error) {
4068 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4069 			    opsetattr.obj_attributes);
4070 			if (verify_argop != -1) {
4071 				nfs4args_verify_free(&argop[verify_argop]);
4072 				verify_argop = -1;
4073 			}
4074 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4075 			goto do_again;
4076 		}
4077 	} while (!e.error);
4078 
4079 	if (e.error) {
4080 		/*
4081 		 * If we are here, rfs4call has an irrecoverable error - return
4082 		 */
4083 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4084 		    opsetattr.obj_attributes);
4085 		if (verify_argop != -1) {
4086 			nfs4args_verify_free(&argop[verify_argop]);
4087 			verify_argop = -1;
4088 		}
4089 		if (resp)
4090 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4091 		return (e.error);
4092 	}
4093 
4094 
4095 
4096 	/*
4097 	 * If changing the size of the file, invalidate
4098 	 * any local cached data which is no longer part
4099 	 * of the file.  We also possibly invalidate the
4100 	 * last page in the file.  We could use
4101 	 * pvn_vpzero(), but this would mark the page as
4102 	 * modified and require it to be written back to
4103 	 * the server for no particularly good reason.
4104 	 * This way, if we access it, then we bring it
4105 	 * back in.  A read should be cheaper than a
4106 	 * write.
4107 	 */
4108 	if (mask & AT_SIZE) {
4109 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
4110 	}
4111 
4112 	/* either no error or one of the postop getattr failed */
4113 
4114 	/*
4115 	 * XXX Perform a simplified version of wcc checking. Instead of
4116 	 * have another getattr to get pre-op, just purge cache if
4117 	 * any of the ops prior to and including the getattr failed.
4118 	 * If the getattr succeeded then update the attrcache accordingly.
4119 	 */
4120 
4121 	garp = NULL;
4122 	if (res.status == NFS4_OK) {
4123 		/*
4124 		 * Last getattr
4125 		 */
4126 		resop = &res.array[numops - 1];
4127 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4128 	}
4129 	/*
4130 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
4131 	 * rather than filling it.  See the function itself for details.
4132 	 */
4133 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4134 	if (garp != NULL) {
4135 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
4136 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
4137 			vs_ace4_destroy(&garp->n4g_vsa);
4138 		} else {
4139 			if (vsap != NULL) {
4140 				/*
4141 				 * The ACL was supposed to be set and to be
4142 				 * returned in the last getattr of this
4143 				 * compound, but for some reason the getattr
4144 				 * result doesn't contain the ACL.  In this
4145 				 * case, purge the ACL cache.
4146 				 */
4147 				if (rp->r_secattr != NULL) {
4148 					mutex_enter(&rp->r_statelock);
4149 					vsp = rp->r_secattr;
4150 					rp->r_secattr = NULL;
4151 					mutex_exit(&rp->r_statelock);
4152 					if (vsp != NULL)
4153 						nfs4_acl_free_cache(vsp);
4154 				}
4155 			}
4156 		}
4157 	}
4158 
4159 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4160 		/*
4161 		 * Set the size, rather than relying on getting it updated
4162 		 * via a GETATTR.  With delegations the client tries to
4163 		 * suppress GETATTR calls.
4164 		 */
4165 		mutex_enter(&rp->r_statelock);
4166 		rp->r_size = vap->va_size;
4167 		mutex_exit(&rp->r_statelock);
4168 	}
4169 
4170 	/*
4171 	 * Can free up request args and res
4172 	 */
4173 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4174 	    opsetattr.obj_attributes);
4175 	if (verify_argop != -1) {
4176 		nfs4args_verify_free(&argop[verify_argop]);
4177 		verify_argop = -1;
4178 	}
4179 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4180 
4181 	/*
4182 	 * Some servers will change the mode to clear the setuid
4183 	 * and setgid bits when changing the uid or gid.  The
4184 	 * client needs to compensate appropriately.
4185 	 */
4186 	if (mask & (AT_UID | AT_GID)) {
4187 		int terror, do_setattr;
4188 
4189 		do_setattr = 0;
4190 		va.va_mask = AT_MODE;
4191 		terror = nfs4getattr(vp, &va, cr);
4192 		if (!terror &&
4193 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4194 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4195 			va.va_mask = AT_MODE;
4196 			if (mask & AT_MODE) {
4197 				/*
4198 				 * We asked the mode to be changed and what
4199 				 * we just got from the server in getattr is
4200 				 * not what we wanted it to be, so set it now.
4201 				 */
4202 				va.va_mode = vap->va_mode;
4203 				do_setattr = 1;
4204 			} else {
4205 				/*
4206 				 * We did not ask the mode to be changed,
4207 				 * Check to see that the server just cleared
4208 				 * I_SUID and I_GUID from it. If not then
4209 				 * set mode to omode with UID/GID cleared.
4210 				 */
4211 				if (nfs4_compare_modes(va.va_mode, omode)) {
4212 					omode &= ~(S_ISUID|S_ISGID);
4213 					va.va_mode = omode;
4214 					do_setattr = 1;
4215 				}
4216 			}
4217 
4218 			if (do_setattr)
4219 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4220 		}
4221 	}
4222 
4223 	return (e.error);
4224 }
4225 
4226 /* ARGSUSED */
4227 static int
4228 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr, caller_context_t *ct)
4229 {
4230 	COMPOUND4args_clnt args;
4231 	COMPOUND4res_clnt res;
4232 	int doqueue;
4233 	uint32_t acc, resacc, argacc;
4234 	rnode4_t *rp;
4235 	cred_t *cred, *ncr, *ncrfree = NULL;
4236 	nfs4_access_type_t cacc;
4237 	int num_ops;
4238 	nfs_argop4 argop[3];
4239 	nfs_resop4 *resop;
4240 	bool_t needrecov = FALSE, do_getattr;
4241 	nfs4_recov_state_t recov_state;
4242 	int rpc_error;
4243 	hrtime_t t;
4244 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4245 	mntinfo4_t *mi = VTOMI4(vp);
4246 
4247 	if (nfs_zone() != mi->mi_zone)
4248 		return (EIO);
4249 
4250 	acc = 0;
4251 	if (mode & VREAD)
4252 		acc |= ACCESS4_READ;
4253 	if (mode & VWRITE) {
4254 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4255 			return (EROFS);
4256 		if (vp->v_type == VDIR)
4257 			acc |= ACCESS4_DELETE;
4258 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4259 	}
4260 	if (mode & VEXEC) {
4261 		if (vp->v_type == VDIR)
4262 			acc |= ACCESS4_LOOKUP;
4263 		else
4264 			acc |= ACCESS4_EXECUTE;
4265 	}
4266 
4267 	if (VTOR4(vp)->r_acache != NULL) {
4268 		e.error = nfs4_validate_caches(vp, cr);
4269 		if (e.error)
4270 			return (e.error);
4271 	}
4272 
4273 	rp = VTOR4(vp);
4274 	if (vp->v_type == VDIR)
4275 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4276 		    ACCESS4_EXTEND | ACCESS4_LOOKUP;
4277 	else
4278 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4279 		    ACCESS4_EXECUTE;
4280 	recov_state.rs_flags = 0;
4281 	recov_state.rs_num_retry_despite_err = 0;
4282 
4283 	cred = cr;
4284 	/*
4285 	 * ncr and ncrfree both initially
4286 	 * point to the memory area returned
4287 	 * by crnetadjust();
4288 	 * ncrfree not NULL when exiting means
4289 	 * that we need to release it
4290 	 */
4291 	ncr = crnetadjust(cred);
4292 	ncrfree = ncr;
4293 
4294 tryagain:
4295 	cacc = nfs4_access_check(rp, acc, cred);
4296 	if (cacc == NFS4_ACCESS_ALLOWED) {
4297 		if (ncrfree != NULL)
4298 			crfree(ncrfree);
4299 		return (0);
4300 	}
4301 	if (cacc == NFS4_ACCESS_DENIED) {
4302 		/*
4303 		 * If the cred can be adjusted, try again
4304 		 * with the new cred.
4305 		 */
4306 		if (ncr != NULL) {
4307 			cred = ncr;
4308 			ncr = NULL;
4309 			goto tryagain;
4310 		}
4311 		if (ncrfree != NULL)
4312 			crfree(ncrfree);
4313 		return (EACCES);
4314 	}
4315 
4316 recov_retry:
4317 	/*
4318 	 * Don't take with r_statev4_lock here. r_deleg_type could
4319 	 * change as soon as lock is released.  Since it is an int,
4320 	 * there is no atomicity issue.
4321 	 */
4322 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4323 	num_ops = do_getattr ? 3 : 2;
4324 
4325 	args.ctag = TAG_ACCESS;
4326 
4327 	args.array_len = num_ops;
4328 	args.array = argop;
4329 
4330 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4331 	    &recov_state, NULL)) {
4332 		if (ncrfree != NULL)
4333 			crfree(ncrfree);
4334 		return (e.error);
4335 	}
4336 
4337 	/* putfh target fh */
4338 	argop[0].argop = OP_CPUTFH;
4339 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4340 
4341 	/* access */
4342 	argop[1].argop = OP_ACCESS;
4343 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4344 
4345 	/* getattr */
4346 	if (do_getattr) {
4347 		argop[2].argop = OP_GETATTR;
4348 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4349 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4350 	}
4351 
4352 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4353 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4354 	    rnode4info(VTOR4(vp))));
4355 
4356 	doqueue = 1;
4357 	t = gethrtime();
4358 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4359 	rpc_error = e.error;
4360 
4361 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4362 	if (needrecov) {
4363 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4364 		    "nfs4_access: initiating recovery\n"));
4365 
4366 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4367 		    NULL, OP_ACCESS, NULL) == FALSE) {
4368 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4369 			    &recov_state, needrecov);
4370 			if (!e.error)
4371 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4372 				    (caddr_t)&res);
4373 			goto recov_retry;
4374 		}
4375 	}
4376 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4377 
4378 	if (e.error)
4379 		goto out;
4380 
4381 	if (res.status) {
4382 		e.error = geterrno4(res.status);
4383 		/*
4384 		 * This might generate over the wire calls throught
4385 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4386 		 * here to avoid a deadlock.
4387 		 */
4388 		nfs4_purge_stale_fh(e.error, vp, cr);
4389 		goto out;
4390 	}
4391 	resop = &res.array[1];	/* access res */
4392 
4393 	resacc = resop->nfs_resop4_u.opaccess.access;
4394 
4395 	if (do_getattr) {
4396 		resop++;	/* getattr res */
4397 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4398 		    t, cr, FALSE, NULL);
4399 	}
4400 
4401 	if (!e.error) {
4402 		nfs4_access_cache(rp, argacc, resacc, cred);
4403 		/*
4404 		 * we just cached results with cred; if cred is the
4405 		 * adjusted credentials from crnetadjust, we do not want
4406 		 * to release them before exiting: hence setting ncrfree
4407 		 * to NULL
4408 		 */
4409 		if (cred != cr)
4410 			ncrfree = NULL;
4411 		/* XXX check the supported bits too? */
4412 		if ((acc & resacc) != acc) {
4413 			/*
4414 			 * The following code implements the semantic
4415 			 * that a setuid root program has *at least* the
4416 			 * permissions of the user that is running the
4417 			 * program.  See rfs3call() for more portions
4418 			 * of the implementation of this functionality.
4419 			 */
4420 			/* XXX-LP */
4421 			if (ncr != NULL) {
4422 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4423 				    (caddr_t)&res);
4424 				cred = ncr;
4425 				ncr = NULL;
4426 				goto tryagain;
4427 			}
4428 			e.error = EACCES;
4429 		}
4430 	}
4431 
4432 out:
4433 	if (!rpc_error)
4434 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4435 
4436 	if (ncrfree != NULL)
4437 		crfree(ncrfree);
4438 
4439 	return (e.error);
4440 }
4441 
4442 /* ARGSUSED */
4443 static int
4444 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr, caller_context_t *ct)
4445 {
4446 	COMPOUND4args_clnt args;
4447 	COMPOUND4res_clnt res;
4448 	int doqueue;
4449 	rnode4_t *rp;
4450 	nfs_argop4 argop[3];
4451 	nfs_resop4 *resop;
4452 	READLINK4res *lr_res;
4453 	nfs4_ga_res_t *garp;
4454 	uint_t len;
4455 	char *linkdata;
4456 	bool_t needrecov = FALSE;
4457 	nfs4_recov_state_t recov_state;
4458 	hrtime_t t;
4459 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4460 
4461 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4462 		return (EIO);
4463 	/*
4464 	 * Can't readlink anything other than a symbolic link.
4465 	 */
4466 	if (vp->v_type != VLNK)
4467 		return (EINVAL);
4468 
4469 	rp = VTOR4(vp);
4470 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4471 		e.error = nfs4_validate_caches(vp, cr);
4472 		if (e.error)
4473 			return (e.error);
4474 		mutex_enter(&rp->r_statelock);
4475 		if (rp->r_symlink.contents != NULL) {
4476 			e.error = uiomove(rp->r_symlink.contents,
4477 			    rp->r_symlink.len, UIO_READ, uiop);
4478 			mutex_exit(&rp->r_statelock);
4479 			return (e.error);
4480 		}
4481 		mutex_exit(&rp->r_statelock);
4482 	}
4483 	recov_state.rs_flags = 0;
4484 	recov_state.rs_num_retry_despite_err = 0;
4485 
4486 recov_retry:
4487 	args.array_len = 3;
4488 	args.array = argop;
4489 	args.ctag = TAG_READLINK;
4490 
4491 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4492 	if (e.error) {
4493 		return (e.error);
4494 	}
4495 
4496 	/* 0. putfh symlink fh */
4497 	argop[0].argop = OP_CPUTFH;
4498 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4499 
4500 	/* 1. readlink */
4501 	argop[1].argop = OP_READLINK;
4502 
4503 	/* 2. getattr */
4504 	argop[2].argop = OP_GETATTR;
4505 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4506 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4507 
4508 	doqueue = 1;
4509 
4510 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4511 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4512 	    rnode4info(VTOR4(vp))));
4513 
4514 	t = gethrtime();
4515 
4516 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4517 
4518 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4519 	if (needrecov) {
4520 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4521 		    "nfs4_readlink: initiating recovery\n"));
4522 
4523 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4524 		    NULL, OP_READLINK, NULL) == FALSE) {
4525 			if (!e.error)
4526 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4527 				    (caddr_t)&res);
4528 
4529 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4530 			    needrecov);
4531 			goto recov_retry;
4532 		}
4533 	}
4534 
4535 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4536 
4537 	if (e.error)
4538 		return (e.error);
4539 
4540 	/*
4541 	 * There is an path in the code below which calls
4542 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4543 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4544 	 * here to avoid nfs4_start_op() deadlock.
4545 	 */
4546 
4547 	if (res.status && (res.array_len < args.array_len)) {
4548 		/*
4549 		 * either Putfh or Link failed
4550 		 */
4551 		e.error = geterrno4(res.status);
4552 		nfs4_purge_stale_fh(e.error, vp, cr);
4553 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4554 		return (e.error);
4555 	}
4556 
4557 	resop = &res.array[1];	/* readlink res */
4558 	lr_res = &resop->nfs_resop4_u.opreadlink;
4559 
4560 	/*
4561 	 * treat symlink names as data
4562 	 */
4563 	linkdata = utf8_to_str(&lr_res->link, &len, NULL);
4564 	if (linkdata != NULL) {
4565 		int uio_len = len - 1;
4566 		/* len includes null byte, which we won't uiomove */
4567 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4568 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4569 			mutex_enter(&rp->r_statelock);
4570 			if (rp->r_symlink.contents == NULL) {
4571 				rp->r_symlink.contents = linkdata;
4572 				rp->r_symlink.len = uio_len;
4573 				rp->r_symlink.size = len;
4574 				mutex_exit(&rp->r_statelock);
4575 			} else {
4576 				mutex_exit(&rp->r_statelock);
4577 				kmem_free(linkdata, len);
4578 			}
4579 		} else {
4580 			kmem_free(linkdata, len);
4581 		}
4582 	}
4583 	if (res.status == NFS4_OK) {
4584 		resop++;	/* getattr res */
4585 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4586 	}
4587 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4588 
4589 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4590 
4591 	/*
4592 	 * The over the wire error for attempting to readlink something
4593 	 * other than a symbolic link is ENXIO.  However, we need to
4594 	 * return EINVAL instead of ENXIO, so we map it here.
4595 	 */
4596 	return (e.error == ENXIO ? EINVAL : e.error);
4597 }
4598 
4599 /*
4600  * Flush local dirty pages to stable storage on the server.
4601  *
4602  * If FNODSYNC is specified, then there is nothing to do because
4603  * metadata changes are not cached on the client before being
4604  * sent to the server.
4605  */
4606 /* ARGSUSED */
4607 static int
4608 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
4609 {
4610 	int error;
4611 
4612 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4613 		return (0);
4614 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4615 		return (EIO);
4616 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4617 	if (!error)
4618 		error = VTOR4(vp)->r_error;
4619 	return (error);
4620 }
4621 
4622 /*
4623  * Weirdness: if the file was removed or the target of a rename
4624  * operation while it was open, it got renamed instead.  Here we
4625  * remove the renamed file.
4626  */
4627 /* ARGSUSED */
4628 void
4629 nfs4_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4630 {
4631 	rnode4_t *rp;
4632 
4633 	ASSERT(vp != DNLC_NO_VNODE);
4634 
4635 	rp = VTOR4(vp);
4636 
4637 	if (IS_SHADOW(vp, rp)) {
4638 		sv_inactive(vp);
4639 		return;
4640 	}
4641 
4642 	/*
4643 	 * If this is coming from the wrong zone, we let someone in the right
4644 	 * zone take care of it asynchronously.  We can get here due to
4645 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4646 	 * potentially turn into an expensive no-op if, for instance, v_count
4647 	 * gets incremented in the meantime, but it's still correct.
4648 	 */
4649 	if (nfs_zone() != VTOMI4(vp)->mi_zone) {
4650 		nfs4_async_inactive(vp, cr);
4651 		return;
4652 	}
4653 
4654 	/*
4655 	 * Some of the cleanup steps might require over-the-wire
4656 	 * operations.  Since VOP_INACTIVE can get called as a result of
4657 	 * other over-the-wire operations (e.g., an attribute cache update
4658 	 * can lead to a DNLC purge), doing those steps now would lead to a
4659 	 * nested call to the recovery framework, which can deadlock.  So
4660 	 * do any over-the-wire cleanups asynchronously, in a separate
4661 	 * thread.
4662 	 */
4663 
4664 	mutex_enter(&rp->r_os_lock);
4665 	mutex_enter(&rp->r_statelock);
4666 	mutex_enter(&rp->r_statev4_lock);
4667 
4668 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4669 		mutex_exit(&rp->r_statev4_lock);
4670 		mutex_exit(&rp->r_statelock);
4671 		mutex_exit(&rp->r_os_lock);
4672 		nfs4_async_inactive(vp, cr);
4673 		return;
4674 	}
4675 
4676 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4677 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4678 		mutex_exit(&rp->r_statev4_lock);
4679 		mutex_exit(&rp->r_statelock);
4680 		mutex_exit(&rp->r_os_lock);
4681 		nfs4_async_inactive(vp, cr);
4682 		return;
4683 	}
4684 
4685 	if (rp->r_unldvp != NULL) {
4686 		mutex_exit(&rp->r_statev4_lock);
4687 		mutex_exit(&rp->r_statelock);
4688 		mutex_exit(&rp->r_os_lock);
4689 		nfs4_async_inactive(vp, cr);
4690 		return;
4691 	}
4692 	mutex_exit(&rp->r_statev4_lock);
4693 	mutex_exit(&rp->r_statelock);
4694 	mutex_exit(&rp->r_os_lock);
4695 
4696 	rp4_addfree(rp, cr);
4697 }
4698 
4699 /*
4700  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4701  * various bits of state.  The caller must not refer to vp after this call.
4702  */
4703 
4704 void
4705 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4706 {
4707 	rnode4_t *rp = VTOR4(vp);
4708 	nfs4_recov_state_t recov_state;
4709 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4710 	vnode_t *unldvp;
4711 	char *unlname;
4712 	cred_t *unlcred;
4713 	COMPOUND4args_clnt args;
4714 	COMPOUND4res_clnt res, *resp;
4715 	nfs_argop4 argop[2];
4716 	int doqueue;
4717 #ifdef DEBUG
4718 	char *name;
4719 #endif
4720 
4721 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
4722 	ASSERT(!IS_SHADOW(vp, rp));
4723 
4724 #ifdef DEBUG
4725 	name = fn_name(VTOSV(vp)->sv_name);
4726 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4727 	    "release vnode %s", name));
4728 	kmem_free(name, MAXNAMELEN);
4729 #endif
4730 
4731 	if (vp->v_type == VREG) {
4732 		bool_t recov_failed = FALSE;
4733 
4734 		e.error = nfs4close_all(vp, cr);
4735 		if (e.error) {
4736 			/* Check to see if recovery failed */
4737 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4738 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4739 				recov_failed = TRUE;
4740 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4741 			if (!recov_failed) {
4742 				mutex_enter(&rp->r_statelock);
4743 				if (rp->r_flags & R4RECOVERR)
4744 					recov_failed = TRUE;
4745 				mutex_exit(&rp->r_statelock);
4746 			}
4747 			if (recov_failed) {
4748 				NFS4_DEBUG(nfs4_client_recov_debug,
4749 				    (CE_NOTE, "nfs4_inactive_otw: "
4750 				    "close failed (recovery failure)"));
4751 			}
4752 		}
4753 	}
4754 
4755 redo:
4756 	if (rp->r_unldvp == NULL) {
4757 		rp4_addfree(rp, cr);
4758 		return;
4759 	}
4760 
4761 	/*
4762 	 * Save the vnode pointer for the directory where the
4763 	 * unlinked-open file got renamed, then set it to NULL
4764 	 * to prevent another thread from getting here before
4765 	 * we're done with the remove.  While we have the
4766 	 * statelock, make local copies of the pertinent rnode
4767 	 * fields.  If we weren't to do this in an atomic way, the
4768 	 * the unl* fields could become inconsistent with respect
4769 	 * to each other due to a race condition between this
4770 	 * code and nfs_remove().  See bug report 1034328.
4771 	 */
4772 	mutex_enter(&rp->r_statelock);
4773 	if (rp->r_unldvp == NULL) {
4774 		mutex_exit(&rp->r_statelock);
4775 		rp4_addfree(rp, cr);
4776 		return;
4777 	}
4778 
4779 	unldvp = rp->r_unldvp;
4780 	rp->r_unldvp = NULL;
4781 	unlname = rp->r_unlname;
4782 	rp->r_unlname = NULL;
4783 	unlcred = rp->r_unlcred;
4784 	rp->r_unlcred = NULL;
4785 	mutex_exit(&rp->r_statelock);
4786 
4787 	/*
4788 	 * If there are any dirty pages left, then flush
4789 	 * them.  This is unfortunate because they just
4790 	 * may get thrown away during the remove operation,
4791 	 * but we have to do this for correctness.
4792 	 */
4793 	if (nfs4_has_pages(vp) &&
4794 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4795 		ASSERT(vp->v_type != VCHR);
4796 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, NULL);
4797 		if (e.error) {
4798 			mutex_enter(&rp->r_statelock);
4799 			if (!rp->r_error)
4800 				rp->r_error = e.error;
4801 			mutex_exit(&rp->r_statelock);
4802 		}
4803 	}
4804 
4805 	recov_state.rs_flags = 0;
4806 	recov_state.rs_num_retry_despite_err = 0;
4807 recov_retry_remove:
4808 	/*
4809 	 * Do the remove operation on the renamed file
4810 	 */
4811 	args.ctag = TAG_INACTIVE;
4812 
4813 	/*
4814 	 * Remove ops: putfh dir; remove
4815 	 */
4816 	args.array_len = 2;
4817 	args.array = argop;
4818 
4819 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4820 	if (e.error) {
4821 		kmem_free(unlname, MAXNAMELEN);
4822 		crfree(unlcred);
4823 		VN_RELE(unldvp);
4824 		/*
4825 		 * Try again; this time around r_unldvp will be NULL, so we'll
4826 		 * just call rp4_addfree() and return.
4827 		 */
4828 		goto redo;
4829 	}
4830 
4831 	/* putfh directory */
4832 	argop[0].argop = OP_CPUTFH;
4833 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4834 
4835 	/* remove */
4836 	argop[1].argop = OP_CREMOVE;
4837 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4838 
4839 	doqueue = 1;
4840 	resp = &res;
4841 
4842 #if 0 /* notyet */
4843 	/*
4844 	 * Can't do this yet.  We may be being called from
4845 	 * dnlc_purge_XXX while that routine is holding a
4846 	 * mutex lock to the nc_rele list.  The calls to
4847 	 * nfs3_cache_wcc_data may result in calls to
4848 	 * dnlc_purge_XXX.  This will result in a deadlock.
4849 	 */
4850 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4851 	if (e.error) {
4852 		PURGE_ATTRCACHE4(unldvp);
4853 		resp = NULL;
4854 	} else if (res.status) {
4855 		e.error = geterrno4(res.status);
4856 		PURGE_ATTRCACHE4(unldvp);
4857 		/*
4858 		 * This code is inactive right now
4859 		 * but if made active there should
4860 		 * be a nfs4_end_op() call before
4861 		 * nfs4_purge_stale_fh to avoid start_op()
4862 		 * deadlock. See BugId: 4948726
4863 		 */
4864 		nfs4_purge_stale_fh(error, unldvp, cr);
4865 	} else {
4866 		nfs_resop4 *resop;
4867 		REMOVE4res *rm_res;
4868 
4869 		resop = &res.array[1];
4870 		rm_res = &resop->nfs_resop4_u.opremove;
4871 		/*
4872 		 * Update directory cache attribute,
4873 		 * readdir and dnlc caches.
4874 		 */
4875 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4876 	}
4877 #else
4878 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4879 
4880 	PURGE_ATTRCACHE4(unldvp);
4881 #endif
4882 
4883 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4884 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4885 		    NULL, NULL, OP_REMOVE, NULL) == FALSE) {
4886 			if (!e.error)
4887 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4888 				    (caddr_t)&res);
4889 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4890 			    &recov_state, TRUE);
4891 			goto recov_retry_remove;
4892 		}
4893 	}
4894 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4895 
4896 	/*
4897 	 * Release stuff held for the remove
4898 	 */
4899 	VN_RELE(unldvp);
4900 	if (!e.error && resp)
4901 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4902 
4903 	kmem_free(unlname, MAXNAMELEN);
4904 	crfree(unlcred);
4905 	goto redo;
4906 }
4907 
4908 /*
4909  * Remote file system operations having to do with directory manipulation.
4910  */
4911 /* ARGSUSED3 */
4912 int
4913 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4914     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
4915     int *direntflags, pathname_t *realpnp)
4916 {
4917 	int error;
4918 	vnode_t *vp, *avp = NULL;
4919 	rnode4_t *drp;
4920 
4921 	*vpp = NULL;
4922 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4923 		return (EPERM);
4924 	/*
4925 	 * if LOOKUP_XATTR, must replace dvp (object) with
4926 	 * object's attrdir before continuing with lookup
4927 	 */
4928 	if (flags & LOOKUP_XATTR) {
4929 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4930 		if (error)
4931 			return (error);
4932 
4933 		dvp = avp;
4934 
4935 		/*
4936 		 * If lookup is for "", just return dvp now.  The attrdir
4937 		 * has already been activated (from nfs4lookup_xattr), and
4938 		 * the caller will RELE the original dvp -- not
4939 		 * the attrdir.  So, set vpp and return.
4940 		 * Currently, when the LOOKUP_XATTR flag is
4941 		 * passed to VOP_LOOKUP, the name is always empty, and
4942 		 * shortcircuiting here avoids 3 unneeded lock/unlock
4943 		 * pairs.
4944 		 *
4945 		 * If a non-empty name was provided, then it is the
4946 		 * attribute name, and it will be looked up below.
4947 		 */
4948 		if (*nm == '\0') {
4949 			*vpp = dvp;
4950 			return (0);
4951 		}
4952 
4953 		/*
4954 		 * The vfs layer never sends a name when asking for the
4955 		 * attrdir, so we should never get here (unless of course
4956 		 * name is passed at some time in future -- at which time
4957 		 * we'll blow up here).
4958 		 */
4959 		ASSERT(0);
4960 	}
4961 
4962 	drp = VTOR4(dvp);
4963 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4964 		return (EINTR);
4965 
4966 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
4967 	nfs_rw_exit(&drp->r_rwlock);
4968 
4969 	/*
4970 	 * If vnode is a device, create special vnode.
4971 	 */
4972 	if (!error && ISVDEV((*vpp)->v_type)) {
4973 		vp = *vpp;
4974 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
4975 		VN_RELE(vp);
4976 	}
4977 
4978 	return (error);
4979 }
4980 
4981 /* ARGSUSED */
4982 static int
4983 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
4984 {
4985 	int error;
4986 	rnode4_t *drp;
4987 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
4988 	mntinfo4_t *mi;
4989 
4990 	mi = VTOMI4(dvp);
4991 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR) &&
4992 	    !vfs_has_feature(mi->mi_vfsp, VFSFT_SYSATTR_VIEWS))
4993 		return (EINVAL);
4994 
4995 	drp = VTOR4(dvp);
4996 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4997 		return (EINTR);
4998 
4999 	mutex_enter(&drp->r_statelock);
5000 	/*
5001 	 * If the server doesn't support xattrs just return EINVAL
5002 	 */
5003 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
5004 		mutex_exit(&drp->r_statelock);
5005 		nfs_rw_exit(&drp->r_rwlock);
5006 		return (EINVAL);
5007 	}
5008 
5009 	/*
5010 	 * If there is a cached xattr directory entry,
5011 	 * use it as long as the attributes are valid. If the
5012 	 * attributes are not valid, take the simple approach and
5013 	 * free the cached value and re-fetch a new value.
5014 	 *
5015 	 * We don't negative entry cache for now, if we did we
5016 	 * would need to check if the file has changed on every
5017 	 * lookup. But xattrs don't exist very often and failing
5018 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
5019 	 * so do an openattr over the wire for now.
5020 	 */
5021 	if (drp->r_xattr_dir != NULL) {
5022 		if (ATTRCACHE4_VALID(dvp)) {
5023 			VN_HOLD(drp->r_xattr_dir);
5024 			*vpp = drp->r_xattr_dir;
5025 			mutex_exit(&drp->r_statelock);
5026 			nfs_rw_exit(&drp->r_rwlock);
5027 			return (0);
5028 		}
5029 		VN_RELE(drp->r_xattr_dir);
5030 		drp->r_xattr_dir = NULL;
5031 	}
5032 	mutex_exit(&drp->r_statelock);
5033 
5034 	error = nfs4openattr(dvp, vpp, cflag, cr);
5035 
5036 	nfs_rw_exit(&drp->r_rwlock);
5037 
5038 	return (error);
5039 }
5040 
5041 static int
5042 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
5043 {
5044 	int error;
5045 	rnode4_t *drp;
5046 
5047 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5048 
5049 	/*
5050 	 * If lookup is for "", just return dvp.  Don't need
5051 	 * to send it over the wire, look it up in the dnlc,
5052 	 * or perform any access checks.
5053 	 */
5054 	if (*nm == '\0') {
5055 		VN_HOLD(dvp);
5056 		*vpp = dvp;
5057 		return (0);
5058 	}
5059 
5060 	/*
5061 	 * Can't do lookups in non-directories.
5062 	 */
5063 	if (dvp->v_type != VDIR)
5064 		return (ENOTDIR);
5065 
5066 	/*
5067 	 * If lookup is for ".", just return dvp.  Don't need
5068 	 * to send it over the wire or look it up in the dnlc,
5069 	 * just need to check access.
5070 	 */
5071 	if (nm[0] == '.' && nm[1] == '\0') {
5072 		error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5073 		if (error)
5074 			return (error);
5075 		VN_HOLD(dvp);
5076 		*vpp = dvp;
5077 		return (0);
5078 	}
5079 
5080 	drp = VTOR4(dvp);
5081 	if (!(drp->r_flags & R4LOOKUP)) {
5082 		mutex_enter(&drp->r_statelock);
5083 		drp->r_flags |= R4LOOKUP;
5084 		mutex_exit(&drp->r_statelock);
5085 	}
5086 
5087 	*vpp = NULL;
5088 	/*
5089 	 * Lookup this name in the DNLC.  If there is no entry
5090 	 * lookup over the wire.
5091 	 */
5092 	if (!skipdnlc)
5093 		*vpp = dnlc_lookup(dvp, nm);
5094 	if (*vpp == NULL) {
5095 		/*
5096 		 * We need to go over the wire to lookup the name.
5097 		 */
5098 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
5099 	}
5100 
5101 	/*
5102 	 * We hit on the dnlc
5103 	 */
5104 	if (*vpp != DNLC_NO_VNODE ||
5105 	    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
5106 		/*
5107 		 * But our attrs may not be valid.
5108 		 */
5109 		if (ATTRCACHE4_VALID(dvp)) {
5110 			error = nfs4_waitfor_purge_complete(dvp);
5111 			if (error) {
5112 				VN_RELE(*vpp);
5113 				*vpp = NULL;
5114 				return (error);
5115 			}
5116 
5117 			/*
5118 			 * If after the purge completes, check to make sure
5119 			 * our attrs are still valid.
5120 			 */
5121 			if (ATTRCACHE4_VALID(dvp)) {
5122 				/*
5123 				 * If we waited for a purge we may have
5124 				 * lost our vnode so look it up again.
5125 				 */
5126 				VN_RELE(*vpp);
5127 				*vpp = dnlc_lookup(dvp, nm);
5128 				if (*vpp == NULL)
5129 					return (nfs4lookupnew_otw(dvp,
5130 					    nm, vpp, cr));
5131 
5132 				/*
5133 				 * The access cache should almost always hit
5134 				 */
5135 				error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5136 
5137 				if (error) {
5138 					VN_RELE(*vpp);
5139 					*vpp = NULL;
5140 					return (error);
5141 				}
5142 				if (*vpp == DNLC_NO_VNODE) {
5143 					VN_RELE(*vpp);
5144 					*vpp = NULL;
5145 					return (ENOENT);
5146 				}
5147 				return (0);
5148 			}
5149 		}
5150 	}
5151 
5152 	ASSERT(*vpp != NULL);
5153 
5154 	/*
5155 	 * We may have gotten here we have one of the following cases:
5156 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5157 	 *		need to validate them.
5158 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5159 	 *		must validate.
5160 	 *
5161 	 * Go to the server and check if the directory has changed, if
5162 	 * it hasn't we are done and can use the dnlc entry.
5163 	 */
5164 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5165 }
5166 
5167 /*
5168  * Go to the server and check if the directory has changed, if
5169  * it hasn't we are done and can use the dnlc entry.  If it
5170  * has changed we get a new copy of its attributes and check
5171  * the access for VEXEC, then relookup the filename and
5172  * get its filehandle and attributes.
5173  *
5174  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5175  *	if the NVERIFY failed we must
5176  *		purge the caches
5177  *		cache new attributes (will set r_time_attr_inval)
5178  *		cache new access
5179  *		recheck VEXEC access
5180  *		add name to dnlc, possibly negative
5181  *		if LOOKUP succeeded
5182  *			cache new attributes
5183  *	else
5184  *		set a new r_time_attr_inval for dvp
5185  *		check to make sure we have access
5186  *
5187  * The vpp returned is the vnode passed in if the directory is valid,
5188  * a new vnode if successful lookup, or NULL on error.
5189  */
5190 static int
5191 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5192 {
5193 	COMPOUND4args_clnt args;
5194 	COMPOUND4res_clnt res;
5195 	fattr4 *ver_fattr;
5196 	fattr4_change dchange;
5197 	int32_t *ptr;
5198 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5199 	nfs_argop4 *argop;
5200 	int doqueue;
5201 	mntinfo4_t *mi;
5202 	nfs4_recov_state_t recov_state;
5203 	hrtime_t t;
5204 	int isdotdot;
5205 	vnode_t *nvp;
5206 	nfs_fh4 *fhp;
5207 	nfs4_sharedfh_t *sfhp;
5208 	nfs4_access_type_t cacc;
5209 	rnode4_t *nrp;
5210 	rnode4_t *drp = VTOR4(dvp);
5211 	nfs4_ga_res_t *garp = NULL;
5212 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5213 
5214 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5215 	ASSERT(nm != NULL);
5216 	ASSERT(nm[0] != '\0');
5217 	ASSERT(dvp->v_type == VDIR);
5218 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5219 	ASSERT(*vpp != NULL);
5220 
5221 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5222 		isdotdot = 1;
5223 		args.ctag = TAG_LOOKUP_VPARENT;
5224 	} else {
5225 		/*
5226 		 * If dvp were a stub, it should have triggered and caused
5227 		 * a mount for us to get this far.
5228 		 */
5229 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5230 
5231 		isdotdot = 0;
5232 		args.ctag = TAG_LOOKUP_VALID;
5233 	}
5234 
5235 	mi = VTOMI4(dvp);
5236 	recov_state.rs_flags = 0;
5237 	recov_state.rs_num_retry_despite_err = 0;
5238 
5239 	nvp = NULL;
5240 
5241 	/* Save the original mount point security information */
5242 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5243 
5244 recov_retry:
5245 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5246 	    &recov_state, NULL);
5247 	if (e.error) {
5248 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5249 		VN_RELE(*vpp);
5250 		*vpp = NULL;
5251 		return (e.error);
5252 	}
5253 
5254 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5255 
5256 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5257 	args.array_len = 7;
5258 	args.array = argop;
5259 
5260 	/* 0. putfh file */
5261 	argop[0].argop = OP_CPUTFH;
5262 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5263 
5264 	/* 1. nverify the change info */
5265 	argop[1].argop = OP_NVERIFY;
5266 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5267 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5268 	ver_fattr->attrlist4 = (char *)&dchange;
5269 	ptr = (int32_t *)&dchange;
5270 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5271 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5272 
5273 	/* 2. getattr directory */
5274 	argop[2].argop = OP_GETATTR;
5275 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5276 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5277 
5278 	/* 3. access directory */
5279 	argop[3].argop = OP_ACCESS;
5280 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5281 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5282 
5283 	/* 4. lookup name */
5284 	if (isdotdot) {
5285 		argop[4].argop = OP_LOOKUPP;
5286 	} else {
5287 		argop[4].argop = OP_CLOOKUP;
5288 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5289 	}
5290 
5291 	/* 5. resulting file handle */
5292 	argop[5].argop = OP_GETFH;
5293 
5294 	/* 6. resulting file attributes */
5295 	argop[6].argop = OP_GETATTR;
5296 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5297 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5298 
5299 	doqueue = 1;
5300 	t = gethrtime();
5301 
5302 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5303 
5304 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5305 		/*
5306 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5307 		 * from this thread, do not go thru the recovery thread since
5308 		 * we need the nm information.
5309 		 *
5310 		 * Not doing dotdot case because there is no specification
5311 		 * for (PUTFH, SECINFO "..") yet.
5312 		 */
5313 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5314 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5315 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5316 				    &recov_state, FALSE);
5317 			else
5318 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5319 				    &recov_state, TRUE);
5320 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5321 			kmem_free(argop, argoplist_size);
5322 			if (!e.error)
5323 				goto recov_retry;
5324 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5325 			VN_RELE(*vpp);
5326 			*vpp = NULL;
5327 			return (e.error);
5328 		}
5329 
5330 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5331 		    OP_LOOKUP, NULL) == FALSE) {
5332 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5333 			    &recov_state, TRUE);
5334 
5335 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5336 			kmem_free(argop, argoplist_size);
5337 			goto recov_retry;
5338 		}
5339 	}
5340 
5341 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5342 
5343 	if (e.error || res.array_len == 0) {
5344 		/*
5345 		 * If e.error isn't set, then reply has no ops (or we couldn't
5346 		 * be here).  The only legal way to reply without an op array
5347 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5348 		 * be in the reply for all other status values.
5349 		 *
5350 		 * For valid replies without an ops array, return ENOTSUP
5351 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5352 		 * return EIO -- don't trust status.
5353 		 */
5354 		if (e.error == 0)
5355 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5356 			    ENOTSUP : EIO;
5357 		VN_RELE(*vpp);
5358 		*vpp = NULL;
5359 		kmem_free(argop, argoplist_size);
5360 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5361 		return (e.error);
5362 	}
5363 
5364 	if (res.status != NFS4ERR_SAME) {
5365 		e.error = geterrno4(res.status);
5366 
5367 		/*
5368 		 * The NVERIFY "failed" so the directory has changed
5369 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5370 		 * cleanly.
5371 		 */
5372 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5373 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5374 			nfs4_purge_stale_fh(e.error, dvp, cr);
5375 			VN_RELE(*vpp);
5376 			*vpp = NULL;
5377 			goto exit;
5378 		}
5379 
5380 		/*
5381 		 * We know the NVERIFY "failed" so we must:
5382 		 *	purge the caches (access and indirectly dnlc if needed)
5383 		 */
5384 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5385 
5386 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5387 			nfs4_purge_stale_fh(e.error, dvp, cr);
5388 			VN_RELE(*vpp);
5389 			*vpp = NULL;
5390 			goto exit;
5391 		}
5392 
5393 		/*
5394 		 * Install new cached attributes for the directory
5395 		 */
5396 		nfs4_attr_cache(dvp,
5397 		    &res.array[2].nfs_resop4_u.opgetattr.ga_res,
5398 		    t, cr, FALSE, NULL);
5399 
5400 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5401 			nfs4_purge_stale_fh(e.error, dvp, cr);
5402 			VN_RELE(*vpp);
5403 			*vpp = NULL;
5404 			e.error = geterrno4(res.status);
5405 			goto exit;
5406 		}
5407 
5408 		/*
5409 		 * Now we know the directory is valid,
5410 		 * cache new directory access
5411 		 */
5412 		nfs4_access_cache(drp,
5413 		    args.array[3].nfs_argop4_u.opaccess.access,
5414 		    res.array[3].nfs_resop4_u.opaccess.access, cr);
5415 
5416 		/*
5417 		 * recheck VEXEC access
5418 		 */
5419 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5420 		if (cacc != NFS4_ACCESS_ALLOWED) {
5421 			/*
5422 			 * Directory permissions might have been revoked
5423 			 */
5424 			if (cacc == NFS4_ACCESS_DENIED) {
5425 				e.error = EACCES;
5426 				VN_RELE(*vpp);
5427 				*vpp = NULL;
5428 				goto exit;
5429 			}
5430 
5431 			/*
5432 			 * Somehow we must not have asked for enough
5433 			 * so try a singleton ACCESS, should never happen.
5434 			 */
5435 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5436 			if (e.error) {
5437 				VN_RELE(*vpp);
5438 				*vpp = NULL;
5439 				goto exit;
5440 			}
5441 		}
5442 
5443 		e.error = geterrno4(res.status);
5444 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5445 			/*
5446 			 * The lookup failed, probably no entry
5447 			 */
5448 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5449 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5450 			} else {
5451 				/*
5452 				 * Might be some other error, so remove
5453 				 * the dnlc entry to make sure we start all
5454 				 * over again, next time.
5455 				 */
5456 				dnlc_remove(dvp, nm);
5457 			}
5458 			VN_RELE(*vpp);
5459 			*vpp = NULL;
5460 			goto exit;
5461 		}
5462 
5463 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5464 			/*
5465 			 * The file exists but we can't get its fh for
5466 			 * some unknown reason.  Remove it from the dnlc
5467 			 * and error out to be safe.
5468 			 */
5469 			dnlc_remove(dvp, nm);
5470 			VN_RELE(*vpp);
5471 			*vpp = NULL;
5472 			goto exit;
5473 		}
5474 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5475 		if (fhp->nfs_fh4_len == 0) {
5476 			/*
5477 			 * The file exists but a bogus fh
5478 			 * some unknown reason.  Remove it from the dnlc
5479 			 * and error out to be safe.
5480 			 */
5481 			e.error = ENOENT;
5482 			dnlc_remove(dvp, nm);
5483 			VN_RELE(*vpp);
5484 			*vpp = NULL;
5485 			goto exit;
5486 		}
5487 		sfhp = sfh4_get(fhp, mi);
5488 
5489 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5490 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5491 
5492 		/*
5493 		 * Make the new rnode
5494 		 */
5495 		if (isdotdot) {
5496 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5497 			if (e.error) {
5498 				sfh4_rele(&sfhp);
5499 				VN_RELE(*vpp);
5500 				*vpp = NULL;
5501 				goto exit;
5502 			}
5503 			/*
5504 			 * XXX if nfs4_make_dotdot uses an existing rnode
5505 			 * XXX it doesn't update the attributes.
5506 			 * XXX for now just save them again to save an OTW
5507 			 */
5508 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5509 		} else {
5510 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5511 			    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
5512 			/*
5513 			 * If v_type == VNON, then garp was NULL because
5514 			 * the last op in the compound failed and makenfs4node
5515 			 * could not find the vnode for sfhp. It created
5516 			 * a new vnode, so we have nothing to purge here.
5517 			 */
5518 			if (nvp->v_type == VNON) {
5519 				vattr_t vattr;
5520 
5521 				vattr.va_mask = AT_TYPE;
5522 				/*
5523 				 * N.B. We've already called nfs4_end_fop above.
5524 				 */
5525 				e.error = nfs4getattr(nvp, &vattr, cr);
5526 				if (e.error) {
5527 					sfh4_rele(&sfhp);
5528 					VN_RELE(*vpp);
5529 					*vpp = NULL;
5530 					VN_RELE(nvp);
5531 					goto exit;
5532 				}
5533 				nvp->v_type = vattr.va_type;
5534 			}
5535 		}
5536 		sfh4_rele(&sfhp);
5537 
5538 		nrp = VTOR4(nvp);
5539 		mutex_enter(&nrp->r_statev4_lock);
5540 		if (!nrp->created_v4) {
5541 			mutex_exit(&nrp->r_statev4_lock);
5542 			dnlc_update(dvp, nm, nvp);
5543 		} else
5544 			mutex_exit(&nrp->r_statev4_lock);
5545 
5546 		VN_RELE(*vpp);
5547 		*vpp = nvp;
5548 	} else {
5549 		hrtime_t now;
5550 		hrtime_t delta = 0;
5551 
5552 		e.error = 0;
5553 
5554 		/*
5555 		 * Because the NVERIFY "succeeded" we know that the
5556 		 * directory attributes are still valid
5557 		 * so update r_time_attr_inval
5558 		 */
5559 		now = gethrtime();
5560 		mutex_enter(&drp->r_statelock);
5561 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5562 			delta = now - drp->r_time_attr_saved;
5563 			if (delta < mi->mi_acdirmin)
5564 				delta = mi->mi_acdirmin;
5565 			else if (delta > mi->mi_acdirmax)
5566 				delta = mi->mi_acdirmax;
5567 		}
5568 		drp->r_time_attr_inval = now + delta;
5569 		mutex_exit(&drp->r_statelock);
5570 		dnlc_update(dvp, nm, *vpp);
5571 
5572 		/*
5573 		 * Even though we have a valid directory attr cache
5574 		 * and dnlc entry, we may not have access.
5575 		 * This should almost always hit the cache.
5576 		 */
5577 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5578 		if (e.error) {
5579 			VN_RELE(*vpp);
5580 			*vpp = NULL;
5581 		}
5582 
5583 		if (*vpp == DNLC_NO_VNODE) {
5584 			VN_RELE(*vpp);
5585 			*vpp = NULL;
5586 			e.error = ENOENT;
5587 		}
5588 	}
5589 
5590 exit:
5591 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5592 	kmem_free(argop, argoplist_size);
5593 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5594 	return (e.error);
5595 }
5596 
5597 /*
5598  * We need to go over the wire to lookup the name, but
5599  * while we are there verify the directory has not
5600  * changed but if it has, get new attributes and check access
5601  *
5602  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5603  *					NVERIFY GETATTR ACCESS
5604  *
5605  * With the results:
5606  *	if the NVERIFY failed we must purge the caches, add new attributes,
5607  *		and cache new access.
5608  *	set a new r_time_attr_inval
5609  *	add name to dnlc, possibly negative
5610  *	if LOOKUP succeeded
5611  *		cache new attributes
5612  */
5613 static int
5614 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5615 {
5616 	COMPOUND4args_clnt args;
5617 	COMPOUND4res_clnt res;
5618 	fattr4 *ver_fattr;
5619 	fattr4_change dchange;
5620 	int32_t *ptr;
5621 	nfs4_ga_res_t *garp = NULL;
5622 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5623 	nfs_argop4 *argop;
5624 	int doqueue;
5625 	mntinfo4_t *mi;
5626 	nfs4_recov_state_t recov_state;
5627 	hrtime_t t;
5628 	int isdotdot;
5629 	vnode_t *nvp;
5630 	nfs_fh4 *fhp;
5631 	nfs4_sharedfh_t *sfhp;
5632 	nfs4_access_type_t cacc;
5633 	rnode4_t *nrp;
5634 	rnode4_t *drp = VTOR4(dvp);
5635 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5636 
5637 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5638 	ASSERT(nm != NULL);
5639 	ASSERT(nm[0] != '\0');
5640 	ASSERT(dvp->v_type == VDIR);
5641 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5642 	ASSERT(*vpp == NULL);
5643 
5644 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5645 		isdotdot = 1;
5646 		args.ctag = TAG_LOOKUP_PARENT;
5647 	} else {
5648 		/*
5649 		 * If dvp were a stub, it should have triggered and caused
5650 		 * a mount for us to get this far.
5651 		 */
5652 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5653 
5654 		isdotdot = 0;
5655 		args.ctag = TAG_LOOKUP;
5656 	}
5657 
5658 	mi = VTOMI4(dvp);
5659 	recov_state.rs_flags = 0;
5660 	recov_state.rs_num_retry_despite_err = 0;
5661 
5662 	nvp = NULL;
5663 
5664 	/* Save the original mount point security information */
5665 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5666 
5667 recov_retry:
5668 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5669 	    &recov_state, NULL);
5670 	if (e.error) {
5671 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5672 		return (e.error);
5673 	}
5674 
5675 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5676 
5677 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5678 	args.array_len = 9;
5679 	args.array = argop;
5680 
5681 	/* 0. putfh file */
5682 	argop[0].argop = OP_CPUTFH;
5683 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5684 
5685 	/* 1. savefh for the nverify */
5686 	argop[1].argop = OP_SAVEFH;
5687 
5688 	/* 2. lookup name */
5689 	if (isdotdot) {
5690 		argop[2].argop = OP_LOOKUPP;
5691 	} else {
5692 		argop[2].argop = OP_CLOOKUP;
5693 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5694 	}
5695 
5696 	/* 3. resulting file handle */
5697 	argop[3].argop = OP_GETFH;
5698 
5699 	/* 4. resulting file attributes */
5700 	argop[4].argop = OP_GETATTR;
5701 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5702 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5703 
5704 	/* 5. restorefh back the directory for the nverify */
5705 	argop[5].argop = OP_RESTOREFH;
5706 
5707 	/* 6. nverify the change info */
5708 	argop[6].argop = OP_NVERIFY;
5709 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5710 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5711 	ver_fattr->attrlist4 = (char *)&dchange;
5712 	ptr = (int32_t *)&dchange;
5713 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5714 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5715 
5716 	/* 7. getattr directory */
5717 	argop[7].argop = OP_GETATTR;
5718 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5719 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5720 
5721 	/* 8. access directory */
5722 	argop[8].argop = OP_ACCESS;
5723 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5724 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5725 
5726 	doqueue = 1;
5727 	t = gethrtime();
5728 
5729 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5730 
5731 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5732 		/*
5733 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5734 		 * from this thread, do not go thru the recovery thread since
5735 		 * we need the nm information.
5736 		 *
5737 		 * Not doing dotdot case because there is no specification
5738 		 * for (PUTFH, SECINFO "..") yet.
5739 		 */
5740 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5741 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5742 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5743 				    &recov_state, FALSE);
5744 			else
5745 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5746 				    &recov_state, TRUE);
5747 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5748 			kmem_free(argop, argoplist_size);
5749 			if (!e.error)
5750 				goto recov_retry;
5751 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5752 			return (e.error);
5753 		}
5754 
5755 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5756 		    OP_LOOKUP, NULL) == FALSE) {
5757 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5758 			    &recov_state, TRUE);
5759 
5760 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5761 			kmem_free(argop, argoplist_size);
5762 			goto recov_retry;
5763 		}
5764 	}
5765 
5766 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5767 
5768 	if (e.error || res.array_len == 0) {
5769 		/*
5770 		 * If e.error isn't set, then reply has no ops (or we couldn't
5771 		 * be here).  The only legal way to reply without an op array
5772 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5773 		 * be in the reply for all other status values.
5774 		 *
5775 		 * For valid replies without an ops array, return ENOTSUP
5776 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5777 		 * return EIO -- don't trust status.
5778 		 */
5779 		if (e.error == 0)
5780 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5781 			    ENOTSUP : EIO;
5782 
5783 		kmem_free(argop, argoplist_size);
5784 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5785 		return (e.error);
5786 	}
5787 
5788 	e.error = geterrno4(res.status);
5789 
5790 	/*
5791 	 * The PUTFH and SAVEFH may have failed.
5792 	 */
5793 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5794 	    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5795 		nfs4_purge_stale_fh(e.error, dvp, cr);
5796 		goto exit;
5797 	}
5798 
5799 	/*
5800 	 * Check if the file exists, if it does delay entering
5801 	 * into the dnlc until after we update the directory
5802 	 * attributes so we don't cause it to get purged immediately.
5803 	 */
5804 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5805 		/*
5806 		 * The lookup failed, probably no entry
5807 		 */
5808 		if (e.error == ENOENT && nfs4_lookup_neg_cache)
5809 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5810 		goto exit;
5811 	}
5812 
5813 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5814 		/*
5815 		 * The file exists but we can't get its fh for
5816 		 * some unknown reason. Error out to be safe.
5817 		 */
5818 		goto exit;
5819 	}
5820 
5821 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5822 	if (fhp->nfs_fh4_len == 0) {
5823 		/*
5824 		 * The file exists but a bogus fh
5825 		 * some unknown reason.  Error out to be safe.
5826 		 */
5827 		e.error = EIO;
5828 		goto exit;
5829 	}
5830 	sfhp = sfh4_get(fhp, mi);
5831 
5832 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5833 		sfh4_rele(&sfhp);
5834 		goto exit;
5835 	}
5836 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5837 
5838 	/*
5839 	 * The RESTOREFH may have failed
5840 	 */
5841 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5842 		sfh4_rele(&sfhp);
5843 		e.error = EIO;
5844 		goto exit;
5845 	}
5846 
5847 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5848 		/*
5849 		 * First make sure the NVERIFY failed as we expected,
5850 		 * if it didn't then be conservative and error out
5851 		 * as we can't trust the directory.
5852 		 */
5853 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5854 			sfh4_rele(&sfhp);
5855 			e.error = EIO;
5856 			goto exit;
5857 		}
5858 
5859 		/*
5860 		 * We know the NVERIFY "failed" so the directory has changed,
5861 		 * so we must:
5862 		 *	purge the caches (access and indirectly dnlc if needed)
5863 		 */
5864 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5865 
5866 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5867 			sfh4_rele(&sfhp);
5868 			goto exit;
5869 		}
5870 		nfs4_attr_cache(dvp,
5871 		    &res.array[7].nfs_resop4_u.opgetattr.ga_res,
5872 		    t, cr, FALSE, NULL);
5873 
5874 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5875 			nfs4_purge_stale_fh(e.error, dvp, cr);
5876 			sfh4_rele(&sfhp);
5877 			e.error = geterrno4(res.status);
5878 			goto exit;
5879 		}
5880 
5881 		/*
5882 		 * Now we know the directory is valid,
5883 		 * cache new directory access
5884 		 */
5885 		nfs4_access_cache(drp,
5886 		    args.array[8].nfs_argop4_u.opaccess.access,
5887 		    res.array[8].nfs_resop4_u.opaccess.access, cr);
5888 
5889 		/*
5890 		 * recheck VEXEC access
5891 		 */
5892 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5893 		if (cacc != NFS4_ACCESS_ALLOWED) {
5894 			/*
5895 			 * Directory permissions might have been revoked
5896 			 */
5897 			if (cacc == NFS4_ACCESS_DENIED) {
5898 				sfh4_rele(&sfhp);
5899 				e.error = EACCES;
5900 				goto exit;
5901 			}
5902 
5903 			/*
5904 			 * Somehow we must not have asked for enough
5905 			 * so try a singleton ACCESS should never happen
5906 			 */
5907 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5908 			if (e.error) {
5909 				sfh4_rele(&sfhp);
5910 				goto exit;
5911 			}
5912 		}
5913 
5914 		e.error = geterrno4(res.status);
5915 	} else {
5916 		hrtime_t now;
5917 		hrtime_t delta = 0;
5918 
5919 		e.error = 0;
5920 
5921 		/*
5922 		 * Because the NVERIFY "succeeded" we know that the
5923 		 * directory attributes are still valid
5924 		 * so update r_time_attr_inval
5925 		 */
5926 		now = gethrtime();
5927 		mutex_enter(&drp->r_statelock);
5928 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5929 			delta = now - drp->r_time_attr_saved;
5930 			if (delta < mi->mi_acdirmin)
5931 				delta = mi->mi_acdirmin;
5932 			else if (delta > mi->mi_acdirmax)
5933 				delta = mi->mi_acdirmax;
5934 		}
5935 		drp->r_time_attr_inval = now + delta;
5936 		mutex_exit(&drp->r_statelock);
5937 
5938 		/*
5939 		 * Even though we have a valid directory attr cache,
5940 		 * we may not have access.
5941 		 * This should almost always hit the cache.
5942 		 */
5943 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5944 		if (e.error) {
5945 			sfh4_rele(&sfhp);
5946 			goto exit;
5947 		}
5948 	}
5949 
5950 	/*
5951 	 * Now we have successfully completed the lookup, if the
5952 	 * directory has changed we now have the valid attributes.
5953 	 * We also know we have directory access.
5954 	 * Create the new rnode and insert it in the dnlc.
5955 	 */
5956 	if (isdotdot) {
5957 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5958 		if (e.error) {
5959 			sfh4_rele(&sfhp);
5960 			goto exit;
5961 		}
5962 		/*
5963 		 * XXX if nfs4_make_dotdot uses an existing rnode
5964 		 * XXX it doesn't update the attributes.
5965 		 * XXX for now just save them again to save an OTW
5966 		 */
5967 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5968 	} else {
5969 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5970 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
5971 	}
5972 	sfh4_rele(&sfhp);
5973 
5974 	nrp = VTOR4(nvp);
5975 	mutex_enter(&nrp->r_statev4_lock);
5976 	if (!nrp->created_v4) {
5977 		mutex_exit(&nrp->r_statev4_lock);
5978 		dnlc_update(dvp, nm, nvp);
5979 	} else
5980 		mutex_exit(&nrp->r_statev4_lock);
5981 
5982 	*vpp = nvp;
5983 
5984 exit:
5985 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5986 	kmem_free(argop, argoplist_size);
5987 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5988 	return (e.error);
5989 }
5990 
5991 #ifdef DEBUG
5992 void
5993 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
5994 {
5995 	uint_t i, len;
5996 	zoneid_t zoneid = getzoneid();
5997 	char *s;
5998 
5999 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
6000 	for (i = 0; i < argcnt; i++) {
6001 		nfs_argop4 *op = &argbase[i];
6002 		switch (op->argop) {
6003 		case OP_CPUTFH:
6004 		case OP_PUTFH:
6005 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
6006 			break;
6007 		case OP_PUTROOTFH:
6008 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
6009 			break;
6010 		case OP_CLOOKUP:
6011 			s = op->nfs_argop4_u.opclookup.cname;
6012 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6013 			break;
6014 		case OP_LOOKUP:
6015 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
6016 			    &len, NULL);
6017 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6018 			kmem_free(s, len);
6019 			break;
6020 		case OP_LOOKUPP:
6021 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
6022 			break;
6023 		case OP_GETFH:
6024 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
6025 			break;
6026 		case OP_GETATTR:
6027 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
6028 			break;
6029 		case OP_OPENATTR:
6030 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
6031 			break;
6032 		default:
6033 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
6034 			    op->argop);
6035 			break;
6036 		}
6037 	}
6038 }
6039 #endif
6040 
6041 /*
6042  * nfs4lookup_setup - constructs a multi-lookup compound request.
6043  *
6044  * Given the path "nm1/nm2/.../nmn", the following compound requests
6045  * may be created:
6046  *
6047  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
6048  * is faster, for now.
6049  *
6050  * l4_getattrs indicates the type of compound requested.
6051  *
6052  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
6053  *
6054  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
6055  *
6056  *   total number of ops is n + 1.
6057  *
6058  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
6059  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
6060  *      before the last component, and only get attributes
6061  *      for the last component.  Note that the second-to-last
6062  *	pathname component is XATTR_RPATH, which does NOT go
6063  *	over-the-wire as a lookup.
6064  *
6065  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
6066  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
6067  *
6068  *   and total number of ops is n + 5.
6069  *
6070  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
6071  *      attribute directory: create lookups plus an OPENATTR
6072  *	replacing the last lookup.  Note that the last pathname
6073  *	component is XATTR_RPATH, which does NOT go over-the-wire
6074  *	as a lookup.
6075  *
6076  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
6077  *		Openattr; Getfh; Getattr }
6078  *
6079  *   and total number of ops is n + 5.
6080  *
6081  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6082  *	nodes too.
6083  *
6084  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6085  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6086  *
6087  *   and total number of ops is 3*n + 1.
6088  *
6089  * All cases: returns the index in the arg array of the final LOOKUP op, or
6090  * -1 if no LOOKUPs were used.
6091  */
6092 int
6093 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6094 {
6095 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6096 	nfs_argop4 *argbase, *argop;
6097 	int arglen, argcnt;
6098 	int n = 1;	/* number of components */
6099 	int nga = 1;	/* number of Getattr's in request */
6100 	char c = '\0', *s, *p;
6101 	int lookup_idx = -1;
6102 	int argoplist_size;
6103 
6104 	/* set lookuparg response result to 0 */
6105 	lookupargp->resp->status = NFS4_OK;
6106 
6107 	/* skip leading "/" or "." e.g. ".//./" if there is */
6108 	for (; ; nm++) {
6109 		if (*nm != '/' && *nm != '.')
6110 			break;
6111 
6112 		/* ".." is counted as 1 component */
6113 		if (*nm == '.' && *(nm + 1) != '/')
6114 			break;
6115 	}
6116 
6117 	/*
6118 	 * Find n = number of components - nm must be null terminated
6119 	 * Skip "." components.
6120 	 */
6121 	if (*nm != '\0')
6122 		for (n = 1, s = nm; *s != '\0'; s++) {
6123 			if ((*s == '/') && (*(s + 1) != '/') &&
6124 			    (*(s + 1) != '\0') &&
6125 			    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6126 			    *(s + 2) == '\0')))
6127 				n++;
6128 		}
6129 	else
6130 		n = 0;
6131 
6132 	/*
6133 	 * nga is number of components that need Getfh+Getattr
6134 	 */
6135 	switch (l4_getattrs) {
6136 	case LKP4_NO_ATTRIBUTES:
6137 		nga = 0;
6138 		break;
6139 	case LKP4_ALL_ATTRIBUTES:
6140 		nga = n;
6141 		/*
6142 		 * Always have at least 1 getfh, getattr pair
6143 		 */
6144 		if (nga == 0)
6145 			nga++;
6146 		break;
6147 	case LKP4_LAST_ATTRDIR:
6148 	case LKP4_LAST_NAMED_ATTR:
6149 		nga = n+1;
6150 		break;
6151 	}
6152 
6153 	/*
6154 	 * If change to use the filehandle attr instead of getfh
6155 	 * the following line can be deleted.
6156 	 */
6157 	nga *= 2;
6158 
6159 	/*
6160 	 * calculate number of ops in request as
6161 	 * header + trailer + lookups + getattrs
6162 	 */
6163 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6164 
6165 	argoplist_size = arglen * sizeof (nfs_argop4);
6166 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6167 	lookupargp->argsp->array = argop;
6168 
6169 	argcnt = lookupargp->header_len;
6170 	argop += argcnt;
6171 
6172 	/*
6173 	 * loop and create a lookup op and possibly getattr/getfh for
6174 	 * each component. Skip "." components.
6175 	 */
6176 	for (s = nm; *s != '\0'; s = p) {
6177 		/*
6178 		 * Set up a pathname struct for each component if needed
6179 		 */
6180 		while (*s == '/')
6181 			s++;
6182 		if (*s == '\0')
6183 			break;
6184 
6185 		for (p = s; (*p != '/') && (*p != '\0'); p++)
6186 			;
6187 		c = *p;
6188 		*p = '\0';
6189 
6190 		if (s[0] == '.' && s[1] == '\0') {
6191 			*p = c;
6192 			continue;
6193 		}
6194 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6195 		    strcmp(s, XATTR_RPATH) == 0) {
6196 			/* getfh XXX may not be needed in future */
6197 			argop->argop = OP_GETFH;
6198 			argop++;
6199 			argcnt++;
6200 
6201 			/* getattr */
6202 			argop->argop = OP_GETATTR;
6203 			argop->nfs_argop4_u.opgetattr.attr_request =
6204 			    lookupargp->ga_bits;
6205 			argop->nfs_argop4_u.opgetattr.mi =
6206 			    lookupargp->mi;
6207 			argop++;
6208 			argcnt++;
6209 
6210 			/* openattr */
6211 			argop->argop = OP_OPENATTR;
6212 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6213 		    strcmp(s, XATTR_RPATH) == 0) {
6214 			/* openattr */
6215 			argop->argop = OP_OPENATTR;
6216 			argop++;
6217 			argcnt++;
6218 
6219 			/* getfh XXX may not be needed in future */
6220 			argop->argop = OP_GETFH;
6221 			argop++;
6222 			argcnt++;
6223 
6224 			/* getattr */
6225 			argop->argop = OP_GETATTR;
6226 			argop->nfs_argop4_u.opgetattr.attr_request =
6227 			    lookupargp->ga_bits;
6228 			argop->nfs_argop4_u.opgetattr.mi =
6229 			    lookupargp->mi;
6230 			argop++;
6231 			argcnt++;
6232 			*p = c;
6233 			continue;
6234 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6235 			/* lookupp */
6236 			argop->argop = OP_LOOKUPP;
6237 		} else {
6238 			/* lookup */
6239 			argop->argop = OP_LOOKUP;
6240 			(void) str_to_utf8(s,
6241 			    &argop->nfs_argop4_u.oplookup.objname);
6242 		}
6243 		lookup_idx = argcnt;
6244 		argop++;
6245 		argcnt++;
6246 
6247 		*p = c;
6248 
6249 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6250 			/* getfh XXX may not be needed in future */
6251 			argop->argop = OP_GETFH;
6252 			argop++;
6253 			argcnt++;
6254 
6255 			/* getattr */
6256 			argop->argop = OP_GETATTR;
6257 			argop->nfs_argop4_u.opgetattr.attr_request =
6258 			    lookupargp->ga_bits;
6259 			argop->nfs_argop4_u.opgetattr.mi =
6260 			    lookupargp->mi;
6261 			argop++;
6262 			argcnt++;
6263 		}
6264 	}
6265 
6266 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6267 	    ((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6268 		if (needgetfh) {
6269 			/* stick in a post-lookup getfh */
6270 			argop->argop = OP_GETFH;
6271 			argcnt++;
6272 			argop++;
6273 		}
6274 		/* post-lookup getattr */
6275 		argop->argop = OP_GETATTR;
6276 		argop->nfs_argop4_u.opgetattr.attr_request =
6277 		    lookupargp->ga_bits;
6278 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6279 		argcnt++;
6280 	}
6281 	argcnt += lookupargp->trailer_len;	/* actual op count */
6282 	lookupargp->argsp->array_len = argcnt;
6283 	lookupargp->arglen = arglen;
6284 
6285 #ifdef DEBUG
6286 	if (nfs4_client_lookup_debug)
6287 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6288 #endif
6289 
6290 	return (lookup_idx);
6291 }
6292 
6293 static int
6294 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6295 {
6296 	COMPOUND4args_clnt	args;
6297 	COMPOUND4res_clnt	res;
6298 	GETFH4res	*gf_res = NULL;
6299 	nfs_argop4	argop[4];
6300 	nfs_resop4	*resop = NULL;
6301 	nfs4_sharedfh_t *sfhp;
6302 	hrtime_t t;
6303 	nfs4_error_t	e;
6304 
6305 	rnode4_t	*drp;
6306 	int		doqueue = 1;
6307 	vnode_t		*vp;
6308 	int		needrecov = 0;
6309 	nfs4_recov_state_t recov_state;
6310 
6311 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6312 
6313 	*avp = NULL;
6314 	recov_state.rs_flags = 0;
6315 	recov_state.rs_num_retry_despite_err = 0;
6316 
6317 recov_retry:
6318 	/* COMPOUND: putfh, openattr, getfh, getattr */
6319 	args.array_len = 4;
6320 	args.array = argop;
6321 	args.ctag = TAG_OPENATTR;
6322 
6323 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6324 	if (e.error)
6325 		return (e.error);
6326 
6327 	drp = VTOR4(dvp);
6328 
6329 	/* putfh */
6330 	argop[0].argop = OP_CPUTFH;
6331 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6332 
6333 	/* openattr */
6334 	argop[1].argop = OP_OPENATTR;
6335 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6336 
6337 	/* getfh */
6338 	argop[2].argop = OP_GETFH;
6339 
6340 	/* getattr */
6341 	argop[3].argop = OP_GETATTR;
6342 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6343 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6344 
6345 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6346 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6347 	    rnode4info(drp)));
6348 
6349 	t = gethrtime();
6350 
6351 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6352 
6353 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6354 	if (needrecov) {
6355 		bool_t abort;
6356 
6357 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6358 		    "nfs4openattr: initiating recovery\n"));
6359 
6360 		abort = nfs4_start_recovery(&e,
6361 		    VTOMI4(dvp), dvp, NULL, NULL, NULL,
6362 		    OP_OPENATTR, NULL);
6363 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6364 		if (!e.error) {
6365 			e.error = geterrno4(res.status);
6366 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6367 		}
6368 		if (abort == FALSE)
6369 			goto recov_retry;
6370 		return (e.error);
6371 	}
6372 
6373 	if (e.error) {
6374 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6375 		return (e.error);
6376 	}
6377 
6378 	if (res.status) {
6379 		/*
6380 		 * If OTW errro is NOTSUPP, then it should be
6381 		 * translated to EINVAL.  All Solaris file system
6382 		 * implementations return EINVAL to the syscall layer
6383 		 * when the attrdir cannot be created due to an
6384 		 * implementation restriction or noxattr mount option.
6385 		 */
6386 		if (res.status == NFS4ERR_NOTSUPP) {
6387 			mutex_enter(&drp->r_statelock);
6388 			if (drp->r_xattr_dir)
6389 				VN_RELE(drp->r_xattr_dir);
6390 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6391 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6392 			mutex_exit(&drp->r_statelock);
6393 
6394 			e.error = EINVAL;
6395 		} else {
6396 			e.error = geterrno4(res.status);
6397 		}
6398 
6399 		if (e.error) {
6400 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6401 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6402 			    needrecov);
6403 			return (e.error);
6404 		}
6405 	}
6406 
6407 	resop = &res.array[0];  /* putfh res */
6408 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6409 
6410 	resop = &res.array[1];  /* openattr res */
6411 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6412 
6413 	resop = &res.array[2];  /* getfh res */
6414 	gf_res = &resop->nfs_resop4_u.opgetfh;
6415 	if (gf_res->object.nfs_fh4_len == 0) {
6416 		*avp = NULL;
6417 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6418 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6419 		return (ENOENT);
6420 	}
6421 
6422 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6423 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6424 	    dvp->v_vfsp, t, cr, dvp,
6425 	    fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH, sfhp));
6426 	sfh4_rele(&sfhp);
6427 
6428 	if (e.error)
6429 		PURGE_ATTRCACHE4(vp);
6430 
6431 	mutex_enter(&vp->v_lock);
6432 	vp->v_flag |= V_XATTRDIR;
6433 	mutex_exit(&vp->v_lock);
6434 
6435 	*avp = vp;
6436 
6437 	mutex_enter(&drp->r_statelock);
6438 	if (drp->r_xattr_dir)
6439 		VN_RELE(drp->r_xattr_dir);
6440 	VN_HOLD(vp);
6441 	drp->r_xattr_dir = vp;
6442 
6443 	/*
6444 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6445 	 * NULL.  xattrs could be created at any time, and we have no
6446 	 * way to update pc4_xattr_exists in the base object if/when
6447 	 * it happens.
6448 	 */
6449 	drp->r_pathconf.pc4_xattr_valid = 0;
6450 
6451 	mutex_exit(&drp->r_statelock);
6452 
6453 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6454 
6455 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6456 
6457 	return (0);
6458 }
6459 
6460 /* ARGSUSED */
6461 static int
6462 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6463 	int mode, vnode_t **vpp, cred_t *cr, int flags, caller_context_t *ct,
6464 	vsecattr_t *vsecp)
6465 {
6466 	int error;
6467 	vnode_t *vp = NULL;
6468 	rnode4_t *rp;
6469 	struct vattr vattr;
6470 	rnode4_t *drp;
6471 	vnode_t *tempvp;
6472 	enum createmode4 createmode;
6473 	bool_t must_trunc = FALSE;
6474 	int	truncating = 0;
6475 
6476 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6477 		return (EPERM);
6478 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6479 		return (EINVAL);
6480 	}
6481 
6482 	/* . and .. have special meaning in the protocol, reject them. */
6483 
6484 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6485 		return (EISDIR);
6486 
6487 	drp = VTOR4(dvp);
6488 
6489 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6490 		return (EINTR);
6491 
6492 top:
6493 	/*
6494 	 * We make a copy of the attributes because the caller does not
6495 	 * expect us to change what va points to.
6496 	 */
6497 	vattr = *va;
6498 
6499 	/*
6500 	 * If the pathname is "", then dvp is the root vnode of
6501 	 * a remote file mounted over a local directory.
6502 	 * All that needs to be done is access
6503 	 * checking and truncation.  Note that we avoid doing
6504 	 * open w/ create because the parent directory might
6505 	 * be in pseudo-fs and the open would fail.
6506 	 */
6507 	if (*nm == '\0') {
6508 		error = 0;
6509 		VN_HOLD(dvp);
6510 		vp = dvp;
6511 		must_trunc = TRUE;
6512 	} else {
6513 		/*
6514 		 * We need to go over the wire, just to be sure whether the
6515 		 * file exists or not.  Using the DNLC can be dangerous in
6516 		 * this case when making a decision regarding existence.
6517 		 */
6518 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6519 	}
6520 
6521 	if (exclusive)
6522 		createmode = EXCLUSIVE4;
6523 	else
6524 		createmode = GUARDED4;
6525 
6526 	/*
6527 	 * error would be set if the file does not exist on the
6528 	 * server, so lets go create it.
6529 	 */
6530 	if (error) {
6531 		goto create_otw;
6532 	}
6533 
6534 	/*
6535 	 * File does exist on the server
6536 	 */
6537 	if (exclusive == EXCL)
6538 		error = EEXIST;
6539 	else if (vp->v_type == VDIR && (mode & VWRITE))
6540 		error = EISDIR;
6541 	else {
6542 		/*
6543 		 * If vnode is a device, create special vnode.
6544 		 */
6545 		if (ISVDEV(vp->v_type)) {
6546 			tempvp = vp;
6547 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6548 			VN_RELE(tempvp);
6549 		}
6550 		if (!(error = VOP_ACCESS(vp, mode, 0, cr, ct))) {
6551 			if ((vattr.va_mask & AT_SIZE) &&
6552 			    vp->v_type == VREG) {
6553 				rp = VTOR4(vp);
6554 				/*
6555 				 * Check here for large file handled
6556 				 * by LF-unaware process (as
6557 				 * ufs_create() does)
6558 				 */
6559 				if (!(flags & FOFFMAX)) {
6560 					mutex_enter(&rp->r_statelock);
6561 					if (rp->r_size > MAXOFF32_T)
6562 						error = EOVERFLOW;
6563 					mutex_exit(&rp->r_statelock);
6564 				}
6565 
6566 				/* if error is set then we need to return */
6567 				if (error) {
6568 					nfs_rw_exit(&drp->r_rwlock);
6569 					VN_RELE(vp);
6570 					return (error);
6571 				}
6572 
6573 				if (must_trunc) {
6574 					vattr.va_mask = AT_SIZE;
6575 					error = nfs4setattr(vp, &vattr, 0, cr,
6576 					    NULL);
6577 				} else {
6578 				/*
6579 				 * we know we have a regular file that already
6580 				 * exists and we may end up truncating the file
6581 				 * as a result of the open_otw, so flush out
6582 				 * any dirty pages for this file first.
6583 				 */
6584 					if (nfs4_has_pages(vp) &&
6585 					    ((rp->r_flags & R4DIRTY) ||
6586 					    rp->r_count > 0 ||
6587 					    rp->r_mapcnt > 0)) {
6588 						error = nfs4_putpage(vp,
6589 						    (offset_t)0, 0, 0, cr, ct);
6590 						if (error && (error == ENOSPC ||
6591 						    error == EDQUOT)) {
6592 							mutex_enter(
6593 							    &rp->r_statelock);
6594 							if (!rp->r_error)
6595 								rp->r_error =
6596 								    error;
6597 							mutex_exit(
6598 							    &rp->r_statelock);
6599 						}
6600 					}
6601 					vattr.va_mask = (AT_SIZE |
6602 					    AT_TYPE | AT_MODE);
6603 					vattr.va_type = VREG;
6604 					createmode = UNCHECKED4;
6605 					truncating = 1;
6606 					goto create_otw;
6607 				}
6608 			}
6609 		}
6610 	}
6611 	nfs_rw_exit(&drp->r_rwlock);
6612 	if (error) {
6613 		VN_RELE(vp);
6614 	} else {
6615 		vnode_t *tvp;
6616 		rnode4_t *trp;
6617 		/*
6618 		 * existing file got truncated, notify.
6619 		 */
6620 		tvp = vp;
6621 		if (vp->v_type == VREG) {
6622 			trp = VTOR4(vp);
6623 			if (IS_SHADOW(vp, trp))
6624 				tvp = RTOV4(trp);
6625 		}
6626 		vnevent_create(tvp, ct);
6627 		*vpp = vp;
6628 	}
6629 	return (error);
6630 
6631 create_otw:
6632 	dnlc_remove(dvp, nm);
6633 
6634 	ASSERT(vattr.va_mask & AT_TYPE);
6635 
6636 	/*
6637 	 * If not a regular file let nfs4mknod() handle it.
6638 	 */
6639 	if (vattr.va_type != VREG) {
6640 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6641 		nfs_rw_exit(&drp->r_rwlock);
6642 		return (error);
6643 	}
6644 
6645 	/*
6646 	 * It _is_ a regular file.
6647 	 */
6648 	ASSERT(vattr.va_mask & AT_MODE);
6649 	if (MANDMODE(vattr.va_mode)) {
6650 		nfs_rw_exit(&drp->r_rwlock);
6651 		return (EACCES);
6652 	}
6653 
6654 	/*
6655 	 * If this happens to be a mknod of a regular file, then flags will
6656 	 * have neither FREAD or FWRITE.  However, we must set at least one
6657 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6658 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6659 	 * set (based on openmode specified by app).
6660 	 */
6661 	if ((flags & (FREAD|FWRITE)) == 0)
6662 		flags |= (FREAD|FWRITE);
6663 
6664 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6665 
6666 	if (vp != NULL) {
6667 		/* if create was successful, throw away the file's pages */
6668 		if (!error && (vattr.va_mask & AT_SIZE))
6669 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6670 			    cr);
6671 		/* release the lookup hold */
6672 		VN_RELE(vp);
6673 		vp = NULL;
6674 	}
6675 
6676 	/*
6677 	 * validate that we opened a regular file. This handles a misbehaving
6678 	 * server that returns an incorrect FH.
6679 	 */
6680 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6681 		error = EISDIR;
6682 		VN_RELE(*vpp);
6683 	}
6684 
6685 	/*
6686 	 * If this is not an exclusive create, then the CREATE
6687 	 * request will be made with the GUARDED mode set.  This
6688 	 * means that the server will return EEXIST if the file
6689 	 * exists.  The file could exist because of a retransmitted
6690 	 * request.  In this case, we recover by starting over and
6691 	 * checking to see whether the file exists.  This second
6692 	 * time through it should and a CREATE request will not be
6693 	 * sent.
6694 	 *
6695 	 * This handles the problem of a dangling CREATE request
6696 	 * which contains attributes which indicate that the file
6697 	 * should be truncated.  This retransmitted request could
6698 	 * possibly truncate valid data in the file if not caught
6699 	 * by the duplicate request mechanism on the server or if
6700 	 * not caught by other means.  The scenario is:
6701 	 *
6702 	 * Client transmits CREATE request with size = 0
6703 	 * Client times out, retransmits request.
6704 	 * Response to the first request arrives from the server
6705 	 *  and the client proceeds on.
6706 	 * Client writes data to the file.
6707 	 * The server now processes retransmitted CREATE request
6708 	 *  and truncates file.
6709 	 *
6710 	 * The use of the GUARDED CREATE request prevents this from
6711 	 * happening because the retransmitted CREATE would fail
6712 	 * with EEXIST and would not truncate the file.
6713 	 */
6714 	if (error == EEXIST && exclusive == NONEXCL) {
6715 #ifdef DEBUG
6716 		nfs4_create_misses++;
6717 #endif
6718 		goto top;
6719 	}
6720 	nfs_rw_exit(&drp->r_rwlock);
6721 	if (truncating && !error && *vpp) {
6722 		vnode_t *tvp;
6723 		rnode4_t *trp;
6724 		/*
6725 		 * existing file got truncated, notify.
6726 		 */
6727 		tvp = *vpp;
6728 		trp = VTOR4(tvp);
6729 		if (IS_SHADOW(tvp, trp))
6730 			tvp = RTOV4(trp);
6731 		vnevent_create(tvp, ct);
6732 	}
6733 	return (error);
6734 }
6735 
6736 /*
6737  * Create compound (for mkdir, mknod, symlink):
6738  * { Putfh <dfh>; Create; Getfh; Getattr }
6739  * It's okay if setattr failed to set gid - this is not considered
6740  * an error, but purge attrs in that case.
6741  */
6742 static int
6743 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6744     vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6745 {
6746 	int need_end_op = FALSE;
6747 	COMPOUND4args_clnt args;
6748 	COMPOUND4res_clnt res, *resp = NULL;
6749 	nfs_argop4 *argop;
6750 	nfs_resop4 *resop;
6751 	int doqueue;
6752 	mntinfo4_t *mi;
6753 	rnode4_t *drp = VTOR4(dvp);
6754 	change_info4 *cinfo;
6755 	GETFH4res *gf_res;
6756 	struct vattr vattr;
6757 	vnode_t *vp;
6758 	fattr4 *crattr;
6759 	bool_t needrecov = FALSE;
6760 	nfs4_recov_state_t recov_state;
6761 	nfs4_sharedfh_t *sfhp = NULL;
6762 	hrtime_t t;
6763 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6764 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6765 	dirattr_info_t dinfo, *dinfop;
6766 	servinfo4_t *svp;
6767 	bitmap4 supp_attrs;
6768 
6769 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6770 	    type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6771 
6772 	mi = VTOMI4(dvp);
6773 
6774 	/*
6775 	 * Make sure we properly deal with setting the right gid
6776 	 * on a new directory to reflect the parent's setgid bit
6777 	 */
6778 	setgid_flag = 0;
6779 	if (type == NF4DIR) {
6780 		struct vattr dva;
6781 
6782 		va->va_mode &= ~VSGID;
6783 		dva.va_mask = AT_MODE | AT_GID;
6784 		if (VOP_GETATTR(dvp, &dva, 0, cr, NULL) == 0) {
6785 
6786 			/*
6787 			 * If the parent's directory has the setgid bit set
6788 			 * _and_ the client was able to get a valid mapping
6789 			 * for the parent dir's owner_group, we want to
6790 			 * append NVERIFY(owner_group == dva.va_gid) and
6791 			 * SETTATTR to the CREATE compound.
6792 			 */
6793 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6794 				setgid_flag = 1;
6795 				va->va_mode |= VSGID;
6796 				if (dva.va_gid != GID_NOBODY) {
6797 					va->va_mask |= AT_GID;
6798 					va->va_gid = dva.va_gid;
6799 				}
6800 			}
6801 		}
6802 	}
6803 
6804 	/*
6805 	 * Create ops:
6806 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6807 	 *	5:restorefh(dir) 6:getattr(dir)
6808 	 *
6809 	 * if (setgid)
6810 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6811 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6812 	 *	8:nverify 9:setattr
6813 	 */
6814 	if (setgid_flag) {
6815 		numops = 10;
6816 		idx_create = 1;
6817 		idx_fattr = 3;
6818 	} else {
6819 		numops = 7;
6820 		idx_create = 2;
6821 		idx_fattr = 4;
6822 	}
6823 
6824 	ASSERT(nfs_zone() == mi->mi_zone);
6825 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6826 		return (EINTR);
6827 	}
6828 	recov_state.rs_flags = 0;
6829 	recov_state.rs_num_retry_despite_err = 0;
6830 
6831 	argoplist_size = numops * sizeof (nfs_argop4);
6832 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6833 
6834 recov_retry:
6835 	if (type == NF4LNK)
6836 		args.ctag = TAG_SYMLINK;
6837 	else if (type == NF4DIR)
6838 		args.ctag = TAG_MKDIR;
6839 	else
6840 		args.ctag = TAG_MKNOD;
6841 
6842 	args.array_len = numops;
6843 	args.array = argop;
6844 
6845 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6846 		nfs_rw_exit(&drp->r_rwlock);
6847 		kmem_free(argop, argoplist_size);
6848 		return (e.error);
6849 	}
6850 	need_end_op = TRUE;
6851 
6852 
6853 	/* 0: putfh directory */
6854 	argop[0].argop = OP_CPUTFH;
6855 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6856 
6857 	/* 1/2: Create object */
6858 	argop[idx_create].argop = OP_CCREATE;
6859 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6860 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6861 	if (type == NF4LNK) {
6862 		/*
6863 		 * symlink, treat name as data
6864 		 */
6865 		ASSERT(data != NULL);
6866 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6867 		    (char *)data;
6868 	}
6869 	if (type == NF4BLK || type == NF4CHR) {
6870 		ASSERT(data != NULL);
6871 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6872 		    *((specdata4 *)data);
6873 	}
6874 
6875 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6876 
6877 	svp = drp->r_server;
6878 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6879 	supp_attrs = svp->sv_supp_attrs;
6880 	nfs_rw_exit(&svp->sv_lock);
6881 
6882 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6883 		nfs_rw_exit(&drp->r_rwlock);
6884 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6885 		e.error = EINVAL;
6886 		kmem_free(argop, argoplist_size);
6887 		return (e.error);
6888 	}
6889 
6890 	/* 2/3: getfh fh of created object */
6891 	ASSERT(idx_create + 1 == idx_fattr - 1);
6892 	argop[idx_create + 1].argop = OP_GETFH;
6893 
6894 	/* 3/4: getattr of new object */
6895 	argop[idx_fattr].argop = OP_GETATTR;
6896 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6897 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6898 
6899 	if (setgid_flag) {
6900 		vattr_t	_v;
6901 
6902 		argop[4].argop = OP_SAVEFH;
6903 
6904 		argop[5].argop = OP_CPUTFH;
6905 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6906 
6907 		argop[6].argop = OP_GETATTR;
6908 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6909 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6910 
6911 		argop[7].argop = OP_RESTOREFH;
6912 
6913 		/*
6914 		 * nverify
6915 		 *
6916 		 * XXX - Revisit the last argument to nfs4_end_op()
6917 		 *	 once 5020486 is fixed.
6918 		 */
6919 		_v.va_mask = AT_GID;
6920 		_v.va_gid = va->va_gid;
6921 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6922 		    supp_attrs)) {
6923 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6924 			nfs_rw_exit(&drp->r_rwlock);
6925 			nfs4_fattr4_free(crattr);
6926 			kmem_free(argop, argoplist_size);
6927 			return (e.error);
6928 		}
6929 
6930 		/*
6931 		 * setattr
6932 		 *
6933 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
6934 		 * so no need for stateid or flags. Also we specify NULL
6935 		 * rp since we're only interested in setting owner_group
6936 		 * attributes.
6937 		 */
6938 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
6939 		    &e.error, 0);
6940 
6941 		if (e.error) {
6942 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6943 			nfs_rw_exit(&drp->r_rwlock);
6944 			nfs4_fattr4_free(crattr);
6945 			nfs4args_verify_free(&argop[8]);
6946 			kmem_free(argop, argoplist_size);
6947 			return (e.error);
6948 		}
6949 	} else {
6950 		argop[1].argop = OP_SAVEFH;
6951 
6952 		argop[5].argop = OP_RESTOREFH;
6953 
6954 		argop[6].argop = OP_GETATTR;
6955 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6956 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6957 	}
6958 
6959 	dnlc_remove(dvp, nm);
6960 
6961 	doqueue = 1;
6962 	t = gethrtime();
6963 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
6964 
6965 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
6966 	if (e.error) {
6967 		PURGE_ATTRCACHE4(dvp);
6968 		if (!needrecov)
6969 			goto out;
6970 	}
6971 
6972 	if (needrecov) {
6973 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
6974 		    OP_CREATE, NULL) == FALSE) {
6975 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6976 			    needrecov);
6977 			need_end_op = FALSE;
6978 			nfs4_fattr4_free(crattr);
6979 			if (setgid_flag) {
6980 				nfs4args_verify_free(&argop[8]);
6981 				nfs4args_setattr_free(&argop[9]);
6982 			}
6983 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6984 			goto recov_retry;
6985 		}
6986 	}
6987 
6988 	resp = &res;
6989 
6990 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
6991 
6992 		if (res.status == NFS4ERR_BADOWNER)
6993 			nfs4_log_badowner(mi, OP_CREATE);
6994 
6995 		e.error = geterrno4(res.status);
6996 
6997 		/*
6998 		 * This check is left over from when create was implemented
6999 		 * using a setattr op (instead of createattrs).  If the
7000 		 * putfh/create/getfh failed, the error was returned.  If
7001 		 * setattr/getattr failed, we keep going.
7002 		 *
7003 		 * It might be better to get rid of the GETFH also, and just
7004 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
7005 		 * Then if any of the operations failed, we could return the
7006 		 * error now, and remove much of the error code below.
7007 		 */
7008 		if (res.array_len <= idx_fattr) {
7009 			/*
7010 			 * Either Putfh, Create or Getfh failed.
7011 			 */
7012 			PURGE_ATTRCACHE4(dvp);
7013 			/*
7014 			 * nfs4_purge_stale_fh() may generate otw calls through
7015 			 * nfs4_invalidate_pages. Hence the need to call
7016 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
7017 			 */
7018 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7019 			    needrecov);
7020 			need_end_op = FALSE;
7021 			nfs4_purge_stale_fh(e.error, dvp, cr);
7022 			goto out;
7023 		}
7024 	}
7025 
7026 	resop = &res.array[idx_create];	/* create res */
7027 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
7028 
7029 	resop = &res.array[idx_create + 1]; /* getfh res */
7030 	gf_res = &resop->nfs_resop4_u.opgetfh;
7031 
7032 	sfhp = sfh4_get(&gf_res->object, mi);
7033 	if (e.error) {
7034 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
7035 		    fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7036 		if (vp->v_type == VNON) {
7037 			vattr.va_mask = AT_TYPE;
7038 			/*
7039 			 * Need to call nfs4_end_op before nfs4getattr to avoid
7040 			 * potential nfs4_start_op deadlock. See RFE 4777612.
7041 			 */
7042 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7043 			    needrecov);
7044 			need_end_op = FALSE;
7045 			e.error = nfs4getattr(vp, &vattr, cr);
7046 			if (e.error) {
7047 				VN_RELE(vp);
7048 				*vpp = NULL;
7049 				goto out;
7050 			}
7051 			vp->v_type = vattr.va_type;
7052 		}
7053 		e.error = 0;
7054 	} else {
7055 		*vpp = vp = makenfs4node(sfhp,
7056 		    &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
7057 		    dvp->v_vfsp, t, cr,
7058 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7059 	}
7060 
7061 	/*
7062 	 * If compound succeeded, then update dir attrs
7063 	 */
7064 	if (res.status == NFS4_OK) {
7065 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
7066 		dinfo.di_cred = cr;
7067 		dinfo.di_time_call = t;
7068 		dinfop = &dinfo;
7069 	} else
7070 		dinfop = NULL;
7071 
7072 	/* Update directory cache attribute, readdir and dnlc caches */
7073 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
7074 
7075 out:
7076 	if (sfhp != NULL)
7077 		sfh4_rele(&sfhp);
7078 	nfs_rw_exit(&drp->r_rwlock);
7079 	nfs4_fattr4_free(crattr);
7080 	if (setgid_flag) {
7081 		nfs4args_verify_free(&argop[8]);
7082 		nfs4args_setattr_free(&argop[9]);
7083 	}
7084 	if (resp)
7085 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7086 	if (need_end_op)
7087 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7088 
7089 	kmem_free(argop, argoplist_size);
7090 	return (e.error);
7091 }
7092 
7093 /* ARGSUSED */
7094 static int
7095 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7096     int mode, vnode_t **vpp, cred_t *cr)
7097 {
7098 	int error;
7099 	vnode_t *vp;
7100 	nfs_ftype4 type;
7101 	specdata4 spec, *specp = NULL;
7102 
7103 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7104 
7105 	switch (va->va_type) {
7106 	case VCHR:
7107 	case VBLK:
7108 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7109 		spec.specdata1 = getmajor(va->va_rdev);
7110 		spec.specdata2 = getminor(va->va_rdev);
7111 		specp = &spec;
7112 		break;
7113 
7114 	case VFIFO:
7115 		type = NF4FIFO;
7116 		break;
7117 	case VSOCK:
7118 		type = NF4SOCK;
7119 		break;
7120 
7121 	default:
7122 		return (EINVAL);
7123 	}
7124 
7125 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7126 	if (error) {
7127 		return (error);
7128 	}
7129 
7130 	/*
7131 	 * This might not be needed any more; special case to deal
7132 	 * with problematic v2/v3 servers.  Since create was unable
7133 	 * to set group correctly, not sure what hope setattr has.
7134 	 */
7135 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7136 		va->va_mask = AT_GID;
7137 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7138 	}
7139 
7140 	/*
7141 	 * If vnode is a device create special vnode
7142 	 */
7143 	if (ISVDEV(vp->v_type)) {
7144 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7145 		VN_RELE(vp);
7146 	} else {
7147 		*vpp = vp;
7148 	}
7149 	return (error);
7150 }
7151 
7152 /*
7153  * Remove requires that the current fh be the target directory.
7154  * After the operation, the current fh is unchanged.
7155  * The compound op structure is:
7156  *      PUTFH(targetdir), REMOVE
7157  *
7158  * Weirdness: if the vnode to be removed is open
7159  * we rename it instead of removing it and nfs_inactive
7160  * will remove the new name.
7161  */
7162 /* ARGSUSED */
7163 static int
7164 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr, caller_context_t *ct, int flags)
7165 {
7166 	COMPOUND4args_clnt args;
7167 	COMPOUND4res_clnt res, *resp = NULL;
7168 	REMOVE4res *rm_res;
7169 	nfs_argop4 argop[3];
7170 	nfs_resop4 *resop;
7171 	vnode_t *vp;
7172 	char *tmpname;
7173 	int doqueue;
7174 	mntinfo4_t *mi;
7175 	rnode4_t *rp;
7176 	rnode4_t *drp;
7177 	int needrecov = 0;
7178 	nfs4_recov_state_t recov_state;
7179 	int isopen;
7180 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7181 	dirattr_info_t dinfo;
7182 
7183 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7184 		return (EPERM);
7185 	drp = VTOR4(dvp);
7186 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7187 		return (EINTR);
7188 
7189 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7190 	if (e.error) {
7191 		nfs_rw_exit(&drp->r_rwlock);
7192 		return (e.error);
7193 	}
7194 
7195 	if (vp->v_type == VDIR) {
7196 		VN_RELE(vp);
7197 		nfs_rw_exit(&drp->r_rwlock);
7198 		return (EISDIR);
7199 	}
7200 
7201 	/*
7202 	 * First just remove the entry from the name cache, as it
7203 	 * is most likely the only entry for this vp.
7204 	 */
7205 	dnlc_remove(dvp, nm);
7206 
7207 	rp = VTOR4(vp);
7208 
7209 	/*
7210 	 * For regular file types, check to see if the file is open by looking
7211 	 * at the open streams.
7212 	 * For all other types, check the reference count on the vnode.  Since
7213 	 * they are not opened OTW they never have an open stream.
7214 	 *
7215 	 * If the file is open, rename it to .nfsXXXX.
7216 	 */
7217 	if (vp->v_type != VREG) {
7218 		/*
7219 		 * If the file has a v_count > 1 then there may be more than one
7220 		 * entry in the name cache due multiple links or an open file,
7221 		 * but we don't have the real reference count so flush all
7222 		 * possible entries.
7223 		 */
7224 		if (vp->v_count > 1)
7225 			dnlc_purge_vp(vp);
7226 
7227 		/*
7228 		 * Now we have the real reference count.
7229 		 */
7230 		isopen = vp->v_count > 1;
7231 	} else {
7232 		mutex_enter(&rp->r_os_lock);
7233 		isopen = list_head(&rp->r_open_streams) != NULL;
7234 		mutex_exit(&rp->r_os_lock);
7235 	}
7236 
7237 	mutex_enter(&rp->r_statelock);
7238 	if (isopen &&
7239 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7240 		mutex_exit(&rp->r_statelock);
7241 		tmpname = newname();
7242 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr, ct);
7243 		if (e.error)
7244 			kmem_free(tmpname, MAXNAMELEN);
7245 		else {
7246 			mutex_enter(&rp->r_statelock);
7247 			if (rp->r_unldvp == NULL) {
7248 				VN_HOLD(dvp);
7249 				rp->r_unldvp = dvp;
7250 				if (rp->r_unlcred != NULL)
7251 					crfree(rp->r_unlcred);
7252 				crhold(cr);
7253 				rp->r_unlcred = cr;
7254 				rp->r_unlname = tmpname;
7255 			} else {
7256 				kmem_free(rp->r_unlname, MAXNAMELEN);
7257 				rp->r_unlname = tmpname;
7258 			}
7259 			mutex_exit(&rp->r_statelock);
7260 		}
7261 		VN_RELE(vp);
7262 		nfs_rw_exit(&drp->r_rwlock);
7263 		return (e.error);
7264 	}
7265 	/*
7266 	 * Actually remove the file/dir
7267 	 */
7268 	mutex_exit(&rp->r_statelock);
7269 
7270 	/*
7271 	 * We need to flush any dirty pages which happen to
7272 	 * be hanging around before removing the file.
7273 	 * This shouldn't happen very often since in NFSv4
7274 	 * we should be close to open consistent.
7275 	 */
7276 	if (nfs4_has_pages(vp) &&
7277 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7278 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, ct);
7279 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7280 			mutex_enter(&rp->r_statelock);
7281 			if (!rp->r_error)
7282 				rp->r_error = e.error;
7283 			mutex_exit(&rp->r_statelock);
7284 		}
7285 	}
7286 
7287 	mi = VTOMI4(dvp);
7288 
7289 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7290 	recov_state.rs_flags = 0;
7291 	recov_state.rs_num_retry_despite_err = 0;
7292 
7293 recov_retry:
7294 	/*
7295 	 * Remove ops: putfh dir; remove
7296 	 */
7297 	args.ctag = TAG_REMOVE;
7298 	args.array_len = 3;
7299 	args.array = argop;
7300 
7301 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7302 	if (e.error) {
7303 		nfs_rw_exit(&drp->r_rwlock);
7304 		VN_RELE(vp);
7305 		return (e.error);
7306 	}
7307 
7308 	/* putfh directory */
7309 	argop[0].argop = OP_CPUTFH;
7310 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7311 
7312 	/* remove */
7313 	argop[1].argop = OP_CREMOVE;
7314 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7315 
7316 	/* getattr dir */
7317 	argop[2].argop = OP_GETATTR;
7318 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7319 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7320 
7321 	doqueue = 1;
7322 	dinfo.di_time_call = gethrtime();
7323 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7324 
7325 	PURGE_ATTRCACHE4(vp);
7326 
7327 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7328 	if (e.error)
7329 		PURGE_ATTRCACHE4(dvp);
7330 
7331 	if (needrecov) {
7332 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7333 		    NULL, NULL, NULL, OP_REMOVE, NULL) == FALSE) {
7334 			if (!e.error)
7335 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7336 				    (caddr_t)&res);
7337 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7338 			    needrecov);
7339 			goto recov_retry;
7340 		}
7341 	}
7342 
7343 	/*
7344 	 * Matching nfs4_end_op() for start_op() above.
7345 	 * There is a path in the code below which calls
7346 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7347 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7348 	 * here to avoid nfs4_start_op() deadlock.
7349 	 */
7350 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7351 
7352 	if (!e.error) {
7353 		resp = &res;
7354 
7355 		if (res.status) {
7356 			e.error = geterrno4(res.status);
7357 			PURGE_ATTRCACHE4(dvp);
7358 			nfs4_purge_stale_fh(e.error, dvp, cr);
7359 		} else {
7360 			resop = &res.array[1];	/* remove res */
7361 			rm_res = &resop->nfs_resop4_u.opremove;
7362 
7363 			dinfo.di_garp =
7364 			    &res.array[2].nfs_resop4_u.opgetattr.ga_res;
7365 			dinfo.di_cred = cr;
7366 
7367 			/* Update directory attr, readdir and dnlc caches */
7368 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7369 			    &dinfo);
7370 		}
7371 	}
7372 	nfs_rw_exit(&drp->r_rwlock);
7373 	if (resp)
7374 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7375 
7376 	if (e.error == 0) {
7377 		vnode_t *tvp;
7378 		rnode4_t *trp;
7379 		trp = VTOR4(vp);
7380 		tvp = vp;
7381 		if (IS_SHADOW(vp, trp))
7382 			tvp = RTOV4(trp);
7383 		vnevent_remove(tvp, dvp, nm, ct);
7384 	}
7385 	VN_RELE(vp);
7386 	return (e.error);
7387 }
7388 
7389 /*
7390  * Link requires that the current fh be the target directory and the
7391  * saved fh be the source fh. After the operation, the current fh is unchanged.
7392  * Thus the compound op structure is:
7393  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7394  *	GETATTR(file)
7395  */
7396 /* ARGSUSED */
7397 static int
7398 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr,
7399     caller_context_t *ct, int flags)
7400 {
7401 	COMPOUND4args_clnt args;
7402 	COMPOUND4res_clnt res, *resp = NULL;
7403 	LINK4res *ln_res;
7404 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7405 	nfs_argop4 *argop;
7406 	nfs_resop4 *resop;
7407 	vnode_t *realvp, *nvp;
7408 	int doqueue;
7409 	mntinfo4_t *mi;
7410 	rnode4_t *tdrp;
7411 	bool_t needrecov = FALSE;
7412 	nfs4_recov_state_t recov_state;
7413 	hrtime_t t;
7414 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7415 	dirattr_info_t dinfo;
7416 
7417 	ASSERT(*tnm != '\0');
7418 	ASSERT(tdvp->v_type == VDIR);
7419 	ASSERT(nfs4_consistent_type(tdvp));
7420 	ASSERT(nfs4_consistent_type(svp));
7421 
7422 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7423 		return (EPERM);
7424 	if (VOP_REALVP(svp, &realvp, ct) == 0) {
7425 		svp = realvp;
7426 		ASSERT(nfs4_consistent_type(svp));
7427 	}
7428 
7429 	tdrp = VTOR4(tdvp);
7430 	mi = VTOMI4(svp);
7431 
7432 	if (!(mi->mi_flags & MI4_LINK)) {
7433 		return (EOPNOTSUPP);
7434 	}
7435 	recov_state.rs_flags = 0;
7436 	recov_state.rs_num_retry_despite_err = 0;
7437 
7438 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7439 		return (EINTR);
7440 
7441 recov_retry:
7442 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7443 
7444 	args.ctag = TAG_LINK;
7445 
7446 	/*
7447 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7448 	 * restorefh; getattr(fl)
7449 	 */
7450 	args.array_len = 7;
7451 	args.array = argop;
7452 
7453 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7454 	if (e.error) {
7455 		kmem_free(argop, argoplist_size);
7456 		nfs_rw_exit(&tdrp->r_rwlock);
7457 		return (e.error);
7458 	}
7459 
7460 	/* 0. putfh file */
7461 	argop[0].argop = OP_CPUTFH;
7462 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7463 
7464 	/* 1. save current fh to free up the space for the dir */
7465 	argop[1].argop = OP_SAVEFH;
7466 
7467 	/* 2. putfh targetdir */
7468 	argop[2].argop = OP_CPUTFH;
7469 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7470 
7471 	/* 3. link: current_fh is targetdir, saved_fh is source */
7472 	argop[3].argop = OP_CLINK;
7473 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7474 
7475 	/* 4. Get attributes of dir */
7476 	argop[4].argop = OP_GETATTR;
7477 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7478 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7479 
7480 	/* 5. If link was successful, restore current vp to file */
7481 	argop[5].argop = OP_RESTOREFH;
7482 
7483 	/* 6. Get attributes of linked object */
7484 	argop[6].argop = OP_GETATTR;
7485 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7486 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7487 
7488 	dnlc_remove(tdvp, tnm);
7489 
7490 	doqueue = 1;
7491 	t = gethrtime();
7492 
7493 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7494 
7495 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7496 	if (e.error != 0 && !needrecov) {
7497 		PURGE_ATTRCACHE4(tdvp);
7498 		PURGE_ATTRCACHE4(svp);
7499 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7500 		goto out;
7501 	}
7502 
7503 	if (needrecov) {
7504 		bool_t abort;
7505 
7506 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7507 		    NULL, NULL, OP_LINK, NULL);
7508 		if (abort == FALSE) {
7509 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7510 			    needrecov);
7511 			kmem_free(argop, argoplist_size);
7512 			if (!e.error)
7513 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7514 				    (caddr_t)&res);
7515 			goto recov_retry;
7516 		} else {
7517 			if (e.error != 0) {
7518 				PURGE_ATTRCACHE4(tdvp);
7519 				PURGE_ATTRCACHE4(svp);
7520 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7521 				    &recov_state, needrecov);
7522 				goto out;
7523 			}
7524 			/* fall through for res.status case */
7525 		}
7526 	}
7527 
7528 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7529 
7530 	resp = &res;
7531 	if (res.status) {
7532 		/* If link succeeded, then don't return error */
7533 		e.error = geterrno4(res.status);
7534 		if (res.array_len <= 4) {
7535 			/*
7536 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7537 			 */
7538 			PURGE_ATTRCACHE4(svp);
7539 			PURGE_ATTRCACHE4(tdvp);
7540 			if (e.error == EOPNOTSUPP) {
7541 				mutex_enter(&mi->mi_lock);
7542 				mi->mi_flags &= ~MI4_LINK;
7543 				mutex_exit(&mi->mi_lock);
7544 			}
7545 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7546 			/* XXX-LP */
7547 			if (e.error == EISDIR && crgetuid(cr) != 0)
7548 				e.error = EPERM;
7549 			goto out;
7550 		}
7551 	}
7552 
7553 	/* either no error or one of the postop getattr failed */
7554 
7555 	/*
7556 	 * XXX - if LINK succeeded, but no attrs were returned for link
7557 	 * file, purge its cache.
7558 	 *
7559 	 * XXX Perform a simplified version of wcc checking. Instead of
7560 	 * have another getattr to get pre-op, just purge cache if
7561 	 * any of the ops prior to and including the getattr failed.
7562 	 * If the getattr succeeded then update the attrcache accordingly.
7563 	 */
7564 
7565 	/*
7566 	 * update cache with link file postattrs.
7567 	 * Note: at this point resop points to link res.
7568 	 */
7569 	resop = &res.array[3];	/* link res */
7570 	ln_res = &resop->nfs_resop4_u.oplink;
7571 	if (res.status == NFS4_OK)
7572 		e.error = nfs4_update_attrcache(res.status,
7573 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res,
7574 		    t, svp, cr);
7575 
7576 	/*
7577 	 * Call makenfs4node to create the new shadow vp for tnm.
7578 	 * We pass NULL attrs because we just cached attrs for
7579 	 * the src object.  All we're trying to accomplish is to
7580 	 * to create the new shadow vnode.
7581 	 */
7582 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7583 	    tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm, VTOR4(svp)->r_fh));
7584 
7585 	/* Update target cache attribute, readdir and dnlc caches */
7586 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7587 	dinfo.di_time_call = t;
7588 	dinfo.di_cred = cr;
7589 
7590 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7591 	ASSERT(nfs4_consistent_type(tdvp));
7592 	ASSERT(nfs4_consistent_type(svp));
7593 	ASSERT(nfs4_consistent_type(nvp));
7594 	VN_RELE(nvp);
7595 
7596 	if (!e.error) {
7597 		vnode_t *tvp;
7598 		rnode4_t *trp;
7599 		/*
7600 		 * Notify the source file of this link operation.
7601 		 */
7602 		trp = VTOR4(svp);
7603 		tvp = svp;
7604 		if (IS_SHADOW(svp, trp))
7605 			tvp = RTOV4(trp);
7606 		vnevent_link(tvp, ct);
7607 	}
7608 out:
7609 	kmem_free(argop, argoplist_size);
7610 	if (resp)
7611 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7612 
7613 	nfs_rw_exit(&tdrp->r_rwlock);
7614 
7615 	return (e.error);
7616 }
7617 
7618 /* ARGSUSED */
7619 static int
7620 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7621     caller_context_t *ct, int flags)
7622 {
7623 	vnode_t *realvp;
7624 
7625 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7626 		return (EPERM);
7627 	if (VOP_REALVP(ndvp, &realvp, ct) == 0)
7628 		ndvp = realvp;
7629 
7630 	return (nfs4rename(odvp, onm, ndvp, nnm, cr, ct));
7631 }
7632 
7633 /*
7634  * nfs4rename does the real work of renaming in NFS Version 4.
7635  *
7636  * A file handle is considered volatile for renaming purposes if either
7637  * of the volatile bits are turned on. However, the compound may differ
7638  * based on the likelihood of the filehandle to change during rename.
7639  */
7640 static int
7641 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7642     caller_context_t *ct)
7643 {
7644 	int error;
7645 	mntinfo4_t *mi;
7646 	vnode_t *nvp = NULL;
7647 	vnode_t *ovp = NULL;
7648 	char *tmpname = NULL;
7649 	rnode4_t *rp;
7650 	rnode4_t *odrp;
7651 	rnode4_t *ndrp;
7652 	int did_link = 0;
7653 	int do_link = 1;
7654 	nfsstat4 stat = NFS4_OK;
7655 
7656 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7657 	ASSERT(nfs4_consistent_type(odvp));
7658 	ASSERT(nfs4_consistent_type(ndvp));
7659 
7660 	if (onm[0] == '.' && (onm[1] == '\0' ||
7661 	    (onm[1] == '.' && onm[2] == '\0')))
7662 		return (EINVAL);
7663 
7664 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7665 	    (nnm[1] == '.' && nnm[2] == '\0')))
7666 		return (EINVAL);
7667 
7668 	odrp = VTOR4(odvp);
7669 	ndrp = VTOR4(ndvp);
7670 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7671 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7672 			return (EINTR);
7673 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7674 			nfs_rw_exit(&odrp->r_rwlock);
7675 			return (EINTR);
7676 		}
7677 	} else {
7678 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7679 			return (EINTR);
7680 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7681 			nfs_rw_exit(&ndrp->r_rwlock);
7682 			return (EINTR);
7683 		}
7684 	}
7685 
7686 	/*
7687 	 * Lookup the target file.  If it exists, it needs to be
7688 	 * checked to see whether it is a mount point and whether
7689 	 * it is active (open).
7690 	 */
7691 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7692 	if (!error) {
7693 		int	isactive;
7694 
7695 		ASSERT(nfs4_consistent_type(nvp));
7696 		/*
7697 		 * If this file has been mounted on, then just
7698 		 * return busy because renaming to it would remove
7699 		 * the mounted file system from the name space.
7700 		 */
7701 		if (vn_ismntpt(nvp)) {
7702 			VN_RELE(nvp);
7703 			nfs_rw_exit(&odrp->r_rwlock);
7704 			nfs_rw_exit(&ndrp->r_rwlock);
7705 			return (EBUSY);
7706 		}
7707 
7708 		/*
7709 		 * First just remove the entry from the name cache, as it
7710 		 * is most likely the only entry for this vp.
7711 		 */
7712 		dnlc_remove(ndvp, nnm);
7713 
7714 		rp = VTOR4(nvp);
7715 
7716 		if (nvp->v_type != VREG) {
7717 			/*
7718 			 * Purge the name cache of all references to this vnode
7719 			 * so that we can check the reference count to infer
7720 			 * whether it is active or not.
7721 			 */
7722 			if (nvp->v_count > 1)
7723 				dnlc_purge_vp(nvp);
7724 
7725 			isactive = nvp->v_count > 1;
7726 		} else {
7727 			mutex_enter(&rp->r_os_lock);
7728 			isactive = list_head(&rp->r_open_streams) != NULL;
7729 			mutex_exit(&rp->r_os_lock);
7730 		}
7731 
7732 		/*
7733 		 * If the vnode is active and is not a directory,
7734 		 * arrange to rename it to a
7735 		 * temporary file so that it will continue to be
7736 		 * accessible.  This implements the "unlink-open-file"
7737 		 * semantics for the target of a rename operation.
7738 		 * Before doing this though, make sure that the
7739 		 * source and target files are not already the same.
7740 		 */
7741 		if (isactive && nvp->v_type != VDIR) {
7742 			/*
7743 			 * Lookup the source name.
7744 			 */
7745 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7746 
7747 			/*
7748 			 * The source name *should* already exist.
7749 			 */
7750 			if (error) {
7751 				VN_RELE(nvp);
7752 				nfs_rw_exit(&odrp->r_rwlock);
7753 				nfs_rw_exit(&ndrp->r_rwlock);
7754 				return (error);
7755 			}
7756 
7757 			ASSERT(nfs4_consistent_type(ovp));
7758 
7759 			/*
7760 			 * Compare the two vnodes.  If they are the same,
7761 			 * just release all held vnodes and return success.
7762 			 */
7763 			if (VN_CMP(ovp, nvp)) {
7764 				VN_RELE(ovp);
7765 				VN_RELE(nvp);
7766 				nfs_rw_exit(&odrp->r_rwlock);
7767 				nfs_rw_exit(&ndrp->r_rwlock);
7768 				return (0);
7769 			}
7770 
7771 			/*
7772 			 * Can't mix and match directories and non-
7773 			 * directories in rename operations.  We already
7774 			 * know that the target is not a directory.  If
7775 			 * the source is a directory, return an error.
7776 			 */
7777 			if (ovp->v_type == VDIR) {
7778 				VN_RELE(ovp);
7779 				VN_RELE(nvp);
7780 				nfs_rw_exit(&odrp->r_rwlock);
7781 				nfs_rw_exit(&ndrp->r_rwlock);
7782 				return (ENOTDIR);
7783 			}
7784 link_call:
7785 			/*
7786 			 * The target file exists, is not the same as
7787 			 * the source file, and is active.  We first
7788 			 * try to Link it to a temporary filename to
7789 			 * avoid having the server removing the file
7790 			 * completely (which could cause data loss to
7791 			 * the user's POV in the event the Rename fails
7792 			 * -- see bug 1165874).
7793 			 */
7794 			/*
7795 			 * The do_link and did_link booleans are
7796 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7797 			 * returned for the Rename.  Some servers can
7798 			 * not Rename over an Open file, so they return
7799 			 * this error.  The client needs to Remove the
7800 			 * newly created Link and do two Renames, just
7801 			 * as if the server didn't support LINK.
7802 			 */
7803 			tmpname = newname();
7804 			error = 0;
7805 
7806 			if (do_link) {
7807 				error = nfs4_link(ndvp, nvp, tmpname, cr,
7808 				    NULL, 0);
7809 			}
7810 			if (error == EOPNOTSUPP || !do_link) {
7811 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7812 				    cr, NULL, 0);
7813 				did_link = 0;
7814 			} else {
7815 				did_link = 1;
7816 			}
7817 			if (error) {
7818 				kmem_free(tmpname, MAXNAMELEN);
7819 				VN_RELE(ovp);
7820 				VN_RELE(nvp);
7821 				nfs_rw_exit(&odrp->r_rwlock);
7822 				nfs_rw_exit(&ndrp->r_rwlock);
7823 				return (error);
7824 			}
7825 
7826 			mutex_enter(&rp->r_statelock);
7827 			if (rp->r_unldvp == NULL) {
7828 				VN_HOLD(ndvp);
7829 				rp->r_unldvp = ndvp;
7830 				if (rp->r_unlcred != NULL)
7831 					crfree(rp->r_unlcred);
7832 				crhold(cr);
7833 				rp->r_unlcred = cr;
7834 				rp->r_unlname = tmpname;
7835 			} else {
7836 				if (rp->r_unlname)
7837 					kmem_free(rp->r_unlname, MAXNAMELEN);
7838 				rp->r_unlname = tmpname;
7839 			}
7840 			mutex_exit(&rp->r_statelock);
7841 		}
7842 
7843 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7844 
7845 		ASSERT(nfs4_consistent_type(nvp));
7846 	}
7847 
7848 	if (ovp == NULL) {
7849 		/*
7850 		 * When renaming directories to be a subdirectory of a
7851 		 * different parent, the dnlc entry for ".." will no
7852 		 * longer be valid, so it must be removed.
7853 		 *
7854 		 * We do a lookup here to determine whether we are renaming
7855 		 * a directory and we need to check if we are renaming
7856 		 * an unlinked file.  This might have already been done
7857 		 * in previous code, so we check ovp == NULL to avoid
7858 		 * doing it twice.
7859 		 */
7860 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7861 		/*
7862 		 * The source name *should* already exist.
7863 		 */
7864 		if (error) {
7865 			nfs_rw_exit(&odrp->r_rwlock);
7866 			nfs_rw_exit(&ndrp->r_rwlock);
7867 			if (nvp) {
7868 				VN_RELE(nvp);
7869 			}
7870 			return (error);
7871 		}
7872 		ASSERT(ovp != NULL);
7873 		ASSERT(nfs4_consistent_type(ovp));
7874 	}
7875 
7876 	/*
7877 	 * Is the object being renamed a dir, and if so, is
7878 	 * it being renamed to a child of itself?  The underlying
7879 	 * fs should ultimately return EINVAL for this case;
7880 	 * however, buggy beta non-Solaris NFSv4 servers at
7881 	 * interop testing events have allowed this behavior,
7882 	 * and it caused our client to panic due to a recursive
7883 	 * mutex_enter in fn_move.
7884 	 *
7885 	 * The tedious locking in fn_move could be changed to
7886 	 * deal with this case, and the client could avoid the
7887 	 * panic; however, the client would just confuse itself
7888 	 * later and misbehave.  A better way to handle the broken
7889 	 * server is to detect this condition and return EINVAL
7890 	 * without ever sending the the bogus rename to the server.
7891 	 * We know the rename is invalid -- just fail it now.
7892 	 */
7893 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7894 		VN_RELE(ovp);
7895 		nfs_rw_exit(&odrp->r_rwlock);
7896 		nfs_rw_exit(&ndrp->r_rwlock);
7897 		if (nvp) {
7898 			VN_RELE(nvp);
7899 		}
7900 		return (EINVAL);
7901 	}
7902 
7903 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7904 
7905 	/*
7906 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7907 	 * possible for the filehandle to change due to the rename.
7908 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7909 	 * the fh will not change because of the rename, but we still need
7910 	 * to update its rnode entry with the new name for
7911 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7912 	 * has no effect on these for now, but for future improvements,
7913 	 * we might want to use it too to simplify handling of files
7914 	 * that are open with that flag on. (XXX)
7915 	 */
7916 	mi = VTOMI4(odvp);
7917 	if (NFS4_VOLATILE_FH(mi))
7918 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7919 		    &stat);
7920 	else
7921 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7922 		    &stat);
7923 
7924 	ASSERT(nfs4_consistent_type(odvp));
7925 	ASSERT(nfs4_consistent_type(ndvp));
7926 	ASSERT(nfs4_consistent_type(ovp));
7927 
7928 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
7929 		do_link = 0;
7930 		/*
7931 		 * Before the 'link_call' code, we did a nfs4_lookup
7932 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
7933 		 * call we call VN_RELE to match that hold.  We need
7934 		 * to place an additional VN_HOLD here since we will
7935 		 * be hitting that VN_RELE again.
7936 		 */
7937 		VN_HOLD(nvp);
7938 
7939 		(void) nfs4_remove(ndvp, tmpname, cr, NULL, 0);
7940 
7941 		/* Undo the unlinked file naming stuff we just did */
7942 		mutex_enter(&rp->r_statelock);
7943 		if (rp->r_unldvp) {
7944 			VN_RELE(ndvp);
7945 			rp->r_unldvp = NULL;
7946 			if (rp->r_unlcred != NULL)
7947 				crfree(rp->r_unlcred);
7948 			rp->r_unlcred = NULL;
7949 			/* rp->r_unlanme points to tmpname */
7950 			if (rp->r_unlname)
7951 				kmem_free(rp->r_unlname, MAXNAMELEN);
7952 			rp->r_unlname = NULL;
7953 		}
7954 		mutex_exit(&rp->r_statelock);
7955 
7956 		if (nvp) {
7957 			VN_RELE(nvp);
7958 		}
7959 		goto link_call;
7960 	}
7961 
7962 	if (error) {
7963 		VN_RELE(ovp);
7964 		nfs_rw_exit(&odrp->r_rwlock);
7965 		nfs_rw_exit(&ndrp->r_rwlock);
7966 		if (nvp) {
7967 			VN_RELE(nvp);
7968 		}
7969 		return (error);
7970 	}
7971 
7972 	/*
7973 	 * when renaming directories to be a subdirectory of a
7974 	 * different parent, the dnlc entry for ".." will no
7975 	 * longer be valid, so it must be removed
7976 	 */
7977 	rp = VTOR4(ovp);
7978 	if (ndvp != odvp) {
7979 		if (ovp->v_type == VDIR) {
7980 			dnlc_remove(ovp, "..");
7981 			if (rp->r_dir != NULL)
7982 				nfs4_purge_rddir_cache(ovp);
7983 		}
7984 	}
7985 
7986 	/*
7987 	 * If we are renaming the unlinked file, update the
7988 	 * r_unldvp and r_unlname as needed.
7989 	 */
7990 	mutex_enter(&rp->r_statelock);
7991 	if (rp->r_unldvp != NULL) {
7992 		if (strcmp(rp->r_unlname, onm) == 0) {
7993 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
7994 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
7995 			if (ndvp != rp->r_unldvp) {
7996 				VN_RELE(rp->r_unldvp);
7997 				rp->r_unldvp = ndvp;
7998 				VN_HOLD(ndvp);
7999 			}
8000 		}
8001 	}
8002 	mutex_exit(&rp->r_statelock);
8003 
8004 	/*
8005 	 * Notify the rename vnevents to source vnode, and to the target
8006 	 * vnode if it already existed.
8007 	 */
8008 	if (error == 0) {
8009 		vnode_t *tvp;
8010 		rnode4_t *trp;
8011 		/*
8012 		 * Notify the vnode. Each links is represented by
8013 		 * a different vnode, in nfsv4.
8014 		 */
8015 		if (nvp) {
8016 			trp = VTOR4(nvp);
8017 			tvp = nvp;
8018 			if (IS_SHADOW(nvp, trp))
8019 				tvp = RTOV4(trp);
8020 			vnevent_rename_dest(tvp, ndvp, nnm, ct);
8021 		}
8022 
8023 		/*
8024 		 * if the source and destination directory are not the
8025 		 * same notify the destination directory.
8026 		 */
8027 		if (VTOR4(odvp) != VTOR4(ndvp)) {
8028 			trp = VTOR4(ndvp);
8029 			tvp = ndvp;
8030 			if (IS_SHADOW(ndvp, trp))
8031 				tvp = RTOV4(trp);
8032 			vnevent_rename_dest_dir(tvp, ct);
8033 		}
8034 
8035 		trp = VTOR4(ovp);
8036 		tvp = ovp;
8037 		if (IS_SHADOW(ovp, trp))
8038 			tvp = RTOV4(trp);
8039 		vnevent_rename_src(tvp, odvp, onm, ct);
8040 	}
8041 
8042 	if (nvp) {
8043 		VN_RELE(nvp);
8044 	}
8045 	VN_RELE(ovp);
8046 
8047 	nfs_rw_exit(&odrp->r_rwlock);
8048 	nfs_rw_exit(&ndrp->r_rwlock);
8049 
8050 	return (error);
8051 }
8052 
8053 /*
8054  * When the parent directory has changed, sv_dfh must be updated
8055  */
8056 static void
8057 update_parentdir_sfh(vnode_t *vp, vnode_t *ndvp)
8058 {
8059 	svnode_t *sv = VTOSV(vp);
8060 	nfs4_sharedfh_t *old_dfh = sv->sv_dfh;
8061 	nfs4_sharedfh_t *new_dfh = VTOR4(ndvp)->r_fh;
8062 
8063 	sfh4_hold(new_dfh);
8064 	sv->sv_dfh = new_dfh;
8065 	sfh4_rele(&old_dfh);
8066 }
8067 
8068 /*
8069  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
8070  * when it is known that the filehandle is persistent through rename.
8071  *
8072  * Rename requires that the current fh be the target directory and the
8073  * saved fh be the source directory. After the operation, the current fh
8074  * is unchanged.
8075  * The compound op structure for persistent fh rename is:
8076  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
8077  * Rather than bother with the directory postop args, we'll simply
8078  * update that a change occurred in the cache, so no post-op getattrs.
8079  */
8080 static int
8081 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
8082     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8083 {
8084 	COMPOUND4args_clnt args;
8085 	COMPOUND4res_clnt res, *resp = NULL;
8086 	nfs_argop4 *argop;
8087 	nfs_resop4 *resop;
8088 	int doqueue, argoplist_size;
8089 	mntinfo4_t *mi;
8090 	rnode4_t *odrp = VTOR4(odvp);
8091 	rnode4_t *ndrp = VTOR4(ndvp);
8092 	RENAME4res *rn_res;
8093 	bool_t needrecov;
8094 	nfs4_recov_state_t recov_state;
8095 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8096 	dirattr_info_t dinfo, *dinfop;
8097 
8098 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8099 
8100 	recov_state.rs_flags = 0;
8101 	recov_state.rs_num_retry_despite_err = 0;
8102 
8103 	/*
8104 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
8105 	 *
8106 	 * If source/target are different dirs, then append putfh(src); getattr
8107 	 */
8108 	args.array_len = (odvp == ndvp) ? 5 : 7;
8109 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8110 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8111 
8112 recov_retry:
8113 	*statp = NFS4_OK;
8114 
8115 	/* No need to Lookup the file, persistent fh */
8116 	args.ctag = TAG_RENAME;
8117 
8118 	mi = VTOMI4(odvp);
8119 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8120 	if (e.error) {
8121 		kmem_free(argop, argoplist_size);
8122 		return (e.error);
8123 	}
8124 
8125 	/* 0: putfh source directory */
8126 	argop[0].argop = OP_CPUTFH;
8127 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8128 
8129 	/* 1: Save source fh to free up current for target */
8130 	argop[1].argop = OP_SAVEFH;
8131 
8132 	/* 2: putfh targetdir */
8133 	argop[2].argop = OP_CPUTFH;
8134 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8135 
8136 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8137 	argop[3].argop = OP_CRENAME;
8138 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8139 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8140 
8141 	/* 4: getattr (targetdir) */
8142 	argop[4].argop = OP_GETATTR;
8143 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8144 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8145 
8146 	if (ndvp != odvp) {
8147 
8148 		/* 5: putfh (sourcedir) */
8149 		argop[5].argop = OP_CPUTFH;
8150 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8151 
8152 		/* 6: getattr (sourcedir) */
8153 		argop[6].argop = OP_GETATTR;
8154 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8155 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8156 	}
8157 
8158 	dnlc_remove(odvp, onm);
8159 	dnlc_remove(ndvp, nnm);
8160 
8161 	doqueue = 1;
8162 	dinfo.di_time_call = gethrtime();
8163 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8164 
8165 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8166 	if (e.error) {
8167 		PURGE_ATTRCACHE4(odvp);
8168 		PURGE_ATTRCACHE4(ndvp);
8169 	} else {
8170 		*statp = res.status;
8171 	}
8172 
8173 	if (needrecov) {
8174 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8175 		    OP_RENAME, NULL) == FALSE) {
8176 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8177 			if (!e.error)
8178 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8179 				    (caddr_t)&res);
8180 			goto recov_retry;
8181 		}
8182 	}
8183 
8184 	if (!e.error) {
8185 		resp = &res;
8186 		/*
8187 		 * as long as OP_RENAME
8188 		 */
8189 		if (res.status != NFS4_OK && res.array_len <= 4) {
8190 			e.error = geterrno4(res.status);
8191 			PURGE_ATTRCACHE4(odvp);
8192 			PURGE_ATTRCACHE4(ndvp);
8193 			/*
8194 			 * System V defines rename to return EEXIST, not
8195 			 * ENOTEMPTY if the target directory is not empty.
8196 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8197 			 * which geterrno4 maps to ENOTEMPTY.
8198 			 */
8199 			if (e.error == ENOTEMPTY)
8200 				e.error = EEXIST;
8201 		} else {
8202 
8203 			resop = &res.array[3];	/* rename res */
8204 			rn_res = &resop->nfs_resop4_u.oprename;
8205 
8206 			if (res.status == NFS4_OK) {
8207 				/*
8208 				 * Update target attribute, readdir and dnlc
8209 				 * caches.
8210 				 */
8211 				dinfo.di_garp =
8212 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8213 				dinfo.di_cred = cr;
8214 				dinfop = &dinfo;
8215 			} else
8216 				dinfop = NULL;
8217 
8218 			nfs4_update_dircaches(&rn_res->target_cinfo,
8219 			    ndvp, NULL, NULL, dinfop);
8220 
8221 			/*
8222 			 * Update source attribute, readdir and dnlc caches
8223 			 *
8224 			 */
8225 			if (ndvp != odvp) {
8226 				update_parentdir_sfh(renvp, ndvp);
8227 
8228 				if (dinfop)
8229 					dinfo.di_garp =
8230 					    &(res.array[6].nfs_resop4_u.
8231 					    opgetattr.ga_res);
8232 
8233 				nfs4_update_dircaches(&rn_res->source_cinfo,
8234 				    odvp, NULL, NULL, dinfop);
8235 			}
8236 
8237 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8238 			    nnm);
8239 		}
8240 	}
8241 
8242 	if (resp)
8243 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8244 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8245 	kmem_free(argop, argoplist_size);
8246 
8247 	return (e.error);
8248 }
8249 
8250 /*
8251  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8252  * it is possible for the filehandle to change due to the rename.
8253  *
8254  * The compound req in this case includes a post-rename lookup and getattr
8255  * to ensure that we have the correct fh and attributes for the object.
8256  *
8257  * Rename requires that the current fh be the target directory and the
8258  * saved fh be the source directory. After the operation, the current fh
8259  * is unchanged.
8260  *
8261  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8262  * update the filehandle for the renamed object.  We also get the old
8263  * filehandle for historical reasons; this should be taken out sometime.
8264  * This results in a rather cumbersome compound...
8265  *
8266  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8267  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8268  *
8269  */
8270 static int
8271 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8272     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8273 {
8274 	COMPOUND4args_clnt args;
8275 	COMPOUND4res_clnt res, *resp = NULL;
8276 	int argoplist_size;
8277 	nfs_argop4 *argop;
8278 	nfs_resop4 *resop;
8279 	int doqueue;
8280 	mntinfo4_t *mi;
8281 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8282 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8283 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8284 	RENAME4res *rn_res;
8285 	GETFH4res *ngf_res;
8286 	bool_t needrecov;
8287 	nfs4_recov_state_t recov_state;
8288 	hrtime_t t;
8289 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8290 	dirattr_info_t dinfo, *dinfop = &dinfo;
8291 
8292 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8293 
8294 	recov_state.rs_flags = 0;
8295 	recov_state.rs_num_retry_despite_err = 0;
8296 
8297 recov_retry:
8298 	*statp = NFS4_OK;
8299 
8300 	/*
8301 	 * There is a window between the RPC and updating the path and
8302 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8303 	 * code, so that it doesn't try to use the old path during that
8304 	 * window.
8305 	 */
8306 	mutex_enter(&orp->r_statelock);
8307 	while (orp->r_flags & R4RECEXPFH) {
8308 		klwp_t *lwp = ttolwp(curthread);
8309 
8310 		if (lwp != NULL)
8311 			lwp->lwp_nostop++;
8312 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8313 			mutex_exit(&orp->r_statelock);
8314 			if (lwp != NULL)
8315 				lwp->lwp_nostop--;
8316 			return (EINTR);
8317 		}
8318 		if (lwp != NULL)
8319 			lwp->lwp_nostop--;
8320 	}
8321 	orp->r_flags |= R4RECEXPFH;
8322 	mutex_exit(&orp->r_statelock);
8323 
8324 	mi = VTOMI4(odvp);
8325 
8326 	args.ctag = TAG_RENAME_VFH;
8327 	args.array_len = (odvp == ndvp) ? 10 : 12;
8328 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8329 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8330 
8331 	/*
8332 	 * Rename ops:
8333 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8334 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8335 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8336 	 *
8337 	 *    if (odvp != ndvp)
8338 	 *	add putfh(sourcedir), getattr(sourcedir) }
8339 	 */
8340 	args.array = argop;
8341 
8342 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8343 	    &recov_state, NULL);
8344 	if (e.error) {
8345 		kmem_free(argop, argoplist_size);
8346 		mutex_enter(&orp->r_statelock);
8347 		orp->r_flags &= ~R4RECEXPFH;
8348 		cv_broadcast(&orp->r_cv);
8349 		mutex_exit(&orp->r_statelock);
8350 		return (e.error);
8351 	}
8352 
8353 	/* 0: putfh source directory */
8354 	argop[0].argop = OP_CPUTFH;
8355 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8356 
8357 	/* 1: Save source fh to free up current for target */
8358 	argop[1].argop = OP_SAVEFH;
8359 
8360 	/* 2: Lookup pre-rename fh of renamed object */
8361 	argop[2].argop = OP_CLOOKUP;
8362 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8363 
8364 	/* 3: getfh fh of renamed object (before rename) */
8365 	argop[3].argop = OP_GETFH;
8366 
8367 	/* 4: putfh targetdir */
8368 	argop[4].argop = OP_CPUTFH;
8369 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8370 
8371 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8372 	argop[5].argop = OP_CRENAME;
8373 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8374 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8375 
8376 	/* 6: getattr of target dir (post op attrs) */
8377 	argop[6].argop = OP_GETATTR;
8378 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8379 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8380 
8381 	/* 7: Lookup post-rename fh of renamed object */
8382 	argop[7].argop = OP_CLOOKUP;
8383 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8384 
8385 	/* 8: getfh fh of renamed object (after rename) */
8386 	argop[8].argop = OP_GETFH;
8387 
8388 	/* 9: getattr of renamed object */
8389 	argop[9].argop = OP_GETATTR;
8390 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8391 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8392 
8393 	/*
8394 	 * If source/target dirs are different, then get new post-op
8395 	 * attrs for source dir also.
8396 	 */
8397 	if (ndvp != odvp) {
8398 		/* 10: putfh (sourcedir) */
8399 		argop[10].argop = OP_CPUTFH;
8400 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8401 
8402 		/* 11: getattr (sourcedir) */
8403 		argop[11].argop = OP_GETATTR;
8404 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8405 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8406 	}
8407 
8408 	dnlc_remove(odvp, onm);
8409 	dnlc_remove(ndvp, nnm);
8410 
8411 	doqueue = 1;
8412 	t = gethrtime();
8413 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8414 
8415 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8416 	if (e.error) {
8417 		PURGE_ATTRCACHE4(odvp);
8418 		PURGE_ATTRCACHE4(ndvp);
8419 		if (!needrecov) {
8420 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8421 			    &recov_state, needrecov);
8422 			goto out;
8423 		}
8424 	} else {
8425 		*statp = res.status;
8426 	}
8427 
8428 	if (needrecov) {
8429 		bool_t abort;
8430 
8431 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8432 		    OP_RENAME, NULL);
8433 		if (abort == FALSE) {
8434 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8435 			    &recov_state, needrecov);
8436 			kmem_free(argop, argoplist_size);
8437 			if (!e.error)
8438 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8439 				    (caddr_t)&res);
8440 			mutex_enter(&orp->r_statelock);
8441 			orp->r_flags &= ~R4RECEXPFH;
8442 			cv_broadcast(&orp->r_cv);
8443 			mutex_exit(&orp->r_statelock);
8444 			goto recov_retry;
8445 		} else {
8446 			if (e.error != 0) {
8447 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8448 				    &recov_state, needrecov);
8449 				goto out;
8450 			}
8451 			/* fall through for res.status case */
8452 		}
8453 	}
8454 
8455 	resp = &res;
8456 	/*
8457 	 * If OP_RENAME (or any prev op) failed, then return an error.
8458 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8459 	 */
8460 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8461 		/*
8462 		 * Error in an op other than last Getattr
8463 		 */
8464 		e.error = geterrno4(res.status);
8465 		PURGE_ATTRCACHE4(odvp);
8466 		PURGE_ATTRCACHE4(ndvp);
8467 		/*
8468 		 * System V defines rename to return EEXIST, not
8469 		 * ENOTEMPTY if the target directory is not empty.
8470 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8471 		 * which geterrno4 maps to ENOTEMPTY.
8472 		 */
8473 		if (e.error == ENOTEMPTY)
8474 			e.error = EEXIST;
8475 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8476 		    needrecov);
8477 		goto out;
8478 	}
8479 
8480 	/* rename results */
8481 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8482 
8483 	if (res.status == NFS4_OK) {
8484 		/* Update target attribute, readdir and dnlc caches */
8485 		dinfo.di_garp =
8486 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
8487 		dinfo.di_cred = cr;
8488 		dinfo.di_time_call = t;
8489 	} else
8490 		dinfop = NULL;
8491 
8492 	/* Update source cache attribute, readdir and dnlc caches */
8493 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8494 
8495 	/* Update source cache attribute, readdir and dnlc caches */
8496 	if (ndvp != odvp) {
8497 		update_parentdir_sfh(ovp, ndvp);
8498 
8499 		/*
8500 		 * If dinfop is non-NULL, then compound succeded, so
8501 		 * set di_garp to attrs for source dir.  dinfop is only
8502 		 * set to NULL when compound fails.
8503 		 */
8504 		if (dinfop)
8505 			dinfo.di_garp =
8506 			    &res.array[11].nfs_resop4_u.opgetattr.ga_res;
8507 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8508 		    dinfop);
8509 	}
8510 
8511 	/*
8512 	 * Update the rnode with the new component name and args,
8513 	 * and if the file handle changed, also update it with the new fh.
8514 	 * This is only necessary if the target object has an rnode
8515 	 * entry and there is no need to create one for it.
8516 	 */
8517 	resop = &res.array[8];	/* getfh new res */
8518 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8519 
8520 	/*
8521 	 * Update the path and filehandle for the renamed object.
8522 	 */
8523 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8524 
8525 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8526 
8527 	if (res.status == NFS4_OK) {
8528 		resop++;	/* getattr res */
8529 		e.error = nfs4_update_attrcache(res.status,
8530 		    &resop->nfs_resop4_u.opgetattr.ga_res,
8531 		    t, ovp, cr);
8532 	}
8533 
8534 out:
8535 	kmem_free(argop, argoplist_size);
8536 	if (resp)
8537 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8538 	mutex_enter(&orp->r_statelock);
8539 	orp->r_flags &= ~R4RECEXPFH;
8540 	cv_broadcast(&orp->r_cv);
8541 	mutex_exit(&orp->r_statelock);
8542 
8543 	return (e.error);
8544 }
8545 
8546 /* ARGSUSED */
8547 static int
8548 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr,
8549     caller_context_t *ct, int flags, vsecattr_t *vsecp)
8550 {
8551 	int error;
8552 	vnode_t *vp;
8553 
8554 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8555 		return (EPERM);
8556 	/*
8557 	 * As ".." has special meaning and rather than send a mkdir
8558 	 * over the wire to just let the server freak out, we just
8559 	 * short circuit it here and return EEXIST
8560 	 */
8561 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8562 		return (EEXIST);
8563 
8564 	/*
8565 	 * Decision to get the right gid and setgid bit of the
8566 	 * new directory is now made in call_nfs4_create_req.
8567 	 */
8568 	va->va_mask |= AT_MODE;
8569 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8570 	if (error)
8571 		return (error);
8572 
8573 	*vpp = vp;
8574 	return (0);
8575 }
8576 
8577 
8578 /*
8579  * rmdir is using the same remove v4 op as does remove.
8580  * Remove requires that the current fh be the target directory.
8581  * After the operation, the current fh is unchanged.
8582  * The compound op structure is:
8583  *      PUTFH(targetdir), REMOVE
8584  */
8585 /*ARGSUSED4*/
8586 static int
8587 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr,
8588     caller_context_t *ct, int flags)
8589 {
8590 	int need_end_op = FALSE;
8591 	COMPOUND4args_clnt args;
8592 	COMPOUND4res_clnt res, *resp = NULL;
8593 	REMOVE4res *rm_res;
8594 	nfs_argop4 argop[3];
8595 	nfs_resop4 *resop;
8596 	vnode_t *vp;
8597 	int doqueue;
8598 	mntinfo4_t *mi;
8599 	rnode4_t *drp;
8600 	bool_t needrecov = FALSE;
8601 	nfs4_recov_state_t recov_state;
8602 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8603 	dirattr_info_t dinfo, *dinfop;
8604 
8605 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8606 		return (EPERM);
8607 	/*
8608 	 * As ".." has special meaning and rather than send a rmdir
8609 	 * over the wire to just let the server freak out, we just
8610 	 * short circuit it here and return EEXIST
8611 	 */
8612 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8613 		return (EEXIST);
8614 
8615 	drp = VTOR4(dvp);
8616 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8617 		return (EINTR);
8618 
8619 	/*
8620 	 * Attempt to prevent a rmdir(".") from succeeding.
8621 	 */
8622 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8623 	if (e.error) {
8624 		nfs_rw_exit(&drp->r_rwlock);
8625 		return (e.error);
8626 	}
8627 	if (vp == cdir) {
8628 		VN_RELE(vp);
8629 		nfs_rw_exit(&drp->r_rwlock);
8630 		return (EINVAL);
8631 	}
8632 
8633 	/*
8634 	 * Since nfsv4 remove op works on both files and directories,
8635 	 * check that the removed object is indeed a directory.
8636 	 */
8637 	if (vp->v_type != VDIR) {
8638 		VN_RELE(vp);
8639 		nfs_rw_exit(&drp->r_rwlock);
8640 		return (ENOTDIR);
8641 	}
8642 
8643 	/*
8644 	 * First just remove the entry from the name cache, as it
8645 	 * is most likely an entry for this vp.
8646 	 */
8647 	dnlc_remove(dvp, nm);
8648 
8649 	/*
8650 	 * If there vnode reference count is greater than one, then
8651 	 * there may be additional references in the DNLC which will
8652 	 * need to be purged.  First, trying removing the entry for
8653 	 * the parent directory and see if that removes the additional
8654 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8655 	 * to completely remove any references to the directory which
8656 	 * might still exist in the DNLC.
8657 	 */
8658 	if (vp->v_count > 1) {
8659 		dnlc_remove(vp, "..");
8660 		if (vp->v_count > 1)
8661 			dnlc_purge_vp(vp);
8662 	}
8663 
8664 	mi = VTOMI4(dvp);
8665 	recov_state.rs_flags = 0;
8666 	recov_state.rs_num_retry_despite_err = 0;
8667 
8668 recov_retry:
8669 	args.ctag = TAG_RMDIR;
8670 
8671 	/*
8672 	 * Rmdir ops: putfh dir; remove
8673 	 */
8674 	args.array_len = 3;
8675 	args.array = argop;
8676 
8677 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8678 	if (e.error) {
8679 		nfs_rw_exit(&drp->r_rwlock);
8680 		return (e.error);
8681 	}
8682 	need_end_op = TRUE;
8683 
8684 	/* putfh directory */
8685 	argop[0].argop = OP_CPUTFH;
8686 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8687 
8688 	/* remove */
8689 	argop[1].argop = OP_CREMOVE;
8690 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8691 
8692 	/* getattr (postop attrs for dir that contained removed dir) */
8693 	argop[2].argop = OP_GETATTR;
8694 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8695 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8696 
8697 	dinfo.di_time_call = gethrtime();
8698 	doqueue = 1;
8699 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8700 
8701 	PURGE_ATTRCACHE4(vp);
8702 
8703 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8704 	if (e.error) {
8705 		PURGE_ATTRCACHE4(dvp);
8706 	}
8707 
8708 	if (needrecov) {
8709 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8710 		    NULL, OP_REMOVE, NULL) == FALSE) {
8711 			if (!e.error)
8712 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8713 				    (caddr_t)&res);
8714 
8715 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8716 			    needrecov);
8717 			need_end_op = FALSE;
8718 			goto recov_retry;
8719 		}
8720 	}
8721 
8722 	if (!e.error) {
8723 		resp = &res;
8724 
8725 		/*
8726 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8727 		 * failed.
8728 		 */
8729 		if (res.status != NFS4_OK && res.array_len <= 2) {
8730 			e.error = geterrno4(res.status);
8731 			PURGE_ATTRCACHE4(dvp);
8732 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8733 			    &recov_state, needrecov);
8734 			need_end_op = FALSE;
8735 			nfs4_purge_stale_fh(e.error, dvp, cr);
8736 			/*
8737 			 * System V defines rmdir to return EEXIST, not
8738 			 * ENOTEMPTY if the directory is not empty.  Over
8739 			 * the wire, the error is NFSERR_ENOTEMPTY which
8740 			 * geterrno4 maps to ENOTEMPTY.
8741 			 */
8742 			if (e.error == ENOTEMPTY)
8743 				e.error = EEXIST;
8744 		} else {
8745 			resop = &res.array[1];	/* remove res */
8746 			rm_res = &resop->nfs_resop4_u.opremove;
8747 
8748 			if (res.status == NFS4_OK) {
8749 				resop = &res.array[2];	/* dir attrs */
8750 				dinfo.di_garp =
8751 				    &resop->nfs_resop4_u.opgetattr.ga_res;
8752 				dinfo.di_cred = cr;
8753 				dinfop = &dinfo;
8754 			} else
8755 				dinfop = NULL;
8756 
8757 			/* Update dir attribute, readdir and dnlc caches */
8758 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8759 			    dinfop);
8760 
8761 			/* destroy rddir cache for dir that was removed */
8762 			if (VTOR4(vp)->r_dir != NULL)
8763 				nfs4_purge_rddir_cache(vp);
8764 		}
8765 	}
8766 
8767 	if (need_end_op)
8768 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8769 
8770 	nfs_rw_exit(&drp->r_rwlock);
8771 
8772 	if (resp)
8773 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8774 
8775 	if (e.error == 0) {
8776 		vnode_t *tvp;
8777 		rnode4_t *trp;
8778 		trp = VTOR4(vp);
8779 		tvp = vp;
8780 		if (IS_SHADOW(vp, trp))
8781 			tvp = RTOV4(trp);
8782 		vnevent_rmdir(tvp, dvp, nm, ct);
8783 	}
8784 
8785 	VN_RELE(vp);
8786 
8787 	return (e.error);
8788 }
8789 
8790 /* ARGSUSED */
8791 static int
8792 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr,
8793     caller_context_t *ct, int flags)
8794 {
8795 	int error;
8796 	vnode_t *vp;
8797 	rnode4_t *rp;
8798 	char *contents;
8799 	mntinfo4_t *mi = VTOMI4(dvp);
8800 
8801 	if (nfs_zone() != mi->mi_zone)
8802 		return (EPERM);
8803 	if (!(mi->mi_flags & MI4_SYMLINK))
8804 		return (EOPNOTSUPP);
8805 
8806 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8807 	if (error)
8808 		return (error);
8809 
8810 	ASSERT(nfs4_consistent_type(vp));
8811 	rp = VTOR4(vp);
8812 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8813 
8814 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8815 
8816 		if (contents != NULL) {
8817 			mutex_enter(&rp->r_statelock);
8818 			if (rp->r_symlink.contents == NULL) {
8819 				rp->r_symlink.len = strlen(tnm);
8820 				bcopy(tnm, contents, rp->r_symlink.len);
8821 				rp->r_symlink.contents = contents;
8822 				rp->r_symlink.size = MAXPATHLEN;
8823 				mutex_exit(&rp->r_statelock);
8824 			} else {
8825 				mutex_exit(&rp->r_statelock);
8826 				kmem_free((void *)contents, MAXPATHLEN);
8827 			}
8828 		}
8829 	}
8830 	VN_RELE(vp);
8831 
8832 	return (error);
8833 }
8834 
8835 
8836 /*
8837  * Read directory entries.
8838  * There are some weird things to look out for here.  The uio_loffset
8839  * field is either 0 or it is the offset returned from a previous
8840  * readdir.  It is an opaque value used by the server to find the
8841  * correct directory block to read. The count field is the number
8842  * of blocks to read on the server.  This is advisory only, the server
8843  * may return only one block's worth of entries.  Entries may be compressed
8844  * on the server.
8845  */
8846 /* ARGSUSED */
8847 static int
8848 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp,
8849 	caller_context_t *ct, int flags)
8850 {
8851 	int error;
8852 	uint_t count;
8853 	rnode4_t *rp;
8854 	rddir4_cache *rdc;
8855 	rddir4_cache *rrdc;
8856 
8857 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8858 		return (EIO);
8859 	rp = VTOR4(vp);
8860 
8861 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8862 
8863 	/*
8864 	 * Make sure that the directory cache is valid.
8865 	 */
8866 	if (rp->r_dir != NULL) {
8867 		if (nfs_disable_rddir_cache != 0) {
8868 			/*
8869 			 * Setting nfs_disable_rddir_cache in /etc/system
8870 			 * allows interoperability with servers that do not
8871 			 * properly update the attributes of directories.
8872 			 * Any cached information gets purged before an
8873 			 * access is made to it.
8874 			 */
8875 			nfs4_purge_rddir_cache(vp);
8876 		}
8877 
8878 		error = nfs4_validate_caches(vp, cr);
8879 		if (error)
8880 			return (error);
8881 	}
8882 
8883 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8884 
8885 	/*
8886 	 * Short circuit last readdir which always returns 0 bytes.
8887 	 * This can be done after the directory has been read through
8888 	 * completely at least once.  This will set r_direof which
8889 	 * can be used to find the value of the last cookie.
8890 	 */
8891 	mutex_enter(&rp->r_statelock);
8892 	if (rp->r_direof != NULL &&
8893 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8894 		mutex_exit(&rp->r_statelock);
8895 #ifdef DEBUG
8896 		nfs4_readdir_cache_shorts++;
8897 #endif
8898 		if (eofp)
8899 			*eofp = 1;
8900 		return (0);
8901 	}
8902 
8903 	/*
8904 	 * Look for a cache entry.  Cache entries are identified
8905 	 * by the NFS cookie value and the byte count requested.
8906 	 */
8907 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8908 
8909 	/*
8910 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8911 	 */
8912 	if (rdc == NULL) {
8913 		mutex_exit(&rp->r_statelock);
8914 		return (EINTR);
8915 	}
8916 
8917 	/*
8918 	 * Check to see if we need to fill this entry in.
8919 	 */
8920 	if (rdc->flags & RDDIRREQ) {
8921 		rdc->flags &= ~RDDIRREQ;
8922 		rdc->flags |= RDDIR;
8923 		mutex_exit(&rp->r_statelock);
8924 
8925 		/*
8926 		 * Do the readdir.
8927 		 */
8928 		nfs4readdir(vp, rdc, cr);
8929 
8930 		/*
8931 		 * Reacquire the lock, so that we can continue
8932 		 */
8933 		mutex_enter(&rp->r_statelock);
8934 		/*
8935 		 * The entry is now complete
8936 		 */
8937 		rdc->flags &= ~RDDIR;
8938 	}
8939 
8940 	ASSERT(!(rdc->flags & RDDIR));
8941 
8942 	/*
8943 	 * If an error occurred while attempting
8944 	 * to fill the cache entry, mark the entry invalid and
8945 	 * just return the error.
8946 	 */
8947 	if (rdc->error) {
8948 		error = rdc->error;
8949 		rdc->flags |= RDDIRREQ;
8950 		rddir4_cache_rele(rp, rdc);
8951 		mutex_exit(&rp->r_statelock);
8952 		return (error);
8953 	}
8954 
8955 	/*
8956 	 * The cache entry is complete and good,
8957 	 * copyout the dirent structs to the calling
8958 	 * thread.
8959 	 */
8960 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
8961 
8962 	/*
8963 	 * If no error occurred during the copyout,
8964 	 * update the offset in the uio struct to
8965 	 * contain the value of the next NFS 4 cookie
8966 	 * and set the eof value appropriately.
8967 	 */
8968 	if (!error) {
8969 		uiop->uio_loffset = rdc->nfs4_ncookie;
8970 		if (eofp)
8971 			*eofp = rdc->eof;
8972 	}
8973 
8974 	/*
8975 	 * Decide whether to do readahead.  Don't if we
8976 	 * have already read to the end of directory.
8977 	 */
8978 	if (rdc->eof) {
8979 		/*
8980 		 * Make the entry the direof only if it is cached
8981 		 */
8982 		if (rdc->flags & RDDIRCACHED)
8983 			rp->r_direof = rdc;
8984 		rddir4_cache_rele(rp, rdc);
8985 		mutex_exit(&rp->r_statelock);
8986 		return (error);
8987 	}
8988 
8989 	/* Determine if a readdir readahead should be done */
8990 	if (!(rp->r_flags & R4LOOKUP)) {
8991 		rddir4_cache_rele(rp, rdc);
8992 		mutex_exit(&rp->r_statelock);
8993 		return (error);
8994 	}
8995 
8996 	/*
8997 	 * Now look for a readahead entry.
8998 	 *
8999 	 * Check to see whether we found an entry for the readahead.
9000 	 * If so, we don't need to do anything further, so free the new
9001 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
9002 	 * it to the cache, and then initiate an asynchronous readdir
9003 	 * operation to fill it.
9004 	 */
9005 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
9006 
9007 	/*
9008 	 * A readdir cache entry could not be obtained for the readahead.  In
9009 	 * this case we skip the readahead and return.
9010 	 */
9011 	if (rrdc == NULL) {
9012 		rddir4_cache_rele(rp, rdc);
9013 		mutex_exit(&rp->r_statelock);
9014 		return (error);
9015 	}
9016 
9017 	/*
9018 	 * Check to see if we need to fill this entry in.
9019 	 */
9020 	if (rrdc->flags & RDDIRREQ) {
9021 		rrdc->flags &= ~RDDIRREQ;
9022 		rrdc->flags |= RDDIR;
9023 		rddir4_cache_rele(rp, rdc);
9024 		mutex_exit(&rp->r_statelock);
9025 #ifdef DEBUG
9026 		nfs4_readdir_readahead++;
9027 #endif
9028 		/*
9029 		 * Do the readdir.
9030 		 */
9031 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
9032 		return (error);
9033 	}
9034 
9035 	rddir4_cache_rele(rp, rrdc);
9036 	rddir4_cache_rele(rp, rdc);
9037 	mutex_exit(&rp->r_statelock);
9038 	return (error);
9039 }
9040 
9041 static int
9042 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9043 {
9044 	int error;
9045 	rnode4_t *rp;
9046 
9047 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9048 
9049 	rp = VTOR4(vp);
9050 
9051 	/*
9052 	 * Obtain the readdir results for the caller.
9053 	 */
9054 	nfs4readdir(vp, rdc, cr);
9055 
9056 	mutex_enter(&rp->r_statelock);
9057 	/*
9058 	 * The entry is now complete
9059 	 */
9060 	rdc->flags &= ~RDDIR;
9061 
9062 	error = rdc->error;
9063 	if (error)
9064 		rdc->flags |= RDDIRREQ;
9065 	rddir4_cache_rele(rp, rdc);
9066 	mutex_exit(&rp->r_statelock);
9067 
9068 	return (error);
9069 }
9070 
9071 /*
9072  * Read directory entries.
9073  * There are some weird things to look out for here.  The uio_loffset
9074  * field is either 0 or it is the offset returned from a previous
9075  * readdir.  It is an opaque value used by the server to find the
9076  * correct directory block to read. The count field is the number
9077  * of blocks to read on the server.  This is advisory only, the server
9078  * may return only one block's worth of entries.  Entries may be compressed
9079  * on the server.
9080  *
9081  * Generates the following compound request:
9082  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9083  *    must include a Lookupp as well. In this case, send:
9084  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9085  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9086  *
9087  * Get complete attributes and filehandles for entries if this is the
9088  * first read of the directory. Otherwise, just get fileid's.
9089  */
9090 static void
9091 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9092 {
9093 	COMPOUND4args_clnt args;
9094 	COMPOUND4res_clnt res;
9095 	READDIR4args *rargs;
9096 	READDIR4res_clnt *rd_res;
9097 	bitmap4 rd_bitsval;
9098 	nfs_argop4 argop[5];
9099 	nfs_resop4 *resop;
9100 	rnode4_t *rp = VTOR4(vp);
9101 	mntinfo4_t *mi = VTOMI4(vp);
9102 	int doqueue;
9103 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9104 	vnode_t *dvp;
9105 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9106 	int num_ops, res_opcnt;
9107 	bool_t needrecov = FALSE;
9108 	nfs4_recov_state_t recov_state;
9109 	hrtime_t t;
9110 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9111 
9112 	ASSERT(nfs_zone() == mi->mi_zone);
9113 	ASSERT(rdc->flags & RDDIR);
9114 	ASSERT(rdc->entries == NULL);
9115 
9116 	/*
9117 	 * If rp were a stub, it should have triggered and caused
9118 	 * a mount for us to get this far.
9119 	 */
9120 	ASSERT(!RP_ISSTUB(rp));
9121 
9122 	num_ops = 2;
9123 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9124 		/*
9125 		 * Since nfsv4 readdir may not return entries for "." and "..",
9126 		 * the client must recreate them:
9127 		 * To find the correct nodeid, do the following:
9128 		 * For current node, get nodeid from dnlc.
9129 		 * - if current node is rootvp, set pnodeid to nodeid.
9130 		 * - else if parent is in the dnlc, get its nodeid from there.
9131 		 * - else add LOOKUPP+GETATTR to compound.
9132 		 */
9133 		nodeid = rp->r_attr.va_nodeid;
9134 		if (vp->v_flag & VROOT) {
9135 			pnodeid = nodeid;	/* root of mount point */
9136 		} else {
9137 			dvp = dnlc_lookup(vp, "..");
9138 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9139 				/* parent in dnlc cache - no need for otw */
9140 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9141 			} else {
9142 				/*
9143 				 * parent not in dnlc cache,
9144 				 * do lookupp to get its id
9145 				 */
9146 				num_ops = 5;
9147 				pnodeid = 0; /* set later by getattr parent */
9148 			}
9149 			if (dvp)
9150 				VN_RELE(dvp);
9151 		}
9152 	}
9153 	recov_state.rs_flags = 0;
9154 	recov_state.rs_num_retry_despite_err = 0;
9155 
9156 	/* Save the original mount point security flavor */
9157 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9158 
9159 recov_retry:
9160 	args.ctag = TAG_READDIR;
9161 
9162 	args.array = argop;
9163 	args.array_len = num_ops;
9164 
9165 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9166 	    &recov_state, NULL)) {
9167 		/*
9168 		 * If readdir a node that is a stub for a crossed mount point,
9169 		 * keep the original secinfo flavor for the current file
9170 		 * system, not the crossed one.
9171 		 */
9172 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9173 		rdc->error = e.error;
9174 		return;
9175 	}
9176 
9177 	/*
9178 	 * Determine which attrs to request for dirents.  This code
9179 	 * must be protected by nfs4_start/end_fop because of r_server
9180 	 * (which will change during failover recovery).
9181 	 *
9182 	 */
9183 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9184 		/*
9185 		 * Get all vattr attrs plus filehandle and rdattr_error
9186 		 */
9187 		rd_bitsval = NFS4_VATTR_MASK |
9188 		    FATTR4_RDATTR_ERROR_MASK |
9189 		    FATTR4_FILEHANDLE_MASK;
9190 
9191 		if (rp->r_flags & R4READDIRWATTR) {
9192 			mutex_enter(&rp->r_statelock);
9193 			rp->r_flags &= ~R4READDIRWATTR;
9194 			mutex_exit(&rp->r_statelock);
9195 		}
9196 	} else {
9197 		servinfo4_t *svp = rp->r_server;
9198 
9199 		/*
9200 		 * Already read directory. Use readdir with
9201 		 * no attrs (except for mounted_on_fileid) for updates.
9202 		 */
9203 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9204 
9205 		/*
9206 		 * request mounted on fileid if supported, else request
9207 		 * fileid.  maybe we should verify that fileid is supported
9208 		 * and request something else if not.
9209 		 */
9210 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9211 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9212 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9213 		nfs_rw_exit(&svp->sv_lock);
9214 	}
9215 
9216 	/* putfh directory fh */
9217 	argop[0].argop = OP_CPUTFH;
9218 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9219 
9220 	argop[1].argop = OP_READDIR;
9221 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9222 	/*
9223 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9224 	 * cookie 0 should be used over-the-wire to start reading at
9225 	 * the beginning of the directory excluding "." and "..".
9226 	 */
9227 	if (rdc->nfs4_cookie == 0 ||
9228 	    rdc->nfs4_cookie == 1 ||
9229 	    rdc->nfs4_cookie == 2) {
9230 		rargs->cookie = (nfs_cookie4)0;
9231 		rargs->cookieverf = 0;
9232 	} else {
9233 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9234 		mutex_enter(&rp->r_statelock);
9235 		rargs->cookieverf = rp->r_cookieverf4;
9236 		mutex_exit(&rp->r_statelock);
9237 	}
9238 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9239 	rargs->maxcount = mi->mi_tsize;
9240 	rargs->attr_request = rd_bitsval;
9241 	rargs->rdc = rdc;
9242 	rargs->dvp = vp;
9243 	rargs->mi = mi;
9244 	rargs->cr = cr;
9245 
9246 
9247 	/*
9248 	 * If count < than the minimum required, we return no entries
9249 	 * and fail with EINVAL
9250 	 */
9251 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9252 		rdc->error = EINVAL;
9253 		goto out;
9254 	}
9255 
9256 	if (args.array_len == 5) {
9257 		/*
9258 		 * Add lookupp and getattr for parent nodeid.
9259 		 */
9260 		argop[2].argop = OP_LOOKUPP;
9261 
9262 		argop[3].argop = OP_GETFH;
9263 
9264 		/* getattr parent */
9265 		argop[4].argop = OP_GETATTR;
9266 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9267 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9268 	}
9269 
9270 	doqueue = 1;
9271 
9272 	if (mi->mi_io_kstats) {
9273 		mutex_enter(&mi->mi_lock);
9274 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9275 		mutex_exit(&mi->mi_lock);
9276 	}
9277 
9278 	/* capture the time of this call */
9279 	rargs->t = t = gethrtime();
9280 
9281 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9282 
9283 	if (mi->mi_io_kstats) {
9284 		mutex_enter(&mi->mi_lock);
9285 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9286 		mutex_exit(&mi->mi_lock);
9287 	}
9288 
9289 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9290 
9291 	/*
9292 	 * If RPC error occurred and it isn't an error that
9293 	 * triggers recovery, then go ahead and fail now.
9294 	 */
9295 	if (e.error != 0 && !needrecov) {
9296 		rdc->error = e.error;
9297 		goto out;
9298 	}
9299 
9300 	if (needrecov) {
9301 		bool_t abort;
9302 
9303 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9304 		    "nfs4readdir: initiating recovery.\n"));
9305 
9306 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9307 		    NULL, OP_READDIR, NULL);
9308 		if (abort == FALSE) {
9309 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9310 			    &recov_state, needrecov);
9311 			if (!e.error)
9312 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9313 				    (caddr_t)&res);
9314 			if (rdc->entries != NULL) {
9315 				kmem_free(rdc->entries, rdc->entlen);
9316 				rdc->entries = NULL;
9317 			}
9318 			goto recov_retry;
9319 		}
9320 
9321 		if (e.error != 0) {
9322 			rdc->error = e.error;
9323 			goto out;
9324 		}
9325 
9326 		/* fall through for res.status case */
9327 	}
9328 
9329 	res_opcnt = res.array_len;
9330 
9331 	/*
9332 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9333 	 * failure here.  Subsequent ops are for filling out dot-dot
9334 	 * dirent, and if they fail, we still want to give the caller
9335 	 * the dirents returned by (the successful) READDIR op, so we need
9336 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9337 	 *
9338 	 * One example where PUTFH+READDIR ops would succeed but
9339 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9340 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9341 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9342 	 * x perm.  We need to come up with a non-vendor-specific way
9343 	 * for a POSIX server to return d_ino from dotdot's dirent if
9344 	 * client only requests mounted_on_fileid, and just say the
9345 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9346 	 * client requested any mandatory attrs, server would be required
9347 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9348 	 * for dotdot.
9349 	 */
9350 
9351 	if (res.status) {
9352 		if (res_opcnt <= 2) {
9353 			e.error = geterrno4(res.status);
9354 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9355 			    &recov_state, needrecov);
9356 			nfs4_purge_stale_fh(e.error, vp, cr);
9357 			rdc->error = e.error;
9358 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9359 			if (rdc->entries != NULL) {
9360 				kmem_free(rdc->entries, rdc->entlen);
9361 				rdc->entries = NULL;
9362 			}
9363 			/*
9364 			 * If readdir a node that is a stub for a
9365 			 * crossed mount point, keep the original
9366 			 * secinfo flavor for the current file system,
9367 			 * not the crossed one.
9368 			 */
9369 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9370 			return;
9371 		}
9372 	}
9373 
9374 	resop = &res.array[1];	/* readdir res */
9375 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9376 
9377 	mutex_enter(&rp->r_statelock);
9378 	rp->r_cookieverf4 = rd_res->cookieverf;
9379 	mutex_exit(&rp->r_statelock);
9380 
9381 	/*
9382 	 * For "." and ".." entries
9383 	 * e.g.
9384 	 *	seek(cookie=0) -> "." entry with d_off = 1
9385 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9386 	 */
9387 	if (cookie == (nfs_cookie4) 0) {
9388 		if (rd_res->dotp)
9389 			rd_res->dotp->d_ino = nodeid;
9390 		if (rd_res->dotdotp)
9391 			rd_res->dotdotp->d_ino = pnodeid;
9392 	}
9393 	if (cookie == (nfs_cookie4) 1) {
9394 		if (rd_res->dotdotp)
9395 			rd_res->dotdotp->d_ino = pnodeid;
9396 	}
9397 
9398 
9399 	/* LOOKUPP+GETATTR attemped */
9400 	if (args.array_len == 5 && rd_res->dotdotp) {
9401 		if (res.status == NFS4_OK && res_opcnt == 5) {
9402 			nfs_fh4 *fhp;
9403 			nfs4_sharedfh_t *sfhp;
9404 			vnode_t *pvp;
9405 			nfs4_ga_res_t *garp;
9406 
9407 			resop++;	/* lookupp */
9408 			resop++;	/* getfh   */
9409 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9410 
9411 			resop++;	/* getattr of parent */
9412 
9413 			/*
9414 			 * First, take care of finishing the
9415 			 * readdir results.
9416 			 */
9417 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9418 			/*
9419 			 * The d_ino of .. must be the inode number
9420 			 * of the mounted filesystem.
9421 			 */
9422 			if (garp->n4g_va.va_mask & AT_NODEID)
9423 				rd_res->dotdotp->d_ino =
9424 				    garp->n4g_va.va_nodeid;
9425 
9426 
9427 			/*
9428 			 * Next, create the ".." dnlc entry
9429 			 */
9430 			sfhp = sfh4_get(fhp, mi);
9431 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9432 				dnlc_update(vp, "..", pvp);
9433 				VN_RELE(pvp);
9434 			}
9435 			sfh4_rele(&sfhp);
9436 		}
9437 	}
9438 
9439 	if (mi->mi_io_kstats) {
9440 		mutex_enter(&mi->mi_lock);
9441 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9442 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9443 		mutex_exit(&mi->mi_lock);
9444 	}
9445 
9446 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9447 
9448 out:
9449 	/*
9450 	 * If readdir a node that is a stub for a crossed mount point,
9451 	 * keep the original secinfo flavor for the current file system,
9452 	 * not the crossed one.
9453 	 */
9454 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9455 
9456 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9457 }
9458 
9459 
9460 static int
9461 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9462 {
9463 	rnode4_t *rp = VTOR4(bp->b_vp);
9464 	int count;
9465 	int error;
9466 	cred_t *cred_otw = NULL;
9467 	offset_t offset;
9468 	nfs4_open_stream_t *osp = NULL;
9469 	bool_t first_time = TRUE;	/* first time getting otw cred */
9470 	bool_t last_time = FALSE;	/* last time getting otw cred */
9471 
9472 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9473 
9474 	DTRACE_IO1(start, struct buf *, bp);
9475 	offset = ldbtob(bp->b_lblkno);
9476 
9477 	if (bp->b_flags & B_READ) {
9478 	read_again:
9479 		/*
9480 		 * Releases the osp, if it is provided.
9481 		 * Puts a hold on the cred_otw and the new osp (if found).
9482 		 */
9483 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9484 		    &first_time, &last_time);
9485 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9486 		    offset, bp->b_bcount, &bp->b_resid, cred_otw,
9487 		    readahead, NULL);
9488 		crfree(cred_otw);
9489 		if (!error) {
9490 			if (bp->b_resid) {
9491 				/*
9492 				 * Didn't get it all because we hit EOF,
9493 				 * zero all the memory beyond the EOF.
9494 				 */
9495 				/* bzero(rdaddr + */
9496 				bzero(bp->b_un.b_addr +
9497 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9498 			}
9499 			mutex_enter(&rp->r_statelock);
9500 			if (bp->b_resid == bp->b_bcount &&
9501 			    offset >= rp->r_size) {
9502 				/*
9503 				 * We didn't read anything at all as we are
9504 				 * past EOF.  Return an error indicator back
9505 				 * but don't destroy the pages (yet).
9506 				 */
9507 				error = NFS_EOF;
9508 			}
9509 			mutex_exit(&rp->r_statelock);
9510 		} else if (error == EACCES && last_time == FALSE) {
9511 				goto read_again;
9512 		}
9513 	} else {
9514 		if (!(rp->r_flags & R4STALE)) {
9515 write_again:
9516 			/*
9517 			 * Releases the osp, if it is provided.
9518 			 * Puts a hold on the cred_otw and the new
9519 			 * osp (if found).
9520 			 */
9521 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9522 			    &first_time, &last_time);
9523 			mutex_enter(&rp->r_statelock);
9524 			count = MIN(bp->b_bcount, rp->r_size - offset);
9525 			mutex_exit(&rp->r_statelock);
9526 			if (count < 0)
9527 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9528 #ifdef DEBUG
9529 			if (count == 0) {
9530 				zoneid_t zoneid = getzoneid();
9531 
9532 				zcmn_err(zoneid, CE_WARN,
9533 				    "nfs4_bio: zero length write at %lld",
9534 				    offset);
9535 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9536 				    "b_bcount=%ld, file size=%lld",
9537 				    rp->r_flags, (long)bp->b_bcount,
9538 				    rp->r_size);
9539 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9540 				if (nfs4_bio_do_stop)
9541 					debug_enter("nfs4_bio");
9542 			}
9543 #endif
9544 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9545 			    count, cred_otw, stab_comm);
9546 			if (error == EACCES && last_time == FALSE) {
9547 				crfree(cred_otw);
9548 				goto write_again;
9549 			}
9550 			bp->b_error = error;
9551 			if (error && error != EINTR &&
9552 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9553 				/*
9554 				 * Don't print EDQUOT errors on the console.
9555 				 * Don't print asynchronous EACCES errors.
9556 				 * Don't print EFBIG errors.
9557 				 * Print all other write errors.
9558 				 */
9559 				if (error != EDQUOT && error != EFBIG &&
9560 				    (error != EACCES ||
9561 				    !(bp->b_flags & B_ASYNC)))
9562 					nfs4_write_error(bp->b_vp,
9563 					    error, cred_otw);
9564 				/*
9565 				 * Update r_error and r_flags as appropriate.
9566 				 * If the error was ESTALE, then mark the
9567 				 * rnode as not being writeable and save
9568 				 * the error status.  Otherwise, save any
9569 				 * errors which occur from asynchronous
9570 				 * page invalidations.  Any errors occurring
9571 				 * from other operations should be saved
9572 				 * by the caller.
9573 				 */
9574 				mutex_enter(&rp->r_statelock);
9575 				if (error == ESTALE) {
9576 					rp->r_flags |= R4STALE;
9577 					if (!rp->r_error)
9578 						rp->r_error = error;
9579 				} else if (!rp->r_error &&
9580 				    (bp->b_flags &
9581 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9582 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9583 					rp->r_error = error;
9584 				}
9585 				mutex_exit(&rp->r_statelock);
9586 			}
9587 			crfree(cred_otw);
9588 		} else {
9589 			error = rp->r_error;
9590 			/*
9591 			 * A close may have cleared r_error, if so,
9592 			 * propagate ESTALE error return properly
9593 			 */
9594 			if (error == 0)
9595 				error = ESTALE;
9596 		}
9597 	}
9598 
9599 	if (error != 0 && error != NFS_EOF)
9600 		bp->b_flags |= B_ERROR;
9601 
9602 	if (osp)
9603 		open_stream_rele(osp, rp);
9604 
9605 	DTRACE_IO1(done, struct buf *, bp);
9606 
9607 	return (error);
9608 }
9609 
9610 /* ARGSUSED */
9611 int
9612 nfs4_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
9613 {
9614 	return (EREMOTE);
9615 }
9616 
9617 /* ARGSUSED2 */
9618 int
9619 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9620 {
9621 	rnode4_t *rp = VTOR4(vp);
9622 
9623 	if (!write_lock) {
9624 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9625 		return (V_WRITELOCK_FALSE);
9626 	}
9627 
9628 	if ((rp->r_flags & R4DIRECTIO) ||
9629 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9630 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9631 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9632 			return (V_WRITELOCK_FALSE);
9633 		nfs_rw_exit(&rp->r_rwlock);
9634 	}
9635 
9636 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9637 	return (V_WRITELOCK_TRUE);
9638 }
9639 
9640 /* ARGSUSED */
9641 void
9642 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9643 {
9644 	rnode4_t *rp = VTOR4(vp);
9645 
9646 	nfs_rw_exit(&rp->r_rwlock);
9647 }
9648 
9649 /* ARGSUSED */
9650 static int
9651 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp, caller_context_t *ct)
9652 {
9653 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9654 		return (EIO);
9655 
9656 	/*
9657 	 * Because we stuff the readdir cookie into the offset field
9658 	 * someone may attempt to do an lseek with the cookie which
9659 	 * we want to succeed.
9660 	 */
9661 	if (vp->v_type == VDIR)
9662 		return (0);
9663 	if (*noffp < 0)
9664 		return (EINVAL);
9665 	return (0);
9666 }
9667 
9668 
9669 /*
9670  * Return all the pages from [off..off+len) in file
9671  */
9672 /* ARGSUSED */
9673 static int
9674 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9675     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9676 	enum seg_rw rw, cred_t *cr, caller_context_t *ct)
9677 {
9678 	rnode4_t *rp;
9679 	int error;
9680 	mntinfo4_t *mi;
9681 
9682 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9683 		return (EIO);
9684 	rp = VTOR4(vp);
9685 	if (IS_SHADOW(vp, rp))
9686 		vp = RTOV4(rp);
9687 
9688 	if (vp->v_flag & VNOMAP)
9689 		return (ENOSYS);
9690 
9691 	if (protp != NULL)
9692 		*protp = PROT_ALL;
9693 
9694 	/*
9695 	 * Now validate that the caches are up to date.
9696 	 */
9697 	if (error = nfs4_validate_caches(vp, cr))
9698 		return (error);
9699 
9700 	mi = VTOMI4(vp);
9701 retry:
9702 	mutex_enter(&rp->r_statelock);
9703 
9704 	/*
9705 	 * Don't create dirty pages faster than they
9706 	 * can be cleaned so that the system doesn't
9707 	 * get imbalanced.  If the async queue is
9708 	 * maxed out, then wait for it to drain before
9709 	 * creating more dirty pages.  Also, wait for
9710 	 * any threads doing pagewalks in the vop_getattr
9711 	 * entry points so that they don't block for
9712 	 * long periods.
9713 	 */
9714 	if (rw == S_CREATE) {
9715 		while ((mi->mi_max_threads != 0 &&
9716 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
9717 		    rp->r_gcount > 0)
9718 			cv_wait(&rp->r_cv, &rp->r_statelock);
9719 	}
9720 
9721 	/*
9722 	 * If we are getting called as a side effect of an nfs_write()
9723 	 * operation the local file size might not be extended yet.
9724 	 * In this case we want to be able to return pages of zeroes.
9725 	 */
9726 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9727 		NFS4_DEBUG(nfs4_pageio_debug,
9728 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9729 		    "len=%llu, size=%llu, attrsize =%llu", off,
9730 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9731 		mutex_exit(&rp->r_statelock);
9732 		return (EFAULT);		/* beyond EOF */
9733 	}
9734 
9735 	mutex_exit(&rp->r_statelock);
9736 
9737 	if (len <= PAGESIZE) {
9738 		error = nfs4_getapage(vp, off, len, protp, pl, plsz,
9739 		    seg, addr, rw, cr);
9740 		NFS4_DEBUG(nfs4_pageio_debug && error,
9741 		    (CE_NOTE, "getpage error %d; off=%lld, "
9742 		    "len=%lld", error, off, (u_longlong_t)len));
9743 	} else {
9744 		error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9745 		    pl, plsz, seg, addr, rw, cr);
9746 		NFS4_DEBUG(nfs4_pageio_debug && error,
9747 		    (CE_NOTE, "getpages error %d; off=%lld, "
9748 		    "len=%lld", error, off, (u_longlong_t)len));
9749 	}
9750 
9751 	switch (error) {
9752 	case NFS_EOF:
9753 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9754 		goto retry;
9755 	case ESTALE:
9756 		nfs4_purge_stale_fh(error, vp, cr);
9757 	}
9758 
9759 	return (error);
9760 }
9761 
9762 /*
9763  * Called from pvn_getpages or nfs4_getpage to get a particular page.
9764  */
9765 /* ARGSUSED */
9766 static int
9767 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9768     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9769     enum seg_rw rw, cred_t *cr)
9770 {
9771 	rnode4_t *rp;
9772 	uint_t bsize;
9773 	struct buf *bp;
9774 	page_t *pp;
9775 	u_offset_t lbn;
9776 	u_offset_t io_off;
9777 	u_offset_t blkoff;
9778 	u_offset_t rablkoff;
9779 	size_t io_len;
9780 	uint_t blksize;
9781 	int error;
9782 	int readahead;
9783 	int readahead_issued = 0;
9784 	int ra_window; /* readahead window */
9785 	page_t *pagefound;
9786 	page_t *savepp;
9787 
9788 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9789 		return (EIO);
9790 
9791 	rp = VTOR4(vp);
9792 	ASSERT(!IS_SHADOW(vp, rp));
9793 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9794 
9795 reread:
9796 	bp = NULL;
9797 	pp = NULL;
9798 	pagefound = NULL;
9799 
9800 	if (pl != NULL)
9801 		pl[0] = NULL;
9802 
9803 	error = 0;
9804 	lbn = off / bsize;
9805 	blkoff = lbn * bsize;
9806 
9807 	/*
9808 	 * Queueing up the readahead before doing the synchronous read
9809 	 * results in a significant increase in read throughput because
9810 	 * of the increased parallelism between the async threads and
9811 	 * the process context.
9812 	 */
9813 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9814 	    rw != S_CREATE &&
9815 	    !(vp->v_flag & VNOCACHE)) {
9816 		mutex_enter(&rp->r_statelock);
9817 
9818 		/*
9819 		 * Calculate the number of readaheads to do.
9820 		 * a) No readaheads at offset = 0.
9821 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9822 		 *    window is closed.
9823 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9824 		 *    upon how far the readahead window is open or close.
9825 		 * d) No readaheads if rp->r_nextr is not within the scope
9826 		 *    of the readahead window (random i/o).
9827 		 */
9828 
9829 		if (off == 0)
9830 			readahead = 0;
9831 		else if (blkoff == rp->r_nextr)
9832 			readahead = nfs4_nra;
9833 		else if (rp->r_nextr > blkoff &&
9834 		    ((ra_window = (rp->r_nextr - blkoff) / bsize)
9835 		    <= (nfs4_nra - 1)))
9836 			readahead = nfs4_nra - ra_window;
9837 		else
9838 			readahead = 0;
9839 
9840 		rablkoff = rp->r_nextr;
9841 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9842 			mutex_exit(&rp->r_statelock);
9843 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9844 			    addr + (rablkoff + bsize - off),
9845 			    seg, cr, nfs4_readahead) < 0) {
9846 				mutex_enter(&rp->r_statelock);
9847 				break;
9848 			}
9849 			readahead--;
9850 			rablkoff += bsize;
9851 			/*
9852 			 * Indicate that we did a readahead so
9853 			 * readahead offset is not updated
9854 			 * by the synchronous read below.
9855 			 */
9856 			readahead_issued = 1;
9857 			mutex_enter(&rp->r_statelock);
9858 			/*
9859 			 * set readahead offset to
9860 			 * offset of last async readahead
9861 			 * request.
9862 			 */
9863 			rp->r_nextr = rablkoff;
9864 		}
9865 		mutex_exit(&rp->r_statelock);
9866 	}
9867 
9868 again:
9869 	if ((pagefound = page_exists(vp, off)) == NULL) {
9870 		if (pl == NULL) {
9871 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9872 			    nfs4_readahead);
9873 		} else if (rw == S_CREATE) {
9874 			/*
9875 			 * Block for this page is not allocated, or the offset
9876 			 * is beyond the current allocation size, or we're
9877 			 * allocating a swap slot and the page was not found,
9878 			 * so allocate it and return a zero page.
9879 			 */
9880 			if ((pp = page_create_va(vp, off,
9881 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9882 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9883 			io_len = PAGESIZE;
9884 			mutex_enter(&rp->r_statelock);
9885 			rp->r_nextr = off + PAGESIZE;
9886 			mutex_exit(&rp->r_statelock);
9887 		} else {
9888 			/*
9889 			 * Need to go to server to get a block
9890 			 */
9891 			mutex_enter(&rp->r_statelock);
9892 			if (blkoff < rp->r_size &&
9893 			    blkoff + bsize > rp->r_size) {
9894 				/*
9895 				 * If less than a block left in
9896 				 * file read less than a block.
9897 				 */
9898 				if (rp->r_size <= off) {
9899 					/*
9900 					 * Trying to access beyond EOF,
9901 					 * set up to get at least one page.
9902 					 */
9903 					blksize = off + PAGESIZE - blkoff;
9904 				} else
9905 					blksize = rp->r_size - blkoff;
9906 			} else if ((off == 0) ||
9907 			    (off != rp->r_nextr && !readahead_issued)) {
9908 				blksize = PAGESIZE;
9909 				blkoff = off; /* block = page here */
9910 			} else
9911 				blksize = bsize;
9912 			mutex_exit(&rp->r_statelock);
9913 
9914 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9915 			    &io_len, blkoff, blksize, 0);
9916 
9917 			/*
9918 			 * Some other thread has entered the page,
9919 			 * so just use it.
9920 			 */
9921 			if (pp == NULL)
9922 				goto again;
9923 
9924 			/*
9925 			 * Now round the request size up to page boundaries.
9926 			 * This ensures that the entire page will be
9927 			 * initialized to zeroes if EOF is encountered.
9928 			 */
9929 			io_len = ptob(btopr(io_len));
9930 
9931 			bp = pageio_setup(pp, io_len, vp, B_READ);
9932 			ASSERT(bp != NULL);
9933 
9934 			/*
9935 			 * pageio_setup should have set b_addr to 0.  This
9936 			 * is correct since we want to do I/O on a page
9937 			 * boundary.  bp_mapin will use this addr to calculate
9938 			 * an offset, and then set b_addr to the kernel virtual
9939 			 * address it allocated for us.
9940 			 */
9941 			ASSERT(bp->b_un.b_addr == 0);
9942 
9943 			bp->b_edev = 0;
9944 			bp->b_dev = 0;
9945 			bp->b_lblkno = lbtodb(io_off);
9946 			bp->b_file = vp;
9947 			bp->b_offset = (offset_t)off;
9948 			bp_mapin(bp);
9949 
9950 			/*
9951 			 * If doing a write beyond what we believe is EOF,
9952 			 * don't bother trying to read the pages from the
9953 			 * server, we'll just zero the pages here.  We
9954 			 * don't check that the rw flag is S_WRITE here
9955 			 * because some implementations may attempt a
9956 			 * read access to the buffer before copying data.
9957 			 */
9958 			mutex_enter(&rp->r_statelock);
9959 			if (io_off >= rp->r_size && seg == segkmap) {
9960 				mutex_exit(&rp->r_statelock);
9961 				bzero(bp->b_un.b_addr, io_len);
9962 			} else {
9963 				mutex_exit(&rp->r_statelock);
9964 				error = nfs4_bio(bp, NULL, cr, FALSE);
9965 			}
9966 
9967 			/*
9968 			 * Unmap the buffer before freeing it.
9969 			 */
9970 			bp_mapout(bp);
9971 			pageio_done(bp);
9972 
9973 			savepp = pp;
9974 			do {
9975 				pp->p_fsdata = C_NOCOMMIT;
9976 			} while ((pp = pp->p_next) != savepp);
9977 
9978 			if (error == NFS_EOF) {
9979 				/*
9980 				 * If doing a write system call just return
9981 				 * zeroed pages, else user tried to get pages
9982 				 * beyond EOF, return error.  We don't check
9983 				 * that the rw flag is S_WRITE here because
9984 				 * some implementations may attempt a read
9985 				 * access to the buffer before copying data.
9986 				 */
9987 				if (seg == segkmap)
9988 					error = 0;
9989 				else
9990 					error = EFAULT;
9991 			}
9992 
9993 			if (!readahead_issued && !error) {
9994 				mutex_enter(&rp->r_statelock);
9995 				rp->r_nextr = io_off + io_len;
9996 				mutex_exit(&rp->r_statelock);
9997 			}
9998 		}
9999 	}
10000 
10001 out:
10002 	if (pl == NULL)
10003 		return (error);
10004 
10005 	if (error) {
10006 		if (pp != NULL)
10007 			pvn_read_done(pp, B_ERROR);
10008 		return (error);
10009 	}
10010 
10011 	if (pagefound) {
10012 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
10013 
10014 		/*
10015 		 * Page exists in the cache, acquire the appropriate lock.
10016 		 * If this fails, start all over again.
10017 		 */
10018 		if ((pp = page_lookup(vp, off, se)) == NULL) {
10019 #ifdef DEBUG
10020 			nfs4_lostpage++;
10021 #endif
10022 			goto reread;
10023 		}
10024 		pl[0] = pp;
10025 		pl[1] = NULL;
10026 		return (0);
10027 	}
10028 
10029 	if (pp != NULL)
10030 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
10031 
10032 	return (error);
10033 }
10034 
10035 static void
10036 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
10037     cred_t *cr)
10038 {
10039 	int error;
10040 	page_t *pp;
10041 	u_offset_t io_off;
10042 	size_t io_len;
10043 	struct buf *bp;
10044 	uint_t bsize, blksize;
10045 	rnode4_t *rp = VTOR4(vp);
10046 	page_t *savepp;
10047 
10048 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10049 
10050 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10051 
10052 	mutex_enter(&rp->r_statelock);
10053 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
10054 		/*
10055 		 * If less than a block left in file read less
10056 		 * than a block.
10057 		 */
10058 		blksize = rp->r_size - blkoff;
10059 	} else
10060 		blksize = bsize;
10061 	mutex_exit(&rp->r_statelock);
10062 
10063 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
10064 	    &io_off, &io_len, blkoff, blksize, 1);
10065 	/*
10066 	 * The isra flag passed to the kluster function is 1, we may have
10067 	 * gotten a return value of NULL for a variety of reasons (# of free
10068 	 * pages < minfree, someone entered the page on the vnode etc). In all
10069 	 * cases, we want to punt on the readahead.
10070 	 */
10071 	if (pp == NULL)
10072 		return;
10073 
10074 	/*
10075 	 * Now round the request size up to page boundaries.
10076 	 * This ensures that the entire page will be
10077 	 * initialized to zeroes if EOF is encountered.
10078 	 */
10079 	io_len = ptob(btopr(io_len));
10080 
10081 	bp = pageio_setup(pp, io_len, vp, B_READ);
10082 	ASSERT(bp != NULL);
10083 
10084 	/*
10085 	 * pageio_setup should have set b_addr to 0.  This is correct since
10086 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10087 	 * to calculate an offset, and then set b_addr to the kernel virtual
10088 	 * address it allocated for us.
10089 	 */
10090 	ASSERT(bp->b_un.b_addr == 0);
10091 
10092 	bp->b_edev = 0;
10093 	bp->b_dev = 0;
10094 	bp->b_lblkno = lbtodb(io_off);
10095 	bp->b_file = vp;
10096 	bp->b_offset = (offset_t)blkoff;
10097 	bp_mapin(bp);
10098 
10099 	/*
10100 	 * If doing a write beyond what we believe is EOF, don't bother trying
10101 	 * to read the pages from the server, we'll just zero the pages here.
10102 	 * We don't check that the rw flag is S_WRITE here because some
10103 	 * implementations may attempt a read access to the buffer before
10104 	 * copying data.
10105 	 */
10106 	mutex_enter(&rp->r_statelock);
10107 	if (io_off >= rp->r_size && seg == segkmap) {
10108 		mutex_exit(&rp->r_statelock);
10109 		bzero(bp->b_un.b_addr, io_len);
10110 		error = 0;
10111 	} else {
10112 		mutex_exit(&rp->r_statelock);
10113 		error = nfs4_bio(bp, NULL, cr, TRUE);
10114 		if (error == NFS_EOF)
10115 			error = 0;
10116 	}
10117 
10118 	/*
10119 	 * Unmap the buffer before freeing it.
10120 	 */
10121 	bp_mapout(bp);
10122 	pageio_done(bp);
10123 
10124 	savepp = pp;
10125 	do {
10126 		pp->p_fsdata = C_NOCOMMIT;
10127 	} while ((pp = pp->p_next) != savepp);
10128 
10129 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10130 
10131 	/*
10132 	 * In case of error set readahead offset
10133 	 * to the lowest offset.
10134 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10135 	 */
10136 	if (error && rp->r_nextr > io_off) {
10137 		mutex_enter(&rp->r_statelock);
10138 		if (rp->r_nextr > io_off)
10139 			rp->r_nextr = io_off;
10140 		mutex_exit(&rp->r_statelock);
10141 	}
10142 }
10143 
10144 /*
10145  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10146  * If len == 0, do from off to EOF.
10147  *
10148  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10149  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10150  * (from pageout).
10151  */
10152 /* ARGSUSED */
10153 static int
10154 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
10155 	caller_context_t *ct)
10156 {
10157 	int error;
10158 	rnode4_t *rp;
10159 
10160 	ASSERT(cr != NULL);
10161 
10162 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10163 		return (EIO);
10164 
10165 	rp = VTOR4(vp);
10166 	if (IS_SHADOW(vp, rp))
10167 		vp = RTOV4(rp);
10168 
10169 	/*
10170 	 * XXX - Why should this check be made here?
10171 	 */
10172 	if (vp->v_flag & VNOMAP)
10173 		return (ENOSYS);
10174 
10175 	if (len == 0 && !(flags & B_INVAL) &&
10176 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10177 		return (0);
10178 
10179 	mutex_enter(&rp->r_statelock);
10180 	rp->r_count++;
10181 	mutex_exit(&rp->r_statelock);
10182 	error = nfs4_putpages(vp, off, len, flags, cr);
10183 	mutex_enter(&rp->r_statelock);
10184 	rp->r_count--;
10185 	cv_broadcast(&rp->r_cv);
10186 	mutex_exit(&rp->r_statelock);
10187 
10188 	return (error);
10189 }
10190 
10191 /*
10192  * Write out a single page, possibly klustering adjacent dirty pages.
10193  */
10194 int
10195 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10196     int flags, cred_t *cr)
10197 {
10198 	u_offset_t io_off;
10199 	u_offset_t lbn_off;
10200 	u_offset_t lbn;
10201 	size_t io_len;
10202 	uint_t bsize;
10203 	int error;
10204 	rnode4_t *rp;
10205 
10206 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10207 	ASSERT(pp != NULL);
10208 	ASSERT(cr != NULL);
10209 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10210 
10211 	rp = VTOR4(vp);
10212 	ASSERT(rp->r_count > 0);
10213 	ASSERT(!IS_SHADOW(vp, rp));
10214 
10215 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10216 	lbn = pp->p_offset / bsize;
10217 	lbn_off = lbn * bsize;
10218 
10219 	/*
10220 	 * Find a kluster that fits in one block, or in
10221 	 * one page if pages are bigger than blocks.  If
10222 	 * there is less file space allocated than a whole
10223 	 * page, we'll shorten the i/o request below.
10224 	 */
10225 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10226 	    roundup(bsize, PAGESIZE), flags);
10227 
10228 	/*
10229 	 * pvn_write_kluster shouldn't have returned a page with offset
10230 	 * behind the original page we were given.  Verify that.
10231 	 */
10232 	ASSERT((pp->p_offset / bsize) >= lbn);
10233 
10234 	/*
10235 	 * Now pp will have the list of kept dirty pages marked for
10236 	 * write back.  It will also handle invalidation and freeing
10237 	 * of pages that are not dirty.  Check for page length rounding
10238 	 * problems.
10239 	 */
10240 	if (io_off + io_len > lbn_off + bsize) {
10241 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10242 		io_len = lbn_off + bsize - io_off;
10243 	}
10244 	/*
10245 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10246 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10247 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10248 	 * progress and the r_size has not been made consistent with the
10249 	 * new size of the file. When the uiomove() completes the r_size is
10250 	 * updated and the R4MODINPROGRESS flag is cleared.
10251 	 *
10252 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10253 	 * consistent value of r_size. Without this handshaking, it is
10254 	 * possible that nfs4_bio() picks  up the old value of r_size
10255 	 * before the uiomove() in writerp4() completes. This will result
10256 	 * in the write through nfs4_bio() being dropped.
10257 	 *
10258 	 * More precisely, there is a window between the time the uiomove()
10259 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10260 	 * operation intervenes in this window, the page will be picked up,
10261 	 * because it is dirty (it will be unlocked, unless it was
10262 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10263 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10264 	 * checked. This will still be the old size. Therefore the page will
10265 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10266 	 * the page will be found to be clean and the write will be dropped.
10267 	 */
10268 	if (rp->r_flags & R4MODINPROGRESS) {
10269 		mutex_enter(&rp->r_statelock);
10270 		if ((rp->r_flags & R4MODINPROGRESS) &&
10271 		    rp->r_modaddr + MAXBSIZE > io_off &&
10272 		    rp->r_modaddr < io_off + io_len) {
10273 			page_t *plist;
10274 			/*
10275 			 * A write is in progress for this region of the file.
10276 			 * If we did not detect R4MODINPROGRESS here then this
10277 			 * path through nfs_putapage() would eventually go to
10278 			 * nfs4_bio() and may not write out all of the data
10279 			 * in the pages. We end up losing data. So we decide
10280 			 * to set the modified bit on each page in the page
10281 			 * list and mark the rnode with R4DIRTY. This write
10282 			 * will be restarted at some later time.
10283 			 */
10284 			plist = pp;
10285 			while (plist != NULL) {
10286 				pp = plist;
10287 				page_sub(&plist, pp);
10288 				hat_setmod(pp);
10289 				page_io_unlock(pp);
10290 				page_unlock(pp);
10291 			}
10292 			rp->r_flags |= R4DIRTY;
10293 			mutex_exit(&rp->r_statelock);
10294 			if (offp)
10295 				*offp = io_off;
10296 			if (lenp)
10297 				*lenp = io_len;
10298 			return (0);
10299 		}
10300 		mutex_exit(&rp->r_statelock);
10301 	}
10302 
10303 	if (flags & B_ASYNC) {
10304 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10305 		    nfs4_sync_putapage);
10306 	} else
10307 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10308 
10309 	if (offp)
10310 		*offp = io_off;
10311 	if (lenp)
10312 		*lenp = io_len;
10313 	return (error);
10314 }
10315 
10316 static int
10317 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10318     int flags, cred_t *cr)
10319 {
10320 	int error;
10321 	rnode4_t *rp;
10322 
10323 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10324 
10325 	flags |= B_WRITE;
10326 
10327 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10328 
10329 	rp = VTOR4(vp);
10330 
10331 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10332 	    error == EACCES) &&
10333 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10334 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10335 			mutex_enter(&rp->r_statelock);
10336 			rp->r_flags |= R4OUTOFSPACE;
10337 			mutex_exit(&rp->r_statelock);
10338 		}
10339 		flags |= B_ERROR;
10340 		pvn_write_done(pp, flags);
10341 		/*
10342 		 * If this was not an async thread, then try again to
10343 		 * write out the pages, but this time, also destroy
10344 		 * them whether or not the write is successful.  This
10345 		 * will prevent memory from filling up with these
10346 		 * pages and destroying them is the only alternative
10347 		 * if they can't be written out.
10348 		 *
10349 		 * Don't do this if this is an async thread because
10350 		 * when the pages are unlocked in pvn_write_done,
10351 		 * some other thread could have come along, locked
10352 		 * them, and queued for an async thread.  It would be
10353 		 * possible for all of the async threads to be tied
10354 		 * up waiting to lock the pages again and they would
10355 		 * all already be locked and waiting for an async
10356 		 * thread to handle them.  Deadlock.
10357 		 */
10358 		if (!(flags & B_ASYNC)) {
10359 			error = nfs4_putpage(vp, io_off, io_len,
10360 			    B_INVAL | B_FORCE, cr, NULL);
10361 		}
10362 	} else {
10363 		if (error)
10364 			flags |= B_ERROR;
10365 		else if (rp->r_flags & R4OUTOFSPACE) {
10366 			mutex_enter(&rp->r_statelock);
10367 			rp->r_flags &= ~R4OUTOFSPACE;
10368 			mutex_exit(&rp->r_statelock);
10369 		}
10370 		pvn_write_done(pp, flags);
10371 		if (freemem < desfree)
10372 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10373 			    NFS4_WRITE_NOWAIT);
10374 	}
10375 
10376 	return (error);
10377 }
10378 
10379 #ifdef DEBUG
10380 int nfs4_force_open_before_mmap = 0;
10381 #endif
10382 
10383 /* ARGSUSED */
10384 static int
10385 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10386     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10387     caller_context_t *ct)
10388 {
10389 	struct segvn_crargs vn_a;
10390 	int error = 0;
10391 	rnode4_t *rp = VTOR4(vp);
10392 	mntinfo4_t *mi = VTOMI4(vp);
10393 
10394 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10395 		return (EIO);
10396 
10397 	if (vp->v_flag & VNOMAP)
10398 		return (ENOSYS);
10399 
10400 	if (off < 0 || (off + len) < 0)
10401 		return (ENXIO);
10402 
10403 	if (vp->v_type != VREG)
10404 		return (ENODEV);
10405 
10406 	/*
10407 	 * If the file is delegated to the client don't do anything.
10408 	 * If the file is not delegated, then validate the data cache.
10409 	 */
10410 	mutex_enter(&rp->r_statev4_lock);
10411 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10412 		mutex_exit(&rp->r_statev4_lock);
10413 		error = nfs4_validate_caches(vp, cr);
10414 		if (error)
10415 			return (error);
10416 	} else {
10417 		mutex_exit(&rp->r_statev4_lock);
10418 	}
10419 
10420 	/*
10421 	 * Check to see if the vnode is currently marked as not cachable.
10422 	 * This means portions of the file are locked (through VOP_FRLOCK).
10423 	 * In this case the map request must be refused.  We use
10424 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10425 	 *
10426 	 * Atomically increment r_inmap after acquiring r_rwlock. The
10427 	 * idea here is to acquire r_rwlock to block read/write and
10428 	 * not to protect r_inmap. r_inmap will inform nfs4_read/write()
10429 	 * that we are in nfs4_map(). Now, r_rwlock is acquired in order
10430 	 * and we can prevent the deadlock that would have occurred
10431 	 * when nfs4_addmap() would have acquired it out of order.
10432 	 *
10433 	 * Since we are not protecting r_inmap by any lock, we do not
10434 	 * hold any lock when we decrement it. We atomically decrement
10435 	 * r_inmap after we release r_lkserlock.
10436 	 */
10437 
10438 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR(vp)))
10439 		return (EINTR);
10440 	atomic_add_int(&rp->r_inmap, 1);
10441 	nfs_rw_exit(&rp->r_rwlock);
10442 
10443 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp))) {
10444 		atomic_add_int(&rp->r_inmap, -1);
10445 		return (EINTR);
10446 	}
10447 
10448 
10449 	if (vp->v_flag & VNOCACHE) {
10450 		error = EAGAIN;
10451 		goto done;
10452 	}
10453 
10454 	/*
10455 	 * Don't allow concurrent locks and mapping if mandatory locking is
10456 	 * enabled.
10457 	 */
10458 	if (flk_has_remote_locks(vp)) {
10459 		struct vattr va;
10460 		va.va_mask = AT_MODE;
10461 		error = nfs4getattr(vp, &va, cr);
10462 		if (error != 0)
10463 			goto done;
10464 		if (MANDLOCK(vp, va.va_mode)) {
10465 			error = EAGAIN;
10466 			goto done;
10467 		}
10468 	}
10469 
10470 	/*
10471 	 * It is possible that the rnode has a lost lock request that we
10472 	 * are still trying to recover, and that the request conflicts with
10473 	 * this map request.
10474 	 *
10475 	 * An alternative approach would be for nfs4_safemap() to consider
10476 	 * queued lock requests when deciding whether to set or clear
10477 	 * VNOCACHE.  This would require the frlock code path to call
10478 	 * nfs4_safemap() after enqueing a lost request.
10479 	 */
10480 	if (nfs4_map_lost_lock_conflict(vp)) {
10481 		error = EAGAIN;
10482 		goto done;
10483 	}
10484 
10485 	as_rangelock(as);
10486 	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
10487 	if (error != 0) {
10488 		as_rangeunlock(as);
10489 		goto done;
10490 	}
10491 
10492 	if (vp->v_type == VREG) {
10493 		/*
10494 		 * We need to retrieve the open stream
10495 		 */
10496 		nfs4_open_stream_t	*osp = NULL;
10497 		nfs4_open_owner_t	*oop = NULL;
10498 
10499 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10500 		if (oop != NULL) {
10501 			/* returns with 'os_sync_lock' held */
10502 			osp = find_open_stream(oop, rp);
10503 			open_owner_rele(oop);
10504 		}
10505 		if (osp == NULL) {
10506 #ifdef DEBUG
10507 			if (nfs4_force_open_before_mmap) {
10508 				error = EIO;
10509 				goto done;
10510 			}
10511 #endif
10512 			/* returns with 'os_sync_lock' held */
10513 			error = open_and_get_osp(vp, cr, &osp);
10514 			if (osp == NULL) {
10515 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10516 				    "nfs4_map: we tried to OPEN the file "
10517 				    "but again no osp, so fail with EIO"));
10518 				goto done;
10519 			}
10520 		}
10521 
10522 		if (osp->os_failed_reopen) {
10523 			mutex_exit(&osp->os_sync_lock);
10524 			open_stream_rele(osp, rp);
10525 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10526 			    "nfs4_map: os_failed_reopen set on "
10527 			    "osp %p, cr %p, rp %s", (void *)osp,
10528 			    (void *)cr, rnode4info(rp)));
10529 			error = EIO;
10530 			goto done;
10531 		}
10532 		mutex_exit(&osp->os_sync_lock);
10533 		open_stream_rele(osp, rp);
10534 	}
10535 
10536 	vn_a.vp = vp;
10537 	vn_a.offset = off;
10538 	vn_a.type = (flags & MAP_TYPE);
10539 	vn_a.prot = (uchar_t)prot;
10540 	vn_a.maxprot = (uchar_t)maxprot;
10541 	vn_a.flags = (flags & ~MAP_TYPE);
10542 	vn_a.cred = cr;
10543 	vn_a.amp = NULL;
10544 	vn_a.szc = 0;
10545 	vn_a.lgrp_mem_policy_flags = 0;
10546 
10547 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10548 	as_rangeunlock(as);
10549 
10550 done:
10551 	nfs_rw_exit(&rp->r_lkserlock);
10552 	atomic_add_int(&rp->r_inmap, -1);
10553 	return (error);
10554 }
10555 
10556 /*
10557  * We're most likely dealing with a kernel module that likes to READ
10558  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10559  * officially OPEN the file to create the necessary client state
10560  * for bookkeeping of os_mmap_read/write counts.
10561  *
10562  * Since VOP_MAP only passes in a pointer to the vnode rather than
10563  * a double pointer, we can't handle the case where nfs4open_otw()
10564  * returns a different vnode than the one passed into VOP_MAP (since
10565  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10566  * we return NULL and let nfs4_map() fail.  Note: the only case where
10567  * this should happen is if the file got removed and replaced with the
10568  * same name on the server (in addition to the fact that we're trying
10569  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10570  */
10571 static int
10572 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10573 {
10574 	rnode4_t		*rp, *drp;
10575 	vnode_t			*dvp, *open_vp;
10576 	char			file_name[MAXNAMELEN];
10577 	int			just_created;
10578 	nfs4_open_stream_t	*osp;
10579 	nfs4_open_owner_t	*oop;
10580 	int			error;
10581 
10582 	*ospp = NULL;
10583 	open_vp = map_vp;
10584 
10585 	rp = VTOR4(open_vp);
10586 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10587 		return (error);
10588 	drp = VTOR4(dvp);
10589 
10590 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10591 		VN_RELE(dvp);
10592 		return (EINTR);
10593 	}
10594 
10595 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10596 		nfs_rw_exit(&drp->r_rwlock);
10597 		VN_RELE(dvp);
10598 		return (error);
10599 	}
10600 
10601 	mutex_enter(&rp->r_statev4_lock);
10602 	if (rp->created_v4) {
10603 		rp->created_v4 = 0;
10604 		mutex_exit(&rp->r_statev4_lock);
10605 
10606 		dnlc_update(dvp, file_name, open_vp);
10607 		/* This is needed so we don't bump the open ref count */
10608 		just_created = 1;
10609 	} else {
10610 		mutex_exit(&rp->r_statev4_lock);
10611 		just_created = 0;
10612 	}
10613 
10614 	VN_HOLD(map_vp);
10615 
10616 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10617 	    just_created);
10618 	if (error) {
10619 		nfs_rw_exit(&drp->r_rwlock);
10620 		VN_RELE(dvp);
10621 		VN_RELE(map_vp);
10622 		return (error);
10623 	}
10624 
10625 	nfs_rw_exit(&drp->r_rwlock);
10626 	VN_RELE(dvp);
10627 
10628 	/*
10629 	 * If nfs4open_otw() returned a different vnode then "undo"
10630 	 * the open and return failure to the caller.
10631 	 */
10632 	if (!VN_CMP(open_vp, map_vp)) {
10633 		nfs4_error_t e;
10634 
10635 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10636 		    "open returned a different vnode"));
10637 		/*
10638 		 * If there's an error, ignore it,
10639 		 * and let VOP_INACTIVE handle it.
10640 		 */
10641 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10642 		    CLOSE_NORM, 0, 0, 0);
10643 		VN_RELE(map_vp);
10644 		return (EIO);
10645 	}
10646 
10647 	VN_RELE(map_vp);
10648 
10649 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10650 	if (!oop) {
10651 		nfs4_error_t e;
10652 
10653 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10654 		    "no open owner"));
10655 		/*
10656 		 * If there's an error, ignore it,
10657 		 * and let VOP_INACTIVE handle it.
10658 		 */
10659 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10660 		    CLOSE_NORM, 0, 0, 0);
10661 		return (EIO);
10662 	}
10663 	osp = find_open_stream(oop, rp);
10664 	open_owner_rele(oop);
10665 	*ospp = osp;
10666 	return (0);
10667 }
10668 
10669 /*
10670  * Please be aware that when this function is called, the address space write
10671  * a_lock is held.  Do not put over the wire calls in this function.
10672  */
10673 /* ARGSUSED */
10674 static int
10675 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10676     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10677     caller_context_t *ct)
10678 {
10679 	rnode4_t		*rp;
10680 	int			error = 0;
10681 	mntinfo4_t		*mi;
10682 
10683 	mi = VTOMI4(vp);
10684 	rp = VTOR4(vp);
10685 
10686 	if (nfs_zone() != mi->mi_zone)
10687 		return (EIO);
10688 	if (vp->v_flag & VNOMAP)
10689 		return (ENOSYS);
10690 
10691 	/*
10692 	 * Don't need to update the open stream first, since this
10693 	 * mmap can't add any additional share access that isn't
10694 	 * already contained in the open stream (for the case where we
10695 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10696 	 * take into account os_mmap_read[write] counts).
10697 	 */
10698 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10699 
10700 	if (vp->v_type == VREG) {
10701 		/*
10702 		 * We need to retrieve the open stream and update the counts.
10703 		 * If there is no open stream here, something is wrong.
10704 		 */
10705 		nfs4_open_stream_t	*osp = NULL;
10706 		nfs4_open_owner_t	*oop = NULL;
10707 
10708 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10709 		if (oop != NULL) {
10710 			/* returns with 'os_sync_lock' held */
10711 			osp = find_open_stream(oop, rp);
10712 			open_owner_rele(oop);
10713 		}
10714 		if (osp == NULL) {
10715 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10716 			    "nfs4_addmap: we should have an osp"
10717 			    "but we don't, so fail with EIO"));
10718 			error = EIO;
10719 			goto out;
10720 		}
10721 
10722 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10723 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10724 
10725 		/*
10726 		 * Update the map count in the open stream.
10727 		 * This is necessary in the case where we
10728 		 * open/mmap/close/, then the server reboots, and we
10729 		 * attempt to reopen.  If the mmap doesn't add share
10730 		 * access then we send an invalid reopen with
10731 		 * access = NONE.
10732 		 *
10733 		 * We need to specifically check each PROT_* so a mmap
10734 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10735 		 * read and write access.  A simple comparison of prot
10736 		 * to ~PROT_WRITE to determine read access is insufficient
10737 		 * since prot can be |= with PROT_USER, etc.
10738 		 */
10739 
10740 		/*
10741 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10742 		 */
10743 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10744 			osp->os_mmap_write += btopr(len);
10745 		if (maxprot & PROT_READ)
10746 			osp->os_mmap_read += btopr(len);
10747 		if (maxprot & PROT_EXEC)
10748 			osp->os_mmap_read += btopr(len);
10749 		/*
10750 		 * Ensure that os_mmap_read gets incremented, even if
10751 		 * maxprot were to look like PROT_NONE.
10752 		 */
10753 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10754 		    !(maxprot & PROT_EXEC))
10755 			osp->os_mmap_read += btopr(len);
10756 		osp->os_mapcnt += btopr(len);
10757 		mutex_exit(&osp->os_sync_lock);
10758 		open_stream_rele(osp, rp);
10759 	}
10760 
10761 out:
10762 	/*
10763 	 * If we got an error, then undo our
10764 	 * incrementing of 'r_mapcnt'.
10765 	 */
10766 
10767 	if (error) {
10768 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10769 		ASSERT(rp->r_mapcnt >= 0);
10770 	}
10771 	return (error);
10772 }
10773 
10774 /* ARGSUSED */
10775 static int
10776 nfs4_cmp(vnode_t *vp1, vnode_t *vp2, caller_context_t *ct)
10777 {
10778 
10779 	return (VTOR4(vp1) == VTOR4(vp2));
10780 }
10781 
10782 /* ARGSUSED */
10783 static int
10784 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10785     offset_t offset, struct flk_callback *flk_cbp, cred_t *cr,
10786     caller_context_t *ct)
10787 {
10788 	int rc;
10789 	u_offset_t start, end;
10790 	rnode4_t *rp;
10791 	int error = 0, intr = INTR4(vp);
10792 	nfs4_error_t e;
10793 
10794 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10795 		return (EIO);
10796 
10797 	/* check for valid cmd parameter */
10798 	if (cmd != F_GETLK && cmd != F_SETLK && cmd != F_SETLKW)
10799 		return (EINVAL);
10800 
10801 	/* Verify l_type. */
10802 	switch (bfp->l_type) {
10803 	case F_RDLCK:
10804 		if (cmd != F_GETLK && !(flag & FREAD))
10805 			return (EBADF);
10806 		break;
10807 	case F_WRLCK:
10808 		if (cmd != F_GETLK && !(flag & FWRITE))
10809 			return (EBADF);
10810 		break;
10811 	case F_UNLCK:
10812 		intr = 0;
10813 		break;
10814 
10815 	default:
10816 		return (EINVAL);
10817 	}
10818 
10819 	/* check the validity of the lock range */
10820 	if (rc = flk_convert_lock_data(vp, bfp, &start, &end, offset))
10821 		return (rc);
10822 	if (rc = flk_check_lock_data(start, end, MAXEND))
10823 		return (rc);
10824 
10825 	/*
10826 	 * If the filesystem is mounted using local locking, pass the
10827 	 * request off to the local locking code.
10828 	 */
10829 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10830 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10831 			/*
10832 			 * For complete safety, we should be holding
10833 			 * r_lkserlock.  However, we can't call
10834 			 * nfs4_safelock and then fs_frlock while
10835 			 * holding r_lkserlock, so just invoke
10836 			 * nfs4_safelock and expect that this will
10837 			 * catch enough of the cases.
10838 			 */
10839 			if (!nfs4_safelock(vp, bfp, cr))
10840 				return (EAGAIN);
10841 		}
10842 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
10843 	}
10844 
10845 	rp = VTOR4(vp);
10846 
10847 	/*
10848 	 * Check whether the given lock request can proceed, given the
10849 	 * current file mappings.
10850 	 */
10851 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr))
10852 		return (EINTR);
10853 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10854 		if (!nfs4_safelock(vp, bfp, cr)) {
10855 			rc = EAGAIN;
10856 			goto done;
10857 		}
10858 	}
10859 
10860 	/*
10861 	 * Flush the cache after waiting for async I/O to finish.  For new
10862 	 * locks, this is so that the process gets the latest bits from the
10863 	 * server.  For unlocks, this is so that other clients see the
10864 	 * latest bits once the file has been unlocked.  If currently dirty
10865 	 * pages can't be flushed, then don't allow a lock to be set.  But
10866 	 * allow unlocks to succeed, to avoid having orphan locks on the
10867 	 * server.
10868 	 */
10869 	if (cmd != F_GETLK) {
10870 		mutex_enter(&rp->r_statelock);
10871 		while (rp->r_count > 0) {
10872 			if (intr) {
10873 				klwp_t *lwp = ttolwp(curthread);
10874 
10875 				if (lwp != NULL)
10876 					lwp->lwp_nostop++;
10877 				if (cv_wait_sig(&rp->r_cv,
10878 				    &rp->r_statelock) == 0) {
10879 					if (lwp != NULL)
10880 						lwp->lwp_nostop--;
10881 					rc = EINTR;
10882 					break;
10883 				}
10884 				if (lwp != NULL)
10885 					lwp->lwp_nostop--;
10886 				} else
10887 					cv_wait(&rp->r_cv, &rp->r_statelock);
10888 		}
10889 		mutex_exit(&rp->r_statelock);
10890 		if (rc != 0)
10891 			goto done;
10892 		error = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr, ct);
10893 		if (error) {
10894 			if (error == ENOSPC || error == EDQUOT) {
10895 				mutex_enter(&rp->r_statelock);
10896 				if (!rp->r_error)
10897 					rp->r_error = error;
10898 				mutex_exit(&rp->r_statelock);
10899 			}
10900 			if (bfp->l_type != F_UNLCK) {
10901 				rc = ENOLCK;
10902 				goto done;
10903 			}
10904 		}
10905 	}
10906 
10907 	/*
10908 	 * Call the lock manager to do the real work of contacting
10909 	 * the server and obtaining the lock.
10910 	 */
10911 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, flag, offset,
10912 	    cr, &e, NULL, NULL);
10913 	rc = e.error;
10914 
10915 	if (rc == 0)
10916 		nfs4_lockcompletion(vp, cmd);
10917 
10918 done:
10919 	nfs_rw_exit(&rp->r_lkserlock);
10920 
10921 	return (rc);
10922 }
10923 
10924 /*
10925  * Free storage space associated with the specified vnode.  The portion
10926  * to be freed is specified by bfp->l_start and bfp->l_len (already
10927  * normalized to a "whence" of 0).
10928  *
10929  * This is an experimental facility whose continued existence is not
10930  * guaranteed.  Currently, we only support the special case
10931  * of l_len == 0, meaning free to end of file.
10932  */
10933 /* ARGSUSED */
10934 static int
10935 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10936     offset_t offset, cred_t *cr, caller_context_t *ct)
10937 {
10938 	int error;
10939 
10940 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10941 		return (EIO);
10942 	ASSERT(vp->v_type == VREG);
10943 	if (cmd != F_FREESP)
10944 		return (EINVAL);
10945 
10946 	error = convoff(vp, bfp, 0, offset);
10947 	if (!error) {
10948 		ASSERT(bfp->l_start >= 0);
10949 		if (bfp->l_len == 0) {
10950 			struct vattr va;
10951 
10952 			va.va_mask = AT_SIZE;
10953 			va.va_size = bfp->l_start;
10954 			error = nfs4setattr(vp, &va, 0, cr, NULL);
10955 		} else
10956 			error = EINVAL;
10957 	}
10958 
10959 	return (error);
10960 }
10961 
10962 /* ARGSUSED */
10963 int
10964 nfs4_realvp(vnode_t *vp, vnode_t **vpp, caller_context_t *ct)
10965 {
10966 	rnode4_t *rp;
10967 	rp = VTOR4(vp);
10968 
10969 	if (vp->v_type == VREG && IS_SHADOW(vp, rp)) {
10970 		vp = RTOV4(rp);
10971 	}
10972 	*vpp = vp;
10973 	return (0);
10974 }
10975 
10976 /*
10977  * Setup and add an address space callback to do the work of the delmap call.
10978  * The callback will (and must be) deleted in the actual callback function.
10979  *
10980  * This is done in order to take care of the problem that we have with holding
10981  * the address space's a_lock for a long period of time (e.g. if the NFS server
10982  * is down).  Callbacks will be executed in the address space code while the
10983  * a_lock is not held.  Holding the address space's a_lock causes things such
10984  * as ps and fork to hang because they are trying to acquire this lock as well.
10985  */
10986 /* ARGSUSED */
10987 static int
10988 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10989     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
10990     caller_context_t *ct)
10991 {
10992 	int			caller_found;
10993 	int			error;
10994 	rnode4_t		*rp;
10995 	nfs4_delmap_args_t	*dmapp;
10996 	nfs4_delmapcall_t	*delmap_call;
10997 
10998 	if (vp->v_flag & VNOMAP)
10999 		return (ENOSYS);
11000 
11001 	/*
11002 	 * A process may not change zones if it has NFS pages mmap'ed
11003 	 * in, so we can't legitimately get here from the wrong zone.
11004 	 */
11005 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11006 
11007 	rp = VTOR4(vp);
11008 
11009 	/*
11010 	 * The way that the address space of this process deletes its mapping
11011 	 * of this file is via the following call chains:
11012 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11013 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11014 	 *
11015 	 * With the use of address space callbacks we are allowed to drop the
11016 	 * address space lock, a_lock, while executing the NFS operations that
11017 	 * need to go over the wire.  Returning EAGAIN to the caller of this
11018 	 * function is what drives the execution of the callback that we add
11019 	 * below.  The callback will be executed by the address space code
11020 	 * after dropping the a_lock.  When the callback is finished, since
11021 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
11022 	 * is called again on the same segment to finish the rest of the work
11023 	 * that needs to happen during unmapping.
11024 	 *
11025 	 * This action of calling back into the segment driver causes
11026 	 * nfs4_delmap() to get called again, but since the callback was
11027 	 * already executed at this point, it already did the work and there
11028 	 * is nothing left for us to do.
11029 	 *
11030 	 * To Summarize:
11031 	 * - The first time nfs4_delmap is called by the current thread is when
11032 	 * we add the caller associated with this delmap to the delmap caller
11033 	 * list, add the callback, and return EAGAIN.
11034 	 * - The second time in this call chain when nfs4_delmap is called we
11035 	 * will find this caller in the delmap caller list and realize there
11036 	 * is no more work to do thus removing this caller from the list and
11037 	 * returning the error that was set in the callback execution.
11038 	 */
11039 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
11040 	if (caller_found) {
11041 		/*
11042 		 * 'error' is from the actual delmap operations.  To avoid
11043 		 * hangs, we need to handle the return of EAGAIN differently
11044 		 * since this is what drives the callback execution.
11045 		 * In this case, we don't want to return EAGAIN and do the
11046 		 * callback execution because there are none to execute.
11047 		 */
11048 		if (error == EAGAIN)
11049 			return (0);
11050 		else
11051 			return (error);
11052 	}
11053 
11054 	/* current caller was not in the list */
11055 	delmap_call = nfs4_init_delmapcall();
11056 
11057 	mutex_enter(&rp->r_statelock);
11058 	list_insert_tail(&rp->r_indelmap, delmap_call);
11059 	mutex_exit(&rp->r_statelock);
11060 
11061 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
11062 
11063 	dmapp->vp = vp;
11064 	dmapp->off = off;
11065 	dmapp->addr = addr;
11066 	dmapp->len = len;
11067 	dmapp->prot = prot;
11068 	dmapp->maxprot = maxprot;
11069 	dmapp->flags = flags;
11070 	dmapp->cr = cr;
11071 	dmapp->caller = delmap_call;
11072 
11073 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
11074 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
11075 
11076 	return (error ? error : EAGAIN);
11077 }
11078 
11079 static nfs4_delmapcall_t *
11080 nfs4_init_delmapcall()
11081 {
11082 	nfs4_delmapcall_t	*delmap_call;
11083 
11084 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
11085 	delmap_call->call_id = curthread;
11086 	delmap_call->error = 0;
11087 
11088 	return (delmap_call);
11089 }
11090 
11091 static void
11092 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11093 {
11094 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11095 }
11096 
11097 /*
11098  * Searches for the current delmap caller (based on curthread) in the list of
11099  * callers.  If it is found, we remove it and free the delmap caller.
11100  * Returns:
11101  *      0 if the caller wasn't found
11102  *      1 if the caller was found, removed and freed.  *errp will be set
11103  *	to what the result of the delmap was.
11104  */
11105 static int
11106 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11107 {
11108 	nfs4_delmapcall_t	*delmap_call;
11109 
11110 	/*
11111 	 * If the list doesn't exist yet, we create it and return
11112 	 * that the caller wasn't found.  No list = no callers.
11113 	 */
11114 	mutex_enter(&rp->r_statelock);
11115 	if (!(rp->r_flags & R4DELMAPLIST)) {
11116 		/* The list does not exist */
11117 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11118 		    offsetof(nfs4_delmapcall_t, call_node));
11119 		rp->r_flags |= R4DELMAPLIST;
11120 		mutex_exit(&rp->r_statelock);
11121 		return (0);
11122 	} else {
11123 		/* The list exists so search it */
11124 		for (delmap_call = list_head(&rp->r_indelmap);
11125 		    delmap_call != NULL;
11126 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11127 			if (delmap_call->call_id == curthread) {
11128 				/* current caller is in the list */
11129 				*errp = delmap_call->error;
11130 				list_remove(&rp->r_indelmap, delmap_call);
11131 				mutex_exit(&rp->r_statelock);
11132 				nfs4_free_delmapcall(delmap_call);
11133 				return (1);
11134 			}
11135 		}
11136 	}
11137 	mutex_exit(&rp->r_statelock);
11138 	return (0);
11139 }
11140 
11141 /*
11142  * Remove some pages from an mmap'd vnode.  Just update the
11143  * count of pages.  If doing close-to-open, then flush and
11144  * commit all of the pages associated with this file.
11145  * Otherwise, start an asynchronous page flush to write out
11146  * any dirty pages.  This will also associate a credential
11147  * with the rnode which can be used to write the pages.
11148  */
11149 /* ARGSUSED */
11150 static void
11151 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11152 {
11153 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11154 	rnode4_t		*rp;
11155 	mntinfo4_t		*mi;
11156 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11157 
11158 	rp = VTOR4(dmapp->vp);
11159 	mi = VTOMI4(dmapp->vp);
11160 
11161 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11162 	ASSERT(rp->r_mapcnt >= 0);
11163 
11164 	/*
11165 	 * Initiate a page flush and potential commit if there are
11166 	 * pages, the file system was not mounted readonly, the segment
11167 	 * was mapped shared, and the pages themselves were writeable.
11168 	 */
11169 	if (nfs4_has_pages(dmapp->vp) &&
11170 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11171 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11172 		mutex_enter(&rp->r_statelock);
11173 		rp->r_flags |= R4DIRTY;
11174 		mutex_exit(&rp->r_statelock);
11175 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11176 		    dmapp->len, dmapp->cr);
11177 		if (!e.error) {
11178 			mutex_enter(&rp->r_statelock);
11179 			e.error = rp->r_error;
11180 			rp->r_error = 0;
11181 			mutex_exit(&rp->r_statelock);
11182 		}
11183 	} else
11184 		e.error = 0;
11185 
11186 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11187 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11188 		    B_INVAL, dmapp->cr, NULL);
11189 
11190 	if (e.error) {
11191 		e.stat = puterrno4(e.error);
11192 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11193 		    OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11194 		dmapp->caller->error = e.error;
11195 	}
11196 
11197 	/* Check to see if we need to close the file */
11198 
11199 	if (dmapp->vp->v_type == VREG) {
11200 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11201 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11202 
11203 		if (e.error != 0 || e.stat != NFS4_OK) {
11204 			/*
11205 			 * Since it is possible that e.error == 0 and
11206 			 * e.stat != NFS4_OK (and vice versa),
11207 			 * we do the proper checking in order to get both
11208 			 * e.error and e.stat reporting the correct info.
11209 			 */
11210 			if (e.stat == NFS4_OK)
11211 				e.stat = puterrno4(e.error);
11212 			if (e.error == 0)
11213 				e.error = geterrno4(e.stat);
11214 
11215 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11216 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11217 			dmapp->caller->error = e.error;
11218 		}
11219 	}
11220 
11221 	(void) as_delete_callback(as, arg);
11222 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11223 }
11224 
11225 
11226 static uint_t
11227 fattr4_maxfilesize_to_bits(uint64_t ll)
11228 {
11229 	uint_t l = 1;
11230 
11231 	if (ll == 0) {
11232 		return (0);
11233 	}
11234 
11235 	if (ll & 0xffffffff00000000) {
11236 		l += 32; ll >>= 32;
11237 	}
11238 	if (ll & 0xffff0000) {
11239 		l += 16; ll >>= 16;
11240 	}
11241 	if (ll & 0xff00) {
11242 		l += 8; ll >>= 8;
11243 	}
11244 	if (ll & 0xf0) {
11245 		l += 4; ll >>= 4;
11246 	}
11247 	if (ll & 0xc) {
11248 		l += 2; ll >>= 2;
11249 	}
11250 	if (ll & 0x2) {
11251 		l += 1;
11252 	}
11253 	return (l);
11254 }
11255 
11256 static int
11257 nfs4_have_xattrs(vnode_t *vp, ulong_t *valp, cred_t *cr)
11258 {
11259 	vnode_t *avp = NULL;
11260 	int error;
11261 
11262 	if ((error = nfs4lookup_xattr(vp, "", &avp,
11263 	    LOOKUP_XATTR, cr)) == 0)
11264 		error = do_xattr_exists_check(avp, valp, cr);
11265 	if (avp)
11266 		VN_RELE(avp);
11267 
11268 	return (error);
11269 }
11270 
11271 /* ARGSUSED */
11272 int
11273 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
11274 	caller_context_t *ct)
11275 {
11276 	int error;
11277 	hrtime_t t;
11278 	rnode4_t *rp;
11279 	nfs4_ga_res_t gar;
11280 	nfs4_ga_ext_res_t ger;
11281 
11282 	gar.n4g_ext_res = &ger;
11283 
11284 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11285 		return (EIO);
11286 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11287 		*valp = MAXPATHLEN;
11288 		return (0);
11289 	}
11290 	if (cmd == _PC_ACL_ENABLED) {
11291 		*valp = _ACL_ACE_ENABLED;
11292 		return (0);
11293 	}
11294 
11295 	rp = VTOR4(vp);
11296 	if (cmd == _PC_XATTR_EXISTS) {
11297 		/*
11298 		 * The existence of the xattr directory is not sufficient
11299 		 * for determining whether generic user attributes exists.
11300 		 * The attribute directory could only be a transient directory
11301 		 * used for Solaris sysattr support.  Do a small readdir
11302 		 * to verify if the only entries are sysattrs or not.
11303 		 *
11304 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11305 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11306 		 * and we don't have any way to update the "base" object's
11307 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11308 		 * could help out.
11309 		 */
11310 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11311 		    rp->r_xattr_dir == NULL) {
11312 			return (nfs4_have_xattrs(vp, valp, cr));
11313 		}
11314 	} else {  /* OLD CODE */
11315 		if (ATTRCACHE4_VALID(vp)) {
11316 			mutex_enter(&rp->r_statelock);
11317 			if (rp->r_pathconf.pc4_cache_valid) {
11318 				error = 0;
11319 				switch (cmd) {
11320 				case _PC_FILESIZEBITS:
11321 					*valp =
11322 					    rp->r_pathconf.pc4_filesizebits;
11323 					break;
11324 				case _PC_LINK_MAX:
11325 					*valp =
11326 					    rp->r_pathconf.pc4_link_max;
11327 					break;
11328 				case _PC_NAME_MAX:
11329 					*valp =
11330 					    rp->r_pathconf.pc4_name_max;
11331 					break;
11332 				case _PC_CHOWN_RESTRICTED:
11333 					*valp =
11334 					    rp->r_pathconf.pc4_chown_restricted;
11335 					break;
11336 				case _PC_NO_TRUNC:
11337 					*valp =
11338 					    rp->r_pathconf.pc4_no_trunc;
11339 					break;
11340 				default:
11341 					error = EINVAL;
11342 					break;
11343 				}
11344 				mutex_exit(&rp->r_statelock);
11345 #ifdef DEBUG
11346 				nfs4_pathconf_cache_hits++;
11347 #endif
11348 				return (error);
11349 			}
11350 			mutex_exit(&rp->r_statelock);
11351 		}
11352 	}
11353 #ifdef DEBUG
11354 	nfs4_pathconf_cache_misses++;
11355 #endif
11356 
11357 	t = gethrtime();
11358 
11359 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11360 
11361 	if (error) {
11362 		mutex_enter(&rp->r_statelock);
11363 		rp->r_pathconf.pc4_cache_valid = FALSE;
11364 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11365 		mutex_exit(&rp->r_statelock);
11366 		return (error);
11367 	}
11368 
11369 	/* interpret the max filesize */
11370 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11371 	    fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11372 
11373 	/* Store the attributes we just received */
11374 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11375 
11376 	switch (cmd) {
11377 	case _PC_FILESIZEBITS:
11378 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11379 		break;
11380 	case _PC_LINK_MAX:
11381 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11382 		break;
11383 	case _PC_NAME_MAX:
11384 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11385 		break;
11386 	case _PC_CHOWN_RESTRICTED:
11387 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11388 		break;
11389 	case _PC_NO_TRUNC:
11390 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11391 		break;
11392 	case _PC_XATTR_EXISTS:
11393 		if (gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists) {
11394 			if (error = nfs4_have_xattrs(vp, valp, cr))
11395 				return (error);
11396 		}
11397 		break;
11398 	default:
11399 		return (EINVAL);
11400 	}
11401 
11402 	return (0);
11403 }
11404 
11405 /*
11406  * Called by async thread to do synchronous pageio. Do the i/o, wait
11407  * for it to complete, and cleanup the page list when done.
11408  */
11409 static int
11410 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11411     int flags, cred_t *cr)
11412 {
11413 	int error;
11414 
11415 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11416 
11417 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11418 	if (flags & B_READ)
11419 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11420 	else
11421 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11422 	return (error);
11423 }
11424 
11425 /* ARGSUSED */
11426 static int
11427 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11428 	int flags, cred_t *cr, caller_context_t *ct)
11429 {
11430 	int error;
11431 	rnode4_t *rp;
11432 
11433 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11434 		return (EIO);
11435 
11436 	if (pp == NULL)
11437 		return (EINVAL);
11438 
11439 	rp = VTOR4(vp);
11440 	mutex_enter(&rp->r_statelock);
11441 	rp->r_count++;
11442 	mutex_exit(&rp->r_statelock);
11443 
11444 	if (flags & B_ASYNC) {
11445 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11446 		    nfs4_sync_pageio);
11447 	} else
11448 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11449 	mutex_enter(&rp->r_statelock);
11450 	rp->r_count--;
11451 	cv_broadcast(&rp->r_cv);
11452 	mutex_exit(&rp->r_statelock);
11453 	return (error);
11454 }
11455 
11456 /* ARGSUSED */
11457 static void
11458 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr,
11459 	caller_context_t *ct)
11460 {
11461 	int error;
11462 	rnode4_t *rp;
11463 	page_t *plist;
11464 	page_t *pptr;
11465 	offset3 offset;
11466 	count3 len;
11467 	k_sigset_t smask;
11468 
11469 	/*
11470 	 * We should get called with fl equal to either B_FREE or
11471 	 * B_INVAL.  Any other value is illegal.
11472 	 *
11473 	 * The page that we are either supposed to free or destroy
11474 	 * should be exclusive locked and its io lock should not
11475 	 * be held.
11476 	 */
11477 	ASSERT(fl == B_FREE || fl == B_INVAL);
11478 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11479 
11480 	rp = VTOR4(vp);
11481 
11482 	/*
11483 	 * If the page doesn't need to be committed or we shouldn't
11484 	 * even bother attempting to commit it, then just make sure
11485 	 * that the p_fsdata byte is clear and then either free or
11486 	 * destroy the page as appropriate.
11487 	 */
11488 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11489 		pp->p_fsdata = C_NOCOMMIT;
11490 		if (fl == B_FREE)
11491 			page_free(pp, dn);
11492 		else
11493 			page_destroy(pp, dn);
11494 		return;
11495 	}
11496 
11497 	/*
11498 	 * If there is a page invalidation operation going on, then
11499 	 * if this is one of the pages being destroyed, then just
11500 	 * clear the p_fsdata byte and then either free or destroy
11501 	 * the page as appropriate.
11502 	 */
11503 	mutex_enter(&rp->r_statelock);
11504 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11505 		mutex_exit(&rp->r_statelock);
11506 		pp->p_fsdata = C_NOCOMMIT;
11507 		if (fl == B_FREE)
11508 			page_free(pp, dn);
11509 		else
11510 			page_destroy(pp, dn);
11511 		return;
11512 	}
11513 
11514 	/*
11515 	 * If we are freeing this page and someone else is already
11516 	 * waiting to do a commit, then just unlock the page and
11517 	 * return.  That other thread will take care of commiting
11518 	 * this page.  The page can be freed sometime after the
11519 	 * commit has finished.  Otherwise, if the page is marked
11520 	 * as delay commit, then we may be getting called from
11521 	 * pvn_write_done, one page at a time.   This could result
11522 	 * in one commit per page, so we end up doing lots of small
11523 	 * commits instead of fewer larger commits.  This is bad,
11524 	 * we want do as few commits as possible.
11525 	 */
11526 	if (fl == B_FREE) {
11527 		if (rp->r_flags & R4COMMITWAIT) {
11528 			page_unlock(pp);
11529 			mutex_exit(&rp->r_statelock);
11530 			return;
11531 		}
11532 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11533 			pp->p_fsdata = C_COMMIT;
11534 			page_unlock(pp);
11535 			mutex_exit(&rp->r_statelock);
11536 			return;
11537 		}
11538 	}
11539 
11540 	/*
11541 	 * Check to see if there is a signal which would prevent an
11542 	 * attempt to commit the pages from being successful.  If so,
11543 	 * then don't bother with all of the work to gather pages and
11544 	 * generate the unsuccessful RPC.  Just return from here and
11545 	 * let the page be committed at some later time.
11546 	 */
11547 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11548 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11549 		sigunintr(&smask);
11550 		page_unlock(pp);
11551 		mutex_exit(&rp->r_statelock);
11552 		return;
11553 	}
11554 	sigunintr(&smask);
11555 
11556 	/*
11557 	 * We are starting to need to commit pages, so let's try
11558 	 * to commit as many as possible at once to reduce the
11559 	 * overhead.
11560 	 *
11561 	 * Set the `commit inprogress' state bit.  We must
11562 	 * first wait until any current one finishes.  Then
11563 	 * we initialize the c_pages list with this page.
11564 	 */
11565 	while (rp->r_flags & R4COMMIT) {
11566 		rp->r_flags |= R4COMMITWAIT;
11567 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11568 		rp->r_flags &= ~R4COMMITWAIT;
11569 	}
11570 	rp->r_flags |= R4COMMIT;
11571 	mutex_exit(&rp->r_statelock);
11572 	ASSERT(rp->r_commit.c_pages == NULL);
11573 	rp->r_commit.c_pages = pp;
11574 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11575 	rp->r_commit.c_commlen = PAGESIZE;
11576 
11577 	/*
11578 	 * Gather together all other pages which can be committed.
11579 	 * They will all be chained off r_commit.c_pages.
11580 	 */
11581 	nfs4_get_commit(vp);
11582 
11583 	/*
11584 	 * Clear the `commit inprogress' status and disconnect
11585 	 * the list of pages to be committed from the rnode.
11586 	 * At this same time, we also save the starting offset
11587 	 * and length of data to be committed on the server.
11588 	 */
11589 	plist = rp->r_commit.c_pages;
11590 	rp->r_commit.c_pages = NULL;
11591 	offset = rp->r_commit.c_commbase;
11592 	len = rp->r_commit.c_commlen;
11593 	mutex_enter(&rp->r_statelock);
11594 	rp->r_flags &= ~R4COMMIT;
11595 	cv_broadcast(&rp->r_commit.c_cv);
11596 	mutex_exit(&rp->r_statelock);
11597 
11598 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11599 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11600 		nfs4_async_commit(vp, plist, offset, len,
11601 		    cr, do_nfs4_async_commit);
11602 		return;
11603 	}
11604 
11605 	/*
11606 	 * Actually generate the COMMIT op over the wire operation.
11607 	 */
11608 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11609 
11610 	/*
11611 	 * If we got an error during the commit, just unlock all
11612 	 * of the pages.  The pages will get retransmitted to the
11613 	 * server during a putpage operation.
11614 	 */
11615 	if (error) {
11616 		while (plist != NULL) {
11617 			pptr = plist;
11618 			page_sub(&plist, pptr);
11619 			page_unlock(pptr);
11620 		}
11621 		return;
11622 	}
11623 
11624 	/*
11625 	 * We've tried as hard as we can to commit the data to stable
11626 	 * storage on the server.  We just unlock the rest of the pages
11627 	 * and clear the commit required state.  They will be put
11628 	 * onto the tail of the cachelist if they are nolonger
11629 	 * mapped.
11630 	 */
11631 	while (plist != pp) {
11632 		pptr = plist;
11633 		page_sub(&plist, pptr);
11634 		pptr->p_fsdata = C_NOCOMMIT;
11635 		page_unlock(pptr);
11636 	}
11637 
11638 	/*
11639 	 * It is possible that nfs4_commit didn't return error but
11640 	 * some other thread has modified the page we are going
11641 	 * to free/destroy.
11642 	 *    In this case we need to rewrite the page. Do an explicit check
11643 	 * before attempting to free/destroy the page. If modified, needs to
11644 	 * be rewritten so unlock the page and return.
11645 	 */
11646 	if (hat_ismod(pp)) {
11647 		pp->p_fsdata = C_NOCOMMIT;
11648 		page_unlock(pp);
11649 		return;
11650 	}
11651 
11652 	/*
11653 	 * Now, as appropriate, either free or destroy the page
11654 	 * that we were called with.
11655 	 */
11656 	pp->p_fsdata = C_NOCOMMIT;
11657 	if (fl == B_FREE)
11658 		page_free(pp, dn);
11659 	else
11660 		page_destroy(pp, dn);
11661 }
11662 
11663 /*
11664  * Commit requires that the current fh be the file written to.
11665  * The compound op structure is:
11666  *      PUTFH(file), COMMIT
11667  */
11668 static int
11669 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11670 {
11671 	COMPOUND4args_clnt args;
11672 	COMPOUND4res_clnt res;
11673 	COMMIT4res *cm_res;
11674 	nfs_argop4 argop[2];
11675 	nfs_resop4 *resop;
11676 	int doqueue;
11677 	mntinfo4_t *mi;
11678 	rnode4_t *rp;
11679 	cred_t *cred_otw = NULL;
11680 	bool_t needrecov = FALSE;
11681 	nfs4_recov_state_t recov_state;
11682 	nfs4_open_stream_t *osp = NULL;
11683 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11684 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11685 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11686 
11687 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11688 
11689 	rp = VTOR4(vp);
11690 
11691 	mi = VTOMI4(vp);
11692 	recov_state.rs_flags = 0;
11693 	recov_state.rs_num_retry_despite_err = 0;
11694 get_commit_cred:
11695 	/*
11696 	 * Releases the osp, if a valid open stream is provided.
11697 	 * Puts a hold on the cred_otw and the new osp (if found).
11698 	 */
11699 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11700 	    &first_time, &last_time);
11701 	args.ctag = TAG_COMMIT;
11702 recov_retry:
11703 	/*
11704 	 * Commit ops: putfh file; commit
11705 	 */
11706 	args.array_len = 2;
11707 	args.array = argop;
11708 
11709 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11710 	    &recov_state, NULL);
11711 	if (e.error) {
11712 		crfree(cred_otw);
11713 		if (osp != NULL)
11714 			open_stream_rele(osp, rp);
11715 		return (e.error);
11716 	}
11717 
11718 	/* putfh directory */
11719 	argop[0].argop = OP_CPUTFH;
11720 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11721 
11722 	/* commit */
11723 	argop[1].argop = OP_COMMIT;
11724 	argop[1].nfs_argop4_u.opcommit.offset = offset;
11725 	argop[1].nfs_argop4_u.opcommit.count = count;
11726 
11727 	doqueue = 1;
11728 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
11729 
11730 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
11731 	if (!needrecov && e.error) {
11732 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
11733 		    needrecov);
11734 		crfree(cred_otw);
11735 		if (e.error == EACCES && last_time == FALSE)
11736 			goto get_commit_cred;
11737 		if (osp != NULL)
11738 			open_stream_rele(osp, rp);
11739 		return (e.error);
11740 	}
11741 
11742 	if (needrecov) {
11743 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
11744 		    NULL, OP_COMMIT, NULL) == FALSE) {
11745 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11746 			    &recov_state, needrecov);
11747 			if (!e.error)
11748 				(void) xdr_free(xdr_COMPOUND4res_clnt,
11749 				    (caddr_t)&res);
11750 			goto recov_retry;
11751 		}
11752 		if (e.error) {
11753 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11754 			    &recov_state, needrecov);
11755 			crfree(cred_otw);
11756 			if (osp != NULL)
11757 				open_stream_rele(osp, rp);
11758 			return (e.error);
11759 		}
11760 		/* fall through for res.status case */
11761 	}
11762 
11763 	if (res.status) {
11764 		e.error = geterrno4(res.status);
11765 		if (e.error == EACCES && last_time == FALSE) {
11766 			crfree(cred_otw);
11767 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11768 			    &recov_state, needrecov);
11769 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11770 			goto get_commit_cred;
11771 		}
11772 		/*
11773 		 * Can't do a nfs4_purge_stale_fh here because this
11774 		 * can cause a deadlock.  nfs4_commit can
11775 		 * be called from nfs4_dispose which can be called
11776 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
11777 		 * can call back to pvn_vplist_dirty.
11778 		 */
11779 		if (e.error == ESTALE) {
11780 			mutex_enter(&rp->r_statelock);
11781 			rp->r_flags |= R4STALE;
11782 			if (!rp->r_error)
11783 				rp->r_error = e.error;
11784 			mutex_exit(&rp->r_statelock);
11785 			PURGE_ATTRCACHE4(vp);
11786 		} else {
11787 			mutex_enter(&rp->r_statelock);
11788 			if (!rp->r_error)
11789 				rp->r_error = e.error;
11790 			mutex_exit(&rp->r_statelock);
11791 		}
11792 	} else {
11793 		ASSERT(rp->r_flags & R4HAVEVERF);
11794 		resop = &res.array[1];	/* commit res */
11795 		cm_res = &resop->nfs_resop4_u.opcommit;
11796 		mutex_enter(&rp->r_statelock);
11797 		if (cm_res->writeverf == rp->r_writeverf) {
11798 			mutex_exit(&rp->r_statelock);
11799 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11800 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11801 			    &recov_state, needrecov);
11802 			crfree(cred_otw);
11803 			if (osp != NULL)
11804 				open_stream_rele(osp, rp);
11805 			return (0);
11806 		}
11807 		nfs4_set_mod(vp);
11808 		rp->r_writeverf = cm_res->writeverf;
11809 		mutex_exit(&rp->r_statelock);
11810 		e.error = NFS_VERF_MISMATCH;
11811 	}
11812 
11813 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11814 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
11815 	crfree(cred_otw);
11816 	if (osp != NULL)
11817 		open_stream_rele(osp, rp);
11818 
11819 	return (e.error);
11820 }
11821 
11822 static void
11823 nfs4_set_mod(vnode_t *vp)
11824 {
11825 	page_t *pp;
11826 	kmutex_t *vphm;
11827 	rnode4_t *rp;
11828 
11829 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11830 
11831 	/* make sure we're looking at the master vnode, not a shadow */
11832 
11833 	rp = VTOR4(vp);
11834 	if (IS_SHADOW(vp, rp))
11835 		vp = RTOV4(rp);
11836 
11837 	vphm = page_vnode_mutex(vp);
11838 	mutex_enter(vphm);
11839 	/*
11840 	 * If there are no pages associated with this vnode, then
11841 	 * just return.
11842 	 */
11843 	if ((pp = vp->v_pages) == NULL) {
11844 		mutex_exit(vphm);
11845 		return;
11846 	}
11847 
11848 	do {
11849 		if (pp->p_fsdata != C_NOCOMMIT) {
11850 			hat_setmod(pp);
11851 			pp->p_fsdata = C_NOCOMMIT;
11852 		}
11853 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11854 	mutex_exit(vphm);
11855 }
11856 
11857 /*
11858  * This function is used to gather a page list of the pages which
11859  * can be committed on the server.
11860  *
11861  * The calling thread must have set R4COMMIT.  This bit is used to
11862  * serialize access to the commit structure in the rnode.  As long
11863  * as the thread has set R4COMMIT, then it can manipulate the commit
11864  * structure without requiring any other locks.
11865  *
11866  * When this function is called from nfs4_dispose() the page passed
11867  * into nfs4_dispose() will be SE_EXCL locked, and so this function
11868  * will skip it. This is not a problem since we initially add the
11869  * page to the r_commit page list.
11870  *
11871  */
11872 static void
11873 nfs4_get_commit(vnode_t *vp)
11874 {
11875 	rnode4_t *rp;
11876 	page_t *pp;
11877 	kmutex_t *vphm;
11878 
11879 	rp = VTOR4(vp);
11880 
11881 	ASSERT(rp->r_flags & R4COMMIT);
11882 
11883 	/* make sure we're looking at the master vnode, not a shadow */
11884 
11885 	if (IS_SHADOW(vp, rp))
11886 		vp = RTOV4(rp);
11887 
11888 	vphm = page_vnode_mutex(vp);
11889 	mutex_enter(vphm);
11890 
11891 	/*
11892 	 * If there are no pages associated with this vnode, then
11893 	 * just return.
11894 	 */
11895 	if ((pp = vp->v_pages) == NULL) {
11896 		mutex_exit(vphm);
11897 		return;
11898 	}
11899 
11900 	/*
11901 	 * Step through all of the pages associated with this vnode
11902 	 * looking for pages which need to be committed.
11903 	 */
11904 	do {
11905 		/*
11906 		 * First short-cut everything (without the page_lock)
11907 		 * and see if this page does not need to be committed
11908 		 * or is modified if so then we'll just skip it.
11909 		 */
11910 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
11911 			continue;
11912 
11913 		/*
11914 		 * Attempt to lock the page.  If we can't, then
11915 		 * someone else is messing with it or we have been
11916 		 * called from nfs4_dispose and this is the page that
11917 		 * nfs4_dispose was called with.. anyway just skip it.
11918 		 */
11919 		if (!page_trylock(pp, SE_EXCL))
11920 			continue;
11921 
11922 		/*
11923 		 * Lets check again now that we have the page lock.
11924 		 */
11925 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11926 			page_unlock(pp);
11927 			continue;
11928 		}
11929 
11930 		/* this had better not be a free page */
11931 		ASSERT(PP_ISFREE(pp) == 0);
11932 
11933 		/*
11934 		 * The page needs to be committed and we locked it.
11935 		 * Update the base and length parameters and add it
11936 		 * to r_pages.
11937 		 */
11938 		if (rp->r_commit.c_pages == NULL) {
11939 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11940 			rp->r_commit.c_commlen = PAGESIZE;
11941 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
11942 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
11943 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
11944 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11945 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
11946 		    <= pp->p_offset) {
11947 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11948 			    rp->r_commit.c_commbase + PAGESIZE;
11949 		}
11950 		page_add(&rp->r_commit.c_pages, pp);
11951 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11952 
11953 	mutex_exit(vphm);
11954 }
11955 
11956 /*
11957  * This routine is used to gather together a page list of the pages
11958  * which are to be committed on the server.  This routine must not
11959  * be called if the calling thread holds any locked pages.
11960  *
11961  * The calling thread must have set R4COMMIT.  This bit is used to
11962  * serialize access to the commit structure in the rnode.  As long
11963  * as the thread has set R4COMMIT, then it can manipulate the commit
11964  * structure without requiring any other locks.
11965  */
11966 static void
11967 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
11968 {
11969 
11970 	rnode4_t *rp;
11971 	page_t *pp;
11972 	u_offset_t end;
11973 	u_offset_t off;
11974 	ASSERT(len != 0);
11975 	rp = VTOR4(vp);
11976 	ASSERT(rp->r_flags & R4COMMIT);
11977 
11978 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11979 
11980 	/* make sure we're looking at the master vnode, not a shadow */
11981 
11982 	if (IS_SHADOW(vp, rp))
11983 		vp = RTOV4(rp);
11984 
11985 	/*
11986 	 * If there are no pages associated with this vnode, then
11987 	 * just return.
11988 	 */
11989 	if ((pp = vp->v_pages) == NULL)
11990 		return;
11991 	/*
11992 	 * Calculate the ending offset.
11993 	 */
11994 	end = soff + len;
11995 	for (off = soff; off < end; off += PAGESIZE) {
11996 		/*
11997 		 * Lookup each page by vp, offset.
11998 		 */
11999 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
12000 			continue;
12001 		/*
12002 		 * If this page does not need to be committed or is
12003 		 * modified, then just skip it.
12004 		 */
12005 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
12006 			page_unlock(pp);
12007 			continue;
12008 		}
12009 
12010 		ASSERT(PP_ISFREE(pp) == 0);
12011 		/*
12012 		 * The page needs to be committed and we locked it.
12013 		 * Update the base and length parameters and add it
12014 		 * to r_pages.
12015 		 */
12016 		if (rp->r_commit.c_pages == NULL) {
12017 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
12018 			rp->r_commit.c_commlen = PAGESIZE;
12019 		} else {
12020 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
12021 			    rp->r_commit.c_commbase + PAGESIZE;
12022 		}
12023 		page_add(&rp->r_commit.c_pages, pp);
12024 	}
12025 }
12026 
12027 /*
12028  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
12029  * Flushes and commits data to the server.
12030  */
12031 static int
12032 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
12033 {
12034 	int error;
12035 	verifier4 write_verf;
12036 	rnode4_t *rp = VTOR4(vp);
12037 
12038 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12039 
12040 	/*
12041 	 * Flush the data portion of the file and then commit any
12042 	 * portions which need to be committed.  This may need to
12043 	 * be done twice if the server has changed state since
12044 	 * data was last written.  The data will need to be
12045 	 * rewritten to the server and then a new commit done.
12046 	 *
12047 	 * In fact, this may need to be done several times if the
12048 	 * server is having problems and crashing while we are
12049 	 * attempting to do this.
12050 	 */
12051 
12052 top:
12053 	/*
12054 	 * Do a flush based on the poff and plen arguments.  This
12055 	 * will synchronously write out any modified pages in the
12056 	 * range specified by (poff, plen). This starts all of the
12057 	 * i/o operations which will be waited for in the next
12058 	 * call to nfs4_putpage
12059 	 */
12060 
12061 	mutex_enter(&rp->r_statelock);
12062 	write_verf = rp->r_writeverf;
12063 	mutex_exit(&rp->r_statelock);
12064 
12065 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr, NULL);
12066 	if (error == EAGAIN)
12067 		error = 0;
12068 
12069 	/*
12070 	 * Do a flush based on the poff and plen arguments.  This
12071 	 * will synchronously write out any modified pages in the
12072 	 * range specified by (poff, plen) and wait until all of
12073 	 * the asynchronous i/o's in that range are done as well.
12074 	 */
12075 	if (!error)
12076 		error = nfs4_putpage(vp, poff, plen, 0, cr, NULL);
12077 
12078 	if (error)
12079 		return (error);
12080 
12081 	mutex_enter(&rp->r_statelock);
12082 	if (rp->r_writeverf != write_verf) {
12083 		mutex_exit(&rp->r_statelock);
12084 		goto top;
12085 	}
12086 	mutex_exit(&rp->r_statelock);
12087 
12088 	/*
12089 	 * Now commit any pages which might need to be committed.
12090 	 * If the error, NFS_VERF_MISMATCH, is returned, then
12091 	 * start over with the flush operation.
12092 	 */
12093 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
12094 
12095 	if (error == NFS_VERF_MISMATCH)
12096 		goto top;
12097 
12098 	return (error);
12099 }
12100 
12101 /*
12102  * nfs4_commit_vp()  will wait for other pending commits and
12103  * will either commit the whole file or a range, plen dictates
12104  * if we commit whole file. a value of zero indicates the whole
12105  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
12106  */
12107 static int
12108 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12109     cred_t *cr, int wait_on_writes)
12110 {
12111 	rnode4_t *rp;
12112 	page_t *plist;
12113 	offset3 offset;
12114 	count3 len;
12115 
12116 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12117 
12118 	rp = VTOR4(vp);
12119 
12120 	/*
12121 	 *  before we gather commitable pages make
12122 	 *  sure there are no outstanding async writes
12123 	 */
12124 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12125 		mutex_enter(&rp->r_statelock);
12126 		while (rp->r_count > 0) {
12127 			cv_wait(&rp->r_cv, &rp->r_statelock);
12128 		}
12129 		mutex_exit(&rp->r_statelock);
12130 	}
12131 
12132 	/*
12133 	 * Set the `commit inprogress' state bit.  We must
12134 	 * first wait until any current one finishes.
12135 	 */
12136 	mutex_enter(&rp->r_statelock);
12137 	while (rp->r_flags & R4COMMIT) {
12138 		rp->r_flags |= R4COMMITWAIT;
12139 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12140 		rp->r_flags &= ~R4COMMITWAIT;
12141 	}
12142 	rp->r_flags |= R4COMMIT;
12143 	mutex_exit(&rp->r_statelock);
12144 
12145 	/*
12146 	 * Gather all of the pages which need to be
12147 	 * committed.
12148 	 */
12149 	if (plen == 0)
12150 		nfs4_get_commit(vp);
12151 	else
12152 		nfs4_get_commit_range(vp, poff, plen);
12153 
12154 	/*
12155 	 * Clear the `commit inprogress' bit and disconnect the
12156 	 * page list which was gathered by nfs4_get_commit.
12157 	 */
12158 	plist = rp->r_commit.c_pages;
12159 	rp->r_commit.c_pages = NULL;
12160 	offset = rp->r_commit.c_commbase;
12161 	len = rp->r_commit.c_commlen;
12162 	mutex_enter(&rp->r_statelock);
12163 	rp->r_flags &= ~R4COMMIT;
12164 	cv_broadcast(&rp->r_commit.c_cv);
12165 	mutex_exit(&rp->r_statelock);
12166 
12167 	/*
12168 	 * If any pages need to be committed, commit them and
12169 	 * then unlock them so that they can be freed some
12170 	 * time later.
12171 	 */
12172 	if (plist == NULL)
12173 		return (0);
12174 
12175 	/*
12176 	 * No error occurred during the flush portion
12177 	 * of this operation, so now attempt to commit
12178 	 * the data to stable storage on the server.
12179 	 *
12180 	 * This will unlock all of the pages on the list.
12181 	 */
12182 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12183 }
12184 
12185 static int
12186 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12187     cred_t *cr)
12188 {
12189 	int error;
12190 	page_t *pp;
12191 
12192 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12193 
12194 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12195 
12196 	/*
12197 	 * If we got an error, then just unlock all of the pages
12198 	 * on the list.
12199 	 */
12200 	if (error) {
12201 		while (plist != NULL) {
12202 			pp = plist;
12203 			page_sub(&plist, pp);
12204 			page_unlock(pp);
12205 		}
12206 		return (error);
12207 	}
12208 	/*
12209 	 * We've tried as hard as we can to commit the data to stable
12210 	 * storage on the server.  We just unlock the pages and clear
12211 	 * the commit required state.  They will get freed later.
12212 	 */
12213 	while (plist != NULL) {
12214 		pp = plist;
12215 		page_sub(&plist, pp);
12216 		pp->p_fsdata = C_NOCOMMIT;
12217 		page_unlock(pp);
12218 	}
12219 
12220 	return (error);
12221 }
12222 
12223 static void
12224 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12225     cred_t *cr)
12226 {
12227 
12228 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12229 }
12230 
12231 /*ARGSUSED*/
12232 static int
12233 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12234 	caller_context_t *ct)
12235 {
12236 	int		error = 0;
12237 	mntinfo4_t	*mi;
12238 	vattr_t		va;
12239 	vsecattr_t	nfsace4_vsap;
12240 
12241 	mi = VTOMI4(vp);
12242 	if (nfs_zone() != mi->mi_zone)
12243 		return (EIO);
12244 	if (mi->mi_flags & MI4_ACL) {
12245 		/* if we have a delegation, return it */
12246 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12247 			(void) nfs4delegreturn(VTOR4(vp),
12248 			    NFS4_DR_REOPEN|NFS4_DR_PUSH);
12249 
12250 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12251 		    NFS4_ACL_SET);
12252 		if (error) /* EINVAL */
12253 			return (error);
12254 
12255 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12256 			/*
12257 			 * These are aclent_t type entries.
12258 			 */
12259 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12260 			    vp->v_type == VDIR, FALSE);
12261 			if (error)
12262 				return (error);
12263 		} else {
12264 			/*
12265 			 * These are ace_t type entries.
12266 			 */
12267 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12268 			    FALSE);
12269 			if (error)
12270 				return (error);
12271 		}
12272 		bzero(&va, sizeof (va));
12273 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12274 		vs_ace4_destroy(&nfsace4_vsap);
12275 		return (error);
12276 	}
12277 	return (ENOSYS);
12278 }
12279 
12280 /* ARGSUSED */
12281 int
12282 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12283 	caller_context_t *ct)
12284 {
12285 	int		error;
12286 	mntinfo4_t	*mi;
12287 	nfs4_ga_res_t	gar;
12288 	rnode4_t	*rp = VTOR4(vp);
12289 
12290 	mi = VTOMI4(vp);
12291 	if (nfs_zone() != mi->mi_zone)
12292 		return (EIO);
12293 
12294 	bzero(&gar, sizeof (gar));
12295 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12296 
12297 	/*
12298 	 * vsecattr->vsa_mask holds the original acl request mask.
12299 	 * This is needed when determining what to return.
12300 	 * (See: nfs4_create_getsecattr_return())
12301 	 */
12302 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12303 	if (error) /* EINVAL */
12304 		return (error);
12305 
12306 	if (mi->mi_flags & MI4_ACL) {
12307 		/*
12308 		 * Check if the data is cached and the cache is valid.  If it
12309 		 * is we don't go over the wire.
12310 		 */
12311 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12312 			mutex_enter(&rp->r_statelock);
12313 			if (rp->r_secattr != NULL) {
12314 				error = nfs4_create_getsecattr_return(
12315 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12316 				    rp->r_attr.va_gid,
12317 				    vp->v_type == VDIR);
12318 				if (!error) { /* error == 0 - Success! */
12319 					mutex_exit(&rp->r_statelock);
12320 					return (error);
12321 				}
12322 			}
12323 			mutex_exit(&rp->r_statelock);
12324 		}
12325 
12326 		/*
12327 		 * The getattr otw call will always get both the acl, in
12328 		 * the form of a list of nfsace4's, and the number of acl
12329 		 * entries; independent of the value of gar.n4g_vsa.vsa_mask.
12330 		 */
12331 		gar.n4g_va.va_mask = AT_ALL;
12332 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12333 		if (error) {
12334 			vs_ace4_destroy(&gar.n4g_vsa);
12335 			if (error == ENOTSUP || error == EOPNOTSUPP)
12336 				error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12337 			return (error);
12338 		}
12339 
12340 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12341 			/*
12342 			 * No error was returned, but according to the response
12343 			 * bitmap, neither was an acl.
12344 			 */
12345 			vs_ace4_destroy(&gar.n4g_vsa);
12346 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12347 			return (error);
12348 		}
12349 
12350 		/*
12351 		 * Update the cache with the ACL.
12352 		 */
12353 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12354 
12355 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12356 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12357 		    vp->v_type == VDIR);
12358 		vs_ace4_destroy(&gar.n4g_vsa);
12359 		if ((error) && (vsecattr->vsa_mask &
12360 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12361 		    (error != EACCES)) {
12362 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12363 		}
12364 		return (error);
12365 	}
12366 	error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12367 	return (error);
12368 }
12369 
12370 /*
12371  * The function returns:
12372  * 	- 0 (zero) if the passed in "acl_mask" is a valid request.
12373  * 	- EINVAL if the passed in "acl_mask" is an invalid request.
12374  *
12375  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12376  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12377  *
12378  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12379  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12380  * - We have a count field set without the corresponding acl field set. (e.g. -
12381  * VSA_ACECNT is set, but VSA_ACE is not)
12382  */
12383 static int
12384 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12385 {
12386 	/* Shortcut the masks that are always valid. */
12387 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12388 		return (0);
12389 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12390 		return (0);
12391 
12392 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12393 		/*
12394 		 * We can't have any VSA_ACL type stuff in the mask now.
12395 		 */
12396 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12397 		    VSA_DFACLCNT))
12398 			return (EINVAL);
12399 
12400 		if (op == NFS4_ACL_SET) {
12401 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12402 				return (EINVAL);
12403 		}
12404 	}
12405 
12406 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12407 		/*
12408 		 * We can't have any VSA_ACE type stuff in the mask now.
12409 		 */
12410 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12411 			return (EINVAL);
12412 
12413 		if (op == NFS4_ACL_SET) {
12414 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12415 				return (EINVAL);
12416 
12417 			if ((acl_mask & VSA_DFACLCNT) &&
12418 			    !(acl_mask & VSA_DFACL))
12419 				return (EINVAL);
12420 		}
12421 	}
12422 	return (0);
12423 }
12424 
12425 /*
12426  * The theory behind creating the correct getsecattr return is simply this:
12427  * "Don't return anything that the caller is not expecting to have to free."
12428  */
12429 static int
12430 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12431     uid_t uid, gid_t gid, int isdir)
12432 {
12433 	int error = 0;
12434 	/* Save the mask since the translators modify it. */
12435 	uint_t	orig_mask = vsap->vsa_mask;
12436 
12437 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12438 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid,
12439 		    FALSE, ((orig_mask & VSA_ACE) ? FALSE : TRUE));
12440 
12441 		if (error)
12442 			return (error);
12443 
12444 		/*
12445 		 * If the caller only asked for the ace count (VSA_ACECNT)
12446 		 * don't give them the full acl (VSA_ACE), free it.
12447 		 */
12448 		if (!orig_mask & VSA_ACE) {
12449 			if (vsap->vsa_aclentp != NULL) {
12450 				kmem_free(vsap->vsa_aclentp,
12451 				    vsap->vsa_aclcnt * sizeof (ace_t));
12452 				vsap->vsa_aclentp = NULL;
12453 			}
12454 		}
12455 		vsap->vsa_mask = orig_mask;
12456 
12457 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12458 	    VSA_DFACLCNT)) {
12459 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12460 		    isdir, FALSE,
12461 		    ((orig_mask & (VSA_ACL | VSA_DFACL)) ? FALSE : TRUE));
12462 
12463 		if (error)
12464 			return (error);
12465 
12466 		/*
12467 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12468 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12469 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12470 		 */
12471 		if (!orig_mask & VSA_ACL) {
12472 			if (vsap->vsa_aclentp != NULL) {
12473 				kmem_free(vsap->vsa_aclentp,
12474 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12475 				vsap->vsa_aclentp = NULL;
12476 			}
12477 		}
12478 
12479 		if (!orig_mask & VSA_DFACL) {
12480 			if (vsap->vsa_dfaclentp != NULL) {
12481 				kmem_free(vsap->vsa_dfaclentp,
12482 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12483 				vsap->vsa_dfaclentp = NULL;
12484 			}
12485 		}
12486 		vsap->vsa_mask = orig_mask;
12487 	}
12488 	return (0);
12489 }
12490 
12491 /* ARGSUSED */
12492 int
12493 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr,
12494     caller_context_t *ct)
12495 {
12496 	int error;
12497 
12498 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12499 		return (EIO);
12500 	/*
12501 	 * check for valid cmd parameter
12502 	 */
12503 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12504 		return (EINVAL);
12505 
12506 	/*
12507 	 * Check access permissions
12508 	 */
12509 	if ((cmd & F_SHARE) &&
12510 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12511 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12512 		return (EBADF);
12513 
12514 	/*
12515 	 * If the filesystem is mounted using local locking, pass the
12516 	 * request off to the local share code.
12517 	 */
12518 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12519 		return (fs_shrlock(vp, cmd, shr, flag, cr, ct));
12520 
12521 	switch (cmd) {
12522 	case F_SHARE:
12523 	case F_UNSHARE:
12524 		/*
12525 		 * This will be properly implemented later,
12526 		 * see RFE: 4823948 .
12527 		 */
12528 		error = EAGAIN;
12529 		break;
12530 
12531 	case F_HASREMOTELOCKS:
12532 		/*
12533 		 * NFS client can't store remote locks itself
12534 		 */
12535 		shr->s_access = 0;
12536 		error = 0;
12537 		break;
12538 
12539 	default:
12540 		error = EINVAL;
12541 		break;
12542 	}
12543 
12544 	return (error);
12545 }
12546 
12547 /*
12548  * Common code called by directory ops to update the attrcache
12549  */
12550 static int
12551 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12552     hrtime_t t, vnode_t *vp, cred_t *cr)
12553 {
12554 	int error = 0;
12555 
12556 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12557 
12558 	if (status != NFS4_OK) {
12559 		/* getattr not done or failed */
12560 		PURGE_ATTRCACHE4(vp);
12561 		return (error);
12562 	}
12563 
12564 	if (garp) {
12565 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12566 	} else {
12567 		PURGE_ATTRCACHE4(vp);
12568 	}
12569 	return (error);
12570 }
12571 
12572 /*
12573  * Update directory caches for directory modification ops (link, rename, etc.)
12574  * When dinfo is NULL, manage dircaches in the old way.
12575  */
12576 static void
12577 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12578     dirattr_info_t *dinfo)
12579 {
12580 	rnode4_t	*drp = VTOR4(dvp);
12581 
12582 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12583 
12584 	/* Purge rddir cache for dir since it changed */
12585 	if (drp->r_dir != NULL)
12586 		nfs4_purge_rddir_cache(dvp);
12587 
12588 	/*
12589 	 * If caller provided dinfo, then use it to manage dir caches.
12590 	 */
12591 	if (dinfo != NULL) {
12592 		if (vp != NULL) {
12593 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12594 			if (!VTOR4(vp)->created_v4) {
12595 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12596 				dnlc_update(dvp, nm, vp);
12597 			} else {
12598 				/*
12599 				 * XXX don't update if the created_v4 flag is
12600 				 * set
12601 				 */
12602 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12603 				NFS4_DEBUG(nfs4_client_state_debug,
12604 				    (CE_NOTE, "nfs4_update_dircaches: "
12605 				    "don't update dnlc: created_v4 flag"));
12606 			}
12607 		}
12608 
12609 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12610 		    dinfo->di_cred, FALSE, cinfo);
12611 
12612 		return;
12613 	}
12614 
12615 	/*
12616 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12617 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12618 	 * attrs, the dir's attrs must be purged.
12619 	 *
12620 	 * XXX this check and dnlc update/purge should really be atomic,
12621 	 * XXX but can't use rnode statelock because it'll deadlock in
12622 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12623 	 * XXX does occur.
12624 	 *
12625 	 * XXX We also may want to check that atomic is true in the
12626 	 * XXX change_info struct. If it is not, the change_info may
12627 	 * XXX reflect changes by more than one clients which means that
12628 	 * XXX our cache may not be valid.
12629 	 */
12630 	PURGE_ATTRCACHE4(dvp);
12631 	if (drp->r_change == cinfo->before) {
12632 		/* no changes took place in the directory prior to our link */
12633 		if (vp != NULL) {
12634 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12635 			if (!VTOR4(vp)->created_v4) {
12636 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12637 				dnlc_update(dvp, nm, vp);
12638 			} else {
12639 				/*
12640 				 * XXX dont' update if the created_v4 flag
12641 				 * is set
12642 				 */
12643 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12644 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12645 				    "nfs4_update_dircaches: don't"
12646 				    " update dnlc: created_v4 flag"));
12647 			}
12648 		}
12649 	} else {
12650 		/* Another client modified directory - purge its dnlc cache */
12651 		dnlc_purge_vp(dvp);
12652 	}
12653 }
12654 
12655 /*
12656  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12657  * file.
12658  *
12659  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12660  * file (ie: client recovery) and otherwise set to FALSE.
12661  *
12662  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12663  * initiated) calling functions.
12664  *
12665  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12666  * of resending a 'lost' open request.
12667  *
12668  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12669  * server that hands out BAD_SEQID on open confirm.
12670  *
12671  * Errors are returned via the nfs4_error_t parameter.
12672  */
12673 void
12674 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12675     bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12676     bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12677 {
12678 	COMPOUND4args_clnt args;
12679 	COMPOUND4res_clnt res;
12680 	nfs_argop4 argop[2];
12681 	nfs_resop4 *resop;
12682 	int doqueue = 1;
12683 	mntinfo4_t *mi;
12684 	OPEN_CONFIRM4args *open_confirm_args;
12685 	int needrecov;
12686 
12687 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12688 #if DEBUG
12689 	mutex_enter(&oop->oo_lock);
12690 	ASSERT(oop->oo_seqid_inuse);
12691 	mutex_exit(&oop->oo_lock);
12692 #endif
12693 
12694 recov_retry_confirm:
12695 	nfs4_error_zinit(ep);
12696 	*retry_open = FALSE;
12697 
12698 	if (resend)
12699 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12700 	else
12701 		args.ctag = TAG_OPEN_CONFIRM;
12702 
12703 	args.array_len = 2;
12704 	args.array = argop;
12705 
12706 	/* putfh target fh */
12707 	argop[0].argop = OP_CPUTFH;
12708 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12709 
12710 	argop[1].argop = OP_OPEN_CONFIRM;
12711 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12712 
12713 	(*seqid) += 1;
12714 	open_confirm_args->seqid = *seqid;
12715 	open_confirm_args->open_stateid = *stateid;
12716 
12717 	mi = VTOMI4(vp);
12718 
12719 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12720 
12721 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12722 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12723 	}
12724 
12725 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12726 	if (!needrecov && ep->error)
12727 		return;
12728 
12729 	if (needrecov) {
12730 		bool_t abort = FALSE;
12731 
12732 		if (reopening_file == FALSE) {
12733 			nfs4_bseqid_entry_t *bsep = NULL;
12734 
12735 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12736 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12737 				    vp, 0, args.ctag,
12738 				    open_confirm_args->seqid);
12739 
12740 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp,
12741 			    NULL, NULL, NULL, OP_OPEN_CONFIRM, bsep);
12742 			if (bsep) {
12743 				kmem_free(bsep, sizeof (*bsep));
12744 				if (num_bseqid_retryp &&
12745 				    --(*num_bseqid_retryp) == 0)
12746 					abort = TRUE;
12747 			}
12748 		}
12749 		if ((ep->error == ETIMEDOUT ||
12750 		    res.status == NFS4ERR_RESOURCE) &&
12751 		    abort == FALSE && resend == FALSE) {
12752 			if (!ep->error)
12753 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12754 				    (caddr_t)&res);
12755 
12756 			delay(SEC_TO_TICK(confirm_retry_sec));
12757 			goto recov_retry_confirm;
12758 		}
12759 		/* State may have changed so retry the entire OPEN op */
12760 		if (abort == FALSE)
12761 			*retry_open = TRUE;
12762 		else
12763 			*retry_open = FALSE;
12764 		if (!ep->error)
12765 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12766 		return;
12767 	}
12768 
12769 	if (res.status) {
12770 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12771 		return;
12772 	}
12773 
12774 	resop = &res.array[1];  /* open confirm res */
12775 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
12776 	    stateid, sizeof (*stateid));
12777 
12778 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12779 }
12780 
12781 /*
12782  * Return the credentials associated with a client state object.  The
12783  * caller is responsible for freeing the credentials.
12784  */
12785 
12786 static cred_t *
12787 state_to_cred(nfs4_open_stream_t *osp)
12788 {
12789 	cred_t *cr;
12790 
12791 	/*
12792 	 * It's ok to not lock the open stream and open owner to get
12793 	 * the oo_cred since this is only written once (upon creation)
12794 	 * and will not change.
12795 	 */
12796 	cr = osp->os_open_owner->oo_cred;
12797 	crhold(cr);
12798 
12799 	return (cr);
12800 }
12801 
12802 /*
12803  * nfs4_find_sysid
12804  *
12805  * Find the sysid for the knetconfig associated with the given mi.
12806  */
12807 static struct lm_sysid *
12808 nfs4_find_sysid(mntinfo4_t *mi)
12809 {
12810 	ASSERT(nfs_zone() == mi->mi_zone);
12811 
12812 	/*
12813 	 * Switch from RDMA knconf to original mount knconf
12814 	 */
12815 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
12816 	    mi->mi_curr_serv->sv_hostname, NULL));
12817 }
12818 
12819 #ifdef DEBUG
12820 /*
12821  * Return a string version of the call type for easy reading.
12822  */
12823 static char *
12824 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
12825 {
12826 	switch (ctype) {
12827 	case NFS4_LCK_CTYPE_NORM:
12828 		return ("NORMAL");
12829 	case NFS4_LCK_CTYPE_RECLAIM:
12830 		return ("RECLAIM");
12831 	case NFS4_LCK_CTYPE_RESEND:
12832 		return ("RESEND");
12833 	case NFS4_LCK_CTYPE_REINSTATE:
12834 		return ("REINSTATE");
12835 	default:
12836 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
12837 		    "type %d", ctype);
12838 		return ("");
12839 	}
12840 }
12841 #endif
12842 
12843 /*
12844  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
12845  * Unlock requests don't have an over-the-wire locktype, so we just return
12846  * something non-threatening.
12847  */
12848 
12849 static nfs_lock_type4
12850 flk_to_locktype(int cmd, int l_type)
12851 {
12852 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
12853 
12854 	switch (l_type) {
12855 	case F_UNLCK:
12856 		return (READ_LT);
12857 	case F_RDLCK:
12858 		if (cmd == F_SETLK)
12859 			return (READ_LT);
12860 		else
12861 			return (READW_LT);
12862 	case F_WRLCK:
12863 		if (cmd == F_SETLK)
12864 			return (WRITE_LT);
12865 		else
12866 			return (WRITEW_LT);
12867 	}
12868 	panic("flk_to_locktype");
12869 	/*NOTREACHED*/
12870 }
12871 
12872 /*
12873  * Do some preliminary checks for nfs4frlock.
12874  */
12875 static int
12876 nfs4frlock_validate_args(int cmd, flock64_t *flk, int flag, vnode_t *vp,
12877     u_offset_t offset)
12878 {
12879 	int error = 0;
12880 
12881 	/*
12882 	 * If we are setting a lock, check that the file is opened
12883 	 * with the correct mode.
12884 	 */
12885 	if (cmd == F_SETLK || cmd == F_SETLKW) {
12886 		if ((flk->l_type == F_RDLCK && (flag & FREAD) == 0) ||
12887 		    (flk->l_type == F_WRLCK && (flag & FWRITE) == 0)) {
12888 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12889 			    "nfs4frlock_validate_args: file was opened with "
12890 			    "incorrect mode"));
12891 			return (EBADF);
12892 		}
12893 	}
12894 
12895 	/* Convert the offset. It may need to be restored before returning. */
12896 	if (error = convoff(vp, flk, 0, offset)) {
12897 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12898 		    "nfs4frlock_validate_args: convoff  =>  error= %d\n",
12899 		    error));
12900 		return (error);
12901 	}
12902 
12903 	return (error);
12904 }
12905 
12906 /*
12907  * Set the flock64's lm_sysid for nfs4frlock.
12908  */
12909 static int
12910 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
12911 {
12912 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12913 
12914 	/* Find the lm_sysid */
12915 	*lspp = nfs4_find_sysid(VTOMI4(vp));
12916 
12917 	if (*lspp == NULL) {
12918 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12919 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
12920 		return (ENOLCK);
12921 	}
12922 
12923 	flk->l_sysid = lm_sysidt(*lspp);
12924 
12925 	return (0);
12926 }
12927 
12928 /*
12929  * Do the remaining preliminary setup for nfs4frlock.
12930  */
12931 static void
12932 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
12933     flock64_t *flk, short *whencep, vnode_t *vp, cred_t *search_cr,
12934     cred_t **cred_otw)
12935 {
12936 	/*
12937 	 * set tick_delay to the base delay time.
12938 	 * (NFS4_BASE_WAIT_TIME is in secs)
12939 	 */
12940 
12941 	*tick_delayp = drv_usectohz(NFS4_BASE_WAIT_TIME * 1000 * 1000);
12942 
12943 	/*
12944 	 * If lock is relative to EOF, we need the newest length of the
12945 	 * file. Therefore invalidate the ATTR_CACHE.
12946 	 */
12947 
12948 	*whencep = flk->l_whence;
12949 
12950 	if (*whencep == 2)		/* SEEK_END */
12951 		PURGE_ATTRCACHE4(vp);
12952 
12953 	recov_statep->rs_flags = 0;
12954 	recov_statep->rs_num_retry_despite_err = 0;
12955 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
12956 }
12957 
12958 /*
12959  * Initialize and allocate the data structures necessary for
12960  * the nfs4frlock call.
12961  * Allocates argsp's op array, frees up the saved_rqstpp if there is one.
12962  */
12963 static void
12964 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
12965     nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
12966     bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
12967     bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
12968 {
12969 	int		argoplist_size;
12970 	int		num_ops = 2;
12971 
12972 	*retry = FALSE;
12973 	*did_start_fop = FALSE;
12974 	*skip_get_err = FALSE;
12975 	lost_rqstp->lr_op = 0;
12976 	argoplist_size  = num_ops * sizeof (nfs_argop4);
12977 	/* fill array with zero */
12978 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
12979 
12980 	*argspp = argsp;
12981 	*respp = NULL;
12982 
12983 	argsp->array_len = num_ops;
12984 	argsp->array = *argopp;
12985 
12986 	/* initialize in case of error; will get real value down below */
12987 	argsp->ctag = TAG_NONE;
12988 
12989 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
12990 		*op_hintp = OH_LOCKU;
12991 	else
12992 		*op_hintp = OH_OTHER;
12993 }
12994 
12995 /*
12996  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
12997  * the proper nfs4_server_t for this instance of nfs4frlock.
12998  * Returns 0 (success) or an errno value.
12999  */
13000 static int
13001 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
13002     nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
13003     bool_t *did_start_fop, bool_t *startrecovp)
13004 {
13005 	int error = 0;
13006 	rnode4_t *rp;
13007 
13008 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13009 
13010 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13011 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
13012 		    recov_statep, startrecovp);
13013 		if (error)
13014 			return (error);
13015 		*did_start_fop = TRUE;
13016 	} else {
13017 		*did_start_fop = FALSE;
13018 		*startrecovp = FALSE;
13019 	}
13020 
13021 	if (!error) {
13022 		rp = VTOR4(vp);
13023 
13024 		/* If the file failed recovery, just quit. */
13025 		mutex_enter(&rp->r_statelock);
13026 		if (rp->r_flags & R4RECOVERR) {
13027 			error = EIO;
13028 		}
13029 		mutex_exit(&rp->r_statelock);
13030 	}
13031 
13032 	return (error);
13033 }
13034 
13035 /*
13036  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
13037  * resend nfs4frlock call is initiated by the recovery framework.
13038  * Acquires the lop and oop seqid synchronization.
13039  */
13040 static void
13041 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
13042     COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
13043     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13044     LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
13045 {
13046 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
13047 	int error;
13048 
13049 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
13050 	    (CE_NOTE,
13051 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
13052 	ASSERT(resend_rqstp != NULL);
13053 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
13054 	    resend_rqstp->lr_op == OP_LOCKU);
13055 
13056 	*oopp = resend_rqstp->lr_oop;
13057 	if (resend_rqstp->lr_oop) {
13058 		open_owner_hold(resend_rqstp->lr_oop);
13059 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
13060 		ASSERT(error == 0);	/* recov thread always succeeds */
13061 	}
13062 
13063 	/* Must resend this lost lock/locku request. */
13064 	ASSERT(resend_rqstp->lr_lop != NULL);
13065 	*lopp = resend_rqstp->lr_lop;
13066 	lock_owner_hold(resend_rqstp->lr_lop);
13067 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
13068 	ASSERT(error == 0);	/* recov thread always succeeds */
13069 
13070 	*ospp = resend_rqstp->lr_osp;
13071 	if (*ospp)
13072 		open_stream_hold(resend_rqstp->lr_osp);
13073 
13074 	if (resend_rqstp->lr_op == OP_LOCK) {
13075 		LOCK4args *lock_args;
13076 
13077 		argop->argop = OP_LOCK;
13078 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
13079 		lock_args->locktype = resend_rqstp->lr_locktype;
13080 		lock_args->reclaim =
13081 		    (resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
13082 		lock_args->offset = resend_rqstp->lr_flk->l_start;
13083 		lock_args->length = resend_rqstp->lr_flk->l_len;
13084 		if (lock_args->length == 0)
13085 			lock_args->length = ~lock_args->length;
13086 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
13087 		    mi2clientid(mi), &lock_args->locker);
13088 
13089 		switch (resend_rqstp->lr_ctype) {
13090 		case NFS4_LCK_CTYPE_RESEND:
13091 			argsp->ctag = TAG_LOCK_RESEND;
13092 			break;
13093 		case NFS4_LCK_CTYPE_REINSTATE:
13094 			argsp->ctag = TAG_LOCK_REINSTATE;
13095 			break;
13096 		case NFS4_LCK_CTYPE_RECLAIM:
13097 			argsp->ctag = TAG_LOCK_RECLAIM;
13098 			break;
13099 		default:
13100 			argsp->ctag = TAG_LOCK_UNKNOWN;
13101 			break;
13102 		}
13103 	} else {
13104 		LOCKU4args *locku_args;
13105 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
13106 
13107 		argop->argop = OP_LOCKU;
13108 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
13109 		locku_args->locktype = READ_LT;
13110 		locku_args->seqid = lop->lock_seqid + 1;
13111 		mutex_enter(&lop->lo_lock);
13112 		locku_args->lock_stateid = lop->lock_stateid;
13113 		mutex_exit(&lop->lo_lock);
13114 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13115 		locku_args->length = resend_rqstp->lr_flk->l_len;
13116 		if (locku_args->length == 0)
13117 			locku_args->length = ~locku_args->length;
13118 
13119 		switch (resend_rqstp->lr_ctype) {
13120 		case NFS4_LCK_CTYPE_RESEND:
13121 			argsp->ctag = TAG_LOCKU_RESEND;
13122 			break;
13123 		case NFS4_LCK_CTYPE_REINSTATE:
13124 			argsp->ctag = TAG_LOCKU_REINSTATE;
13125 			break;
13126 		default:
13127 			argsp->ctag = TAG_LOCK_UNKNOWN;
13128 			break;
13129 		}
13130 	}
13131 }
13132 
13133 /*
13134  * Setup the LOCKT4 arguments.
13135  */
13136 static void
13137 nfs4frlock_setup_lockt_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13138     LOCKT4args **lockt_argsp, COMPOUND4args_clnt *argsp, flock64_t *flk,
13139     rnode4_t *rp)
13140 {
13141 	LOCKT4args *lockt_args;
13142 
13143 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13144 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13145 	argop->argop = OP_LOCKT;
13146 	argsp->ctag = TAG_LOCKT;
13147 	lockt_args = &argop->nfs_argop4_u.oplockt;
13148 
13149 	/*
13150 	 * The locktype will be READ_LT unless it's
13151 	 * a write lock. We do this because the Solaris
13152 	 * system call allows the combination of
13153 	 * F_UNLCK and F_GETLK* and so in that case the
13154 	 * unlock is mapped to a read.
13155 	 */
13156 	if (flk->l_type == F_WRLCK)
13157 		lockt_args->locktype = WRITE_LT;
13158 	else
13159 		lockt_args->locktype = READ_LT;
13160 
13161 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13162 	/* set the lock owner4 args */
13163 	nfs4_setlockowner_args(&lockt_args->owner, rp,
13164 	    ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13165 	    flk->l_pid);
13166 	lockt_args->offset = flk->l_start;
13167 	lockt_args->length = flk->l_len;
13168 	if (flk->l_len == 0)
13169 		lockt_args->length = ~lockt_args->length;
13170 
13171 	*lockt_argsp = lockt_args;
13172 }
13173 
13174 /*
13175  * If the client is holding a delegation, and the open stream to be used
13176  * with this lock request is a delegation open stream, then re-open the stream.
13177  * Sets the nfs4_error_t to all zeros unless the open stream has already
13178  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13179  * means the caller should retry (like a recovery retry).
13180  */
13181 static void
13182 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13183 {
13184 	open_delegation_type4	dt;
13185 	bool_t			reopen_needed, force;
13186 	nfs4_open_stream_t	*osp;
13187 	open_claim_type4 	oclaim;
13188 	rnode4_t		*rp = VTOR4(vp);
13189 	mntinfo4_t		*mi = VTOMI4(vp);
13190 
13191 	ASSERT(nfs_zone() == mi->mi_zone);
13192 
13193 	nfs4_error_zinit(ep);
13194 
13195 	mutex_enter(&rp->r_statev4_lock);
13196 	dt = rp->r_deleg_type;
13197 	mutex_exit(&rp->r_statev4_lock);
13198 
13199 	if (dt != OPEN_DELEGATE_NONE) {
13200 		nfs4_open_owner_t	*oop;
13201 
13202 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13203 		if (!oop) {
13204 			ep->stat = NFS4ERR_IO;
13205 			return;
13206 		}
13207 		/* returns with 'os_sync_lock' held */
13208 		osp = find_open_stream(oop, rp);
13209 		if (!osp) {
13210 			open_owner_rele(oop);
13211 			ep->stat = NFS4ERR_IO;
13212 			return;
13213 		}
13214 
13215 		if (osp->os_failed_reopen) {
13216 			NFS4_DEBUG((nfs4_open_stream_debug ||
13217 			    nfs4_client_lock_debug), (CE_NOTE,
13218 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13219 			    "for osp %p, cr %p, rp %s", (void *)osp,
13220 			    (void *)cr, rnode4info(rp)));
13221 			mutex_exit(&osp->os_sync_lock);
13222 			open_stream_rele(osp, rp);
13223 			open_owner_rele(oop);
13224 			ep->stat = NFS4ERR_IO;
13225 			return;
13226 		}
13227 
13228 		/*
13229 		 * Determine whether a reopen is needed.  If this
13230 		 * is a delegation open stream, then send the open
13231 		 * to the server to give visibility to the open owner.
13232 		 * Even if it isn't a delegation open stream, we need
13233 		 * to check if the previous open CLAIM_DELEGATE_CUR
13234 		 * was sufficient.
13235 		 */
13236 
13237 		reopen_needed = osp->os_delegation ||
13238 		    ((lt == F_RDLCK &&
13239 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13240 		    (lt == F_WRLCK &&
13241 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13242 
13243 		mutex_exit(&osp->os_sync_lock);
13244 		open_owner_rele(oop);
13245 
13246 		if (reopen_needed) {
13247 			/*
13248 			 * Always use CLAIM_PREVIOUS after server reboot.
13249 			 * The server will reject CLAIM_DELEGATE_CUR if
13250 			 * it is used during the grace period.
13251 			 */
13252 			mutex_enter(&mi->mi_lock);
13253 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13254 				oclaim = CLAIM_PREVIOUS;
13255 				force = TRUE;
13256 			} else {
13257 				oclaim = CLAIM_DELEGATE_CUR;
13258 				force = FALSE;
13259 			}
13260 			mutex_exit(&mi->mi_lock);
13261 
13262 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13263 			if (ep->error == EAGAIN) {
13264 				nfs4_error_zinit(ep);
13265 				ep->stat = NFS4ERR_DELAY;
13266 			}
13267 		}
13268 		open_stream_rele(osp, rp);
13269 		osp = NULL;
13270 	}
13271 }
13272 
13273 /*
13274  * Setup the LOCKU4 arguments.
13275  * Returns errors via the nfs4_error_t.
13276  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13277  *			over-the-wire.  The caller must release the
13278  *			reference on *lopp.
13279  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13280  * (other)		unrecoverable error.
13281  */
13282 static void
13283 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13284     LOCKU4args **locku_argsp, flock64_t *flk,
13285     nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13286     vnode_t *vp, int flag, u_offset_t offset, cred_t *cr,
13287     bool_t *skip_get_err, bool_t *go_otwp)
13288 {
13289 	nfs4_lock_owner_t	*lop = NULL;
13290 	LOCKU4args		*locku_args;
13291 	pid_t			pid;
13292 	bool_t			is_spec = FALSE;
13293 	rnode4_t		*rp = VTOR4(vp);
13294 
13295 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13296 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13297 
13298 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13299 	if (ep->error || ep->stat)
13300 		return;
13301 
13302 	argop->argop = OP_LOCKU;
13303 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13304 		argsp->ctag = TAG_LOCKU_REINSTATE;
13305 	else
13306 		argsp->ctag = TAG_LOCKU;
13307 	locku_args = &argop->nfs_argop4_u.oplocku;
13308 	*locku_argsp = locku_args;
13309 
13310 	/*
13311 	 * XXX what should locku_args->locktype be?
13312 	 * setting to ALWAYS be READ_LT so at least
13313 	 * it is a valid locktype.
13314 	 */
13315 
13316 	locku_args->locktype = READ_LT;
13317 
13318 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13319 	    flk->l_pid;
13320 
13321 	/*
13322 	 * Get the lock owner stateid.  If no lock owner
13323 	 * exists, return success.
13324 	 */
13325 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13326 	*lopp = lop;
13327 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13328 		is_spec = TRUE;
13329 	if (!lop || is_spec) {
13330 		/*
13331 		 * No lock owner so no locks to unlock.
13332 		 * Return success.  If there was a failed
13333 		 * reclaim earlier, the lock might still be
13334 		 * registered with the local locking code,
13335 		 * so notify it of the unlock.
13336 		 *
13337 		 * If the lockowner is using a special stateid,
13338 		 * then the original lock request (that created
13339 		 * this lockowner) was never successful, so we
13340 		 * have no lock to undo OTW.
13341 		 */
13342 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13343 		    "nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13344 		    "(%ld) so return success", (long)pid));
13345 
13346 		if (ctype == NFS4_LCK_CTYPE_NORM)
13347 			flk->l_pid = curproc->p_pid;
13348 		nfs4_register_lock_locally(vp, flk, flag, offset);
13349 		/*
13350 		 * Release our hold and NULL out so final_cleanup
13351 		 * doesn't try to end a lock seqid sync we
13352 		 * never started.
13353 		 */
13354 		if (is_spec) {
13355 			lock_owner_rele(lop);
13356 			*lopp = NULL;
13357 		}
13358 		*skip_get_err = TRUE;
13359 		*go_otwp = FALSE;
13360 		return;
13361 	}
13362 
13363 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13364 	if (ep->error == EAGAIN) {
13365 		lock_owner_rele(lop);
13366 		*lopp = NULL;
13367 		return;
13368 	}
13369 
13370 	mutex_enter(&lop->lo_lock);
13371 	locku_args->lock_stateid = lop->lock_stateid;
13372 	mutex_exit(&lop->lo_lock);
13373 	locku_args->seqid = lop->lock_seqid + 1;
13374 
13375 	/* leave the ref count on lop, rele after RPC call */
13376 
13377 	locku_args->offset = flk->l_start;
13378 	locku_args->length = flk->l_len;
13379 	if (flk->l_len == 0)
13380 		locku_args->length = ~locku_args->length;
13381 
13382 	*go_otwp = TRUE;
13383 }
13384 
13385 /*
13386  * Setup the LOCK4 arguments.
13387  *
13388  * Returns errors via the nfs4_error_t.
13389  * NFS4_OK		no problems
13390  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13391  * (other)		unrecoverable error
13392  */
13393 static void
13394 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13395     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13396     nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13397     flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13398 {
13399 	LOCK4args		*lock_args;
13400 	nfs4_open_owner_t	*oop = NULL;
13401 	nfs4_open_stream_t	*osp = NULL;
13402 	nfs4_lock_owner_t	*lop = NULL;
13403 	pid_t			pid;
13404 	rnode4_t		*rp = VTOR4(vp);
13405 
13406 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13407 
13408 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13409 	if (ep->error || ep->stat != NFS4_OK)
13410 		return;
13411 
13412 	argop->argop = OP_LOCK;
13413 	if (ctype == NFS4_LCK_CTYPE_NORM)
13414 		argsp->ctag = TAG_LOCK;
13415 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13416 		argsp->ctag = TAG_RELOCK;
13417 	else
13418 		argsp->ctag = TAG_LOCK_REINSTATE;
13419 	lock_args = &argop->nfs_argop4_u.oplock;
13420 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13421 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13422 	/*
13423 	 * Get the lock owner.  If no lock owner exists,
13424 	 * create a 'temporary' one and grab the open seqid
13425 	 * synchronization (which puts a hold on the open
13426 	 * owner and open stream).
13427 	 * This also grabs the lock seqid synchronization.
13428 	 */
13429 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid : flk->l_pid;
13430 	ep->stat =
13431 	    nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13432 
13433 	if (ep->stat != NFS4_OK)
13434 		goto out;
13435 
13436 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13437 	    &lock_args->locker);
13438 
13439 	lock_args->offset = flk->l_start;
13440 	lock_args->length = flk->l_len;
13441 	if (flk->l_len == 0)
13442 		lock_args->length = ~lock_args->length;
13443 	*lock_argsp = lock_args;
13444 out:
13445 	*oopp = oop;
13446 	*ospp = osp;
13447 	*lopp = lop;
13448 }
13449 
13450 /*
13451  * After we get the reply from the server, record the proper information
13452  * for possible resend lock requests.
13453  *
13454  * Allocates memory for the saved_rqstp if we have a lost lock to save.
13455  */
13456 static void
13457 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13458     nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13459     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13460     nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13461 {
13462 	bool_t unlock = (flk->l_type == F_UNLCK);
13463 
13464 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13465 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13466 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13467 
13468 	if (error != 0 && !unlock) {
13469 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13470 		    nfs4_client_lock_debug), (CE_NOTE,
13471 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13472 		    " for lop %p", (void *)lop));
13473 		ASSERT(lop != NULL);
13474 		mutex_enter(&lop->lo_lock);
13475 		lop->lo_pending_rqsts = 1;
13476 		mutex_exit(&lop->lo_lock);
13477 	}
13478 
13479 	lost_rqstp->lr_putfirst = FALSE;
13480 	lost_rqstp->lr_op = 0;
13481 
13482 	/*
13483 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13484 	 * recovery purposes so that the lock request that was sent
13485 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13486 	 * unmount.  This is done to have the client's local locking state
13487 	 * match the v4 server's state; that is, the request was
13488 	 * potentially received and accepted by the server but the client
13489 	 * thinks it was not.
13490 	 */
13491 	if (error == ETIMEDOUT || error == EINTR ||
13492 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13493 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13494 		    nfs4_client_lock_debug), (CE_NOTE,
13495 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13496 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13497 		    (void *)lop, (void *)oop, (void *)osp));
13498 		if (unlock)
13499 			lost_rqstp->lr_op = OP_LOCKU;
13500 		else {
13501 			lost_rqstp->lr_op = OP_LOCK;
13502 			lost_rqstp->lr_locktype = locktype;
13503 		}
13504 		/*
13505 		 * Objects are held and rele'd via the recovery code.
13506 		 * See nfs4_save_lost_rqst.
13507 		 */
13508 		lost_rqstp->lr_vp = vp;
13509 		lost_rqstp->lr_dvp = NULL;
13510 		lost_rqstp->lr_oop = oop;
13511 		lost_rqstp->lr_osp = osp;
13512 		lost_rqstp->lr_lop = lop;
13513 		lost_rqstp->lr_cr = cr;
13514 		switch (ctype) {
13515 		case NFS4_LCK_CTYPE_NORM:
13516 			flk->l_pid = ttoproc(curthread)->p_pid;
13517 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13518 			break;
13519 		case NFS4_LCK_CTYPE_REINSTATE:
13520 			lost_rqstp->lr_putfirst = TRUE;
13521 			lost_rqstp->lr_ctype = ctype;
13522 			break;
13523 		default:
13524 			break;
13525 		}
13526 		lost_rqstp->lr_flk = flk;
13527 	}
13528 }
13529 
13530 /*
13531  * Update lop's seqid.  Also update the seqid stored in a resend request,
13532  * if any.  (Some recovery errors increment the seqid, and we may have to
13533  * send the resend request again.)
13534  */
13535 
13536 static void
13537 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13538     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13539 {
13540 	if (lock_args) {
13541 		if (lock_args->locker.new_lock_owner == TRUE)
13542 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13543 		else {
13544 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13545 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13546 		}
13547 	} else if (locku_args) {
13548 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13549 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13550 	}
13551 }
13552 
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  * Switches the *cred_otwp to base_cr.
13557  */
13558 static void
13559 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13560     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13561     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13562     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13563     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13564 {
13565 	nfs4_open_owner_t	*oop = *oopp;
13566 	nfs4_open_stream_t	*osp = *ospp;
13567 	nfs4_lock_owner_t	*lop = *lopp;
13568 	nfs_argop4		*argop = (*argspp)->array;
13569 
13570 	if (*did_start_fop) {
13571 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13572 		    needrecov);
13573 		*did_start_fop = FALSE;
13574 	}
13575 	ASSERT((*argspp)->array_len == 2);
13576 	if (argop[1].argop == OP_LOCK)
13577 		nfs4args_lock_free(&argop[1]);
13578 	else if (argop[1].argop == OP_LOCKT)
13579 		nfs4args_lockt_free(&argop[1]);
13580 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13581 	if (!error)
13582 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13583 	*argspp = NULL;
13584 	*respp = NULL;
13585 
13586 	if (lop) {
13587 		nfs4_end_lock_seqid_sync(lop);
13588 		lock_owner_rele(lop);
13589 		*lopp = NULL;
13590 	}
13591 
13592 	/* need to free up the reference on osp for lock args */
13593 	if (osp != NULL) {
13594 		open_stream_rele(osp, VTOR4(vp));
13595 		*ospp = NULL;
13596 	}
13597 
13598 	/* need to free up the reference on oop for lock args */
13599 	if (oop != NULL) {
13600 		nfs4_end_open_seqid_sync(oop);
13601 		open_owner_rele(oop);
13602 		*oopp = NULL;
13603 	}
13604 
13605 	crfree(*cred_otwp);
13606 	*cred_otwp = base_cr;
13607 	crhold(*cred_otwp);
13608 }
13609 
13610 /*
13611  * Function to process the client's recovery for nfs4frlock.
13612  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13613  *
13614  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13615  * COMPOUND4 args/res for calls that need to retry.
13616  *
13617  * Note: the rp's r_lkserlock is *not* dropped during this path.
13618  */
13619 static bool_t
13620 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13621     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13622     LOCK4args *lock_args, LOCKU4args *locku_args,
13623     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13624     nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13625     nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13626     bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13627 {
13628 	nfs4_open_owner_t	*oop = *oopp;
13629 	nfs4_open_stream_t	*osp = *ospp;
13630 	nfs4_lock_owner_t	*lop = *lopp;
13631 
13632 	bool_t abort, retry;
13633 
13634 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13635 	ASSERT((*argspp) != NULL);
13636 	ASSERT((*respp) != NULL);
13637 	if (lock_args || locku_args)
13638 		ASSERT(lop != NULL);
13639 
13640 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13641 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13642 
13643 	retry = TRUE;
13644 	abort = FALSE;
13645 	if (needrecov) {
13646 		nfs4_bseqid_entry_t *bsep = NULL;
13647 		nfs_opnum4 op;
13648 
13649 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13650 
13651 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13652 			seqid4 seqid;
13653 
13654 			if (lock_args) {
13655 				if (lock_args->locker.new_lock_owner == TRUE)
13656 					seqid = lock_args->locker.locker4_u.
13657 					    open_owner.open_seqid;
13658 				else
13659 					seqid = lock_args->locker.locker4_u.
13660 					    lock_owner.lock_seqid;
13661 			} else if (locku_args) {
13662 				seqid = locku_args->seqid;
13663 			} else {
13664 				seqid = 0;
13665 			}
13666 
13667 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13668 			    flk->l_pid, (*argspp)->ctag, seqid);
13669 		}
13670 
13671 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13672 		    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13673 		    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13674 		    NULL, op, bsep);
13675 
13676 		if (bsep)
13677 			kmem_free(bsep, sizeof (*bsep));
13678 	}
13679 
13680 	/*
13681 	 * Return that we do not want to retry the request for 3 cases:
13682 	 * 1. If we received EINTR or are bailing out because of a forced
13683 	 *    unmount, we came into this code path just for the sake of
13684 	 *    initiating recovery, we now need to return the error.
13685 	 * 2. If we have aborted recovery.
13686 	 * 3. We received NFS4ERR_BAD_SEQID.
13687 	 */
13688 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13689 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13690 		retry = FALSE;
13691 
13692 	if (*did_start_fop == TRUE) {
13693 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13694 		    needrecov);
13695 		*did_start_fop = FALSE;
13696 	}
13697 
13698 	if (retry == TRUE) {
13699 		nfs_argop4	*argop;
13700 
13701 		argop = (*argspp)->array;
13702 		ASSERT((*argspp)->array_len == 2);
13703 
13704 		if (argop[1].argop == OP_LOCK)
13705 			nfs4args_lock_free(&argop[1]);
13706 		else if (argop[1].argop == OP_LOCKT)
13707 			nfs4args_lockt_free(&argop[1]);
13708 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13709 		if (!ep->error)
13710 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13711 		*respp = NULL;
13712 		*argspp = NULL;
13713 	}
13714 
13715 	if (lop != NULL) {
13716 		nfs4_end_lock_seqid_sync(lop);
13717 		lock_owner_rele(lop);
13718 	}
13719 
13720 	*lopp = NULL;
13721 
13722 	/* need to free up the reference on osp for lock args */
13723 	if (osp != NULL) {
13724 		open_stream_rele(osp, rp);
13725 		*ospp = NULL;
13726 	}
13727 
13728 	/* need to free up the reference on oop for lock args */
13729 	if (oop != NULL) {
13730 		nfs4_end_open_seqid_sync(oop);
13731 		open_owner_rele(oop);
13732 		*oopp = NULL;
13733 	}
13734 
13735 	return (retry);
13736 }
13737 
13738 /*
13739  * Handles the successful reply from the server for nfs4frlock.
13740  */
13741 static void
13742 nfs4frlock_results_ok(nfs4_lock_call_type_t ctype, int cmd, flock64_t *flk,
13743     vnode_t *vp, int flag, u_offset_t offset,
13744     nfs4_lost_rqst_t *resend_rqstp)
13745 {
13746 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13747 	if ((cmd == F_SETLK || cmd == F_SETLKW) &&
13748 	    (flk->l_type == F_RDLCK || flk->l_type == F_WRLCK)) {
13749 		if (ctype == NFS4_LCK_CTYPE_NORM) {
13750 			flk->l_pid = ttoproc(curthread)->p_pid;
13751 			/*
13752 			 * We do not register lost locks locally in
13753 			 * the 'resend' case since the user/application
13754 			 * doesn't think we have the lock.
13755 			 */
13756 			ASSERT(!resend_rqstp);
13757 			nfs4_register_lock_locally(vp, flk, flag, offset);
13758 		}
13759 	}
13760 }
13761 
13762 /*
13763  * Handle the DENIED reply from the server for nfs4frlock.
13764  * Returns TRUE if we should retry the request; FALSE otherwise.
13765  *
13766  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13767  * COMPOUND4 args/res for calls that need to retry.  Can also
13768  * drop and regrab the r_lkserlock.
13769  */
13770 static bool_t
13771 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13772     LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13773     nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13774     vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13775     nfs4_recov_state_t *recov_statep, int needrecov,
13776     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13777     clock_t *tick_delayp, short *whencep, int *errorp,
13778     nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13779     bool_t *skip_get_err)
13780 {
13781 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13782 
13783 	if (lock_args) {
13784 		nfs4_open_owner_t	*oop = *oopp;
13785 		nfs4_open_stream_t	*osp = *ospp;
13786 		nfs4_lock_owner_t	*lop = *lopp;
13787 		int			intr;
13788 
13789 		/*
13790 		 * Blocking lock needs to sleep and retry from the request.
13791 		 *
13792 		 * Do not block and wait for 'resend' or 'reinstate'
13793 		 * lock requests, just return the error.
13794 		 *
13795 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13796 		 */
13797 		if (cmd == F_SETLKW) {
13798 			rnode4_t *rp = VTOR4(vp);
13799 			nfs_argop4 *argop = (*argspp)->array;
13800 
13801 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13802 
13803 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13804 			    recov_statep, needrecov);
13805 			*did_start_fop = FALSE;
13806 			ASSERT((*argspp)->array_len == 2);
13807 			if (argop[1].argop == OP_LOCK)
13808 				nfs4args_lock_free(&argop[1]);
13809 			else if (argop[1].argop == OP_LOCKT)
13810 				nfs4args_lockt_free(&argop[1]);
13811 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13812 			if (*respp)
13813 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13814 				    (caddr_t)*respp);
13815 			*argspp = NULL;
13816 			*respp = NULL;
13817 			nfs4_end_lock_seqid_sync(lop);
13818 			lock_owner_rele(lop);
13819 			*lopp = NULL;
13820 			if (osp != NULL) {
13821 				open_stream_rele(osp, rp);
13822 				*ospp = NULL;
13823 			}
13824 			if (oop != NULL) {
13825 				nfs4_end_open_seqid_sync(oop);
13826 				open_owner_rele(oop);
13827 				*oopp = NULL;
13828 			}
13829 
13830 			nfs_rw_exit(&rp->r_lkserlock);
13831 
13832 			intr = nfs4_block_and_wait(tick_delayp, rp);
13833 
13834 			if (intr) {
13835 				(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13836 				    RW_WRITER, FALSE);
13837 				*errorp = EINTR;
13838 				return (FALSE);
13839 			}
13840 
13841 			(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13842 			    RW_WRITER, FALSE);
13843 
13844 			/*
13845 			 * Make sure we are still safe to lock with
13846 			 * regards to mmapping.
13847 			 */
13848 			if (!nfs4_safelock(vp, flk, cr)) {
13849 				*errorp = EAGAIN;
13850 				return (FALSE);
13851 			}
13852 
13853 			return (TRUE);
13854 		}
13855 		if (ctype == NFS4_LCK_CTYPE_NORM)
13856 			*errorp = EAGAIN;
13857 		*skip_get_err = TRUE;
13858 		flk->l_whence = 0;
13859 		*whencep = 0;
13860 		return (FALSE);
13861 	} else if (lockt_args) {
13862 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13863 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
13864 
13865 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
13866 		    flk, lockt_args);
13867 
13868 		/* according to NLM code */
13869 		*errorp = 0;
13870 		*whencep = 0;
13871 		*skip_get_err = TRUE;
13872 		return (FALSE);
13873 	}
13874 	return (FALSE);
13875 }
13876 
13877 /*
13878  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
13879  */
13880 static void
13881 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
13882 {
13883 	switch (resp->status) {
13884 	case NFS4ERR_ACCESS:
13885 	case NFS4ERR_ADMIN_REVOKED:
13886 	case NFS4ERR_BADHANDLE:
13887 	case NFS4ERR_BAD_RANGE:
13888 	case NFS4ERR_BAD_SEQID:
13889 	case NFS4ERR_BAD_STATEID:
13890 	case NFS4ERR_BADXDR:
13891 	case NFS4ERR_DEADLOCK:
13892 	case NFS4ERR_DELAY:
13893 	case NFS4ERR_EXPIRED:
13894 	case NFS4ERR_FHEXPIRED:
13895 	case NFS4ERR_GRACE:
13896 	case NFS4ERR_INVAL:
13897 	case NFS4ERR_ISDIR:
13898 	case NFS4ERR_LEASE_MOVED:
13899 	case NFS4ERR_LOCK_NOTSUPP:
13900 	case NFS4ERR_LOCK_RANGE:
13901 	case NFS4ERR_MOVED:
13902 	case NFS4ERR_NOFILEHANDLE:
13903 	case NFS4ERR_NO_GRACE:
13904 	case NFS4ERR_OLD_STATEID:
13905 	case NFS4ERR_OPENMODE:
13906 	case NFS4ERR_RECLAIM_BAD:
13907 	case NFS4ERR_RECLAIM_CONFLICT:
13908 	case NFS4ERR_RESOURCE:
13909 	case NFS4ERR_SERVERFAULT:
13910 	case NFS4ERR_STALE:
13911 	case NFS4ERR_STALE_CLIENTID:
13912 	case NFS4ERR_STALE_STATEID:
13913 		return;
13914 	default:
13915 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13916 		    "nfs4frlock_results_default: got unrecognizable "
13917 		    "res.status %d", resp->status));
13918 		*errorp = NFS4ERR_INVAL;
13919 	}
13920 }
13921 
13922 /*
13923  * The lock request was successful, so update the client's state.
13924  */
13925 static void
13926 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
13927     LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
13928     vnode_t *vp, flock64_t *flk, cred_t *cr,
13929     nfs4_lost_rqst_t *resend_rqstp)
13930 {
13931 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13932 
13933 	if (lock_args) {
13934 		LOCK4res *lock_res;
13935 
13936 		lock_res = &resop->nfs_resop4_u.oplock;
13937 		/* update the stateid with server's response */
13938 
13939 		if (lock_args->locker.new_lock_owner == TRUE) {
13940 			mutex_enter(&lop->lo_lock);
13941 			lop->lo_just_created = NFS4_PERM_CREATED;
13942 			mutex_exit(&lop->lo_lock);
13943 		}
13944 
13945 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
13946 
13947 		/*
13948 		 * If the lock was the result of a resending a lost
13949 		 * request, we've synched up the stateid and seqid
13950 		 * with the server, but now the server might be out of sync
13951 		 * with what the application thinks it has for locks.
13952 		 * Clean that up here.  It's unclear whether we should do
13953 		 * this even if the filesystem has been forcibly unmounted.
13954 		 * For most servers, it's probably wasted effort, but
13955 		 * RFC3530 lets servers require that unlocks exactly match
13956 		 * the locks that are held.
13957 		 */
13958 		if (resend_rqstp != NULL &&
13959 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
13960 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
13961 		} else {
13962 			flk->l_whence = 0;
13963 		}
13964 	} else if (locku_args) {
13965 		LOCKU4res *locku_res;
13966 
13967 		locku_res = &resop->nfs_resop4_u.oplocku;
13968 
13969 		/* Update the stateid with the server's response */
13970 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
13971 	} else if (lockt_args) {
13972 		/* Switch the lock type to express success, see fcntl */
13973 		flk->l_type = F_UNLCK;
13974 		flk->l_whence = 0;
13975 	}
13976 }
13977 
13978 /*
13979  * Do final cleanup before exiting nfs4frlock.
13980  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13981  * COMPOUND4 args/res for calls that haven't already.
13982  */
13983 static void
13984 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
13985     COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
13986     nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
13987     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13988     short whence, u_offset_t offset, struct lm_sysid *ls,
13989     int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
13990     bool_t did_start_fop, bool_t skip_get_err,
13991     cred_t *cred_otw, cred_t *cred)
13992 {
13993 	mntinfo4_t	*mi = VTOMI4(vp);
13994 	rnode4_t	*rp = VTOR4(vp);
13995 	int		error = *errorp;
13996 	nfs_argop4	*argop;
13997 
13998 	ASSERT(nfs_zone() == mi->mi_zone);
13999 	/*
14000 	 * The client recovery code wants the raw status information,
14001 	 * so don't map the NFS status code to an errno value for
14002 	 * non-normal call types.
14003 	 */
14004 	if (ctype == NFS4_LCK_CTYPE_NORM) {
14005 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
14006 			*errorp = geterrno4(resp->status);
14007 		if (did_start_fop == TRUE)
14008 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
14009 			    needrecov);
14010 
14011 		/*
14012 		 * We've established a new lock on the server, so invalidate
14013 		 * the pages associated with the vnode to get the most up to
14014 		 * date pages from the server after acquiring the lock. We
14015 		 * want to be sure that the read operation gets the newest data.
14016 		 * N.B.
14017 		 * We used to do this in nfs4frlock_results_ok but that doesn't
14018 		 * work since VOP_PUTPAGE can call nfs4_commit which calls
14019 		 * nfs4_start_fop. We flush the pages below after calling
14020 		 * nfs4_end_fop above
14021 		 */
14022 		if (!error && resp && resp->status == NFS4_OK) {
14023 			int error;
14024 
14025 			error = VOP_PUTPAGE(vp, (u_offset_t)0,
14026 			    0, B_INVAL, cred, NULL);
14027 
14028 			if (error && (error == ENOSPC || error == EDQUOT)) {
14029 				rnode4_t *rp = VTOR4(vp);
14030 
14031 				mutex_enter(&rp->r_statelock);
14032 				if (!rp->r_error)
14033 					rp->r_error = error;
14034 				mutex_exit(&rp->r_statelock);
14035 			}
14036 		}
14037 	}
14038 	if (argsp) {
14039 		ASSERT(argsp->array_len == 2);
14040 		argop = argsp->array;
14041 		if (argop[1].argop == OP_LOCK)
14042 			nfs4args_lock_free(&argop[1]);
14043 		else if (argop[1].argop == OP_LOCKT)
14044 			nfs4args_lockt_free(&argop[1]);
14045 		kmem_free(argop, 2 * sizeof (nfs_argop4));
14046 		if (resp)
14047 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
14048 	}
14049 
14050 	/* free the reference on the lock owner */
14051 	if (lop != NULL) {
14052 		nfs4_end_lock_seqid_sync(lop);
14053 		lock_owner_rele(lop);
14054 	}
14055 
14056 	/* need to free up the reference on osp for lock args */
14057 	if (osp != NULL)
14058 		open_stream_rele(osp, rp);
14059 
14060 	/* need to free up the reference on oop for lock args */
14061 	if (oop != NULL) {
14062 		nfs4_end_open_seqid_sync(oop);
14063 		open_owner_rele(oop);
14064 	}
14065 
14066 	(void) convoff(vp, flk, whence, offset);
14067 
14068 	lm_rel_sysid(ls);
14069 
14070 	/*
14071 	 * Record debug information in the event we get EINVAL.
14072 	 */
14073 	mutex_enter(&mi->mi_lock);
14074 	if (*errorp == EINVAL && (lock_args || locku_args) &&
14075 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
14076 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
14077 			zcmn_err(getzoneid(), CE_NOTE,
14078 			    "%s operation failed with "
14079 			    "EINVAL probably since the server, %s,"
14080 			    " doesn't support POSIX style locking",
14081 			    lock_args ? "LOCK" : "LOCKU",
14082 			    mi->mi_curr_serv->sv_hostname);
14083 			mi->mi_flags |= MI4_LOCK_DEBUG;
14084 		}
14085 	}
14086 	mutex_exit(&mi->mi_lock);
14087 
14088 	if (cred_otw)
14089 		crfree(cred_otw);
14090 }
14091 
14092 /*
14093  * This calls the server and the local locking code.
14094  *
14095  * Client locks are registerred locally by oring the sysid with
14096  * LM_SYSID_CLIENT. The server registers locks locally using just the sysid.
14097  * We need to distinguish between the two to avoid collision in case one
14098  * machine is used as both client and server.
14099  *
14100  * Blocking lock requests will continually retry to acquire the lock
14101  * forever.
14102  *
14103  * The ctype is defined as follows:
14104  * NFS4_LCK_CTYPE_NORM: normal lock request.
14105  *
14106  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
14107  * recovery, get the pid from flk instead of curproc, and don't reregister
14108  * the lock locally.
14109  *
14110  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
14111  * that we will use the information passed in via resend_rqstp to setup the
14112  * lock/locku request.  This resend is the exact same request as the 'lost
14113  * lock', and is initiated by the recovery framework. A successful resend
14114  * request can initiate one or more reinstate requests.
14115  *
14116  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14117  * does not trigger additional reinstate requests.  This lock call type is
14118  * set for setting the v4 server's locking state back to match what the
14119  * client's local locking state is in the event of a received 'lost lock'.
14120  *
14121  * Errors are returned via the nfs4_error_t parameter.
14122  */
14123 void
14124 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14125     int flag, u_offset_t offset, cred_t *cr, nfs4_error_t *ep,
14126     nfs4_lost_rqst_t *resend_rqstp, int *did_reclaimp)
14127 {
14128 	COMPOUND4args_clnt	args, *argsp = NULL;
14129 	COMPOUND4res_clnt	res, *resp = NULL;
14130 	nfs_argop4	*argop;
14131 	nfs_resop4	*resop;
14132 	rnode4_t	*rp;
14133 	int		doqueue = 1;
14134 	clock_t		tick_delay;  /* delay in clock ticks */
14135 	struct lm_sysid	*ls;
14136 	LOCK4args	*lock_args = NULL;
14137 	LOCKU4args	*locku_args = NULL;
14138 	LOCKT4args	*lockt_args = NULL;
14139 	nfs4_open_owner_t *oop = NULL;
14140 	nfs4_open_stream_t *osp = NULL;
14141 	nfs4_lock_owner_t *lop = NULL;
14142 	bool_t		needrecov = FALSE;
14143 	nfs4_recov_state_t recov_state;
14144 	short		whence;
14145 	nfs4_op_hint_t	op_hint;
14146 	nfs4_lost_rqst_t lost_rqst;
14147 	bool_t		retry = FALSE;
14148 	bool_t		did_start_fop = FALSE;
14149 	bool_t		skip_get_err = FALSE;
14150 	cred_t		*cred_otw = NULL;
14151 	bool_t		recovonly;	/* just queue request */
14152 	int		frc_no_reclaim = 0;
14153 #ifdef DEBUG
14154 	char *name;
14155 #endif
14156 
14157 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14158 
14159 #ifdef DEBUG
14160 	name = fn_name(VTOSV(vp)->sv_name);
14161 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14162 	    "%s: cmd %d, type %d, offset %llu, start %"PRIx64", "
14163 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14164 	    "resend request %s", name, cmd, flk->l_type, offset, flk->l_start,
14165 	    flk->l_len, ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid :
14166 	    flk->l_pid, flk->l_sysid, nfs4frlock_get_call_type(ctype),
14167 	    resend_rqstp ? "TRUE" : "FALSE"));
14168 	kmem_free(name, MAXNAMELEN);
14169 #endif
14170 
14171 	nfs4_error_zinit(ep);
14172 	ep->error = nfs4frlock_validate_args(cmd, flk, flag, vp, offset);
14173 	if (ep->error)
14174 		return;
14175 	ep->error = nfs4frlock_get_sysid(&ls, vp, flk);
14176 	if (ep->error)
14177 		return;
14178 	nfs4frlock_pre_setup(&tick_delay, &recov_state, flk, &whence,
14179 	    vp, cr, &cred_otw);
14180 
14181 recov_retry:
14182 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14183 	    &retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14184 	rp = VTOR4(vp);
14185 
14186 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14187 	    &did_start_fop, &recovonly);
14188 
14189 	if (ep->error)
14190 		goto out;
14191 
14192 	if (recovonly) {
14193 		/*
14194 		 * Leave the request for the recovery system to deal with.
14195 		 */
14196 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14197 		ASSERT(cmd != F_GETLK);
14198 		ASSERT(flk->l_type == F_UNLCK);
14199 
14200 		nfs4_error_init(ep, EINTR);
14201 		needrecov = TRUE;
14202 		lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14203 		if (lop != NULL) {
14204 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14205 			    NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14206 			(void) nfs4_start_recovery(ep,
14207 			    VTOMI4(vp), vp, NULL, NULL,
14208 			    (lost_rqst.lr_op == OP_LOCK ||
14209 			    lost_rqst.lr_op == OP_LOCKU) ?
14210 			    &lost_rqst : NULL, OP_LOCKU, NULL);
14211 			lock_owner_rele(lop);
14212 			lop = NULL;
14213 		}
14214 		flk->l_pid = curproc->p_pid;
14215 		nfs4_register_lock_locally(vp, flk, flag, offset);
14216 		goto out;
14217 	}
14218 
14219 	/* putfh directory fh */
14220 	argop[0].argop = OP_CPUTFH;
14221 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14222 
14223 	/*
14224 	 * Set up the over-the-wire arguments and get references to the
14225 	 * open owner, etc.
14226 	 */
14227 
14228 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14229 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14230 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14231 		    &argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14232 	} else {
14233 		bool_t go_otw = TRUE;
14234 
14235 		ASSERT(resend_rqstp == NULL);
14236 
14237 		switch (cmd) {
14238 		case F_GETLK:
14239 		case F_O_GETLK:
14240 			nfs4frlock_setup_lockt_args(ctype, &argop[1],
14241 			    &lockt_args, argsp, flk, rp);
14242 			break;
14243 		case F_SETLKW:
14244 		case F_SETLK:
14245 			if (flk->l_type == F_UNLCK)
14246 				nfs4frlock_setup_locku_args(ctype,
14247 				    &argop[1], &locku_args, flk,
14248 				    &lop, ep, argsp,
14249 				    vp, flag, offset, cr,
14250 				    &skip_get_err, &go_otw);
14251 			else
14252 				nfs4frlock_setup_lock_args(ctype,
14253 				    &lock_args, &oop, &osp, &lop, &argop[1],
14254 				    argsp, flk, cmd, vp, cr, ep);
14255 
14256 			if (ep->error)
14257 				goto out;
14258 
14259 			switch (ep->stat) {
14260 			case NFS4_OK:
14261 				break;
14262 			case NFS4ERR_DELAY:
14263 				/* recov thread never gets this error */
14264 				ASSERT(resend_rqstp == NULL);
14265 				ASSERT(did_start_fop);
14266 
14267 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14268 				    &recov_state, TRUE);
14269 				did_start_fop = FALSE;
14270 				if (argop[1].argop == OP_LOCK)
14271 					nfs4args_lock_free(&argop[1]);
14272 				else if (argop[1].argop == OP_LOCKT)
14273 					nfs4args_lockt_free(&argop[1]);
14274 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14275 				argsp = NULL;
14276 				goto recov_retry;
14277 			default:
14278 				ep->error = EIO;
14279 				goto out;
14280 			}
14281 			break;
14282 		default:
14283 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14284 			    "nfs4_frlock: invalid cmd %d", cmd));
14285 			ep->error = EINVAL;
14286 			goto out;
14287 		}
14288 
14289 		if (!go_otw)
14290 			goto out;
14291 	}
14292 
14293 	/* XXX should we use the local reclock as a cache ? */
14294 	/*
14295 	 * Unregister the lock with the local locking code before
14296 	 * contacting the server.  This avoids a potential race where
14297 	 * another process gets notified that it has been granted a lock
14298 	 * before we can unregister ourselves locally.
14299 	 */
14300 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK) {
14301 		if (ctype == NFS4_LCK_CTYPE_NORM)
14302 			flk->l_pid = ttoproc(curthread)->p_pid;
14303 		nfs4_register_lock_locally(vp, flk, flag, offset);
14304 	}
14305 
14306 	/*
14307 	 * Send the server the lock request.  Continually loop with a delay
14308 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14309 	 */
14310 	resp = &res;
14311 
14312 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14313 	    (CE_NOTE,
14314 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14315 	    rnode4info(rp)));
14316 
14317 	if (lock_args && frc_no_reclaim) {
14318 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14319 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14320 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14321 		lock_args->reclaim = FALSE;
14322 		if (did_reclaimp)
14323 			*did_reclaimp = 0;
14324 	}
14325 
14326 	/*
14327 	 * Do the OTW call.
14328 	 */
14329 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14330 
14331 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14332 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14333 
14334 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14335 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14336 	    "nfs4frlock: needrecov %d", needrecov));
14337 
14338 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14339 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14340 		    args.ctag);
14341 
14342 	/*
14343 	 * Check if one of these mutually exclusive error cases has
14344 	 * happened:
14345 	 *   need to swap credentials due to access error
14346 	 *   recovery is needed
14347 	 *   different error (only known case is missing Kerberos ticket)
14348 	 */
14349 
14350 	if ((ep->error == EACCES ||
14351 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14352 	    cred_otw != cr) {
14353 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14354 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14355 		    cr, &cred_otw);
14356 		goto recov_retry;
14357 	}
14358 
14359 	if (needrecov) {
14360 		/*
14361 		 * LOCKT requests don't need to recover from lost
14362 		 * requests since they don't create/modify state.
14363 		 */
14364 		if ((ep->error == EINTR ||
14365 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14366 		    lockt_args)
14367 			goto out;
14368 		/*
14369 		 * Do not attempt recovery for requests initiated by
14370 		 * the recovery framework.  Let the framework redrive them.
14371 		 */
14372 		if (ctype != NFS4_LCK_CTYPE_NORM)
14373 			goto out;
14374 		else {
14375 			ASSERT(resend_rqstp == NULL);
14376 		}
14377 
14378 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14379 		    flk_to_locktype(cmd, flk->l_type),
14380 		    oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14381 
14382 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14383 		    &resp, lock_args, locku_args, &oop, &osp, &lop,
14384 		    rp, vp, &recov_state, op_hint, &did_start_fop,
14385 		    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14386 
14387 		if (retry) {
14388 			ASSERT(oop == NULL);
14389 			ASSERT(osp == NULL);
14390 			ASSERT(lop == NULL);
14391 			goto recov_retry;
14392 		}
14393 		goto out;
14394 	}
14395 
14396 	/*
14397 	 * Bail out if have reached this point with ep->error set. Can
14398 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14399 	 * This happens if Kerberos ticket has expired or has been
14400 	 * destroyed.
14401 	 */
14402 	if (ep->error != 0)
14403 		goto out;
14404 
14405 	/*
14406 	 * Process the reply.
14407 	 */
14408 	switch (resp->status) {
14409 	case NFS4_OK:
14410 		resop = &resp->array[1];
14411 		nfs4frlock_results_ok(ctype, cmd, flk, vp, flag, offset,
14412 		    resend_rqstp);
14413 		/*
14414 		 * Have a successful lock operation, now update state.
14415 		 */
14416 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14417 		    resop, lop, vp, flk, cr, resend_rqstp);
14418 		break;
14419 
14420 	case NFS4ERR_DENIED:
14421 		resop = &resp->array[1];
14422 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14423 		    &oop, &osp, &lop, cmd, vp, flk, op_hint,
14424 		    &recov_state, needrecov, &argsp, &resp,
14425 		    &tick_delay, &whence, &ep->error, resop, cr,
14426 		    &did_start_fop, &skip_get_err);
14427 
14428 		if (retry) {
14429 			ASSERT(oop == NULL);
14430 			ASSERT(osp == NULL);
14431 			ASSERT(lop == NULL);
14432 			goto recov_retry;
14433 		}
14434 		break;
14435 	/*
14436 	 * If the server won't let us reclaim, fall-back to trying to lock
14437 	 * the file from scratch. Code elsewhere will check the changeinfo
14438 	 * to ensure the file hasn't been changed.
14439 	 */
14440 	case NFS4ERR_NO_GRACE:
14441 		if (lock_args && lock_args->reclaim == TRUE) {
14442 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14443 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14444 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14445 			frc_no_reclaim = 1;
14446 			/* clean up before retrying */
14447 			needrecov = 0;
14448 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14449 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14450 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14451 			goto recov_retry;
14452 		}
14453 		/* FALLTHROUGH */
14454 
14455 	default:
14456 		nfs4frlock_results_default(resp, &ep->error);
14457 		break;
14458 	}
14459 out:
14460 	/*
14461 	 * Process and cleanup from error.  Make interrupted unlock
14462 	 * requests look successful, since they will be handled by the
14463 	 * client recovery code.
14464 	 */
14465 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14466 	    needrecov, oop, osp, lop, flk, whence, offset, ls, &ep->error,
14467 	    lock_args, locku_args, did_start_fop,
14468 	    skip_get_err, cred_otw, cr);
14469 
14470 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14471 	    (cmd == F_SETLK || cmd == F_SETLKW))
14472 		ep->error = 0;
14473 }
14474 
14475 /*
14476  * nfs4_safelock:
14477  *
14478  * Return non-zero if the given lock request can be handled without
14479  * violating the constraints on concurrent mapping and locking.
14480  */
14481 
14482 static int
14483 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14484 {
14485 	rnode4_t *rp = VTOR4(vp);
14486 	struct vattr va;
14487 	int error;
14488 
14489 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14490 	ASSERT(rp->r_mapcnt >= 0);
14491 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14492 	    "(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14493 	    "write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14494 	    bfp->l_start, bfp->l_len, rp->r_mapcnt));
14495 
14496 	if (rp->r_mapcnt == 0)
14497 		return (1);		/* always safe if not mapped */
14498 
14499 	/*
14500 	 * If the file is already mapped and there are locks, then they
14501 	 * should be all safe locks.  So adding or removing a lock is safe
14502 	 * as long as the new request is safe (i.e., whole-file, meaning
14503 	 * length and starting offset are both zero).
14504 	 */
14505 
14506 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14507 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14508 		    "cannot lock a memory mapped file unless locking the "
14509 		    "entire file: start %"PRIx64", len %"PRIx64,
14510 		    bfp->l_start, bfp->l_len));
14511 		return (0);
14512 	}
14513 
14514 	/* mandatory locking and mapping don't mix */
14515 	va.va_mask = AT_MODE;
14516 	error = VOP_GETATTR(vp, &va, 0, cr, NULL);
14517 	if (error != 0) {
14518 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14519 		    "getattr error %d", error));
14520 		return (0);		/* treat errors conservatively */
14521 	}
14522 	if (MANDLOCK(vp, va.va_mode)) {
14523 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14524 		    "cannot mandatory lock and mmap a file"));
14525 		return (0);
14526 	}
14527 
14528 	return (1);
14529 }
14530 
14531 
14532 /*
14533  * Register the lock locally within Solaris.
14534  * As the client, we "or" the sysid with LM_SYSID_CLIENT when
14535  * recording locks locally.
14536  *
14537  * This should handle conflicts/cooperation with NFS v2/v3 since all locks
14538  * are registered locally.
14539  */
14540 void
14541 nfs4_register_lock_locally(vnode_t *vp, struct flock64 *flk, int flag,
14542     u_offset_t offset)
14543 {
14544 	int oldsysid;
14545 	int error;
14546 #ifdef DEBUG
14547 	char *name;
14548 #endif
14549 
14550 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14551 
14552 #ifdef DEBUG
14553 	name = fn_name(VTOSV(vp)->sv_name);
14554 	NFS4_DEBUG(nfs4_client_lock_debug,
14555 	    (CE_NOTE, "nfs4_register_lock_locally: %s: type %d, "
14556 	    "start %"PRIx64", length %"PRIx64", pid %ld, sysid %d",
14557 	    name, flk->l_type, flk->l_start, flk->l_len, (long)flk->l_pid,
14558 	    flk->l_sysid));
14559 	kmem_free(name, MAXNAMELEN);
14560 #endif
14561 
14562 	/* register the lock with local locking */
14563 	oldsysid = flk->l_sysid;
14564 	flk->l_sysid |= LM_SYSID_CLIENT;
14565 	error = reclock(vp, flk, SETFLCK, flag, offset, NULL);
14566 #ifdef DEBUG
14567 	if (error != 0) {
14568 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14569 		    "nfs4_register_lock_locally: could not register with"
14570 		    " local locking"));
14571 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14572 		    "error %d, vp 0x%p, pid %d, sysid 0x%x",
14573 		    error, (void *)vp, flk->l_pid, flk->l_sysid));
14574 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14575 		    "type %d off 0x%" PRIx64 " len 0x%" PRIx64,
14576 		    flk->l_type, flk->l_start, flk->l_len));
14577 		(void) reclock(vp, flk, 0, flag, offset, NULL);
14578 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14579 		    "blocked by pid %d sysid 0x%x type %d "
14580 		    "off 0x%" PRIx64 " len 0x%" PRIx64,
14581 		    flk->l_pid, flk->l_sysid, flk->l_type, flk->l_start,
14582 		    flk->l_len));
14583 	}
14584 #endif
14585 	flk->l_sysid = oldsysid;
14586 }
14587 
14588 /*
14589  * nfs4_lockrelease:
14590  *
14591  * Release any locks on the given vnode that are held by the current
14592  * process.  Also removes the lock owner (if one exists) from the rnode's
14593  * list.
14594  */
14595 static int
14596 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14597 {
14598 	flock64_t ld;
14599 	int ret, error;
14600 	rnode4_t *rp;
14601 	nfs4_lock_owner_t *lop;
14602 	nfs4_recov_state_t recov_state;
14603 	mntinfo4_t *mi;
14604 	bool_t possible_orphan = FALSE;
14605 	bool_t recovonly;
14606 
14607 	ASSERT((uintptr_t)vp > KERNELBASE);
14608 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14609 
14610 	rp = VTOR4(vp);
14611 	mi = VTOMI4(vp);
14612 
14613 	/*
14614 	 * If we have not locked anything then we can
14615 	 * just return since we have no work to do.
14616 	 */
14617 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14618 		return (0);
14619 	}
14620 
14621 	/*
14622 	 * We need to comprehend that another thread may
14623 	 * kick off recovery and the lock_owner we have stashed
14624 	 * in lop might be invalid so we should NOT cache it
14625 	 * locally!
14626 	 */
14627 	recov_state.rs_flags = 0;
14628 	recov_state.rs_num_retry_despite_err = 0;
14629 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14630 	    &recovonly);
14631 	if (error) {
14632 		mutex_enter(&rp->r_statelock);
14633 		rp->r_flags |= R4LODANGLERS;
14634 		mutex_exit(&rp->r_statelock);
14635 		return (error);
14636 	}
14637 
14638 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14639 
14640 	/*
14641 	 * Check if the lock owner might have a lock (request was sent but
14642 	 * no response was received).  Also check if there are any remote
14643 	 * locks on the file.  (In theory we shouldn't have to make this
14644 	 * second check if there's no lock owner, but for now we'll be
14645 	 * conservative and do it anyway.)  If either condition is true,
14646 	 * send an unlock for the entire file to the server.
14647 	 *
14648 	 * Note that no explicit synchronization is needed here.  At worst,
14649 	 * flk_has_remote_locks() will return a false positive, in which case
14650 	 * the unlock call wastes time but doesn't harm correctness.
14651 	 */
14652 
14653 	if (lop) {
14654 		mutex_enter(&lop->lo_lock);
14655 		possible_orphan = lop->lo_pending_rqsts;
14656 		mutex_exit(&lop->lo_lock);
14657 		lock_owner_rele(lop);
14658 	}
14659 
14660 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14661 
14662 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14663 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14664 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14665 	    (void *)lop));
14666 
14667 	if (possible_orphan || flk_has_remote_locks(vp)) {
14668 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14669 		ld.l_whence = 0;	/* unlock from start of file */
14670 		ld.l_start = 0;
14671 		ld.l_len = 0;		/* do entire file */
14672 
14673 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL,
14674 		    cr, NULL);
14675 
14676 		if (ret != 0) {
14677 			/*
14678 			 * If VOP_FRLOCK fails, make sure we unregister
14679 			 * local locks before we continue.
14680 			 */
14681 			ld.l_pid = ttoproc(curthread)->p_pid;
14682 			nfs4_register_lock_locally(vp, &ld, flag, offset);
14683 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14684 			    "nfs4_lockrelease: lock release error on vp"
14685 			    " %p: error %d.\n", (void *)vp, ret));
14686 		}
14687 	}
14688 
14689 	recov_state.rs_flags = 0;
14690 	recov_state.rs_num_retry_despite_err = 0;
14691 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14692 	    &recovonly);
14693 	if (error) {
14694 		mutex_enter(&rp->r_statelock);
14695 		rp->r_flags |= R4LODANGLERS;
14696 		mutex_exit(&rp->r_statelock);
14697 		return (error);
14698 	}
14699 
14700 	/*
14701 	 * So, here we're going to need to retrieve the lock-owner
14702 	 * again (in case recovery has done a switch-a-roo) and
14703 	 * remove it because we can.
14704 	 */
14705 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14706 
14707 	if (lop) {
14708 		nfs4_rnode_remove_lock_owner(rp, lop);
14709 		lock_owner_rele(lop);
14710 	}
14711 
14712 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14713 	return (0);
14714 }
14715 
14716 /*
14717  * Wait for 'tick_delay' clock ticks.
14718  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14719  * NOTE: lock_lease_time is in seconds.
14720  *
14721  * XXX For future improvements, should implement a waiting queue scheme.
14722  */
14723 static int
14724 nfs4_block_and_wait(clock_t *tick_delay, rnode4_t *rp)
14725 {
14726 	long milliseconds_delay;
14727 	time_t lock_lease_time;
14728 
14729 	/* wait tick_delay clock ticks or siginteruptus */
14730 	if (delay_sig(*tick_delay)) {
14731 		return (EINTR);
14732 	}
14733 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14734 	    "reissue the lock request: blocked for %ld clock ticks: %ld "
14735 	    "milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14736 
14737 	/* get the lease time */
14738 	lock_lease_time = r2lease_time(rp);
14739 
14740 	/* drv_hztousec converts ticks to microseconds */
14741 	milliseconds_delay = drv_hztousec(*tick_delay) / 1000;
14742 	if (milliseconds_delay < lock_lease_time * 1000) {
14743 		*tick_delay = 2 * *tick_delay;
14744 		if (drv_hztousec(*tick_delay) > lock_lease_time * 1000 * 1000)
14745 			*tick_delay = drv_usectohz(lock_lease_time*1000*1000);
14746 	}
14747 	return (0);
14748 }
14749 
14750 
14751 void
14752 nfs4_vnops_init(void)
14753 {
14754 }
14755 
14756 void
14757 nfs4_vnops_fini(void)
14758 {
14759 }
14760 
14761 /*
14762  * Return a reference to the directory (parent) vnode for a given vnode,
14763  * using the saved pathname information and the directory file handle.  The
14764  * caller is responsible for disposing of the reference.
14765  * Returns zero or an errno value.
14766  *
14767  * Caller should set need_start_op to FALSE if it is the recovery
14768  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14769  */
14770 int
14771 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14772 {
14773 	svnode_t *svnp;
14774 	vnode_t *dvp = NULL;
14775 	servinfo4_t *svp;
14776 	nfs4_fname_t *mfname;
14777 	int error;
14778 
14779 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14780 
14781 	if (vp->v_flag & VROOT) {
14782 		nfs4_sharedfh_t *sfh;
14783 		nfs_fh4 fh;
14784 		mntinfo4_t *mi;
14785 
14786 		ASSERT(vp->v_type == VREG);
14787 
14788 		mi = VTOMI4(vp);
14789 		svp = mi->mi_curr_serv;
14790 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14791 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14792 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14793 		sfh = sfh4_get(&fh, VTOMI4(vp));
14794 		nfs_rw_exit(&svp->sv_lock);
14795 		mfname = mi->mi_fname;
14796 		fn_hold(mfname);
14797 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14798 		sfh4_rele(&sfh);
14799 
14800 		if (dvp->v_type == VNON)
14801 			dvp->v_type = VDIR;
14802 		*dvpp = dvp;
14803 		return (0);
14804 	}
14805 
14806 	svnp = VTOSV(vp);
14807 
14808 	if (svnp == NULL) {
14809 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14810 		    "shadow node is NULL"));
14811 		return (EINVAL);
14812 	}
14813 
14814 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14815 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14816 		    "shadow node name or dfh val == NULL"));
14817 		return (EINVAL);
14818 	}
14819 
14820 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14821 	    (int)need_start_op);
14822 	if (error != 0) {
14823 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14824 		    "nfs4_make_dotdot returned %d", error));
14825 		return (error);
14826 	}
14827 	if (!dvp) {
14828 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14829 		    "nfs4_make_dotdot returned a NULL dvp"));
14830 		return (EIO);
14831 	}
14832 	if (dvp->v_type == VNON)
14833 		dvp->v_type = VDIR;
14834 	ASSERT(dvp->v_type == VDIR);
14835 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14836 		mutex_enter(&dvp->v_lock);
14837 		dvp->v_flag |= V_XATTRDIR;
14838 		mutex_exit(&dvp->v_lock);
14839 	}
14840 	*dvpp = dvp;
14841 	return (0);
14842 }
14843 
14844 /*
14845  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14846  * length that fnamep can accept, including the trailing null.
14847  * Returns 0 if okay, returns an errno value if there was a problem.
14848  */
14849 
14850 int
14851 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14852 {
14853 	char *fn;
14854 	int err = 0;
14855 	servinfo4_t *svp;
14856 	svnode_t *shvp;
14857 
14858 	/*
14859 	 * If the file being opened has VROOT set, then this is
14860 	 * a "file" mount.  sv_name will not be interesting, so
14861 	 * go back to the servinfo4 to get the original mount
14862 	 * path and strip off all but the final edge.  Otherwise
14863 	 * just return the name from the shadow vnode.
14864 	 */
14865 
14866 	if (vp->v_flag & VROOT) {
14867 
14868 		svp = VTOMI4(vp)->mi_curr_serv;
14869 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14870 
14871 		fn = strrchr(svp->sv_path, '/');
14872 		if (fn == NULL)
14873 			err = EINVAL;
14874 		else
14875 			fn++;
14876 	} else {
14877 		shvp = VTOSV(vp);
14878 		fn = fn_name(shvp->sv_name);
14879 	}
14880 
14881 	if (err == 0)
14882 		if (strlen(fn) < maxlen)
14883 			(void) strcpy(fnamep, fn);
14884 		else
14885 			err = ENAMETOOLONG;
14886 
14887 	if (vp->v_flag & VROOT)
14888 		nfs_rw_exit(&svp->sv_lock);
14889 	else
14890 		kmem_free(fn, MAXNAMELEN);
14891 
14892 	return (err);
14893 }
14894 
14895 /*
14896  * Bookkeeping for a close that doesn't need to go over the wire.
14897  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14898  * it is left at 1.
14899  */
14900 void
14901 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14902 {
14903 	rnode4_t		*rp;
14904 	mntinfo4_t		*mi;
14905 
14906 	mi = VTOMI4(vp);
14907 	rp = VTOR4(vp);
14908 
14909 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14910 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14911 	ASSERT(nfs_zone() == mi->mi_zone);
14912 	ASSERT(mutex_owned(&osp->os_sync_lock));
14913 	ASSERT(*have_lockp);
14914 
14915 	if (!osp->os_valid ||
14916 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14917 		return;
14918 	}
14919 
14920 	/*
14921 	 * This removes the reference obtained at OPEN; ie,
14922 	 * when the open stream structure was created.
14923 	 *
14924 	 * We don't have to worry about calling 'open_stream_rele'
14925 	 * since we our currently holding a reference to this
14926 	 * open stream which means the count can not go to 0 with
14927 	 * this decrement.
14928 	 */
14929 	ASSERT(osp->os_ref_count >= 2);
14930 	osp->os_ref_count--;
14931 	osp->os_valid = 0;
14932 	mutex_exit(&osp->os_sync_lock);
14933 	*have_lockp = 0;
14934 
14935 	nfs4_dec_state_ref_count(mi);
14936 }
14937 
14938 /*
14939  * Close all remaining open streams on the rnode.  These open streams
14940  * could be here because:
14941  * - The close attempted at either close or delmap failed
14942  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
14943  * - Someone did mknod on a regular file but never opened it
14944  */
14945 int
14946 nfs4close_all(vnode_t *vp, cred_t *cr)
14947 {
14948 	nfs4_open_stream_t *osp;
14949 	int error;
14950 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
14951 	rnode4_t *rp;
14952 
14953 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14954 
14955 	error = 0;
14956 	rp = VTOR4(vp);
14957 
14958 	/*
14959 	 * At this point, all we know is that the last time
14960 	 * someone called vn_rele, the count was 1.  Since then,
14961 	 * the vnode could have been re-activated.  We want to
14962 	 * loop through the open streams and close each one, but
14963 	 * we have to be careful since once we release the rnode
14964 	 * hash bucket lock, someone else is free to come in and
14965 	 * re-activate the rnode and add new open streams.  The
14966 	 * strategy is take the rnode hash bucket lock, verify that
14967 	 * the count is still 1, grab the open stream off the
14968 	 * head of the list and mark it invalid, then release the
14969 	 * rnode hash bucket lock and proceed with that open stream.
14970 	 * This is ok because nfs4close_one() will acquire the proper
14971 	 * open/create to close/destroy synchronization for open
14972 	 * streams, and will ensure that if someone has reopened
14973 	 * the open stream after we've dropped the hash bucket lock
14974 	 * then we'll just simply return without destroying the
14975 	 * open stream.
14976 	 * Repeat until the list is empty.
14977 	 */
14978 
14979 	for (;;) {
14980 
14981 		/* make sure vnode hasn't been reactivated */
14982 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
14983 		mutex_enter(&vp->v_lock);
14984 		if (vp->v_count > 1) {
14985 			mutex_exit(&vp->v_lock);
14986 			rw_exit(&rp->r_hashq->r_lock);
14987 			break;
14988 		}
14989 		/*
14990 		 * Grabbing r_os_lock before releasing v_lock prevents
14991 		 * a window where the rnode/open stream could get
14992 		 * reactivated (and os_force_close set to 0) before we
14993 		 * had a chance to set os_force_close to 1.
14994 		 */
14995 		mutex_enter(&rp->r_os_lock);
14996 		mutex_exit(&vp->v_lock);
14997 
14998 		osp = list_head(&rp->r_open_streams);
14999 		if (!osp) {
15000 			/* nothing left to CLOSE OTW, so return */
15001 			mutex_exit(&rp->r_os_lock);
15002 			rw_exit(&rp->r_hashq->r_lock);
15003 			break;
15004 		}
15005 
15006 		mutex_enter(&rp->r_statev4_lock);
15007 		/* the file can't still be mem mapped */
15008 		ASSERT(rp->r_mapcnt == 0);
15009 		if (rp->created_v4)
15010 			rp->created_v4 = 0;
15011 		mutex_exit(&rp->r_statev4_lock);
15012 
15013 		/*
15014 		 * Grab a ref on this open stream; nfs4close_one
15015 		 * will mark it as invalid
15016 		 */
15017 		mutex_enter(&osp->os_sync_lock);
15018 		osp->os_ref_count++;
15019 		osp->os_force_close = 1;
15020 		mutex_exit(&osp->os_sync_lock);
15021 		mutex_exit(&rp->r_os_lock);
15022 		rw_exit(&rp->r_hashq->r_lock);
15023 
15024 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
15025 
15026 		/* Update error if it isn't already non-zero */
15027 		if (error == 0) {
15028 			if (e.error)
15029 				error = e.error;
15030 			else if (e.stat)
15031 				error = geterrno4(e.stat);
15032 		}
15033 
15034 #ifdef	DEBUG
15035 		nfs4close_all_cnt++;
15036 #endif
15037 		/* Release the ref on osp acquired above. */
15038 		open_stream_rele(osp, rp);
15039 
15040 		/* Proceed to the next open stream, if any */
15041 	}
15042 	return (error);
15043 }
15044 
15045 /*
15046  * nfs4close_one - close one open stream for a file if needed.
15047  *
15048  * "close_type" indicates which close path this is:
15049  * CLOSE_NORM: close initiated via VOP_CLOSE.
15050  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
15051  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
15052  *	the close and release of client state for this open stream
15053  *	(unless someone else has the open stream open).
15054  * CLOSE_RESEND: indicates the request is a replay of an earlier request
15055  *	(e.g., due to abort because of a signal).
15056  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
15057  *
15058  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
15059  * recovery.  Instead, the caller is expected to deal with retries.
15060  *
15061  * The caller can either pass in the osp ('provided_osp') or not.
15062  *
15063  * 'access_bits' represents the access we are closing/downgrading.
15064  *
15065  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
15066  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
15067  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
15068  *
15069  * Errors are returned via the nfs4_error_t.
15070  */
15071 void
15072 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
15073     int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
15074     nfs4_close_type_t close_type, size_t len, uint_t maxprot,
15075     uint_t mmap_flags)
15076 {
15077 	nfs4_open_owner_t *oop;
15078 	nfs4_open_stream_t *osp = NULL;
15079 	int retry = 0;
15080 	int num_retries = NFS4_NUM_RECOV_RETRIES;
15081 	rnode4_t *rp;
15082 	mntinfo4_t *mi;
15083 	nfs4_recov_state_t recov_state;
15084 	cred_t *cred_otw = NULL;
15085 	bool_t recovonly = FALSE;
15086 	int isrecov;
15087 	int force_close;
15088 	int close_failed = 0;
15089 	int did_dec_count = 0;
15090 	int did_start_op = 0;
15091 	int did_force_recovlock = 0;
15092 	int did_start_seqid_sync = 0;
15093 	int have_sync_lock = 0;
15094 
15095 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15096 
15097 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
15098 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
15099 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
15100 	    len, maxprot, mmap_flags, access_bits));
15101 
15102 	nfs4_error_zinit(ep);
15103 	rp = VTOR4(vp);
15104 	mi = VTOMI4(vp);
15105 	isrecov = (close_type == CLOSE_RESEND ||
15106 	    close_type == CLOSE_AFTER_RESEND);
15107 
15108 	/*
15109 	 * First get the open owner.
15110 	 */
15111 	if (!provided_osp) {
15112 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
15113 	} else {
15114 		oop = provided_osp->os_open_owner;
15115 		ASSERT(oop != NULL);
15116 		open_owner_hold(oop);
15117 	}
15118 
15119 	if (!oop) {
15120 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15121 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15122 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15123 		    (void *)provided_osp, close_type));
15124 		ep->error = EIO;
15125 		goto out;
15126 	}
15127 
15128 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15129 recov_retry:
15130 	osp = NULL;
15131 	close_failed = 0;
15132 	force_close = (close_type == CLOSE_FORCE);
15133 	retry = 0;
15134 	did_start_op = 0;
15135 	did_force_recovlock = 0;
15136 	did_start_seqid_sync = 0;
15137 	have_sync_lock = 0;
15138 	recovonly = FALSE;
15139 	recov_state.rs_flags = 0;
15140 	recov_state.rs_num_retry_despite_err = 0;
15141 
15142 	/*
15143 	 * Second synchronize with recovery.
15144 	 */
15145 	if (!isrecov) {
15146 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15147 		    &recov_state, &recovonly);
15148 		if (!ep->error) {
15149 			did_start_op = 1;
15150 		} else {
15151 			close_failed = 1;
15152 			/*
15153 			 * If we couldn't get start_fop, but have to
15154 			 * cleanup state, then at least acquire the
15155 			 * mi_recovlock so we can synchronize with
15156 			 * recovery.
15157 			 */
15158 			if (close_type == CLOSE_FORCE) {
15159 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15160 				    RW_READER, FALSE);
15161 				did_force_recovlock = 1;
15162 			} else
15163 				goto out;
15164 		}
15165 	}
15166 
15167 	/*
15168 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15169 	 * set 'recovonly' to TRUE since most likely this is due to
15170 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15171 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15172 	 * to retry, causing us to loop until recovery finishes.  Plus we
15173 	 * don't need protection over the open seqid since we're not going
15174 	 * OTW, hence don't need to use the seqid.
15175 	 */
15176 	if (recovonly == FALSE) {
15177 		/* need to grab the open owner sync before 'os_sync_lock' */
15178 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15179 		if (ep->error == EAGAIN) {
15180 			ASSERT(!isrecov);
15181 			if (did_start_op)
15182 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15183 				    &recov_state, TRUE);
15184 			if (did_force_recovlock)
15185 				nfs_rw_exit(&mi->mi_recovlock);
15186 			goto recov_retry;
15187 		}
15188 		did_start_seqid_sync = 1;
15189 	}
15190 
15191 	/*
15192 	 * Third get an open stream and acquire 'os_sync_lock' to
15193 	 * sychronize the opening/creating of an open stream with the
15194 	 * closing/destroying of an open stream.
15195 	 */
15196 	if (!provided_osp) {
15197 		/* returns with 'os_sync_lock' held */
15198 		osp = find_open_stream(oop, rp);
15199 		if (!osp) {
15200 			ep->error = EIO;
15201 			goto out;
15202 		}
15203 	} else {
15204 		osp = provided_osp;
15205 		open_stream_hold(osp);
15206 		mutex_enter(&osp->os_sync_lock);
15207 	}
15208 	have_sync_lock = 1;
15209 
15210 	ASSERT(oop == osp->os_open_owner);
15211 
15212 	/*
15213 	 * Fourth, do any special pre-OTW CLOSE processing
15214 	 * based on the specific close type.
15215 	 */
15216 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15217 	    !did_dec_count) {
15218 		ASSERT(osp->os_open_ref_count > 0);
15219 		osp->os_open_ref_count--;
15220 		did_dec_count = 1;
15221 		if (osp->os_open_ref_count == 0)
15222 			osp->os_final_close = 1;
15223 	}
15224 
15225 	if (close_type == CLOSE_FORCE) {
15226 		/* see if somebody reopened the open stream. */
15227 		if (!osp->os_force_close) {
15228 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15229 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15230 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15231 			ep->error = 0;
15232 			ep->stat = NFS4_OK;
15233 			goto out;
15234 		}
15235 
15236 		if (!osp->os_final_close && !did_dec_count) {
15237 			osp->os_open_ref_count--;
15238 			did_dec_count = 1;
15239 		}
15240 
15241 		/*
15242 		 * We can't depend on os_open_ref_count being 0 due to the
15243 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15244 		 */
15245 #ifdef	NOTYET
15246 		ASSERT(osp->os_open_ref_count == 0);
15247 #endif
15248 		if (osp->os_open_ref_count != 0) {
15249 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15250 			    "nfs4close_one: should panic here on an "
15251 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15252 			    "since this is probably the exec problem."));
15253 
15254 			osp->os_open_ref_count = 0;
15255 		}
15256 
15257 		/*
15258 		 * There is the possibility that nfs4close_one()
15259 		 * for close_type == CLOSE_DELMAP couldn't find the
15260 		 * open stream, thus couldn't decrement its os_mapcnt;
15261 		 * therefore we can't use this ASSERT yet.
15262 		 */
15263 #ifdef	NOTYET
15264 		ASSERT(osp->os_mapcnt == 0);
15265 #endif
15266 		osp->os_mapcnt = 0;
15267 	}
15268 
15269 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15270 		ASSERT(osp->os_mapcnt >= btopr(len));
15271 
15272 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15273 			osp->os_mmap_write -= btopr(len);
15274 		if (maxprot & PROT_READ)
15275 			osp->os_mmap_read -= btopr(len);
15276 		if (maxprot & PROT_EXEC)
15277 			osp->os_mmap_read -= btopr(len);
15278 		/* mirror the PROT_NONE check in nfs4_addmap() */
15279 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15280 		    !(maxprot & PROT_EXEC))
15281 			osp->os_mmap_read -= btopr(len);
15282 		osp->os_mapcnt -= btopr(len);
15283 		did_dec_count = 1;
15284 	}
15285 
15286 	if (recovonly) {
15287 		nfs4_lost_rqst_t lost_rqst;
15288 
15289 		/* request should not already be in recovery queue */
15290 		ASSERT(lrp == NULL);
15291 		nfs4_error_init(ep, EINTR);
15292 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15293 		    osp, cred_otw, vp);
15294 		mutex_exit(&osp->os_sync_lock);
15295 		have_sync_lock = 0;
15296 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15297 		    lost_rqst.lr_op == OP_CLOSE ?
15298 		    &lost_rqst : NULL, OP_CLOSE, NULL);
15299 		close_failed = 1;
15300 		force_close = 0;
15301 		goto close_cleanup;
15302 	}
15303 
15304 	/*
15305 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15306 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15307 	 * space, which means we stopped operating on the open stream
15308 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15309 	 * stateid could be stale, potentially triggering a false
15310 	 * setclientid), and just clean up the client's internal state.
15311 	 */
15312 	if (osp->os_orig_oo_name != oop->oo_name) {
15313 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15314 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15315 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15316 		    "oo_name %" PRIx64")",
15317 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15318 		    oop->oo_name));
15319 		close_failed = 1;
15320 	}
15321 
15322 	/* If the file failed recovery, just quit. */
15323 	mutex_enter(&rp->r_statelock);
15324 	if (rp->r_flags & R4RECOVERR) {
15325 		close_failed = 1;
15326 	}
15327 	mutex_exit(&rp->r_statelock);
15328 
15329 	/*
15330 	 * If the force close path failed to obtain start_fop
15331 	 * then skip the OTW close and just remove the state.
15332 	 */
15333 	if (close_failed)
15334 		goto close_cleanup;
15335 
15336 	/*
15337 	 * Fifth, check to see if there are still mapped pages or other
15338 	 * opens using this open stream.  If there are then we can't
15339 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15340 	 */
15341 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15342 		nfs4_lost_rqst_t	new_lost_rqst;
15343 		bool_t			needrecov = FALSE;
15344 		cred_t			*odg_cred_otw = NULL;
15345 		seqid4			open_dg_seqid = 0;
15346 
15347 		if (osp->os_delegation) {
15348 			/*
15349 			 * If this open stream was never OPENed OTW then we
15350 			 * surely can't DOWNGRADE it (especially since the
15351 			 * osp->open_stateid is really a delegation stateid
15352 			 * when os_delegation is 1).
15353 			 */
15354 			if (access_bits & FREAD)
15355 				osp->os_share_acc_read--;
15356 			if (access_bits & FWRITE)
15357 				osp->os_share_acc_write--;
15358 			osp->os_share_deny_none--;
15359 			nfs4_error_zinit(ep);
15360 			goto out;
15361 		}
15362 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15363 		    lrp, ep, &odg_cred_otw, &open_dg_seqid);
15364 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15365 		if (needrecov && !isrecov) {
15366 			bool_t abort;
15367 			nfs4_bseqid_entry_t *bsep = NULL;
15368 
15369 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15370 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15371 				    vp, 0,
15372 				    lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15373 				    open_dg_seqid);
15374 
15375 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15376 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15377 			mutex_exit(&osp->os_sync_lock);
15378 			have_sync_lock = 0;
15379 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15380 			    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15381 			    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15382 			    bsep);
15383 			if (odg_cred_otw)
15384 				crfree(odg_cred_otw);
15385 			if (bsep)
15386 				kmem_free(bsep, sizeof (*bsep));
15387 
15388 			if (abort == TRUE)
15389 				goto out;
15390 
15391 			if (did_start_seqid_sync) {
15392 				nfs4_end_open_seqid_sync(oop);
15393 				did_start_seqid_sync = 0;
15394 			}
15395 			open_stream_rele(osp, rp);
15396 
15397 			if (did_start_op)
15398 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15399 				    &recov_state, FALSE);
15400 			if (did_force_recovlock)
15401 				nfs_rw_exit(&mi->mi_recovlock);
15402 
15403 			goto recov_retry;
15404 		} else {
15405 			if (odg_cred_otw)
15406 				crfree(odg_cred_otw);
15407 		}
15408 		goto out;
15409 	}
15410 
15411 	/*
15412 	 * If this open stream was created as the results of an open
15413 	 * while holding a delegation, then just release it; no need
15414 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15415 	 */
15416 	if (osp->os_delegation) {
15417 		nfs4close_notw(vp, osp, &have_sync_lock);
15418 		nfs4_error_zinit(ep);
15419 		goto out;
15420 	}
15421 
15422 	/*
15423 	 * If this stream is not valid, we're done.
15424 	 */
15425 	if (!osp->os_valid) {
15426 		nfs4_error_zinit(ep);
15427 		goto out;
15428 	}
15429 
15430 	/*
15431 	 * Last open or mmap ref has vanished, need to do an OTW close.
15432 	 * First check to see if a close is still necessary.
15433 	 */
15434 	if (osp->os_failed_reopen) {
15435 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15436 		    "don't close OTW osp %p since reopen failed.",
15437 		    (void *)osp));
15438 		/*
15439 		 * Reopen of the open stream failed, hence the
15440 		 * stateid of the open stream is invalid/stale, and
15441 		 * sending this OTW would incorrectly cause another
15442 		 * round of recovery.  In this case, we need to set
15443 		 * the 'os_valid' bit to 0 so another thread doesn't
15444 		 * come in and re-open this open stream before
15445 		 * this "closing" thread cleans up state (decrementing
15446 		 * the nfs4_server_t's state_ref_count and decrementing
15447 		 * the os_ref_count).
15448 		 */
15449 		osp->os_valid = 0;
15450 		/*
15451 		 * This removes the reference obtained at OPEN; ie,
15452 		 * when the open stream structure was created.
15453 		 *
15454 		 * We don't have to worry about calling 'open_stream_rele'
15455 		 * since we our currently holding a reference to this
15456 		 * open stream which means the count can not go to 0 with
15457 		 * this decrement.
15458 		 */
15459 		ASSERT(osp->os_ref_count >= 2);
15460 		osp->os_ref_count--;
15461 		nfs4_error_zinit(ep);
15462 		close_failed = 0;
15463 		goto close_cleanup;
15464 	}
15465 
15466 	ASSERT(osp->os_ref_count > 1);
15467 
15468 	/*
15469 	 * Sixth, try the CLOSE OTW.
15470 	 */
15471 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15472 	    close_type, ep, &have_sync_lock);
15473 
15474 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15475 		/*
15476 		 * Let the recovery thread be responsible for
15477 		 * removing the state for CLOSE.
15478 		 */
15479 		close_failed = 1;
15480 		force_close = 0;
15481 		retry = 0;
15482 	}
15483 
15484 	/* See if we need to retry with a different cred */
15485 	if ((ep->error == EACCES ||
15486 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15487 	    cred_otw != cr) {
15488 		crfree(cred_otw);
15489 		cred_otw = cr;
15490 		crhold(cred_otw);
15491 		retry = 1;
15492 	}
15493 
15494 	if (ep->error || ep->stat)
15495 		close_failed = 1;
15496 
15497 	if (retry && !isrecov && num_retries-- > 0) {
15498 		if (have_sync_lock) {
15499 			mutex_exit(&osp->os_sync_lock);
15500 			have_sync_lock = 0;
15501 		}
15502 		if (did_start_seqid_sync) {
15503 			nfs4_end_open_seqid_sync(oop);
15504 			did_start_seqid_sync = 0;
15505 		}
15506 		open_stream_rele(osp, rp);
15507 
15508 		if (did_start_op)
15509 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15510 			    &recov_state, FALSE);
15511 		if (did_force_recovlock)
15512 			nfs_rw_exit(&mi->mi_recovlock);
15513 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15514 		    "nfs4close_one: need to retry the close "
15515 		    "operation"));
15516 		goto recov_retry;
15517 	}
15518 close_cleanup:
15519 	/*
15520 	 * Seventh and lastly, process our results.
15521 	 */
15522 	if (close_failed && force_close) {
15523 		/*
15524 		 * It's ok to drop and regrab the 'os_sync_lock' since
15525 		 * nfs4close_notw() will recheck to make sure the
15526 		 * "close"/removal of state should happen.
15527 		 */
15528 		if (!have_sync_lock) {
15529 			mutex_enter(&osp->os_sync_lock);
15530 			have_sync_lock = 1;
15531 		}
15532 		/*
15533 		 * This is last call, remove the ref on the open
15534 		 * stream created by open and clean everything up.
15535 		 */
15536 		osp->os_pending_close = 0;
15537 		nfs4close_notw(vp, osp, &have_sync_lock);
15538 		nfs4_error_zinit(ep);
15539 	}
15540 
15541 	if (!close_failed) {
15542 		if (have_sync_lock) {
15543 			osp->os_pending_close = 0;
15544 			mutex_exit(&osp->os_sync_lock);
15545 			have_sync_lock = 0;
15546 		} else {
15547 			mutex_enter(&osp->os_sync_lock);
15548 			osp->os_pending_close = 0;
15549 			mutex_exit(&osp->os_sync_lock);
15550 		}
15551 		if (did_start_op && recov_state.rs_sp != NULL) {
15552 			mutex_enter(&recov_state.rs_sp->s_lock);
15553 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15554 			mutex_exit(&recov_state.rs_sp->s_lock);
15555 		} else {
15556 			nfs4_dec_state_ref_count(mi);
15557 		}
15558 		nfs4_error_zinit(ep);
15559 	}
15560 
15561 out:
15562 	if (have_sync_lock)
15563 		mutex_exit(&osp->os_sync_lock);
15564 	if (did_start_op)
15565 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15566 		    recovonly ? TRUE : FALSE);
15567 	if (did_force_recovlock)
15568 		nfs_rw_exit(&mi->mi_recovlock);
15569 	if (cred_otw)
15570 		crfree(cred_otw);
15571 	if (osp)
15572 		open_stream_rele(osp, rp);
15573 	if (oop) {
15574 		if (did_start_seqid_sync)
15575 			nfs4_end_open_seqid_sync(oop);
15576 		open_owner_rele(oop);
15577 	}
15578 }
15579 
15580 /*
15581  * Convert information returned by the server in the LOCK4denied
15582  * structure to the form required by fcntl.
15583  */
15584 static void
15585 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15586 {
15587 	nfs4_lo_name_t *lo;
15588 
15589 #ifdef	DEBUG
15590 	if (denied_to_flk_debug) {
15591 		lockt_denied_debug = lockt_denied;
15592 		debug_enter("lockt_denied");
15593 	}
15594 #endif
15595 
15596 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15597 	flk->l_whence = 0;	/* aka SEEK_SET */
15598 	flk->l_start = lockt_denied->offset;
15599 	flk->l_len = lockt_denied->length;
15600 
15601 	/*
15602 	 * If the blocking clientid matches our client id, then we can
15603 	 * interpret the lockowner (since we built it).  If not, then
15604 	 * fabricate a sysid and pid.  Note that the l_sysid field
15605 	 * in *flk already has the local sysid.
15606 	 */
15607 
15608 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15609 
15610 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15611 			lo = (nfs4_lo_name_t *)
15612 			    lockt_denied->owner.owner_val;
15613 
15614 			flk->l_pid = lo->ln_pid;
15615 		} else {
15616 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15617 			    "denied_to_flk: bad lock owner length\n"));
15618 
15619 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15620 		}
15621 	} else {
15622 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15623 		"denied_to_flk: foreign clientid\n"));
15624 
15625 		/*
15626 		 * Construct a new sysid which should be different from
15627 		 * sysids of other systems.
15628 		 */
15629 
15630 		flk->l_sysid++;
15631 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15632 	}
15633 }
15634 
15635 static pid_t
15636 lo_to_pid(lock_owner4 *lop)
15637 {
15638 	pid_t pid = 0;
15639 	uchar_t *cp;
15640 	int i;
15641 
15642 	cp = (uchar_t *)&lop->clientid;
15643 
15644 	for (i = 0; i < sizeof (lop->clientid); i++)
15645 		pid += (pid_t)*cp++;
15646 
15647 	cp = (uchar_t *)lop->owner_val;
15648 
15649 	for (i = 0; i < lop->owner_len; i++)
15650 		pid += (pid_t)*cp++;
15651 
15652 	return (pid);
15653 }
15654 
15655 /*
15656  * Given a lock pointer, returns the length of that lock.
15657  * "end" is the last locked offset the "l_len" covers from
15658  * the start of the lock.
15659  */
15660 static off64_t
15661 lock_to_end(flock64_t *lock)
15662 {
15663 	off64_t lock_end;
15664 
15665 	if (lock->l_len == 0)
15666 		lock_end = (off64_t)MAXEND;
15667 	else
15668 		lock_end = lock->l_start + lock->l_len - 1;
15669 
15670 	return (lock_end);
15671 }
15672 
15673 /*
15674  * Given the end of a lock, it will return you the length "l_len" for that lock.
15675  */
15676 static off64_t
15677 end_to_len(off64_t start, off64_t end)
15678 {
15679 	off64_t lock_len;
15680 
15681 	ASSERT(end >= start);
15682 	if (end == MAXEND)
15683 		lock_len = 0;
15684 	else
15685 		lock_len = end - start + 1;
15686 
15687 	return (lock_len);
15688 }
15689 
15690 /*
15691  * On given end for a lock it determines if it is the last locked offset
15692  * or not, if so keeps it as is, else adds one to return the length for
15693  * valid start.
15694  */
15695 static off64_t
15696 start_check(off64_t x)
15697 {
15698 	if (x == MAXEND)
15699 		return (x);
15700 	else
15701 		return (x + 1);
15702 }
15703 
15704 /*
15705  * See if these two locks overlap, and if so return 1;
15706  * otherwise, return 0.
15707  */
15708 static int
15709 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15710 {
15711 	off64_t llfp_end, curfp_end;
15712 
15713 	llfp_end = lock_to_end(llfp);
15714 	curfp_end = lock_to_end(curfp);
15715 
15716 	if (((llfp_end >= curfp->l_start) &&
15717 	    (llfp->l_start <= curfp->l_start)) ||
15718 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15719 		return (1);
15720 	return (0);
15721 }
15722 
15723 /*
15724  * Determine what the intersecting lock region is, and add that to the
15725  * 'nl_llpp' locklist in increasing order (by l_start).
15726  */
15727 static void
15728 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15729     locklist_t **nl_llpp, vnode_t *vp)
15730 {
15731 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15732 	off64_t lost_flp_end, local_flp_end, len, start;
15733 
15734 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15735 
15736 	if (!locks_intersect(lost_flp, local_flp))
15737 		return;
15738 
15739 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15740 	    "locks intersect"));
15741 
15742 	lost_flp_end = lock_to_end(lost_flp);
15743 	local_flp_end = lock_to_end(local_flp);
15744 
15745 	/* Find the starting point of the intersecting region */
15746 	if (local_flp->l_start > lost_flp->l_start)
15747 		start = local_flp->l_start;
15748 	else
15749 		start = lost_flp->l_start;
15750 
15751 	/* Find the lenght of the intersecting region */
15752 	if (lost_flp_end < local_flp_end)
15753 		len = end_to_len(start, lost_flp_end);
15754 	else
15755 		len = end_to_len(start, local_flp_end);
15756 
15757 	/*
15758 	 * Prepare the flock structure for the intersection found and insert
15759 	 * it into the new list in increasing l_start order. This list contains
15760 	 * intersections of locks registered by the client with the local host
15761 	 * and the lost lock.
15762 	 * The lock type of this lock is the same as that of the local_flp.
15763 	 */
15764 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15765 	intersect_llp->ll_flock.l_start = start;
15766 	intersect_llp->ll_flock.l_len = len;
15767 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15768 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15769 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15770 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15771 	intersect_llp->ll_vp = vp;
15772 
15773 	tmp_fllp = *nl_llpp;
15774 	cur_fllp = NULL;
15775 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15776 	    intersect_llp->ll_flock.l_start) {
15777 			cur_fllp = tmp_fllp;
15778 			tmp_fllp = tmp_fllp->ll_next;
15779 	}
15780 	if (cur_fllp == NULL) {
15781 		/* first on the list */
15782 		intersect_llp->ll_next = *nl_llpp;
15783 		*nl_llpp = intersect_llp;
15784 	} else {
15785 		intersect_llp->ll_next = cur_fllp->ll_next;
15786 		cur_fllp->ll_next = intersect_llp;
15787 	}
15788 
15789 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15790 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15791 	    intersect_llp->ll_flock.l_start,
15792 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15793 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15794 }
15795 
15796 /*
15797  * Our local locking current state is potentially different than
15798  * what the NFSv4 server thinks we have due to a lost lock that was
15799  * resent and then received.  We need to reset our "NFSv4" locking
15800  * state to match the current local locking state for this pid since
15801  * that is what the user/application sees as what the world is.
15802  *
15803  * We cannot afford to drop the open/lock seqid sync since then we can
15804  * get confused about what the current local locking state "is" versus
15805  * "was".
15806  *
15807  * If we are unable to fix up the locks, we send SIGLOST to the affected
15808  * process.  This is not done if the filesystem has been forcibly
15809  * unmounted, in case the process has already exited and a new process
15810  * exists with the same pid.
15811  */
15812 static void
15813 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15814     nfs4_lock_owner_t *lop)
15815 {
15816 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15817 	mntinfo4_t *mi = VTOMI4(vp);
15818 	const int cmd = F_SETLK;
15819 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15820 	flock64_t ul_fl;
15821 
15822 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15823 	    "nfs4_reinstitute_local_lock_state"));
15824 
15825 	/*
15826 	 * Find active locks for this vp from the local locking code.
15827 	 * Scan through this list and find out the locks that intersect with
15828 	 * the lost lock. Once we find the lock that intersects, add the
15829 	 * intersection area as a new lock to a new list "ri_llp". The lock
15830 	 * type of the intersection region lock added to ri_llp is the same
15831 	 * as that found in the active lock list, "list". The intersecting
15832 	 * region locks are added to ri_llp in increasing l_start order.
15833 	 */
15834 	ASSERT(nfs_zone() == mi->mi_zone);
15835 
15836 	locks = flk_active_locks_for_vp(vp);
15837 	ri_llp = NULL;
15838 
15839 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15840 		ASSERT(llp->ll_vp == vp);
15841 		/*
15842 		 * Pick locks that belong to this pid/lockowner
15843 		 */
15844 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15845 			continue;
15846 
15847 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15848 	}
15849 
15850 	/*
15851 	 * Now we have the list of intersections with the lost lock. These are
15852 	 * the locks that were/are active before the server replied to the
15853 	 * last/lost lock. Issue these locks to the server here. Playing these
15854 	 * locks to the server will re-establish aur current local locking state
15855 	 * with the v4 server.
15856 	 * If we get an error, send SIGLOST to the application for that lock.
15857 	 */
15858 
15859 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15860 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15861 		    "nfs4_reinstitute_local_lock_state: need to issue "
15862 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15863 		    llp->ll_flock.l_start,
15864 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15865 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15866 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15867 		/*
15868 		 * No need to relock what we already have
15869 		 */
15870 		if (llp->ll_flock.l_type == lost_flp->l_type)
15871 			continue;
15872 
15873 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15874 	}
15875 
15876 	/*
15877 	 * Now keeping the start of the lost lock as our reference parse the
15878 	 * newly created ri_llp locklist to find the ranges that we have locked
15879 	 * with the v4 server but not in the current local locking. We need
15880 	 * to unlock these ranges.
15881 	 * These ranges can also be reffered to as those ranges, where the lost
15882 	 * lock does not overlap with the locks in the ri_llp but are locked
15883 	 * since the server replied to the lost lock.
15884 	 */
15885 	cur_start = lost_flp->l_start;
15886 	lost_flp_end = lock_to_end(lost_flp);
15887 
15888 	ul_fl.l_type = F_UNLCK;
15889 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15890 	ul_fl.l_sysid = lost_flp->l_sysid;
15891 	ul_fl.l_pid = lost_flp->l_pid;
15892 
15893 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15894 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15895 
15896 		if (llp->ll_flock.l_start <= cur_start) {
15897 			cur_start = start_check(llp_ll_flock_end);
15898 			continue;
15899 		}
15900 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15901 		    "nfs4_reinstitute_local_lock_state: "
15902 		    "UNLOCK [%"PRIx64" - %"PRIx64"]",
15903 		    cur_start, llp->ll_flock.l_start));
15904 
15905 		ul_fl.l_start = cur_start;
15906 		ul_fl.l_len = end_to_len(cur_start,
15907 		    (llp->ll_flock.l_start - 1));
15908 
15909 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15910 		cur_start = start_check(llp_ll_flock_end);
15911 	}
15912 
15913 	/*
15914 	 * In the case where the lost lock ends after all intersecting locks,
15915 	 * unlock the last part of the lost lock range.
15916 	 */
15917 	if (cur_start != start_check(lost_flp_end)) {
15918 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15919 		    "nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15920 		    "lost lock region [%"PRIx64" - %"PRIx64"]",
15921 		    cur_start, lost_flp->l_start + lost_flp->l_len));
15922 
15923 		ul_fl.l_start = cur_start;
15924 		/*
15925 		 * Is it an to-EOF lock? if so unlock till the end
15926 		 */
15927 		if (lost_flp->l_len == 0)
15928 			ul_fl.l_len = 0;
15929 		else
15930 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15931 
15932 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15933 	}
15934 
15935 	if (locks != NULL)
15936 		flk_free_locklist(locks);
15937 
15938 	/* Free up our newly created locklist */
15939 	for (llp = ri_llp; llp != NULL; ) {
15940 		tmp_llp = llp->ll_next;
15941 		kmem_free(llp, sizeof (locklist_t));
15942 		llp = tmp_llp;
15943 	}
15944 
15945 	/*
15946 	 * Now return back to the original calling nfs4frlock()
15947 	 * and let us naturally drop our seqid syncs.
15948 	 */
15949 }
15950 
15951 /*
15952  * Create a lost state record for the given lock reinstantiation request
15953  * and push it onto the lost state queue.
15954  */
15955 static void
15956 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
15957     nfs4_lock_owner_t *lop)
15958 {
15959 	nfs4_lost_rqst_t req;
15960 	nfs_lock_type4 locktype;
15961 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
15962 
15963 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15964 
15965 	locktype = flk_to_locktype(cmd, flk->l_type);
15966 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
15967 	    NULL, NULL, lop, flk, &req, cr, vp);
15968 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
15969 	    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
15970 	    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
15971 	    NULL);
15972 }
15973